Open History to see the last commit
1import {
2 ChatAttachmentId,
3 ComposerContextId,
4 EnvironmentId,
5 MessageId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnItemId,
9} from "@t3tools/contracts";
10import { scopeThreadRef } from "@t3tools/client-runtime/environment";
11import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
12import { beforeEach, describe, expect, it } from "vite-plus/test";
13import {
14 DraftId,
15 useComposerDraftStore,
16 type ComposerFileAttachment,
17 type ComposerImageAttachment,
18} from "../../composerDraftStore";
19import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
20import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords";
21import { formatInlineContextReference } from "../../lib/composerContextReferences";
22import {
23 matchRestorableQueuedAttachment,
24 prepareQueuedEditAttachments,
25 recoverQueuedMessageEdit,
26} from "./queuedMessageEdit";
27
28const environmentId = EnvironmentId.make("remote-environment");
29const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit"));
30const editTarget = DraftId.make("queued-edit:test");
31const originalModelSelection = {
32 instanceId: ProviderInstanceId.make("codex"),
33 model: "original-model",
34};
35const changedModelSelection = { ...originalModelSelection, model: "changed-model" };
36const originalMessage = {
37 editTarget,
38 threadTarget,
39 originalText: "Original message",
40 originalReplyTo: null,
41};
42const reply = responseContextRecord({
43 citation: {
44 version: 1,
45 environmentId,
46 threadId: ThreadId.make("thread:edit"),
47 messageId: MessageId.make("message:answer"),
48 text: "Done.",
49 start: 0,
50 end: 5,
51 prefix: "",
52 suffix: "",
53 },
54 itemId: TurnItemId.make("item:answer"),
55 subagents: [],
56});
57const file: ComposerFileAttachment = {
58 type: "file",
59 id: "file:report",
60 name: "report.pdf",
61 mimeType: "application/pdf",
62 sizeBytes: 6,
63 file: new File(["report"], "report.pdf", { type: "application/pdf" }),
64};
65const image: ComposerImageAttachment = {
66 type: "image",
67 id: "image:screen",
68 name: "screen.png",
69 mimeType: "image/png",
70 sizeBytes: 5,
71 file: new File(["image"], "screen.png", { type: "image/png" }),
72 previewUrl: "blob:screen",
73};
74const uploadedFile = {
75 type: "file" as const,
76 id: "upload:report",
77 name: file.name,
78 mimeType: file.mimeType,
79 sizeBytes: file.sizeBytes,
80};
81
82describe("queued message file edits", () => {
83 beforeEach(() => {
84 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
85 });
86
87 it.each([
88 { images: [], label: "file-only" },
89 { images: [image], label: "mixed" },
90 ])("preserves a generic file in a $label save", async ({ images }) => {
91 const attachments = await prepareQueuedEditAttachments({
92 existingAttachments: [],
93 images,
94 files: [file],
95 uploadFiles: async () => [uploadedFile],
96 readImage: async () => "data:image/png;base64,aW1hZ2U=",
97 });
98 expect(attachments.at(-1)).toEqual(uploadedFile);
99 expect(attachments.length).toBe(images.length + 1);
100 if (images.length > 0)
101 expect(attachments[0]).toMatchObject({
102 type: "image",
103 dataUrl: "data:image/png;base64,aW1hZ2U=",
104 });
105 });
106
107 it("fails a save instead of dropping a file whose upload is missing", async () => {
108 await expect(
109 prepareQueuedEditAttachments({
110 existingAttachments: [],
111 images: [image],
112 files: [file],
113 uploadFiles: async () => [],
114 readImage: async () => "image",
115 }),
116 ).rejects.toThrow("Retry or remove");
117 });
118
119 it("keeps file-only edits when another client starts the queued run", () => {
120 const store = useComposerDraftStore.getState();
121 store.setPrompt(editTarget, "Original message");
122 const elsewhere: ComposerFileAttachment = {
123 ...uploadedFile,
124 id: "file:elsewhere",
125 name: "elsewhere.pdf",
126 file: null,
127 uploadedAttachmentId: "upload:elsewhere",
128 uploadEnvironmentId: EnvironmentId.make("other-environment"),
129 };
130 store.addFiles(editTarget, [file, elsewhere]);
131 expect(recoverQueuedMessageEdit(originalMessage)).toBe("kept");
132 expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Original message");
133 // An upload this environment cannot reach comes back as a file to reattach, not a dropped chip.
134 const { uploadedAttachmentId: _id, uploadEnvironmentId: _env, ...reattach } = elsewhere;
135 expect(store.getComposerDraft(threadTarget)?.files).toEqual([file, reattach]);
136 expect(store.getComposerDraft(editTarget)).toBeNull();
137 });
138
139 it("keeps the mentions and reply of a kept edit in the thread draft", () => {
140 const store = useComposerDraftStore.getState();
141 store.setPrompt(editTarget, "Edited message");
142 const thread = threadContextRecord(
143 scopeThreadRef(environmentId, ThreadId.make("thread:other")),
144 "Other",
145 );
146 const machine = environmentContextRecord(EnvironmentId.make("environment-vps"), "vps");
147 store.addThreadContexts(editTarget, [thread]);
148 store.addEnvironmentContexts(editTarget, [machine]);
149 store.setReplyTo(editTarget, reply);
150 const editedPrompt = store.getComposerDraft(editTarget)!.prompt;
151 expect(recoverQueuedMessageEdit(originalMessage)).toBe("kept");
152 expect(store.getComposerDraft(editTarget)).toBeNull();
153 expect(store.getComposerDraft(threadTarget)).toMatchObject({
154 prompt: editedPrompt,
155 threadContexts: [thread],
156 environmentContexts: [machine],
157 replyTo: reply,
158 });
159 });
160
161 it.each([
162 {
163 edit: "changed model",
164 originalReplyTo: null,
165 replyTo: null,
166 modelSelection: changedModelSelection,
167 result: "kept",
168 },
169 {
170 edit: "unchanged model",
171 originalReplyTo: null,
172 replyTo: null,
173 modelSelection: originalModelSelection,
174 result: "clean",
175 },
176 {
177 edit: "added reply",
178 originalReplyTo: null,
179 replyTo: reply,
180 originalText: "",
181 result: "kept",
182 },
183 { edit: "removed reply", originalReplyTo: reply, replyTo: null, result: "kept" },
184 {
185 edit: "unchanged reply",
186 originalReplyTo: reply,
187 replyTo: structuredClone(reply),
188 result: "clean",
189 },
190 ])(
191 "reports $result for a queued edit with $edit",
192 ({ originalReplyTo, replyTo, originalText = "Original message", modelSelection, result }) => {
193 const store = useComposerDraftStore.getState();
194 store.setPrompt(editTarget, originalText);
195 store.setReplyTo(editTarget, replyTo);
196 if (modelSelection) store.setModelSelection(editTarget, modelSelection, { explicit: true });
197 expect(
198 recoverQueuedMessageEdit({
199 editTarget,
200 threadTarget,
201 originalText,
202 originalReplyTo,
203 originalModelSelection,
204 }),
205 ).toBe(result);
206 if (result === "kept" && modelSelection) {
207 expect(
208 store.getComposerDraft(threadTarget)?.modelSelectionByProvider[modelSelection.instanceId],
209 ).toEqual(modelSelection);
210 }
211 expect(store.getComposerDraft(editTarget)).toBeNull();
212 expect(store.getComposerDraft(threadTarget)).toEqual(
213 result === "kept" ? expect.objectContaining({ prompt: originalText, replyTo }) : null,
214 );
215 },
216 );
217
218 it("reports a removed queued attachment as an edit when the run leaves", () => {
219 const store = useComposerDraftStore.getState();
220 store.setPrompt(editTarget, "Original message");
221 expect(
222 recoverQueuedMessageEdit({
223 ...originalMessage,
224 removedExistingAttachment: true,
225 }),
226 ).toBe("kept");
227 expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Original message");
228 store.clearComposerContent(threadTarget);
229 // An attachment-only message leaves nothing to put back in the composer.
230 expect(
231 recoverQueuedMessageEdit({
232 ...originalMessage,
233 originalText: "",
234 removedExistingAttachment: true,
235 }),
236 ).toBe("discarded");
237 expect(store.getComposerDraft(threadTarget)).toBeNull();
238 });
239
240 it("strips existing queued attachment references when recovering an edit into the thread draft", () => {
241 const store = useComposerDraftStore.getState();
242 const chip = formatInlineContextReference({
243 kind: "image",
244 contextId: "image_queued-1",
245 label: "image.png",
246 });
247 store.setPrompt(editTarget, `Check ${chip} closely`);
248 expect(
249 recoverQueuedMessageEdit({
250 ...originalMessage,
251 originalText: `Check ${chip}`,
252 existingAttachmentContextIds: ["image_queued-1"],
253 }),
254 ).toBe("kept");
255 expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely");
256 expect(store.getComposerDraft(editTarget)).toBeNull();
257
258 store.clearComposerContent(threadTarget);
259 store.setPrompt(editTarget, chip);
260 expect(
261 recoverQueuedMessageEdit({
262 ...originalMessage,
263 originalText: `${chip} note`,
264 existingAttachmentContextIds: ["image_queued-1"],
265 }),
266 ).toBe("discarded");
267 expect(store.getComposerDraft(threadTarget)).toBeNull();
268 });
269
270 it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => {
271 const fileId = ChatAttachmentId.make("server-file-1");
272 const contextId = ComposerContextId.make("file_local-1");
273 const removedAttachment = {
274 type: "file" as const,
275 id: fileId,
276 name: "notes.txt",
277 mimeType: "text/plain",
278 sizeBytes: 12,
279 };
280 const record = {
281 version: 1 as const,
282 kind: "file" as const,
283 contextId,
284 label: "notes.txt",
285 attachmentId: fileId,
286 name: "notes.txt",
287 mimeType: "text/plain",
288 sizeBytes: 12,
289 };
290
291 expect(
292 matchRestorableQueuedAttachment({
293 environmentId,
294 sourceEnvironmentId: environmentId,
295 record,
296 removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }],
297 }),
298 ).toEqual({ attachment: removedAttachment, contextId });
299
300 expect(
301 matchRestorableQueuedAttachment({
302 environmentId,
303 sourceEnvironmentId: EnvironmentId.make("other-environment"),
304 record,
305 removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }],
306 }),
307 ).toBeNull();
308
309 expect(
310 matchRestorableQueuedAttachment({
311 environmentId,
312 sourceEnvironmentId: environmentId,
313 record: { ...record, attachmentId: ChatAttachmentId.make("different-file") },
314 removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }],
315 }),
316 ).toBeNull();
317 });
318
319 it("does not overwrite a separate draft when the queued run leaves", () => {
320 const store = useComposerDraftStore.getState();
321 store.setPrompt(threadTarget, "Separate draft");
322 store.addFiles(editTarget, [file]);
323 useAttachmentUploadStore.setState({
324 uploadsByImageId: {
325 [file.id]: { status: "ready", environmentId, attachmentId: uploadedFile.id },
326 },
327 });
328 expect(recoverQueuedMessageEdit({ ...originalMessage, originalText: "" })).toBe("discarded");
329 expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Separate draft");
330 expect(store.getComposerDraft(editTarget)).toBeNull();
331 expect(readAttachmentUpload(file.id)).toBeUndefined();
332 });
333});