fix(chat): autosave unsent composer drafts across page navigation

This commit is contained in:
Antonio-Faure
2026-10-30 19:07:04 +01:00
parent 40c051b731
commit 59f2a5d17a
5 changed files with 347 additions and 29 deletions

View File

@@ -11,9 +11,11 @@ import {
type RefObject,
} from "react";
import {
currentWorkspaceDraftLocation,
saveWorkspaceDraft,
readWorkspaceDraft,
type WorkspaceDraft,
type WorkspaceDraftLocation,
} from "@/lib/workspace-drafts";
import {
ArrowUp,
@@ -534,19 +536,103 @@ export default memo(function ChatComposer({
}, [onAddFiles]);
const restoredDraftRef = useRef(false);
const restoreFailedRef = useRef(false);
const draftSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const draftDirtyRef = useRef(false);
const draftLocationRef = useRef<WorkspaceDraftLocation | null>(null);
const draftTextRef = useRef("");
const interactedBeforeRestoreRef = useRef(false);
const restoreBaseRef = useRef<WorkspaceDraft | undefined | null>(null);
const suppressDraftSaveRef = useRef(false);
const collectDraft = useCallback(
(): WorkspaceDraft => ({
// Keep the last value in a ref: the imperative handle may already be
// detached when the unmount cleanup runs.
text: draftTextRef.current,
attachments: draftAttachmentsRef.current.map(
({ filename, base64, mimeType }) => ({ filename, base64, mimeType }),
),
}),
[],
);
const cancelDraftSave = useCallback(() => {
if (draftSaveTimerRef.current) {
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
draftDirtyRef.current = false;
}, []);
const saveDraftInBackground = useCallback(async () => {
if (!draftDirtyRef.current) return;
const location = draftLocationRef.current;
if (!location) return;
const draft = collectDraft();
draftDirtyRef.current = false;
try {
if (restoreFailedRef.current) {
// The stored draft never reached the composer; merge instead of
// overwriting it with only what was typed after the failure.
if (restoreBaseRef.current === null) {
restoreBaseRef.current = await readWorkspaceDraft(
location.workspaceId,
location.pathname,
);
}
const base = restoreBaseRef.current;
await saveWorkspaceDraft(
{
text: [base?.text, draft.text].filter(Boolean).join("\n"),
attachments: [...(base?.attachments ?? []), ...draft.attachments],
},
location.workspaceId,
location.pathname,
);
} else {
await saveWorkspaceDraft(draft, location.workspaceId, location.pathname);
}
} catch (error) {
draftDirtyRef.current = true;
console.warn("[ChatComposer] workspace draft autosave failed", error);
}
}, [collectDraft]);
const scheduleDraftSave = useCallback(() => {
if (!restoredDraftRef.current && !restoreFailedRef.current) return;
draftDirtyRef.current = true;
if (draftSaveTimerRef.current) clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = setTimeout(() => {
draftSaveTimerRef.current = null;
void saveDraftInBackground();
}, 500);
}, [saveDraftInBackground]);
useEffect(() => {
let alive = true;
const restore = readWorkspaceDraft();
const location = currentWorkspaceDraftLocation();
draftLocationRef.current = location;
const restore = readWorkspaceDraft(location.workspaceId, location.pathname);
if (!restoredDraftRef.current) {
void restore
.then((draft) => {
if (!alive || restoredDraftRef.current) return;
if (restoredDraftRef.current) return;
restoredDraftRef.current = true;
if (!draft) return;
if (!alive) return;
if (!draft) {
if (interactedBeforeRestoreRef.current) scheduleDraftSave();
return;
}
const current = inputHandleRef.current?.getValue() || "";
inputHandleRef.current?.setValue(
current ? `${draft.text}\n${current}` : draft.text,
);
const restoredText = current ? `${draft.text}\n${current}` : draft.text;
draftTextRef.current = restoredText;
// Restoring is not user input; don't queue a save that would write
// the draft straight back to storage.
suppressDraftSaveRef.current = true;
inputHandleRef.current?.setValue(restoredText);
queueMicrotask(() => {
suppressDraftSaveRef.current = false;
});
if (interactedBeforeRestoreRef.current) scheduleDraftSave();
const files = draft.attachments
.filter((item) => item.base64)
.map((item) => {
@@ -568,17 +654,10 @@ export default memo(function ChatComposer({
);
});
}
const collectDraft = () => ({
text: inputHandleRef.current?.getValue() || "",
attachments: draftAttachmentsRef.current.map(
({ filename, base64, mimeType }) => ({ filename, base64, mimeType }),
),
});
// The stored draft never made it into the composer, so saving the composer
// as-is could clobber it. Skip when nothing new was typed; otherwise merge
// the new input on top of the stored draft. If even the re-read fails,
// reject the switch (as on main) instead of losing the new input.
let storedDraft: WorkspaceDraft | undefined | null = null;
const saveAfterFailedRestore = () => {
restoreFailedRef.current = true;
const draft = collectDraft();
@@ -587,13 +666,14 @@ export default memo(function ChatComposer({
saveWorkspaceDraft({
text: [stored?.text, draft.text].filter(Boolean).join("\n"),
attachments: [...(stored?.attachments ?? []), ...draft.attachments],
});
}, location.workspaceId, location.pathname);
// Re-read only once per mount so a retried switch merges the original
// stored draft instead of re-appending the composer to itself.
if (storedDraft !== null) return merge(storedDraft);
return readWorkspaceDraft().then((stored) => {
storedDraft = stored ?? { text: "", attachments: [] };
return merge(stored);
// stored draft instead of re-appending the composer to itself. Autosave
// shares the same cache: it may already have written base + typed text.
if (restoreBaseRef.current !== null) return merge(restoreBaseRef.current);
return readWorkspaceDraft(location.workspaceId, location.pathname).then((stored) => {
restoreBaseRef.current = stored ?? { text: "", attachments: [] };
return merge(restoreBaseRef.current);
});
};
const save = (event: Event) => {
@@ -601,7 +681,7 @@ export default memo(function ChatComposer({
restoreFailedRef.current
? saveAfterFailedRestore()
: restore.then(
() => saveWorkspaceDraft(collectDraft()),
() => saveWorkspaceDraft(collectDraft(), location.workspaceId, location.pathname),
saveAfterFailedRestore,
),
);
@@ -610,8 +690,53 @@ export default memo(function ChatComposer({
return () => {
alive = false;
window.removeEventListener("deeptutor:before-workspace-switch", save);
if (draftSaveTimerRef.current) {
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
if (!draftDirtyRef.current) return;
if (restoredDraftRef.current || restoreFailedRef.current) {
void saveDraftInBackground();
return;
}
// The composer unmounted before the stored draft arrived. Merge it with
// whatever was typed so neither side is lost.
void restore
.then((draft) => {
if (!draftDirtyRef.current) return;
const current = collectDraft();
void saveWorkspaceDraft({
text: [draft?.text, current.text].filter(Boolean).join("\n"),
attachments: [...(draft?.attachments ?? []), ...current.attachments],
}, location.workspaceId, location.pathname).catch(() => {});
})
.catch(() => {
if (draftDirtyRef.current) {
void saveWorkspaceDraft(collectDraft(), location.workspaceId, location.pathname).catch(() => {});
}
});
};
}, []);
}, [collectDraft, saveDraftInBackground, scheduleDraftSave]);
// Attachments are part of the same draft. Their signature is a cheap way to
// react to add/remove without re-saving on every parent render.
const attachmentSignature = attachments
.map((item) => `${item.filename}:${item.base64?.length ?? 0}:${item.mimeType ?? ""}`)
.join("|");
const attachmentsInitializedRef = useRef(false);
useEffect(() => {
if (!attachmentsInitializedRef.current) {
attachmentsInitializedRef.current = true;
return;
}
if (suppressDraftSaveRef.current) return;
if (!restoredDraftRef.current && !restoreFailedRef.current) {
interactedBeforeRestoreRef.current = true;
return;
}
draftLocationRef.current = currentWorkspaceDraftLocation();
scheduleDraftSave();
}, [attachmentSignature, scheduleDraftSave]);
if (lastCapMenuOpen !== capMenuOpen) {
setLastCapMenuOpen(capMenuOpen);
if (!capMenuOpen) setMoreCapsOpen(false);
@@ -702,9 +827,17 @@ export default memo(function ChatComposer({
// every keystroke (no `hasContent` in deps), so the memoized ComposerInput
// doesn't get re-rendered just because we observed a content-empty toggle.
const handleInputChange = useCallback((val: string) => {
draftTextRef.current = val;
const next = !!val.trim();
setHasContent((prev) => (prev === next ? prev : next));
}, []);
if (suppressDraftSaveRef.current) return;
if (!restoredDraftRef.current && !restoreFailedRef.current) {
interactedBeforeRestoreRef.current = true;
return;
}
draftLocationRef.current = currentWorkspaceDraftLocation();
scheduleDraftSave();
}, [scheduleDraftSave]);
const doSend = useCallback(
(content: string) => {
@@ -716,11 +849,24 @@ export default memo(function ChatComposer({
return false;
}
onSend(content);
if (!restoreFailedRef.current) {
void saveWorkspaceDraft({ text: "", attachments: [] }).catch(() => {});
if (restoredDraftRef.current && !restoreFailedRef.current) {
const location = draftLocationRef.current ?? currentWorkspaceDraftLocation();
void saveWorkspaceDraft(
{ text: "", attachments: [] },
location.workspaceId,
location.pathname,
).catch(() => {});
}
setHasContent(false);
// Suppress the draft save that the clear below would otherwise queue:
// the message is sent, so there is nothing left to restore.
suppressDraftSaveRef.current = true;
inputHandleRef.current?.clear();
draftTextRef.current = "";
queueMicrotask(() => {
suppressDraftSaveRef.current = false;
});
cancelDraftSave();
// Sending can move focus to the button or rerender the empty-state
// composer into the conversation layout. Restore it after that update
// so the user can keep typing, including after switching back to the tab.
@@ -728,7 +874,7 @@ export default memo(function ChatComposer({
return true;
},
[awaitingUserReply, capabilityConfigConfirmed, capabilityNeedsConfig,
focusTextarea, isStreaming, onRequestConfigConfirm, onSend],
cancelDraftSave, focusTextarea, isStreaming, onRequestConfigConfirm, onSend],
);
const { board: taskBoard } = useTaskBoard();

View File

@@ -5,6 +5,25 @@ export type WorkspaceDraft = {
text: string
attachments: { filename: string; base64?: string; mimeType?: string }[]
}
export type WorkspaceDraftLocation = {
workspaceId: string
pathname: string
}
/**
* Snapshot the scope a composer is writing into. Callers capture this at
* typing time: by the time a deferred save or an unmount cleanup runs, the
* URL may already point at the destination page, and the draft would land
* under the wrong key.
*/
export function currentWorkspaceDraftLocation(): WorkspaceDraftLocation {
return {
workspaceId: activeWorkspaceId(),
pathname: window.location.pathname,
}
}
async function key(workspaceId = activeWorkspaceId(), pathname = window.location.pathname): Promise<string> {
const location = `${workspaceId}:${pathname}`
const status = await fetchAuthStatus()

View File

@@ -11,6 +11,7 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("@/lib/workspace-drafts", () => ({
currentWorkspaceDraftLocation: () => ({ workspaceId: "", pathname: "/chat" }),
readWorkspaceDraft: vi.fn().mockResolvedValue(null),
saveWorkspaceDraft: vi.fn().mockResolvedValue(undefined),
}));

View File

@@ -10,8 +10,12 @@ const drafts = vi.hoisted(() => ({
read: vi.fn<() => Promise<unknown>>(),
save: vi.fn<() => Promise<void>>(),
}));
const draftLocation = vi.hoisted(() => ({
current: { workspaceId: "ws_test", pathname: "/chat" },
}));
vi.mock("@/lib/workspace-drafts", () => ({
currentWorkspaceDraftLocation: () => draftLocation.current,
readWorkspaceDraft: drafts.read,
saveWorkspaceDraft: drafts.save,
}));
@@ -34,6 +38,7 @@ const activeCap: CapabilityDef = {
beforeEach(() => {
drafts.read.mockReset();
drafts.save.mockReset();
draftLocation.current = { workspaceId: "ws_test", pathname: "/chat" };
});
function Harness({ onSend = () => {} }: { onSend?: (content: string) => void }) {
@@ -152,7 +157,7 @@ it("saves newly typed text merged with the stored draft when switching after a f
expect(drafts.save).toHaveBeenCalledWith({
text: "stored draft\ntyped after failure",
attachments: [],
});
}, "ws_test", "/chat");
});
it("keeps typed text on a retried switch after the first merge save failed", async () => {
@@ -177,7 +182,7 @@ it("keeps typed text on a retried switch after the first merge save failed", asy
expect(drafts.save).toHaveBeenLastCalledWith({
text: "typed after failure",
attachments: [],
});
}, "ws_test", "/chat");
});
it("keeps typed text when the stored draft has attachments but no text", async () => {
@@ -201,7 +206,7 @@ it("keeps typed text when the stored draft has attachments but no text", async (
expect(drafts.save).toHaveBeenCalledWith({
text: "typed after failure",
attachments: storedAttachments,
});
}, "ws_test", "/chat");
});
it("rejects the switch when a re-read of the stored draft still fails after new input", async () => {
@@ -248,5 +253,151 @@ it("still saves the composer content on workspace switch after a successful rest
expect(drafts.save).toHaveBeenCalledWith({
text: "saved on switch",
attachments: [],
});
}, "ws_test", "/chat");
});
it("autosaves typed text after a short pause", async () => {
vi.useFakeTimers();
try {
drafts.read.mockResolvedValue(undefined);
drafts.save.mockResolvedValue(undefined);
render(<Harness />);
await act(async () => {});
fireEvent.change(screen.getByRole("textbox"), {
target: { value: "half-written question" },
});
await act(async () => {
vi.advanceTimersByTime(500);
});
expect(drafts.save).toHaveBeenCalledWith({
text: "half-written question",
attachments: [],
}, "ws_test", "/chat");
} finally {
vi.useRealTimers();
}
});
it("flushes a pending draft when the composer unmounts", async () => {
drafts.read.mockResolvedValue(undefined);
drafts.save.mockResolvedValue(undefined);
const { unmount } = render(<Harness />);
await act(async () => {});
fireEvent.change(screen.getByRole("textbox"), {
target: { value: "not sent yet" },
});
unmount();
await act(async () => {});
expect(drafts.save).toHaveBeenCalledWith({
text: "not sent yet",
attachments: [],
}, "ws_test", "/chat");
});
it("does not overwrite a stored draft when an empty composer unmounts", async () => {
drafts.read.mockResolvedValue({ text: "stored draft", attachments: [] });
drafts.save.mockResolvedValue(undefined);
const { unmount } = render(<Harness />);
await act(async () => {});
unmount();
await act(async () => {});
expect(drafts.save).not.toHaveBeenCalled();
});
it("saves under the route where the text was typed", async () => {
draftLocation.current = { workspaceId: "ws_test", pathname: "/chat/one" };
drafts.read.mockResolvedValue(undefined);
drafts.save.mockResolvedValue(undefined);
const { unmount } = render(<Harness />);
await act(async () => {});
fireEvent.change(screen.getByRole("textbox"), {
target: { value: "route-bound draft" },
});
draftLocation.current = { workspaceId: "ws_test", pathname: "/settings" };
unmount();
await act(async () => {});
expect(drafts.save).toHaveBeenCalledWith({
text: "route-bound draft",
attachments: [],
}, "ws_test", "/chat/one");
});
it("merges text typed before the stored draft finishes loading", async () => {
let resolveRead!: (value: unknown) => void;
drafts.read.mockReturnValue(new Promise((resolve) => {
resolveRead = resolve;
}));
drafts.save.mockResolvedValue(undefined);
render(<Harness />);
fireEvent.change(screen.getByRole("textbox"), {
target: { value: "typed early" },
});
expect(drafts.save).not.toHaveBeenCalled();
await act(async () => {
resolveRead({ text: "stored draft", attachments: [] });
});
expect(screen.getByRole("textbox")).toHaveValue("stored draft\ntyped early");
});
it("does not duplicate the stored draft when autosave and a workspace switch both merge", async () => {
vi.useFakeTimers();
try {
drafts.read
.mockRejectedValueOnce(new Error("indexeddb unavailable"))
.mockResolvedValueOnce({ text: "stored draft", attachments: [] });
drafts.save.mockResolvedValue(undefined);
render(<Harness />);
await act(async () => {});
fireEvent.change(screen.getByRole("textbox"), {
target: { value: "typed after failure" },
});
await act(async () => {
vi.advanceTimersByTime(500);
});
expect(drafts.save).toHaveBeenLastCalledWith({
text: "stored draft\ntyped after failure",
attachments: [],
}, "ws_test", "/chat");
const pending = switchWorkspace();
await expect(Promise.all(pending)).resolves.toBeDefined();
expect(drafts.save).toHaveBeenCalledTimes(2);
expect(drafts.save).toHaveBeenLastCalledWith({
text: "stored draft\ntyped after failure",
attachments: [],
}, "ws_test", "/chat");
} finally {
vi.useRealTimers();
}
});
it("clears the sent draft under the route it was typed on", async () => {
draftLocation.current = { workspaceId: "ws_test", pathname: "/chat/one" };
drafts.read.mockResolvedValue(undefined);
drafts.save.mockResolvedValue(undefined);
const onSend = vi.fn();
render(<Harness onSend={onSend} />);
await act(async () => {});
const input = screen.getByRole("textbox");
fireEvent.change(input, { target: { value: "send me" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("send me");
expect(drafts.save).toHaveBeenCalledWith({
text: "",
attachments: [],
}, "ws_test", "/chat/one");
});

View File

@@ -9,6 +9,7 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("@/lib/workspace-drafts", () => ({
currentWorkspaceDraftLocation: () => ({ workspaceId: "", pathname: "/chat" }),
readWorkspaceDraft: async () => null,
saveWorkspaceDraft: async () => undefined,
}));