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