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

queued-run-edit.test.ts

305 lines11.3 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2import { Atom } from "effect/reactivity";
3import {
4 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
5 restoreAttachmentOnlyBootstrapPrompt,
6} from "@t3tools/shared/composerContextReferences";
7import {
8 ChatAttachmentId,
9 ComposerContextId,
10 MessageId,
11 EnvironmentId,
12 ThreadId,
13 ProviderInstanceId,
14 RunId,
15 type ChatAttachment,
16 type OrchestrationMessageContext,
17} from "@t3tools/contracts";
18​
19import { selectThreadModel } from "./thread-model-selection";
20import { scopedThreadKey } from "../lib/scopedEntities";
21import { appAtomRegistry } from "./atom-registry";
22import {
23 activeComposerDraftKey,
24 startQueuedRunEditSave,
25 beginQueuedRunEdit,
26 getQueuedRunEdit,
27 queuedEditDraftKey,
28 removeQueuedRunEditAttachment,
29 resolveQueuedEditPayload,
30 type QueuedRunEdit,
31} from "./queued-run-edit";
32import { threadComposerErrorsAtom } from "./thread-composer-error";
33import {
34 flushComposerDrafts,
35 getComposerDraftSnapshot,
36 setComposerDraftText,
37 waitForComposerDraftsLoaded,
38} from "./use-composer-drafts";
39​
40vi.mock("../components/ui/Dialog", () => ({ alert: vi.fn() }));
41vi.mock("./session", () => ({ readEnvironmentScope: () => false }));
42vi.mock("./threads", () => ({
43 environmentThreadShells: { threadShellAtom: () => Atom.make(null) },
44 threadEnvironment: { setModelSelection: {} },
45}));
46​
47vi.mock("expo-file-system", () => ({
48 Directory: class {
49 create() {}
50 },
51 File: class {
52 exists = false;
53 create() {}
54 write() {}
55 moveSync() {}
56 },
57 Paths: { document: { uri: "file:///documents" } },
58}));
59​
60const image = (id: string): ChatAttachment => ({
61 type: "image",
62 id: ChatAttachmentId.make(id),
63 name: `${id}.png`,
64 mimeType: "image/png",
65 sizeBytes: 10,
66});
67​
68function edit(attachments: ReadonlyArray<ChatAttachment>): QueuedRunEdit {
69 return {
70 runId: RunId.make("run-1"),
71 messageId: MessageId.make("message-1"),
72 originalText: "original",
73 existingAttachments: attachments,
74 };
76​
77function context(attachmentIds: ReadonlyArray<string>): OrchestrationMessageContext {
78 return {
79 version: 1,
80 records: attachmentIds.map((attachmentId, index) => ({
81 version: 1,
82 kind: "image",
83 contextId: ComposerContextId.make(`ctx-${index}`),
84 label: `${attachmentId}.png`,
85 attachmentId,
86 name: `${attachmentId}.png`,
87 mimeType: "image/png",
88 sizeBytes: 10,
89 })),
90 };
92​
93describe("resolveQueuedEditPayload", () => {
94 it("resends the kept server attachments ahead of the newly uploaded ones", () => {
95 const payload = resolveQueuedEditPayload({
96 edit: edit([image("kept")]),
97 draftContext: undefined,
98 draftAttachments: [{ id: "draft-1" }],
99 uploaded: [image("uploaded")],
100 });
101​
102 expect(payload.attachments.map((attachment) => attachment.id)).toEqual(["kept", "uploaded"]);
103 });
104​
105 it("rebinds context records from the draft's ids to the uploaded ones", () => {
106 const payload = resolveQueuedEditPayload({
107 edit: edit([]),
108 draftContext: context(["draft-1"]),
109 draftAttachments: [{ id: "draft-1" }],
110 uploaded: [image("uploaded")],
111 });
112​
113 expect(payload.context?.records).toEqual([
114 expect.objectContaining({ attachmentId: "uploaded" }),
115 ]);
116 });
117​
118 it("drops the record of an attachment the user removed", () => {
119 const payload = resolveQueuedEditPayload({
120 edit: edit([image("kept")]),
121 draftContext: context(["kept", "gone"]),
122 draftAttachments: [],
123 uploaded: [],
124 });
125​
126 expect(payload.attachments.map((attachment) => attachment.id)).toEqual(["kept"]);
127 expect(payload.context?.records).toEqual([expect.objectContaining({ attachmentId: "kept" })]);
128 });
129});
130​
131describe("beginQueuedRunEdit", () => {
132 it.each(["", "Ultrathink:\n"])(
133 "opens attachment-only edits without the placeholder and treats them as untouched (%j)",
134 (prefix) => {
135 const threadKey = `env-exit:attachment-only-${prefix.length}`;
136 const original = {
137 ...edit([image("kept")]),
138 originalText: prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
139 };
140 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>(
141 [{ id: original.runId, status: "queued" }],
142 );
143 beginQueuedRunEdit(threadKey, original, runs);
144 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, original.runId));
145 expect(draft.text).toBe(prefix.trimEnd());
146 expect(
147 restoreAttachmentOnlyBootstrapPrompt(draft.text, original.existingAttachments.length > 0),
148 ).toBe(original.originalText);
149 expect(getQueuedRunEdit(threadKey)).toEqual({ ...original, originalText: prefix.trimEnd() });
150 appAtomRegistry.set(runs, [{ id: original.runId, status: "running" }]);
151 expect(getQueuedRunEdit(threadKey)).toBeNull();
152 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
153 },
154 );
155​
156 it("silently drops an untouched edit when its run starts", () => {
157 const threadKey = "env-exit:thread-untouched";
158 const runId = RunId.make("run-1");
159 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
160 { id: runId, status: "queued" },
161 ]);
162 beginQueuedRunEdit(threadKey, edit([]), runs);
163​
164 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
165​
166 expect(getQueuedRunEdit(threadKey)).toBeNull();
167 expect(getComposerDraftSnapshot(threadKey).text).toBe("");
168 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
169 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBeUndefined();
170 });
171​
172 it("recovers text after a server attachment was removed", async () => {
173 await waitForComposerDraftsLoaded();
174 const threadKey = "env-exit:thread-removed-recover";
175 const runId = RunId.make("run-1");
176 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
177 { id: runId, status: "queued" },
178 ]);
179 beginQueuedRunEdit(threadKey, edit([image("removed")]), runs);
180 removeQueuedRunEditAttachment(threadKey, "removed");
181​
182 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
183 await flushComposerDrafts();
184​
185 expect(getQueuedRunEdit(threadKey)).toBeNull();
186 expect(getComposerDraftSnapshot(threadKey).text).toBe("original");
187 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
188 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
189 "That message already started. Your edit is back in the composer.",
190 );
191 });
192​
193 it("recovers changed text into an empty thread draft", async () => {
194 await waitForComposerDraftsLoaded();
195 const threadKey = "env-exit:thread-changed-recover";
196 const runId = RunId.make("run-1");
197 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
198 { id: runId, status: "queued" },
199 ]);
200 beginQueuedRunEdit(threadKey, edit([]), runs);
201 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "revised");
202​
203 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
204 await flushComposerDrafts();
205​
206 expect(getQueuedRunEdit(threadKey)).toBeNull();
207 expect(getComposerDraftSnapshot(threadKey).text).toBe("revised");
208 expect(getComposerDraftSnapshot(queuedEditDraftKey(threadKey, runId)).text).toBe("");
209 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
210 "That message already started. Your edit is back in the composer.",
211 );
212 });
213​
214 it("ends a changed edit when its run starts, without the thread's composer mounted", () => {
215 const threadKey = "env-exit:thread-exit";
216 const runId = RunId.make("run-1");
217 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
218 { id: runId, status: "queued" },
219 ]);
220 setComposerDraftText(threadKey, "other work");
221 beginQueuedRunEdit(threadKey, edit([]), runs);
222 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "changed");
223​
224 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
225​
226 expect(getQueuedRunEdit(threadKey)).toBeNull();
227 expect(getComposerDraftSnapshot(threadKey).text).toBe("other work");
228 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
229 "That message already started, so the edit was discarded.",
230 );
231 });
232​
233 it("reports a cleared edit as discarded when the run starts", () => {
234 const threadKey = "env-exit:thread-cleared";
235 const runId = RunId.make("run-1");
236 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
237 { id: runId, status: "queued" },
238 ]);
239 beginQueuedRunEdit(threadKey, edit([]), runs);
240 setComposerDraftText(queuedEditDraftKey(threadKey, runId), "");
241​
242 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
243​
244 expect(getQueuedRunEdit(threadKey)).toBeNull();
245 expect(getComposerDraftSnapshot(threadKey).text).toBe("");
246 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
247 "That message already started, so the edit was discarded.",
248 );
249 });
250​
251 it("treats a removed server attachment as a change when the run starts", () => {
252 const threadKey = "env-exit:thread-removed";
253 const runId = RunId.make("run-1");
254 const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
255 { id: runId, status: "queued" },
256 ]);
257 setComposerDraftText(threadKey, "other work");
258 beginQueuedRunEdit(threadKey, edit([image("kept")]), runs);
259 removeQueuedRunEditAttachment(threadKey, "kept");
260​
261 appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
262​
263 expect(getQueuedRunEdit(threadKey)).toBeNull();
264 expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
265 "That message already started, so the edit was discarded.",
266 );
267 });
268});
269​
270describe("activeComposerDraftKey", () => {
271 const threadKey = "env:thread";
272 const editKey = queuedEditDraftKey(threadKey, RunId.make("run-1"));
273​
274 it("keeps a queued edit's draft while that edit is open", () => {
275 expect(activeComposerDraftKey(threadKey, editKey, edit([]))).toBe(editKey);
276 });
277​
278 it("falls back to the thread's draft once the edit has ended", () => {
279 expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey);
280 });
281});
282​
283it("blocks model and option picks while a queued edit save is in flight", () => {
284 const ref = {
285 environmentId: EnvironmentId.make("env-model-save"),
286 threadId: ThreadId.make("thread"),
287 };
288 const threadKey = scopedThreadKey(ref.environmentId, ref.threadId);
289 const originalSelection = { instanceId: ProviderInstanceId.make("codex"), model: "original" };
290 const edited = { ...edit([]), modelSelection: originalSelection };
291 const draftKey = queuedEditDraftKey(threadKey, edited.runId);
292 const runs = Atom.make([{ id: edited.runId, status: "queued" }]);
293 beginQueuedRunEdit(threadKey, edited, runs);
294 const finishSave = startQueuedRunEditSave(threadKey)!;
295 const changed = {
296 ...originalSelection,
297 model: "changed",
298 options: [{ id: "effort", value: "high" }],
299 };
300 selectThreadModel({ ...ref, draftKey }, changed);
301 expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(originalSelection);
302 finishSave(false);
303 selectThreadModel({ ...ref, draftKey }, changed);
304 expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(changed);
305});