Skip to content

Commit 4e89c76

Browse files
committed
fix(web): discarding a sidebar draft can be undone
Fixes #12735
1 parent c5bc98d commit 4e89c76

8 files changed

Lines changed: 190 additions & 24 deletions

File tree

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
endThreadContextDrag,
88
moveThreadContextDrag as moveThreadContextDragGhost,
99
} from "./chat/threadContextDrag";
10-
import { releaseComposerDraftUploads } from "../lib/composerDraftUploads";
10+
import { discardComposerDraft } from "../lib/discardComposerDraft";
1111
import { requestCustomSnooze } from "./CustomSnoozeDialog";
1212
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
1313
import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
@@ -915,7 +915,6 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
915915
}) {
916916
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
917917
const draftsByThreadKey = useComposerDraftStore((store) => store.draftsByThreadKey);
918-
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
919918
// The open draft's row is FROZEN at the moment the draft became the route:
920919
// it stays visible (like a thread row) but never repaints while the user
921920
// types. A draft that was never navigated away from has no snapshot to
@@ -979,16 +978,6 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
979978
props.routeDraftId,
980979
props.scopedProjectKeys,
981980
]);
982-
const handleDiscard = useCallback(
983-
(draftId: DraftId) => {
984-
// The /draft/$draftId route redirects home on its own when the draft
985-
// it renders disappears, so discarding the open draft needs no
986-
// special-casing here.
987-
releaseComposerDraftUploads(draftId);
988-
clearDraftThread(draftId);
989-
},
990-
[clearDraftThread],
991-
);
992981
if (drafts.length === 0) {
993982
return null;
994983
}
@@ -1005,7 +994,10 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
1005994
projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null}
1006995
isActive={draftId === props.routeDraftId}
1007996
onNavigate={props.onNavigateToDraft}
1008-
onDiscard={handleDiscard}
997+
// The /draft/$draftId route redirects home on its own when the
998+
// draft it renders disappears, so discarding the open draft needs
999+
// no special-casing here.
1000+
onDiscard={discardComposerDraft}
10091001
/>
10101002
);
10111003
})}
@@ -1164,15 +1156,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
11641156
// Unsent composer text on this thread. The open thread shows its own
11651157
// composer, so the marker only decorates rows you have navigated away from.
11661158
const hasUnsentDraft = useThreadHasUnsentDraft(threadRef) && !props.isActive;
1167-
const clearComposerContent = useComposerDraftStore((store) => store.clearComposerContent);
11681159
const handleDiscardDraftClick = useCallback(
11691160
(event: ReactMouseEvent) => {
11701161
event.preventDefault();
11711162
event.stopPropagation();
1172-
releaseComposerDraftUploads(threadRef);
1173-
clearComposerContent(threadRef);
1163+
discardComposerDraft(threadRef);
11741164
},
1175-
[clearComposerContent, threadRef],
1165+
[threadRef],
11761166
);
11771167

11781168
const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null;

