Skip to content

Commit 9d54e21

Browse files
committed
fix(web): preserve citation drafts when source disappears
1 parent 37e0786 commit 9d54e21

2 files changed

Lines changed: 175 additions & 10 deletions

File tree

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import {
2+
ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
3+
EnvironmentId,
4+
MessageId,
5+
ThreadId,
6+
} from "@t3tools/contracts";
7+
import { act, useState, type ReactNode } from "react";
8+
import { create, type ReactTestRenderer } from "react-test-renderer";
9+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10+
11+
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
12+
13+
const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
14+
vi.mock("./AssistantCitationSource", () => ({
15+
observeAssistantCitationCommentSource: mocks.observeSource,
16+
}));
17+
vi.mock("@tanstack/react-router", () => ({
18+
useNavigate: () => vi.fn(),
19+
Link: ({ children }: { children: ReactNode }) => <a>{children}</a>,
20+
}));
21+
// Keep the real chip/editor lifecycle while replacing DOM positioning and portals.
22+
vi.mock("../ui/popover", () => ({
23+
Popover: ({ children }: { children: ReactNode }) => <>{children}</>,
24+
PopoverTrigger: ({ children }: { children: ReactNode }) => <button>{children}</button>,
25+
PopoverPopup: ({ children }: { children: ReactNode }) => <>{children}</>,
26+
}));
27+
vi.mock("../ui/button", () => ({
28+
Button: (props: React.ComponentProps<"button">) => <button {...props} />,
29+
}));
30+
31+
import { PopoverPopup } from "../ui/popover";
32+
import { AssistantCitationChip } from "./AssistantCitationChip";
33+
34+
const citation = {
35+
version: 1 as const,
36+
environmentId: EnvironmentId.make("environment"),
37+
threadId: ThreadId.make("thread"),
38+
messageId: MessageId.make("source"),
39+
text: "hello",
40+
start: 0,
41+
end: 5,
42+
prefix: "",
43+
suffix: "",
44+
};
45+
// The observer owns DOM access; these identities let us check which anchor survives.
46+
const sourceAnchor = {
47+
source: {},
48+
range: {},
49+
viewport: {},
50+
} as AssistantCitationSourceAnchor;
51+
52+
let renderer: ReactTestRenderer;
53+
54+
function mount(onSave = vi.fn(() => true)) {
55+
function Composer() {
56+
const [open, setOpen] = useState(true);
57+
return (
58+
<AssistantCitationChip
59+
citation={citation}
60+
onRemove={() => {}}
61+
commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
62+
/>
63+
);
64+
}
65+
act(() => {
66+
renderer = create(<Composer />);
67+
});
68+
return onSave;
69+
}
70+
71+
function typeComment(value: string) {
72+
act(() => renderer.root.findByType("textarea").props.onChange({ currentTarget: { value } }));
73+
}
74+
75+
function removeSource() {
76+
const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
77+
act(() => onUnavailable());
78+
}
79+
80+
function clickButton(label: string) {
81+
act(() =>
82+
renderer.root
83+
.findAllByType("button")
84+
.find((button) => button.props.children === label)!
85+
.props.onClick(),
86+
);
87+
}
88+
89+
beforeEach(() => {
90+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
91+
mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
92+
mocks.dispose.mockClear();
93+
});
94+
95+
afterEach(() => {
96+
act(() => renderer?.unmount());
97+
vi.unstubAllGlobals();
98+
});
99+
100+
describe("citation comment source disappearance", () => {
101+
it("preserves an over-length draft at the composer until it can be shortened and saved", () => {
102+
const onSave = mount();
103+
const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
104+
typeComment(draft);
105+
removeSource();
106+
107+
expect(renderer.root.findByType("textarea").props.value).toBe(draft);
108+
expect(renderer.root.findByType("textarea").props["aria-invalid"]).toBe(true);
109+
expect(renderer.root.findByType(PopoverPopup).props.anchor).toBeUndefined();
110+
expect(renderer.root.findByType(PopoverPopup).props.side).toBe("top");
111+
expect(onSave).not.toHaveBeenCalled();
112+
expect(mocks.dispose).toHaveBeenCalled();
113+
expect(mocks.observeSource).toHaveBeenCalledTimes(1);
114+
115+
typeComment("shortened comment");
116+
clickButton("Save");
117+
expect(onSave).toHaveBeenCalledWith("shortened comment");
118+
expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
119+
});
120+
121+
it("preserves a rejected save and allows a later retry", () => {
122+
const onSave = mount(vi.fn(() => false));
123+
typeComment("keep this draft");
124+
removeSource();
125+
126+
expect(onSave).toHaveBeenCalledWith("keep this draft");
127+
expect(renderer.root.findByType("textarea").props.value).toBe("keep this draft");
128+
expect(renderer.root.findByType(PopoverPopup).props.anchor).toBeUndefined();
129+
onSave.mockReturnValue(true);
130+
clickButton("Save");
131+
expect(onSave).toHaveBeenLastCalledWith("keep this draft");
132+
expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
133+
});
134+
135+
it("still allows explicit cancellation after source disappearance", () => {
136+
const onSave = mount(vi.fn(() => false));
137+
typeComment("discard this draft");
138+
removeSource();
139+
onSave.mockClear();
140+
clickButton("Cancel");
141+
expect(onSave).not.toHaveBeenCalled();
142+
expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
143+
});
144+
145+
it("saves and closes when the source disappears with a valid draft", () => {
146+
const onSave = mount();
147+
typeComment("saved comment");
148+
removeSource();
149+
expect(onSave).toHaveBeenCalledWith("saved comment");
150+
expect(renderer.root.findAllByType("textarea")).toHaveLength(0);
151+
});
152+
});

