diff --git a/apps/web/src/components/ChatView.composer.browser.tsx b/apps/web/src/components/ChatView.composer.browser.tsx index 8fdf24f52..b0d7850e4 100644 --- a/apps/web/src/components/ChatView.composer.browser.tsx +++ b/apps/web/src/components/ChatView.composer.browser.tsx @@ -13,7 +13,7 @@ import { createModelCapabilities } from "@threadlines/shared/model"; import { page, userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; -import { useComposerDraftStore } from "../composerDraftStore"; +import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../composerDraftStore"; import { useRoomRecipientStore } from "../rooms"; import { isMacPlatform } from "../lib/utils"; import { useTerminalStateStore } from "../terminalStateStore"; @@ -1983,6 +1983,51 @@ describe("ChatView (full app): composer", () => { } }); + it("still saves a file attached just before the user leaves the thread", async () => { + // Reading a file into a data URL takes a moment; hold this one's read open. + let releaseRead: () => void = () => {}; + const readHeld = new Promise((resolve) => { + releaseRead = resolve; + }); + const realArrayBuffer = File.prototype.arrayBuffer; + const arrayBufferSpy = vi + .spyOn(File.prototype, "arrayBuffer") + .mockImplementation(async function (this: File) { + if (this.name === "left-behind.txt") await readHeld; + return realArrayBuffer.call(this); + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-left-behind" as MessageId, + targetText: "left behind", + }), + }); + try { + const input = await waitForElement( + () => + document.querySelector('input[type="file"][multiple]:not([accept])'), + "The attach-files picker did not render.", + ); + const transfer = new DataTransfer(); + transfer.items.add(new File(["kept"], "left-behind.txt", { type: "text/plain" })); + input.files = transfer.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await expect.element(page.getByTitle("left-behind.txt")).toBeInTheDocument(); + } finally { + // Leaving the thread unmounts its composer while the file is still being read. + await mounted.cleanup(); + } + releaseRead(); + await vi.waitFor( + () => { + expect(localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) ?? "").toContain("left-behind.txt"); + }, + { timeout: 5_000, interval: 50 }, + ); + arrayBufferSpy.mockRestore(); + }); + it("edits a user prompt from a stopped stale turn while preserving attachments and skills", async () => { const sourceMessageId = "msg-user-edit-and-branch" as MessageId; const staleTurnId = "turn-stale-edit-and-branch" as TurnId; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b2e8af5ca..06ecca6f2 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2714,16 +2714,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Image persist effect // ------------------------------------------------------------------ - // Saves the attachments whenever they change; a stale run skips its write. + // Saves the attachments whenever they change. A run is never cancelled: when + // the user switches threads mid-read it still finishes for the thread it + // started in (its composer is gone, so nothing else would), and a run whose + // list a newer change replaced finds that out itself and writes nothing. useEffect(() => { - let cancelled = false; - void saveComposerDraftAttachments(composerDraftTarget, { - attachments: composerAttachments, - cancelled: () => cancelled, - }); - return () => { - cancelled = true; - }; + void saveComposerDraftAttachments(composerDraftTarget, { attachments: composerAttachments }); }, [composerDraftTarget, composerAttachments]); // ------------------------------------------------------------------ diff --git a/apps/web/src/composerDraftAttachmentSave.browser.tsx b/apps/web/src/composerDraftAttachmentSave.browser.tsx index 2f98f96e5..52d87440e 100644 --- a/apps/web/src/composerDraftAttachmentSave.browser.tsx +++ b/apps/web/src/composerDraftAttachmentSave.browser.tsx @@ -7,6 +7,7 @@ import { COMPOSER_DRAFT_ATTACHMENT_MAX_SAVED_BYTES, COMPOSER_DRAFT_STORAGE_KEY, type ComposerAttachment, + hydrateAttachmentsFromPersisted, useComposerDraftStore, } from "./composerDraftStore"; @@ -113,3 +114,95 @@ describe("saveComposerDraftAttachments", () => { ).toEqual([]); }); }); + +describe("drafts kept across tabs and reloads", () => { + const otherThread = scopeThreadRef(EnvironmentId.make("env-save"), ThreadId.make("thread-other")); + const settle = () => new Promise((resolve) => setTimeout(resolve, 500)); + const storedDrafts = () => + ( + JSON.parse(localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) ?? "{}") as { + state?: { draftsByThreadKey?: Record }; + } + ).state?.draftsByThreadKey ?? {}; + + afterEach(() => { + useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); + localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY); + }); + + /** Another tab's write: it changes storage and leaves its own writer stamp. */ + function writeFromAnotherTab(edit: (drafts: Record) => void) { + const raw = JSON.parse(localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) ?? "{}") as { + state: { draftsByThreadKey: Record }; + }; + edit(raw.state.draftsByThreadKey); + localStorage.setItem(COMPOSER_DRAFT_STORAGE_KEY, JSON.stringify(raw)); + localStorage.setItem(`${COMPOSER_DRAFT_STORAGE_KEY}:writer`, "another-tab:1"); + } + + it("keeps a draft another tab changed when this tab saves a different one", async () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(threadRef, "first draft, from this tab"); + store.setPrompt(otherThread, "second draft, from this tab"); + await settle(); + + // Another tab edits the first draft and writes every draft it holds. No + // storage event is needed: this tab sees the other writer's stamp. + writeFromAnotherTab((drafts) => { + drafts[scopedThreadKey(threadRef)]!.prompt = "first draft, other tab"; + }); + + // This tab still holds its old copy of the first draft, and edits the second. + store.setPrompt(otherThread, "second draft, edited here"); + await settle(); + + const drafts = storedDrafts(); + expect(drafts[scopedThreadKey(threadRef)]?.prompt).toBe("first draft, other tab"); + expect(drafts[scopedThreadKey(otherThread)]?.prompt).toBe("second draft, edited here"); + }); + + it("keeps a draft another tab filled when this tab cleans it up as empty", async () => { + const store = useComposerDraftStore.getState(); + // Empty here: only a mode, which is kept but holds nothing the user wrote. + store.setRuntimeMode(threadRef, "full-access"); + store.setPrompt(otherThread, "unrelated"); + await settle(); + + writeFromAnotherTab((drafts) => { + drafts[scopedThreadKey(threadRef)]!.prompt = "typed in the other tab"; + }); + + // This tab drops the draft it sees as empty (as starting a new thread does). + useComposerDraftStore.setState((state) => { + const { [scopedThreadKey(threadRef)]: _dropped, ...rest } = state.draftsByThreadKey; + return { draftsByThreadKey: rest }; + }); + store.setPrompt(otherThread, "unrelated, edited"); + await settle(); + + expect(storedDrafts()[scopedThreadKey(threadRef)]?.prompt).toBe("typed in the other tab"); + }); + + it("brings an empty file back after a reload", async () => { + const store = useComposerDraftStore.getState(); + const empty = file("empty", 0); + store.addAttachments(threadRef, [empty]); + await saveComposerDraftAttachments(threadRef); + await settle(); + + // A reload: the draft comes back from storage alone. + useComposerDraftStore.setState({ draftsByThreadKey: {} }); + await useComposerDraftStore.persist.rehydrate(); + + const restored = useComposerDraftStore.getState().getComposerDraft(threadRef)?.attachments; + expect(restored?.map((attachment) => [attachment.id, attachment.sizeBytes])).toEqual([ + ["empty", 0], + ]); + // A broken record of size 0 is still not a file. + expect( + hydrateAttachmentsFromPersisted([ + { id: "broken", name: "x", mimeType: "text/plain", sizeBytes: 0, dataUrl: "garbage," }, + ]), + ).toEqual([]); + }); +}); diff --git a/apps/web/src/composerDraftAttachmentSave.ts b/apps/web/src/composerDraftAttachmentSave.ts index d3126f9d1..c809b39e8 100644 --- a/apps/web/src/composerDraftAttachmentSave.ts +++ b/apps/web/src/composerDraftAttachmentSave.ts @@ -30,7 +30,7 @@ async function dataUrlOf(file: File): Promise { * An attachment already saved stays saved, whatever its size: it keeps the * data it was saved with. A new one is tried only if it could ever fit * (`composerAttachmentFitsDraftStorage`); a bigger one would only fail the - * write. `cancelled` lets a caller whose run went stale skip the write. + * write. * * Reading files takes a while. If the draft's attachments changed meanwhile * (one removed, another pasted), this run's list is old: it writes nothing @@ -42,7 +42,6 @@ export async function saveComposerDraftAttachments( options: { /** The draft's attachments as the caller sees them; read from the draft when left out. */ readonly attachments?: ReadonlyArray; - readonly cancelled?: () => boolean; } = {}, ): Promise<"saved" | "stale"> { const store = useComposerDraftStore.getState(); @@ -79,7 +78,6 @@ export async function saveComposerDraftAttachments( // Unreadable now: left unsaved. } } - if (options.cancelled?.()) return "stale"; const now = useComposerDraftStore.getState().getComposerDraft(target); if ((now?.attachments ?? []).map((attachment) => attachment.id).join("\u0000") !== listed) { return "stale"; diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 24d4b13f2..391265bd1 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -63,7 +63,7 @@ import { type PickedElementContextDraft, } from "./lib/pickedElementContext"; import { create } from "zustand"; -import { persist } from "zustand/middleware"; +import { persist, type StorageValue } from "zustand/middleware"; import { useShallow } from "zustand/react/shallow"; import { createDebouncedJSONStorage, @@ -86,6 +86,129 @@ export type DraftId = typeof DraftId.Type; const COMPOSER_PERSIST_DEBOUNCE_MS = 300; +/** + * What this tab changed since its last successful draft write, found by the + * store's own object identity (an untouched draft keeps its object). Another + * tab's write changes storage under this tab; then each write keeps every + * draft this tab did not change as storage has it, so one tab never writes + * its stale copy of a draft another tab edited, sent or cleared. Two tabs + * changing the same draft is the one case left: the last write wins for it. + */ +const changedSinceWrite = { + drafts: new Set(), + draftThreads: new Set(), + projectDraftKeys: new Set(), + sticky: false, + /** + * Drafts this tab removed while they held nothing in its own copy: cleanup + * (a new thread replacing an empty draft), not a send or a clear. Another + * tab may have typed into one meanwhile, so the merge keeps a stored copy + * that has content rather than deleting it. + */ + emptiedRemovals: new Set(), +}; + +function resetChangedSinceWrite() { + changedSinceWrite.drafts.clear(); + changedSinceWrite.draftThreads.clear(); + changedSinceWrite.projectDraftKeys.clear(); + changedSinceWrite.sticky = false; + changedSinceWrite.emptiedRemovals.clear(); +} + +/** A saved draft the user put something into: text, files or context chips. */ +function persistedDraftHasUserContent( + draft: PersistedComposerThreadDraftState | undefined, +): boolean { + return ( + draft !== undefined && + (draft.prompt.trim().length > 0 || + draft.attachments.length > 0 || + (draft.terminalContexts?.length ?? 0) > 0 || + (draft.transcriptHighlightContexts?.length ?? 0) > 0 || + (draft.fileSelectionContexts?.length ?? 0) > 0 || + (draft.pickedElementContexts?.length ?? 0) > 0) + ); +} + +function noteChangedKeys( + changed: Set, + next: Readonly>, + previous: Readonly>, +) { + if (next === previous) return; + for (const key of Object.keys(next)) { + if (next[key] !== previous[key]) changed.add(key); + } + for (const key of Object.keys(previous)) { + if (!(key in next)) changed.add(key); + } +} + +/** + * `stored`'s entries, with this tab's changed keys taken from `next` (or + * removed). `keepStored` names removals to skip: the stored entry stays. + */ +function mergeChangedEntries( + stored: Readonly> | undefined, + next: Readonly>, + changed: ReadonlySet, + keepStored: (key: string) => boolean = () => false, +): Record { + const merged: Record = { ...stored }; + for (const key of changed) { + const value = next[key]; + if (value !== undefined) merged[key] = value; + else if (!keepStored(key)) delete merged[key]; + } + return merged; +} + +function mergeComposerDraftsWithStored( + next: StorageValue, + stored: StorageValue | null, +): StorageValue { + // Another version's shape can't be merged into; this tab's whole state wins, as before. + if (stored === null || stored.version !== next.version || typeof stored.state !== "object") { + return next; + } + // The last-used model is one value: this tab's if it changed it, else storage's. + const sticky = changedSinceWrite.sticky ? next.state : stored.state; + // A draft this tab cleaned up as empty, which another tab has since filled: + // keep it and its session, so the other tab's text stays a draft. + const keepFilledElsewhere = (key: string) => + changedSinceWrite.emptiedRemovals.has(key) && + persistedDraftHasUserContent(stored.state.draftsByThreadKey?.[key]); + return { + ...next, + state: { + draftsByThreadKey: mergeChangedEntries( + stored.state.draftsByThreadKey, + next.state.draftsByThreadKey, + changedSinceWrite.drafts, + keepFilledElsewhere, + ), + draftThreadsByThreadKey: mergeChangedEntries( + stored.state.draftThreadsByThreadKey, + next.state.draftThreadsByThreadKey, + changedSinceWrite.draftThreads, + keepFilledElsewhere, + ), + logicalProjectDraftThreadKeyByLogicalProjectKey: mergeChangedEntries( + stored.state.logicalProjectDraftThreadKeyByLogicalProjectKey, + next.state.logicalProjectDraftThreadKeyByLogicalProjectKey, + changedSinceWrite.projectDraftKeys, + ), + ...(sticky.stickyModelSelectionByProvider !== undefined + ? { stickyModelSelectionByProvider: sticky.stickyModelSelectionByProvider } + : {}), + ...(sticky.stickyActiveProvider !== undefined + ? { stickyActiveProvider: sticky.stickyActiveProvider } + : {}), + }, + }; +} + // Every keystroke is a store update, so serializing waits for the debounce too. const composerDebouncedStorage = createDebouncedJSONStorage( withLegacyFallbackStorage( @@ -94,6 +217,7 @@ const composerDebouncedStorage = createDebouncedJSONStorage;base64,` and comes back as one; anything + // else without a payload is broken. + return commaIndex !== -1 && attachment.sizeBytes === 0 && header.startsWith("data:") + ? new File([], attachment.name, { type: attachment.mimeType }) + : null; } try { const isBase64 = header.includes(";base64"); @@ -4135,6 +4263,8 @@ const composerDraftStore = create()( name: COMPOSER_DRAFT_STORAGE_KEY, version: COMPOSER_DRAFT_STORAGE_VERSION, storage: composerDebouncedStorage, + // Loading from storage is not a change of this tab's. + onRehydrateStorage: () => () => resetChangedSinceWrite(), migrate: migratePersistedComposerDraftStoreState, partialize: partializeComposerDraftStoreState, merge: (persistedState, currentState) => { @@ -4167,6 +4297,46 @@ const composerDraftStore = create()( export const useComposerDraftStore = composerDraftStore; +composerDraftStore.subscribe((state, previous) => { + if (state.draftsByThreadKey !== previous.draftsByThreadKey) { + for (const key of Object.keys(previous.draftsByThreadKey)) { + if ( + !(key in state.draftsByThreadKey) && + !composerDraftHasUserContent(previous.draftsByThreadKey[key]) + ) { + changedSinceWrite.emptiedRemovals.add(key); + } + } + } + if (state.draftThreadsByThreadKey !== previous.draftThreadsByThreadKey) { + for (const key of Object.keys(previous.draftThreadsByThreadKey)) { + if ( + !(key in state.draftThreadsByThreadKey) && + !composerDraftHasUserContent(previous.draftsByThreadKey[key]) + ) { + changedSinceWrite.emptiedRemovals.add(key); + } + } + } + noteChangedKeys(changedSinceWrite.drafts, state.draftsByThreadKey, previous.draftsByThreadKey); + noteChangedKeys( + changedSinceWrite.draftThreads, + state.draftThreadsByThreadKey, + previous.draftThreadsByThreadKey, + ); + noteChangedKeys( + changedSinceWrite.projectDraftKeys, + state.logicalProjectDraftThreadKeyByLogicalProjectKey, + previous.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + if ( + state.stickyModelSelectionByProvider !== previous.stickyModelSelectionByProvider || + state.stickyActiveProvider !== previous.stickyActiveProvider + ) { + changedSinceWrite.sticky = true; + } +}); + export function useComposerThreadDraft(threadRef: ComposerThreadTarget): ComposerThreadDraftState { return useComposerDraftStore((state) => { return getComposerDraftState(state, threadRef) ?? EMPTY_THREAD_DRAFT; diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.ts index 79cb8ff26..abfd78bc2 100644 --- a/apps/web/src/lib/storage.ts +++ b/apps/web/src/lib/storage.ts @@ -87,27 +87,101 @@ function parseStorageValue(raw: string | null): StorageValue | null { return raw === null ? null : (JSON.parse(raw) as StorageValue); } +/** + * How a store shares its storage key with other tabs. Every tab holds the + * whole persisted state and writes all of it, so without this a tab writes + * its stale copy of what another tab changed. See `createDebouncedJSONStorage`. + */ +export interface StoredValueMerge { + /** + * What to write, given what this tab wants stored and what storage holds + * now. `stored` is read once another tab has written the key since this tab + * loaded it (this tab's copy of the rest may be stale from then on); before + * that it is null and `next` can go as is. + */ + readonly mergeWithStored: ( + next: StorageValue, + stored: StorageValue | null, + ) => StorageValue; + /** The write landed: whatever the store tracks since its last write starts over. */ + readonly onWritten: () => void; +} + +/** A random id for this tab's writes, so it can tell another tab's apart. */ +const tabWriterId = (() => { + const bytes = new Uint8Array(8); + globalThis.crypto?.getRandomValues?.(bytes); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("") || "tab"; +})(); + /** * A zustand persist storage that serializes and writes at most once per * `debounceMs`. Use it in place of `createJSONStorage` for stores that change * on every keystroke: that helper runs `JSON.stringify` on every state change * before its storage sees the value, so debouncing only the write still pays * for serializing the whole persisted state, pasted images included, per key. + * + * With `merge`, every write also leaves a small stamp (`:writer`) saying + * which tab wrote last. Before each write the tab reads that stamp (a few + * bytes); once it is another tab's, this tab's copy may be stale, and from + * then on every write reads storage first and lets the store keep the other + * tab's changes. With one tab open nothing large is read. */ export function createDebouncedJSONStorage( baseStorage: Partial | null | undefined, debounceMs: number = 300, + merge?: StoredValueMerge, ): DebouncedPersistStorage { const resolvedStorage = resolveStorage(baseStorage); + const stampKey = (name: string) => `${name}:writer`; + const readStamp = (name: string): string | null => { + try { + const stamp = resolvedStorage.getItem(stampKey(name)); + return typeof stamp === "string" ? stamp : null; + } catch { + return null; + } + }; + // The stamp this tab last saw or wrote, per key: storage matched this tab then. + const knownStamps = new Map(); + // Keys another tab wrote after this tab loaded them: every later write merges. + const sharedKeys = new Set(); + let writes = 0; + const readStored = (name: string): StorageValue | null => { + try { + const raw = resolvedStorage.getItem(name); + return typeof raw === "string" ? parseStorageValue(raw) : null; + } catch { + return null; + } + }; const debouncedSetItem = new Debouncer( (name: string, value: StorageValue) => { - resolvedStorage.setItem(name, JSON.stringify(value)); + if (!merge) { + resolvedStorage.setItem(name, JSON.stringify(value)); + return; + } + if (knownStamps.has(name) && readStamp(name) !== knownStamps.get(name)) { + sharedKeys.add(name); + } + const stored = sharedKeys.has(name) ? readStored(name) : null; + resolvedStorage.setItem(name, JSON.stringify(merge.mergeWithStored(value, stored))); + const stamp = `${tabWriterId}:${++writes}`; + try { + resolvedStorage.setItem(stampKey(name), stamp); + } catch { + // The stamp is small; if even it can't be written, the next write merges. + } + knownStamps.set(name, stamp); + merge.onWritten(); }, { wait: debounceMs }, ); return { getItem: (name) => { + // What this tab loads is what storage holds: in step with the last writer. + if (merge) knownStamps.set(name, readStamp(name)); const raw = resolvedStorage.getItem(name); return raw instanceof Promise ? raw.then((value) => parseStorageValue(value))