Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

queued-run-edit.test.ts

407 lines15.4 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2import { Atom } from "effect/reactivity";
3import {
4 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
5 formatComposerContextReference,
6 restoreAttachmentOnlyBootstrapPrompt,
7} from "@t3tools/shared/composerContextReferences";
8import {
9 ChatAttachmentId,
10 ComposerContextId,
11 MessageId,
12 EnvironmentId,
13 ThreadId,
14 ProviderInstanceId,
15 RunId,
16 type ChatAttachment,
17 type ComposerContextRecord,
18 type OrchestrationMessageContext,
19} from "@t3tools/contracts";
20​
21import { selectThreadModel } from "./thread-model-selection";
22import { scopedThreadKey } from "../lib/scopedEntities";
23import { appAtomRegistry } from "./atom-registry";
24import {
25 activeComposerDraftKey,
26 startQueuedRunEditSave,
27 beginQueuedRunEdit,
28 getQueuedRunEdit,
29 queuedEditDraftKey,
30 removeQueuedRunEditAttachment,
31 resolveQueuedEditPayload,
32 type QueuedRunEdit,
33} from "./queued-run-edit";
34import { threadComposerErrorsAtom } from "./thread-composer-error";
35import {
36 flushComposerDrafts,
37 getComposerDraftSnapshot,
38 setComposerDraftText,
39 waitForComposerDraftsLoaded,
40} from "./use-composer-drafts";
41​
42vi.mock("../components/ui/Dialog", () => ({ alert: vi.fn() }));
43vi.mock("./session", () => ({ readEnvironmentScope: () => false }));
44vi.mock("./threads", () => ({
45 environmentThreadShells: { threadShellAtom: () => Atom.make(null) },
46 threadEnvironment: { setModelSelection: {} },
47}));
48​
49vi.mock("expo-file-system", () => ({
50 Directory: class {
51 create() {}
52 },
53 File: class {
54 exists = false;
55 create() {}
56 write() {}
57 moveSync() {}
58 },
59 Paths: { document: { uri: "file:///documents" } },
60}));
61​
62const image = (id: string): ChatAttachment => ({
63 type: "image",
64 id: ChatAttachmentId.make(id),
65 name: `${id}.png`,
66 mimeType: "image/png",
67 sizeBytes: 10,
68});
69​
70const file = (id: string): ChatAttachment => ({
71 type: "file",
72 id: ChatAttachmentId.make(id),
73 name: `${id}.txt`,
74 mimeType: "text/plain",
75 sizeBytes: 10,
76});
77​
78function edit(attachments: ReadonlyArray<ChatAttachment>): QueuedRunEdit {
79 return {
80 runId: RunId.make("run-1"),
81 messageId: MessageId.make("message-1"),
82 originalText: "original",
83 existingAttachments: attachments,
84 };
86​
87function record(attachment: ChatAttachment, index: number): ComposerContextRecord {
88 const binding = {
89 version: 1,
90 contextId: ComposerContextId.make(`ctx-${index}`),
91 label: attachment.name,
92 attachmentId: attachment.id,
93 name: attachment.name,
94 mimeType: attachment.mimeType,
95 sizeBytes: attachment.sizeBytes,
96 } as const;
97 return attachment.type === "image" ? { ...binding, kind: "image" } : { ...binding, kind: "file" };
99​
100function context(attachmentIds: ReadonlyArray<string>): OrchestrationMessageContext {
101 return { version: 1, records: attachmentIds.map((id, index) => record(image(id), index)) };
103​
104describe("resolveQueuedEditPayload", () => {
105 it("resends the kept server attachments ahead of the newly uploaded ones", () => {
106 const payload = resolveQueuedEditPayload({
107 edit: edit([image("kept")]),
108 draftContext: undefined,
109 draftAttachments: [{ id: "draft-1" }],
110 uploaded: [image("uploaded")],
111 });
112​
113 expect(payload.attachments.map((attachment) => attachment.id)).toEqual(["kept", "uploaded"]);
114 });
115​
116 it("rebinds context records from the draft's ids to the uploaded ones", () => {
117 const payload = resolveQueuedEditPayload({
118 edit: edit([]),
119 draftContext: context(["draft-1"]),
120 draftAttachments: [{ id: "draft-1" }],
121 uploaded: [image("uploaded")],
122 });
123​
124 expect(payload.context?.records).toEqual([
125 expect.objectContaining({ attachmentId: "uploaded" }),
126 ]);
127 });
128​
129 it("drops the record of an attachment the user removed", () => {
130 const payload = resolveQueuedEditPayload({
131 edit: edit([image("kept")]),
132 draftContext: context(["kept", "gone"]),
133 draftAttachments: [],
134 uploaded: [],
135 });
136​
137 expect(payload.attachments.map((attachment) => attachment.id)).toEqual(["kept"]);
138 expect(payload.context?.records).toEqual([expect.objectContaining({ attachmentId: "kept" })]);
139 });
140​
141 it("drops a server file whose chip left the text, and keeps an image as a draft does", () => {
142 const attachments = [file("gone"), file("kept"), image("photo"), file("unchipped")];
143 const records = attachments.map(record);
144 const [gone, kept, photo] = records;
145 const payload = resolveQueuedEditPayload({
146 edit: {
147 ...edit(attachments),
148 originalText: [gone!, kept!, photo!].map(formatComposerContextReference).join(" "),
149 context: { version: 1, records },
150 },
151 draftContext: { version: 1, records: [kept!] },
152 draftAttachments: [],
153 uploaded: [],
154 });
155​
156 expect(payload.attachments.map((attachment) => attachment.id)).toEqual([
157 "kept",
158 "photo",
159 "unchipped",
160 ]);
161 });
162});
163​
164describe("beginQueuedRunEdit", () => {
165 it.each(["", "Ultrathink:\n"])(
166 "opens attachment-only edits without the placeholder and treats them as untouched (%j)",
167 (prefix) => {
168 const threadKey = `env-exit:attachment-only-${prefix.length}`;
169 const original = {
170 ...edit([image("kept")]),
171 originalText: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
172 };
173 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>(
174 [{ id: original.runId, status: "queued" }],
175 );
176 beginQueuedRunEdit(threadKey, original, runs);
177 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, original.runId));
178 expect(draft.text).toBe(prefix.trimEnd());
179 expect(
180 restoreAttachmentOnlyBootstrapPrompt(draft.text, original.existingAttachments.length > 0),
181 ).toBe(original.originalText);
182 expect(getQueuedRunEdit(threadKey)).toEqual({ ...original, originalText: prefix.trimEnd() });
183 appAtomRegistry.set(runs, [{ id: original.runId, status: "running" }]);
184 expect(getQueuedRunEdit(threadKey)).toBeNull();
185 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
186 },
187 );
188​
189 it("silently drops an untouched edit when its run starts", () => {
190 const threadKey = "env-exit:thread-untouched";
191 const runId = RunId.make("run-1");
192 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
193 { id: runId, status: "queued" },
194 ]);
195 beginQueuedRunEdit(threadKey, edit([]), runs);
196​
197 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
198​
199 expect(getQueuedRunEdit(threadKey)).toBeNull();
200 expect(getComposerDraftSnapshot(threadKey).text).toBe("");
201 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
202 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
203 });
204​
205 it.each(["polish it $ui-taste", "ask model:codex/gpt-5"])(
206 "keeps a trailing chip and treats the edit as untouched (%j)",
207 (sentText) => {
208 const threadKey = `env-exit:thread-trailing-${sentText}`;
209 const runId = RunId.make("run-1");
210 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>(
211 [{ id: runId, status: "queued" }],
212 );
213 beginQueuedRunEdit(threadKey, { ...edit([]), originalText: sentText }, runs);
214​
215 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe(
216 `${sentText} `,
217 );
218 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
219 expect(getComposerDraftSnapshot(threadKey).text).toBe("");
220 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
221 },
222 );
223​
224 it("recovers text after a server attachment was removed", async () => {
225 await waitForComposerDraftsLoaded();
226 const threadKey = "env-exit:thread-removed-recover";
227 const runId = RunId.make("run-1");
228 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
229 { id: runId, status: "queued" },
230 ]);
231 beginQueuedRunEdit(threadKey, edit([image("removed")]), runs);
232 removeQueuedRunEditAttachment(threadKey, "removed");
233​
234 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
235 await flushComposerDrafts();
236​
237 expect(getQueuedRunEdit(threadKey)).toBeNull();
238 expect(getComposerDraftSnapshot(threadKey).text).toBe("original");
239 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
240 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
241 "That message already started. Your edit is back in the composer.",
242 );
243 });
244​
245 it("recovers changed text into an empty thread draft", async () => {
246 await waitForComposerDraftsLoaded();
247 const threadKey = "env-exit:thread-changed-recover";
248 const runId = RunId.make("run-1");
249 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
250 { id: runId, status: "queued" },
251 ]);
252 beginQueuedRunEdit(threadKey, edit([]), runs);
253 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "revised");
254​
255 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
256 await flushComposerDrafts();
257​
258 expect(getQueuedRunEdit(threadKey)).toBeNull();
259 expect(getComposerDraftSnapshot(threadKey).text).toBe("revised");
260 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
261 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
262 "That message already started. Your edit is back in the composer.",
263 );
264 });
265​
266 it("recovers an edit without chips for the started message's own attachments", async () => {
267 await waitForComposerDraftsLoaded();
268 const threadKey = "env-exit:thread-recover-chips";
269 const runId = RunId.make("run-1");
270 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
271 { id: runId, status: "queued" },
272 ]);
273 const withChip = context(["kept"]);
274 const chip = formatComposerContextReference(withChip.records[0]!);
275 beginQueuedRunEdit(
276 threadKey,
277 { ...edit([image("kept")]), originalText: `look ${chip}`, context: withChip },
278 runs,
279 );
280 setComposerDraftText(queuedEditDraftKey(threadKey, runId), `look closer ${chip}`);
281​
282 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
283 await flushComposerDrafts();
284​
285 const recovered = getComposerDraftSnapshot(threadKey);
286 expect(recovered.text).toContain("look closer");
287 expect(recovered.text).not.toContain(chip);
288 expect(recovered.context).toBeUndefined();
289 });
290​
291 it("ends a changed edit when its run starts, without the thread's composer mounted", () => {
292 const threadKey = "env-exit:thread-exit";
293 const runId = RunId.make("run-1");
294 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
295 { id: runId, status: "queued" },
296 ]);
297 setComposerDraftText(threadKey, "other work");
298 beginQueuedRunEdit(threadKey, edit([]), runs);
299 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "changed");
300​
301 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
302​
303 expect(getQueuedRunEdit(threadKey)).toBeNull();
304 expect(getComposerDraftSnapshot(threadKey).text).toBe("other work");
305 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
306 "That message already started, so the edit was discarded.",
307 );
308 });
309​
310 it("reports a cleared edit as discarded when the run starts", () => {
311 const threadKey = "env-exit:thread-cleared";
312 const runId = RunId.make("run-1");
313 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
314 { id: runId, status: "queued" },
315 ]);
316 beginQueuedRunEdit(threadKey, edit([]), runs);
317 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "");
318​
319 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
320​
321 expect(getQueuedRunEdit(threadKey)).toBeNull();
322 expect(getComposerDraftSnapshot(threadKey).text).toBe("");
323 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
324 "That message already started, so the edit was discarded.",
325 );
326 });
327​
328 it("removes a server attachment's chip from the edit text along with its thumbnail", () => {
329 const threadKey = "env-exit:thread-removed-chip";
330 const runId = RunId.make("run-1");
331 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
332 { id: runId, status: "queued" },
333 ]);
334 const withChips = context(["kept", "gone"]);
335 const [keptRecord, goneRecord] = withChips.records;
336 const originalText = `look ${formatComposerContextReference(keptRecord!)} and ${formatComposerContextReference(goneRecord!)}`;
337 beginQueuedRunEdit(
338 threadKey,
339 { ...edit([image("kept"), image("gone")]), originalText, context: withChips },
340 runs,
341 );
342​
343 removeQueuedRunEditAttachment(threadKey, "gone");
344​
345 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId));
346 expect(draft.text).toContain(formatComposerContextReference(keptRecord!));
347 expect(draft.text).not.toContain(formatComposerContextReference(goneRecord!));
348 expect(draft.context?.records.map((record) => record.contextId)).toEqual([
349 keptRecord!.contextId,
350 ]);
351 });
352​
353 it("treats a removed server attachment as a change when the run starts", () => {
354 const threadKey = "env-exit:thread-removed";
355 const runId = RunId.make("run-1");
356 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
357 { id: runId, status: "queued" },
358 ]);
359 setComposerDraftText(threadKey, "other work");
360 beginQueuedRunEdit(threadKey, edit([image("kept")]), runs);
361 removeQueuedRunEditAttachment(threadKey, "kept");
362​
363 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
364​
365 expect(getQueuedRunEdit(threadKey)).toBeNull();
366 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
367 "That message already started, so the edit was discarded.",
368 );
369 });
370});
371​
372describe("activeComposerDraftKey", () => {
373 const threadKey = "env:thread";
374 const editKey = queuedEditDraftKey(threadKey, RunId.make("run-1"));
375​
376 it("keeps a queued edit's draft while that edit is open", () => {
377 expect(activeComposerDraftKey(threadKey, editKey, edit([]))).toBe(editKey);
378 });
379​
380 it("falls back to the thread's draft once the edit has ended", () => {
381 expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey);
382 });
383});
384​
385it("blocks model and option picks while a queued edit save is in flight", () => {
386 const ref = {
387 environmentId: EnvironmentId.make("env-model-save"),
388 threadId: ThreadId.make("thread"),
389 };
390 const threadKey = scopedThreadKey(ref.environmentId, ref.threadId);
391 const originalSelection = { instanceId: ProviderInstanceId.make("codex"), model: "original" };
392 const edited = { ...edit([]), modelSelection: originalSelection };
393 const draftKey = queuedEditDraftKey(threadKey, edited.runId);
394 const runs = Atom.make([{ id: edited.runId, status: "queued" }]);
395 beginQueuedRunEdit(threadKey, edited, runs);
396 const finishSave = startQueuedRunEditSave(threadKey)!;
397 const changed = {
398 ...originalSelection,
399 model: "changed",
400 options: [{ id: "effort", value: "high" }],
401 };
402 selectThreadModel({ ...ref, draftKey }, changed);
403 expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(originalSelection);
404 finishSave(false);
405 selectThreadModel({ ...ref, draftKey }, changed);
406 expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(changed);
407});