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
47 changes: 46 additions & 1 deletion apps/web/src/components/ChatView.composer.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<void>((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<HTMLInputElement>('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;
Expand Down
14 changes: 5 additions & 9 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]);

// ------------------------------------------------------------------
Expand Down
93 changes: 93 additions & 0 deletions apps/web/src/composerDraftAttachmentSave.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
COMPOSER_DRAFT_ATTACHMENT_MAX_SAVED_BYTES,
COMPOSER_DRAFT_STORAGE_KEY,
type ComposerAttachment,
hydrateAttachmentsFromPersisted,
useComposerDraftStore,
} from "./composerDraftStore";

Expand Down Expand Up @@ -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<string, { prompt: string }> };
}
).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<string, { prompt: string }>) => void) {
const raw = JSON.parse(localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) ?? "{}") as {
state: { draftsByThreadKey: Record<string, { prompt: string }> };
};
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([]);
});
});
4 changes: 1 addition & 3 deletions apps/web/src/composerDraftAttachmentSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async function dataUrlOf(file: File): Promise<string> {
* 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
Expand All @@ -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<ComposerAttachment>;
readonly cancelled?: () => boolean;
} = {},
): Promise<"saved" | "stale"> {
const store = useComposerDraftStore.getState();
Expand Down Expand Up @@ -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";
Expand Down
Loading
Loading