‎apps/web/src/components/chat/AssistantCitationChip.tsx‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ import type { AssistantCitation } from "@t3tools/contracts";
22
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
33
import { Link, useNavigate } from "@tanstack/react-router";
44
import { PencilIcon, QuoteIcon, XIcon } from "lucide-react";
5-
import { useEffect, useEffectEvent, useRef, type MouseEvent as ReactMouseEvent } from "react";
5+
import {
6+
useEffect,
7+
useEffectEvent,
8+
useRef,
9+
useState,
10+
type MouseEvent as ReactMouseEvent,
11+
} from "react";
612
import {
713
findAssistantCitationSourceAnchor,
814
type AssistantCitationSourceAnchor,
@@ -50,8 +56,11 @@ export function AssistantCitationChip({
5056
const navigate = useNavigate();
5157
const commentInputRef = useRef<HTMLTextAreaElement>(null);
5258
const draftCommentRef = useRef<string | null>(null);
59+
const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
60+
useState<AssistantCitationSourceAnchor | null>(null);
5361
const commentOpen = commentEditor?.open ?? false;
5462
const sourceAnchor = commentEditor?.sourceAnchor;
63+
const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
5564
useEffect(() => {
5665
if (!commentOpen) draftCommentRef.current = null;
5766
}, [commentOpen]);
@@ -66,27 +75,31 @@ export function AssistantCitationChip({
6675
};
6776
const onSourceUnavailable = useEffectEvent(() => {
6877
if (!sourceAnchor) return;
69-
settleDraftOnClose("none");
70-
commentEditor?.onOpenChange(false);
78+
if (settleDraftOnClose("none")) {
79+
commentEditor?.onOpenChange(false);
80+
} else {
81+
// Keep the draft mounted, positioned at the composer trigger instead of a detached range.
82+
setUnavailableSourceAnchor(sourceAnchor);
83+
}
7184
});
7285
useEffect(() => {
73-
if (!commentOpen) return;
86+
if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
7487
const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
7588
if (!anchor) return;
7689
return observeAssistantCitationCommentSource({
7790
anchor,
7891
citation,
7992
onUnavailable: onSourceUnavailable,
8093
});
81-
}, [citation, commentOpen, sourceAnchor]);
94+
}, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
8295
// A multi-line selection's bounding box spans the full message width; anchor
8396
// the bubble to the selection's last line, where the pointer released.
84-
const popupAnchor = sourceAnchor
97+
const popupAnchor = activeSourceAnchor
8598
? {
86-
contextElement: sourceAnchor.source,
99+
contextElement: activeSourceAnchor.source,
87100
getBoundingClientRect: () => {
88-
const rects = sourceAnchor.range.getClientRects();
89-
return rects.item(rects.length - 1) ?? sourceAnchor.range.getBoundingClientRect();
101+
const rects = activeSourceAnchor.range.getClientRects();
102+
return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
90103
},
91104
}
92105
: undefined;
@@ -164,7 +177,7 @@ export function AssistantCitationChip({
164177
{commentEditor.open ? (
165178
<PopoverPopup
166179
{...composerFloatingLayerProps}
167-
side={sourceAnchor ? "bottom" : "top"}
180+
side={activeSourceAnchor ? "bottom" : "top"}
168181
align="end"
169182
anchor={popupAnchor}
170183
initialFocus={() => {

0 commit comments

Comments
 (0)