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(queue): deliver images with send-now steering (#2071)
Call Whitec740829af51c
diff --git a/core/services/agent_steering.py b/core/services/agent_steering.pyindex 31dbcb553..d6dcef71b 100644--- a/core/services/agent_steering.py+++ b/core/services/agent_steering.py@@ -11,6 +11,7 @@ from core.agent_input import AgentInputMetadataif TYPE_CHECKING:from modules.agents.base import AgentRequest+ from modules.im.base import FileAttachmentAGENT_TURN_TOKEN = "turn_token"AGENT_RUNTIME_TURN_TOKEN = "agent_runtime_turn_token"@@ -27,7 +28,7 @@ class SteerOutcome(str, Enum):@dataclass(frozen=True)class SteerRequest:- """One guarded insertion request carrying the original user text."""+ """One guarded insertion with original text and session-resolved attachments."""target_session_id: strexpected_logical_turn_id: str@@ -35,6 +36,7 @@ class SteerRequest:text: strattempt_id: str = ""input_metadata: AgentInputMetadata | None = None+ files: tuple[FileAttachment, ...] = ()@dataclass(frozen=True)diff --git a/core/session_turns.py b/core/session_turns.pyindex 9c2bc076c..9bea61dda 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -23,6 +23,7 @@ import weakreffrom contextlib import contextmanagerfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezone+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Awaitable, Callable, ContextManager, Iterator, Literal, Optionalfrom sqlalchemy import and_, exists, literal, or_, select, update@@ -2490,11 +2491,6 @@ class SessionTurnManager:has_attachments=bool(specs),)- @staticmethod- def _delivery_has_attachment_references(delivery: dict[str, Any]) -> bool:- payload = delivery_store.delivery_payload(delivery)- return bool((payload.get("content") or {}).get("attachments"))-def _hydrate_delivery_batch_context(self,context: "MessageContext",@@ -2723,11 +2719,34 @@ class SessionTurnManager:context: "MessageContext",) -> DeliveryResult:delivery_id = str(deliveries[0]["id"])+ # The steering claim has committed. Other viewers must see the same+ # read-only pending row while the native write is in flight.+ self._publish_queue_update(str(deliveries[0]["session_id"]))if not self._compatible_steer_memory_authority(logical_turn_id, deliveries):return await self._finish_steer(delivery_id, steer_result(SteerOutcome.REFUSED, reason="memory_authority_changed"), context=context)try:+ from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs++ attachments = [+ attachment+ for row in deliveries+ for attachment in ((delivery_store.delivery_payload(row).get("content") or {}).get("attachments") or [])+ ]+ with self._sqlite_engine().connect() as conn:+ specs = resolve_attachment_specs(+ conn, session_id=str(deliveries[0]["session_id"]), attachments=attachments+ )+ files = tuple(file_attachments_from_specs(specs) or ())+ # Never accept the text while silently losing one of its attachments.+ # Resolve only session-bound tokens, never caller-supplied local paths.+ if len(files) != len(attachments) or any(not Path(file.local_path).is_file() for file in files):+ return await self._finish_steer(+ delivery_id,+ steer_result(SteerOutcome.REFUSED, reason="attachments_unavailable"),+ context=context,+ )metadata = await self._steer_input_metadata(deliveries)request = SteerRequest(target_session_id=str(deliveries[0]["session_id"]),@@ -2736,6 +2755,7 @@ class SessionTurnManager:text=_segment_dispatch_text(deliveries),attempt_id=attempt_id,input_metadata=metadata,+ files=files,)except asyncio.CancelledError:await self._finish_steer(@@ -3038,23 +3058,7 @@ class SessionTurnManager:and identity is not Noneand identity[0] == observed_id)- if current is not None and self._delivery_has_attachment_references(delivery):- claimed = delivery_store.cas_delivery(- conn,- str(delivery["id"]),- expected_version=int(delivery["version"]),- expected_states=("reserved",),- values={"priority": "p3", "state": "queued"},- history_event={- "kind": "steer",- "turn_id": str(current["id"]),- "outcome": "attachments_require_new_turn",- },- )- if claimed is None:- raise RuntimeError("attachment P1 fallback claim lost")- delivery = claimed- elif same_active:+ if same_active:attempt_id = delivery_store.new_attempt_id()native_id = str(identity[1])turn_id = observed_id@@ -3248,17 +3252,6 @@ class SessionTurnManager:)else:claimed_rows = claimed["deliveries"]- elif any(- self._delivery_has_attachment_references(row)- for row in delivery_rows- ):- return DeliveryResult(- delivery_id,- None,- "queued",- str(current_turn["id"]),- reason="attachments_wait_for_new_turn",- )elif (observed_turn_idand str(current_turn["id"]) == observed_turn_id@@ -3392,14 +3385,12 @@ class SessionTurnManager:receipt=body,)saved = unknown_rows[0] if unknown_rows else None- return DeliveryResult(- delivery_id,- None,- "reconciling_steer",- target_turn_id or None,- None if unknown_rows and all(unknown_rows) else "receipt_cas_lost",- )- if not materialized:+ if not unknown_rows or not all(unknown_rows):+ return DeliveryResult(+ delivery_id, None, "reconciling_steer",+ target_turn_id or None, "receipt_cas_lost",+ )+ elif not materialized:session_status = conn.execute(select(agent_sessions.c.status).where(agent_sessions.c.id == str(delivery["session_id"])@@ -3456,6 +3447,8 @@ class SessionTurnManager:"failed to persist steer receipt recovery fence for delivery=%s",delivery_id,)+ if session_id:+ self._publish_queue_update(session_id)return DeliveryResult(delivery_id,None,@@ -3483,16 +3476,19 @@ class SessionTurnManager:target_turn_id or None,admission="steered",)+ if saved is not None:+ # Publish only after the receipt transaction commits, including+ # recovery refusal: otherwise a viewer stays stuck in confirming.+ self._publish_queue_update(session_id)if should_drain:await self.drain_delivery_queue(session_id)- return self._committed_delivery_result(- delivery_id,- )+ committed = self._committed_delivery_result(delivery_id)+ return replace(committed, reason=body["reason"]) if committed.state == "queued" else committedreturn DeliveryResult(delivery_id,None,str((saved or {}).get("state") or "reconciling_steer"),- None,+ str((saved or {}).get("current_target_turn_id") or "") or None,)async def _admit_p0(@@ -8406,6 +8402,7 @@ class SessionTurnManager:"session_id": session_id,"status": result.state,"delivery_id": result.delivery_id,+ **({"reason": result.reason} if result.reason else {}),}# --- shared turn chokepoints (status + Show checkpoint projection) ------------diff --git a/docs/plans/2026-09-19-queued-attachment-previews.md b/docs/plans/2026-09-19-queued-attachment-previews.mdindex 6e7f1f1fd..9289bf6a0 100644--- a/docs/plans/2026-09-19-queued-attachment-previews.md+++ b/docs/plans/2026-09-19-queued-attachment-previews.md@@ -44,6 +44,38 @@ Owner acceptance after authorized deployment: queue text with an image, an imageOne PR against master, closes #2042. Exact-head Codex review, all expected CI green, and zero unresolved threads required. The lane owns its fix watch; the orchestrator independently gates and checks scope. No merge or shared deployment without owner instruction. Record material deviations and validation evidence below as they land.+## Attachment send-now repair (2026-09-20)++A subsequent user report exposed a separate dispatch defect: the active-turn+promotion path deliberately left every attachment-bearing Delivery queued, and+its response discarded the reason. The orchestrator expanded this follow-up's+scope to carry resolved attachments through the existing native steering owner.+See `agent-message-priority.md`, scenarios `QUEUE-IMAGE-001`–`004`, for the amended+contract. No Stop fallback, new queue owner, storage migration, or dependency is+introduced.++Use each backend's normal-turn attachment encoding: Codex `localImage`, and the+existing file/image path context for Claude and OpenCode. Preserve complete+Delivery snapshots on refusal or ambiguous acknowledgement. Surface deferred+send feedback without hiding the queued image.++The first review found a read-side gap: retaining the Delivery snapshot was not+enough when the queue endpoint selected only `queued`. Both queue and bootstrap+now include unaccepted steering states, preserving order and attachments without+making them claimable. The UI derives confirming feedback and disabled mutation+controls from that persisted state, including after reload. Accepted and refused+receipts notify viewers after commit; tests cover the actual HTTP projection and+subsequent settlement rather than returning an unchanged queued mock.++The current queue renderer already handles Web and IM image shapes. Inspection+found an installed host serving an older bundle without those components, while+the current local master regression contains them; do not infer a new renderer+defect or restart that host. This follow-up extends isolated upload-to-native+coverage with a decodable PNG, a Chinese filename, image-only input, real busy+admission, queue/reload projections and transcript identity. Existing browser+preview tests remain required. Deployed acceptance is a separate authorized+local regression step under `docs/regression/README.md`, not a host restart.+## What was built- `ui/src/lib/messageAttachments.ts` reads `content.attachments` and decides, ondiff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.mdindex cc66657d9..98f17f750 100644--- a/docs/plans/agent-message-priority.md+++ b/docs/plans/agent-message-priority.md@@ -23,7 +23,7 @@ natural-language content.## Native Steering Contract-The shared backend request has exactly these fields:+The shared backend request has these fields:```textSteerRequest@@ -31,6 +31,9 @@ SteerRequestexpected_logical_turn_id: strexpected_native_turn_id: strtext: str+ attempt_id: str = ""+ input_metadata: AgentInputMetadata | None = None+ files: tuple[FileAttachment, ...] = ()```- `target_session_id` is the target Avibe Agent Session identity.@@ -41,6 +44,12 @@ SteerRequestclient/receiver generation, or the OpenCode native session/runner generation.- `text` is the original, unmodified input. Adapters must pass it to the nativebackend byte-for-byte as text, including non-ASCII and Markdown/code content.+- `files` contains session-bound attachments resolved from the durable Delivery+ tokens immediately before native dispatch. Never accept arbitrary caller paths.+ If any reference is revoked, foreign, missing, or no longer local, refuse before+ writing any part of the batch and keep the original Delivery queued.+- `attempt_id` is the durable attempt identity; `input_metadata` renders only at+ the native boundary. Neither changes the original text or attachment snapshot.The typed result has one `outcome` with exactly four possible values. Optional`reason` and `details` fields are subordinate diagnostics and do not create@@ -68,18 +77,22 @@ receiver.## Backend Acknowledgements- **Codex:** call the installed app-server `turn/steer` method with `threadId`,- `expectedTurnId`, and one text `input`. A response is accepted only when its+ `expectedTurnId`, and the same text / `localImage` input builder as `turn/start`.+ Non-image files use the existing attachment context. A response is accepted only when its`turnId` equals the expected native turn. Never fall back to `turn/start`.- **Claude:** call `query()` on the existing live client using the existingruntime session id while retaining the same receiver generation. Successfulcompletion of the SDK transport write is the acknowledgement. A timeout,disconnect, or failed write with an ambiguous partial-write boundary is`unknown`; a pre-write unavailable state is `refused`.+ Use the same attachment-path context as normal turns; receipt tracking includes+ the complete rendered prompt, including image/file paths.- **OpenCode:** call `prompt_async` on the existing native session and runner.HTTP 200/204 is the acknowledgement. A definitive HTTP rejection is`refused` (or `not_active` when the native session is absent); a timeout ordisconnect after request dispatch is `unknown`. The adapter never calls abort- or stop.+ or stop. Use the normal-turn attachment-path context and track that full prompt+ for reconciliation.These acknowledgement strengths are intentionally different because the nativeprotocols expose different boundaries. The common result preserves that truth@@ -99,9 +112,34 @@ instead of claiming equivalent durability.| 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 adapters-accept text only, an attachment-bearing P1 is preserved as P3 and starts a new-Turn after the current one finishes.+Attachments remain part of the same Delivery and follow the same P1 admission+as text. Send Now can steer pure-image and mixed text/file messages into the+active Turn without stopping it. Definitive refusal preserves the queue; an+ambiguous acknowledgement retains the existing reconciliation fence. The+send-now response exposes queued refusal reasons so the UI never implies that+the attachment was sent when it was not.++The queue and bootstrap read projections retain unaccepted `pending_steer`,+`steering`, and `reconciling_steer` rows in FIFO order with their original content.+These rows remain inspectable after reload but cannot be recalled, deleted, or+sent again; a fenced head blocks Send Now without blocking removal of queued+followers. The strict queued-only storage default and native ordering fences+remain unchanged. Receipt settlement publishes a queue refresh after commit:+acceptance transfers the input to the transcript, while definitive refusal+restores the editable queued row (or retires it for an inactive Session).++Attachment steering acceptance scenarios:++- `QUEUE-IMAGE-001`: pure image and Chinese text/image queue heads reach the exact+ active native turn, preserving token, filename and transcript identity.+- `QUEUE-IMAGE-002`: Codex uses `localImage`; Claude/OpenCode use their normal+ attachment context; all retain their current receiver/runner and never Stop.+- `QUEUE-IMAGE-003`: foreign/revoked/missing media refuses the whole input before+ writing text; unknown acknowledgements never retry or duplicate the input.+- `QUEUE-IMAGE-004`: queued thumbnails and send feedback survive refresh and+ reload while steering is unconfirmed; pending rows are read-only, and receipt+ settlement restores queued actions or moves the input to the transcript.+ Text-only rows use the same delivery-state projection.## Ownership Closurediff --git a/modules/agents/base.py b/modules/agents/base.pyindex 28efc9079..90f74a04c 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -7,7 +7,7 @@ import loggingimport timefrom abc import ABC, abstractmethodfrom dataclasses import dataclass, field-from typing import Any, Callable, Dict, List, Optional+from typing import Any, Callable, Dict, List, Optional, Sequencefrom modules.im import MessageContextfrom modules.im.base import FileAttachment@@ -24,6 +24,23 @@ AGENT_RUNTIME_TURN_TOKEN = "agent_runtime_turn_token"AGENT_TURN_TOKEN = "turn_token"+def message_with_files(message: str, files: Sequence[FileAttachment] | None) -> str:+ """Use the same attachment context for new turns and native steering."""+ local_files = [file for file in files or () if file.local_path]+ if not local_files:+ return message+ # Preserve the established native prompt format: images, then other files.+ images = [file for file in local_files if (file.mimetype or "").startswith("image/")]+ other_files = [file for file in local_files if not (file.mimetype or "").startswith("image/")]+ lines = ["", "[User Attachments]"]+ for label, group in (("Image", images), ("File", other_files)):+ for file in group:+ size = f", {file.size} bytes" if file.size else ""+ lines.append(f"- {label}: {file.local_path} ({file.mimetype}{size})")+ file_info = "\n".join(lines)+ return f"{message}{file_info}" if message.strip() else file_info.lstrip()++@dataclassclass AgentRequest:"""Normalized agent invocation request."""diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 415430442..e6e70db66 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -45,6 +45,7 @@ from modules.agents.base import (AGENT_TURN_TOKEN,AgentRequest,BaseAgent,+ message_with_files,)# NOTE: AskUserQuestion support is disabled because Claude Code SDK cannot@@ -1161,7 +1162,7 @@ class ClaudeAgent(BaseAgent):)writers = self._steering_writer_keys()writers.add(composite_key)- message = self.render_input(request.text, request.input_metadata)+ message = self.render_input(message_with_files(request.text, request.files), request.input_metadata)input_receipt = self._register_native_input(composite_key,message,@@ -4309,54 +4310,4 @@ class ClaudeAgent(BaseAgent):return mapping.get(class_name)def _prepare_message_with_files(self, request: AgentRequest) -> str:- """Prepare message with file attachment information.-- If there are file attachments, append file info to the message- so the agent knows what files are available to read.- Files are stored in ~/.vibe_remote/attachments/{channel_id}/.-- Args:- request: The agent request containing message and files-- Returns:- Message string, potentially with file info appended- """- if not request.files:- return request.message-- # Build file info section- images = []- other_files = []-- for attachment in request.files:- if not attachment.local_path:- continue-- is_image = (attachment.mimetype or "").startswith("image/")- if is_image:- images.append(attachment)- else:- other_files.append(attachment)-- if not images and not other_files:- return request.message-- # Format file info as a clear block at the end- file_lines = ["", "[User Attachments]"]-- for img in images:- size_str = f", {img.size} bytes" if img.size else ""- file_lines.append(f"- Image: {img.local_path} ({img.mimetype}{size_str})")-- for f in other_files:- size_str = f", {f.size} bytes" if f.size else ""- file_lines.append(f"- File: {f.local_path} ({f.mimetype}{size_str})")-- file_info = "\n".join(file_lines)-- # If there's no text message, just use file info (without leading newline)- if not request.message or not request.message.strip():- return file_info.lstrip()-- # Append file info to message- return f"{request.message}{file_info}"+ return message_with_files(request.message, request.files)diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 374b9a645..41addac44 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -10,7 +10,7 @@ import shleximport timefrom contextlib import AsyncExitStackfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Sequencefrom config import pathsfrom config.v2_config import (@@ -18,6 +18,7 @@ from config.v2_config import (DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,)from core.backend_failure import emit_backend_failure+from core.agent_input import AgentInputMetadatafrom core.caller_context import caller_env_for_platform_payloadfrom core.message_output import stop_output_for, terminal_output_forfrom core.memory_cli_access import configure_memory_cli_access@@ -55,6 +56,7 @@ from core.runtime_ownership import (wake_runtime_ownership,)from modules.agents.base import AgentRequest, BaseAgent+from modules.im.base import FileAttachmentfrom modules.agents.subagent_router import SubagentDefinition, load_codex_subagentfrom modules.agents.codex.event_handler import CodexEventHandlerfrom modules.agents.codex.session import CodexSessionManager@@ -626,7 +628,7 @@ class CodexAgent(BaseAgent):{"threadId": thread_id,"expectedTurnId": request.expected_native_turn_id,- "input": [{"type": "text", "text": self.render_input(request.text, request.input_metadata)}],+ "input": self._build_native_input(request.text, request.files, request.input_metadata),},)except RuntimeError as exc:@@ -3623,14 +3625,22 @@ class CodexAgent(BaseAgent):def _build_input(self, request: AgentRequest) -> list[Dict[str, Any]]:"""Convert AgentRequest into Codex UserInput items."""+ return self._build_native_input(request.message, request.files, getattr(request, "input_metadata", None))++ def _build_native_input(+ self,+ message: str,+ files: Sequence[FileAttachment] | None,+ input_metadata: AgentInputMetadata | None,+ ) -> list[Dict[str, Any]]:+ """Build both turn/start and turn/steer input without dropping images."""items: list[Dict[str, Any]] = []# Text input- message = request.message- if request.files:+ if files:# Append file info like Claude agent doesfile_lines = ["", "[User Attachments]"]- for attachment in request.files:+ for attachment in files:if not attachment.local_path:continueis_image = (attachment.mimetype or "").startswith("image/")@@ -3648,7 +3658,7 @@ class CodexAgent(BaseAgent):if len(file_lines) > 2:message = f"{message}\n" + "\n".join(file_lines)- message = self.render_input(message, getattr(request, "input_metadata", None))+ message = self.render_input(message, input_metadata)if message:items.insert(0, {"type": "text", "text": message})diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 5bca86047..d52c8e217 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -62,7 +62,7 @@ from core.system_prompt_injection import (build_system_prompt_injection,get_enabled_agents_for_prompt,)-from modules.agents.base import AgentRequest, BaseAgent+from modules.agents.base import AgentRequest, BaseAgent, message_with_filesfrom modules.agents.model_hub import (ModelHubLaunch,OpenCodeOverlay,@@ -2082,7 +2082,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):backend=self.name,)before_insert = _SteeringAwareOpenCodeServer._message_ids(messages)- prompt_text = self.render_input(request.text, request.input_metadata)+ prompt_text = self.render_input(message_with_files(request.text, request.files), request.input_metadata)try:prompt_kwargs = {"session_id": native_session_id,@@ -2994,54 +2994,4 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):restoration_ready.set_result(False)def _prepare_message_with_files(self, request: AgentRequest) -> str:- """Prepare message with file attachment information.-- If there are file attachments, append file info to the message- so the agent knows what files are available to read.- Files are stored in ~/.vibe_remote/attachments/{channel_id}/.-- Args:- request: The agent request containing message and files-- Returns:- Message string, potentially with file info appended- """- if not request.files:- return request.message-- # Build file info section- images = []- other_files = []-- for attachment in request.files:- if not attachment.local_path:- continue-- is_image = (attachment.mimetype or "").startswith("image/")- if is_image:- images.append(attachment)- else:- other_files.append(attachment)-- if not images and not other_files:- return request.message-- # Format file info as a clear block at the end- file_lines = ["", "[User Attachments]"]-- for img in images:- size_str = f", {img.size} bytes" if img.size else ""- file_lines.append(f"- Image: {img.local_path} ({img.mimetype}{size_str})")-- for f in other_files:- size_str = f", {f.size} bytes" if f.size else ""- file_lines.append(f"- File: {f.local_path} ({f.mimetype}{size_str})")-- file_info = "\n".join(file_lines)-- # If there's no text message, just use file info (without leading newline)- if not request.message or not request.message.strip():- return file_info.lstrip()-- # Append file info to message- return f"{request.message}{file_info}"+ return message_with_files(request.message, request.files)diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 49c96bc02..b5f3ad6c8 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -480,11 +480,20 @@ def claimable_fifo_prefix(conn: Connection, session_id: str) -> list[dict[str, Areturn prefix-def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:+def list_queued(+ conn: Connection, session_id: str, *, include_steering: bool = False+) -> list[dict[str, Any]]:+ """Read the backlog, optionally including unaccepted UI-visible steers.++ Steering rows remain fenced, not claimable or removable. Operational callers+ retain the strict queued-only default; queue/bootstrap use the wider read+ projection so an uncertain native write never hides the original input.+ """+ states = ("queued", "pending_steer", "steering", "reconciling_steer") if include_steering else ("queued",)rows = conn.execute(select(message_deliveries).where(message_deliveries.c.session_id == session_id)- .where(message_deliveries.c.state == "queued")+ .where(message_deliveries.c.state.in_(states)).order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)).mappings()return [delivery_payload(dict(row)) for row in rows]diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 006a25216..e8248fd53 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -31,6 +31,7 @@ from modules.agents.opencode.agent import (from modules.agents.opencode.poll_loop import OpenCodePollLoopfrom modules.agents.opencode.server import OpenCodePromptRejectedErrorfrom modules.im import MessageContext+from modules.im.base import FileAttachmentfrom tests.test_memory_delegated_reads import (_create_definition,@@ -283,6 +284,83 @@ async def _cancel_tasks(*tasks: asyncio.Task) -> None:await asyncio.gather(*tasks, return_exceptions=True)[email protected]("backend", ["codex", "claude", "opencode"])[email protected]("text", ["", STEER_TEXT])+async def test_native_steer_uses_normal_attachment_input_without_replacing_primary(backend, text, tmp_path):+ """QUEUE-IMAGE-002: attachment delivery shares each adapter's start format."""+ image = tmp_path / "队列图片.png"+ image.write_bytes(b"test image")+ document = tmp_path / "说明.txt"+ document.write_text("附件说明", encoding="utf-8")+ files = (+ FileAttachment(name=image.name, local_path=str(image), mimetype="image/png"),+ FileAttachment(name=document.name, local_path=str(document), mimetype="text/plain"),+ )+ primary = _primary_request(backend=backend)+ gate_task = await _held_task()+ receiver_task = await _held_task()+ transport = _CodexTransport()+ client = _ClaudeClient()+ server = _OpenCodeServer()+ if backend == "codex":+ agent = object.__new__(CodexAgent)+ agent._turn_registry = _CodexTurnRegistry(primary.base_session_id, "codex-turn")+ agent._session_mgr = _CodexSessionManager(primary.base_session_id, "codex-thread", primary.working_path)+ agent._transports = {primary.working_path: transport}+ elif backend == "claude":+ agent = object.__new__(ClaudeAgent)+ agent.claude_sessions = {"runtime-key": client}+ agent.receiver_tasks = {"runtime-key": receiver_task}+ agent.session_handler = _ClaudeSessionHandler("runtime-key")+ agent._pending_requests = {"runtime-key": [primary]}+ else:+ agent = _opencode_agent(primary, gate_task, server)+ controller = _controller_with_active_gate(agent, primary, gate_task)+ try:+ identity = active_steer_identity(controller, backend, "avibe-session")+ assert identity is not None+ request = SteerRequest(+ target_session_id="avibe-session",+ expected_logical_turn_id=identity[0],+ expected_native_turn_id=identity[1],+ text=text,+ files=files,+ )+ receipt = await steer_active_turn(controller, backend, request)+ assert receipt.outcome is SteerOutcome.ACCEPTED+ if backend == "codex":+ assert transport.calls == [("turn/steer", {+ "threadId": "codex-thread",+ "expectedTurnId": identity[1],+ "input": [+ {"type": "text", "text": f"{text}\n\n[User Attachments]\n- File: {document} (text/plain)"},+ {"type": "localImage", "path": str(image)},+ ],+ })]+ else:+ prompt = (+ f"{text}\n[User Attachments]\n"+ f"- Image: {image} (image/png)\n- File: {document} (text/plain)"+ )+ if not text:+ prompt = prompt.lstrip()+ if backend == "claude":+ assert client.queries[-1] == (prompt, "runtime-key")+ assert agent._pending_requests["runtime-key"] == [primary]+ assert agent.receiver_tasks["runtime-key"] is receiver_task+ client._transport.end_input.assert_not_awaited()+ else:+ assert server.prompt_calls[0]["text"] == prompt+ assert agent._steering_states[primary.base_session_id].awaiting_user_text == prompt+ assert server.abort_calls == []+ assert request.text == text+ assert primary.message == "primary" and primary.files is None+ assert not gate_task.done() and not receiver_task.done()+ finally:+ await _cancel_tasks(gate_task, receiver_task)++@pytest.mark.anyioasync def test_codex_steers_expected_active_turn_without_starting_another_turn(native_input) -> None:metadata, prefix = native_inputdiff --git a/tests/test_queued_image_delivery.py b/tests/test_queued_image_delivery.pynew file mode 100644index 000000000..9ae6cac22--- /dev/null+++ b/tests/test_queued_image_delivery.py@@ -0,0 +1,297 @@+"""Upload -> real busy admission -> queue -> native steer -> transcript.++Only the local controller transport and native app-server write are replaced.+All storage, attachment resolution, admission and HTTP projections are real.+"""++from __future__ import annotations++import asyncio+import base64+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import httpx+import pytest++from core import internal_server+from core.services.agent_steering import SteerOutcome, result as steer_result+from modules.agents.codex.agent import CodexAgent+from storage import message_deliveries, messages_service+from storage.db import create_sqlite_engine+from tests.test_agent_steering import (+ _CodexSessionManager,+ _CodexTransport,+ _CodexTurnRegistry,+ _primary_request,+)+from tests.test_internal_server import _build_controller_double, _reserve_submission+from tests.test_ui_session_stream import _make_session, isolated_state # noqa: F401+from tests.ui_server_test_helpers import csrf_headers++PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="+)+++def test_queue_and_bootstrap_project_all_unaccepted_steering_states(isolated_state, tmp_path):+ """The wider UI read must not change claimable queue semantics or ordering."""+ from vibe.ui_server import app++ scope_id, session_id = _make_session(tmp_path)+ states = ["queued", "pending_steer", "steering", "reconciling_steer", "reserved", "retired"]+ attachment = {"token": "projection-image", "name": "队列图片.png", "mime": "image/png"}+ turn_id = message_deliveries.new_turn_id()+ with create_sqlite_engine().begin() as conn:+ # Reverse insertion with tied timestamps tests the ID tiebreak, too.+ for index, state in reversed(list(enumerate(states))):+ steering = state in {"pending_steer", "steering", "reconciling_steer"}+ message_deliveries.insert_delivery(+ conn, delivery_id=f"msg_projection_{index}", session_id=session_id,+ priority="p3" if state == "queued" else "p1", state=state,+ snapshot=message_deliveries.message_snapshot(+ scope_id=scope_id, session_id=session_id, platform="avibe",+ author="user", source="user", content={"attachments": [attachment]},+ ),+ dispatch_text="", now="2026-09-20T00:00:00Z",+ current_attempt_id=message_deliveries.new_attempt_id() if steering else None,+ current_attempt_kind="steer" if steering else None,+ current_target_turn_id=turn_id if steering else None,+ current_expected_native_turn_id="native-turn" if state in {"steering", "reconciling_steer"} else None,+ current_receipt_outcome="unknown" if state == "reconciling_steer" else None,+ )+ assert [row["state"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]+ initial = _reserve_submission(conn, scope_id=scope_id, session_id=session_id, text="claimed input")+ message_deliveries.insert_turn(+ conn, turn_id=turn_id, session_id=session_id,+ initial_delivery_id=initial["id"], state="starting", backend="claude",+ )+ assert message_deliveries.open_start_attempt(+ conn, initial["id"], expected_version=initial["version"],+ turn_id=turn_id, attempt_id=message_deliveries.new_attempt_id(),+ ) is not None++ client = app.test_client()+ queued = client.get(f"/api/sessions/{session_id}/queue").get_json()["queued"]+ with patch("vibe.api.get_vibe_agents", return_value={"agents": [], "default_agent_name": None}):+ bootstrap = client.get(f"/api/sessions/{session_id}/bootstrap").get_json()["queued"]+ assert queued == bootstrap+ assert [row["state"] for row in queued] == states[:4]+ assert [row["id"] for row in queued] == [f"msg_projection_{index}" for index in range(4)]+ assert all(row["content"]["attachments"] == [attachment] for row in queued)++[email protected]("text", ["", "看看这张图片,不要丢掉附件"])[email protected]("receipt", ["accepted", "unknown_accepted", "unknown_refused", "refused"])+def test_uploaded_image_survives_real_queue_admission_and_send_now(isolated_state, tmp_path, text, receipt):+ """QUEUE-IMAGE-001/003/004: no disconnected producer/consumer fixtures."""+ from vibe.ui_server import app++ scope_id, session_id = _make_session(tmp_path, agent_backend="codex")+ engine = create_sqlite_engine()+ turn_id = message_deliveries.new_turn_id()+ with engine.begin() as conn:+ initial = _reserve_submission(conn, scope_id=scope_id, session_id=session_id, text="active work")+ message_deliveries.insert_turn(+ conn, turn_id=turn_id, session_id=session_id,+ initial_delivery_id=initial["id"], state="starting", backend="codex",+ )+ message_deliveries.open_start_attempt(+ conn, initial["id"], expected_version=initial["version"],+ turn_id=turn_id, attempt_id=message_deliveries.new_attempt_id(),+ )+ turn = message_deliveries.get_turn(conn, turn_id)+ assert message_deliveries.bind_native_start(+ conn, turn_id, expected_version=turn["version"],+ runtime_key="runtime-key", runtime_turn_id="runtime-token", native_turn_id="codex-turn",+ ) is not None+ assert message_deliveries.materialize_start_acceptance(conn, turn_id=turn_id, evidence={"kind": "test"})++ primary = _primary_request(session_id=session_id, backend="codex")+ primary.context.platform_specific["turn_token"] = turn_id+ native = _CodexTransport(error={+ "accepted": None,+ "unknown_accepted": TimeoutError("native write acknowledgement lost"),+ "unknown_refused": TimeoutError("native write acknowledgement lost"),+ "refused": RuntimeError("activeTurnNotSteerable"),+ }[receipt])+ agent = object.__new__(CodexAgent)+ agent.config = SimpleNamespace(include_time_info=False, include_user_info=False)+ agent._turn_registry = _CodexTurnRegistry(session_id, "codex-turn")+ agent._session_mgr = _CodexSessionManager(session_id, "codex-thread", primary.working_path)+ agent._transports = {primary.working_path: native}+ controller = _build_controller_double()+ controller.config.memory.enabled = False+ controller.agent_service = SimpleNamespace(+ agents={"codex": agent},+ _turn_gates={"runtime-key": SimpleNamespace(+ backend="codex", token="runtime-token", runtime_started=True,+ request=primary, context=primary.context, agent=agent,+ )},+ )+ agent.controller = controller+ internal_app = internal_server.create_app(controller)++ async def call_internal(path, **kwargs):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=internal_app), base_url="http://controller.test",+ ) as client:+ response = await client.post(path, **kwargs)+ return {"status_code": response.status_code, "body": response.json()}++ async def dispatch(payload):+ return await call_internal("/internal/dispatch_async", json=payload)++ async def send_now(sid, *, expected_delivery_id):+ return await call_internal(+ f"/internal/send-now/{sid}", params={"expected_delivery_id": expected_delivery_id},+ )++ client = app.test_client()+ headers = csrf_headers(client, "http://127.0.0.1:15131")+ upload = client.post(+ f"/api/sessions/{session_id}/attachments",+ data={"upload_id": "queued-image-integration"},+ files={"file": ("队列图片.png", PNG, "image/png")},+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert upload.status_code == 201+ attachment = upload.get_json()+ assert attachment["name"] == "队列图片.png"+ assert (attachment["width"], attachment["height"]) == (1, 1)+ with patch("vibe.internal_client.dispatch_async", side_effect=dispatch):+ response = client.post(+ f"/api/sessions/{session_id}/messages",+ json={"content": {"text": text, "attachments": [attachment]}},+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert response.status_code == 202+ assert response.get_json()["queued"] is True+ delivery_id = response.get_json()["id"]+ queued = client.get(f"/api/sessions/{session_id}/queue").get_json()["queued"]+ assert len(queued) == 1+ assert queued[0]["id"] == delivery_id+ assert queued[0]["content"]["attachments"] == [attachment]+ with patch("vibe.api.get_vibe_agents", return_value={"agents": [], "default_agent_name": None}):+ bootstrap = client.get(f"/api/sessions/{session_id}/bootstrap").get_json()+ assert bootstrap["queued"][0]["content"]["attachments"] == [attachment]+ assert client.get(attachment["url"]).content == PNG++ def queue_projection():+ return client.get(f"/api/sessions/{session_id}/queue").get_json()["queued"]++ def bootstrap_projection():+ with patch("vibe.api.get_vibe_agents", return_value={"agents": [], "default_agent_name": None}):+ return client.get(f"/api/sessions/{session_id}/bootstrap").get_json()["queued"]++ committed_states = []++ def observe_queue_event(event, payload):+ if event == "queue.updated" and payload["session_id"] == session_id:+ # A separate connection proves the notification follows commit.+ with engine.connect() as conn:+ committed_states.append(message_deliveries.get_delivery(conn, delivery_id)["state"])++ native_send = native.send_request++ async def observe_native_write(method, params):+ # Read the projection while the native call is in flight without nesting+ # a synchronous test-client request in the request's own event loop.+ with engine.connect() as conn:+ rows = message_deliveries.list_queued(conn, session_id, include_steering=True)+ assert [(row["id"], row["state"]) for row in rows] == [(delivery_id, "steering")]+ assert rows[0]["content"]["attachments"] == [attachment]+ return await native_send(method, params)++ with (+ patch("vibe.internal_client.send_now", side_effect=send_now),+ patch("core.inbox_events.bus.publish", side_effect=observe_queue_event),+ patch.object(native, "send_request", side_effect=observe_native_write),+ ):+ sent = client.post(+ f"/api/sessions/{session_id}/queue/{delivery_id}/send-now",+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert sent.status_code == 200+ assert sent.get_json()["status"] == {+ "accepted": "accepted", "unknown_accepted": "reconciling_steer",+ "unknown_refused": "reconciling_steer", "refused": "queued",+ }[receipt]+ assert committed_states == ["steering", sent.get_json()["status"]]+ assert len(native.calls) == 1+ method, params = native.calls[0]+ assert method == "turn/steer"+ assert params["expectedTurnId"] == "codex-turn"+ native_image = next(item for item in params["input"] if item["type"] == "localImage")+ assert Path(native_image["path"]).read_bytes() == PNG+ native_text = [item["text"] for item in params["input"] if item["type"] == "text"]+ assert native_text == ([text] if text else [])+ controller.command_handler.handle_stop.assert_not_awaited()+ controller.message_handler.handle_user_message.assert_not_awaited()++ with engine.connect() as conn:+ delivery = message_deliveries.get_delivery(conn, delivery_id)+ message = messages_service.get_message(conn, delivery_id, session_id=session_id)+ active = message_deliveries.active_turn(conn, session_id)+ assert active["id"] == turn_id+ if receipt == "accepted":+ # Acceptance transfers the snapshot to the transcript and scrubs the+ # duplicate Delivery payload; it does not discard the attachment.+ assert delivery["snapshot_json"] is None+ assert message["content"]["attachments"] == [attachment]+ assert client.get(f"/api/sessions/{session_id}/queue").get_json()["queued"] == []+ else:+ assert message_deliveries.delivery_payload(delivery)["content"]["attachments"] == [attachment]+ assert message is None+ assert delivery["state"] == sent.get_json()["status"]+ for rows in (queue_projection(), bootstrap_projection()):+ assert [(row["id"], row["state"]) for row in rows] == [(delivery_id, delivery["state"])]+ assert rows[0]["content"]["attachments"] == [attachment]+ if receipt == "refused":+ assert sent.get_json()["reason"] == "native_turn_not_steerable"+ else:+ # An ambiguous native write is fenced, not sent a second time.+ with patch("vibe.internal_client.send_now", side_effect=send_now):+ retry = client.post(+ f"/api/sessions/{session_id}/queue/{delivery_id}/send-now",+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert retry.status_code == 409+ assert len(native.calls) == 1+ with engine.connect() as conn:+ assert message_deliveries.list_queued(conn, session_id) == []+ # A follower stays behind the fence but remains removable.+ with patch("vibe.internal_client.dispatch_async", side_effect=dispatch):+ follower = client.post(+ f"/api/sessions/{session_id}/messages", json={"text": "后续消息"},+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert follower.status_code == 202+ follower_id = follower.get_json()["id"]+ assert [row["id"] for row in queue_projection()] == [delivery_id, follower_id]+ for row_id, removed in ((delivery_id, False), (follower_id, True)):+ response = client.delete(+ f"/api/sessions/{session_id}/queue/{row_id}",+ headers=headers, base_url="http://127.0.0.1:15131",+ )+ assert response.get_json()["removed"] is removed++ # Recovery settles the original native attempt, not a second write.+ outcome = SteerOutcome.ACCEPTED if receipt == "unknown_accepted" else SteerOutcome.REFUSED+ committed_states.clear()+ with patch("core.inbox_events.bus.publish", side_effect=observe_queue_event):+ settled = asyncio.run(controller.session_turns._finish_steer(+ delivery_id, steer_result(outcome, reason="reconciled"), context=primary.context,+ ))+ assert len(native.calls) == 1+ assert committed_states == [settled.state]+ for rows in (queue_projection(), bootstrap_projection()):+ if outcome == SteerOutcome.ACCEPTED:+ assert rows == []+ with engine.connect() as conn:+ message = messages_service.get_message(conn, delivery_id, session_id=session_id)+ assert message["content"]["attachments"] == [attachment]+ else:+ assert [(row["id"], row["state"]) for row in rows] == [(delivery_id, "queued")]+ assert rows[0]["content"]["attachments"] == [attachment]diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex a5e45a8ff..055cdabd7 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -8156,33 +8156,36 @@ def test_stale_send_now_does_not_mutate_the_deferred_queue(managers) -> None:assert _row(engine, str(queued.delivery_id))["state"] == "queued"-def test_send_now_keeps_attachment_head_for_the_next_turn([email protected]("text", ["", "看看这张图片"])+def test_send_now_steers_attachment_head_into_the_active_turn(managers,tmp_path: Path,+ text: str,) -> None:from storage import media_servicemanager, _other, engine, _engine_b, _starts = managers- asyncio.run(_activate(manager, text="active turn"))- attachment = tmp_path / "queued-input.txt"- attachment.write_text("queued attachment", encoding="utf-8")+ turn_id, _ = asyncio.run(_activate(manager, text="active turn"))+ attachment = tmp_path / "队列图片.png"+ attachment.write_bytes(b"queued image bytes")with engine.begin() as conn:token = media_service.register(conn,scope_id=None,session_id="ses_fsm",- kind="file",+ kind="image",source="user_upload",local_path=str(attachment),file_name=attachment.name,- content_type="text/plain",+ content_type="image/png",)queued = asyncio.run(manager.deliver(DeliveryRequest(session_id="ses_fsm",priority="p3",- content="review this file",+ content=text,+ has_content=True,content_json={"attachments": [{"token": token}]},),context=_context(),@@ -8202,20 +8205,25 @@ def test_send_now_keeps_attachment_head_for_the_next_turn())- assert promoted.state == "queued"- assert promoted.reason == "attachments_wait_for_new_turn"- manager._steer.assert_not_awaited()- assert _row(engine, str(queued.delivery_id))["state"] == "queued"+ assert promoted.state == "accepted"+ assert promoted.turn_id == turn_id+ request = manager._steer.await_args.args[1]+ assert request.text == text+ assert request.files[0].local_path == str(attachment)+ assert request.files[0].mimetype == "image/png"+ assert request.files[0].name == "队列图片.png"+ assert _row(engine, str(queued.delivery_id))["state"] == "accepted"+ manager.controller.command_handler.handle_stop.assert_not_awaited()-def test_content_p1_with_attachment_queues_behind_an_active_turn(+def test_content_p1_with_attachment_steers_the_active_turn(managers,tmp_path: Path,) -> None:from storage import media_servicemanager, _other, engine, _engine_b, _starts = managers- asyncio.run(_activate(manager, text="active turn"))+ turn_id, _ = asyncio.run(_activate(manager, text="active turn"))attachment = tmp_path / "priority-input.txt"attachment.write_text("priority attachment", encoding="utf-8")with engine.begin() as conn:@@ -8243,11 +8251,58 @@ def test_content_p1_with_attachment_queues_behind_an_active_turn())- assert admitted.state == "queued"- manager._steer.assert_not_awaited()+ assert admitted.state == "accepted"+ assert admitted.turn_id == turn_id+ request = manager._steer.await_args.args[1]+ assert request.text == "review this first"+ assert request.files[0].local_path == str(attachment)row = _row(engine, str(admitted.delivery_id))- assert row["priority"] == "p3"- assert row["state"] == "queued"+ assert row["priority"] == "p1"+ assert row["state"] == "accepted"+ manager.controller.command_handler.handle_stop.assert_not_awaited()++[email protected]("invalid", ["foreign_session", "revoked", "missing_file", "missing_token"])+def test_send_now_does_not_partially_steer_unavailable_attachments(managers, tmp_path, invalid):+ from storage import media_service++ manager, _other, engine, _engine_b, _starts = managers+ asyncio.run(_activate(manager))+ attachment = tmp_path / "图片.png"+ attachment.write_bytes(b"image bytes")+ with engine.begin() as conn:+ if invalid == "foreign_session":+ _seed_session(engine, "ses_foreign")+ token = media_service.register(+ conn,+ scope_id=None,+ session_id="ses_foreign" if invalid == "foreign_session" else "ses_fsm",+ kind="image",+ source="user_upload",+ local_path=str(attachment),+ file_name=attachment.name,+ content_type="image/png",+ )+ if invalid == "revoked":+ conn.execute(update(media_objects).where(media_objects.c.token == token).values(revoked_at="now"))+ if invalid == "missing_file":+ attachment.unlink()+ queued = asyncio.run(manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm", priority="p3", content="must keep my image",+ content_json={"attachments": [{"token": "missing" if invalid == "missing_token" else token}]},+ ),+ context=_context(),+ ))+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))++ result = asyncio.run(manager.send_now("ses_fsm", expected_delivery_id=queued.delivery_id))++ assert result["status"] == "queued"+ assert result["reason"] == "attachments_unavailable"+ manager._steer.assert_not_awaited()+ assert _row(engine, str(queued.delivery_id))["state"] == "queued"+ manager.controller.command_handler.handle_stop.assert_not_awaited()def test_archive_keeps_unknown_and_materializes_late_positive_evidence(managers) -> None:diff --git a/ui/e2e/queue-attachments/fixture.tsx b/ui/e2e/queue-attachments/fixture.tsxindex 09e23ff1a..2231a6fa5 100644--- a/ui/e2e/queue-attachments/fixture.tsx+++ b/ui/e2e/queue-attachments/fixture.tsx@@ -109,7 +109,9 @@ const QUEUE: WorkbenchMessage[] = [const GALLERY = ['/api/media/med_1', '/api/media/med_2'];export function Fixture() {- const [queue, setQueue] = useState(QUEUE);+ const [queue, setQueue] = useState(() => new URLSearchParams(location.search).has('confirming')+ ? [{ ...queued('q-confirming', '', [media('med_1', '队列图片.png')]), state: 'reconciling_steer' }]+ : QUEUE);const [sent, setSent] = useState(0);return (// ThemeProvider is what the app puts above the chat, and the file viewer'sdiff --git a/ui/e2e/queue-attachments/previews.spec.ts b/ui/e2e/queue-attachments/previews.spec.tsindex 4df3df7b8..c208db09c 100644--- a/ui/e2e/queue-attachments/previews.spec.ts+++ b/ui/e2e/queue-attachments/previews.spec.ts@@ -140,6 +140,23 @@ test('a queued image is visible, 20px, centred, and costs the row no height', as.toBeGreaterThan(0);});+test('an unconfirmed image survives reload and can be inspected but not resent or removed', async ({ page }) => {+ await page.goto('/e2e/queue-attachments/fixture.html?confirming');+ for (let visit = 0; visit < 2; visit += 1) {+ if (visit) await page.reload();+ const pendingRow = page.locator('[data-queue-row]');+ await expect(pendingRow).toContainText('队列图片.png');+ const image = pendingRow.locator('img');+ await expect.poll(() => image.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBeGreaterThan(0);+ await expect(page.getByRole('button', { name: 'Confirming…' })).toBeDisabled();+ await expect(pendingRow.getByRole('button', { name: 'Remove from queue' })).toBeDisabled();+ await activate(page, pendingRow.locator('[data-queue-attachment]').first());+ await expect(page.getByRole('dialog')).toBeVisible();+ await page.keyboard.press('Escape');+ await expect(page.getByTestId('queue-fixture')).toHaveAttribute('data-sent', '0');+ }+});+test('a single-line queued message is vertically centred in its row', async ({ page }) => {const queuedRow = await boxOf(row(page, 'q-text'), 'the text-only row');const text = await boxOf(row(page, 'q-text').locator('div[role="button"]'), 'the queued message text');diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsxindex 662f39915..232109ba3 100644--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({getWorkbenchPrefs: vi.fn(),listSessionMessages: vi.fn(),listSessionQueue: vi.fn(),+ sendQueuedNow: vi.fn(),mutateConfig: vi.fn(),waitForAgentActivityConfigMutations: vi.fn(),onSessionArchived: vi.fn(),@@ -243,6 +244,7 @@ describe('ChatPage transcript hydration', () => {mocks.api.getWorkbenchPrefs.mockResolvedValue({});mocks.api.listSessionMessages.mockResolvedValue({ messages: [] });mocks.api.listSessionQueue.mockResolvedValue([]);+ mocks.api.sendQueuedNow.mockResolvedValue({ ok: true, status: 'accepted' });mocks.api.mutateConfig.mockResolvedValue({ ui: {} });mocks.api.waitForAgentActivityConfigMutations.mockResolvedValue(undefined);mocks.api.onSessionArchived.mockReturnValue(() => {});@@ -254,6 +256,83 @@ describe('ChatPage transcript hydration', () => {vi.useRealTimers();});+ it.each([+ { status: 'queued', reason: 'attachments_unavailable', notice: 'chat.queue.attachmentsUnavailable' },+ { status: 'queued', reason: 'runtime_unavailable', notice: 'chat.queue.sendDeferred' },+ { status: 'reconciling_steer', reason: undefined, notice: 'chat.queue.sendReconciling' },+ ])('retains the image and explains $status after send-now', async ({ status, reason, notice }) => {+ const image = {+ ...queuedMessage('queued-image', ''),+ state: 'queued',+ content: { attachments: [{+ token: 'image-token', name: '队列图片.png', mime: 'image/png', url: '/api/media/image-token',+ }] },+ };+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };+ mocks.api.getSessionBootstrap.mockResolvedValue({+ ...bootstrapPayload('session-new'), queued: [image], turn_state: running,+ });+ mocks.api.getTurnState.mockResolvedValue(running);+ mocks.api.listSessionQueue.mockResolvedValue({ queued: [{ ...image, state: status }] });+ const send = deferred<{ ok: boolean; status: string; reason?: string }>();+ mocks.api.sendQueuedNow.mockReturnValue(send.promise);+ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes><Route path="/chat/:sessionId" element={<ChatPage />} /></Routes>+ </MemoryRouter>,+ );+ const button = await screen.findByRole('button', { name: 'chat.queue.sendNow' });+ fireEvent.click(button);+ expect(screen.getByRole('button', { name: 'chat.queue.sendingNow' }).getAttribute('disabled')).not.toBeNull();+ expect(mocks.api.sendQueuedNow).toHaveBeenCalledWith('session-new', 'queued-image');+ expect(document.querySelector('img[src="/api/media/image-token"]')).not.toBeNull();+ await act(async () => send.resolve({ ok: true, status, reason }));+ await screen.findByText(notice);+ expect(document.querySelector('img[src="/api/media/image-token"]')).not.toBeNull();+ const control = screen.getByRole('button', {+ name: status === 'reconciling_steer' ? 'chat.queue.confirmingNow' : 'chat.queue.sendNow',+ }) as HTMLButtonElement;+ expect(control.disabled).toBe(status === 'reconciling_steer');+ expect(mocks.api.cancelSession).not.toHaveBeenCalled();+ });++ it.each(['accepted', 'queued'])('restores a confirming image on reload and follows $status settlement', async (settlement) => {+ const image = {+ ...queuedMessage('queued-image', ''),+ state: 'reconciling_steer',+ content: { attachments: [{+ token: 'image-token', name: '队列图片.png', mime: 'image/png', url: '/api/media/image-token',+ }] },+ };+ mocks.api.getSessionBootstrap.mockResolvedValue({+ ...bootstrapPayload('session-new'), queued: [image],+ });+ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes><Route path="/chat/:sessionId" element={<ChatPage />} /></Routes>+ </MemoryRouter>,+ );+ const confirming = await screen.findByRole('button', { name: 'chat.queue.confirmingNow' });+ expect((confirming as HTMLButtonElement).disabled).toBe(true);+ expect(document.querySelector('img[src="/api/media/image-token"]')).not.toBeNull();+ fireEvent.click(confirming);+ expect(mocks.api.sendQueuedNow).not.toHaveBeenCalled();+ mocks.api.listSessionQueue.mockResolvedValue({+ queued: settlement === 'accepted' ? [] : [{ ...image, state: 'queued' }],+ });+ act(() => mocks.events?.onQueueUpdated({ session_id: 'session-new' }));+ await waitFor(() => expect(screen.queryByRole('button', { name: 'chat.queue.confirmingNow' })).toBeNull());+ expect(screen.queryByText('chat.queue.sendReconciling')).toBeNull();+ if (settlement === 'queued') {+ expect((screen.getByRole('button', { name: 'chat.queue.sendNow' }) as HTMLButtonElement).disabled).toBe(false);+ expect(document.querySelector('img[src="/api/media/image-token"]')).not.toBeNull();+ } else {+ expect(document.querySelector('[data-queue-row]')).toBeNull();+ act(() => mocks.events?.onMessageNew({ ...image, type: 'user' }));+ expect(document.querySelector('img[src="/api/media/image-token"]')).not.toBeNull();+ }+ });+it('keeps the loading view when SSE Session-row recovery beats transcript bootstrap', async () => {render(<MemoryRouter initialEntries={['/chat/session-new']}>diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex b43b6542d..be2a2d3bb 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -2325,17 +2325,18 @@ export const ChatPage: React.FC = () => {);const sendQueueNow = useCallback(async () => {- // "立即发送": interrupt the running turn + flush the queue now. The queue- // flushes as one merged turn, so this runs the whole queue.+ // Promote the exact FIFO head: steer the current turn without interrupting+ // it, or start a new turn if idle. Only a compatible prefix may be claimed.const sid = sessionId;- if (!sid || queue.length === 0 || sendingQueueNow) return;+ if (!sid || queue.length === 0 || sendingQueueNow || isQueueDeliveryFenced(queue[0])) return;const requestGeneration = ++queueSendGenerationRef.current;const isCurrentRequest = () =>requestGeneration === queueSendGenerationRef.current && sid === sessionIdRef.current;- // Give the click an immediate visual response while the request interrupts- // the current turn. The queue stays visible until admission succeeds so a+ // Give the click an immediate visual response during admission.+ // The queue stays visible until admission succeeds so a// failed or ambiguous request never hides work the user may need to retry.setSendingQueueNow(true);+ setError(null);// A turn is about to run (the flushed queue) — reflect it immediately so// Stop stays available even if the controller's turn.start is missed/delayed// (especially for the idle-flush case that starts a fresh turn) (Codex P2).@@ -2351,13 +2352,16 @@ export const ChatPage: React.FC = () => {// (Codex P2). Other failures mean no turn is running → clear working.if (res.code !== 'stop_failed') setWorking(false);setError(res.detail ? String(res.detail) : t('chat.stopFailed'));- } else if (res && (res as { status?: string }).status === 'empty') {+ } else if (res?.status === 'queued') {+ setError(t(res.reason === 'attachments_unavailable'+ ? 'chat.queue.attachmentsUnavailable'+ : 'chat.queue.sendDeferred'));+ } else if (res?.status === 'empty') {// Nothing was actually flushed (a stale queue item already gone) — no// turn is starting, so drop the optimistic working state + resync.setWorking(false);} else {- // A successful admission may only claim the compatible prefix (for- // example, attachment rows can remain queued behind an active turn).+ // A successful admission may only claim the compatible prefix.// Re-read the authoritative queue instead of assuming the whole visible// batch was flushed.}@@ -3026,11 +3030,15 @@ export const ChatPage: React.FC = () => {};// Pending send-while-busy messages, shown between the transcript and the-// composer. Queued work is visually grouped, but each Delivery stays-// independently removable and compatible rows merge only at claim time.+// composer. Queued work is visually grouped; editable Deliveries stay+// independently removable. Unconfirmed steers remain visible but read-only,+// 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.+const isQueueDeliveryFenced = (item: WorkbenchMessage) =>+ item.state === 'pending_steer' || item.state === 'steering' || item.state === 'reconciling_steer';+export const QueueRow: React.FC<{item: WorkbenchMessage;onRemove: (id: string) => void;@@ -3057,10 +3065,12 @@ export const QueueRow: React.FC<{// - harness/scheduled rows (source !== 'user') carry provenance flush_queue// needs (suppress-delivery, native-id dedupe) that a plain recall would drop;// - recall can't carry uploaded files (content.attachments), so an attachment- // row would silently lose them. Both can still be deleted or left to send.+ // row would silently lose them. Editable queued rows can still be deleted;+ // unconfirmed steers cannot be recalled or removed.const att = (item.content as Record<string, unknown> | undefined)?.attachments;const hasAttachments = Array.isArray(att) && att.length > 0;- const canRecall = item.source === 'user' && !hasAttachments;+ const fenced = isQueueDeliveryFenced(item);+ const canRecall = item.source === 'user' && !hasAttachments && !fenced;// Rule 08: a queued annotation belongs to the strip and nowhere else, so the// strip is where it has to be identifiable. Same title as the card it will// become, so the row the user is looking at and the bubble that replaces it@@ -3107,6 +3117,7 @@ export const QueueRow: React.FC<{return (<divdata-queue-row="true"+ aria-busy={fenced}className={clsx('relative flex 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',hasExpandedContent ? 'items-start' : 'items-center',@@ -3192,6 +3203,7 @@ export const QueueRow: React.FC<{variant="ghost"size="icon"onClick={() => onRemove(item.id)}+ disabled={fenced}aria-label={t('chat.queue.remove')}title={t('chat.queue.remove')}className="size-6 shrink-0 text-muted hover:text-destructive-ink"@@ -3416,6 +3428,8 @@ export const QueueStrip: React.FC<{const { t } = useTranslation();if (queue.length === 0) return null;const retryRequired = queue.some((item) => item.requires_explicit_retry === true);+ const headFenced = isQueueDeliveryFenced(queue[0]);+ const busy = sendingNow || headFenced;return (<div className="shrink-0 px-4 md:px-8"><div className="mx-auto w-full max-w-[1080px] rounded-xl border border-cyan/25 bg-cyan/[0.04] p-2">@@ -3429,20 +3443,23 @@ export const QueueStrip: React.FC<{variant="ghost"size="sm"onClick={onSendNow}- disabled={sendingNow}- aria-busy={sendingNow}+ disabled={busy}+ aria-busy={busy}className="h-6 min-w-[60px] justify-center px-2 text-[11px] text-cyan-ink">- {sendingNow ? (+ {busy ? (<><Loader2 className="size-3.5 animate-spin" aria-hidden="true" />- {t('chat.queue.sendingNow')}+ {t(queue[0].state === 'reconciling_steer' ? 'chat.queue.confirmingNow' : 'chat.queue.sendingNow')}</>) : (t('chat.queue.sendNow'))}</Button></div>+ {headFenced && (+ <p role="status" className="px-1 pb-1.5 text-[11px] text-muted">{t('chat.queue.sendReconciling')}</p>+ )}{retryRequired && <p className="px-1 pb-1.5 text-[11px] text-muted">{t('chat.queue.retryHint')}</p>}<divdata-queue-batch="true"diff --git a/ui/src/components/workbench/ChatQueueRow.test.tsx b/ui/src/components/workbench/ChatQueueRow.test.tsxindex 034e26208..d6380e692 100644--- a/ui/src/components/workbench/ChatQueueRow.test.tsx+++ b/ui/src/components/workbench/ChatQueueRow.test.tsx@@ -120,6 +120,43 @@ const chips = () => [...document.querySelectorAll('[data-queue-attachment^="fileconst more = () => [...document.querySelectorAll('[data-queue-attachment-more="true"]')] as HTMLElement[];describe('QueueStrip — compatible queued messages read as one batch', () => {+ it.each(['pending_steer', 'steering', 'reconciling_steer'])('keeps a %s head visible and read-only while followers remain editable', (state) => {+ const onSendNow = vi.fn();+ const onRemove = vi.fn();+ const items = [+ queued({ id: 'head', source: 'user', state, content: {} }),+ queued({ id: 'follower', source: 'user', state: 'queued', content: {} }),+ ];+ render(+ <I18nextProvider i18n={i18n}>+ <QueueStrip queue={items} onRemove={onRemove} onRecall={vi.fn()} onSendNow={onSendNow} />+ </I18nextProvider>,+ );+ const send = screen.getByRole('button', { name: state === 'reconciling_steer' ? 'Confirming…' : 'Sending…' });+ expect((send as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(send);+ expect(onSendNow).not.toHaveBeenCalled();+ const rows = [...document.querySelectorAll<HTMLElement>('[data-queue-row]')];+ const remove = within(rows[0]).getByRole('button', { name: 'Remove from queue' });+ expect((remove as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(remove);+ expect(onRemove).not.toHaveBeenCalled();+ expect(within(rows[0]).queryByRole('button', { name: 'Recall to input' })).toBeNull();+ expect(within(rows[1]).getByRole('button', { name: 'Recall to input' })).toBeTruthy();+ fireEvent.click(within(rows[1]).getByRole('button', { name: 'Remove from queue' }));+ expect(onRemove).toHaveBeenCalledWith('follower');+ });++ it('leaves a fenced image inspectable', () => {+ const { openImage } = mountQueued(queued({+ state: 'reconciling_steer', text: '',+ content: { attachments: [{ token: 'pending-image', name: '队列图片.png', mime: 'image/png' }] },+ }));+ fireEvent.click(thumbs()[0]);+ expect(openImage).toHaveBeenCalled();+ expect(screen.getByText('队列图片.png')).toBeTruthy();+ });+it('MESSAGE-DELIVERY-031: shows the server-owned retry hold and preserves Send now', () => {const onSendNow = vi.fn();const items = [queued({diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 29d4bef28..447918331 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -786,7 +786,7 @@ export type ApiContextType = {// Send-while-busy queue (messages sent while a turn runs) + per-session draft.listSessionQueue: (sessionId: string, options?: { cache?: boolean }) => Promise<{ queued: WorkbenchMessage[] }>;removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;- sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;+ sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; reason?: string; code?: string; detail?: string }>;getTurnState: (sessionId: string, options?: { handleError?: boolean }) => Promise<SessionRuntimeState>;getCachedSessionDraft: (sessionId: string) => string | null;cacheSessionDraft: (sessionId: string, text: string) => void;@@ -1316,6 +1316,9 @@ export type WorkbenchMessage = {parent_native_message_id: string | null;// Server-owned read projection. Durable Message rows never carry this field.projection?: 'claimed_delivery' | null;+ // Queue/bootstrap include unaccepted steers as well as editable queued rows.+ // Durable transcript Messages do not carry Delivery state.+ state?: string;// Server-owned queued Delivery recovery projection, not Message metadata.requires_explicit_retry?: boolean;retry_reason?: string | null;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f4b474091..6b87a950a 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4299,6 +4299,10 @@"retryHint": "Automatic startup retries stopped after failure. Your input is retained. Resolve the error, then use Send now or Retry on the failure notice.","sendNow": "Send now","sendingNow": "Sending…",+ "confirmingNow": "Confirming…",+ "sendDeferred": "Couldn't send into the current turn. Your message is still queued.",+ "attachmentsUnavailable": "An attachment is no longer available. Your message is still queued; upload the attachment again to resend it.",+ "sendReconciling": "Delivery is being confirmed. Your message is retained; don't resend it.","recall": "Recall to input","remove": "Remove from queue","attachments": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b5947ec98..c295c5f1e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4299,6 +4299,10 @@"title": "排队中 · {{count}}","sendNow": "立即发送","sendingNow": "发送中…",+ "confirmingNow": "确认中…",+ "sendDeferred": "暂时无法发送到当前任务,消息仍保留在队列中。",+ "attachmentsUnavailable": "部分附件已不可用,原消息仍保留在队列中。请重新上传附件后再发送。",+ "sendReconciling": "正在确认消息是否送达,原消息已保留,请勿重复发送。","recall": "撤回到输入框","remove": "移出队列","attachments": {diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 36d8f9c71..4b4fc1229 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -9355,7 +9355,7 @@ async def sessions_bootstrap(session_id: str):queued = ([message_deliveries.public_delivery_payload(item)- for item in message_deliveries.list_queued(conn, session_id)+ for item in message_deliveries.list_queued(conn, session_id, include_steering=True)]if can_chatelse []@@ -11788,7 +11788,7 @@ def sessions_queue_list(session_id: str):with engine.connect() as conn:queued = [message_deliveries.public_delivery_payload(item)- for item in message_deliveries.list_queued(conn, session_id)+ for item in message_deliveries.list_queued(conn, session_id, include_steering=True)]return jsonify({"queued": queued})