Skip to content

Commit 42ca5d5

Browse files
only21milcodexclaudemaria-rcks
authored
fix(web): keep deleted clipboard attachments out of the draft (pingdotgg#23447)
Co-authored-by: GPT-6.1 Sol <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent b665f0b commit 42ca5d5

3 files changed

Lines changed: 206 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,6 +1356,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
13561356
composerContextRecords,
13571357
composerImages,
13581358
composerFilesRef,
1359+
promptRef,
13591360
pendingThreadImportsRef,
13601361
addComposerFilesToDraft,
13611362
});
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import { useEffect } from "react";
2+
import { type ComposerContextRecord, ComposerContextId, EnvironmentId } from "@t3tools/contracts";
3+
import { expect, it, vi } from "vite-plus/test";
4+
5+
import { act, render, stubGlobal } from "../../../test/render";
6+
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
7+
import { formatInlineContextReference } from "../../lib/composerContextReferences";
8+
import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments";
9+
import { pendingDraftWork } from "./pendingDraftWork";
10+
import { useComposerContextImport } from "./useComposerContextImport";
11+
12+
vi.mock("~/state/use-atom-query-runner", async (importOriginal) => ({
13+
...(await importOriginal<typeof import("~/state/use-atom-query-runner")>()),
14+
useAtomQueryRunner: () => async () => ({ _tag: "Success", value: { relativeUrl: "/file" } }),
15+
}));
16+
vi.mock("../../state/use-atom-command", async (importOriginal) => ({
17+
...(await importOriginal<typeof import("../../state/use-atom-command")>()),
18+
useAtomCommand: () => () => {},
19+
}));
20+
vi.mock("~/state/session", async (importOriginal) => ({
21+
...(await importOriginal<typeof import("~/state/session")>()),
22+
readPreparedConnection: () => ({ httpBaseUrl: "http://localhost" }),
23+
}));
24+
25+
type ImportInput = Parameters<typeof useComposerContextImport>[0];
26+
type Importer = ReturnType<typeof useComposerContextImport>;
27+
28+
function Harness({ input, ready }: { input: ImportInput; ready: (value: Importer) => void }) {
29+
const importer = useComposerContextImport(input);
30+
useEffect(() => ready(importer));
31+
return null;
32+
}
33+
34+
function deferred<T>() {
35+
let resolve!: (value: T) => void;
36+
const promise = new Promise<T>((fulfill) => {
37+
resolve = fulfill;
38+
});
39+
return { promise, resolve };
40+
}
41+
42+
it.each([
43+
{ kind: "file", edit: "delete" },
44+
{ kind: "image", edit: "delete" },
45+
{ kind: "file", edit: "undo" },
46+
{ kind: "file", edit: "retain" },
47+
{ kind: "file", edit: "switch" },
48+
{ kind: "file", edit: "cached" },
49+
{ kind: "file", edit: "question" },
50+
{ kind: "image", edit: "question" },
51+
{ kind: "image", edit: "annotation" },
52+
{ kind: "image", edit: "delete-annotation" },
53+
] as const)("settles a delayed $kind import after $edit", async ({ kind, edit }) => {
54+
const target = DraftId.make(`clipboard-${kind}-${edit}`);
55+
const store = useComposerDraftStore.getState();
56+
using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
57+
const sourceEnvironmentId = EnvironmentId.make("clipboard-source");
58+
rememberCopiedComposerAttachments(
59+
sourceEnvironmentId,
60+
edit === "cached"
61+
? new Map([["source-attachment", new File(["notes"], "notes.txt")]])
62+
: new Map(),
63+
);
64+
using _copy = {
65+
[Symbol.dispose]: () => rememberCopiedComposerAttachments(sourceEnvironmentId, new Map()),
66+
};
67+
const promptRef = { current: "" };
68+
const downloaded = deferred<Response>();
69+
const requested = deferred<void>();
70+
const settled = deferred<void>();
71+
const input = {
72+
environmentId: EnvironmentId.make("clipboard-target"),
73+
linkedEnvironments: new Map(),
74+
activeThread: undefined,
75+
activeThreadId: null,
76+
composerDraftTarget: target,
77+
attachmentDraftTarget: target,
78+
attachmentTargetKey: target,
79+
attachmentTargetKeyRef: { current: target },
80+
questionAttachmentTarget: edit === "question" ? target : null,
81+
pendingUserInputs: [],
82+
composerContextRecords: new Map(),
83+
composerImages: [],
84+
composerFilesRef: { current: [] },
85+
pendingThreadImportsRef: { current: new Map() },
86+
promptRef,
87+
addComposerFilesToDraft: (files: Parameters<typeof store.addFiles>[1]) =>
88+
store.addFiles(target, files, { appendReference: edit !== "question" }),
89+
} satisfies ImportInput & { promptRef: { current: string } };
90+
let importer!: Importer;
91+
await using _screen = await render(
92+
<Harness
93+
input={input}
94+
ready={(value) => {
95+
importer = value;
96+
}}
97+
/>,
98+
);
99+
const end = pendingDraftWork.end.bind(pendingDraftWork);
100+
using _settled = vi.spyOn(pendingDraftWork, "end").mockImplementation((key) => {
101+
end(key);
102+
settled.resolve();
103+
});
104+
using _fetch = stubGlobal("fetch", () => {
105+
requested.resolve();
106+
return downloaded.promise;
107+
});
108+
const contextId = ComposerContextId.make(`${kind}_source`);
109+
const attachmentFields = {
110+
version: 1 as const,
111+
contextId,
112+
label: "notes.txt",
113+
attachmentId: "source-attachment",
114+
name: "notes.txt",
115+
mimeType: kind === "file" ? "text/plain" : "image/png",
116+
sizeBytes: 5,
117+
};
118+
const attachment = (
119+
kind === "file"
120+
? { ...attachmentFields, kind: "file" as const }
121+
: { ...attachmentFields, kind: "image" as const }
122+
) satisfies ComposerContextRecord;
123+
const annotation = {
124+
version: 1,
125+
kind: "preview-annotation",
126+
contextId: ComposerContextId.make("preview-annotation_source"),
127+
label: "Page annotation",
128+
annotationId: "source",
129+
pageUrl: "http://localhost/page",
130+
pageTitle: "Page",
131+
comment: "Check this",
132+
targetSummary: "Page",
133+
styleChanges: [],
134+
screenshotContextId: contextId,
135+
} satisfies ComposerContextRecord;
136+
const annotated = edit === "annotation" || edit === "delete-annotation";
137+
let pastedPrompt = "";
138+
await act(async () => {
139+
const remapped = importer.importContextRecords(
140+
annotated ? [attachment, annotation] : [attachment],
141+
sourceEnvironmentId,
142+
);
143+
pastedPrompt = formatInlineContextReference({
144+
kind: annotated ? "preview-annotation" : kind,
145+
contextId: remapped.get(annotated ? annotation.contextId : contextId)!,
146+
label: annotated ? "Page annotation" : "notes.txt",
147+
});
148+
if (edit === "question") pastedPrompt = "Question answer";
149+
promptRef.current = pastedPrompt;
150+
store.setPrompt(target, pastedPrompt);
151+
if (edit !== "cached") await requested.promise;
152+
});
153+
if (edit !== "cached") expect(pendingDraftWork.has(target)).toBe(true);
154+
await act(() => {
155+
if (
156+
edit !== "annotation" &&
157+
edit !== "retain" &&
158+
edit !== "cached" &&
159+
edit !== "question" &&
160+
edit !== "switch"
161+
) {
162+
promptRef.current = "Keep this edit";
163+
store.setPrompt(target, promptRef.current);
164+
}
165+
if (edit === "undo") {
166+
promptRef.current = pastedPrompt;
167+
store.setPrompt(target, pastedPrompt);
168+
}
169+
if (edit === "switch") input.attachmentTargetKeyRef.current = DraftId.make("other-draft");
170+
});
171+
await act(async () => {
172+
downloaded.resolve(new Response("notes", { headers: { "Content-Type": attachment.mimeType } }));
173+
await settled.promise;
174+
});
175+
expect(pendingDraftWork.has(target)).toBe(false);
176+
const draft = store.getComposerDraft(target)!;
177+
expect(draft.prompt).toBe(promptRef.current);
178+
const attachments = kind === "file" ? draft.files : draft.images;
179+
expect(attachments.map((file) => file.name)).toEqual(
180+
edit === "undo" ||
181+
edit === "retain" ||
182+
edit === "annotation" ||
183+
edit === "cached" ||
184+
edit === "question"
185+
? ["notes.txt"]
186+
: [],
187+
);
188+
});

