Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions apps/web/src/components/ChatView.composer.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<HTMLInputElement>('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<HTMLElement>('[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();
}
});
});
123 changes: 99 additions & 24 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<ComposerAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerTranscriptHighlightContextsRef = useRef<TranscriptHighlightContextDraft[]>([]);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
};
};

Expand Down
Loading
Loading