The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a draft another writer changed behind the window is no longer lost or revived
Teknium512d8513b70e
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.persist-window.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.persist-window.test.tsxindex 69c48116fc4..4afb3c2aa6c 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.persist-window.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.persist-window.test.tsx@@ -1,13 +1,8 @@import { act, cleanup, render } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import {- clearSessionDraft,- mainComposerScope,- SESSION_DRAFTS_STORAGE_KEY,- stashSessionDraft,- takeSessionDraft-} from '@/store/composer'+import { clearSessionDraft, mainComposerScope, stashSessionDraft, takeSessionDraft } from '@/store/composer'+import { DRAFT_STASH_STORAGE_KEY } from '@/store/composer-draft-stash'import { TYPING_STORE_IDLE_MS } from '../composer-store-writer'import { DRAFT_PERSIST_DEBOUNCE_MS, type QueueEditState } from '../composer-utils'@@ -172,13 +167,19 @@ describe('useComposerDraft — the draft stash window starts at the keystroke',stashSessionDraft(OTHER_SCOPE, 'sent from the other window', [])const { rerender } = render(<Harness scope={SCOPE} />)act(() => {- mainComposerScope.$attachments.set([{ id: 'shot.png', kind: 'image', label: 'shot.png', occurrenceId: 'occ-img' }])+ mainComposerScope.$attachments.set([+ { id: 'shot.png', kind: 'image', label: 'shot.png', occurrenceId: 'occ-img' }+ ])})rerender(<Harness scope={OTHER_SCOPE} />)// The other window sends OTHER_SCOPE's draft and saves one in a third session.- window.localStorage.setItem(SESSION_DRAFTS_STORAGE_KEY, JSON.stringify({ [THIRD_SCOPE]: 'typed elsewhere' }))- window.dispatchEvent(new StorageEvent('storage', { key: SESSION_DRAFTS_STORAGE_KEY }))+ const at = Date.now() + 1_000+ window.localStorage.setItem(+ DRAFT_STASH_STORAGE_KEY,+ JSON.stringify({ cleared: { [OTHER_SCOPE]: at }, drafts: { [THIRD_SCOPE]: { at, text: 'typed elsewhere' } } })+ )+ window.dispatchEvent(new StorageEvent('storage', { key: DRAFT_STASH_STORAGE_KEY }))expect(takeSessionDraft(THIRD_SCOPE).text).toBe('typed elsewhere')expect(takeSessionDraft(OTHER_SCOPE).text).toBe('')diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.accept-clear.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.accept-clear.test.tsxnew file mode 100644index 00000000000..4a88e93786e--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.accept-clear.test.tsx@@ -0,0 +1,130 @@+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { clearSessionDraft, mainComposerScope, takeSessionDraft } from '@/store/composer'++import { DRAFT_PERSIST_DEBOUNCE_MS, type QueueEditState } from '../composer-utils'+import { composerPlainText, RICH_INPUT_SLOT } from '../rich-editor'++import { useComposerDraft } from './use-composer-draft'+import { useComposerSubmit } from './use-composer-submit'++// Only the assistant-ui adapter is substituted; the draft hook, the submit+// hook and the shared stash are the real ones.+const runtime = vi.hoisted(() => {+ let text = ''+ const listeners = new Set<() => void>()++ const setText = vi.fn((next: string) => {+ text = next+ listeners.forEach(listener => listener())+ })++ return {+ composer: { setText },+ getState: () => ({ text }),+ reset: () => {+ text = ''+ listeners.clear()+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener)++ return () => listeners.delete(listener)+ }+ }+})++vi.mock('@assistant-ui/react', () => ({+ useAui: () => ({ composer: () => runtime.composer }),+ useAuiState: (selector: (state: { composer: { text: string } }) => unknown) =>+ selector({ composer: runtime.getState() }),+ useComposerRuntime: () => runtime+}))++const SCOPE = 'accept-clear-session'+const OTHER = 'accept-clear-other'+const queueEditRef = { current: null as QueueEditState | null }+let submitDraft: () => void+let accept: (accepted: boolean) => void++function Harness({ scope }: { scope: string }) {+ const draft = useComposerDraft({+ activeQueueSessionKey: scope,+ focusKey: null,+ inputDisabled: false,+ queueEditRef,+ sessionId: scope+ })++ const submit = useComposerSubmit({+ ...draft,+ activeQueueSessionKey: scope,+ attachments: [],+ busy: false,+ disabled: false,+ drainNextQueued: async () => false,+ exitQueuedEdit: () => false,+ inputDisabled: false,+ onCancel: () => {},+ onSteer: async () => true,+ onSteerHidden: async () => true,+ onSubmit: () => new Promise<boolean>(resolve => (accept = resolve)),+ queueCurrentDraft: () => false,+ queueEdit: null,+ queuedPrompts: [],+ sessionId: scope+ })++ submitDraft = submit.submitDraft++ return (+ <div+ contentEditable+ data-slot={RICH_INPUT_SLOT}+ data-testid="editor"+ ref={draft.editorRef}+ suppressContentEditableWarning+ />+ )+}++function typeAndSave(editor: HTMLElement, text: string) {+ editor.textContent = text+ editor.dispatchEvent(new Event('input', { bubbles: true }))+ act(() => {+ runtime.composer.setText(text)+ })+ act(() => void vi.advanceTimersByTime(DRAFT_PERSIST_DEBOUNCE_MS + 50))+}++beforeEach(() => {+ vi.useFakeTimers()+ runtime.reset()+})++afterEach(() => {+ cleanup()+ vi.useRealTimers()+ mainComposerScope.clear()+ clearSessionDraft(SCOPE)+ clearSessionDraft(OTHER)+})++it('a send accepted after the next message was typed and saved keeps that message', async () => {+ const { getByTestId, rerender } = render(<Harness scope={SCOPE} />)+ const editor = getByTestId('editor')++ typeAndSave(editor, 'first message')+ act(() => submitDraft())+ typeAndSave(editor, 'next message')+ expect(takeSessionDraft(SCOPE).text).toBe('next message')++ // The gateway's accept for "first message" lands only now.+ await act(async () => accept(true))++ rerender(<Harness scope={OTHER} />)+ rerender(<Harness scope={SCOPE} />)+ expect(takeSessionDraft(SCOPE).text).toBe('next message')+ expect(composerPlainText(editor).trim()).toBe('next message')+})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 26ffde61ae7..5d71745743c 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@@ -10,10 +10,10 @@ import { isTouchInteraction } from '@/lib/touch-interaction'import type { BusyInputMode } from '@/store/busy-input-mode'import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'import {- clearSessionDraft,type ComposerAttachment,freezeComposerTransportPayload,- isFreshDraftScope+ isFreshDraftScope,+ takeSessionDraft} from '@/store/composer'import { type ComposerDraftRetry, draftRetry } from '@/store/composer-draft-retry'import { resetBrowseState } from '@/store/composer-input-history'@@ -31,6 +31,21 @@ import { composerPlainText } from '../rich-editor'import { useComposerScope, useComposerSurfaceId } from '../scope'import type { ChatBarProps } from '../types'+const sameOccurrence = (a: ComposerAttachment, b: ComposerAttachment) =>+ a.id === b.id && a.occurrenceId === b.occurrenceId++// Whether `scope`'s stashed draft is still the message just sent. By the time+// the send is accepted the user may have typed the next one and the debounce+// saved it there; that draft is not the sent one and stays.+function stashStillHoldsSent(scope: string | null, text: string, attachments: ComposerAttachment[]): boolean {+ const stashed = takeSessionDraft(scope)++ return (+ (stashed.text === text || pathifyRefs(stashed.text) === text) &&+ stashed.attachments.every(attachment => attachments.some(sent => sameOccurrence(sent, attachment)))+ )+}+interface UseComposerSubmitArgs {activeQueueSessionKey: string | nullactiveQueueSessionKeyRef: RefObject<string | null>@@ -167,7 +182,15 @@ export function useComposerSubmit({...(displayKind ? { displayKind } : {})}))- .then(accepted => void (accepted === false ? rejected() : clearSessionDraft(submittedScope)))+ .then(accepted => {+ if (accepted === false) {+ rejected()+ } else if (stashStillHoldsSent(submittedScope, text, submittedAttachments)) {+ // Through the composer's own save, so a next message the user types+ // into this emptied draft counts as unsaved and is saved again.+ stashAt(submittedScope, '', [])+ }+ }).catch(rejected)}@@ -382,7 +405,12 @@ export function useComposerSubmit({return false}- notify({ id: 'onboarding-slash-off', kind: 'info', message: t.firstRun.slashOffBody, title: t.firstRun.slashOffTitle })+ notify({+ id: 'onboarding-slash-off',+ kind: 'info',+ message: t.firstRun.slashOffBody,+ title: t.firstRun.slashOffTitle+ })focusInput()return truediff --git a/apps/desktop/src/store/composer-draft-stash.test.ts b/apps/desktop/src/store/composer-draft-stash.test.tsnew file mode 100644index 00000000000..da235cd9e6b--- /dev/null+++ b/apps/desktop/src/store/composer-draft-stash.test.ts@@ -0,0 +1,71 @@+import { afterEach, expect, it, vi } from 'vitest'++import type * as ComposerStore from './composer'+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from './composer'++// Two windows share localStorage, but each reads its own copy and gets the+// other's writes milliseconds later. A second module instance is the other+// window; restoring the storage it loaded with before it writes makes its+// write come from that stale copy, exactly as a write landing in that gap does.+const ALPHA = 'stash-race-alpha'+const GAMMA = 'stash-race-gamma'++const storageKeys = () =>+ Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index)!)++function snapshotStorage(): Record<string, string> {+ return Object.fromEntries(storageKeys().map(key => [key, window.localStorage.getItem(key)!]))+}++function restoreStorage(snapshot: Record<string, string>) {+ window.localStorage.clear()++ for (const [key, value] of Object.entries(snapshot)) {+ window.localStorage.setItem(key, value)+ }+}++// The other window writes from `stale`; then this window hears about every key it changed.+async function otherWindowWritesFrom(stale: Record<string, string>, write: (other: typeof ComposerStore) => void) {+ const before = snapshotStorage()+ restoreStorage(stale)+ vi.resetModules()+ const other = await import('./composer')+ write(other)++ for (const key of new Set([...Object.keys(before), ...storageKeys()])) {+ if (before[key] !== window.localStorage.getItem(key)) {+ window.dispatchEvent(new StorageEvent('storage', { key }))+ }+ }+}++afterEach(() => {+ clearSessionDraft(ALPHA)+ clearSessionDraft(GAMMA)+ window.localStorage.clear()+})++it("another window's write from a stale copy neither drops nor revives this window's draft", async () => {+ // Saved here while the other window's copy predates it: its write must not drop it.+ const beforeSave = snapshotStorage()+ stashSessionDraft(ALPHA, 'alpha draft', [])+ await otherWindowWritesFrom(beforeSave, other => other.stashSessionDraft(GAMMA, 'gamma draft', []))++ expect(takeSessionDraft(ALPHA).text).toBe('alpha draft')+ expect(takeSessionDraft(GAMMA).text).toBe('gamma draft')+ vi.resetModules()+ expect((await import('./composer')).takeSessionDraft(ALPHA).text).toBe('alpha draft')++ // Cleared (sent) here while the other window's copy still holds it: its write must not bring it back.+ const beforeClear = snapshotStorage()+ clearSessionDraft(ALPHA)+ await otherWindowWritesFrom(beforeClear, other => other.stashSessionDraft(GAMMA, 'gamma edited', []))++ expect(takeSessionDraft(ALPHA).text).toBe('')+ expect(takeSessionDraft(GAMMA).text).toBe('gamma edited')+ vi.resetModules()+ const reopened = await import('./composer')+ expect(reopened.takeSessionDraft(ALPHA).text).toBe('')+ expect(reopened.takeSessionDraft(GAMMA).text).toBe('gamma edited')+})diff --git a/apps/desktop/src/store/composer-draft-stash.ts b/apps/desktop/src/store/composer-draft-stash.tsnew file mode 100644index 00000000000..a0c35c56bdc--- /dev/null+++ b/apps/desktop/src/store/composer-draft-stash.ts@@ -0,0 +1,145 @@+/**+ * The shared draft stash every window of the app reads and writes.+ *+ * Each window keeps its own copy of localStorage, and another window's write+ * reaches it some milliseconds later. A window that wrote its whole draft+ * list from that copy dropped or reverted a draft the other window had just+ * saved, and the other window took the result as "sent elsewhere".+ *+ * So every draft carries the time it was last saved, and a cleared draft+ * leaves a timestamped marker for a while. Merging two copies keeps the newer+ * entry for each key (`newerEntry`). A window that sees storage holding an+ * older entry than the one it saved writes its own back, so a write made from+ * a stale copy cannot stick. The cap keeps the most recently saved drafts,+ * by those times, so every window drops the same ones.+ *+ * The authoritative copy is one key (`DRAFT_STASH_STORAGE_KEY`) so a read never+ * sees half of another window's write. The older `{ key: text }` list is still+ * written after it, for builds and readers that only know that list.+ */++export const DRAFT_STASH_STORAGE_KEY = 'hermes:composer-drafts:v4'++/** `text: null` marks a draft cleared at `at` (sent, emptied). */+export interface StashEntry {+ at: number+ text: string | null+}++export type StashEntries = Map<string, StashEntry>++interface StoredStash {+ cleared?: Record<string, number>+ drafts?: Record<string, { at?: number; text?: string }>+}++// A marker only has to outlive another window's stale copy (milliseconds);+// the cap bounds a long session's sends.+const CLEARED_MARKER_TTL_MS = 10 * 60_000+const MAX_CLEARED_MARKERS = 200++/** a wins over b: saved later, or (same millisecond) by a fixed order so every window agrees. */+export function newerEntry(a: StashEntry | undefined, b: StashEntry | undefined): boolean {+ if (!a) {+ return false+ }++ if (!b || a.at !== b.at) {+ return !b || a.at > b.at+ }++ return (a.text ?? '') > (b.text ?? '')+}++export function readDraftStash(): StashEntries {+ const entries: StashEntries = new Map()++ try {+ const stored = JSON.parse(window.localStorage.getItem(DRAFT_STASH_STORAGE_KEY) ?? '{}') as StoredStash++ for (const [key, at] of Object.entries(stored.cleared ?? {})) {+ entries.set(key, { at: Number(at) || 0, text: null })+ }++ for (const [key, draft] of Object.entries(stored.drafts ?? {})) {+ if (typeof draft?.text === 'string' && draft.text) {+ entries.set(key, { at: Number(draft.at) || 0, text: draft.text })+ }+ }+ } catch {+ // Unreadable reads as empty: every window then writes back what it saved.+ }++ return entries+}++/** The pre-v4 list: texts with no times, so every one counts as the oldest. */+export function readLegacyDrafts(legacyKey: string): StashEntries {+ try {+ const raw = window.localStorage.getItem(legacyKey)+ const texts = raw ? (JSON.parse(raw) as Record<string, string>) : {}++ return new Map(+ Object.entries(texts)+ .filter(([, text]) => typeof text === 'string' && text)+ .map(([key, text]) => [key, { at: 0, text }])+ )+ } catch {+ return new Map()+ }+}++/** Keep the `maxDrafts` most recently saved drafts and only recent cleared markers. */+export function compactDraftStash(entries: StashEntries, maxDrafts: number, now: number): StashEntries {+ const byRecency = [...entries].sort(([ka, a], [kb, b]) => b.at - a.at || (ka < kb ? -1 : ka > kb ? 1 : 0))+ const kept: StashEntries = new Map()+ let drafts = 0+ let markers = 0++ for (const [key, entry] of byRecency) {+ if (entry.text !== null) {+ if (drafts++ < maxDrafts) {+ kept.set(key, entry)+ }+ } else if (now - entry.at < CLEARED_MARKER_TTL_MS && markers++ < MAX_CLEARED_MARKERS) {+ kept.set(key, entry)+ }+ }++ return kept+}++/** Write the stash (and the legacy list after it); `false` when storage refused. */+export function writeDraftStash(entries: StashEntries, legacyKey: string): boolean {+ const drafts: NonNullable<StoredStash['drafts']> = {}+ const cleared: Record<string, number> = {}+ const texts: Record<string, string> = {}++ // Oldest first, so the legacy list keeps its most-recent-last order.+ for (const [key, entry] of [...entries].sort(([, a], [, b]) => a.at - b.at)) {+ if (entry.text === null) {+ cleared[key] = entry.at+ } else {+ drafts[key] = { at: entry.at, text: entry.text }+ texts[key] = entry.text+ }+ }++ try {+ const raw = JSON.stringify({ cleared, drafts })++ if (window.localStorage.getItem(DRAFT_STASH_STORAGE_KEY) !== raw) {+ window.localStorage.setItem(DRAFT_STASH_STORAGE_KEY, raw)+ }++ if (Object.keys(texts).length === 0) {+ window.localStorage.removeItem(legacyKey)+ } else {+ window.localStorage.setItem(legacyKey, JSON.stringify(texts))+ }++ return true+ } catch {+ return false+ }+}diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex da4a9521f36..6de69f4859a 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -5,6 +5,16 @@ import { deriveDraftTitle } from '@/lib/draft-title'import { triggerHaptic } from '@/lib/haptics'import { persistString, storedString } from '@/lib/storage'+import {+ compactDraftStash,+ DRAFT_STASH_STORAGE_KEY,+ newerEntry,+ readDraftStash,+ readLegacyDrafts,+ type StashEntries,+ type StashEntry,+ writeDraftStash+} from './composer-draft-stash'import { recordDislike, recordFriction } from './desktop-metrics'/** Release blob: chip previews created for OS image drops (see #63682). */@@ -302,24 +312,22 @@ const cloneDraft = (draft: SessionDraft): SessionDraft => ({text: draft.text})-function loadPersistedDraftTexts(): Map<string, string> {- try {- const raw = window.localStorage.getItem(SESSION_DRAFTS_STORAGE_KEY)+// What this window last read from or wrote to the shared stash, cleared+// markers included. A reload applies only entries newer than this, and a write+// puts back any entry here that storage has since lost to a stale writer.+let persistedDrafts: StashEntries = readDraftStash()- return new Map(raw ? Object.entries(JSON.parse(raw) as Record<string, string>) : [])- } catch {- return new Map()+// A pre-v4 list is read once, never over a newer entry or a cleared marker.+for (const [key, entry] of readLegacyDrafts(SESSION_DRAFTS_STORAGE_KEY)) {+ if (!persistedDrafts.has(key)) {+ persistedDrafts.set(key, entry)}}-// The draft texts as this window last read or wrote them in the shared stash.-// A cross-window reload applies only what changed there since: a key absent-// from both snapshots was never persisted (an attachment-only draft, one past-// MAX_PERSISTED_DRAFTS), so nobody deleted it.-let persistedDraftTexts = loadPersistedDraftTexts()-const draftsBySession = new Map<string, SessionDraft>(- [...persistedDraftTexts].map(([key, text]) => [key, { attachments: [], text }])+ [...persistedDrafts]+ .filter((entry): entry is [string, StashEntry & { text: string }] => entry[1].text !== null)+ .map(([key, { text }]) => [key, { attachments: [], text }]))/**@@ -404,48 +412,70 @@ function publishDraftTitle(key: string, title: string): void {* whichever window mounted first keeps its stale copy forever, so text typed* in the HUD is simply gone when you return to the app.*- * Merge, don't clobber: only texts the stash changed since this window last- * saw it move, and attachments (memory-only, so no other window can have seen- * or sent them) stay put. An image-only draft is still a draft.+ * Merge, don't clobber: only entries saved after this window's own copy move,+ * and attachments (memory-only, so no other window can have seen or sent them)+ * stay put. An image-only draft is still a draft. An entry this window saved+ * later than storage now shows was overwritten from another window's stale+ * copy, so it is written back rather than taken as sent elsewhere.*/export function reloadPersistedDrafts(): void {- const incoming = loadPersistedDraftTexts()+ syncPersistedDrafts()+}- for (const [key, text] of incoming) {- if (persistedDraftTexts.get(key) === text) {- continue- }+function applyStoredDraft(key: string, entry: StashEntry): void {+ const attachments = draftsBySession.get(key)?.attachments ?? []- draftsBySession.set(key, { attachments: draftsBySession.get(key)?.attachments ?? [], text })- publishDraftTitle(key, deriveDraftTitle(text))+ if (entry.text !== null) {+ draftsBySession.set(key, { attachments, text: entry.text })+ } else if (attachments.length > 0) {+ draftsBySession.set(key, { attachments, text: '' })+ } else {+ draftsBySession.delete(key)}- // A key that vanished from storage was cleared (sent) in the other window.- for (const key of persistedDraftTexts.keys()) {- if (incoming.has(key)) {- continue- }+ publishDraftTitle(key, deriveDraftTitle(entry.text ?? ''))+}++/** Merge storage with this window's copy (plus `local`, this window's new save) and write back what storage lacks. */+function syncPersistedDrafts(local?: { entry: StashEntry; key: string }): void {+ const stored = readDraftStash()+ const merged: StashEntries = new Map()+ let rewrite = Boolean(local)- const attachments = draftsBySession.get(key)?.attachments ?? []+ for (const key of new Set([...stored.keys(), ...persistedDrafts.keys()])) {+ const theirs = stored.get(key)+ const mine = persistedDrafts.get(key)- if (attachments.length > 0) {- draftsBySession.set(key, { attachments, text: '' })- } else {- draftsBySession.delete(key)+ if (newerEntry(theirs, mine)) {+ applyStoredDraft(key, theirs!)+ merged.set(key, theirs!)+ } else if (newerEntry(mine, theirs) && !(mine!.text === null && !theirs)) {+ merged.set(key, mine!)+ rewrite = true+ } else if (theirs) {+ merged.set(key, theirs)}+ }- publishDraftTitle(key, '')+ if (local) {+ merged.set(local.key, local.entry)}- persistedDraftTexts = incoming+ persistedDrafts = rewrite ? compactDraftStash(merged, MAX_PERSISTED_DRAFTS, Date.now()) : merged++ if (rewrite) {+ // Best-effort only — quota/private-mode must never break typing. A failed+ // write stays in persistedDrafts, so the next sync retries it.+ writeDraftStash(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY)+ }}// localStorage `storage` events fire across Electron BrowserWindows of the// same origin, so the other window's write is the sync signal.if (typeof window !== 'undefined') {window.addEventListener('storage', event => {- if (event.key === SESSION_DRAFTS_STORAGE_KEY) {- reloadPersistedDrafts()+ if (event.key === DRAFT_STASH_STORAGE_KEY || event.key === null) {+ syncPersistedDrafts()}})}@@ -490,29 +520,9 @@ export function onComposerDraftSyncRequest(handler: (detail: ComposerDraftSyncDereturn () => window.removeEventListener(DRAFT_SYNC_EVENT, listener)}-function persistDraftTexts() {- try {- const entries = [...draftsBySession]- .filter(([, draft]) => draft.text)- .slice(-MAX_PERSISTED_DRAFTS)- .map(([key, draft]) => [key, draft.text] as const)-- if (entries.length === 0) {- window.localStorage.removeItem(SESSION_DRAFTS_STORAGE_KEY)- } else {- window.localStorage.setItem(SESSION_DRAFTS_STORAGE_KEY, JSON.stringify(Object.fromEntries(entries)))- }-- persistedDraftTexts = new Map(entries)- } catch {- // Best-effort only — quota/private-mode must never break typing.- }-}-export function stashSessionDraft(scope: string | null | undefined, text: string, attachments: ComposerAttachment[]) {const key = draftKey(scope)- // Delete-then-set keeps MRU order for MAX_PERSISTED_DRAFTS eviction.draftsBySession.delete(key)if (text.trim() || attachments.length > 0) {@@ -523,7 +533,16 @@ export function stashSessionDraft(scope: string | null | undefined, text: string$restoredDraftNotice.set(null)}- persistDraftTexts()+ const saved = draftsBySession.get(key)?.text || null+ const previous = persistedDrafts.get(key)++ // Clearing a draft this window never saw saved has nothing to clear.+ if (saved !== null || previous?.text) {+ // Stamped later than any copy of this key this window has seen, so the+ // save wins the merge in every window.+ syncPersistedDrafts({ entry: { at: Math.max(Date.now(), (previous?.at ?? 0) + 1), text: saved }, key })+ }+publishDraftTitle(key, deriveDraftTitle(text))}