From 0bc77c551fc68f9d496505a701cfdc5579181d14 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Fri, 6 Nov 2026 09:52:03 -0800 Subject: [PATCH] feat(sidechat): keep a thread's draft across a rebind The upstream draft owner lives and dies with the binding, so leaving a thread threw its words and screenshots away. A thread now owns its draft: a bounded LRU cache (8 threads) keeps the text and the images, restores them when the binding comes back, reuses the preview URLs instead of minting new ones, and revokes a preview when its draft is evicted, sent, or has its image removed. A draft whose prompt is already under way is never restored, so a send cannot be replayed by switching away and back. --- src/client/SideChatView.tsx | 1 + src/client/sidechat-draft.ts | 92 ++++++- tests/sidechat-draft-isolation.spec.tsx | 29 +-- tests/sidechat-draft-persistence.spec.tsx | 279 +++++++++++++++++++++ tests/sidechat-image-composer.spec.tsx | 2 + tests/sidechat-send-while-running.spec.tsx | 2 + 6 files changed, 387 insertions(+), 18 deletions(-) create mode 100644 tests/sidechat-draft-persistence.spec.tsx diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index d258f144..046befcd 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -1923,6 +1923,7 @@ export function SideChatView(props: { void fetchThread(childId) void fetchInfo(childId) } catch (cause) { + draft.abandon(attempt) if (attempt.owner.active) setError(cause instanceof SidebarApiError && cause.code === 'network' ? t('sideChatSendUncertain') : cause instanceof Error ? cause.message : String(cause)) diff --git a/src/client/sidechat-draft.ts b/src/client/sidechat-draft.ts index 846e7b08..6dfad43c 100644 --- a/src/client/sidechat-draft.ts +++ b/src/client/sidechat-draft.ts @@ -17,15 +17,91 @@ export interface SidechatSendAttempt { images: readonly DraftImage[] } +/** + * How many threads keep a saved draft. Bounded because a saved image holds its + * object URL alive for as long as the page lives. + */ +const DRAFT_CACHE_LIMIT = 8 + +/** A thread's draft while nothing is bound to it: the words, and the images whose previews it keeps alive. */ +interface SavedDraft { text: string; images: DraftImage[] } + +/** Saved drafts by thread id, least recently used first (`Map` keeps insertion order). */ +const savedDrafts = new Map() + +/** Owners whose prompt is under way: their draft is dropped, never saved. */ +const sendingOwners = new WeakSet() + +/** Release the previews a dropped draft was the last owner of. */ +function releaseDraftImages(images: readonly DraftImage[]): void { + images.forEach(image => URL.revokeObjectURL(image.preview)) +} + +/** + * Drop every saved draft and release the previews they kept alive. The app has + * no reason to call this (a saved draft is bounded and cheap); it exists so a + * test can start from a clean cache between cases. + */ +export function clearSavedSidechatDrafts(): void { + for (const draft of savedDrafts.values()) releaseDraftImages(draft.images) + savedDrafts.clear() +} + +/** + * Save the draft of a binding that is going away, then keep the cache bounded + * (least recently saved first out). An empty draft is not saved: it would evict + * a real one for a mere visit. + */ +function saveDraft(owner: SidechatDraftOwner): void { + const childId = owner.childId + if (childId === undefined) return + savedDrafts.delete(childId) + if (owner.text !== '' || owner.images.length > 0) savedDrafts.set(childId, { text: owner.text, images: [...owner.images] }) + for (const [id, draft] of savedDrafts) { + if (savedDrafts.size <= DRAFT_CACHE_LIMIT) break + savedDrafts.delete(id) + releaseDraftImages(draft.images) + } +} + +/** + * Give a freshly created owner the draft its thread left behind. The saved copy + * is taken out of the cache: the live owner holds it until the binding goes. + * @returns whether a draft came back (the caller has to redraw). + */ +function restoreDraft(owner: SidechatDraftOwner): boolean { + if (owner.childId === undefined) return false + const saved = savedDrafts.get(owner.childId) + if (saved === undefined) return false + savedDrafts.delete(owner.childId) + owner.text = saved.text + owner.images = [...saved.images] + // Keep the next `add` above the restored ids, or `remove(id)` could drop two images at once. + for (const image of saved.images) { + if (image.id > owner.revision) owner.revision = image.id + } + return true +} + export function useSidechatDraft(childId: string | undefined) { const [, redraw] = useReducer((value: number) => value + 1, 0) const owner = useMemo(() => ({ childId, active: true, revision: 0, text: '', images: [] }), [childId]) useLayoutEffect(() => { owner.active = true + // A draft belongs to its THREAD, not to the binding: pick it back up so + // half-written words and their screenshots survive leaving and returning. + if (restoreDraft(owner)) redraw() return () => { owner.active = false - owner.images.forEach(image => URL.revokeObjectURL(image.preview)) - owner.images = [] + // An unbound tab has nowhere to save to, and a draft whose prompt is + // already under way must not come back (it could be sent twice), so both + // release their previews instead of leaving them to a saved copy. + if (owner.childId === undefined || sendingOwners.has(owner)) { + releaseDraftImages(owner.images) + owner.images = [] + return + } + saveDraft(owner) } }, [owner]) const changed = (): void => { owner.revision++; redraw() } @@ -60,10 +136,19 @@ export function useSidechatDraft(childId: string | undefined) { changed() }, capture(): SidechatSendAttempt { + // The prompt is under way from here: a binding that goes away mid-flight + // must not hand the same words back to be sent a second time. `accept` + // (sent) and `abandon` (failed) both clear the mark. + sendingOwners.add(owner) return { owner, revision: owner.revision, text: owner.text.trim(), images: [...owner.images] } }, + /** The prompt never started (the request failed): the draft is the reader's again. */ + abandon(attempt: SidechatSendAttempt) { + if (attempt.owner === owner) sendingOwners.delete(owner) + }, accept(attempt: SidechatSendAttempt) { if (!owner.active || attempt.owner !== owner) return + sendingOwners.delete(owner) const sent = new Set(attempt.images.map(image => image.id)) owner.images = owner.images.filter(image => { if (!sent.has(image.id)) return true @@ -77,6 +162,9 @@ export function useSidechatDraft(childId: string | undefined) { } export async function encodeSidechatImages(attempt: SidechatSendAttempt): Promise { + // From here on the prompt is under way — the composer's draft for this thread + // belongs to that send now, not to a future visit to the thread. + sendingOwners.add(attempt.owner) const images: SidechatImageUpload[] = [] for (const image of attempt.images) { const data = await new Promise((resolve, reject) => { diff --git a/tests/sidechat-draft-isolation.spec.tsx b/tests/sidechat-draft-isolation.spec.tsx index 3d4b0f45..1809c3db 100644 --- a/tests/sidechat-draft-isolation.spec.tsx +++ b/tests/sidechat-draft-isolation.spec.tsx @@ -17,13 +17,10 @@ * another thread's name. * 1. Re-binding the tab to another thread shows an EMPTY composer (the previous * thread's text must not follow the binding). - * 2. MERGED BEHAVIOUR (v0.30.x): the text does NOT survive a rebind back. The - * owner — text included — is released with the binding, so returning to a - * thread starts from an empty composer. This REPLACES the pre-merge - * per-tab draft map (`draftsRef` / `draftKeyOf`), which restored each - * thread's words verbatim; the upstream owner isolates per thread but does - * not persist across a switch. Asserted below so the difference is visible, - * not silent. + * 2. A draft belongs to its THREAD: re-binding to a thread that was left with + * words brings them back (the saved draft, see `sidechat-draft.ts`), while + * another thread never inherits them. A draft whose prompt went out does + * not come back. * 3. A successful send clears the sending thread's composer, and the draft * reaches exactly that thread. * 4. `openNewThread` (the "+" control) creates the thread through @@ -44,6 +41,7 @@ import { act } from 'react-dom/test-utils' import { renderRoot, type RenderedRoot } from './test-utils.ts' import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' import { SideChatView } from '../src/client/SideChatView.tsx' +import { clearSavedSidechatDrafts } from '../src/client/sidechat-draft.ts' import { t } from '../src/client/locales.ts' import type { Context, SidebarSessionList } from '../src/context-types.ts' import type { SidebarTab } from '../src/client/state.ts' @@ -91,6 +89,7 @@ function tabFor(threadId: string): SidebarTab { let harness: SidechatHarness let ctx: Context +beforeEach(() => { clearSavedSidechatDrafts() }) beforeEach(() => { harness = installSidechatHarness() harness.wire.events = [ @@ -171,7 +170,7 @@ describe('per-thread composer drafts (D8)', () => { } }) - it('releases the draft with the binding instead of restoring it on the way back', async () => { + it('restores a thread’s draft when the binding comes back, without leaking it to the other', async () => { const view = render('t1') try { await flush() @@ -182,17 +181,15 @@ describe('per-thread composer drafts (D8)', () => { await flush(2) expect(composerOf(view).value, 'thread two holds its own words').toBe('draft B') - // Merged behaviour: the owner (text included) is released with the - // binding, so the earlier thread comes back empty — isolation without - // persistence (see the header's contract 2). + // The words belong to the thread, so coming back restores them (contract 2). await bind(view, 't1') - expect(composerOf(view).value, 'a rebind starts from an empty composer').toBe('') + expect(composerOf(view).value, 'the earlier thread gets its own words back').toBe('draft A') } finally { view.unmount() } }) - it('clears the sending thread and leaves the other thread’s composer empty on the way back', async () => { + it('clears the sent draft and keeps the other thread’s draft on the way back', async () => { const view = render('t1') try { await flush() @@ -209,7 +206,7 @@ describe('per-thread composer drafts (D8)', () => { expect(composerOf(view).value, 'a sent draft leaves an empty composer').toBe('') await bind(view, 't2') - expect(composerOf(view).value, 'the other thread never inherits it either').toBe('') + expect(composerOf(view).value, 'the other thread keeps its own draft').toBe('draft B') await bind(view, 't1') expect(composerOf(view).value, 'the sent thread is still empty').toBe('') } finally { @@ -237,9 +234,9 @@ describe('per-thread composer drafts (D8)', () => { expect(composerOf(view).value, 'a brand-new thread has no draft').toBe('') await bind(view, 't1') - expect(composerOf(view).value, 'and nothing is carried back to the old thread').toBe('') + expect(composerOf(view).value, 'the old thread still owns its words').toBe('draft A') await bind(view, 't2') - expect(composerOf(view).value, 'nor to an untouched one').toBe('') + expect(composerOf(view).value, 'nor does an untouched thread gain any').toBe('') } finally { view.unmount() } diff --git a/tests/sidechat-draft-persistence.spec.tsx b/tests/sidechat-draft-persistence.spec.tsx new file mode 100644 index 00000000..92e1863b --- /dev/null +++ b/tests/sidechat-draft-persistence.spec.tsx @@ -0,0 +1,279 @@ +// @vitest-environment jsdom +/** + * A side-chat DRAFT belongs to its thread and must survive leaving it — the + * reader types half a question, clicks another conversation, comes back, and + * the words (and the attached screenshots) are still there. + * + * Why this spec exists: the upstream owner hook (`useSidechatDraft(childId)`, + * v0.30) creates a per-BINDING owner and RELEASES it on unmount — it revokes + * every preview URL and drops the text. That is the right isolation — one + * thread's draft can never appear under another thread's name — but it also + * means switching away loses the draft the reader was mid-way through, which + * the pre-merge per-tab draft map did preserve. + * + * ============================ CONTRACT ============================ + * 1. ROUND TRIP. Unmounting and re-mounting the same `childId` restores the + * draft: the text, and every image with its `id`, its `File` and its + * preview URL (the SAME url — nothing is re-minted, nothing revoked on the + * way out). + * 2. ISOLATION. Two threads never see each other's draft: B starts empty while + * A holds one, and each keeps its own words across its own round trip. + * 3. UNBOUND TABS DO NOT PERSIST (`childId === undefined`): a draft typed with + * no thread bound is gone after a remount. + * 4. BOUNDED MEMORY. The cache holds at most EIGHT threads, least-recently-used + * evicted first; an evicted draft's preview URLs are REVOKED (leaking them + * is a page-level leak the reader can never get back), and re-mounting a + * thread never mints a second preview URL for the same image. + * 5. SENT MEANS GONE. After `accept()` clears the composer, the persisted copy + * is gone too: a remount starts empty (no ghost draft resurrects and gets + * sent twice). + * 6. UNCHANGED SEMANTICS: `remove(id)` still revokes exactly that one preview, + * and threads stay isolated (2). + * ================================================================== + * + * The hook is exercised directly (a probe component, like + * tests/use-sidechat-push.spec.ts) because the contract IS the hook: mount / + * unmount is the whole subject, and driving it through the view would only add + * fetch stubs between the test and the behaviour. + * + * The module keeps its cache across tests, so every test uses its OWN thread + * ids and never relies on a clean slate. + */ +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' +import { createElement, type ReactNode } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { act } from 'react-dom/test-utils' +import { useSidechatDraft } from '../src/client/sidechat-draft.ts' +import type { SidechatImageLimits } from '../src/sidechat-images.ts' +import { setupReactAct } from './test-utils.ts' + +setupReactAct() + +/** The thread cache size this contract pins. */ +const CACHE_LIMIT = 8 + +/** Image limits a composition would report (jsdom never asks the host). */ +const LIMITS = { + maxImageBytes: 5_000_000, + maxImagesPerMessage: 4, + maxMessageImageBytes: 20_000_000, + mediaTypes: ['image/png', 'image/jpeg', 'image/webp', 'image/gif'], +} as unknown as SidechatImageLimits + +/** What the hook hands a caller. */ +type DraftApi = ReturnType + +/** A mounted probe: the hook's current API plus its unmount. */ +interface Mounted { + sink: { api?: DraftApi } + unmount: () => void +} + +/** Every preview URL the stub minted, in order. */ +let minted: string[] = [] +/** Every preview URL the hook released, in order. */ +let revoked: string[] = [] +let createUrl: Mock +let revokeUrl: Mock + +beforeEach(() => { + minted = [] + revoked = [] + createUrl = vi.fn(() => { + const url = `blob:draft/${String(minted.length + 1)}` + minted.push(url) + return url + }) + revokeUrl = vi.fn((url: string) => { revoked.push(url) }) + // jsdom implements neither; the hook is the only owner of these URLs. + Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createUrl }) + Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeUrl }) +}) + +afterEach(() => { + delete (URL as unknown as { createObjectURL?: unknown }).createObjectURL + delete (URL as unknown as { revokeObjectURL?: unknown }).revokeObjectURL +}) + +/** Renders the hook for one childId and publishes its API to the test. */ +function Probe(props: { childId: string | undefined; sink: { api?: DraftApi } }): ReactNode { + props.sink.api = useSidechatDraft(props.childId) + return null +} + +/** + * Mount the hook for one thread. + * @param childId - the bound thread (undefined = an unbound tab). + */ +function mountDraft(childId: string | undefined): Mounted { + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + const sink: { api?: DraftApi } = {} + act(() => { root.render(createElement(Probe, { childId, sink })) }) + return { + sink, + unmount: () => { + act(() => { root.unmount() }) + container.remove() + }, + } +} + +/** The mounted hook's current API. */ +function apiOf(mounted: Mounted): DraftApi { + const api = mounted.sink.api + expect(api, 'the hook rendered').toBeDefined() + return api as DraftApi +} + +/** One small PNG-shaped file (never read, only held). */ +function pngFile(name: string): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'image/png' }) +} + +/** Type a draft into a freshly mounted probe. */ +function typeDraft(mounted: Mounted, text: string): DraftApi { + const api = apiOf(mounted) + act(() => { api.setText(text) }) + return api +} + +/** Attach one image to a freshly mounted probe. */ +function attachImage(mounted: Mounted, name: string): DraftApi { + const api = apiOf(mounted) + act(() => { api.add([pngFile(name)], LIMITS) }) + return api +} + +describe('a draft survives leaving the thread (R-draft)', () => { + it('restores the text and the image after the binding comes back', () => { + const first = mountDraft('roundtrip-thread') + const typed = typeDraft(first, 'half-written question') + const attached = attachImage(first, 'shot.png') + const image = attached.owner.images[0] + expect(image, 'the image is attached').toBeDefined() + expect(typed.owner.text).toBe('half-written question') + first.unmount() + + expect( + revoked, + 'unmounting no longer throws the preview away — the draft still owns it', + ).not.toContain(image?.preview) + + const second = mountDraft('roundtrip-thread') + const back = apiOf(second) + expect(back.owner.text, 'the text comes back').toBe('half-written question') + expect(back.owner.images, 'and the image with it').toHaveLength(1) + expect(back.owner.images[0], 'with the same id and preview').toMatchObject({ + id: image?.id, + preview: image?.preview, + }) + expect(back.owner.images[0]?.file, 'the same File object, not a copy').toBe(image?.file) + second.unmount() + }) + + it('mints no second preview URL when the same thread is mounted again', () => { + const first = mountDraft('stable-thread') + const preview = attachImage(first, 'stable.png').owner.images[0]?.preview + first.unmount() + + for (let round = 0; round < 3; round += 1) { + const again = mountDraft('stable-thread') + expect(apiOf(again).owner.images[0]?.preview, 'the preview is reused').toBe(preview) + again.unmount() + } + expect(createUrl, 'no page-level accumulation of object URLs').toHaveBeenCalledTimes(1) + }) + + it('keeps two threads apart while remembering each one', () => { + const a = mountDraft('isolated-a') + typeDraft(a, 'A draft') + a.unmount() + + const b = mountDraft('isolated-b') + expect(apiOf(b).owner.text, 'B never inherits A').toBe('') + typeDraft(b, 'B draft') + b.unmount() + + const aAgain = mountDraft('isolated-a') + expect(apiOf(aAgain).owner.text, 'A gets its own words back').toBe('A draft') + aAgain.unmount() + + const bAgain = mountDraft('isolated-b') + expect(apiOf(bAgain).owner.text, 'and B its own').toBe('B draft') + bAgain.unmount() + }) + + it('does not persist a draft typed with no thread bound', () => { + const unbound = mountDraft(undefined) + typeDraft(unbound, 'who am I writing to') + unbound.unmount() + + const again = mountDraft(undefined) + expect(apiOf(again).owner.text, 'an unbound tab has nowhere to persist').toBe('') + again.unmount() + }) + + it('evicts the least recently used draft past the cache bound and revokes its previews', () => { + const previews = new Map() + for (let index = 1; index <= CACHE_LIMIT + 1; index += 1) { + const thread = `lru-${String(index)}` + const mounted = mountDraft(thread) + const api = attachImage(mounted, `${thread}.png`) + const preview = api.owner.images[0]?.preview ?? '' + previews.set(thread, preview) + mounted.unmount() + } + + expect( + revoked, + 'the evicted draft releases the previews it was holding', + ).toContain(previews.get(`lru-1`)) + expect( + revoked, + 'a draft still inside the cache is not released', + ).not.toContain(previews.get(`lru-${String(CACHE_LIMIT + 1)}`)) + + // The newest and the second-oldest survive... + for (const thread of [`lru-${String(CACHE_LIMIT + 1)}`, 'lru-2']) { + const survivor = mountDraft(thread) + expect(apiOf(survivor).owner.images, `${thread} is still cached`).toHaveLength(1) + survivor.unmount() + } + // ...and the evicted one is gone for good. + const evicted = mountDraft('lru-1') + expect(apiOf(evicted).owner.images, 'the evicted draft is empty').toHaveLength(0) + expect(apiOf(evicted).owner.text).toBe('') + evicted.unmount() + }) + + it('drops the persisted draft once the message is sent', () => { + const mounted = mountDraft('sent-thread') + const api = typeDraft(mounted, 'ready to send') + const attempt = api.capture() + act(() => { api.accept(attempt) }) + expect(apiOf(mounted).owner.text, 'the composer is cleared').toBe('') + mounted.unmount() + + const again = mountDraft('sent-thread') + expect(apiOf(again).owner.text, 'no ghost draft comes back').toBe('') + again.unmount() + }) + + it('revokes exactly one preview when an image is removed', () => { + const mounted = mountDraft('remove-thread') + const api = apiOf(mounted) + act(() => { api.add([pngFile('one.png'), pngFile('two.png')], LIMITS) }) + const [first, second] = apiOf(mounted).owner.images + expect(first, 'two images attached').toBeDefined() + expect(second).toBeDefined() + + act(() => { apiOf(mounted).remove(first?.id as number) }) + + expect(revoked, 'the removed preview is released').toContain(first?.preview) + expect(revoked, 'the kept one is not').not.toContain(second?.preview) + expect(apiOf(mounted).owner.images, 'and only the other one is left').toHaveLength(1) + mounted.unmount() + }) +}) diff --git a/tests/sidechat-image-composer.spec.tsx b/tests/sidechat-image-composer.spec.tsx index a934dc8f..ed4379bb 100644 --- a/tests/sidechat-image-composer.spec.tsx +++ b/tests/sidechat-image-composer.spec.tsx @@ -5,6 +5,7 @@ import { act } from 'react-dom/test-utils' import { createElement } from 'react' import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' import { SideChatView } from '../src/client/SideChatView.tsx' +import { clearSavedSidechatDrafts } from '../src/client/sidechat-draft.ts' import type { Context } from '../src/context-types.ts' import type { RenderedRoot } from './test-utils.ts' @@ -20,6 +21,7 @@ const revokeUrl = vi.fn() const response = (value: unknown) => ({ ok: true, status: 200, json: async () => ({ ok: true, value }) }) as Response const image = (name = 'shot.png') => new File(['abc'], name, { type: 'image/png' }) +beforeEach(() => { clearSavedSidechatDrafts() }) beforeEach(() => { calls = []; imageReads = []; hold = undefined; rejectSend = false; createUrl.mockClear(); revokeUrl.mockClear() harness = installSidechatHarness({ info: { live: true, images: { available: true, limits } } }) diff --git a/tests/sidechat-send-while-running.spec.tsx b/tests/sidechat-send-while-running.spec.tsx index 6de36be0..0f17fc83 100644 --- a/tests/sidechat-send-while-running.spec.tsx +++ b/tests/sidechat-send-while-running.spec.tsx @@ -39,6 +39,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act } from 'react-dom/test-utils' import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' import { t } from '../src/client/locales.ts' +import { clearSavedSidechatDrafts } from '../src/client/sidechat-draft.ts' import type { Context, SidebarSessionList } from '../src/context-types.ts' /** Every route the view asked for, in order (method names only). */ @@ -115,6 +116,7 @@ function isOffered(button: HTMLButtonElement | undefined): boolean { let harness: SidechatHarness let store: RunningStore +beforeEach(() => { clearSavedSidechatDrafts() }) beforeEach(() => { routes = [] harness = installSidechatHarness()