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(queue): recover stale send-now deliveries (#2086)

Call Whitef8c66911d336
diff --git a/core/session_turns.py b/core/session_turns.py
index 9bea61dda..0a6b8e729 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -2722,7 +2722,30 @@ class SessionTurnManager:
# 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):
+ try:
+ memory_authority_compatible = self._compatible_steer_memory_authority(
+ logical_turn_id,
+ deliveries,
+ )
+ except Exception as exc:
+ # An unavailable optional Memory runtime must not strand a claimed
+ # Delivery in ``steering``. No native write has happened yet, so
+ # this is a definitive refusal and the exact input can safely
+ # return to the retryable FIFO queue.
+ logger.exception(
+ "steering memory-authority check failed before native write for delivery=%s",
+ delivery_id,
+ )
+ return await self._finish_steer(
+ delivery_id,
+ steer_result(
+ SteerOutcome.REFUSED,
+ reason="memory_runtime_unavailable",
+ error_type=type(exc).__name__,
+ ),
+ context=context,
+ )
+ if not memory_authority_compatible:
return await self._finish_steer(
delivery_id, steer_result(SteerOutcome.REFUSED, reason="memory_authority_changed"), context=context
)
diff --git a/docs/plans/2026-09-21-queue-send-feedback.md b/docs/plans/2026-09-21-queue-send-feedback.md
new file mode 100644
index 000000000..8d17123c8
--- /dev/null
+++ b/docs/plans/2026-09-21-queue-send-feedback.md
@@ -0,0 +1,59 @@
+# Queue send-now recovery and feedback
+
+## Contract
+
+- A Memory authority check that fails before a native write returns the exact
+ claimed Delivery to the retryable FIFO queue. It must not replay old input,
+ invoke Stop, or weaken the unknown-write fence.
+- A send-now invocation owns its queue, error, working, and progress updates only
+ until another invocation or session navigation invalidates it. Returning to
+ the same session ID does not restore ownership. A later authoritative Turn
+ event also prevents the request from undoing the current working state.
+- Both rejected transport promises and non-success HTTP responses reconcile the
+ authoritative queue before selecting failure feedback. Retry feedback requires
+ the exact clicked Delivery to remain present and unfenced. An absent, fenced,
+ unreadable, or superseded snapshot gets neutral, localized feedback.
+- Raw controller/socket details remain diagnostics, never user-facing copy.
+ No automatic retry or synthetic Message is introduced.
+
+## Review circuit-breaker diagnosis
+
+The complete GitHub inventory for PR #2086 was checked on 2026-09-21, including
+resolved/outdated threads. Two distinct heads have findings:
+
+| Root-cause class | `814261de3a` | `a4379a743b` |
+| --- | --- | --- |
+| Async request ownership | #4059515552: recheck after awaited refresh | #4059672447: invalidate across A → B → A |
+| Retry feedback without delivery evidence | #4059515553: transport ambiguity | #4059672451: stale-head HTTP response |
+| Localized failure boundary | #4059515557: raw controller detail | No new finding |
+
+The first two classes repeat across two reviewed heads, so further patching was
+paused for a full boundary review. The orchestrator inspected the previous fix,
+its A → B consuming test, the session-reset effect, queue snapshot ordering,
+`ApiContext.sendQueuedNow`, and the controller FIFO admission refusals.
+
+Diagnosis: the first repair guarded post-refresh writes but never invalidated
+the invocation on navigation. It also applied evidence-based feedback only to
+thrown requests, although `handleError: false` returns HTTP failures as values.
+Queue membership alone is insufficient when the same row is still held behind
+a native-write fence.
+
+Scope decision: retain the existing invocation generation and queue-read ordering.
+Advance the invocation generation in the session-reset lifecycle and share one
+failure-reconciliation path for HTTP and transport errors. Reuse the queue's
+existing fenced-state predicate. No database, backend admission, API-shape, or
+runtime deployment change is required for this review repair. The existing Turn
+epoch protects working-state rollback while the queue refresh is pending.
+
+## Validation and delivery
+
+- Component tests exercise A → B and A → B → A during both send and refresh,
+ preserve a newer invocation's spinner, and cover HTTP/transport failures with
+ retryable, fenced, absent, and unreadable queue snapshots.
+- Run the focused ChatPage suite, changed-file lint, UI build/test typechecks,
+ and relevant hermetic browser queue tests.
+- Retain the backend pre-write failure regression and existing FIFO/no-Stop
+ behavior; do not infer deployed or live-model acceptance from hermetic tests.
+- Keep the original PR Watch/cursor. Require automatic exact-head Codex review,
+ complete current-head CI, and zero unresolved threads before readiness.
+ Merge, installation, and regression updates remain separately authorized.
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 055cdabd7..9d18d4336 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -9,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, closing
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
from sqlalchemy import select, update
@@ -1283,6 +1283,32 @@ async def test_steering_preparation_failure_preserves_a_definitively_unwritten_b
assert all(_row(engine, row["id"])["state"] == "accepted" for row in queued)
+async def test_steering_memory_check_failure_restores_a_retryable_queue_row(managers):
+ manager, _other, engine, _engine_b, _starts = managers
+ await _activate(manager, text="active")
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ manager._compatible_steer_memory_authority = Mock(
+ side_effect=ModuleNotFoundError("avibe_memory")
+ )
+
+ result = await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content="retry after memory recovery",
+ ),
+ context=_context(),
+ )
+
+ assert result.state == "queued"
+ manager._steer.assert_not_awaited()
+ queued = [row for row in _rows(engine) if row["state"] == "queued"]
+ assert len(queued) == 1
+ assert queued[0]["dispatch_text"] == "retry after memory recovery"
+ assert queued[0]["current_attempt_id"] is None
+
+
def test_persisted_start_attempt_reaches_dispatch_context(managers) -> None:
manager, _other, engine, _engine_b, _starts = managers
captured: dict[str, object] = {}
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 232109ba3..2528d8f8d 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -296,6 +296,273 @@ describe('ChatPage transcript hydration', () => {
expect(mocks.api.cancelSession).not.toHaveBeenCalled();
});
+ it('refreshes a stale queue snapshot after send-now transport failure', async () => {
+ const queued = {
+ ...queuedMessage('stale-queued-row', 'stale queued row'),
+ state: 'queued' as const,
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ queued: [queued],
+ turn_state: running,
+ });
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionQueue.mockResolvedValue({ queued: [] });
+ mocks.api.sendQueuedNow.mockRejectedValue(new Error('socket unavailable'));
+
+ 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' });
+ expect(screen.getByText(queued.text)).toBeTruthy();
+ fireEvent.click(button);
+
+ await screen.findByText('chat.queue.sendStatusUnknown');
+ await waitFor(() => expect(screen.queryByText(queued.text)).toBeNull());
+ expect(mocks.api.listSessionQueue).toHaveBeenCalledWith('session-new', { cache: false });
+ expect(screen.queryByText('chat.stopFailed')).toBeNull();
+ });
+
+ it('does not overwrite a newer chat after a stale send-now refresh finishes', async () => {
+ const queued = {
+ ...queuedMessage('stale-send-row', 'stale send row'),
+ state: 'queued' as const,
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ const queueRefresh = deferred<{ queued: (typeof queued)[] }>();
+ let holdQueueRefresh = false;
+ mocks.api.getSession.mockImplementation((id: string) => Promise.resolve({ id }));
+ mocks.api.getSessionBootstrap.mockImplementation((id: string) => Promise.resolve({
+ ...bootstrapPayload(id),
+ queued: id === 'session-new' ? [queued] : [],
+ turn_state: id === 'session-new' ? running : idleTurnState,
+ }));
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionQueue.mockImplementation((id: string) => {
+ if (id === 'session-new' && holdQueueRefresh) return queueRefresh.promise;
+ return Promise.resolve({ queued: id === 'session-new' ? [queued] : [] });
+ });
+ mocks.api.sendQueuedNow.mockImplementation(async () => {
+ holdQueueRefresh = true;
+ throw new Error('socket unavailable');
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route
+ path="/chat/:sessionId"
+ element={(
+ <>
+ <SessionSwitcher sessionId="session-other" />
+ <ChatPage />
+ </>
+ )}
+ />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chat.queue.sendNow' }));
+ await waitFor(() => expect(mocks.api.sendQueuedNow).toHaveBeenCalledWith('session-new', 'stale-send-row'));
+ fireEvent.click(screen.getByRole('button', { name: 'switch chat' }));
+ await act(async () => queueRefresh.resolve({ queued: [] }));
+
+ await waitFor(() => expect(screen.queryByText('chat.queue.sendStatusUnknown')).toBeNull());
+ expect(screen.queryByText('chat.queue.sendFailed')).toBeNull();
+ });
+
+ it.each(
+ ['rejected send', 'refused send', 'accepted send', 'rejected refresh', 'refused refresh']
+ .flatMap((phase) => [false, true].map((newerSend) => ({ phase, newerSend }))),
+ )('does not revive a stale $phase after A → B → A (new send: $newerSend)', async ({ phase, newerSend }) => {
+ const queued = {
+ ...queuedMessage('stale-return-row', 'stale return row'),
+ state: 'queued' as const,
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ const send = deferred<{ ok: boolean; code?: string; status?: string }>();
+ const nextSend = deferred<{ ok: boolean; status: string }>();
+ const queueRefresh = deferred<{ queued: (typeof queued)[] }>();
+ const settleSend = () => {
+ if (phase.startsWith('rejected')) send.reject(new Error('socket unavailable'));
+ else if (phase.startsWith('refused')) send.resolve({ ok: false, code: 'stale_head' });
+ else send.resolve({ ok: true, status: 'accepted' });
+ };
+ mocks.api.getSession.mockImplementation((id: string) => Promise.resolve({ id }));
+ mocks.api.getSessionBootstrap.mockImplementation((id: string) => Promise.resolve({
+ ...bootstrapPayload(id),
+ queued: id === 'session-new' ? [queued] : [],
+ turn_state: running,
+ }));
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionQueue.mockReturnValue(queueRefresh.promise);
+ mocks.api.sendQueuedNow.mockReturnValueOnce(send.promise).mockReturnValue(nextSend.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route
+ path="/chat/:sessionId"
+ element={(
+ <>
+ <SessionSwitcher sessionId="session-other" />
+ <SessionSwitcher sessionId="session-new" label="return chat" />
+ <ChatPage />
+ </>
+ )}
+ />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chat.queue.sendNow' }));
+ await waitFor(() => expect(mocks.api.sendQueuedNow).toHaveBeenCalledWith('session-new', 'stale-return-row'));
+ if (phase.endsWith('refresh')) {
+ await act(async () => settleSend());
+ await waitFor(() => expect(mocks.api.listSessionQueue).toHaveBeenCalledTimes(1));
+ }
+ fireEvent.click(screen.getByRole('button', { name: 'switch chat' }));
+ await waitFor(() => expect(mocks.composer?.sessionId).toBe('session-other'));
+ expect(screen.queryByText(queued.text)).toBeNull();
+ fireEvent.click(await screen.findByRole('button', { name: 'return chat' }));
+ await screen.findByText(queued.text);
+ if (newerSend) fireEvent.click(screen.getByRole('button', { name: 'chat.queue.sendNow' }));
+ if (phase.endsWith('send')) await act(async () => settleSend());
+ await act(async () => queueRefresh.resolve({ queued: [] }));
+
+ expect(screen.queryByText('chat.queue.sendStatusUnknown')).toBeNull();
+ expect(screen.queryByText('chat.queue.sendFailed')).toBeNull();
+ expect(screen.getByText(queued.text)).toBeTruthy();
+ expect(mocks.composer?.busy).toBe(true);
+ const button = screen.getByRole('button', {
+ name: newerSend ? 'chat.queue.sendingNow' : 'chat.queue.sendNow',
+ }) as HTMLButtonElement;
+ expect(button.disabled).toBe(newerSend);
+ expect(mocks.api.listSessionQueue).toHaveBeenCalledTimes(phase.endsWith('refresh') ? 1 : 0);
+ expect(mocks.api.cancelSession).not.toHaveBeenCalled();
+ if (newerSend) {
+ await act(async () => nextSend.resolve({ ok: true, status: 'accepted' }));
+ expect(screen.queryByRole('button', { name: 'chat.queue.sendingNow' })).toBeNull();
+ }
+ });
+
+ it.each(
+ ['transport', 'stale_head', 'internal_unavailable', 'ordering_fence', 'stop_failed'].flatMap((failure) =>
+ ['queued', 'gone', 'unreadable', 'superseded', 'pending_steer', 'steering', 'reconciling_steer'].map((state) => ({
+ failure, state,
+ })),
+ ),
+ )('reconciles $failure against an exact row that is $state', async ({ failure, state }) => {
+ const queued = {
+ ...queuedMessage('stale-head-row', 'stale head row'),
+ state: 'queued',
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ const otherRow = { ...queued, id: 'another-row', text: 'another queued message' };
+ const queueRefresh = deferred<{ queued: (typeof queued)[] }>();
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ queued: [queued],
+ turn_state: running,
+ });
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionQueue.mockReturnValue(queueRefresh.promise);
+ mocks.api.sendQueuedNow.mockImplementation(async () => {
+ if (failure === 'transport') throw new Error('controller socket unavailable');
+ return { ok: false, code: failure, detail: 'controller socket unavailable' };
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes><Route path="/chat/:sessionId" element={<ChatPage />} /></Routes>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chat.queue.sendNow' }));
+
+ await waitFor(() => expect(mocks.api.listSessionQueue).toHaveBeenCalledTimes(1));
+ // Never flash retry advice before the reconciliation evidence arrives.
+ expect(screen.queryByText('chat.queue.sendFailed')).toBeNull();
+ if (state === 'superseded') {
+ mocks.api.listSessionQueue.mockResolvedValue({ queued: [otherRow] });
+ act(() => {
+ mocks.events?.onTurnStart({ session_id: 'session-new' });
+ mocks.events?.onQueueUpdated({ session_id: 'session-new' });
+ });
+ await screen.findByText(otherRow.text);
+ expect(screen.queryByText(queued.text)).toBeNull();
+ }
+ await act(async () => {
+ if (state === 'unreadable') queueRefresh.reject(new Error('queue unavailable'));
+ else queueRefresh.resolve({
+ queued: state === 'gone' ? [otherRow] : [
+ { ...queued, state: state === 'superseded' ? 'queued' : state }, otherRow,
+ ],
+ });
+ });
+ const expectedNotice = state === 'queued' ? 'chat.queue.sendFailed' : 'chat.queue.sendStatusUnknown';
+ await screen.findByText(expectedNotice);
+ expect(screen.queryByText('controller socket unavailable')).toBeNull();
+ if (state !== 'queued') expect(screen.queryByText('chat.queue.sendFailed')).toBeNull();
+ if (state === 'gone' || state === 'superseded') {
+ expect(screen.queryByText(queued.text)).toBeNull();
+ expect(screen.getByText(otherRow.text)).toBeTruthy();
+ } else {
+ expect(screen.getByText(queued.text)).toBeTruthy();
+ }
+ if (['pending_steer', 'steering', 'reconciling_steer'].includes(state)) {
+ const name = state === 'reconciling_steer' ? 'chat.queue.confirmingNow' : 'chat.queue.sendingNow';
+ expect((screen.getByRole('button', { name }) as HTMLButtonElement).disabled).toBe(true);
+ // The server's fence remains authoritative, but the HTTP invocation's
+ // spinner must already be released once that fence settles.
+ mocks.api.listSessionQueue.mockResolvedValue({ queued: [queued, otherRow] });
+ act(() => mocks.events?.onQueueUpdated({ session_id: 'session-new' }));
+ }
+ const retryButton = await screen.findByRole('button', { name: 'chat.queue.sendNow' });
+ expect((retryButton as HTMLButtonElement).disabled).toBe(false);
+ expect(mocks.composer?.busy).toBe(failure === 'stop_failed' || state === 'superseded');
+ expect(mocks.api.sendQueuedNow).toHaveBeenCalledTimes(1);
+ expect(mocks.api.cancelSession).not.toHaveBeenCalled();
+ });
+
+ it('does not present send-now refusal as a stop failure', async () => {
+ const queued = {
+ ...queuedMessage('refused-queued-row', 'refused queued row'),
+ state: 'queued' as const,
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ queued: [queued],
+ turn_state: running,
+ });
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionQueue.mockResolvedValue({ queued: [queued] });
+ mocks.api.sendQueuedNow.mockResolvedValue({
+ ok: false,
+ code: 'internal_unavailable',
+ detail: 'controller socket unavailable',
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes><Route path="/chat/:sessionId" element={<ChatPage />} /></Routes>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chat.queue.sendNow' }));
+
+ await screen.findByText('chat.queue.sendFailed');
+ expect(screen.queryByText('chat.stopFailed')).toBeNull();
+ expect(screen.queryByText('controller socket unavailable')).toBeNull();
+ expect(screen.getByText(queued.text)).toBeTruthy();
+ });
+
it.each(['accepted', 'queued'])('restores a confirming image on reload and follows $status settlement', async (settlement) => {
const image = {
...queuedMessage('queued-image', ''),
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 266749f09..ddcad1a41 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1281,16 +1281,19 @@ export const ChatPage: React.FC = () => {
// The send-while-busy queue (pending messages shown above the composer).
// Re-fetched on mount + on every ``queue.updated`` (enqueue / flush / remove).
const refreshQueue = useCallback(async (isCurrentRequest?: () => boolean) => {
- if (!sessionId) return;
+ if (!sessionId) return null;
const claimQueueSnapshot = beginQueueSnapshotRead(sessionId);
try {
const res = await api.listSessionQueue(sessionId, { cache: false });
- if (isCurrentRequest && !isCurrentRequest()) return;
- if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
- if (!claimQueueSnapshot()) return;
- setQueue(res.queued ?? []);
+ if (isCurrentRequest && !isCurrentRequest()) return null;
+ if (sessionId !== sessionIdRef.current) return null; // switched chats mid-fetch
+ if (!claimQueueSnapshot()) return null;
+ const queued = res.queued ?? [];
+ setQueue(queued);
+ return queued;
} catch {
/* leave the last-known queue; the next queue.updated refetches */
+ return null;
}
}, [api, beginQueueSnapshotRead, sessionId]);
@@ -1591,6 +1594,8 @@ export const ChatPage: React.FC = () => {
// and the merge in ``refresh`` only ever unions same-session rows.
useEffect(() => {
bootstrapRequestGenerationRef.current += 1;
+ // Returning to the same session must not revive an earlier send's ownership.
+ queueSendGenerationRef.current += 1;
turnEpochRef.current += 1;
// The gate is session-scoped. A PATCH for the previous chat may still be
// pending after navigation, but it must never hold the new chat's bootstrap
@@ -2337,21 +2342,36 @@ export const ChatPage: React.FC = () => {
// 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).
+ const messageId = queue[0].id;
+ // Reflect admission immediately, but only undo this optimistic working
+ // state if no newer authoritative Turn event has arrived in the meantime.
markWorking();
+ const turnEpochAtSend = turnEpochRef.current;
+ const reconcileFailure = async (keepWorking = false) => {
+ const refreshedQueue = await refreshQueue(isCurrentRequest);
+ if (!isCurrentRequest()) return;
+ if (!keepWorking && turnEpochAtSend === turnEpochRef.current) setWorking(false);
+ // HTTP refusals and transport failures have the same evidence boundary:
+ // retry advice is safe only for this exact, still-unfenced Delivery.
+ // A gone/fenced row or an unreadable/superseded snapshot is ambiguous.
+ const retryable = refreshedQueue?.some(
+ (item) => item.id === messageId && !isQueueDeliveryFenced(item),
+ ) ?? false;
+ setError(t(retryable ? 'chat.queue.sendFailed' : 'chat.queue.sendStatusUnknown'));
+ };
try {
- const res = await api.sendQueuedNow(sid, queue[0].id);
+ const res = await api.sendQueuedNow(sid, messageId);
// Drop every effect from a request that lost ownership while it was in
// flight, including responses that arrive after a newer send starts.
if (!isCurrentRequest()) return;
if (res && res.ok === false) {
// stop_failed: the controller left the ORIGINAL turn running and the
- // queue intact — keep Stop visible so the user can still interrupt it
- // (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'));
+ // queue intact — preserve the existing Stop visibility behavior.
+ // Response detail is a transport/controller diagnostic, not
+ // user-facing copy. Reconcile even HTTP failures such as stale_head:
+ // another tab may already have sent the clicked Delivery.
+ await reconcileFailure(res.code === 'stop_failed');
+ return;
} else if (res?.status === 'queued') {
setError(t(res.reason === 'attachments_unavailable'
? 'chat.queue.attachmentsUnavailable'
@@ -2359,19 +2379,18 @@ export const ChatPage: React.FC = () => {
} 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);
+ if (turnEpochAtSend === turnEpochRef.current) setWorking(false);
} else {
// A successful admission may only claim the compatible prefix.
// Re-read the authoritative queue instead of assuming the whole visible
// batch was flushed.
}
await refreshQueue(isCurrentRequest);
- } catch (err) {
+ } catch {
// The same ownership guard applies to failures: an older request must not
// clear the new chat's working state or surface a stale error.
if (isCurrentRequest()) {
- setWorking(false);
- setError(errorMessage(err) ?? String(err));
+ await reconcileFailure();
}
} finally {
if (isCurrentRequest()) {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 98d705e12..28c2d408a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4337,6 +4337,8 @@
"sendNow": "Send now",
"sendingNow": "Sending…",
"confirmingNow": "Send status not confirmed",
+ "sendFailed": "Couldn't send this message right now. Please try again.",
+ "sendStatusUnknown": "We couldn't confirm whether this message was sent. Check the conversation and queue to avoid sending it twice.",
"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": "We couldn't confirm whether this message was sent. It is kept here, and Avibe won't send it again. Refresh to check the latest status.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 334221507..b6f8f7a47 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4337,6 +4337,8 @@
"sendNow": "立即发送",
"sendingNow": "发送中…",
"confirmingNow": "发送状态未确认",
+ "sendFailed": "暂时无法发送这条消息,请稍后重试。",
+ "sendStatusUnknown": "暂时无法确认发送结果,请先查看会话记录和队列,避免重复发送。",
"sendDeferred": "暂时无法发送到当前任务,消息仍保留在队列中。",
"attachmentsUnavailable": "部分附件已不可用,原消息仍保留在队列中。请重新上传附件后再发送。",
"sendReconciling": "暂时无法确认这条消息是否发送成功。消息已保留,系统不会重复发送;请刷新页面查看最新状态。",