The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a send that already landed is not offered again as the draft
Teknium4c333e0d4974
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsxindex 24721b9568e..be663ccd3ef 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx@@ -33,6 +33,18 @@ const composer = vi.hoisted(() => {return { aui: { composer: () => api }, runtime }})+// The stored transcript the owner serves for a session (the REST page the outbox reads on reopen).+const transcript = vi.hoisted(() => ({ rows: new Map<string, unknown[]>() }))++vi.mock('@/api/sessions', async importOriginal => ({+ ...(await importOriginal<object>()),+ getSessionMessages: async (id: string) => ({+ messages: transcript.rows.get(id) ?? [],+ pagination: { limit: 200, offset: 0, order: 'latest' },+ session_id: id+ })+}))+vi.mock('@assistant-ui/react', () => ({useAui: () => composer.aui,useAuiState: (selector: (state: { composer: { text: string } }) => unknown) =>@@ -48,7 +60,9 @@ interface Handles {let handles: Handles// One app page: fresh imports of the composer hooks and stores (as a reload or relaunch gets).-async function openPage(onSubmit: ChatBarProps['onSubmit']) {+// Opening the session resumes it: the owner's snapshot lists its pending admissions (`pending`).+async function openPage(onSubmit: ChatBarProps['onSubmit'], pending: unknown[] = []) {+ const { reconcilePendingSubmissions } = await import('@/store/pending-submissions')const { useComposerDraft } = await import('./use-composer-draft')const { useComposerSubmit } = await import('./use-composer-submit')const { mainComposerScope } = await import('@/store/composer')@@ -95,7 +109,10 @@ async function openPage(onSubmit: ChatBarProps['onSubmit']) {return <div contentEditable data-testid="editor" ref={draft.editorRef} />}- return render(<Page />)+ const page = render(<Page />)+ reconcilePendingSubmissions('stored-B', pending)++ return page}function closeWindow() {@@ -107,9 +124,13 @@ function closeWindow() {afterEach(() => {cleanup()window.localStorage.clear()+ transcript.rows.clear()vi.resetModules()})+const outboxKeys = () =>+ Object.keys(window.localStorage).filter(key => key.startsWith('hermes:composer-outbox:'))+it('a message sent right before the window closes is never lost and never sent twice', async () => {window.localStorage.setItem('hermes:composer-drafts:v3', JSON.stringify({ 'stored-B': 'answered question' }))@@ -145,3 +166,33 @@ it('a message sent right before the window closes is never lost and never sent texpect(reopened.mock.calls[0][0].trim()).toBe('my long question')expect(reopened.mock.calls[0][1]?.submission_id).toBe(firstId)})++it('a send the owner admitted before the window closed is never offered again as the draft', async () => {+ // Admitted and run (its stored user row names it), or admitted and still queued (only the resume+ // snapshot lists it): either way the chat already shows it.+ const landed = {+ queued: (id: string) => ({ pending: [{ admission_id: 'adm-1', input_id: id, status: 'queued', text: 'queued one' }] }),+ ran: (id: string) => ({ row: { content: 'ran one', display_metadata: { submission_id: id }, role: 'user' } })+ }++ for (const [text, owner] of [['ran one', landed.ran], ['queued one', landed.queued]] as const) {+ // Enter, the frame reaches the owner, and the window closes before the ack comes back.+ window.localStorage.setItem('hermes:composer-drafts:v3', JSON.stringify({ 'stored-B': text }))+ const unacked = vi.fn<ChatBarProps['onSubmit']>(() => new Promise<boolean>(() => {}))+ await openPage(unacked)+ act(() => handles.submitDraft())+ const held = owner(unacked.mock.calls[0][1]?.submission_id ?? '')+ closeWindow()++ transcript.rows.set('stored-B', 'row' in held ? [held.row] : [])+ const reopened = vi.fn<ChatBarProps['onSubmit']>(async () => true)+ await openPage(reopened, 'pending' in held ? held.pending : [])+ await waitFor(() => expect(outboxKeys()).toEqual([]))+ await act(async () => {})+ // Shown once (in the chat), never also back in the composer.+ expect(handles.editor()).toBe('')+ expect(reopened).not.toHaveBeenCalled()+ closeWindow()+ window.localStorage.clear()+ }+})diff --git a/apps/desktop/src/store/admitted-submissions.ts b/apps/desktop/src/store/admitted-submissions.tsnew file mode 100644index 00000000000..66cbf316fec--- /dev/null+++ b/apps/desktop/src/store/admitted-submissions.ts@@ -0,0 +1,33 @@+// The input ids (client submission ids) the owner's latest pending snapshot lists per composer+// queue key, as this page saw them. A send the owner admitted but has not run yet (queued behind a+// running turn or an unresolved one) has no stored row, so only this listing shows that it landed.+const listed = new Map<string, Set<string>>()+const waiters = new Set<() => void>()++/** Record one pending snapshot of `key` (called by the pending-submissions reconcile). */+export function noteListedSubmissions(key: string, inputIds: Iterable<string>): void {+ listed.set(key, new Set(inputIds))+ waiters.forEach(wake => wake())+}++/** The ids `key`'s pending snapshot lists, waiting up to `timeoutMs` for this page's first one;+ * `undefined` when none arrived (an owner that sends no snapshot): the caller then knows nothing. */+export function listedSubmissions(key: string, timeoutMs: number): Promise<Set<string> | undefined> {+ const now = listed.get(key)++ if (now) {+ return Promise.resolve(now)+ }++ return new Promise(resolve => {+ const done = () => {+ waiters.delete(wake)+ clearTimeout(timer)+ resolve(listed.get(key))+ }++ const wake = () => void (listed.has(key) && done())+ const timer = setTimeout(done, timeoutMs)+ waiters.add(wake)+ })+}diff --git a/apps/desktop/src/store/composer-outbox-landed.ts b/apps/desktop/src/store/composer-outbox-landed.tsnew file mode 100644index 00000000000..66f9bc817a3--- /dev/null+++ b/apps/desktop/src/store/composer-outbox-landed.ts@@ -0,0 +1,78 @@+import { getSessionMessages } from '@/api/sessions'+import type { SessionMessage } from '@/types/hermes'++import { listedSubmissions } from './admitted-submissions'++// A window can close after the backend admitted a send but before the submit ack came back. Its+// outbox entry then outlives a send that DID land: re-offering it as the draft would show the words+// twice (in the chat and in the composer). The owner stamps the admission's `submission_id` on the+// user row the turn persists (gateway/session_display.py), so the stored transcript answers+// "did it land" for that exact send, never by matching text. A send admitted but not run yet has no+// row: the owner's pending snapshot lists it by the same id instead.++const PAGE = 200+// Pages are read newest first until the send is found or the rows predate it. The margin absorbs+// clock skew between this machine and a remote backend; the page cap bounds a pathological transcript.+const SKEW_MS = 10 * 60_000+const MAX_PAGES = 20+// Opening the session resumes it, and the resume snapshot lists its pending admissions.+const SNAPSHOT_WAIT_MS = 5000++const NEW_SESSION_SCOPE = /^__new__/++function submissionOf(message: SessionMessage): unknown {+ let metadata: unknown = message.display_metadata++ if (typeof metadata === 'string') {+ try {+ metadata = JSON.parse(metadata)+ } catch {+ return undefined+ }+ }++ return metadata && typeof metadata === 'object' ? (metadata as Record<string, unknown>).submission_id : undefined+}++const predates = (message: SessionMessage, sentAt: number) =>+ typeof message.timestamp === 'number' && message.timestamp * 1000 < sentAt - SKEW_MS++/** True only when the owner holds `submissionId` for `scope`: listed pending (read first: an admission+ * that leaves the pending set has persisted its row by then), or its user row stored. No snapshot, a+ * failed read, a scope that is not a stored session yet, or an exhausted search answers false: the+ * entry is then re-offered as the draft, so an unknown outcome can show the words twice but never+ * lose them. */+export async function sendLanded(scope: string, submissionId: string, sentAt?: number): Promise<boolean> {+ if (!scope || NEW_SESSION_SCOPE.test(scope)) {+ return false+ }++ if ((await listedSubmissions(scope, SNAPSHOT_WAIT_MS))?.has(submissionId)) {+ return true+ }++ try {+ for (let page = 0; page < MAX_PAGES; page += 1) {+ const { messages, pagination } = await getSessionMessages(+ scope,+ undefined,+ { includeCompacted: true, limit: PAGE, offset: page * PAGE, order: 'latest' },+ { passive: true }+ )++ if (messages.some(message => message.role === 'user' && submissionOf(message) === submissionId)) {+ return true+ }++ const exhausted = !pagination || messages.length < PAGE++ if (exhausted || (sentAt !== undefined && messages.some(message => predates(message, sentAt)))) {+ return false+ }+ }+ } catch {+ return false+ }++ return false+}diff --git a/apps/desktop/src/store/composer-outbox.ts b/apps/desktop/src/store/composer-outbox.tsindex c866ef571e2..278239606a7 100644--- a/apps/desktop/src/store/composer-outbox.ts+++ b/apps/desktop/src/store/composer-outbox.ts@@ -1,5 +1,6 @@import { freshDraftScope } from './composer'import type { ComposerDraftRetry } from './composer-draft-retry'+import { sendLanded } from './composer-outbox-landed'// Enter clears the composer and hands the words to an async send chain (session resume or create,// attachment sync, the prepared journal) before `prompt.submit` is written. Closing or reloading the@@ -9,12 +10,17 @@ import type { ComposerDraftRetry } from './composer-draft-retry'// path). An entry no live page holds is a send its page never finished: the next load of its draft// scope restores it as the draft with its retry identity, so sending it again is the explicit retry// under the same submission id and the owner never runs it twice. Restored, never re-sent on its-// own: like the prepared journal, this is not an automatic outbox.+// own: like the prepared journal, this is not an automatic outbox. An entry whose send the owner+// already admitted (the window closed after the frame left but before the ack came back) is in the+// owner's pending snapshot or stored transcript under its submission id: it is dropped instead, so+// a send is never both shown and offered again.const PREFIX = 'hermes:composer-outbox:v1:'interface OutboxEntry {scope: stringretry: ComposerDraftRetry+ /** When Enter journaled it (ms): bounds the transcript search for its stored row. */+ at?: number}// Journal keys of sends this page has in flight: key -> release of the Web Lock that marks the@@ -65,8 +71,9 @@ export interface OutgoingSend {/** Journal one send synchronously, before any await of the send chain can be cut by unload. */export function journalOutgoingSend(scope: string | null, retry: ComposerDraftRetry): OutgoingSend {+ const at = Date.now()let key = entryKey(scopeKey(scope), retry.id)- write(key, { scope: scopeKey(scope), retry })+ write(key, { at, scope: scopeKey(scope), retry })hold(key)const release = () => {@@ -84,15 +91,16 @@ export function journalOutgoingSend(scope: string | null, retry: ComposerDraftRerelease()key = entryKey(scopeKey(next), retry.id)- write(key, { scope: scopeKey(next), retry })+ write(key, { at, scope: scopeKey(next), retry })hold(key)},retire: release}}-/** Offer `scope`'s interrupted send (one no live page owns) to `apply`; the entry is removed only- * when `apply` took it, so a composer the user already typed into leaves it for the next load. */+/** Offer `scope`'s interrupted send (one no live page owns) to `apply`; the entry is removed when+ * its send already landed in the stored transcript (silently) or when `apply` took it, so a+ * composer the user already typed into leaves it for the next load. */export async function restoreInterruptedSend(scope: string | null | undefined,apply: (retry: ComposerDraftRetry) => boolean@@ -108,10 +116,16 @@ export async function restoreInterruptedSend(}}- const take = (key: string) => {+ const take = async (key: string) => {const entry = read(key)- if (entry && !ownedHere.has(key) && apply(entry.retry)) {+ if (!entry || ownedHere.has(key)) {+ return+ }++ if (await sendLanded(entry.scope, entry.retry.id, entry.at)) {+ write(key, undefined)+ } else if (read(key) && apply(entry.retry)) {write(key, undefined)}}@@ -120,10 +134,11 @@ export async function restoreInterruptedSend(for (const key of keys.sort()) {if (!available) {- take(key)+ await take(key)} else {- // A held lock is another live window's send still in flight: never adopted from here.- await available.request(lockName(key), { ifAvailable: true }, lock => void (lock && take(key)))+ // A held lock is another live window's send still in flight: never adopted from here. The+ // lock stays held across the transcript read, so two windows never both adopt one entry.+ await available.request(lockName(key), { ifAvailable: true }, lock => (lock ? take(key) : undefined))}}}diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.tsindex 73c7a0d779e..e3c242e2504 100644--- a/apps/desktop/src/store/pending-submissions.ts+++ b/apps/desktop/src/store/pending-submissions.ts@@ -1,3 +1,4 @@+import { noteListedSubmissions } from './admitted-submissions'import { getQueuedPrompts, type QueuedPromptEntry, writeSessionQueue } from './composer-queue'import { $sessions, resolveComposerSessionKey } from './session'@@ -332,6 +333,7 @@ export function reconcilePendingSubmissions(storedId: string, value: unknown, fe// shown there. Receipts journaled under the tip before the lineage was known move along.const key = journalKey(storedId)adoptJournal(storedId, key)+ noteListedSubmissions(key, value.flatMap(raw => (typeof raw?.input_id === 'string' ? [raw.input_id] : [])))const before = readPendingSubmissions(key)const known = { ...before }diff --git a/gateway/response_filters.py b/gateway/response_filters.pyindex d4a00defa2d..d930075a2ed 100644--- a/gateway/response_filters.py+++ b/gateway/response_filters.py@@ -143,6 +143,13 @@ def display_metadata_for_event(event: Any) -> dict:return {**_producer_card(event), **({"title_preview": preview} if preview else {})}+def persisted_user_metadata_for_event(event: Any) -> dict:+ """The user row's display metadata: ``display_metadata_for_event`` plus the canonical admission's+ ``submission_id``, which lets a client match a send whose ack it never received to its stored row."""+ from gateway.session_display import admission_submission+ return {**display_metadata_for_event(event), **admission_submission(event)}++def is_machinery_display_kind(display_kind: Any) -> bool:"""Only a machinery turn may vanish on a bare silence marker; a human turn gets a visible fallback.diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 6da1f61bdb4..991449c2f35 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -26,8 +26,8 @@ from gateway.media_repair import repair_explicit_computer_use_media_pathsfrom gateway.platforms.base import BasePlatformAdapter, ProcessingOutcomefrom gateway.platforms.event import MessageEventfrom gateway.response_filters import (- display_kind_for_event, display_metadata_for_event, is_machinery_display_kind, reply_expected_metadata,- silence_allowed,+ display_kind_for_event, display_metadata_for_event, is_machinery_display_kind, persisted_user_metadata_for_event,+ reply_expected_metadata, silence_allowed,)from gateway.warning_notifications import diagnostic_metadata, diagnostic_turn_muted, diagnostic_wake_mutedfrom gateway.session import (@@ -276,7 +276,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewaypersist_user_display_kind=prepared.persist_user_display_kind,reply_expected=event.reply_expected,persist_user_display_metadata={- "gateway_input_owner": prepared.persistence_owner, **display_metadata_for_event(event),+ "gateway_input_owner": prepared.persistence_owner, **persisted_user_metadata_for_event(event),**reply_expected_metadata(event.reply_expected), **diagnostic_metadata(event)},message_type=event.message_type,scheduled_heartbeat=bool(getattr(event, "_heartbeat_session_id", None)),diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 5bf9866e7f5..962e31e1b8c 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -423,9 +423,9 @@ class GatewayTurnPersistenceMixin:}if prepared.persist_user_display_kind:_user_entry["display_kind"] = prepared.persist_user_display_kind- from gateway.response_filters import display_metadata_for_event+ from gateway.response_filters import persisted_user_metadata_for_eventdisplay_metadata = {**({"gateway_input_owner": prepared.persistence_owner} if prepared.persistence_owner else {}),- **display_metadata_for_event(event)}+ **persisted_user_metadata_for_event(event)}if display_metadata:_user_entry["display_metadata"] = display_metadataif getattr(event, "message_id", None):diff --git a/gateway/session_display.py b/gateway/session_display.pyindex a9e552eabf2..7616ed357f6 100644--- a/gateway/session_display.py+++ b/gateway/session_display.py@@ -15,6 +15,7 @@ HIDDEN = 'hidden'_TITLE_PREVIEW_LIMIT = 1000_SUBMIT_FIELDS = ('display_kind', 'title_preview')_display_turn: ContextVar[tuple | None] = ContextVar('display_turn', default=None)+_submission_turn: ContextVar[tuple | None] = ContextVar('submission_turn', default=None)def submit_display_fields(params):@@ -60,6 +61,27 @@ def display_turn_scope(admission_id, committed):_display_turn.reset(token)+@contextmanager+def submission_turn_scope(admission_id, submission_id):+ """Bind the client's ``submission_id`` (the admission's ``request_id``) to the admission's own event.++ The user row this turn persists carries it, so a client whose window closed before the submit ack+ came back can read the stored transcript and tell a send that landed from one that never did."""+ token = _submission_turn.set((admission_id, submission_id) if submission_id else None)+ try:+ yield+ finally:+ _submission_turn.reset(token)+++def admission_submission(event):+ """``{'submission_id': ...}`` for the admission ``event`` executes, ``{}`` for any other event."""+ bound = _submission_turn.get()+ if bound is None or event is None or getattr(event, 'message_id', None) != bound[0]:+ return {}+ return {'submission_id': bound[1]}++def admission_display(event):"""The committed presentation of the admission ``event`` executes (its ``message_id`` is theadmission id), ``{}`` for any other event: a follow-up on the same task never inherits it."""diff --git a/gateway/session_finite.py b/gateway/session_finite.pyindex 7a2a58456bb..c5071734b79 100644--- a/gateway/session_finite.py+++ b/gateway/session_finite.py@@ -70,11 +70,12 @@ def _may_run_unattended(connection, ref):async def execute_finite_admission(authority, ref, row):from gateway.session_ingress import execute_admission- from gateway.session_display import display_turn_scope+ from gateway.session_display import display_turn_scope, submission_turn_scopefrom gateway.session_surface import surface_turn_scopefrom gateway.session_cli_turn import cli_turn_scopewith finite_turn_scope(row['payload'].get('finite', False), row['payload'].get('unattended') is True), \surface_turn_scope(row['payload'].get('surface_v1')), \display_turn_scope(row['admission_id'], row['payload'].get('display_v1')), \+ submission_turn_scope(row['admission_id'], row.get('request_id')), \cli_turn_scope(row['admission_id'], row['payload'].get('cli_turn_v1')):return await execute_admission(authority, ref, row)diff --git a/tests/gateway/test_submission_row_identity.py b/tests/gateway/test_submission_row_identity.pynew file mode 100644index 00000000000..47803906613--- /dev/null+++ b/tests/gateway/test_submission_row_identity.py@@ -0,0 +1,44 @@+"""The user row a canonical admission persists names the client's ``submission_id``.++A Desktop window that closes after the owner admitted a send but before the ack came back reads the+stored transcript on reopen to tell a send that landed from one that never did (its composer outbox).+"""+from types import SimpleNamespace++import pytest++from tests.gateway.test_surface_admission import _authority+++async def test_the_admitted_turns_user_row_names_its_submission_id(tmp_path, monkeypatch):+ from gateway.run_turn_persistence import GatewayTurnPersistenceMixin+ from gateway.session_controls import AuthorityConnection++ def stored_metadata(event):+ prepared = SimpleNamespace(persist_user_message=None, message_text=event.text, persist_user_timestamp=None,+ persist_user_display_kind=None, persistence_owner=None)+ return GatewayTurnPersistenceMixin._hmwa_user_transcript_entry(event, prepared, 0.0).get('display_metadata', {})++ seen = []+ async def answer(event):+ # A follow-up event on the same task (a /queue chain) is another input: it never inherits the id.+ stray = SimpleNamespace(message_id='other', internal=False, metadata={}, text='stray')+ seen.append((event.text, stored_metadata(event), stored_metadata(stray)))+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ try:+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ for rid, extra in (('send-1', {}), ('send-2', {'title_preview': 'Notes'})):+ reply = await connection.dispatch({'id': 2, 'method': 'prompt.submit', 'params': {+ 'session_id': 's', 'submission_id': rid, 'text': rid, **extra}})+ assert reply.get('result', {}).get('status') == 'queued', reply+ await authority.sessions['s'].task+ finally:+ await connection.close()++ assert seen == [+ ('send-1', {'submission_id': 'send-1'}, {}),+ ('send-2', {'title_preview': 'Notes', 'submission_id': 'send-2'}, {}),+ ]