Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(opencode): release prewrite Stop runtime gate (#1456)

Call White9fd42eab0438
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 8719a6e66..16d238ccf 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -458,6 +458,11 @@ class ConsolidatedMessageDispatcher:
trigger_id = self._thread_current_message_id.get(tracking_key) or context.message_id or ""
return f"{session_key}:{thread_key}:{trigger_id}"
+ def status_key_for_context(self, context: MessageContext) -> str:
+ """Capture the current turn's status key before runtime ownership changes."""
+
+ return self._get_consolidated_message_key(context)
+
def update_thread_message_id(self, context: MessageContext) -> None:
if not context.message_id:
return
@@ -504,6 +509,27 @@ class ConsolidatedMessageDispatcher:
async def _clear_consolidated_state(self, context: MessageContext) -> None:
await self._drop_status_keys(self._get_consolidated_message_key(context))
+ async def finish_prewrite_stop_surfaces(
+ self,
+ context: MessageContext,
+ *,
+ consolidated_key: str,
+ ) -> None:
+ """Retire IM-only progress surfaces without claiming Turn terminal ownership."""
+
+ try:
+ await self._collapse_status_bubble(
+ context,
+ self._get_im_client(context),
+ reason="stopped",
+ consolidated_key=consolidated_key,
+ )
+ finally:
+ try:
+ await self._drop_status_keys(consolidated_key)
+ finally:
+ await self._finish_processing_indicator_turn(context)
+
# ------------------------------------------------------------------
# Concise status bubble (Slack / Discord)
# ------------------------------------------------------------------
@@ -1053,7 +1079,12 @@ class ConsolidatedMessageDispatcher:
return self._consolidated_message_ids.get(consolidated_key)
async def _collapse_status_bubble(
- self, context: MessageContext, im_client, *, reason: str = "done"
+ self,
+ context: MessageContext,
+ im_client,
+ *,
+ reason: str = "done",
+ consolidated_key: str | None = None,
) -> None:
"""Collapse a still-open concise status bubble to its terminal marker.
@@ -1070,7 +1101,7 @@ class ConsolidatedMessageDispatcher:
if a bubble exists — edits it to the terminal footer. The footer marker
(✅ for ``done`` else ⏹, time only when ``show_duration``) is owned by
``_status_footer_text``. ``reason`` ∈ {"done","stopped","failed"}."""
- key = self._get_consolidated_message_key(context)
+ key = consolidated_key or self._get_consolidated_message_key(context)
# Gate on whether a CONCISE bubble was posted for this turn, not the current
# style: a Web UI concise -> off/verbose change mid-turn must still collapse
# an already-posted bubble. Keying on the concise-bubble set (not plain
diff --git a/modules/agents/service.py b/modules/agents/service.py
index a25bbec0f..e8aa46387 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -12,6 +12,7 @@ from core.message_output import (
terminal_output_for,
terminal_turn_output,
)
+from core.native_dispatch_phase import prewrite_user_stop_requested
from core.runtime_activation import (
RuntimeActivationIdentity,
RuntimeActivationRegistry,
@@ -381,6 +382,48 @@ class AgentService:
# make the scheduled tidy a no-op and leave the bubble stuck. Release
# inside the scheduled task's finally; fall back to a synchronous
# release if the emit can't be scheduled so the gate never leaks.
+ # A durable pre-write Stop already owns the terminal receipt and has
+ # proven that no native write happened. Release this adapter gate
+ # synchronously: deferring it behind the generic terminal tidy can
+ # leave the next turn waiting forever if that best-effort emit stalls.
+ if prewrite_user_stop_requested(request.context):
+ dispatcher = getattr(self.controller, "message_dispatcher", None)
+ status_key_for_context = getattr(dispatcher, "status_key_for_context", None)
+ consolidated_key = (
+ status_key_for_context(request.context)
+ if callable(status_key_for_context)
+ else None
+ )
+ self.release_runtime_turn_key(runtime_key, gate.token)
+ cleanup = getattr(
+ dispatcher,
+ "finish_prewrite_stop_surfaces",
+ None,
+ )
+ if callable(cleanup) and consolidated_key is not None:
+ try:
+ async def _cleanup_prewrite_stop_surfaces() -> None:
+ try:
+ await cleanup(
+ request.context,
+ consolidated_key=consolidated_key,
+ )
+ except Exception:
+ logger.debug(
+ "Failed to clean prewrite Stop surfaces",
+ exc_info=True,
+ )
+
+ cleanup_task = asyncio.create_task(_cleanup_prewrite_stop_surfaces())
+ self._background_tasks.add(cleanup_task)
+ cleanup_task.add_done_callback(self._background_tasks.discard)
+ except Exception:
+ logger.debug(
+ "Failed to schedule prewrite Stop surface cleanup",
+ exc_info=True,
+ )
+ raise
+
emit = getattr(self.controller, "emit_agent_message", None)
scheduled = False
if callable(emit):
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index d1621670e..4d6901808 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -333,8 +333,10 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
return [delivery_payload(dict(row)) for row in rows]
-def delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
- snapshot = _json_object(row.get("snapshot_json"))
+def _delivery_payload_from_snapshot(
+ row: dict[str, Any],
+ snapshot: dict[str, Any],
+) -> dict[str, Any]:
content = _json_object(snapshot.get("content_json"))
metadata = _json_object(snapshot.get("metadata_json"))
return {
@@ -368,6 +370,13 @@ def delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
}
+def delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
+ return _delivery_payload_from_snapshot(
+ row,
+ _json_object(row.get("snapshot_json")),
+ )
+
+
def delivery_has_remote_resource_context(row: dict[str, Any]) -> bool:
"""Return whether an immutable Delivery snapshot records remote origin."""
@@ -1217,6 +1226,26 @@ def _merged_initial_snapshot(deliveries: list[dict[str, Any]]) -> dict[str, Any]
return first
+def claimed_workbench_message_payload(
+ conn: Connection,
+ turn_id: str,
+) -> dict[str, Any] | None:
+ """Project one claimed Web batch exactly as native acceptance will merge it."""
+
+ deliveries = initial_deliveries_for_turn(conn, turn_id)
+ if not deliveries or any(delivery["state"] != "claimed" for delivery in deliveries):
+ return None
+ snapshot = _merged_initial_snapshot(deliveries)
+ if not (
+ snapshot.get("platform") == "avibe"
+ and snapshot.get("author") == "user"
+ and snapshot.get("type") == "user"
+ and snapshot.get("source") == "user"
+ ):
+ return None
+ return _delivery_payload_from_snapshot(deliveries[0], snapshot)
+
+
def materialize_start_acceptance(
conn: Connection,
*,
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 529fd5f1b..5e65ae623 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -157,6 +157,9 @@ capabilities:
- tests/scenarios/message_delivery/test_message_delivery_scenarios.py
unit_or_contract_tests:
- tests/test_message_dispatcher_scheduled.py
+ - tests/test_agent_service.py
+ - tests/test_ui_session_stream.py
+ - ui/src/components/workbench/Composer.attachmentRetry.test.tsx
- id: tunnel_quality
name: remote-access tunnel quality and smooth route recovery
status: active
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 7cd4dcc01..837c2267a 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -146,6 +146,24 @@ scenarios:
kind: lifecycle
layer: contract
test: tests/test_session_delivery_fsm.py::test_stop_cancels_a_starting_turn_before_native_write
+ - id: MESSAGE-DELIVERY-023
+ name: Prewrite Stop releases its runtime gate before a same-runtime successor enters
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_agent_service.py::test_message_delivery_023_prewrite_stop_releases_gate_without_terminal_tidy
+ - id: MESSAGE-DELIVERY-024
+ name: Workbench reload keeps an active claimed input visible before native acceptance
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_ui_session_stream.py::test_message_delivery_024_claimed_active_input_survives_transcript_reload
+ - id: MESSAGE-DELIVERY-025
+ name: The send gesture cannot activate the newly rendered Stop control
+ status: covered
+ kind: regression
+ layer: contract
+ test: ui/src/components/workbench/Composer.attachmentRetry.test.tsx
- id: MESSAGE-DELIVERY-101
name: Unresolved fallback-capable delivery fences only later FIFO submissions
status: covered
diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yaml
index f382b5ac4..6600e2f13 100644
--- a/tests/scenarios/message_delivery/observations.yaml
+++ b/tests/scenarios/message_delivery/observations.yaml
@@ -46,3 +46,17 @@ observations:
- identify callback events by callee terminal Turn and callback Session
- point every participating parent Run ledger to the shared callback Run
- keep callbacks for different terminal Turns or callback Sessions independent
+ - id: OBS-MESSAGE-DELIVERY-005
+ source: live_local_diagnosis
+ related_scenarios:
+ - MESSAGE-DELIVERY-023
+ - MESSAGE-DELIVERY-024
+ - MESSAGE-DELIVERY-025
+ summary: A prewrite Web Stop left the OpenCode runtime gate owned while the replacement input vanished from the recovered transcript.
+ previous_assumption: The generic cancellation terminal tidy would always release the runtime gate quickly, and optimistic input rendering was sufficient until native acceptance.
+ observed_behavior: The first Turn stopped 134 milliseconds after admission before native write; its asynchronous terminal tidy retained the gate, the next Turn waited before entering OpenCode, and its claimed Delivery was absent after Chat reloaded from materialized Messages.
+ required_updates:
+ - release the runtime gate synchronously when the durable prewrite Stop owns terminalization
+ - prevent a send click burst from activating the destructive control rendered at the same pointer target
+ - project the active claimed Delivery into Workbench tail and bootstrap reads until native acceptance materializes it
+ - log Workbench Stop request and settlement boundaries for future source attribution
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 1df8a3924..6070f6657 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -12,6 +12,7 @@ from core.message_output import HARNESS_PROMPT_ECHO_SPEC_KEY, terminal_turn_outp
from core.native_dispatch_phase import (
DISPATCH_PHASE_PREWRITE,
backend_dispatch_attempted,
+ mark_prewrite_user_stop,
set_dispatch_phase,
)
from core.session_activities import SessionActivityRegistry
@@ -1398,6 +1399,71 @@ def test_agent_service_schedules_terminal_tidy_on_cancellation() -> None:
asyncio.run(_run())
+def test_message_delivery_023_prewrite_stop_releases_gate_without_terminal_tidy() -> None:
+ """MESSAGE-DELIVERY-023: a prewrite Stop cannot retain runtime ownership."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ stalled_tidy = asyncio.Event()
+
+ async def _stall_terminal_tidy(*_args, **_kwargs) -> None:
+ await stalled_tidy.wait()
+
+ controller.emit_agent_message = AsyncMock(side_effect=_stall_terminal_tidy)
+ controller.session_turns = Mock()
+ surface_cleanup_release = asyncio.Event()
+
+ async def _stall_surface_cleanup(*_args, **_kwargs) -> None:
+ await surface_cleanup_release.wait()
+
+ controller.message_dispatcher = SimpleNamespace(
+ status_key_for_context=Mock(return_value="status:first"),
+ finish_prewrite_stop_surfaces=AsyncMock(side_effect=_stall_surface_cleanup),
+ )
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ entered = asyncio.Event()
+
+ class _PrewriteAgent(_RuntimeAgent):
+ async def handle_message(self, request):
+ self.started.append(request.message)
+ if request.message == "first":
+ entered.set()
+ await asyncio.Event().wait()
+
+ agent = _PrewriteAgent()
+ service.register(agent)
+ first = _request("first")
+ first_task = asyncio.create_task(service.handle_message("claude", first))
+ await asyncio.wait_for(entered.wait(), timeout=0.5)
+
+ mark_prewrite_user_stop(first.context)
+ first_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first_task
+ await asyncio.sleep(0)
+
+ gate = service._turn_gates["session:/repo"]
+ assert not gate.lock.locked()
+ assert gate.token == ""
+ controller.emit_agent_message.assert_not_awaited()
+ controller.session_turns.on_native_terminal.assert_not_called()
+ controller.message_dispatcher.status_key_for_context.assert_called_once_with(first.context)
+ controller.message_dispatcher.finish_prewrite_stop_surfaces.assert_awaited_once_with(
+ first.context,
+ consolidated_key="status:first",
+ )
+
+ second = _request("second")
+ await asyncio.wait_for(service.handle_message("claude", second), timeout=0.5)
+ assert agent.started == ["first", "second"]
+ service.release_runtime_turn(second.context)
+ surface_cleanup_release.set()
+ await asyncio.sleep(0)
+
+ asyncio.run(_run())
+
+
def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> None:
"""HFR-001: pre-accept failure releases ownership even if terminal emit fails."""
diff --git a/tests/test_message_dispatcher_status_bubble.py b/tests/test_message_dispatcher_status_bubble.py
index 42f5fc1ad..71d1e1468 100644
--- a/tests/test_message_dispatcher_status_bubble.py
+++ b/tests/test_message_dispatcher_status_bubble.py
@@ -652,6 +652,44 @@ class BeginStatusBubbleTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1"]) # still one send
self.assertEqual(controller.im_client.edits, [("msg-1", "🔧 Bash {}", "⌛ 0s · 1 st")])
+ async def test_prewrite_stop_cleanup_retires_bubble_without_terminal_emit(self):
+ controller = _StubController(platform="slack")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ await d.begin_status_bubble(ctx)
+ key = d._get_consolidated_message_key(ctx)
+
+ await d.finish_prewrite_stop_surfaces(ctx, consolidated_key=key)
+
+ self.assertIn(("msg-1", "", "⏹ stopped · 0s"), controller.im_client.edits)
+ self.assertNotIn(key, d._consolidated_message_ids)
+ self.assertNotIn(key, d._concise_bubble_keys)
+
+ async def test_prewrite_stop_cleanup_cannot_clear_successor_status(self):
+ controller = _StubController(platform="slack")
+ d = _dispatcher(controller)
+ stopped = MessageContext(
+ user_id="U1", channel_id="C1", platform="slack", message_id="old-trigger"
+ )
+ d.update_thread_message_id(stopped)
+ await d.begin_status_bubble(stopped)
+ stopped_key = d.status_key_for_context(stopped)
+
+ successor = MessageContext(
+ user_id="U1", channel_id="C1", platform="slack", message_id="new-trigger"
+ )
+ d.update_thread_message_id(successor)
+ await d.begin_status_bubble(successor)
+ successor_key = d.status_key_for_context(successor)
+
+ await d.finish_prewrite_stop_surfaces(stopped, consolidated_key=stopped_key)
+
+ self.assertNotIn(stopped_key, d._consolidated_message_ids)
+ self.assertEqual(d._consolidated_message_ids[successor_key], "msg-2")
+ self.assertIn(successor_key, d._concise_bubble_keys)
+ self.assertIn(("msg-1", "", "⏹ stopped · 0s"), controller.im_client.edits)
+ self.assertNotIn(("msg-2", "", "⏹ stopped · 0s"), controller.im_client.edits)
+
async def test_begin_is_idempotent(self):
controller = _StubController(platform="slack")
d = _dispatcher(controller)
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 964730a08..b6870b99d 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -16,6 +16,7 @@ import sys
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -175,6 +176,48 @@ def _settle_reserved_delivery(payload: dict, *, state: str) -> dict:
return settled
+def _seed_claimed_batch(
+ *,
+ scope_id: str,
+ session_id: str,
+ texts: list[str],
+ platform: str = "avibe",
+ metadata: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Create the pre-native-write state that must remain visible in Chat."""
+
+ with create_sqlite_engine().begin() as conn:
+ deliveries = [
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id=f"msg_claimed_{session_id}_{index}",
+ session_id=session_id,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=platform,
+ author="user",
+ source="user",
+ text=text,
+ metadata=metadata,
+ ),
+ dispatch_text=text,
+ )
+ for index, text in enumerate(texts)
+ ]
+ turn_id = message_deliveries.new_turn_id()
+ return message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="opencode",
+ deliveries=deliveries,
+ dispatch_text="\n".join(texts),
+ )
+
+
def _accepted_dispatch(session_id: str) -> AsyncMock:
async def dispatch(payload: dict) -> dict:
settled = _settle_reserved_delivery(payload, state="accepted")
@@ -1185,6 +1228,145 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert body["turn_state"]["connection"] == "connected"
+def test_message_delivery_024_claimed_active_input_survives_transcript_reload(
+ isolated_state,
+ tmp_path,
+):
+ """MESSAGE-DELIVERY-024: claimed Web input survives and then reconciles."""
+
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(
+ tmp_path,
+ agent_name="opencode-worker",
+ agent_backend="opencode",
+ )
+ claimed = _seed_claimed_batch(
+ scope_id=scope_id,
+ session_id=session_id,
+ texts=["first input", "second input"],
+ metadata={"resource_user_context": {"sub": "must-not-leak"}},
+ )
+ first_delivery = claimed["deliveries"][0]
+
+ turn_state = AsyncMock(
+ return_value={
+ "status_code": 200,
+ "body": {"in_flight": True, "native_turn_started": False},
+ }
+ )
+ with (
+ patch("vibe.internal_client.turn_state", turn_state),
+ patch(
+ "vibe.api.get_vibe_agents",
+ return_value={"agents": [], "default_agent_name": None},
+ ),
+ ):
+ client = app.test_client()
+ messages_response = client.get(f"/api/sessions/{session_id}/messages?tail=1")
+ bootstrap_response = client.get(f"/api/sessions/{session_id}/bootstrap")
+
+ assert messages_response.status_code == 200
+ assert bootstrap_response.status_code == 200
+ for rows in (
+ messages_response.get_json()["messages"],
+ bootstrap_response.get_json()["messages"],
+ ):
+ assert [row["id"] for row in rows] == [first_delivery["id"]]
+ assert rows[0]["text"] == "first input\nsecond input"
+ assert rows[0]["type"] == "user"
+ assert rows[0]["metadata"]["merged_delivery_ids"] == [
+ delivery["id"] for delivery in claimed["deliveries"]
+ ]
+ assert rows[0]["projection"] == "claimed_delivery"
+ assert rows[0]["delivered_at"] == claimed["turn"]["started_at"]
+ assert "resource_user_context" not in rows[0]["metadata"]
+
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(
+ select(messages.c.id).where(messages.c.session_id == session_id)
+ ).scalar_one_or_none() is None
+
+ with create_sqlite_engine().begin() as conn:
+ turn = message_deliveries.get_turn(conn, claimed["turn"]["id"])
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn["id"],
+ expected_version=int(turn["version"]),
+ runtime_key="runtime:accepted",
+ runtime_turn_id="runtime-turn:accepted",
+ native_turn_id="native:accepted",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn["id"],
+ evidence={"kind": "test_native_acceptance"},
+ )
+
+ accepted_response = client.get(f"/api/sessions/{session_id}/messages?tail=1")
+ accepted_rows = accepted_response.get_json()["messages"]
+ assert accepted_rows[0]["id"] == first_delivery["id"]
+ assert accepted_rows[0]["text"] == "first input\nsecond input"
+ assert "projection" not in accepted_rows[0]
+ assert "workbench_claimed_delivery" not in accepted_rows[0]["metadata"]
+
+ from core.services import sessions as sessions_service
+
+ im_agent = _ensure_vibe_agent("im-opencode-worker", "opencode")
+ with create_sqlite_engine().begin() as conn:
+ im_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend=im_agent.backend,
+ agent_id=im_agent.id,
+ agent_name=im_agent.name,
+ )
+ im_session_id = im_session["id"]
+ _seed_claimed_batch(
+ scope_id=scope_id,
+ session_id=im_session_id,
+ texts=["unaccepted IM input"],
+ platform="slack",
+ )
+ im_response = client.get(f"/api/sessions/{im_session_id}/messages?tail=1")
+ assert im_response.get_json()["messages"] == []
+
+
+def test_claimed_projection_follows_the_result_before_its_turn(isolated_state, tmp_path):
+ """MESSAGE-DELIVERY-024: projection enters at claim time, not submission time."""
+
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(
+ tmp_path,
+ agent_name="opencode-order",
+ agent_backend="opencode",
+ )
+ with create_sqlite_engine().begin() as conn:
+ result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="previous turn result",
+ )
+ claimed = _seed_claimed_batch(
+ scope_id=scope_id,
+ session_id=session_id,
+ texts=["next turn input"],
+ )
+
+ response = app.test_client().get(f"/api/sessions/{session_id}/messages?tail=1")
+
+ assert response.status_code == 200
+ rows = response.get_json()["messages"]
+ assert [row["id"] for row in rows] == [result["id"], claimed["deliveries"][0]["id"]]
+ assert rows[1]["delivered_at"] == claimed["turn"]["started_at"]
+
+
def test_chat_bootstrap_filters_harness_activities_for_viewer(isolated_state, tmp_path):
from vibe.ui_server import app
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 1824b562c..4f0cc04eb 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => ({
events: null as null | {
onConnected: () => void;
onAuthorizationChanged: (data: { resource_kinds?: string[] }) => void;
+ onTurnEnd: (data: { session_id: string }) => void;
},
}));
@@ -138,11 +139,41 @@ const bootstrapPayload = (sessionId: string) => ({
draft: { text: '' },
});
+const projectedMessage = (id: string, text: string) => ({
+ id,
+ scope_id: 'scope-1',
+ session_id: 'session-new',
+ platform: 'avibe',
+ author: 'user',
+ type: 'user',
+ source: 'user',
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ projection: 'claimed_delivery' as const,
+ text,
+ content: {},
+ metadata: {},
+ created_at: '2026-08-15T00:00:00Z',
+ updated_at: '2026-08-15T00:00:00Z',
+ delivered_at: '2026-08-15T00:00:01Z',
+ read_at: null,
+});
+
describe('ChatPage transcript hydration', () => {
let sessionRow: Deferred<{ id: string }>;
let bootstrap: Deferred<never>;
beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
sessionRow = deferred();
bootstrap = deferred();
mocks.events = null;
@@ -162,7 +193,10 @@ describe('ChatPage transcript hydration', () => {
mocks.api.onSessionArchived.mockReturnValue(() => {});
});
- afterEach(cleanup);
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
it('keeps the loading view when SSE Session-row recovery beats transcript bootstrap', async () => {
render(
@@ -236,4 +270,92 @@ describe('ChatPage transcript hydration', () => {
expect(screen.getByText('common.loading')).toBeTruthy();
expect(screen.queryByText('chat.transcriptEmpty')).toBeNull();
});
+
+ it('removes a retired claimed Delivery projection during reconnect recovery', async () => {
+ const projected = projectedMessage('delivery-claimed', 'claimed input still visible');
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ messages: [projected],
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(screen.getByText(projected.text)).toBeTruthy());
+ act(() => mocks.events?.onConnected());
+
+ await waitFor(() => expect(screen.queryByText(projected.text)).toBeNull());
+ expect(mocks.api.listSessionMessages).toHaveBeenCalledWith('session-new', {
+ limit: 50,
+ tail: true,
+ cache: false,
+ });
+ });
+
+ it('does not let an older recovery resurrect a projection after settlement', async () => {
+ const projected = projectedMessage('delivery-racing-recovery', 'stale projected input');
+ const staleRecovery = deferred<{ messages: typeof projected[] }>();
+ const settledRecovery = deferred<{ messages: never[] }>();
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ messages: [projected],
+ });
+ mocks.api.listSessionMessages
+ .mockReset()
+ .mockReturnValueOnce(staleRecovery.promise)
+ .mockReturnValueOnce(settledRecovery.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(screen.getByText(projected.text)).toBeTruthy());
+ act(() => mocks.events?.onConnected());
+ await waitFor(() => expect(mocks.api.listSessionMessages).toHaveBeenCalledTimes(1));
+ act(() => mocks.events?.onTurnEnd({ session_id: 'session-new' }));
+ await waitFor(() => expect(mocks.api.listSessionMessages).toHaveBeenCalledTimes(2));
+
+ await act(async () => settledRecovery.resolve({ messages: [] }));
+ await waitFor(() => expect(screen.queryByText(projected.text)).toBeNull());
+ await act(async () => staleRecovery.resolve({ messages: [projected] }));
+
+ expect(screen.queryByText(projected.text)).toBeNull();
+ });
+
+ it('does not let an older bootstrap resurrect a projection after recovery', async () => {
+ const projected = projectedMessage('delivery-racing-bootstrap', 'stale bootstrap projection');
+ const staleBootstrap = deferred<ReturnType<typeof bootstrapPayload> & { messages: typeof projected[] }>();
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockReset().mockReturnValue(staleBootstrap.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(mocks.events).not.toBeNull());
+ act(() => mocks.events?.onConnected());
+ await waitFor(() => expect(mocks.api.listSessionMessages).toHaveBeenCalledTimes(1));
+ await act(async () => staleBootstrap.resolve({
+ ...bootstrapPayload('session-new'),
+ messages: [projected],
+ }));
+
+ await waitFor(() => expect(screen.getByText('chat.transcriptEmpty')).toBeTruthy());
+ expect(screen.queryByText(projected.text)).toBeNull();
+ });
});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 90d71d063..0c2c47f4c 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -65,6 +65,7 @@ import {
isTranscriptWindowDisjoint,
mergeById,
insertMessageOrdered,
+ reconcileWorkbenchClaimedDeliveries,
} from '../../lib/transcriptOrder';
import { AgentRoutePicker } from './AgentRoutePicker';
import {
@@ -789,6 +790,26 @@ export const ChatPage: React.FC = () => {
// authorization refresh). Only the latest bootstrap may commit state: a
// superseded success or failure describes an older authorization snapshot.
const bootstrapRequestGenerationRef = useRef(0);
+ // Bootstrap, recovery, and jump-to-latest all return authoritative live-tail
+ // snapshots. Order their successful commits through one generation so an
+ // older response cannot restore a claimed projection after a newer
+ // post-settlement snapshot removed it. A failed newer read does not suppress
+ // an older successful fallback; the next successful generation still wins.
+ const transcriptReadGenerationRef = useRef(0);
+ const committedTranscriptReadGenerationRef = useRef(0);
+ const beginTranscriptSnapshotRead = useCallback((requestSessionId: string) => {
+ const generation = ++transcriptReadGenerationRef.current;
+ return () => {
+ if (
+ requestSessionId !== sessionIdRef.current
+ || generation < committedTranscriptReadGenerationRef.current
+ ) {
+ return false;
+ }
+ committedTranscriptReadGenerationRef.current = generation;
+ return true;
+ };
+ }, []);
const appendMessage = useCallback((msg: WorkbenchMessage) => {
setMessages((prev) => {
@@ -926,41 +947,50 @@ export const ChatPage: React.FC = () => {
// Does NOT touch ``working``: ``turn.end`` is the authoritative end signal, and
// clearing on a fetched (possibly older) result could hide Stop on a newer
// queued turn that is still in flight (Codex P2). Cheap + idempotent.
- const reconcile = useCallback(async () => {
+ const reconcile = useCallback(async ({ force = false }: { force?: boolean } = {}) => {
if (!sessionId) return;
- if (historicalWindowRef.current) return;
+ if (historicalWindowRef.current && !force) return;
// Reader scrolled up in an already-capped window: don't recover tail rows they
// aren't looking at into the DOM — detach the live tail so jump-to-latest
// reloads it. Synchronous flip (not via the [messages] effect) so the same
// commit gates mark-read. Bounds repeated-gap growth: once historical, this
// early-returns above. Mirrors the onMessageNew ingest policy.
- if (!followingTailRef.current && messagesRef.current.length >= MAX_RETAINED_MESSAGES) {
+ if (
+ !force &&
+ !followingTailRef.current &&
+ messagesRef.current.length >= MAX_RETAINED_MESSAGES
+ ) {
setHistoricalWindow(true);
return;
}
+ const claimTranscriptSnapshot = beginTranscriptSnapshotRead(sessionId);
try {
// tail: the RECENT window (not the oldest page), so a missed latest row in
// a long chat is actually recovered (Codex P2).
const res = await api.listSessionMessages(sessionId, { limit: 50, tail: true, cache: false });
- if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
+ if (!claimTranscriptSnapshot()) return;
const fresh = res.messages.filter(isTranscriptMessage);
+ setMessages((prev) => {
+ // The tail endpoint includes the one active claimed projection, if any,
+ // so every successful recovery read is authoritative for projection
+ // replacement/removal even when turn.end was missed.
+ const reconciled = reconcileWorkbenchClaimedDeliveries(prev, fresh);
+ if (historicalWindowRef.current) return reconciled;
+ const merged = mergeById(reconciled, fresh);
+ // Following the tail: keep the window capped. A gap larger than the tail
+ // fetch, recovered here, would otherwise blow past the cap until the next
+ // live append. Drop the oldest and re-point the cursor below.
+ if (followingTailRef.current && merged.length > MAX_RETAINED_MESSAGES) {
+ trimmedOldestRef.current = true;
+ return merged.slice(merged.length - MAX_RETAINED_MESSAGES);
+ }
+ return merged;
+ });
+ if (historicalWindowRef.current) return;
if (fresh.length) {
const tailOldest = fresh[0];
const previousOldestId = oldestLoadedIdRef.current;
const previousNewest = messagesRef.current[messagesRef.current.length - 1];
- setMessages((prev) => {
- const merged = mergeById(prev, fresh);
- // Following the tail: keep the window capped. A gap larger than the tail
- // fetch, recovered here, would otherwise blow past the cap until the next
- // live append (Codex). Drop the oldest; the [messages] effect re-points
- // the older cursor (it overrides the cursor set below, which stays for
- // the no-trim case).
- if (followingTailRef.current && merged.length > MAX_RETAINED_MESSAGES) {
- trimmedOldestRef.current = true;
- return merged.slice(merged.length - MAX_RETAINED_MESSAGES);
- }
- return merged;
- });
if (
!previousOldestId ||
!previousNewest ||
@@ -976,7 +1006,7 @@ export const ChatPage: React.FC = () => {
// settled groups from storage (a recovered turn gets its chip; a still-running
// turn keeps/re-hydrates its card). Coalesced + no-op when the toggle is off.
scheduleActivityRefresh(workingRef.current);
- }, [api, sessionId, scheduleActivityRefresh]);
+ }, [api, sessionId, scheduleActivityRefresh, beginTranscriptSnapshotRead]);
// The send-while-busy queue (pending messages shown above the composer).
// Re-fetched on mount + on every ``queue.updated`` (enqueue / flush / remove).
@@ -1032,10 +1062,11 @@ export const ChatPage: React.FC = () => {
const reloadLatestMessages = useCallback(async (): Promise<boolean> => {
if (!sessionId) return false;
+ const claimTranscriptSnapshot = beginTranscriptSnapshotRead(sessionId);
try {
const res = await api.listSessionMessages(sessionId, { limit: 50, tail: true, cache: false });
- if (sessionId !== sessionIdRef.current) return false;
const tailMessages = res.messages.filter(isTranscriptMessage);
+ if (!claimTranscriptSnapshot()) return false;
if (tailMessages.length === 0) return false;
setMessages(tailMessages);
setOlderCursor(res.next_before_id ?? null);
@@ -1049,7 +1080,7 @@ export const ChatPage: React.FC = () => {
} catch {
return false;
}
- }, [api, sessionId, scheduleActivityRefresh]);
+ }, [api, sessionId, scheduleActivityRefresh, beginTranscriptSnapshotRead]);
// Cache every edit synchronously so navigation, a tab close, or a disconnected
// network cannot lose it. Cloud persistence remains debounced and serialized.
@@ -1154,6 +1185,7 @@ export const ChatPage: React.FC = () => {
const refresh = useCallback(async () => {
if (!sessionId) return;
const requestGeneration = ++bootstrapRequestGenerationRef.current;
+ const claimTranscriptSnapshot = beginTranscriptSnapshotRead(sessionId);
const requestIsCurrent = () => (
sessionId === sessionIdRef.current
&& requestGeneration === bootstrapRequestGenerationRef.current
@@ -1202,11 +1234,14 @@ export const ChatPage: React.FC = () => {
// visibility decision too — unfiltered, a queued annotation opened the chat
// as a delivered bubble *and* sat in the queue strip, the exact double
// render the live path already rejects.
- setMessages((prev) => mergeById(bootstrap.messages.filter(isTranscriptMessage), prev));
+ const transcriptSnapshotIsCurrent = claimTranscriptSnapshot();
+ if (transcriptSnapshotIsCurrent) {
+ setMessages((prev) => mergeById(prev, bootstrap.messages.filter(isTranscriptMessage)));
+ setOlderCursor(bootstrap.next_before_id ?? null);
+ setHistoricalWindow(false);
+ }
setHydratedTranscriptSessionId(sessionId);
setFailedBootstrapSessionId(null);
- setOlderCursor(bootstrap.next_before_id ?? null);
- setHistoricalWindow(false);
// Chat Activity chips for past turns: resync the per-turn summary (row text
// lazy-loads on expand). If a turn is in flight, the refresh re-hydrates the
// running card instead of showing it as interrupted.
@@ -1236,7 +1271,7 @@ export const ChatPage: React.FC = () => {
// of its own loading state into a premature not-found / error view.
if (requestIsCurrent()) setLoading(false);
}
- }, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow]);
+ }, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow, beginTranscriptSnapshotRead]);
// Clear per-session state the instant the session changes (React Router swaps
// only :sessionId, reusing this instance), before the new session's
@@ -1392,6 +1427,7 @@ export const ChatPage: React.FC = () => {
// so the header picks up both that route and a first native bind.
void refreshSessionRow();
void syncTurnState();
+ void reconcile({ force: true });
}
},
onQueueUpdated: (data) => {
@@ -1430,7 +1466,7 @@ export const ChatPage: React.FC = () => {
// Every (re)connect recovers any state missed while the socket was down:
// dropped message rows, the queue, whether a turn is still running, and
// a native bind whose turn.end we missed.
- void reconcile();
+ void reconcile({ force: true });
void refreshQueue();
void syncTurnState({ quiet: true });
void refreshSessionRow();
@@ -1472,7 +1508,7 @@ export const ChatPage: React.FC = () => {
if (document.visibilityState !== 'visible') return;
// A suspended tab can drop the reply AND the turn.end, so recover all
// three: missed rows, the queue, and the working/Stop state (Codex P2).
- void reconcile();
+ void reconcile({ force: true });
void refreshQueue();
void syncTurnState({ quiet: true });
void refreshSessionRow();
diff --git a/ui/src/components/workbench/Composer.attachmentRetry.test.tsx b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
index 0f64e06d6..409928d4f 100644
--- a/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
+++ b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
@@ -1,7 +1,7 @@
/* @vitest-environment jsdom */
import { createInstance } from 'i18next';
-import { createRef, type ReactElement } from 'react';
+import { createRef, useState, type ReactElement } from 'react';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -40,7 +40,10 @@ const providers = (ui: ReactElement) => (
</I18nextProvider>
);
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
beforeEach(() => uploadWorkbenchAttachment.mockReset());
describe('Composer attachment retry', () => {
@@ -156,3 +159,37 @@ describe('Composer draft retry', () => {
]);
});
});
+
+describe('Composer Stop activation', () => {
+ it('MESSAGE-DELIVERY-025 blocks a send click burst from the new Stop control', async () => {
+ vi.useFakeTimers();
+ const onStop = vi.fn();
+
+ const Harness = () => {
+ const [busy, setBusy] = useState(false);
+ return (
+ <Composer
+ busy={busy}
+ onSend={() => {
+ setBusy(true);
+ }}
+ onStop={onStop}
+ />
+ );
+ };
+
+ render(providers(<Harness />));
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'start' } });
+ fireEvent.click(screen.getByLabelText(en.chat.compose.send));
+ const stop = screen.getByLabelText(en.chat.compose.stop) as HTMLButtonElement;
+
+ expect(stop.disabled).toBe(true);
+ fireEvent.click(stop);
+ expect(onStop).not.toHaveBeenCalled();
+
+ await act(async () => vi.advanceTimersByTime(400));
+ expect(stop.disabled).toBe(false);
+ fireEvent.click(stop);
+ expect(onStop).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 26fecf389..4a8a34919 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -79,6 +79,10 @@ export type ComposerAttachment = {
// concurrency still prevents a large drop from saturating the connection.
const UPLOAD_CONCURRENCY = 4;
+// Send and Stop occupy the same pointer target. A fast second click from the
+// send gesture can otherwise land on the newly-rendered destructive control.
+const STOP_ARM_DELAY_MS = 400;
+
// Unique-enough id for an optimistic attachment chip before the server token
// lands. Date.now() collides within a batch, so the random suffix separates
// files staged in the same tick.
@@ -1198,6 +1202,17 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
);
const voiceCaptureActive = recording || voiceProcessing;
const voiceDiscardAvailable = recording || voiceRetainedSession !== null;
+ const [stopArmed, setStopArmed] = useState(false);
+
+ useEffect(() => {
+ if (!busyControls) {
+ setStopArmed(false);
+ return;
+ }
+ setStopArmed(false);
+ const timer = window.setTimeout(() => setStopArmed(true), STOP_ARM_DELAY_MS);
+ return () => window.clearTimeout(timer);
+ }, [busyControls, sessionId]);
const update = (next: string) => {
valueRef.current = next;
@@ -1530,6 +1545,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
variant="destructive-soft"
size="icon"
onClick={onStop}
+ disabled={!stopArmed}
aria-label={t('chat.compose.stop')}
className="size-9 shrink-0"
>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index e2781b52b..76c267b92 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1248,6 +1248,8 @@ export type WorkbenchMessage = {
source_session_agent_name?: string | null;
native_message_id: string | null;
parent_native_message_id: string | null;
+ // Server-owned read projection. Durable Message rows never carry this field.
+ projection?: 'claimed_delivery' | null;
text: string;
content: Record<string, unknown>;
metadata: Record<string, unknown>;
diff --git a/ui/src/lib/transcriptOrder.test.ts b/ui/src/lib/transcriptOrder.test.ts
index 35f0a2da0..12406cec5 100644
--- a/ui/src/lib/transcriptOrder.test.ts
+++ b/ui/src/lib/transcriptOrder.test.ts
@@ -7,6 +7,7 @@ import {
mergeAnchorWindow,
mergeById,
insertMessageOrdered,
+ reconcileWorkbenchClaimedDeliveries,
messageOrderTimeMs,
transcriptWindowsOverlap,
timestampOrderTimeMs,
@@ -21,6 +22,13 @@ const t = (s: number) => `2024-01-01T00:00:${String(s).padStart(2, '0')}Z`;
const mk = (id: string, created_at: string, delivered_at: string | null = null): WorkbenchMessage =>
({ id, created_at, delivered_at }) as unknown as WorkbenchMessage;
const ids = (list: WorkbenchMessage[]): string[] => list.map((m) => m.id);
+const claimed = (id: string, createdAt: string, text = 'pending'): WorkbenchMessage =>
+ ({
+ ...mk(id, createdAt),
+ text,
+ projection: 'claimed_delivery',
+ metadata: {},
+ }) as WorkbenchMessage;
describe('messageOrderTimeMs', () => {
it('recovers subsecond positions from canonical message ids', () => {
@@ -248,6 +256,12 @@ describe('insertMessageOrdered', () => {
expect(insertMessageOrdered(list, mk('c', t(3)))).toBe(list);
});
+ it('replaces a claimed Delivery projection with its materialized live row', () => {
+ const materialized = { ...mk('c', t(3)), text: 'accepted', metadata: {} } as WorkbenchMessage;
+ const next = insertMessageOrdered([claimed('c', t(3))], materialized);
+ expect(next).toEqual([materialized]);
+ });
+
it('binary-inserts an out-of-order arrival at the head', () => {
expect(ids(insertMessageOrdered(base(), mk('0', t(0))))).toEqual(['0', 'a', 'c', 'e']);
});
@@ -276,3 +290,24 @@ describe('insertMessageOrdered', () => {
}
});
});
+
+describe('reconcileWorkbenchClaimedDeliveries', () => {
+ it('replaces accepted projections and removes retired projections', () => {
+ const accepted = { ...mk('accepted', t(2)), text: 'materialized', metadata: {} } as WorkbenchMessage;
+ const existing = [claimed('retired', t(1)), claimed('accepted', t(2)), mk('stable', t(3))];
+
+ const reconciled = reconcileWorkbenchClaimedDeliveries(existing, [accepted]);
+
+ expect(ids(reconciled)).toEqual(['accepted', 'stable']);
+ expect(reconciled[0]).toEqual(accepted);
+ });
+
+ it('does not treat persisted user metadata as a projection marker', () => {
+ const durable = {
+ ...mk('durable', t(1)),
+ metadata: { workbench_claimed_delivery: true },
+ } as WorkbenchMessage;
+
+ expect(reconcileWorkbenchClaimedDeliveries([durable], [])).toEqual([durable]);
+ });
+});
diff --git a/ui/src/lib/transcriptOrder.ts b/ui/src/lib/transcriptOrder.ts
index 13f4711a0..2ddff8248 100644
--- a/ui/src/lib/transcriptOrder.ts
+++ b/ui/src/lib/transcriptOrder.ts
@@ -95,6 +95,9 @@ function mergeReconcileMetadata(
return changed ? { ...existing, metadata } : existing;
}
+export const isWorkbenchClaimedDelivery = (message: WorkbenchMessage): boolean =>
+ message.projection === 'claimed_delivery';
+
/** Merge a fetched anchor window without trimming away the row it is meant to reveal. */
export const mergeAnchorWindow = (
existing: WorkbenchMessage[],
@@ -139,6 +142,7 @@ export const mergeById = (
// untouched, and unseen incoming ids are appended as before.
const patched = existing.map((m) => {
const inc = incomingById.get(m.id);
+ if (inc && isWorkbenchClaimedDelivery(m)) return inc;
if (
inc &&
((m.source_session_id == null && inc.source_session_id != null) ||
@@ -182,7 +186,14 @@ export const insertMessageOrdered = (
existing: WorkbenchMessage[],
msg: WorkbenchMessage,
): WorkbenchMessage[] => {
- if (existing.some((m) => m.id === msg.id)) return existing;
+ const existingIndex = existing.findIndex((m) => m.id === msg.id);
+ if (existingIndex >= 0) {
+ if (!isWorkbenchClaimedDelivery(existing[existingIndex])) return existing;
+ const next = existing.slice();
+ next[existingIndex] = msg;
+ next.sort(byCreatedThenId);
+ return next;
+ }
const n = existing.length;
if (n === 0 || byCreatedThenId(msg, existing[n - 1]) > 0) return [...existing, msg];
let lo = 0;
@@ -196,3 +207,18 @@ export const insertMessageOrdered = (
next.splice(lo, 0, msg);
return next;
};
+
+/** Replace or remove only claimed Delivery projections from an authoritative tail read. */
+export const reconcileWorkbenchClaimedDeliveries = (
+ existing: WorkbenchMessage[],
+ incoming: WorkbenchMessage[],
+): WorkbenchMessage[] => {
+ const incomingById = new Map(incoming.map((message) => [message.id, message]));
+ const reconciled = existing.flatMap((message) => {
+ if (!isWorkbenchClaimedDelivery(message)) return [message];
+ const replacement = incomingById.get(message.id);
+ return replacement ? [replacement] : [];
+ });
+ reconciled.sort(byCreatedThenId);
+ return reconciled;
+};
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bef03e2bb..0622648d3 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -8963,6 +8963,50 @@ def _session_runtime_projection(
return projection
+def _active_unmaterialized_input(conn, session_id: str) -> dict[str, Any] | None:
+ """Project the active claimed Delivery as a temporary transcript row."""
+
+ from storage import message_deliveries
+
+ turn = message_deliveries.active_turn(conn, session_id)
+ if turn is None:
+ return None
+ payload = message_deliveries.claimed_workbench_message_payload(
+ conn,
+ str(turn["id"]),
+ )
+ if payload is None:
+ return None
+ payload = message_deliveries.public_delivery_payload(payload)
+ payload.update(
+ projection="claimed_delivery",
+ delivered_at=turn.get("started_at") or turn.get("created_at"),
+ read_at=None,
+ )
+ return payload
+
+
+def _append_active_input(
+ messages_result: dict[str, Any],
+ active_input: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """Keep a claimed input visible until native acceptance materializes it."""
+
+ if active_input is None:
+ return messages_result
+ current = list(messages_result.get("messages") or [])
+ if any(str(row.get("id") or "") == str(active_input["id"]) for row in current):
+ return messages_result
+ current.append(active_input)
+ current.sort(
+ key=lambda row: (
+ str(row.get("delivered_at") or row.get("created_at") or ""),
+ str(row.get("id") or ""),
+ )
+ )
+ return {**messages_result, "messages": current}
+
+
@app.route("/api/sessions/<session_id>/bootstrap", methods=["GET"])
async def sessions_bootstrap(session_id: str):
"""First-screen payload for the Workbench Chat page.
@@ -9003,6 +9047,10 @@ async def sessions_bootstrap(session_id: str):
authorization_context=authorization_context,
tail=True,
)
+ messages_result = _append_active_input(
+ messages_result,
+ _active_unmaterialized_input(conn, session_id),
+ )
from storage import message_deliveries
queued = (
@@ -9698,6 +9746,13 @@ def sessions_messages_list(session_id: str):
authorization_context=authorization_context,
tail=tail,
)
+ if tail and not any(
+ (after_id, before_id, around_id, around_native_id, around_turn_id, around_run_id)
+ ):
+ result = _append_active_input(
+ result,
+ _active_unmaterialized_input(conn, session_id),
+ )
return jsonify(result)
@@ -11254,6 +11309,8 @@ async def sessions_cancel(session_id: str):
from vibe import internal_client
+ logger.info("Workbench Stop requested for session=%s", session_id)
+
try:
result = await internal_client.cancel_dispatch(session_id)
except internal_client.InternalServerUnavailable as exc:
@@ -11262,6 +11319,13 @@ async def sessions_cancel(session_id: str):
body = result.get("body") or {}
body.setdefault("ok", status == 200)
body.setdefault("recovered_agent_status", False)
+ logger.info(
+ "Workbench Stop settled for session=%s status=%s outcome=%s code=%s",
+ session_id,
+ status,
+ body.get("status"),
+ body.get("code"),
+ )
return jsonify(body), status