diff --git a/apps/web/src/components/ChatView.composer.browser.tsx b/apps/web/src/components/ChatView.composer.browser.tsx index b0d7850e4..4a0f419b8 100644 --- a/apps/web/src/components/ChatView.composer.browser.tsx +++ b/apps/web/src/components/ChatView.composer.browser.tsx @@ -14,6 +14,13 @@ import { page, userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../composerDraftStore"; +import { + clearAttachmentBlobsForTest, + readAttachmentBlob, + setAttachmentBlobBackendForTest, + stashAttachmentBlobKey, +} from "../lib/attachmentBlobStore"; +import { PROMPT_STASH_STORAGE_KEY, usePromptStashStore } from "../promptStashStore"; import { useRoomRecipientStore } from "../rooms"; import { isMacPlatform } from "../lib/utils"; import { useTerminalStateStore } from "../terminalStateStore"; @@ -2172,4 +2179,99 @@ describe("ChatView (full app): composer", () => { await mounted.cleanup(); } }); + + it("stashes and restores a large image via IndexedDB without base64 in localStorage, and updates the unsaved tooltip copy", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-stash-idb" as MessageId, + targetText: "stash test", + }), + }); + + try { + const input = await waitForElement( + () => + document.querySelector('input[type="file"][multiple]:not([accept])'), + "The attach-files picker did not render.", + ); + const bigBytes = new Uint8Array(4_000_000); + // PNG signature followed by payload so it's a valid large image attachment. + bigBytes.set([137, 80, 78, 71, 13, 10, 26, 10]); + const transfer = new DataTransfer(); + transfer.items.add(new File([bigBytes], "retina-hero.png", { type: "image/png" })); + input.files = transfer.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + + await vi.waitFor(() => { + expect( + useComposerDraftStore.getState().getComposerDraft(THREAD_REF)?.attachments, + ).toHaveLength(1); + }); + + // Stash the image-only prompt via the "+" menu. + await page.getByRole("button", { name: "Add to message" }).click(); + await page.getByRole("menuitem", { name: /Stash this prompt/ }).click(); + + await vi.waitFor(() => { + expect(usePromptStashStore.getState().entries).toHaveLength(1); + expect( + useComposerDraftStore.getState().getComposerDraft(THREAD_REF)?.attachments ?? [], + ).toHaveLength(0); + }); + + const stashed = usePromptStashStore.getState().entries[0]!; + expect(stashed.attachments).toHaveLength(1); + expect(stashed.attachments[0]?.dataUrl).toBeUndefined(); + // localStorage stays tiny (metadata only, no base64). + expect((localStorage.getItem(PROMPT_STASH_STORAGE_KEY) ?? "").length).toBeLessThan(2_000); + const stashKey = stashAttachmentBlobKey(stashed.id, stashed.attachments[0]!.id); + expect((await readAttachmentBlob(stashKey)).status).toBe("ok"); + + // Restore it from the Stashed prompts submenu. + await page.getByRole("button", { name: "Add to message" }).click(); + await page.getByRole("menuitem", { name: /Stashed prompts/ }).click(); + await page.getByRole("menuitem", { name: /1 attachment/ }).click(); + + await vi.waitFor(() => { + const restored = useComposerDraftStore.getState().getComposerDraft(THREAD_REF)?.attachments; + expect(restored).toHaveLength(1); + expect(restored?.[0]?.name).toBe("retina-hero.png"); + expect(restored?.[0]?.sizeBytes).toBe(4_000_000); + }); + await vi.waitFor(async () => { + expect((await readAttachmentBlob(stashKey)).status).toBe("not-found"); + }); + + // Now simulate IndexedDB rejecting writes: warning icon tooltip says "on reload". + setAttachmentBlobBackendForTest({ + put: async () => false, + get: async () => ({ status: "error" }), + deleteMany: async () => {}, + listMeta: async () => null, + }); + const failedTransfer = new DataTransfer(); + failedTransfer.items.add(new File(["tiny"], "unsaved.txt", { type: "text/plain" })); + input.files = failedTransfer.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + + const warningIcon = await waitForElement( + () => + document.querySelector('[aria-label="Draft attachment may not persist"]'), + "Unsaved attachment warning icon did not render.", + ); + await page.elementLocator(warningIcon).hover(); + await expect + .element( + page.getByText("Draft attachment could not be saved locally and may be lost on reload."), + ) + .toBeVisible(); + } finally { + setAttachmentBlobBackendForTest(null); + usePromptStashStore.setState({ entries: [] }); + localStorage.removeItem(PROMPT_STASH_STORAGE_KEY); + await clearAttachmentBlobsForTest(); + await mounted.cleanup(); + } + }); }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 27dd18116..d423b3e84 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -61,7 +61,16 @@ import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { Debouncer } from "@tanstack/react-pacer"; import { useQueryClient } from "@tanstack/react-query"; import * as Option from "effect/Option"; -import { memo, useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; +import { + memo, + useCallback, + useEffect, + useEffectEvent, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; import { useNavigate, useSearch } from "@tanstack/react-router"; import { useShallow } from "zustand/react/shallow"; import { useGitStatus } from "~/lib/gitStatusState"; @@ -259,12 +268,14 @@ import { import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRoutes"; import { type ComposerAttachment, + composerAttachmentFromFile, composerDraftActiveModelSelection, type DraftThreadEnvMode, - hydrateAttachmentsFromPersisted, + ensureDraftAttachmentsHydrated, useComposerDraftStore, type DraftId, } from "../composerDraftStore"; +import { hasPendingStashRestore, waitForPendingStashRestore } from "../promptStashStore"; import { appendTerminalContextsToPrompt, deriveDisplayedUserMessageState, @@ -1181,6 +1192,14 @@ export default function ChatView(props: ChatViewProps) { : null, ); const promptRef = useRef(""); + const activeComposerDraftTargetKey = + typeof composerDraftTarget === "string" + ? composerDraftTarget + : scopedThreadKey(composerDraftTarget); + const activeComposerDraftTargetKeyRef = useRef(activeComposerDraftTargetKey); + useLayoutEffect(() => { + activeComposerDraftTargetKeyRef.current = activeComposerDraftTargetKey; + }, [activeComposerDraftTargetKey]); const composerAttachmentsRef = useRef([]); const composerTerminalContextsRef = useRef([]); const composerTranscriptHighlightContextsRef = useRef([]); @@ -5441,20 +5460,78 @@ export default function ChatView(props: ChatViewProps) { return; } if (replyingInChatTo === null && pendingUserInputs.some(isBlockingUserInput)) return; + + const sendTargetKey = activeComposerDraftTargetKey; + const preSendDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + const needsPreSendHydration = + hasPendingStashRestore(sendTargetKey) || + (preSendDraft?.hydratingAttachmentIds.length ?? 0) > 0 || + (preSendDraft?.failedHydrationAttachmentIds.length ?? 0) > 0; + if (needsPreSendHydration) { + // Hold the send guard across the wait so a rapid second Enter press + // cannot start a duplicate send while IndexedDB blobs finish loading. + sendInFlightRef.current = true; + try { + await waitForPendingStashRestore(sendTargetKey); + await ensureDraftAttachmentsHydrated(composerDraftTarget, { retryFailed: true }); + } finally { + sendInFlightRef.current = false; + } + if (activeComposerDraftTargetKeyRef.current !== sendTargetKey) { + return; + } + } + + const hydratedDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + if (hydratedDraft && hydratedDraft.failedHydrationAttachmentIds.length > 0) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Couldn't load attached files", + description: + "Browser storage could not load one or more attached files. Re-attach them or try again before sending.", + }), + ); + return; + } + const sendCtx = composerRef.current?.getSendContext(); if (!sendCtx) return; - const { - images: composerAttachments, - terminalContexts: composerTerminalContexts, - transcriptHighlightContexts: composerTranscriptHighlightContexts, - fileSelectionContexts: composerFileSelectionContexts, - pickedElementContexts: composerPickedElementContexts, - drawingContexts: composerDrawingContexts, - selectedModel: ctxSelectedModel, - selectedModelSelection: ctxSelectedModelSelection, - skillReferences: composerSkillReferences, - } = sendCtx; - const promptForSend = promptRef.current; + // When we waited for async hydration or stash restore, read the live draft + // directly from the store so refs updated by React effects cannot lag behind. + const composerAttachments = needsPreSendHydration + ? (hydratedDraft?.attachments ?? []) + : sendCtx.images; + const composerTerminalContexts = needsPreSendHydration + ? (hydratedDraft?.terminalContexts ?? sendCtx.terminalContexts) + : sendCtx.terminalContexts; + const composerTranscriptHighlightContexts = needsPreSendHydration + ? (hydratedDraft?.transcriptHighlightContexts ?? sendCtx.transcriptHighlightContexts) + : sendCtx.transcriptHighlightContexts; + const composerFileSelectionContexts = needsPreSendHydration + ? (hydratedDraft?.fileSelectionContexts ?? sendCtx.fileSelectionContexts) + : sendCtx.fileSelectionContexts; + const composerPickedElementContexts = needsPreSendHydration + ? (hydratedDraft?.pickedElementContexts ?? sendCtx.pickedElementContexts) + : sendCtx.pickedElementContexts; + const composerDrawingContexts = sendCtx.drawingContexts; + const ctxSelectedModel = sendCtx.selectedModel; + const ctxSelectedModelSelection = sendCtx.selectedModelSelection; + const composerSkillReferences = sendCtx.skillReferences; + if ( + composerAttachments.some((attachment) => attachment.type === "image") && + !sendCtx.selectedModelSupportsImages + ) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Selected model doesn't accept images", + }), + ); + return; + } + const promptForSend = + needsPreSendHydration && hydratedDraft ? hydratedDraft.prompt : promptRef.current; const { trimmedPrompt: trimmed, sendableTerminalContexts: sendableComposerTerminalContexts, @@ -6459,32 +6536,30 @@ export default function ChatView(props: ChatViewProps) { const loadQueuedAttachmentsForComposer = async ( attachments: OrchestrationQueuedFollowUp["attachments"], ): Promise<{ restored: ComposerAttachment[]; failedCount: number }> => { - const persisted = await Promise.all( + const loaded = await Promise.all( attachments.map(async (attachment) => { try { const blob = await loadChatAttachmentBlob({ environmentId, attachmentId: attachment.id, }); - const dataUrl = await readFileAsDataUrl( - new File([blob], attachment.name, { type: attachment.mimeType }), - ); - return { + const file = new File([blob], attachment.name, { type: attachment.mimeType }); + return composerAttachmentFromFile({ id: crypto.randomUUID(), name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, - dataUrl, - }; + file, + }); } catch { return null; } }), ); - const loaded = persisted.filter((entry) => entry !== null); + const restored = loaded.filter((entry): entry is ComposerAttachment => entry !== null); return { - restored: hydrateAttachmentsFromPersisted(loaded), - failedCount: attachments.length - loaded.length, + restored, + failedCount: attachments.length - restored.length, }; }; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index e4baa8696..857cdf6e4 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -17,7 +17,6 @@ import type { ThreadId, TurnId, } from "@threadlines/contracts"; -import { saveComposerDraftAttachments } from "../../composerDraftAttachmentSave"; import { resolveFollowUpDelivery, useFollowUpDeliveryStore } from "../../followUpDeliveryStore"; import { publishComposerImageSupport } from "./composerImageSupport"; import { type PromptRecall, recallablePrompts, stepPromptRecall } from "./composerPromptRecall"; @@ -69,22 +68,17 @@ import { deriveComposerSendState, desktopCapturedScreenshotToFile } from "../Cha import { type ComposerAttachment, type DraftId, - type PersistedComposerAttachment, - composerAttachmentDedupKey, - hydrateAttachmentsFromPersisted, + composerDraftAttachmentCount, useComposerDraftStore, useComposerThreadDraft, useEffectiveComposerModelState, } from "../../composerDraftStore"; import { - buildStashEntryContexts, - MAX_STASH_ENTRIES, - partitionStashAttachments, - stashEntryContextDrafts, + deleteStashEntryBlobs, + trackPendingStashRestore, usePromptStashStore, type PromptStashEntry, } from "../../promptStashStore"; -import { compressImageForStash, readFileForStash } from "../../lib/stashImageCompression"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings"; import { isTerminalFocused } from "../../lib/terminalFocus"; import { isKeyboardOwnedByDialog } from "../../commands/shortcutBlock"; @@ -490,6 +484,7 @@ export interface ChatComposerHandle { selectedModelSelection: ModelSelection; selectedProvider: ProviderDriverKind; selectedModel: string; + selectedModelSupportsImages: boolean; selectedProviderModels: ReadonlyArray; skillReferences: ChatSkillReference[]; }; @@ -878,18 +873,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const updateComposerDraftTranscriptHighlightContextNote = useComposerDraftStore( (store) => store.updateTranscriptHighlightContextNote, ); - const clearStashableComposerContent = useComposerDraftStore( - (store) => store.clearStashableComposerContent, - ); - const addComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.addTerminalContexts, - ); - const addComposerDraftTranscriptHighlightContexts = useComposerDraftStore( - (store) => store.addTranscriptHighlightContexts, - ); - const addComposerDraftFileSelectionContext = useComposerDraftStore( - (store) => store.addFileSelectionContext, - ); // ------------------------------------------------------------------ // Model state @@ -1417,11 +1400,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Derived: composer send state // ------------------------------------------------------------------ + const composerAttachmentSlotCount = composerDraftAttachmentCount(composerDraft); const composerSendState = useMemo( () => deriveComposerSendState({ prompt, - attachmentCount: composerAttachments.length, + attachmentCount: composerAttachmentSlotCount, terminalContexts: composerTerminalContexts, transcriptHighlightContexts: composerTranscriptHighlightContexts, fileSelectionContextCount: composerFileSelectionContexts.length, @@ -1429,7 +1413,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) drawingContextCount: composerDrawingContexts.length, }), [ - composerAttachments.length, + composerAttachmentSlotCount, composerTerminalContexts, composerTranscriptHighlightContexts, composerFileSelectionContexts.length, @@ -1624,6 +1608,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) () => new Set(nonPersistedComposerImageIds), [nonPersistedComposerImageIds], ); + const failedHydrationAttachments = useMemo(() => { + if (composerDraft.failedHydrationAttachmentIds.length === 0) return []; + const failedIds = new Set(composerDraft.failedHydrationAttachmentIds); + return composerDraft.persistedAttachments.filter((attachment) => failedIds.has(attachment.id)); + }, [composerDraft.failedHydrationAttachmentIds, composerDraft.persistedAttachments]); const isComposerApprovalState = activePendingApproval !== null; const hasBlockingQuestion = pendingUserInputs.some((input) => input.isBlocking !== false); @@ -2164,11 +2153,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // across threads and providers. Deliberately no model or provider: the // composer keeps whatever is selected right now. const stashEntries = usePromptStashStore((state) => state.entries); - const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry); const takeStashEntry = usePromptStashStore((state) => state.takeEntry); - const finalizeStashEntryAttachments = usePromptStashStore( - (state) => state.finalizeEntryAttachments, - ); // The "+" menu, and its Stashed prompts list (opened on its own by the stash // shortcut with nothing typed, the way the stash button used to open). const [isAddMenuOpen, setIsAddMenuOpen] = useState(false); @@ -2178,6 +2163,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setIsStashListOpen(false); }, []); const stashInFlightRef = useRef>(new Set()); + const restoringStashIdsRef = useRef>(new Set()); + const activeDraftTargetKey = + typeof composerDraftTarget === "string" + ? composerDraftTarget + : scopedThreadKey(composerDraftTarget); + const activeDraftTargetKeyRef = useRef(activeDraftTargetKey); + useLayoutEffect(() => { + activeDraftTargetKeyRef.current = activeDraftTargetKey; + }, [activeDraftTargetKey]); const stashShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "composer.stash", { @@ -2190,7 +2184,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // selections is as much work to reassemble as the sentence about them. const composerHasStashableContent = prompt.trim().length > 0 || - composerAttachments.length > 0 || + composerAttachmentSlotCount > 0 || composerTerminalContexts.length > 0 || composerTranscriptHighlightContexts.length > 0 || composerFileSelectionContexts.length > 0 || @@ -2198,153 +2192,56 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const restoreStashEntry = useCallback( (entry: PromptStashEntry) => { - // Remove first so a double activation (click + Enter) cannot restore twice. - const { entry: taken, durable } = takeStashEntry(entry.id); - if (!taken) return; - if (!durable) { - toastManager.add({ - type: "warning", - title: "Restored prompt may reappear in the stash", - description: - "Browser storage rejected the update, so this entry could still be there after a reload.", - data: { hideCopyButton: true }, - }); - } + // Guard before any async work so a double activation (click + Enter) + // cannot restore the same entry twice. + if (restoringStashIdsRef.current.has(entry.id)) return; + restoringStashIdsRef.current.add(entry.id); closeAddMenu(); - const currentPrompt = promptRef.current; - // An attachment-only or chip-only stash must not append blank lines to - // whatever is already in the composer. - const nextPrompt = - entry.prompt.length === 0 - ? currentPrompt - : currentPrompt.trim().length - ? `${currentPrompt.replace(/\s+$/, "")}\n\n${entry.prompt}` - : entry.prompt; - const promptChanged = nextPrompt !== currentPrompt; - if (promptChanged) { - promptRef.current = nextPrompt; - setPrompt(nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - } - - let unrestoredAttachmentNames: string[] = []; - if (entry.attachments.length > 0) { - const existingAttachments = composerAttachmentsRef.current; - const existingIds = new Set(existingAttachments.map((attachment) => attachment.id)); - // The draft store also dedupes by mimeType+sizeBytes+name, so filter - // on the same key here. Counting a duplicate against capacity would - // burn a slot the store then refuses to fill, pushing a genuinely - // unique attachment into the overflow list for nothing. - const existingDedupKeys = new Set( - existingAttachments.map((attachment) => composerAttachmentDedupKey(attachment)), - ); - const capacity = Math.max( - 0, - PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existingAttachments.length, - ); - const pending = entry.attachments.filter( - (attachment) => - !existingIds.has(attachment.id) && - !existingDedupKeys.has(composerAttachmentDedupKey(attachment)), - ); - // Anything past the attachment limit cannot be restored. The entry is - // already out of the queue, so report the overflow by name instead of - // discarding it silently. - unrestoredAttachmentNames = pending.slice(capacity).map((attachment) => attachment.name); - const restored = hydrateAttachmentsFromPersisted(pending.slice(0, capacity)); - if (restored.length > 0) { - addComposerDraftAttachments(composerDraftTarget, restored); - } - } - - // Chips go back through the store's own add paths, so each one is - // re-stamped for this thread and deduped against what is already there. - const chips = stashEntryContextDrafts(taken); - if (chips.terminalContexts.length > 0) { - addComposerDraftTerminalContexts(composerDraftTarget, chips.terminalContexts); - } - if (chips.transcriptHighlightContexts.length > 0) { - addComposerDraftTranscriptHighlightContexts( - composerDraftTarget, - chips.transcriptHighlightContexts, - ); - } - for (const context of chips.fileSelectionContexts) { - addComposerDraftFileSelectionContext(composerDraftTarget, context); - } - if (chips.pickedElementContexts.length > 0) { - // Picked elements are set as a whole list, so merge rather than - // replace, and drop anything already pinned to the same element. - const existingPicked = composerPickedElementContextsRef.current; - const existingKeys = new Set( - existingPicked.map((context) => pickedElementContextDedupKey(context)), - ); - const additions = chips.pickedElementContexts.filter((context) => { - const key = pickedElementContextDedupKey(context); - if (existingKeys.has(key)) return false; - existingKeys.add(key); - return true; - }); - if (additions.length > 0) { - commitPickedElementContexts([...existingPicked, ...additions]); - } - } - - // Each cause gets its own sentence so "too large" is never blamed for a - // file that actually failed to read, or for one the composer simply had - // no room to take back. - const missingReasons: string[] = []; - if (taken.droppedAttachmentNames.length > 0) { - missingReasons.push( - `${taken.droppedAttachmentNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, - ); - } - if (taken.unreadableAttachmentNames && taken.unreadableAttachmentNames.length > 0) { - missingReasons.push( - `${taken.unreadableAttachmentNames.join(", ")} could not be read when this prompt was saved.`, - ); - } - if (unrestoredAttachmentNames.length > 0) { - missingReasons.push( - `${unrestoredAttachmentNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (missingReasons.length > 0) { - toastManager.add({ - type: "warning", - title: "Some attachments were not restored", - description: missingReasons.join(" "), + const restoreTarget = composerDraftTarget; + const restoreTargetKey = + typeof restoreTarget === "string" ? restoreTarget : scopedThreadKey(restoreTarget); + + const restorePromise = import("./composerStashActions") + .then(({ runRestoreStashEntry }) => + runRestoreStashEntry({ + entry, + restoreTarget, + restoreTargetKey, + getActiveDraftTargetKey: () => activeDraftTargetKeyRef.current, + getLivePrompt: () => promptRef.current, + applyPromptOnActiveTarget: (nextPrompt, collapsedCursor) => { + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + setComposerCursor(collapsedCursor); + setComposerTrigger(null); + }, + commitPickedElementsOnActiveTarget: commitPickedElementContexts, + focusAfterWrite, + }), + ) + .finally(() => { + restoringStashIdsRef.current.delete(entry.id); }); - } - // Only yank the caret to the end when text was actually inserted; - // restoring attachments alone should leave the user where they were. - if (promptChanged) { - focusAfterWrite(nextPrompt, "end"); - } + trackPendingStashRestore(restoreTargetKey, restorePromise); }, [ closeAddMenu, - addComposerDraftAttachments, - addComposerDraftFileSelectionContext, - addComposerDraftTerminalContexts, - addComposerDraftTranscriptHighlightContexts, commitPickedElementContexts, - composerAttachmentsRef, composerDraftTarget, - composerPickedElementContextsRef, focusAfterWrite, promptRef, setPrompt, - takeStashEntry, ], ); const deleteStashEntry = useCallback( (entry: PromptStashEntry) => { - const { durable } = takeStashEntry(entry.id); + const { entry: removed, durable } = takeStashEntry(entry.id); + if (removed && durable) { + void deleteStashEntryBlobs(removed); + } if (!durable) { toastManager.add({ type: "warning", @@ -2359,180 +2256,35 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const stashCurrentPrompt = useCallback(async () => { - // Inline terminal placeholders stay in the stashed text: their contexts - // travel with the entry, and the n-th placeholder still maps to the n-th - // context once both are appended back in order. - const stashedPrompt = promptRef.current.trim(); - const attachments = [...composerAttachmentsRef.current]; - const contexts = buildStashEntryContexts({ - terminalContexts: composerTerminalContextsRef.current, - transcriptHighlightContexts: composerTranscriptHighlightContextsRef.current, - fileSelectionContexts: composerFileSelectionContextsRef.current, - pickedElementContexts: composerPickedElementContextsRef.current, - }); - const hasChips = Object.keys(contexts).length > 0; - if (stashedPrompt.length === 0 && attachments.length === 0 && !hasChips) { - if (isAddMenuOpen) { - closeAddMenu(); - } else { - setIsAddMenuOpen(true); - setIsStashListOpen(true); - } - return; - } - // A repeat press on the *same* still-unencoded snapshot would stash it - // twice. Guard on the snapshot itself rather than a bare boolean: once - // the composer has been cleared the user can type something genuinely new - // (or switch threads) while encoding continues, and that deserves its own - // entry. - const snapshotKey = `${String(composerDraftTarget)}${stashedPrompt}${attachments - .map((attachment) => attachment.id) - .join(",")}`; - if (stashInFlightRef.current.has(snapshotKey)) return; - stashInFlightRef.current.add(snapshotKey); - const stashTarget = composerDraftTarget; - const entryId = randomUUID(); + const stashTargetKey = + typeof stashTarget === "string" ? stashTarget : scopedThreadKey(stashTarget); + if (stashInFlightRef.current.has(stashTargetKey)) return; + stashInFlightRef.current.add(stashTargetKey); try { - // Persist the text-and-chips entry *first*, then clear. Ordering - // matters in both directions: writing before clearing means a crash or - // closed tab mid-encode still leaves the prompt recoverable, while - // clearing before the async attachment work means edits typed during - // encoding are not wiped. Attachments are appended to the stored entry - // as they finish encoding. - const { evicted, written, durable } = stashEntryToQueue({ - id: entryId, - createdAt: new Date().toISOString(), - prompt: stashedPrompt, - attachments: [], - droppedAttachmentNames: [], - unreadableAttachmentNames: [], - pendingAttachmentCount: attachments.length, - ...contexts, - }); - - // Clearing the composer is only safe once the write actually landed. - // If it was rejected (quota) the store has already rolled itself back, - // so leave the composer untouched rather than making it the second - // casualty of a reload. - if (!written) { - toastManager.add( - failureNotice({ - title: "Couldn't stash this prompt", - reason: - "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", - data: { hideCopyButton: true }, - }), - ); - return; - } - // Written but only into the in-memory fallback (localStorage blocked): - // the entry is visible and restorable this session, so proceed with the - // clear, but say it will not survive a reload. - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stashed prompt won't survive a reload", - description: - "Browser storage is unavailable, so this stash is kept only until you close this page.", - data: { hideCopyButton: true }, - }); - } - - // Drawings are deliberately left in place: the stash cannot carry their - // picture, so clearing them here would destroy them for good. - promptRef.current = ""; - clearStashableComposerContent(stashTarget); - setComposerCursor(0); - setComposerTrigger(null); - - if (evicted) { - toastManager.add({ - type: "warning", - title: "Oldest stashed prompt discarded", - description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`, - data: { hideCopyButton: true }, - }); - } - - // Images are re-encoded for the stash rather than stored verbatim: the - // composer allows large files, but localStorage gives the whole origin - // roughly 5MB. Only the stashed copy shrinks; the live attachment (and - // anything sent without stashing) keeps the original file. - const candidateAttachments: PersistedComposerAttachment[] = []; - const oversizedNames: string[] = []; - const unreadableNames: string[] = []; - for (const attachment of attachments) { - const result = attachment.mimeType.startsWith("image/") - ? await compressImageForStash(attachment.file) - : await readFileForStash(attachment.file); - if (!result.ok) { - // "too large" and "could not be read" are distinct outcomes; the - // restore toast reports them separately. - (result.reason === "too-large" ? oversizedNames : unreadableNames).push(attachment.name); - continue; - } - candidateAttachments.push({ - id: attachment.id, - name: attachment.name, - mimeType: result.image.mimeType, - sizeBytes: result.image.sizeBytes, - dataUrl: result.image.dataUrl, - }); - } - const { kept, droppedNames } = partitionStashAttachments(candidateAttachments); - - const { attached, durable: attachmentsDurable } = finalizeStashEntryAttachments(entryId, { - attachments: kept, - droppedAttachmentNames: [...oversizedNames, ...droppedNames], - unreadableAttachmentNames: unreadableNames, + const { runStashCurrentPrompt } = await import("./composerStashActions"); + await runStashCurrentPrompt({ + stashTarget, + getActiveDraftTargetKey: () => activeDraftTargetKeyRef.current, + getLivePrompt: () => promptRef.current, + isAddMenuOpen, + closeAddMenu, + openStashList: () => { + setIsAddMenuOpen(true); + setIsStashListOpen(true); + }, + clearPromptUiOnActiveTarget: (capturedRawPrompt) => { + if (promptRef.current === capturedRawPrompt) { + promptRef.current = ""; + setComposerCursor(0); + setComposerTrigger(null); + } + }, }); - if (attached) { - // The second phase can be rejected on its own: the text entry fit, but - // adding attachment payloads pushed past the quota. Disk would then - // still hold the phase-one entry with a pending count set, which reads - // as an orphan after reload, so say so now. Gated on the entry write - // having been durable: on the in-memory fallback nothing is ever - // durable and the session-only warning already covered it. - if (!attachmentsDurable && durable && attachments.length > 0) { - toastManager.add({ - type: "warning", - title: "Stashed attachments weren't saved", - description: - "The prompt was stashed, but browser storage rejected its attachments. They will be missing if you reload.", - data: { hideCopyButton: true }, - }); - } - } else if (kept.length > 0) { - // The entry was restored or deleted before its attachments finished - // encoding, so they have nowhere to land. Say so rather than letting - // them evaporate. - toastManager.add({ - type: "warning", - title: "Stashed attachments didn't attach", - description: `That prompt was restored or deleted before ${kept.length} attachment${kept.length === 1 ? "" : "s"} finished saving. Add ${kept.length === 1 ? "it" : "them"} again if you still need ${kept.length === 1 ? "it" : "them"}.`, - data: { hideCopyButton: true }, - }); - } } finally { - // Must clear on every path: a throw that left this set would wedge this - // snapshot's shortcut until the composer remounts. - stashInFlightRef.current.delete(snapshotKey); + stashInFlightRef.current.delete(stashTargetKey); } - }, [ - clearStashableComposerContent, - closeAddMenu, - composerAttachmentsRef, - composerDraftTarget, - composerFileSelectionContextsRef, - composerPickedElementContextsRef, - composerTerminalContextsRef, - composerTranscriptHighlightContextsRef, - finalizeStashEntryAttachments, - isAddMenuOpen, - promptRef, - stashEntryToQueue, - ]); + }, [closeAddMenu, composerDraftTarget, isAddMenuOpen, promptRef]); const stashProps = useMemo( () => ({ @@ -2775,9 +2527,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // 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. + const hasPersistedComposerAttachments = composerDraft.persistedAttachments.length > 0; useEffect(() => { - void saveComposerDraftAttachments(composerDraftTarget, { attachments: composerAttachments }); - }, [composerDraftTarget, composerAttachments]); + if (composerAttachments.length === 0 && !hasPersistedComposerAttachments) { + return; + } + void import("../../composerDraftAttachmentSave").then(({ saveComposerDraftAttachments }) => + saveComposerDraftAttachments(composerDraftTarget, { attachments: composerAttachments }), + ); + }, [composerDraftTarget, composerAttachments, hasPersistedComposerAttachments]); // ------------------------------------------------------------------ // Callbacks: prompt change @@ -3203,7 +2961,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return; } - if (composerAttachments.length > 0 && !selectedModelSupportsImages) { + const hasImageAttachment = + composerAttachments.some((attachment) => attachment.type === "image") || + composerDraft.persistedAttachments.some((attachment) => + attachment.mimeType.startsWith("image/"), + ); + if (hasImageAttachment && !selectedModelSupportsImages) { event?.preventDefault(); toastManager.add({ type: "error", @@ -3226,7 +2989,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeThread?.latestTurn, hasBlockingQuestion, blurMobileComposerAfterSend, - composerAttachments.length, + composerAttachments, + composerDraft.persistedAttachments, composerSendState.hasSendableContent, onSend, selectedModelSupportsImages, @@ -3339,7 +3103,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } const nextAttachments: ComposerAttachment[] = []; - let nextAttachmentCount = composerAttachmentsRef.current.length; + let nextAttachmentCount = composerDraftAttachmentCount( + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), + ); let error: string | null = null; let rejectedImageForModel = false; for (const file of files) { @@ -3848,6 +3614,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedModelSelection, selectedProvider, selectedModel, + selectedModelSupportsImages, selectedProviderModels, skillReferences: resolveComposerSkillReferences(promptRef.current, composerSkills), }), @@ -3867,6 +3634,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedModel, selectedModelOptionsForDispatch, selectedModelSelection, + selectedModelSupportsImages, selectedPromptEffort, selectedProvider, selectedProviderModels, @@ -4193,7 +3961,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {!isComposerCollapsedMobile && !hasBlockingQuestion && - composerAttachments.length > 0 && ( + (composerAttachments.length > 0 || failedHydrationAttachments.length > 0) && (
{composerAttachments.map((attachment) => (
Draft attachment could not be saved locally and may be lost on - navigation. + reload. )} @@ -4301,6 +4069,48 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
))} + {failedHydrationAttachments.map((attachment) => ( +
+
+ + + {attachment.name} + +
+ + + + + } + /> + + Could not load attachment from browser storage. Reload or remove it. + + + +
+ ))}
)} diff --git a/apps/web/src/components/chat/ComposerAddMenu.browser.tsx b/apps/web/src/components/chat/ComposerAddMenu.browser.tsx index 900628163..1668a1c7e 100644 --- a/apps/web/src/components/chat/ComposerAddMenu.browser.tsx +++ b/apps/web/src/components/chat/ComposerAddMenu.browser.tsx @@ -7,6 +7,11 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { render } from "vitest-browser-react"; import type { PromptStashEntry } from "../../promptStashStore"; +import { + clearAttachmentBlobsForTest, + putAttachmentBlob, + stashAttachmentBlobKey, +} from "../../lib/attachmentBlobStore"; import { ComposerAddMenu } from "./ComposerAddMenu"; import { resetTestPage } from "../../lib/testPage.browser-harness"; @@ -77,6 +82,7 @@ function renderAddMenu(props: { describe("ComposerAddMenu", () => { afterEach(async () => { + await clearAttachmentBlobsForTest(); await resetTestPage(); }); @@ -169,4 +175,41 @@ describe("ComposerAddMenu", () => { expect(onTakePhoto).toHaveBeenCalledTimes(1); await screen.unmount(); }); + + it("renders stashed image thumbnails stored in IndexedDB without inline dataUrls", async () => { + // Tiny valid 1x1 PNG in IndexedDB. + const pngBytes = Uint8Array.from( + atob( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aRX0AAAAASUVORK5CYII=", + ), + (char) => char.charCodeAt(0), + ); + await putAttachmentBlob( + stashAttachmentBlobKey("with-img", "img-1"), + new Blob([pngBytes], { type: "image/png" }), + ); + const entry: PromptStashEntry = { + id: "with-img", + createdAt: new Date().toISOString(), + prompt: "check this screenshot", + attachments: [ + { + id: "img-1", + name: "shot.png", + mimeType: "image/png", + sizeBytes: pngBytes.byteLength, + }, + ], + droppedAttachmentNames: [], + }; + const screen = await renderAddMenu({ entries: [entry], canStash: false }); + + await page.getByRole("button", { name: "Add to message" }).click(); + await page.getByRole("menuitem", { name: /Stashed prompts/ }).click(); + await vi.waitFor(() => { + const img = document.querySelector('img[src^="blob:"]'); + expect(img).not.toBeNull(); + }); + await screen.unmount(); + }); }); diff --git a/apps/web/src/components/chat/ComposerStashControl.tsx b/apps/web/src/components/chat/ComposerStashControl.tsx index 06e6c0797..d203bbffb 100644 --- a/apps/web/src/components/chat/ComposerStashControl.tsx +++ b/apps/web/src/components/chat/ComposerStashControl.tsx @@ -1,6 +1,8 @@ import { BookmarkIcon, XIcon } from "lucide-react"; -import { memo, useCallback, useState } from "react"; +import { memo, useCallback, useEffect, useState } from "react"; +import type { PersistedComposerAttachment } from "../../composerDraftStore"; +import { readAttachmentBlob, stashAttachmentBlobKey } from "../../lib/attachmentBlobStore"; import { stripInlineTerminalContextPlaceholders } from "../../lib/terminalContext"; import { stashEntryChipCount, type PromptStashEntry } from "../../promptStashStore"; import { @@ -77,6 +79,47 @@ export function stashEntrySnippet(entry: PromptStashEntry): string { return chipCount > 0 ? `${chipCount} chip${chipCount === 1 ? "" : "s"}` : "Empty prompt"; } +function StashAttachmentThumbnail(props: { + readonly entryId: string; + readonly attachment: PersistedComposerAttachment; +}) { + const { entryId, attachment } = props; + const inlineDataUrl = attachment.dataUrl; + const lookupKey = + inlineDataUrl === undefined ? stashAttachmentBlobKey(entryId, attachment.id) : null; + const [loaded, setLoaded] = useState<{ readonly key: string; readonly url: string } | null>(null); + + useEffect(() => { + if (lookupKey === null) return; + let cancelled = false; + let objectUrl: string | null = null; + void readAttachmentBlob(lookupKey).then((result) => { + if (cancelled || result.status !== "ok") return; + objectUrl = URL.createObjectURL(result.blob); + setLoaded({ key: lookupKey, url: objectUrl }); + }); + return () => { + cancelled = true; + if (objectUrl !== null) { + URL.revokeObjectURL(objectUrl); + } + }; + }, [lookupKey]); + + const src = inlineDataUrl ?? (loaded?.key === lookupKey ? loaded.url : null); + if (src === null) { + return