‎apps/web/src/components/chat/useComposerContextImport.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
import { assetEnvironment } from "~/state/assets";
4040
import { copiedComposerAttachmentFile } from "~/lib/copiedComposerAttachments";
4141
import { countQuestionAttachments, questionAttachmentDraftId } from "../../questionAttachments";
42+
import { collectInlineContextIds } from "../../lib/composerContextReferences";
4243
import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
4344
import { orchestrationEnvironment } from "~/state/orchestration";
4445
import { pendingDraftWork } from "./pendingDraftWork";
@@ -87,6 +88,7 @@ export function useComposerContextImport(input: {
8788
readonly composerContextRecords: ComposerDraftContextRecords;
8889
readonly composerImages: ReadonlyArray<ComposerImageAttachment>;
8990
readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
91+
readonly promptRef: RefObject<string>;
9092
readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
9193
readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[];
9294
}) {
@@ -104,6 +106,7 @@ export function useComposerContextImport(input: {
104106
composerContextRecords,
105107
composerImages,
106108
composerFilesRef,
109+
promptRef,
107110
pendingThreadImportsRef,
108111
addComposerFilesToDraft,
109112
} = input;
@@ -191,6 +194,20 @@ export function useComposerContextImport(input: {
191194
fail("Downloading it from the source failed.");
192195
return;
193196
}
197+
// Question attachments have no inline reference; annotations can own their screenshots.
198+
const references = new Set(collectInlineContextIds(promptRef.current));
199+
if (
200+
!questionAttachmentTarget &&
201+
!references.has(toKindScopedComposerContextId(record.kind, localId)) &&
202+
!(
203+
record.kind === "image" &&
204+
references.has(previewAnnotationContextId(localId)) &&
205+
getComposerDraft(composerDraftTarget)?.previewAnnotations.some(
206+
(annotation) => annotation.id === localId,
207+
)
208+
)
209+
)
210+
return;
194211
file = new File([blob], record.name, { type: record.mimeType || blob.type });
195212
}
196213
// The draft these bytes belong to may have been sent or switched away from while they

0 commit comments

Comments
 (0)