The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): reuse a retained submission identity only on an explicit retry
Tekniume59eef2c069d
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.tsindex cb7dea22ffa..5923adb34b9 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts@@ -25,6 +25,13 @@ import {stashSessionDraft,takeSessionDraft} from '@/store/composer'+import {+ type ComposerDraftRetry,+ draftRetryTextMatches,+ matchingDraftRetry,+ readDraftRetry,+ writeDraftRetry+} from '@/store/composer-draft-retry'import { isBrowsingHistory } from '@/store/composer-input-history'import { $composerPopout } from '@/store/composer-popout'import { clearDraftSuggestions, sampleComposerDraft } from '@/store/composer-suggestions'@@ -122,6 +129,8 @@ export function useComposerDraft({const editorRef = useRef<HTMLDivElement | null>(null)const draftRef = useRef('')+ // The uncertain send this draft was restored from, while the text is still exactly that send.+ const draftRetryRef = useRef<ComposerDraftRetry | undefined>(undefined)const pendingDraftPersistRef = useRef<{ scope: string | null; text: string } | null>(null)const draftPersistTimerRef = useRef<number | undefined>(undefined)const activeQueueSessionKeyRef = useRef(activeQueueSessionKey)@@ -302,6 +311,32 @@ export function useComposerDraft({const stashAt = (scope: string | null, text = draftRef.current, attachments = attachmentScope.$attachments.get()) =>stashSessionDraft(scope, text, attachments)+ const sameDraftScope = (a: string | null | undefined, b: string | null | undefined) =>+ (isFreshDraftScope(a) || !a ? null : a) === (isFreshDraftScope(b) || !b ? null : b)++ // A rejected or unconfirmed send is restored with its identity, so Enter on that exact draft is+ // the explicit retry. Recorded per draft scope (it survives a reload with the draft text).+ const rememberDraftRetry = (scope: string | null, retry: ComposerDraftRetry) => {+ writeDraftRetry(scope, retry)++ if (sameDraftScope(scope, draftScopeRef.current)) {+ draftRetryRef.current = retry+ }+ }++ // The identity a send of exactly this draft retries, if any. Spent by the send either way: a+ // rejection restores it again, and an accepted send leaves nothing to retry.+ const takeDraftRetry = (text: string, attachments: ComposerAttachment[]) => {+ const retry = matchingDraftRetry(draftRetryRef.current, text, attachments)+ draftRetryRef.current = undefined++ if (retry) {+ writeDraftRetry(draftScopeRef.current, undefined)+ }++ return retry+ }+// Draft read/write bus (plugin SDK `host.composer`): answer for the sessions// this composer owns — the runtime id, the queue/stored key (tiles run with// sessionId = their stored id; the primary's queue key is the resolved@@ -438,6 +473,13 @@ export function useComposerDraft({}const scope = draftScopeRef.current++ // An edited (or cleared) restored draft is a new message: it no longer retries the old send.+ if (draftRetryRef.current && !draftRetryTextMatches(draftRetryRef.current, text)) {+ draftRetryRef.current = undefined+ writeDraftRetry(scope, undefined)+ }+const entry = { scope, text }pendingDraftPersistRef.current = entrywindow.clearTimeout(draftPersistTimerRef.current)@@ -551,6 +593,7 @@ export function useComposerDraft({}draftScopeRef.current = activeQueueSessionKey+ draftRetryRef.current = readDraftRetry(activeQueueSessionKey)const { attachments, text } = takeSessionDraft(activeQueueSessionKey)loadIntoComposer(text, attachments, true)@@ -588,6 +631,7 @@ export function useComposerDraft({}reloadPersistedDrafts()+ draftRetryRef.current = readDraftRetry(draftScopeRef.current)const stashed = takeSessionDraft(draftScopeRef.current)loadIntoComposer(stashed.text, stashed.attachments)}@@ -643,10 +687,12 @@ export function useComposerDraft({isHelpHint,isSteerableText,loadIntoComposer,+ rememberDraftRetry,requestMainFocus,sessionIdRef,setComposerText,stashAt,- syncDraftFromEditor+ syncDraftFromEditor,+ takeDraftRetry}}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.restore-scoping.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.restore-scoping.test.tsxindex 4c643d500dd..b43a453ce92 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.restore-scoping.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.restore-scoping.test.tsx@@ -352,6 +352,7 @@ it('restores text and attachments by the loaded draft owner, not an uncommittedconst rendered = seed({ onSubmit })act(() => handles.submit.submitDraft())expect(onSubmit).toHaveBeenCalledWith(expect.stringContaining('draft B'), {+ submission_id: expect.any(String),attachments: [attachmentB],composerScope: 'stored-B'})@@ -389,6 +390,7 @@ it('restores text and attachments by the loaded draft owner, not an uncommittedonSubmit.mockResolvedValueOnce(false)await act(async () => handles.submit.submitDraft())expect(onSubmit).toHaveBeenLastCalledWith(expect.stringContaining('draft B'), {+ submission_id: expect.any(String),attachments: [attachmentB],composerScope: 'stored-B'})@@ -535,3 +537,60 @@ it('sends the first prompt of a chat keyed by its per-lifecycle fresh-draft scop])expect(route).toBe('stored-B')})++// N7: the owner deduplicates by submission identity (`admit_session_input` replays the+// terminal row). Only an explicit retry of the restored draft may reuse an uncertain send's+// identity; a new message with the same text is a new turn, and a reload keeps the retry.+it('a new identical message never adopts an unconfirmed send; the restored draft retries it exactly', async () => {+ const admitted = new Set<string>()+ let loseAck = true+ vi.mocked(requestGatewayForProfile).mockImplementation(async (_profile, method, params) => {+ if (method !== 'prompt.submit') { throw new Error(`unexpected ${method}`) }+ const id = String((params as Record<string, unknown>).submission_id)+ const replay = admitted.has(id)+ admitted.add(id)++ if (loseAck) {+ loseAck = false+ throw new Error('connection closed')+ }++ return { admission_id: id, status: replay ? 'terminal' : 'started' }+ })+ const ids = () => vi.mocked(requestGatewayForProfile).mock.calls.map(([, , params]) => String((params as Record<string, unknown>).submission_id))+ stashSessionDraft('stored-B', 'continue', [])+ seed()++ // The ACK is lost (the turn may have run): the draft comes back for the user to decide.+ act(() => handles.submit.submitDraft())+ await waitFor(() => expect(editorText()).toBe('continue'))+ expect(ids()).toHaveLength(1)++ // Typing the same words anew is a new message: a fresh identity, so a turn really runs.+ act(() => {+ composer.aui.composer().setText('')+ composer.aui.composer().setText('continue')+ })+ await act(async () => handles.submit.submitDraft())+ await waitFor(() => expect(ids()).toHaveLength(2))+ expect(ids()[1]).not.toBe(ids()[0])++ // A restored draft, unchanged across a renderer reload, is the explicit retry: the same+ // identity, so the owner replays instead of running it twice. (Session A: B is now busy.)+ cleanup()+ loseAck = true+ stashSessionDraft('stored-A', 'retry me', [])+ seed({}, null)+ act(() => navigate('A'))+ act(() => handles.submit.submitDraft())+ await waitFor(() => expect(ids()).toHaveLength(3))+ await waitFor(() => expect(editorText()).toBe('retry me'))+ flushDraft()+ cleanup()+ seed({}, null)+ act(() => navigate('A'))+ await waitFor(() => expect(editorText()).toBe('retry me'))+ await act(async () => handles.submit.submitDraft())+ await waitFor(() => expect(ids()).toHaveLength(4))+ expect(ids()[3]).toBe(ids()[2])+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsxindex df6ea7a7b53..7526a4d0df5 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx@@ -240,6 +240,7 @@ describe('useComposerSubmit external request routing', () => {})expect(onSubmit).toHaveBeenCalledExactlyOnceWith('[setup] links opened', {+ submission_id: expect.any(String),composerScope: 'stored-session',displayKind: 'hidden'})@@ -264,6 +265,7 @@ describe('useComposerSubmit external request routing', () => {await waitFor(() =>expect(visibleMain.onSubmit).toHaveBeenCalledWith('ship this branch', {+ submission_id: expect.any(String),composerScope: 'session-a'}))@@ -281,6 +283,7 @@ describe('useComposerSubmit external request routing', () => {await waitFor(() =>expect(tile.onSubmit).toHaveBeenCalledWith('ship project B', {+ submission_id: expect.any(String),composerScope: 'tile-session'}))@@ -295,6 +298,7 @@ describe('useComposerSubmit external request routing', () => {await waitFor(() =>expect(second.onSubmit).toHaveBeenCalledWith('ship exactly one session', {+ submission_id: expect.any(String),composerScope: 'session-second'}))@@ -313,6 +317,7 @@ describe('useComposerSubmit external request routing', () => {await waitFor(() =>expect(visibleB.onSubmit).toHaveBeenCalledWith('ship session B', {+ submission_id: expect.any(String),composerScope: 'session-b'}))@@ -458,7 +463,7 @@ describe('useComposerSubmit busy-turn routing', () => {})await waitFor(() =>- expect(onSubmit).toHaveBeenCalledWith('/compress preserve context', { composerScope: 'stored-session' })+ expect(onSubmit).toHaveBeenCalledWith('/compress preserve context', { submission_id: expect.any(String), composerScope: 'stored-session' }))expect(clearDraft).toHaveBeenCalledTimes(1)expect(onSteer).not.toHaveBeenCalled()@@ -507,6 +512,7 @@ describe('useComposerSubmit busy-turn routing', () => {await waitFor(() =>expect(onSubmit).toHaveBeenCalledWith('ordinary question', {+ submission_id: expect.any(String),attachments: [],composerScope: 'stored-session'})@@ -541,6 +547,7 @@ describe('useComposerSubmit busy-turn routing', () => {await waitFor(() =>expect(onSubmit).toHaveBeenCalledWith('look at @terminal:`zsh:23-58`', {+ submission_id: expect.any(String),attachments: [],composerScope: 'stored-session'})@@ -846,7 +853,7 @@ describe('useComposerSubmit with a blocking prompt parked on the session', () =>hook.result.current.submitDraft()})- await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('/status', { composerScope: 'stored-session' }))+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('/status', { submission_id: expect.any(String), composerScope: 'stored-session' }))expect(queueCurrentDraft).not.toHaveBeenCalled()expect(onSteer).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex 9e6a174a6ef..9a10b830b9a 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@ -14,6 +14,7 @@ import {freezeComposerTransportPayload,isFreshDraftScope} from '@/store/composer'+import { type ComposerDraftRetry, draftRetry } from '@/store/composer-draft-retry'import { resetBrowseState } from '@/store/composer-input-history'import { enqueueQueuedPrompt, type QueuedPromptEntry, serverOwnsComposerQueue } from '@/store/composer-queue'import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'@@ -53,6 +54,9 @@ interface UseComposerSubmitArgs {sessionId: string | null | undefinedsetComposerText: (value: string) => voidstashAt: (scope: string | null, text?: string, attachments?: ComposerAttachment[]) => void+ /** Restored-send identity (see use-composer-draft); absent = every send is a new message. */+ rememberDraftRetry?: (scope: string | null, retry: ComposerDraftRetry) => void+ takeDraftRetry?: (text: string, attachments: ComposerAttachment[]) => ComposerDraftRetry | undefined}/**@@ -89,7 +93,9 @@ export function useComposerSubmit({queuedPrompts,sessionId,setComposerText,- stashAt+ stashAt,+ rememberDraftRetry,+ takeDraftRetry}: UseComposerSubmitArgs) {const paneVisible = usePaneVisible()const scope = useComposerScope()@@ -129,8 +135,15 @@ export function useComposerSubmit({}: {}+ // The composer owns this send's identity: the caller's (a queue entry), the restored draft's+ // (the explicit retry), else a new one. Equal text never inherits an identity, so a new+ // message that repeats an uncertain send, in this pane or another, is its own turn.+ const submissionId = target?.submission_id ?? crypto.randomUUID()+const restore = () => {stashAt(restoreScope, text, submittedAttachments)+ // Restored with its identity: Enter on this exact draft retries the same send.+ rememberDraftRetry?.(restoreScope, draftRetry(submissionId, text, submittedAttachments))if ((isFreshDraftScope(draftScopeRef.current) ? null : draftScopeRef.current) === restoreScope) {loadIntoComposer(text, submittedAttachments)@@ -144,6 +157,7 @@ export function useComposerSubmit({void Promise.resolve(onSubmit(text, {...target,+ submission_id: submissionId,...(attachments ? { attachments } : {}),composerScope: submittedScope,...assignment,@@ -254,9 +268,10 @@ export function useComposerSubmit({return false}+ const retry = takeDraftRetry?.(text, [])triggerHaptic('submit')clearDraft()- dispatchSubmit(text)+ dispatchSubmit(text, undefined, undefined, retry && { submission_id: retry.id })} else if (!blockingPrompt && !attachments.length && text.trim()) {// Busy Send follows the backend busy-input policy: interrupt redirects// the live turn (Cursor-style stop-and-correct), steer injects at the@@ -387,13 +402,14 @@ export function useComposerSubmit({void drainNextQueued()} else if (payloadPresent) {const submittedAttachments = cloneAttachments(attachments)+ const retry = takeDraftRetry?.(text, submittedAttachments)triggerHaptic('submit')resetBrowseState(sessionId)clearDraft()// Keep blob: previews alive for the optimistic bubble; revoke when that// consumer is discarded/replaced (not here — clear would race the clone).scope.attachments.clear({ retainPreviewUrls: true })- dispatchSubmit(text, submittedAttachments)+ dispatchSubmit(text, submittedAttachments, undefined, retry && { submission_id: retry.id })}focusInput()diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex 0032ce6ed73..6b94cecc843 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -28,6 +28,7 @@ import { isMacPlatform } from '@/lib/platform'import { useStoreSelector, useStoresSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'import { sessionCompacting } from '@/store/compaction'+import { draftRetry } from '@/store/composer-draft-retry'import { browseBackward, browseForward, deriveUserHistory, isBrowsingHistory } from '@/store/composer-input-history'import { POPOUT_WIDTH_REM } from '@/store/composer-popout'import { parkQueuedPrompts } from '@/store/composer-queue'@@ -290,11 +291,13 @@ export function ChatBar({isHelpHint,isSteerableText,loadIntoComposer,+ rememberDraftRetry,requestMainFocus,sessionIdRef,setComposerText,stashAt,- syncDraftFromEditor+ syncDraftFromEditor,+ takeDraftRetry} = useComposerDraft({ activeQueueSessionKey, focusKey, inputDisabled, queueEditRef, sessionId })useComposerScreenshot({ sessionKey: activeQueueSessionKey, focusKey, onAttachImageBlob })@@ -438,7 +441,9 @@ export function ChatBar({queuedPrompts,sessionId,setComposerText,- stashAt+ stashAt,+ rememberDraftRetry,+ takeDraftRetry})// Resting / reconnecting / starting placeholder text, re-rolled only on a real@@ -1296,7 +1301,10 @@ export function ChatBar({<SuggestionPills sessionId={statusSessionId} /><PreparedImageRecoveryoccupied={hasText || attachments.length > 0 || busy || disabled}- onRestore={loadIntoComposer}+ onRestore={(text, restored, id) => {+ loadIntoComposer(text, restored)+ rememberDraftRetry(activeQueueSessionKey, draftRetry(id, text, restored))+ }}request={requestBusyConfig}sessionKey={activeQueueSessionKey}/>diff --git a/apps/desktop/src/app/chat/composer/prepared-image-recovery.test.tsx b/apps/desktop/src/app/chat/composer/prepared-image-recovery.test.tsxindex b21b7f2c458..cdc183c1e16 100644--- a/apps/desktop/src/app/chat/composer/prepared-image-recovery.test.tsx+++ b/apps/desktop/src/app/chat/composer/prepared-image-recovery.test.tsx@@ -20,7 +20,7 @@ test('reopened composer offers exact image occurrence only for its original destexpect(screen.queryByRole('button')).toBeNull()view.rerender(<PreparedImageRecovery occupied={false} onRestore={restore} request={request} sessionKey="original" />)fireEvent.click(await screen.findByRole('button', { name: 'Restore image draft' }))- expect(restore).toHaveBeenCalledWith(' retained image ', attachments)+ expect(restore).toHaveBeenCalledWith(' retained image ', attachments, 'submission')expect(request).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/app/chat/composer/prepared-image-recovery.tsx b/apps/desktop/src/app/chat/composer/prepared-image-recovery.tsxindex 37a14eb6d8b..8974be5cfc4 100644--- a/apps/desktop/src/app/chat/composer/prepared-image-recovery.tsx+++ b/apps/desktop/src/app/chat/composer/prepared-image-recovery.tsx@@ -12,7 +12,8 @@ interface Props {sessionKey: string | nullrequest: GatewayRequestoccupied: boolean- onRestore: (text: string, attachments: ComposerAttachment[]) => void+ /** `id` is the retained send's identity: sending the restored draft unchanged retries it. */+ onRestore: (text: string, attachments: ComposerAttachment[], id: string) => void}export function PreparedImageRecovery({ sessionKey, request, occupied, onRestore }: Props) {@@ -39,7 +40,7 @@ export function PreparedImageRecovery({ sessionKey, request, occupied, onRestore<div className="flex items-center gap-2 rounded-md border bg-background px-3 py-2 text-xs" key={draft.key}><span className="min-w-0 flex-1 truncate">{draft.text || draft.attachments.map(attachment => attachment.label).join(', ')}</span><Button disabled={occupied} onClick={() => {- onRestore(draft.text, draft.attachments)+ onRestore(draft.text, draft.attachments, draft.id)setDrafts(current => current.filter(entry => entry.key !== draft.key))}} size="sm" type="button" variant="outline">{t.composer.restoreImageDraft}</Button></div>diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex dbfa031e5e9..beae0b57789 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -247,6 +247,39 @@ describe('submit timeout admission fences', () => {expect(submits).toHaveLength(2)})+ // Adolanium 6055121721: after a lost identityless (legacy) ACK, Enter on that exact text did+ // nothing forever. The explicit retry is refused once, visibly; a new send of the words is the+ // user's informed new turn and goes out.+ it('a lost legacy acknowledgement is surfaced once and never blocks sending the same text again', async () => {+ const submits: Record<string, unknown>[] = []+ clearNotifications()++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'session.resume') {return { session_id: RUNTIME_SESSION_ID } as never}++ if (method !== 'prompt.submit') {return {} as never}+ submits.push(params!)++ // A legacy serve refuses every submission_id before admission.+ if (params?.submission_id) {throw Object.assign(new Error('capability refused'), { code: 4094 })}++ if (submits.length === 2) {throw new Error('request timed out: prompt.submit')}++ return { ok: true } as never+ })++ let handle: HarnessHandle | null = null+ await actRender(<Harness onReady={h => (handle = h)} rawAdmissionReceipts refreshSessions={async () => undefined} requestGateway={requestGateway} />)+ expect(await handle!.submitText('hello there', { submission_id: 'legacy-lost' })).toBe(false)+ expect(await handle!.submitText('hello there', { submission_id: 'legacy-lost' })).toBe(false)+ expect(submits).toHaveLength(2)+ const shown = $notifications.get().map(n => n.message)+ // The restored draft keeps its identity; pressing Enter again after the notice sends it.+ expect(await handle!.submitText('hello there', { submission_id: 'legacy-lost' })).toBe(true)+ expect(submits).toHaveLength(4)+ expect(shown).toContain(en.desktop.legacySendUnconfirmed)+ })+it('retries an identified timeout with the same admission identity after resume', async () => {const submits: Record<string, unknown>[] = []diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsxindex 60990d35db2..9f58c3e6bd0 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx@@ -58,7 +58,7 @@ async function openWindow(submit: (params: Record<string, unknown>) => unknown)const hook = renderHook(() => useSubmitPrompt(deps))- return { send: (text: string) => act(async () => hook.result.current(text)) }+ return { send: (text: string, options?: { submission_id: string }) => act(async () => hook.result.current(text, options)) }}afterEach(() => {@@ -91,6 +91,6 @@ it('two windows sending the same text keep separate identities; only the writerexpect(ids[1]).not.toBe(ids[0])// The writer's explicit retry reuses its own retained identity.- expect(await first.send('same text')).toBe(true)+ expect(await first.send('same text', { submission_id: ids[0] })).toBe(true)expect(ids[2]).toBe(ids[0])})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions-spent.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions-spent.test.tsindex 74082b3bd7c..8da92d437f5 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions-spent.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions-spent.test.ts@@ -37,7 +37,7 @@ test('an admitted identity whose journal removal failed stays spent across a rel// Renderer reload: module memory is gone, the file entry is not.vi.resetModules()const reloaded = await import('./prepared-submissions')- expect(await reloaded.adoptPreparedSubmission(intent)).toBeUndefined()+ expect(await reloaded.adoptPreparedSubmission(intent, 'admitted-id')).toBeUndefined()expect(await reloaded.readPreparedSubmission(intent)).toBeUndefined()// Storage recovers: the stale file entry is retired instead of lingering.@@ -101,8 +101,8 @@ test('two windows retiring different admitted entries keep both tombstones acrosinWindow(storageView(shared).storage as unknown as Storage)vi.resetModules()const reloaded = await import('./prepared-submissions')- expect(await reloaded.adoptPreparedSubmission(intent('from A'))).toBeUndefined()- expect(await reloaded.adoptPreparedSubmission(intent('from B'))).toBeUndefined()+ expect(await reloaded.adoptPreparedSubmission(intent('from A'), 'admitted-a')).toBeUndefined()+ expect(await reloaded.adoptPreparedSubmission(intent('from B'), 'admitted-b')).toBeUndefined()} finally {inWindow(realStorage)}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.tsindex 5f8c1e8029f..9f7b602473c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts@@ -140,13 +140,13 @@ export async function listPreparedImageDrafts(target: string, scopeKey: string)return Object.entries(await readJournal()).flatMap(([key, entry]) => {const [scope, session, text, , displayKind, fromQueue, submissionId] = JSON.parse(key)- // Restoring an ordinary draft must recreate its exact retry key. Queue and- // slash submissions own their recovery. Historical slash keys intentionally- // omit submissionId, so the retained invocation must also be excluded.- return scope === scopeKey && session === target && !displayKind && !fromQueue && !submissionId &&- !String(text).trimStart().startsWith('/') &&+ // An ordinary draft restores with its own identity, so sending it again is the+ // explicit retry of that entry. Queue and slash submissions own their recovery+ // (historical slash keys omit submissionId; the retained invocation is excluded).+ return scope === scopeKey && session === target && !displayKind && !fromQueue &&+ (!submissionId || submissionId === entry.id) && !String(text).trimStart().startsWith('/') &&!entry.legacyAttempted && entry.attachments.some(attachment => attachment.kind === 'image')- ? [{ key, text: String(text), attachments: entry.attachments }]+ ? [{ key, id: entry.id, text: String(text), attachments: entry.attachments }]: []})}@@ -188,14 +188,28 @@ function holdPreparedSubmission(key: string): Promise<boolean> {})}-const intentVariant = (intent: string, key: string) => key === intent || key.startsWith(`${intent.slice(0, -1)},`)+const sameDestination = (intent: string, key: string) => {+ const [scope, session] = JSON.parse(intent)+ const [savedScope, savedSession] = JSON.parse(key)-/** The retained entry an explicit retry of `intent` may reuse: this window's own, or one a- * closed window left. A live other window's uncertain send is never adopted. */-export async function adoptPreparedSubmission(intent: string): Promise<{ key: string; entry: PreparedSubmission } | undefined> {+ return scope === savedScope && session === savedSession+}++/** The retained entry an explicit retry may reuse: the one carrying exactly `submissionId` on the+ * same destination (scope + session) as `intent`, held by this window or left by a closed one.+ * Equal text never selects an entry: a new message is a new intent even when it repeats an+ * uncertain one, and a live other window's uncertain send is never adopted. */+export async function adoptPreparedSubmission(+ intent: string,+ submissionId: string+): Promise<{ key: string; entry: PreparedSubmission } | undefined> {const journal = await readJournal()- for (const key of Object.keys(journal).filter(key => intentVariant(intent, key)).sort()) {+ const keys = Object.keys(journal)+ .filter(key => journal[key].id === submissionId && sameDestination(intent, key))+ .sort()++ for (const key of keys) {if (await holdPreparedSubmission(key)) { return { key, entry: journal[key] } }}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex a7c7f7355d4..50fff902896 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -240,15 +240,20 @@ export function useSlashCommand(deps: SlashCommandDeps) {}try {- const prepared = (await adoptPreparedSubmission(- preparedSubmissionKey(- resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),- destination,- rawCommand,- options?.attachments ?? $composerAttachments.get(),- retryOptions- )- ))?.entry+ // An explicit retry of this exact invocation reuses its retained expansion; the same+ // command typed again is a new invocation.+ const prepared = options?.submission_id+ ? (await adoptPreparedSubmission(+ preparedSubmissionKey(+ resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),+ destination,+ rawCommand,+ options?.attachments ?? $composerAttachments.get(),+ retryOptions+ ),+ options.submission_id+ ))?.entry+ : undefinedif (prepared) {return await submitPromptText(prepared.text, {diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsxindex 2e4605900bf..af7c17c8dd9 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx@@ -79,6 +79,26 @@ afterEach(() => {})describe('submission intent destinations', () => {+ // N7 (ported from #135061): two panes in one window are enough. The owner replays a known+ // submission id as `terminal`, so a new message adopting the uncertain send's id would vanish.+ it('separate mounted composers submit identical text as distinct intents while an explicit retry retains its payload', async () => {+ const first = setup()+ const second = setup()+ first.requestGateway.mockRejectedValueOnce(new Error('lost acknowledgement'))+ const a = renderHook(() => useSubmitPrompt(first.deps))+ const b = renderHook(() => useSubmitPrompt(second.deps))+ await act(async () => { expect(await a.result.current('same text')).toBe(false) })+ const original = first.requestGateway.mock.calls.find(call => call[0] === 'prompt.submit')![1]!+ await act(async () => { expect(await b.result.current('same text')).toBe(true) })+ const other = second.requestGateway.mock.calls.find(call => call[0] === 'prompt.submit')![1]!+ expect(other.submission_id).not.toBe(original.submission_id)+ const retained = Object.values(JSON.parse(localStorage.getItem('hermes.desktop.preparedSubmissions.v1')!))+ expect(retained).toHaveLength(1)+ expect(retained[0]).toMatchObject({ id: original.submission_id, params: original })+ await act(async () => { expect(await a.result.current('same text', { submission_id: String(original.submission_id) })).toBe(true) })+ expect(first.requestGateway.mock.calls.filter(call => call[0] === 'prompt.submit')[1][1]).toEqual(original)+ })+it('stages canonical images on the captured owner without a legacy image RPC', async () => {const { uploadComposerAttachment } = await import('.')const original = window.hermesDesktop@@ -109,12 +129,12 @@ describe('submission intent destinations', () => {deps.syncAttachmentsForSubmit.mockResolvedValue({ sessionId: 'runtime-a', attachments: [image] } as never)requestGateway.mockRejectedValueOnce(new Error('connection closed'))let hook = renderHook(() => useSubmitPrompt(deps))- await act(async () => { expect(await hook.result.current('image retry', { attachments: [image] })).toBe(false) })+ await act(async () => { expect(await hook.result.current('image retry', { submission_id: 'image-retry', attachments: [image] })).toBe(false) })const first = requestGateway.mock.calls.find(call => call[0] === 'prompt.submit')![1]expect(first?.attachments).toEqual([{ path: image.path, mime: image.mime }])hook.unmount()hook = renderHook(() => useSubmitPrompt(deps))- await act(async () => { expect(await hook.result.current('image retry', { attachments: [image] })).toBe(true) })+ await act(async () => { expect(await hook.result.current('image retry', { submission_id: 'image-retry', attachments: [image] })).toBe(true) })expect(requestGateway.mock.calls.filter(call => call[0] === 'prompt.submit')[1][1]).toEqual(first)expect(deps.syncAttachmentsForSubmit).toHaveBeenCalledOnce()expect(window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1')).not.toContain('image retry')@@ -172,7 +192,7 @@ describe('submission intent destinations', () => {requestGateway.mockRejectedValueOnce(new Error('connection closed'))let hook = renderHook(() => useSubmitPrompt(deps))await act(async () => {- expect(await hook.result.current('retry me')).toBe(false)+ expect(await hook.result.current('retry me', { submission_id: 'explicit-retry' })).toBe(false)})const journal = window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1')expect(journal).toContain('retry me')@@ -197,7 +217,7 @@ describe('submission intent destinations', () => {hook = renderHook(() => useSubmitPrompt(deps))const { result } = hookawait act(async () => {- expect(await result.current('retry me')).toBe(true)+ expect(await result.current('retry me', { submission_id: 'explicit-retry' })).toBe(true)})const calls = requestGateway.mock.calls.filter(@@ -283,7 +303,7 @@ describe('submission intent destinations', () => {const input = slash ? '/private-skill' : 'first prompt'let hook = mount()await act(async () => {- expect(await hook.result.current(input)).toBe(false)+ expect(await hook.result.current(input, { submission_id: 'new-session-retry' })).toBe(false)})const serialized = window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1')expect(serialized).toBeTruthy()@@ -294,7 +314,7 @@ describe('submission intent destinations', () => {loseAck = falsehook = mount()await act(async () => {- expect(await hook.result.current(input)).toBe(true)+ expect(await hook.result.current(input, { submission_id: 'new-session-retry' })).toBe(true)})expect(accepted.size).toBe(1)expect(deps.createBackendSessionForSend).toHaveBeenCalledTimes(1)@@ -328,14 +348,14 @@ describe('submission intent destinations', () => {})let hook = renderHook(() => useSubmitPrompt(deps))await act(async () => {- expect(await hook.result.current('receipt')).toBe(mode === '4094')+ expect(await hook.result.current('receipt', { submission_id: `receipt-${mode}` })).toBe(mode === '4094')})hook.unmount()hook = renderHook(() => useSubmitPrompt(deps))if (mode !== '4094') {await act(async () => {- expect(await hook.result.current('receipt')).toBe(false)+ expect(await hook.result.current('receipt', { submission_id: `receipt-${mode}` })).toBe(false)})const attempts = requestGateway.mock.calls.filter(call => call[0] === 'prompt.submit')diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 48b29f83894..3e456edac13 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -444,13 +444,23 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {let retainedKey: string | undefinedtry {- const adopted = await adoptPreparedSubmission(retryKeyForTarget())+ // Only an explicit retry (the caller names the uncertain send's identity) reuses a+ // retained entry; a new message with the same text is a new turn.+ const adopted = options?.submission_id+ ? await adoptPreparedSubmission(retryKeyForTarget(), options.submission_id)+ : undefined+retained = adopted?.entryretainedKey = adopted?.key// A legacy send has no deduplication identity. After an ambiguous ACK- // even an upgraded server cannot safely admit it under the saved ID.- if (retained?.legacyAttempted) {+ // even an upgraded server cannot safely admit it under the saved ID, so+ // the retry is refused once, visibly, and the entry is retired: sending+ // the words again afterwards is the user's informed new turn.+ if (retained?.legacyAttempted && retainedKey) {+ await removePreparedSubmission(retainedKey, retained.id).catch(error => console.warn('[prepared-submission-retire]', error))+ notify({ kind: 'warning', title: copy.promptFailed, message: copy.legacySendUnconfirmed })+return false}} catch (err) {diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex e0c93290a83..6c72e4792e8 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -5057,6 +5057,8 @@ export const en: Translations = {sessionUnavailable: 'Session unavailable',createSessionFailed: 'Could not create a new session',promptFailed: 'Prompt failed',+ legacySendUnconfirmed:+ 'This server could not confirm the earlier send of this message, so it may already have run. Check the conversation before sending it again.',providerCredentialRequired: 'Add a provider credential before sending your first message.',emptySlashCommand: 'empty slash command',slashCommandIgnoredTitle: 'Command not sent',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex d7680227b48..7647d0ad7dd 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -4298,6 +4298,7 @@ export interface Translations extends NoticeTranslations {sessionUnavailable: stringcreateSessionFailed: stringpromptFailed: string+ legacySendUnconfirmed: stringproviderCredentialRequired: stringemptySlashCommand: stringslashCommandIgnoredTitle: stringdiff --git a/apps/desktop/src/store/composer-draft-retry.ts b/apps/desktop/src/store/composer-draft-retry.tsnew file mode 100644index 00000000000..88c6331494b--- /dev/null+++ b/apps/desktop/src/store/composer-draft-retry.ts@@ -0,0 +1,69 @@+import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'++import { type ComposerAttachment, freshDraftScope } from './composer'++/** The identity of an uncertain send that was restored into a composer draft.+ * Sending that exact draft again is the explicit retry (same `submission_id`,+ * so the owner replays instead of running it twice); editing it, or typing+ * equal text anew in any composer, is a new message with a new identity. */+export interface ComposerDraftRetry {+ id: string+ text: string+ attachmentIds: string[]+}++// One localStorage key per draft scope: every window of the origin shares this+// storage with last-writer-wins per KEY, so one window never drops another's.+const RETRY_PREFIX = 'hermes:composer-draft-retry:v1:'++const attachmentIds = (attachments: ComposerAttachment[]) => attachments.map(a => a.occurrenceId ?? a.id)++export function draftRetry(id: string, text: string, attachments: ComposerAttachment[]): ComposerDraftRetry {+ return { id, text, attachmentIds: attachmentIds(attachments) }+}++export function draftRetryTextMatches(retry: ComposerDraftRetry | undefined, text: string): boolean {+ return Boolean(retry && sanitizeComposerInput(retry.text).trim() === sanitizeComposerInput(text).trim())+}++/** `retry` while the draft is still exactly the restored send; otherwise undefined. */+export function matchingDraftRetry(+ retry: ComposerDraftRetry | undefined,+ text: string,+ attachments: ComposerAttachment[]+): ComposerDraftRetry | undefined {+ return retry &&+ draftRetryTextMatches(retry, text) &&+ JSON.stringify(retry.attachmentIds) === JSON.stringify(attachmentIds(attachments))+ ? retry+ : undefined+}++/** The storage key of a draft scope, the same resolution the draft stash uses. */+const scopeKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()++export function readDraftRetry(scope: string | null | undefined): ComposerDraftRetry | undefined {+ try {+ const parsed: unknown = JSON.parse(window.localStorage.getItem(RETRY_PREFIX + scopeKey(scope)) || 'null')+ const retry = parsed as ComposerDraftRetry | null++ return retry && typeof retry.id === 'string' && typeof retry.text === 'string' && Array.isArray(retry.attachmentIds)+ ? retry+ : undefined+ } catch {+ return undefined+ }+}++export function writeDraftRetry(scope: string | null | undefined, retry: ComposerDraftRetry | undefined): void {+ try {+ if (retry) {+ window.localStorage.setItem(RETRY_PREFIX + scopeKey(scope), JSON.stringify(retry))+ } else {+ window.localStorage.removeItem(RETRY_PREFIX + scopeKey(scope))+ }+ } catch {+ // Best-effort like the draft text itself: without it a reload sends the words as new.+ }+}+diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 9b1c7a10afc..468cd721665 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -1427,6 +1427,7 @@"desktop.imagePreviewFailed","desktop.imageSaved","desktop.imageWriteFailed",+ "desktop.legacySendUnconfirmed","desktop.modelSwitchConfirmBody","desktop.modelSwitchConfirmLabel","desktop.modelSwitchConfirmTitle",