The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): restore the unsent composer draft when a session is gone
teknium1acccd54c67c5
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex ae540cca9de..34f6bab1732 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -69,6 +69,15 @@ rename sibling of `dropTilesForProfile`. Add any new profile-keyed localStoragefamily to BOTH, or a rename leaves it pointing at a backend that no longerexists ("Couldn't open this session" on every restore).+When an id is verifiably gone anyway (`goneSessionVerdict` → `'draft'`), the+window drops to a fresh draft without toasting or looping — and the unsent+text stashed under the dead key follows it: the verdict calls+`announceGoneSessionDraft(id)` and the composer's swap onto the fresh scope+consumes it once (`adoptGoneSessionDraft`, `store/composer.ts`), seeding the+composer and publishing the inline, undoable `$restoredDraftNotice`. Offer,+don't hijack: no navigation beyond the drop itself, no focus steal, no toast,+and an already non-empty fresh draft is never clobbered.+## Server truth is cached, not ownedThe renderer paints from a cache of backend truth, so it must reconcile, notdiff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsxindex c413d81be75..50c61d19daa 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx@@ -4,9 +4,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'import {+ $restoredDraftNotice,+ announceGoneSessionDraft,announceNewSessionDraftKey,clearSessionDraft,type ComposerAttachment,+ dismissRestoredDraftNotice,mainComposerScope,stashSessionDraft,takeSessionDraft@@ -122,6 +125,42 @@ describe('useComposerDraft — attachment scope stays coherent with the committeclearSessionDraft('session-created')})+ it('carries the unsent draft of a GONE session into the fresh chat once, with an undoable notice (#111868)', () => {+ stashSessionDraft('session-gone', 'typed into a session that no longer exists', [])++ const { rerender } = render(+ <ProbeHarness activeQueueSessionKey="session-gone" onLayoutSnapshot={() => undefined} sessionId="session-gone" />+ )++ // The resume's gone verdict announces the dead key, then drops the window+ // to a fresh draft (route → /new, scope → the pre-session bucket).+ announceGoneSessionDraft('session-gone')+ act(() => {+ rerender(<ProbeHarness activeQueueSessionKey={null} onLayoutSnapshot={() => undefined} sessionId="" />)+ })++ expect(takeSessionDraft(null).text).toBe('typed into a session that no longer exists')+ expect(takeSessionDraft('session-gone').text).toBe('')+ expect($restoredDraftNotice.get()).toEqual({+ fromKey: 'session-gone',+ text: 'typed into a session that no longer exists'+ })++ // Fires once: a later trip through the fresh draft finds nothing to move+ // and does not re-publish the notice the user already dismissed.+ dismissRestoredDraftNotice()+ act(() => {+ rerender(<ProbeHarness activeQueueSessionKey="session-A" onLayoutSnapshot={() => undefined} sessionId="session-A" />)+ })+ act(() => {+ rerender(<ProbeHarness activeQueueSessionKey={null} onLayoutSnapshot={() => undefined} sessionId="" />)+ })++ expect($restoredDraftNotice.get()).toBeNull()+ expect(takeSessionDraft(null).text).toBe('typed into a session that no longer exists')+ clearSessionDraft(null)+ })+it('leaves the pre-session draft in its bucket when the user opens another session from a fresh chat', () => {stashSessionDraft(null, 'still composing a new chat', [])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 423572b1b6f..3d6516c473a 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@@ -14,6 +14,7 @@ import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'import { useStoreSelector } from '@/lib/use-session-slice'import {+ adoptGoneSessionDraft,adoptNewSessionDraft,type ComposerAttachment,type ComposerDraftSyncMode,@@ -464,6 +465,14 @@ export function useComposerDraft({// the route flips the scope, so it is not a usable signal here.if (!draftScopeRef.current && activeQueueSessionKey) {adoptNewSessionDraft(activeQueueSessionKey)+ } else if (!activeQueueSessionKey) {+ // The reverse handoff: a session the user was typing into turned out+ // to be gone and the window dropped to a fresh draft (#111868). The+ // outgoing composer's cleanup has already stashed the live text under+ // the dead key — whether that was this instance's previous scope or an+ // unmounted one's — so move it into the fresh draft when the gone+ // verdict announced it. No announcement, no-op.+ adoptGoneSessionDraft()}draftScopeRef.current = activeQueueSessionKeydiff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex 957aba3f69b..dfb440c6f43 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -71,6 +71,7 @@ import { shouldConvertPasteToAttachment } from './large-paste'import { ActionBadges } from './micro-actions'import { chipTypedPathOnSpace, pathifyRefs } from './path-refs'import { QueuePanel } from './queue-panel'+import { RestoredDraftNotice } from './restored-draft-notice'import {beginComposerComposition,composerPlainText,@@ -1439,6 +1440,11 @@ export function ChatBar({additions beside the "+" menu and before the controls.All four render nothing until something contributes. */}<ContribSlot area={COMPOSER_AREAS.top} />+ <RestoredDraftNotice+ freshDraft={activeQueueSessionKey === null}+ onUndone={clearDraft}+ readLiveText={syncDraftFromEditor}+ /><VoiceActivity state={voiceActivityState} /><VoicePlaybackActivity />{queueEdit && editingQueuedPrompt && (diff --git a/apps/desktop/src/app/chat/composer/restored-draft-notice.tsx b/apps/desktop/src/app/chat/composer/restored-draft-notice.tsxnew file mode 100644index 00000000000..609a4d3cabb--- /dev/null+++ b/apps/desktop/src/app/chat/composer/restored-draft-notice.tsx@@ -0,0 +1,63 @@+import { useStore } from '@nanostores/react'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'+import { $restoredDraftNotice, dismissRestoredDraftNotice, undoRestoredDraft } from '@/store/composer'++interface RestoredDraftNoticeProps {+ /** The composer is showing the fresh draft (no session scope). */+ freshDraft: boolean+ /** Clear the editor after Undo emptied the fresh draft. */+ onUndone: () => void+ /** Latest live editor text — Undo only applies while it is still what was restored. */+ readLiveText: () => string+}++/**+ * "Restored your unsent message" strip above the fresh draft's input+ * (#111868). Offers, never hijacks: no focus move, no navigation, no toast —+ * the text is simply in the composer with a way to put it back. Renders+ * nothing outside the fresh draft, so opening another session hides it+ * without consuming the Undo.+ */+export function RestoredDraftNotice({ freshDraft, onUndone, readLiveText }: RestoredDraftNoticeProps) {+ const notice = useStore($restoredDraftNotice)+ const { t } = useI18n()++ if (!notice || !freshDraft) {+ return null+ }++ return (+ <div+ className="flex items-center justify-between gap-2 rounded-lg border border-[color-mix(in_srgb,var(--dt-composer-ring)_32%,transparent)] bg-accent/18 px-2 py-1"+ data-slot="composer-restored-draft"+ role="status"+ >+ <div className="min-w-0 text-[0.7rem] text-muted-foreground/88">{t.composer.restoredDraftNotice}</div>+ <div className="flex shrink-0 items-center gap-1">+ <Button+ className="h-6 rounded-md px-2 text-[0.68rem]"+ onClick={() => {+ if (undoRestoredDraft(readLiveText())) {+ onUndone()+ }+ }}+ type="button"+ variant="ghost"+ >+ {t.composer.restoredDraftUndo}+ </Button>+ <Button+ aria-label={t.common.close}+ className="h-6 rounded-md px-2 text-[0.68rem]"+ onClick={dismissRestoredDraftNotice}+ type="button"+ variant="ghost"+ >+ ×+ </Button>+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex d211801b9b2..a59532638a7 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -27,7 +27,7 @@ import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'import { setSessionYolo } from '@/lib/yolo-session'import { $clarifyRequests } from '@/store/clarify'-import { announceNewSessionDraftKey, migrateSessionDraft } from '@/store/composer'+import { announceGoneSessionDraft, announceNewSessionDraftKey, migrateSessionDraft } from '@/store/composer'import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'import { $connectionRequests } from '@/store/connection-request'import {@@ -2171,6 +2171,11 @@ export function useSessionActions({return}+ // The id is verifiably dead, but the text the user typed into it is+ // still stashed under that key (#111868). Announce it so the+ // composer's swap onto the fresh draft carries it over with an+ // inline, undoable notice instead of leaving it stranded.+ announceGoneSessionDraft(storedSessionId)startFreshSessionDraft(true)returndiff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 84273e59bb6..4ce519901c9 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2160,6 +2160,8 @@ export const ar = defineLocale({attachments: count => `${count} مرفق`,editingInComposer: 'جار التحرير في صندوق الكتابة',editingQueuedInComposer: 'جار تحرير رسالة في الطابور',+ restoredDraftNotice: 'تمت استعادة رسالتك غير المُرسلة',+ restoredDraftUndo: 'تراجع',queueEdit: 'تحرير الرسالة المجدولة',queueSendNext: 'إرسالها تاليا',queueSteer: 'توجيه — تصحيح الدور الجاري فورا',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex f54b272c541..23445ac2fb6 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3038,6 +3038,8 @@ export const en: Translations = {attachments: count => `${count} attachment${count === 1 ? '' : 's'}`,editingInComposer: 'Editing in composer',editingQueuedInComposer: 'Editing queued turn in composer',+ restoredDraftNotice: 'Restored your unsent message',+ restoredDraftUndo: 'Undo',queueEdit: 'Edit',queueSendNext: 'Next',queueSteer: 'Steer — redirect the live turn now',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 2d6f25a159d..26bb6ccf4b1 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2519,6 +2519,8 @@ export const ja = defineLocale({attachments: count => `${count} 件の添付`,editingInComposer: 'コンポーザーで編集中',editingQueuedInComposer: 'コンポーザーでキュー済みターンを編集中',+ restoredDraftNotice: '未送信のメッセージを復元しました',+ restoredDraftUndo: '元に戻す',queueEdit: '編集',queueSendNext: '次に送信',queueSteer: 'ステア — 現在のターンを今すぐ修正',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 66104c48cbf..2115298a845 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -2794,6 +2794,8 @@ export const ru = defineLocale({attachments: count => `${count} ${RU_NOUN(count, 'вложение', 'вложения', 'вложений')}`,editingInComposer: 'Редактирование в композере',editingQueuedInComposer: 'Редактирование хода в очереди в композере',+ restoredDraftNotice: 'Восстановлено ваше неотправленное сообщение',+ restoredDraftUndo: 'Отменить',queueEdit: 'Изменить',queueSendNext: 'Дальше',queueSteer: 'Направить — изменить текущий ход сейчас',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 30c2474084c..a4e1ee1506b 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2617,6 +2617,8 @@ export interface Translations {attachments: (count: number) => stringeditingInComposer: stringeditingQueuedInComposer: string+ restoredDraftNotice: string+ restoredDraftUndo: stringqueueEdit: stringqueueSendNext: stringqueueSend: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 421362188a9..f324224bd1c 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2502,6 +2502,8 @@ export const zhHant = defineLocale({attachments: count => `${count} 個附件`,editingInComposer: '在輸入框中編輯',editingQueuedInComposer: '在輸入框中編輯排隊回合',+ restoredDraftNotice: '已還原你未送出的訊息',+ restoredDraftUndo: '復原',queueEdit: '編輯',queueSendNext: '下一個',queueSteer: '引導 — 立即修正目前回合',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex dd0818fa4d6..b750eb2e824 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3172,6 +3172,8 @@ export const zh = defineLocale({attachments: count => `${count} 个附件`,editingInComposer: '正在输入框中编辑',editingQueuedInComposer: '正在输入框中编辑排队回合',+ restoredDraftNotice: '已恢复你未发送的消息',+ restoredDraftUndo: '撤销',queueEdit: '编辑',queueSendNext: '下一个',queueSteer: '引导 — 立即修正当前回合',diff --git a/apps/desktop/src/store/composer.test.ts b/apps/desktop/src/store/composer.test.tsindex 0055e5ae334..a0f13584d6f 100644--- a/apps/desktop/src/store/composer.test.ts+++ b/apps/desktop/src/store/composer.test.ts@@ -2,8 +2,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import {$composerAttachments,+ $restoredDraftNotice,$voiceConversationStartRequest,addComposerAttachment,+ adoptGoneSessionDraft,+ announceGoneSessionDraft,clearSessionDraft,type ComposerAttachment,createComposerAttachmentOccurrenceId,@@ -15,6 +18,7 @@ import {stashSessionDraft,takeSessionDraft,takeVoiceConversationStart,+ undoRestoredDraft,updateComposerAttachment} from './composer'@@ -267,6 +271,38 @@ describe('session drafts', () => {expect(takeSessionDraft('session-a').attachments[0]?.label).toBe('doc.pdf')})+ it('restores a gone session draft only into an EMPTY fresh chat, and Undo puts it back where it was (#111868)', () => {+ // Never clobber what the user is already typing in the new chat.+ stashSessionDraft('session-a', 'from the dead session', [])+ stashSessionDraft(null, 'already composing here', [])+ announceGoneSessionDraft('session-a')++ expect(adoptGoneSessionDraft()).toBe(false)+ expect($restoredDraftNotice.get()).toBeNull()+ expect(takeSessionDraft(null).text).toBe('already composing here')+ expect(takeSessionDraft('session-a').text).toBe('from the dead session')++ // Empty fresh chat → restored; Undo (text untouched) returns it to the+ // dead key, so the same recovery path can find it again later.+ clearSessionDraft(null)+ announceGoneSessionDraft('session-a')++ expect(adoptGoneSessionDraft()).toBe(true)+ expect(takeSessionDraft(null).text).toBe('from the dead session')+ expect(undoRestoredDraft('from the dead session')).toBe(true)+ expect(takeSessionDraft(null).text).toBe('')+ expect(takeSessionDraft('session-a').text).toBe('from the dead session')+ expect($restoredDraftNotice.get()).toBeNull()++ // Once the user has edited the restored text, Undo would destroy their+ // work: it only dismisses.+ announceGoneSessionDraft('session-a')+ adoptGoneSessionDraft()++ expect(undoRestoredDraft('from the dead session, edited')).toBe(false)+ expect(takeSessionDraft(null).text).toBe('from the dead session')+ })+it('migrates a tip-keyed draft onto the post-compression tip', () => {const tipBefore = '20260720_062637_ad96b3'const tipAfter = '20260720_071049_a28905'diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex bdaa5d50838..7a581b2272f 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -187,6 +187,17 @@ export interface SessionDraft {const draftKey = (scope: string | null | undefined) => scope?.trim() || NEW_SESSION_DRAFT_KEY+/** Inline "Restored your unsent message" notice for the fresh draft (see+ * `adoptGoneSessionDraft`). `null` = nothing to show. */+export interface RestoredDraftNotice {+ /** The dead stored-session key the text came from. */+ fromKey: string+ /** The text as restored — Undo only applies while the draft still equals it. */+ text: string+}++export const $restoredDraftNotice = atom<RestoredDraftNotice | null>(null)+const cloneDraft = (draft: SessionDraft): SessionDraft => ({attachments: draft.attachments.map(attachment => ({ ...attachment })),text: draft.text@@ -389,6 +400,10 @@ export function stashSessionDraft(scope: string | null | undefined, text: stringif (text.trim() || attachments.length > 0) {draftsBySession.set(key, cloneDraft({ attachments, text }))+ } else if (key === NEW_SESSION_DRAFT_KEY) {+ // The fresh draft was sent or emptied — a restore notice has nothing left+ // to undo.+ $restoredDraftNotice.set(null)}persistDraftTexts()@@ -463,6 +478,94 @@ export function adoptNewSessionDraft(toKey: string | null | undefined): booleanreturn !!announced && announced === toKey?.trim() && migrateSessionDraft(null, toKey)}+/**+ * Recovery for the unsent text of a session that turned out to be GONE+ * (#111868): deleted, or a stale id from a wiped / renamed backend.+ *+ * The resume path already drops such a window to a fresh draft without+ * toasting or looping (62af32efe7c, bounded by `goneSessionVerdict`). The+ * composer's draft stash is keyed per stored session, so the text the user+ * typed into the dead id is not lost — but nothing will ever open that key+ * again, so it is invisible. The gone verdict announces the dead key here;+ * the composer's scope swap (concrete id → the `__new__` bucket) consumes+ * it AFTER the outgoing cleanup stashed the live editor text, so even+ * keystrokes still inside the persist debounce ride along.+ *+ * Offer, don't hijack: the fresh draft is seeded and an inline notice with+ * Undo is published — no navigation, no focus steal, no toast. Fires once:+ * the source key is cleared by the move, so re-opening the dead id later+ * finds nothing to restore.+ */+let announcedGoneSessionDraftKey: string | null = null++export function announceGoneSessionDraft(fromKey: string | null | undefined): void {+ announcedGoneSessionDraftKey = fromKey?.trim() || null+}++/**+ * Consume the announcement when a composer enters the fresh-draft scope.+ * Moves the dead key's draft into the `__new__` bucket and publishes the+ * notice. Declines (no notice) when nothing was announced, the key holds no+ * text, or the user is already composing a new chat — never clobber what+ * they are typing. Keyed on the announcement, not on the composer observing+ * an id → fresh transition: the composer can remount across the drop (a+ * loading route mounts no composer), so the dead scope may never have been+ * this instance's previous scope.+ */+export function adoptGoneSessionDraft(): boolean {+ const announced = announcedGoneSessionDraftKey+ announcedGoneSessionDraftKey = null++ if (!announced) {+ return false+ }++ const source = draftsBySession.get(draftKey(announced))++ if (!source?.text.trim()) {+ return false+ }++ const dest = draftsBySession.get(NEW_SESSION_DRAFT_KEY)++ if (dest && (dest.text.trim() || dest.attachments.length > 0)) {+ return false+ }++ const { attachments, text } = source+ stashSessionDraft(null, text, attachments)+ clearSessionDraft(announced)+ $restoredDraftNotice.set({ fromKey: announced, text })++ return true+}++export function dismissRestoredDraftNotice(): void {+ $restoredDraftNotice.set(null)+}++/**+ * Undo the restore: put the text back under the dead key (where it was,+ * still recoverable by the same path) and empty the fresh draft. Only while+ * the live text is still exactly what was restored — once the user has+ * edited it, Undo would destroy their work, so it only dismisses the notice.+ * Returns whether the fresh draft was emptied (the caller repaints).+ */+export function undoRestoredDraft(liveText: string): boolean {+ const notice = $restoredDraftNotice.get()+ $restoredDraftNotice.set(null)++ if (!notice || liveText !== notice.text) {+ return false+ }++ const current = draftsBySession.get(NEW_SESSION_DRAFT_KEY)+ stashSessionDraft(notice.fromKey, notice.text, current?.attachments ?? [])+ clearSessionDraft(null)++ return true+}+export function setComposerDraft(value: string) {$composerDraft.set(value)}diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 8beec726cf7..65bfbaf62c9 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -47,6 +47,7 @@ The center of the app. You get:- **The same conversation history** as every other Hermes surface — sessions started here resume in the CLI/TUI and vice versa.- **Drag-and-drop files** anywhere in the chat area to attach them to your next message.- **Independent background drafts** — hidden chat tabs can update their drafts without moving the caret or selection in the visible composer.+- **Unsent drafts survive a lost session** — a draft you typed into a chat whose session no longer exists (deleted elsewhere, or a stale tab after a profile rename or wiped backend) is carried into the fresh chat the app falls back to, with an inline **Restored your unsent message** strip above the input. **Undo** puts the text back where it was; nothing is sent, navigated, or focused on your behalf, and the strip appears once per lost draft.- **Directive chip actions** — hover an actionable reference (such as a URL) to reveal its action pill. A short grace period lets you move from the chip to the pill before it dismisses. The pill stays available while you move within it; after leaving, unrelated pointer movement does not delay dismissal. Clicking its action preserves the draft selection.- **A right-hand preview rail** — render web pages, files, and tool outputs side by side while you keep chatting.- **Hide vs. Close for stateful panes** — a zone holding a Browser (or HTML preview) or the Terminal pane offers **Hide** instead of Minimize. Hiding collapses the zone to its restore rail but keeps the pane's body mounted: a live page keeps its unsaved form input, timers, scroll position, and the agent's `drive_preview` automation target; a terminal keeps its running shell and scrollback; and **Restore** shows the same content without a reload. The hidden body is inert — it never takes keyboard shortcuts or steals composer focus. **Close** (the tab's ×) is what actually releases the page or shell.