Skip to content

The agent that grows with you

fix(desktop): adopt an interrupted send only under its lock, from a draft saved before it

Tekniumfaf5cf69315b
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.ts
index 1251fb31880..8318a7b84b5 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
@@ -16,6 +16,7 @@ import {
isFreshDraftScope,
onComposerDraftSyncRequest,
reloadPersistedDrafts,
+ savedDraftAt,
stashSessionDraft,
takeSessionDraft
} from '@/store/composer'
@@ -766,18 +767,32 @@ export function useComposerDraft({
}
// The saved draft can already be an interrupted send's words (persisted before the send cleared
- // the composer): it takes that send's identity before Enter could mint a second one.
- const adopted = adoptInterruptedSend(activeQueueSessionKey, text, interruptedSend)
+ // the composer): it takes that send's identity, once its owner lock proves no live window still
+ // sends it, provided the composer still holds exactly that saved draft.
+ void adoptInterruptedSend(activeQueueSessionKey, text, savedDraftAt(activeQueueSessionKey), {
+ ...interruptedSend,
+ adopt: adopted => {
+ if (
+ draftScopeRef.current !== activeQueueSessionKey ||
+ !draftRetryTextMatches(adopted, syncDraftFromEditor()) ||
+ retryAttachmentIds(attachmentScope.$attachments.get()).join() !== retryAttachmentIds(attachments).join()
+ ) {
+ return false
+ }
- if (adopted && !draftRetryTextMatches(draftRetryRef.current, text)) {
- rememberDraftRetry(activeQueueSessionKey, { ...adopted, attachmentIds: retryAttachmentIds(attachments) })
- }
+ if (!draftRetryTextMatches(draftRetryRef.current, text)) {
+ rememberDraftRetry(activeQueueSessionKey, { ...adopted, attachmentIds: retryAttachmentIds(attachments) })
+ }
- // The saved draft can already carry a text-only identity for these words; the journaled send
- // still names the attachments the reload dropped.
- if (adopted && !attachments.length) {
- noteAttachmentsNotRestored(adopted)
- }
+ // The saved draft can already carry a text-only identity for these words; the journaled send
+ // still names the attachments the reload dropped.
+ if (!attachments.length) {
+ noteAttachmentsNotRestored(adopted)
+ }
+
+ return true
+ }
+ })
if (!text.trim() && attachments.length === 0) {
// A send its page never finished (the window closed or reloaded mid-send) is this draft.
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.tsx
index b3ca72d3af3..3e039bc0db8 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
@@ -204,7 +204,7 @@ it('a message sent right before the window closes is never lost and never sent t
expect(reopened).toHaveBeenCalledTimes(1)
expect(reopened.mock.calls[0][0].trim()).toBe('my long question')
expect(reopened.mock.calls[0][1]?.submission_id).toBe(firstId)
-})
+}, 30_000)
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), admitted and still queued (the resume snapshot
@@ -358,3 +358,20 @@ it('recovery never discards a file the user attached while it was running', asyn
expect(await attached()).toEqual(['new-file.txt'])
expect(handles.editor()).toBe('late words')
})
+
+it('equal words typed again after an interrupted send are a new message, never that send', async () => {
+ const firstId = await sendThenClose('same words')
+ const { at } = JSON.parse(window.localStorage.getItem(outboxKeys()[0])!) as { at: number }
+
+ // The draft holding those words was saved after the send: the user typed them again.
+ window.localStorage.setItem(
+ 'hermes:composer-drafts:v4',
+ JSON.stringify({ drafts: { 'stored-B': { at: at + 1000, text: 'same words' } } })
+ )
+ const reopened = vi.fn<ChatBarProps['onSubmit']>(async () => true)
+ await openPage(reopened)
+ await act(async () => {})
+ expect(handles.editor()).toBe('same words')
+ await act(async () => handles.submitDraft())
+ expect(reopened.mock.calls[0][1]?.submission_id).not.toBe(firstId)
+}, 30_000)
diff --git a/apps/desktop/src/store/composer-draft-retry.ts b/apps/desktop/src/store/composer-draft-retry.ts
index d26e93a8e49..bd1bd3d18e1 100644
--- a/apps/desktop/src/store/composer-draft-retry.ts
+++ b/apps/desktop/src/store/composer-draft-retry.ts
@@ -1,6 +1,6 @@
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
-import { type ComposerAttachment, freshDraftScope } from './composer'
+import { type ComposerAttachment, draftKey as scopeKey } 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`,
@@ -53,9 +53,6 @@ export function loadedDraftRetry(
: retry
}
-/** 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')
diff --git a/apps/desktop/src/store/composer-outbox-landed.ts b/apps/desktop/src/store/composer-outbox-landed.ts
index 66f9bc817a3..92e6dcfb72f 100644
--- a/apps/desktop/src/store/composer-outbox-landed.ts
+++ b/apps/desktop/src/store/composer-outbox-landed.ts
@@ -2,6 +2,7 @@ import { getSessionMessages } from '@/api/sessions'
import type { SessionMessage } from '@/types/hermes'
import { listedSubmissions } from './admitted-submissions'
+import { isFreshDraftScope } from './composer'
// 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
@@ -18,8 +19,6 @@ 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
@@ -43,7 +42,7 @@ const predates = (message: SessionMessage, sentAt: number) =>
* 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)) {
+ if (!scope || isFreshDraftScope(scope)) {
return false
}
diff --git a/apps/desktop/src/store/composer-outbox.ts b/apps/desktop/src/store/composer-outbox.ts
index 861f2ffd28c..d5a09d0e4fe 100644
--- a/apps/desktop/src/store/composer-outbox.ts
+++ b/apps/desktop/src/store/composer-outbox.ts
@@ -1,5 +1,5 @@
import { onListedSubmissions } from './admitted-submissions'
-import { freshDraftScope } from './composer'
+import { draftKey as scopeKey } from './composer'
import { type ComposerDraftRetry, draftRetryTextMatches } from './composer-draft-retry'
import { sendLanded } from './composer-outbox-landed'
@@ -35,7 +35,6 @@ interface OutboxEntry {
// entry as owned by a live page for every other window of the origin.
const ownedHere = new Map<string, () => void>()
-const scopeKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()
const entryKey = (scope: string, id: string) => `${PREFIX}${JSON.stringify([scope, id])}`
const lockName = (key: string) => `${key}:owner`
@@ -186,31 +185,51 @@ async function settleTaken(entry: OutboxEntry, { landed, withdraw }: Interrupted
}
}
-/** The saved draft `text` already brought an interrupted send of `scope` back (it was persisted
- * before the send cleared the composer): hand back that send's identity for the draft, synchronously
- * so no Enter can mint a second one, and retire the entry so it is never offered beside it. */
-export function adoptInterruptedSend(
+/** The saved draft `text` (written at `savedAt`) already brought an interrupted send of `scope` back:
+ * it was persisted before the send cleared the composer. `adopt` hands that send's identity to the
+ * draft (false: the composer changed meanwhile, the entry stays for a later load) and the entry is
+ * retired so it is never offered beside it.
+ *
+ * Only a draft saved before the send counts: equal words typed again later are a new message. And
+ * only under the entry's Web Lock, like `restoreInterruptedSend`: a held lock is a live window's send
+ * still in flight, never a copy this draft may take over. */
+export async function adoptInterruptedSend(
scope: string | null | undefined,
text: string,
- handlers: InterruptedSendHandlers
-): ComposerDraftRetry | undefined {
- if (!text.trim()) {
- return undefined
+ savedAt: number | undefined,
+ handlers: InterruptedSendHandlers & { adopt: (retry: ComposerDraftRetry) => boolean }
+): Promise<void> {
+ if (!text.trim() || savedAt === undefined) {
+ return
}
- const key = orphanKeys(scopeKey(scope)).find(key => draftRetryTextMatches(read(key)?.retry, text))
- const entry = key ? read(key) : undefined
+ const savedBefore = (entry: OutboxEntry | undefined): entry is OutboxEntry =>
+ Boolean(entry && savedAt <= entry.at && draftRetryTextMatches(entry.retry, text))
- if (!key || !entry) {
- return undefined
+ const take = (key: string) => {
+ const entry = read(key)
+
+ if (!ownedHere.has(key) && savedBefore(entry) && handlers.adopt(entry.retry)) {
+ write(key, undefined)
+ void settleTaken(entry, handlers)
+
+ return true
+ }
+
+ return false
}
- // Not lock-guarded: a peer window offering or still sending this entry uses the same id, so the
- // owner deduplicates whichever copy is sent.
- write(key, undefined)
- void settleTaken(entry, handlers)
+ const available = locks()
+
+ for (const key of orphanKeys(scopeKey(scope)).filter(key => savedBefore(read(key)))) {
+ const taken = available
+ ? await available.request(lockName(key), { ifAvailable: true }, lock => Boolean(lock && take(key)))
+ : take(key)
- return entry.retry
+ if (taken) {
+ return
+ }
+ }
}
/** Offer `scope`'s interrupted sends (ones no live page owns) to an empty composer: an entry is
diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.ts
index a2429476efa..c8325401842 100644
--- a/apps/desktop/src/store/composer.ts
+++ b/apps/desktop/src/store/composer.ts
@@ -295,7 +295,7 @@ export const isFreshDraftScope = (key: string | null | undefined): boolean =>
// A null/empty scope IS the current fresh-chat lifecycle — resolve it to that
// lifecycle's own key so every stash/read/migrate consumer below addresses the
// active fresh bucket instead of the shared legacy one.
-const draftKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()
+export const draftKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()
/** Inline "Restored your unsent message" notice for the fresh draft (see
* `adoptGoneSessionDraft`). `null` = nothing to show. */
@@ -549,6 +549,11 @@ export function takeSessionDraft(scope: string | null | undefined): SessionDraft
return stashed ? cloneDraft(stashed) : EMPTY_SESSION_DRAFT
}
+/** When `scope`'s saved draft was last written (ms; 0 for one carried over from the unstamped v3
+ * list), or undefined when none is saved. */
+export const savedDraftAt = (scope: string | null | undefined): number | undefined =>
+ persistedDrafts.get(draftKey(scope))?.at
+
export const clearSessionDraft = (scope: string | null | undefined) => stashSessionDraft(scope, '', [])
/**