‎apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@ export function SidebarThreadUndoNotice() {
1212

1313
if (!notice) return null;
1414
const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
15+
const noun = `${notice.action === "Discarded" ? "draft" : "thread"}${notice.count === 1 ? "" : "s"}`;
1516

1617
return (
1718
<Alert role="status" variant="sidebar">
1819
<AlertDescription>
19-
{notice.action} {notice.count} thread{notice.count === 1 ? "" : "s"},{" "}
20+
{notice.action} {notice.count} {noun},{" "}
2021
<InlineButton onClick={undoLatestThreadAction}>
2122
{shortcut ? `${shortcut} to undo` : "Undo"}
2223
</InlineButton>

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1504,7 +1504,7 @@ function normalizeComposerTarget(
15041504
return target;
15051505
}
15061506

1507-
function resolveComposerDraftKey(
1507+
export function resolveComposerDraftKey(
15081508
state: ComposerThreadLookupState,
15091509
target: ComposerThreadTarget,
15101510
): string | null {

‎apps/web/src/hooks/showThreadUndoNotice.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ import { stackedThreadToast, toastManager } from "../components/ui/toast";
99
import * as ThreadUndo from "./threadUndo";
1010

1111
type UndoOptions = {
12-
action: "Settled" | "Snoozed" | "Unpinned" | "Archived";
12+
action: "Settled" | "Snoozed" | "Unpinned" | "Archived" | "Discarded";
1313
undo: () => Promise<AtomCommandResult<unknown, unknown>>;
1414
failureTitle: string;
1515
claim: ReturnType<typeof ThreadUndo.begin>;
16+
/** Runs once the action can no longer be undone. */
17+
commit?: () => void;
1618
};
1719

1820
type UndoNotice = {
@@ -29,7 +31,9 @@ let liveUndos: UndoOptions[] = [];
2931
let expiry: ReturnType<typeof setTimeout> | undefined;
3032

3133
function refreshNotice() {
32-
liveUndos = liveUndos.filter(({ claim }) => claim.isCurrent());
34+
const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
35+
liveUndos = liveUndos.filter((entry) => !stale.includes(entry));
36+
for (const entry of stale) entry.commit?.();
3337
const latest = liveUndos.at(-1);
3438
if (!latest) {
3539
clearTimeout(expiry);
@@ -100,7 +104,10 @@ export function showThreadUndoNotice(options: UndoOptions) {
100104
expiry = setTimeout(() => {
101105
const expired = liveUndos;
102106
liveUndos = [];
103-
for (const { claim } of expired) claim.finish();
107+
for (const { claim, commit } of expired) {
108+
claim.finish();
109+
commit?.();
110+
}
104111
refreshNotice();
105112
}, 5_000);
106113
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2+
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4+
5+
import { toastManager } from "../components/ui/toast";
6+
import { DraftId, useComposerDraftStore } from "../composerDraftStore";
7+
import { useThreadUndoNotice } from "../hooks/showThreadUndoNotice";
8+
import { releaseDraftAttachments } from "./attachmentUploadQueue";
9+
import { discardComposerDraft } from "./discardComposerDraft";
10+
11+
vi.mock("./attachmentUploadQueue", () => ({ releaseDraftAttachments: vi.fn() }));
12+
13+
const environmentId = EnvironmentId.make("environment-local");
14+
const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));
15+
const draftId = DraftId.make("draft-1");
16+
const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread-1"));
17+
18+
function undoNotice() {
19+
const notice = useThreadUndoNotice.getState().notice;
20+
if (!notice) throw new Error("Undo notice is missing");
21+
return notice;
22+
}
23+
24+
beforeEach(() => {
25+
vi.useFakeTimers();
26+
useComposerDraftStore.setState({
27+
draftsByThreadKey: {},
28+
draftThreadsByThreadKey: {},
29+
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
30+
});
31+
});
32+
afterEach(() => {
33+
vi.runAllTimers();
34+
vi.useRealTimers();
35+
vi.clearAllMocks();
36+
vi.restoreAllMocks();
37+
});
38+
39+
describe("discardComposerDraft", () => {
40+
it("restores a discarded new-thread draft with its project mapping", async () => {
41+
const store = useComposerDraftStore.getState();
42+
store.setProjectDraftThreadId(projectRef, draftId);
43+
store.setPrompt(draftId, "half-written prompt");
44+
const before = useComposerDraftStore.getState();
45+
46+
discardComposerDraft(draftId);
47+
expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull();
48+
expect(undoNotice()).toMatchObject({ action: "Discarded", count: 1 });
49+
50+
await undoNotice().undo();
51+
const after = useComposerDraftStore.getState();
52+
expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId));
53+
expect(after.getComposerDraft(draftId)?.prompt).toBe("half-written prompt");
54+
expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual(
55+
before.logicalProjectDraftThreadKeyByLogicalProjectKey,
56+
);
57+
vi.runAllTimers();
58+
expect(releaseDraftAttachments).not.toHaveBeenCalled();
59+
});
60+
61+
it("clears a thread draft for good and releases its uploads once undo expires", async () => {
62+
useComposerDraftStore.getState().setPrompt(threadRef, "reply in progress");
63+
64+
discardComposerDraft(threadRef);
65+
const notice = undoNotice();
66+
expect(useComposerDraftStore.getState().getComposerDraft(threadRef)?.prompt ?? "").toBe("");
67+
expect(releaseDraftAttachments).not.toHaveBeenCalled();
68+
69+
vi.advanceTimersByTime(5_000);
70+
expect(useThreadUndoNotice.getState().notice).toBeNull();
71+
expect(releaseDraftAttachments).toHaveBeenCalledOnce();
72+
await notice.undo();
73+
expect(useComposerDraftStore.getState().getComposerDraft(threadRef)?.prompt ?? "").toBe("");
74+
});
75+
76+
it("does not let undo overwrite text typed after the discard", async () => {
77+
useComposerDraftStore.getState().setPrompt(threadRef, "old reply");
78+
discardComposerDraft(threadRef);
79+
useComposerDraftStore.getState().setPrompt(threadRef, "new reply");
80+
const addToast = vi.spyOn(toastManager, "add").mockReturnValue("error-toast");
81+
82+
await undoNotice().undo();
83+
expect(useComposerDraftStore.getState().getComposerDraft(threadRef)?.prompt).toBe("new reply");
84+
expect(addToast).toHaveBeenCalledWith(
85+
expect.objectContaining({ title: "Failed to restore draft" }),
86+
);
87+
});
88+
});
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import * as Cause from "effect/Cause";
2+
import { AsyncResult } from "effect/unstable/reactivity";
3+
4+
import {
5+
type ComposerThreadTarget,
6+
composerDraftHasUserContent,
7+
resolveComposerDraftKey,
8+
useComposerDraftStore,
9+
} from "../composerDraftStore";
10+
import { showThreadUndoNotice } from "../hooks/showThreadUndoNotice";
11+
import * as ThreadUndo from "../hooks/threadUndo";
12+
import { releaseDraftAttachments } from "./attachmentUploadQueue";
13+
14+
/**
15+
* Discards a draft's unsent content behind the sidebar undo notice. A new-thread
16+
* draft (DraftId) loses its whole session; a thread draft only loses its
17+
* composer content. Uploads are released once the undo window closes.
18+
*/
19+
export function discardComposerDraft(target: ComposerThreadTarget): void {
20+
const store = useComposerDraftStore.getState();
21+
const key = resolveComposerDraftKey(store, target);
22+
const draft = key === null ? undefined : store.draftsByThreadKey[key];
23+
if (key === null || !draft) return;
24+
const session = store.draftThreadsByThreadKey[key];
25+
const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey)
26+
.filter(([, draftKey]) => draftKey === key)
27+
.map(([logicalProjectKey]) => logicalProjectKey);
28+
const discardsSession = typeof target === "string";
29+
30+
const claim = ThreadUndo.begin("discard", key);
31+
if (discardsSession) {
32+
store.clearDraftThread(target);
33+
} else {
34+
store.clearComposerContent(target);
35+
}
36+
37+
showThreadUndoNotice({
38+
action: "Discarded",
39+
claim,
40+
failureTitle: "Failed to restore draft",
41+
undo: async () => {
42+
const current = useComposerDraftStore.getState().draftsByThreadKey[key];
43+
if (current && composerDraftHasUserContent(current)) {
44+
return AsyncResult.failure(Cause.fail(new Error("The draft has new content.")));
45+
}
46+
useComposerDraftStore.setState((state) => {
47+
const logicalProjectDraftThreadKeyByLogicalProjectKey = {
48+
...state.logicalProjectDraftThreadKeyByLogicalProjectKey,
49+
};
50+
for (const logicalProjectKey of logicalProjectKeys) {
51+
logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key;
52+
}
53+
return {
54+
draftsByThreadKey: {
55+
...state.draftsByThreadKey,
56+
// Removing a draft session revokes its image previews.
57+
[key]: discardsSession
58+
? {
59+
...draft,
60+
images: draft.images.map((image) =>
61+
image.previewUrl.startsWith("blob:")
62+
? { ...image, previewUrl: URL.createObjectURL(image.file) }
63+
: image,
64+
),
65+
}
66+
: draft,
67+
},
68+
draftThreadsByThreadKey: session
69+
? { ...state.draftThreadsByThreadKey, [key]: session }
70+
: state.draftThreadsByThreadKey,
71+
logicalProjectDraftThreadKeyByLogicalProjectKey,
72+
};
73+
});
74+
return AsyncResult.success(undefined);
75+
},
76+
commit: () => releaseDraftAttachments([...draft.images, ...draft.files]),
77+
});
78+
}

‎docs/user/keybindings.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,8 @@ a shortcut.
120120
shortcut; assign one in **Settings → Keybindings**.
121121

122122
`thread.undo` (`mod+z` by default) reverses the actions shown in the notice at the
123-
bottom of the sidebar, such as unpin, settle, snooze, or archive. Consecutive
123+
bottom of the sidebar, such as unpin, settle, snooze, archive, or discarding a
124+
draft. Consecutive
124125
actions of the same kind undo together. The notice remains available for five
125126
seconds after the latest action. The default shortcut skips text fields and
126127
terminals so native undo keeps working there.

‎docs/user/thread-sidebar.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ Pin a thread from its menu to keep it above your active work.
4848
On web and desktop, unpinning, settling, snoozing, and archiving a thread each show
4949
a notification with **Undo** for five seconds. Undo restores the thread's previous
5050
state, including its pinned position, and reopens an archived thread you were
51-
viewing. `mod+z` triggers the most recent Undo when no text field is focused; see
51+
viewing. Discarding an unsent draft from the sidebar works the same way: Undo brings
52+
back its text and attachments. `mod+z` triggers the most recent Undo when no text field is focused; see
5253
[Keybindings](./keybindings.md#commands-with-special-behavior).
5354

5455
On web and desktop, you can also drag files from your computer onto any thread row:

0 commit comments

Comments
 (0)