Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(composer): stop losing a draft when you leave the chat view

yetonefdd204d50103
diff --git a/server/src/__tests__/composer-drafts.test.ts b/server/src/__tests__/composer-drafts.test.ts
new file mode 100644
index 0000000..023d482
--- /dev/null
+++ b/server/src/__tests__/composer-drafts.test.ts
@@ -0,0 +1,156 @@
+/**
+ * Composer draft persistence policy.
+ *
+ * The bug these pin: desktop kept drafts in component state, and DesktopApp
+ * mounts views conditionally — so switching to Boards unmounted ChatPane and
+ * a half-typed message was gone. Mobile had already learned this and moved
+ * drafts into the store; desktop had drifted. Both now share this module, and
+ * it mirrors to localStorage so a reload can't lose a draft either.
+ *
+ * The module is deliberately free of store/DOM imports so the policy can be
+ * tested directly — these are the rules, not an approximation of them.
+ *
+ * Run: node --import tsx --test server/src/__tests__/composer-drafts.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import {
+ EMPTY_DRAFT, MAX_DRAFTS, MAX_SERIALIZED_BYTES,
+ applyDraftUpdate, evict, isEmptyDraft, parseStoredDrafts, serializeDrafts,
+ type ComposerDrafts,
+} from '../../../src/stores/composerDrafts.js'
+
+const att = { url: 'https://cdn.example/x.pdf', name: 'x.pdf', kind: 'pdf' as const }
+
+// ── the survival contract ───────────────────────────────────────────────────
+
+test('a draft written for one scope is readable back from the same map', () => {
+ const next = applyDraftUpdate({}, 'convo-1', (d) => ({ ...d, text: 'half typed' }))
+ assert.equal(next['convo-1'].text, 'half typed')
+})
+
+test('a thread composer does not share text with its conversation', () => {
+ // The desktop thread drawer is a second composer over the same conversation.
+ let d: ComposerDrafts = {}
+ d = applyDraftUpdate(d, 'convo-1', (c) => ({ ...c, text: 'main' }))
+ d = applyDraftUpdate(d, 'convo-1::thread::m-9', (c) => ({ ...c, text: 'thread' }))
+ assert.equal(d['convo-1'].text, 'main')
+ assert.equal(d['convo-1::thread::m-9'].text, 'thread')
+})
+
+test('an attachment rides along with the text', () => {
+ // Dropping it would strand a file the user already uploaded.
+ const d = applyDraftUpdate({}, 'c', (c) => ({ ...c, attachment: att }))
+ assert.deepEqual(d.c.attachment, att)
+ assert.equal(d.c.text, '')
+})
+
+// ── emptiness + identity ────────────────────────────────────────────────────
+
+test('emptying a draft deletes it rather than leaving a tombstone', () => {
+ // Otherwise every conversation ever opened would hold a MAX_DRAFTS slot.
+ const one = applyDraftUpdate({}, 'c', (d) => ({ ...d, text: 'x' }))
+ const gone = applyDraftUpdate(one, 'c', () => EMPTY_DRAFT)
+ assert.equal('c' in gone, false)
+})
+
+test('clearing text but keeping an attachment keeps the draft', () => {
+ let d = applyDraftUpdate({}, 'c', (c) => ({ text: 'x', attachment: att }))
+ d = applyDraftUpdate(d, 'c', (c) => ({ ...c, text: '' }))
+ assert.deepEqual(d.c, { text: '', attachment: att })
+})
+
+test('an unchanged update returns the SAME object', () => {
+ // Identity is what lets the store skip both a re-render and a storage write.
+ const d = applyDraftUpdate({}, 'c', (x) => ({ ...x, text: 'x' }))
+ assert.equal(applyDraftUpdate(d, 'c', (x) => ({ ...x, text: 'x' })), d)
+})
+
+test('emptying an already-absent scope returns the SAME object', () => {
+ const d: ComposerDrafts = {}
+ assert.equal(applyDraftUpdate(d, 'never-typed', () => EMPTY_DRAFT), d)
+})
+
+// ── eviction ────────────────────────────────────────────────────────────────
+
+test('the map is capped and evicts the least recently touched', () => {
+ let d: ComposerDrafts = {}
+ for (let i = 0; i < MAX_DRAFTS + 5; i++) {
+ d = applyDraftUpdate(d, `c-${i}`, (c) => ({ ...c, text: `draft ${i}` }))
+ }
+ assert.equal(Object.keys(d).length, MAX_DRAFTS)
+ assert.equal('c-0' in d, false, 'oldest should be gone')
+ assert.equal(`c-${MAX_DRAFTS + 4}` in d, true, 'newest should be kept')
+})
+
+test('touching an old draft protects it from eviction', () => {
+ // Ordering IS the LRU record, so an update has to move the key to the end.
+ let d: ComposerDrafts = {}
+ d = applyDraftUpdate(d, 'old', (c) => ({ ...c, text: 'keep me' }))
+ for (let i = 0; i < MAX_DRAFTS - 1; i++) {
+ d = applyDraftUpdate(d, `f-${i}`, (c) => ({ ...c, text: 'x' }))
+ }
+ d = applyDraftUpdate(d, 'old', (c) => ({ ...c, text: 'still typing' }))
+ for (let i = 0; i < 5; i++) {
+ d = applyDraftUpdate(d, `g-${i}`, (c) => ({ ...c, text: 'x' }))
+ }
+ assert.equal(d.old?.text, 'still typing')
+})
+
+// ── what comes back from storage is not trusted ─────────────────────────────
+
+test('a round trip preserves text and attachment', () => {
+ const d = applyDraftUpdate({}, 'c', () => ({ text: 'hello', attachment: att }))
+ assert.deepEqual(parseStoredDrafts(serializeDrafts(d)), d)
+})
+
+test('garbage in storage yields no drafts instead of throwing', () => {
+ for (const raw of [null, '', 'not json', '[]', '"str"', '3', '{"c":null}', '{"c":5}']) {
+ assert.deepEqual(parseStoredDrafts(raw), {}, JSON.stringify(raw))
+ }
+})
+
+test('a malformed attachment is dropped, not replayed into the composer', () => {
+ // This value is handed to the send path; a half-parsed one must not survive.
+ const raw = JSON.stringify({ c: { text: 'hi', attachment: { url: 'u' } } }) // no name/kind
+ assert.deepEqual(parseStoredDrafts(raw), { c: { text: 'hi', attachment: null } })
+})
+
+test('an unknown attachment kind is rejected', () => {
+ const raw = JSON.stringify({ c: { text: 't', attachment: { ...att, kind: 'exe' } } })
+ assert.equal(parseStoredDrafts(raw).c.attachment, null)
+})
+
+test('stored entries that decode to empty are not resurrected', () => {
+ assert.deepEqual(parseStoredDrafts(JSON.stringify({ c: { text: '', attachment: null } })), {})
+})
+
+// ── the storage mirror stays a guest in localStorage ────────────────────────
+
+test('serialization stays under the byte ceiling by dropping oldest drafts', () => {
+ let d: ComposerDrafts = {}
+ for (let i = 0; i < 12; i++) {
+ d = applyDraftUpdate(d, `c-${i}`, (c) => ({ ...c, text: 'x'.repeat(40_000) }))
+ }
+ const json = serializeDrafts(d)
+ assert.ok(json !== null)
+ assert.ok(json.length <= MAX_SERIALIZED_BYTES, `got ${json.length}`)
+ const back = parseStoredDrafts(json)
+ assert.ok('c-11' in back, 'the newest draft must survive the trim')
+})
+
+test('a single draft too large for the ceiling yields null rather than a partial write', () => {
+ const d = applyDraftUpdate({}, 'c', (c) => ({ ...c, text: 'x'.repeat(MAX_SERIALIZED_BYTES + 10) }))
+ assert.equal(serializeDrafts(d), null)
+})
+
+test('evict is a no-op below the cap and preserves identity', () => {
+ const d = applyDraftUpdate({}, 'c', (x) => ({ ...x, text: 'x' }))
+ assert.equal(evict(d), d)
+})
+
+test('isEmptyDraft only calls a draft empty when both halves are', () => {
+ assert.equal(isEmptyDraft({ text: '', attachment: null }), true)
+ assert.equal(isEmptyDraft({ text: ' ', attachment: null }), false)
+ assert.equal(isEmptyDraft({ text: '', attachment: att }), false)
+})
diff --git a/src/desktop/ChatPane.tsx b/src/desktop/ChatPane.tsx
index 47b94e4..5c7567c 100644
--- a/src/desktop/ChatPane.tsx
+++ b/src/desktop/ChatPane.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
import { useApp } from '@/stores/app'
+import { EMPTY_DRAFT, type ComposerDraft } from '@/stores/composerDrafts'
import { useMe } from '@/stores/auth'
import { useConversations } from '@/stores/conversations'
import { useParticipants } from '@/stores/participants'
@@ -457,12 +458,11 @@ function EmojiPopover({ onPick, onClose }: { onPick: (e: string) => void; onClos
)
}
-type ComposerDraftState = {
- text: string
- attachment: ApiAttachment | null
-}
+/** The draft shape is owned by the store — both shells and the persistence
+ * layer have to agree on it, so it can't be redeclared here. */
+type ComposerDraftState = ComposerDraft
-const EMPTY_COMPOSER_DRAFT: ComposerDraftState = { text: '', attachment: null }
+const EMPTY_COMPOSER_DRAFT: ComposerDraftState = EMPTY_DRAFT
function resolveDraftText(next: string | ((prev: string) => string), prev: string) {
return typeof next === 'function' ? next(prev) : next
@@ -565,7 +565,13 @@ export function Composer({
// Draft scope key — distinct namespace for thread mode so swapping between
// the main composer and a thread drawer doesn't share text.
const scopeKey = isThread ? `${convoId}::thread::${threadRootId}` : convoId
- const [draftsByScope, setDraftsByScope] = useState<Record<string, ComposerDraftState>>({})
+ // Drafts live in the app store, not here. DesktopApp mounts views
+ // conditionally (`{view === 'conversations' && <ConversationsLayout />}`), so
+ // switching to Boards or Me unmounts this entire pane — component state
+ // would take the user's half-typed message with it. The store also mirrors
+ // to localStorage, so a reload doesn't lose it either.
+ const draftsByScope = useApp((s) => s.composerDrafts)
+ const updateDraftInStore = useApp((s) => s.updateComposerDraft)
const [uploadingByScope, setUploadingByScope] = useState<Record<string, boolean>>({})
const [uploadErrorsByScope, setUploadErrorsByScope] = useState<Record<string, string>>({})
const editorRef = useRef<RichInputHandle>(null)
@@ -584,23 +590,15 @@ export function Composer({
const uploading = Boolean(uploadingByScope[scopeKey])
const uploadError = uploadErrorsByScope[scopeKey] ?? null
+ // Same signature as before; the empty-draft deletion and the
+ // nothing-changed short-circuit now live in the store so both shells share
+ // one definition of what a draft is.
const updateComposerDraft = useCallback((
targetScope: string,
updater: (current: ComposerDraftState) => ComposerDraftState,
) => {
- setDraftsByScope((prev) => {
- const current = prev[targetScope] ?? EMPTY_COMPOSER_DRAFT
- const next = updater(current)
- if (next.text === current.text && next.attachment === current.attachment) return prev
- if (next.text === '' && next.attachment === null) {
- if (!prev[targetScope]) return prev
- const copy = { ...prev }
- delete copy[targetScope]
- return copy
- }
- return { ...prev, [targetScope]: next }
- })
- }, [])
+ updateDraftInStore(targetScope, updater)
+ }, [updateDraftInStore])
const setDraft = useCallback((nextText: string | ((prev: string) => string)) => {
updateComposerDraft(scopeKey, (current) => ({
diff --git a/src/mobile/MobileChat.tsx b/src/mobile/MobileChat.tsx
index 5f57590..dc17e3c 100644
--- a/src/mobile/MobileChat.tsx
+++ b/src/mobile/MobileChat.tsx
@@ -71,7 +71,7 @@ export function MobileChat() {
// survives MobileChat unmounts (chat → list → chat keeps the half-typed
// message). Send + convo-switch clears the entry; the cleanup happens
// inside `send()` and the convoId effect below.
- const draft = useApp((s) => (convoId ? s.composerDrafts[convoId] ?? '' : ''))
+ const draft = useApp((s) => (convoId ? s.composerDrafts[convoId]?.text ?? '' : ''))
const setComposerDraft = useApp((s) => s.setComposerDraft)
const setDraft = useCallback((text: string) => {
if (!convoId) return
diff --git a/src/stores/app.ts b/src/stores/app.ts
index a9ada5f..164a0bc 100644
--- a/src/stores/app.ts
+++ b/src/stores/app.ts
@@ -1,5 +1,12 @@
import { create } from 'zustand'
+import type { ApiAttachment } from '@/api/client'
import type { ViewKey } from '@/types'
+import {
+ applyDraftUpdate, loadComposerDrafts, saveComposerDrafts,
+ type ComposerDraft,
+} from './composerDrafts'
+
+export type { ComposerDraft }
interface AppState {
view: ViewKey['view']
@@ -42,13 +49,25 @@ interface AppState {
clearPendingJump: () => void
/**
- * Per-conversation composer text drafts. Mobile lives or dies by this:
- * navigating from chat → list → chat unmounts MobileChat, which would
- * blow away a local useState draft. We persist it here so a half-typed
- * message survives the trip. Cleared on send.
+ * Composer drafts, keyed by composer SCOPE (a conversation id, or
+ * `<id>::thread::<rootId>` for the desktop thread drawer).
+ *
+ * Both shells route through here for the same reason: their composer is
+ * unmounted by ordinary navigation. Mobile loses MobileChat on chat → list
+ * → chat; desktop loses the whole ChatPane the moment `view` leaves
+ * `conversations`, because DesktopApp mounts views conditionally. Component
+ * state cannot survive either, so a half-typed message can't live there.
+ * The store is also mirrored to localStorage (see ./composerDrafts), so a
+ * reload or an app restart doesn't lose it either. Cleared on send, and on
+ * sign-out so drafts don't cross accounts on a shared device.
*/
- composerDrafts: Record<string, string>
+ composerDrafts: Record<string, ComposerDraft>
+ /** Text-only convenience for the mobile composer. */
setComposerDraft: (convoId: string, text: string) => void
+ /** Full read-modify-write, used by the desktop composer (which also carries
+ * an attachment). The updater sees the current draft and returns the next. */
+ updateComposerDraft: (scope: string, updater: (current: ComposerDraft) => ComposerDraft) => void
+ clearComposerDrafts: () => void
/**
* Thread drawer state — when set, the right pane shows the thread view
@@ -124,13 +143,22 @@ export const useApp = create<AppState>((set) => ({
jumpToMessage: (messageId) => set({ pendingJumpMessageId: messageId }),
clearPendingJump: () => set({ pendingJumpMessageId: null }),
- composerDrafts: {},
- setComposerDraft: (convoId, text) => set((s) => {
- const next = { ...s.composerDrafts }
- if (text) next[convoId] = text
- else delete next[convoId]
+ composerDrafts: loadComposerDrafts(),
+ updateComposerDraft: (scope, updater) => set((s) => {
+ const next = applyDraftUpdate(s.composerDrafts, scope, updater)
+ // applyDraftUpdate returns the same reference when nothing changed, which
+ // keeps this a no-op render AND avoids a pointless localStorage write.
+ if (next === s.composerDrafts) return s
+ saveComposerDrafts(next)
return { composerDrafts: next }
}),
+ setComposerDraft: (convoId, text) => {
+ useApp.getState().updateComposerDraft(convoId, (current) => ({ ...current, text }))
+ },
+ clearComposerDrafts: () => set(() => {
+ saveComposerDrafts({})
+ return { composerDrafts: {} }
+ }),
openThread: null,
openThreadView: (convoId, rootId) =>
diff --git a/src/stores/auth.ts b/src/stores/auth.ts
index 19e6ed4..f93229c 100644
--- a/src/stores/auth.ts
+++ b/src/stores/auth.ts
@@ -148,6 +148,11 @@ export const useAuth = create<AuthState>((set) => ({
// dead URL.createObjectURL pointing at a freed blob.
void import('@/lib/avatarCache').then(({ clearAvatarCache }) => clearAvatarCache())
void import('@/api/client').then(({ ws }) => ws.close())
+ // Composer drafts outlive a session by design (they're mirrored to
+ // localStorage so a restart can't lose one), which means signing out has
+ // to drop them explicitly — otherwise a half-typed message would be
+ // waiting for whoever signs in next on a shared machine.
+ void import('./app').then(({ useApp }) => useApp.getState().clearComposerDrafts())
// Library stores survive logout otherwise (they're global singletons).
void Promise.all([
import('./documents').then(({ useDocuments }) => useDocuments.getState().reset()),
diff --git a/src/stores/composerDrafts.ts b/src/stores/composerDrafts.ts
new file mode 100644
index 0000000..77ef596
--- /dev/null
+++ b/src/stores/composerDrafts.ts
@@ -0,0 +1,198 @@
+/**
+ * Composer draft persistence — the storage half of `useApp().composerDrafts`.
+ *
+ * A half-typed message is the user's work, and it used to evaporate twice
+ * over: the desktop composer kept drafts in component state, so switching to
+ * Boards and back unmounted the pane and took them with it, and nothing
+ * survived a reload on either shell. Drafts now live in the store (one mount
+ * boundary can't destroy them) and mirror to localStorage (a restart can't
+ * either).
+ *
+ * Kept in its own module so the policy — what a draft is, how many we keep,
+ * how big the mirror may get — is testable without a store or a DOM.
+ */
+import type { ApiAttachment } from '@/api/client'
+
+export interface ComposerDraft {
+ text: string
+ /** An upload the user already paid for. Dropping it on navigation loses a
+ * file that is sitting in storage, so it rides along with the text. */
+ attachment: ApiAttachment | null
+}
+
+/** Keyed by composer SCOPE, not conversation: the desktop thread drawer is a
+ * separate composer over the same conversation (`<id>::thread::<rootId>`) and
+ * must not share text with the main one. Mobile has one composer per
+ * conversation, so its scope is just the conversation id. */
+export type ComposerDrafts = Record<string, ComposerDraft>
+
+export const STORAGE_KEY = 'cumora.composerDrafts'
+
+/** Enough that nobody realistically hits it, small enough that a pathological
+ * client can't turn localStorage into a landfill. Eviction is least-recently-
+ * updated (see `touch`). */
+export const MAX_DRAFTS = 50
+/** Hard ceiling on the serialized mirror. localStorage is a shared ~5MB budget
+ * for the whole origin; drafts are a guest in it, not the tenant. */
+export const MAX_SERIALIZED_BYTES = 256 * 1024
+
+export const EMPTY_DRAFT: ComposerDraft = { text: '', attachment: null }
+
+export function emptyComposerDraft(): ComposerDraft {
+ return EMPTY_DRAFT
+}
+
+export function isEmptyDraft(d: ComposerDraft): boolean {
+ return d.text === '' && d.attachment === null
+}
+
+/** Re-insert a key so it lands at the end of the object's iteration order.
+ * That ordering IS the LRU record — it means a draft needs no timestamp
+ * field, and eviction can just take from the front. */
+function touch(drafts: ComposerDrafts, scope: string, next: ComposerDraft): ComposerDrafts {
+ const copy = { ...drafts }
+ delete copy[scope]
+ copy[scope] = next
+ return copy
+}
+
+/**
+ * Apply an update to one scope, returning the SAME object when nothing
+ * changed so React and the store can both skip the render.
+ *
+ * An emptied draft is deleted rather than stored as `{ text: '' }` — otherwise
+ * every conversation the user ever opened would accumulate a tombstone and
+ * consume one of the MAX_DRAFTS slots.
+ */
+export function applyDraftUpdate(
+ drafts: ComposerDrafts,
+ scope: string,
+ updater: (current: ComposerDraft) => ComposerDraft,
+): ComposerDrafts {
+ const current = drafts[scope] ?? EMPTY_DRAFT
+ const next = updater(current)
+ if (next.text === current.text && next.attachment === current.attachment) return drafts
+ if (isEmptyDraft(next)) {
+ if (!(scope in drafts)) return drafts
+ const copy = { ...drafts }
+ delete copy[scope]
+ return copy
+ }
+ return evict(touch(drafts, scope, next))
+}
+
+/** Trim to MAX_DRAFTS, oldest-touched first. */
+export function evict(drafts: ComposerDrafts): ComposerDrafts {
+ const keys = Object.keys(drafts)
+ if (keys.length <= MAX_DRAFTS) return drafts
+ const copy = { ...drafts }
+ for (const k of keys.slice(0, keys.length - MAX_DRAFTS)) delete copy[k]
+ return copy
+}
+
+/** Coerce whatever is in storage into the current shape. Anything unrecognized
+ * is dropped rather than trusted: this data is replayed into a composer, and
+ * a bad `attachment` would be handed to the send path. */
+export function parseStoredDrafts(raw: string | null): ComposerDrafts {
+ if (!raw) return {}
+ let parsed: unknown
+ try { parsed = JSON.parse(raw) } catch { return {} }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
+ const out: ComposerDrafts = {}
+ for (const [scope, value] of Object.entries(parsed as Record<string, unknown>)) {
+ if (!scope || typeof value !== 'object' || value === null) continue
+ const v = value as { text?: unknown; attachment?: unknown }
+ const text = typeof v.text === 'string' ? v.text : ''
+ const attachment = parseAttachment(v.attachment)
+ const draft: ComposerDraft = { text, attachment }
+ if (!isEmptyDraft(draft)) out[scope] = draft
+ }
+ return evict(out)
+}
+
+function parseAttachment(value: unknown): ApiAttachment | null {
+ if (!value || typeof value !== 'object') return null
+ const a = value as Record<string, unknown>
+ if (typeof a.url !== 'string' || typeof a.name !== 'string') return null
+ const kind = a.kind
+ if (kind !== 'img' && kind !== 'pdf' && kind !== 'file' && kind !== 'fig') return null
+ return {
+ url: a.url,
+ name: a.name,
+ kind,
+ ...(typeof a.mime === 'string' ? { mime: a.mime } : {}),
+ ...(typeof a.size === 'number' ? { size: a.size } : {}),
+ ...(typeof a.key === 'string' ? { key: a.key } : {}),
+ }
+}
+
+/** Serialize within the byte ceiling, dropping oldest-touched drafts until it
+ * fits. Returns null when even one draft is too big to keep. */
+export function serializeDrafts(drafts: ComposerDrafts): string | null {
+ let working = evict(drafts)
+ for (;;) {
+ const json = JSON.stringify(working)
+ if (json.length <= MAX_SERIALIZED_BYTES) return json
+ const keys = Object.keys(working)
+ if (keys.length <= 1) return null
+ const copy = { ...working }
+ delete copy[keys[0]]
+ working = copy
+ }
+}
+
+export function loadComposerDrafts(): ComposerDrafts {
+ if (typeof localStorage === 'undefined') return {}
+ try {
+ return parseStoredDrafts(localStorage.getItem(STORAGE_KEY))
+ } catch {
+ return {}
+ }
+}
+
+let flushTimer: ReturnType<typeof setTimeout> | null = null
+let pending: ComposerDrafts | null = null
+
+function writeNow(): void {
+ if (pending === null) return
+ const drafts = pending
+ pending = null
+ if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
+ try {
+ if (Object.keys(drafts).length === 0) { localStorage.removeItem(STORAGE_KEY); return }
+ const json = serializeDrafts(drafts)
+ if (json === null) localStorage.removeItem(STORAGE_KEY)
+ else localStorage.setItem(STORAGE_KEY, json)
+ } catch {
+ /* private mode, quota, disabled storage — a lost mirror must never break typing */
+ }
+}
+
+/**
+ * Mirror drafts to localStorage on a trailing debounce: typing fires this on
+ * every keystroke, and a synchronous localStorage write per keystroke is a
+ * jank source on long drafts. The `pagehide` flush below is what makes the
+ * debounce safe — otherwise closing the window inside the window would lose
+ * the very keystrokes this exists to protect.
+ */
+export function saveComposerDrafts(drafts: ComposerDrafts): void {
+ if (typeof localStorage === 'undefined') return
+ pending = drafts
+ if (flushTimer) return
+ flushTimer = setTimeout(() => { flushTimer = null; writeNow() }, 400)
+}
+
+/** Write immediately — used by the unload hooks and by tests. */
+export function flushComposerDrafts(): void {
+ writeNow()
+}
+
+if (typeof window !== 'undefined') {
+ // `pagehide` fires on tab close, navigation and (unlike `beforeunload`)
+ // the iOS back/forward cache path. `visibilitychange` covers backgrounding
+ // the app without closing it, which is the common mobile case.
+ window.addEventListener('pagehide', flushComposerDrafts)
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') flushComposerDrafts()
+ })
+}