@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 269 lines 10.7 KB
Raw
1 import {
2 makeThreadRequestsResolvedAnnouncer,
3 userInputDraftKey,
4 } from "@t3tools/client-runtime/state/thread-requests";
5 import { ApprovalRequestId, EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
6 import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
7 import { beforeEach, expect, it, vi } from "vite-plus/test";
8 import { composerTargetKey, useComposerDraftStore } from "./composerDraftStore";
9 import {
10 addPreparingComposerImages,
11 cancelPreparingComposerImages,
12 getPreparingComposerImages,
13 } from "./components/chat/preparingComposerImages";
14 import { formatInlineContextReference } from "./lib/composerContextReferences";
15 import { threadContextReference } from "./lib/composerContextRecords";
16 import {
17 questionAttachmentDraftId,
18 countQuestionAttachments,
19 questionAttachmentDraftPrefix,
20 changeQuestionAttachmentPreparation,
21 clearQuestionAttachmentDraft,
22 usePendingUserInputAnswers,
23 useQuestionAttachmentPreparation,
24 } from "./questionAttachments";
25
26 const release = vi.hoisted(() => vi.fn());
27 vi.mock("./lib/attachmentUploadQueue", () => ({ releaseDraftAttachments: release }));
28 const environmentId = EnvironmentId.make("environment-1");
29 const threadId = ThreadId.make("thread-1");
30 const requestId = ApprovalRequestId.make("request-1");
31 beforeEach(() => {
32 useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
33 useQuestionAttachmentPreparation.setState({ counts: {} });
34 usePendingUserInputAnswers.setState({}, true);
35 release.mockClear();
36 });
37 it("keeps question files separate from the normal draft and other questions", () => {
38 const revoke = vi.spyOn(URL, "revokeObjectURL");
39 const store = useComposerDraftStore.getState();
40 const first = questionAttachmentDraftId(environmentId, threadId, requestId, "first");
41 const second = questionAttachmentDraftId(environmentId, threadId, requestId, "second");
42 store.setPrompt({ environmentId, threadId }, "Unsent prompt");
43 const image = {
44 type: "image" as const,
45 id: "image-1",
46 name: "image.png",
47 mimeType: "image/png",
48 sizeBytes: 5,
49 previewUrl: "blob:question-image",
50 file: new File(["image"], "image.png", { type: "image/png" }),
51 };
52 store.addImages(first, [image]);
53 store.addFiles(second, [
54 {
55 type: "file",
56 id: "file-1",
57 name: "spec.txt",
58 mimeType: "text/plain",
59 sizeBytes: 4,
60 file: new File(["spec"], "spec.txt", { type: "text/plain" }),
61 },
62 ]);
63 changeQuestionAttachmentPreparation(first, 1);
64 expect(store.getComposerDraft(first)?.images).toHaveLength(1);
65 expect(store.getComposerDraft(second)?.files).toHaveLength(1);
66 clearQuestionAttachmentDraft(first);
67 expect(store.getComposerDraft(first)).toBeNull();
68 expect(store.getComposerDraft(second)?.files).toHaveLength(1);
69 expect(store.getComposerDraft({ environmentId, threadId })?.prompt).toBe("Unsent prompt");
70 expect(useQuestionAttachmentPreparation.getState().counts[first]).toBeUndefined();
71 expect(release).toHaveBeenCalledWith([image]);
72 expect(revoke).toHaveBeenCalledWith(image.previewUrl);
73 revoke.mockRestore();
74 });
75 it("does not clear another environment whose id contains a question prefix", () => {
76 const otherEnvironment = EnvironmentId.make(
77 `${environmentId}:question-${encodeURIComponent(JSON.stringify(threadId))}-nested`,
78 );
79 const otherKey = questionAttachmentDraftId(otherEnvironment, threadId, requestId, "q");
80 const ownKey = questionAttachmentDraftId(environmentId, threadId, requestId, "q");
81 const store = useComposerDraftStore.getState();
82 store.setPrompt(otherKey, "Keep this answer");
83 store.setPrompt(ownKey, "Discard this answer");
84 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
85 for (const key of [ownKey, otherKey]) {
86 if (key.startsWith(prefix)) clearQuestionAttachmentDraft(key);
87 }
88 expect(store.getComposerDraft(ownKey)).toBeNull();
89 expect(store.getComposerDraft(otherKey)?.prompt).toBe("Keep this answer");
90 });
91
92 it("counts files, images, and pending preparation across the shared question budget", () => {
93 const first = questionAttachmentDraftId(environmentId, threadId, requestId, "first");
94 const second = questionAttachmentDraftId(environmentId, threadId, requestId, "second");
95 const other = questionAttachmentDraftId(
96 EnvironmentId.make("other"),
97 threadId,
98 requestId,
99 "first",
100 );
101 const store = useComposerDraftStore.getState();
102 store.addFiles(
103 second,
104 Array.from({ length: 6 }, (_, index) => ({
105 type: "file" as const,
106 id: `file-${index}`,
107 name: `spec-${index}.txt`,
108 mimeType: "text/plain",
109 sizeBytes: 4,
110 file: new File(["spec"], `spec-${index}.txt`),
111 })),
112 );
113 store.addImages(first, [
114 {
115 type: "image",
116 id: "image",
117 name: "image.png",
118 mimeType: "image/png",
119 sizeBytes: 5,
120 previewUrl: "blob:count-test",
121 file: new File(["image"], "image.png"),
122 },
123 ]);
124 changeQuestionAttachmentPreparation(second, 1);
125 changeQuestionAttachmentPreparation(other, 8);
126 expect(countQuestionAttachments([first, second])).toBe(8);
127 expect(countQuestionAttachments([second])).toBe(7);
128 changeQuestionAttachmentPreparation(second, -1);
129 expect(countQuestionAttachments([first, second])).toBe(7);
130 });
131
132 it("clears attachment drafts for requests the thread resolved, wherever they were answered", () => {
133 const store = useComposerDraftStore.getState();
134 const pending = RuntimeRequestId.make("pending");
135 const resolved = RuntimeRequestId.make("resolved");
136 const otherThread = ThreadId.make("thread-2");
137 const keep = questionAttachmentDraftId(environmentId, threadId, pending, "first");
138 const drop = questionAttachmentDraftId(environmentId, threadId, resolved, "first");
139 const elsewhere = questionAttachmentDraftId(environmentId, otherThread, resolved, "first");
140 for (const key of [keep, drop, elsewhere]) store.setPrompt(key, "Answer context");
141 changeQuestionAttachmentPreparation(drop, 1);
142 usePendingUserInputAnswers.setState({
143 [userInputDraftKey(environmentId, threadId, resolved)]: { first: { customAnswer: "Sent" } },
144 });
145
146 // The thread's projection synchronizes with only `pending` left, e.g. after
147 // `resolved` was answered on another device while no composer showed it.
148 makeThreadRequestsResolvedAnnouncer(
149 environmentId,
150 threadId,
151 )([
152 { id: pending, status: "pending" },
153 { id: resolved, status: "resolved" },
154 ]);
155
156 expect(store.getComposerDraft(keep)?.prompt).toBe("Answer context");
157 expect(store.getComposerDraft(drop)).toBeNull();
158 expect(store.getComposerDraft(elsewhere)?.prompt).toBe("Answer context");
159 expect(useQuestionAttachmentPreparation.getState().counts[drop]).toBeUndefined();
160 // An answered question's text was sent, so it does not come back as a draft.
161 expect(store.getComposerDraft({ environmentId, threadId })).toBeNull();
162 expect(usePendingUserInputAnswers.getState()).toEqual({});
163 });
164
165 // Stop cancels an open question; a provider timeout expires it. Neither sends the answer.
166 it.each(["cancelled", "expired"] as const)(
167 "returns typed answers and their thread chips to the thread draft when a question is %s",
168 (status) => {
169 const store = useComposerDraftStore.getState();
170 const request = RuntimeRequestId.make("stopped");
171 const reference = threadContextRecord(
172 { environmentId, threadId: ThreadId.make("reference-thread") },
173 "Reference work",
174 );
175 const answer = `Purple, like ${formatInlineContextReference(threadContextReference(reference))}`;
176 store.setPrompt({ environmentId, threadId }, "Earlier draft");
177 const questionDraft = questionAttachmentDraftId(environmentId, threadId, request, "first");
178 store.setThreadContexts(questionDraft, [reference]);
179 store.addFiles(questionDraft, [
180 {
181 type: "file",
182 id: "notes",
183 name: "notes.txt",
184 mimeType: "text/plain",
185 sizeBytes: 5,
186 file: new File(["notes"], "notes.txt", { type: "text/plain" }),
187 },
188 ]);
189 const photo = {
190 type: "image" as const,
191 id: "photo",
192 name: "photo.png",
193 mimeType: "image/png",
194 sizeBytes: 5,
195 previewUrl: "blob:photo",
196 file: new File(["photo"], "photo.png", { type: "image/png" }),
197 };
198 store.addImages(questionDraft, [photo]);
199 const savedPhoto = {
200 id: "photo",
201 name: "photo.png",
202 mimeType: "image/png",
203 sizeBytes: 5,
204 dataUrl: "data:image/png;base64,cGhvdG8=",
205 };
206 void store.syncPersistedAttachments(questionDraft, [savedPhoto]);
207 usePendingUserInputAnswers.setState({
208 [userInputDraftKey(environmentId, threadId, request)]: {
209 first: { customAnswer: answer },
210 second: { customAnswer: " " },
211 third: { customAnswer: "Also this" },
212 },
213 });
214
215 makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([{ id: request, status }]);
216
217 expect(store.getComposerDraft({ environmentId, threadId })).toMatchObject({
218 prompt: `Earlier draft\n\n${answer}\n\nAlso this`,
219 threadContexts: [reference],
220 files: [expect.objectContaining({ name: "notes.txt" })],
221 images: [expect.objectContaining({ id: "photo" })],
222 persistedAttachments: [savedPhoto],
223 });
224 expect(usePendingUserInputAnswers.getState()).toEqual({});
225 },
226 );
227
228 it.each(["cancelled", "expired"] as const)(
229 "returns preparing images to the thread draft when a question is %s",
230 (status) => {
231 const unanswered = RuntimeRequestId.make("request");
232 const answered = RuntimeRequestId.make("request-other");
233 const target = composerTargetKey({ environmentId, threadId });
234 const preparing = [
235 [threadId, unanswered, "first", "move-first"],
236 [threadId, unanswered, "second", "move-second"],
237 [threadId, answered, "first", "discard"],
238 [ThreadId.make("other-thread"), unanswered, "first", "stay"],
239 ] as const;
240 const keys = preparing.map(([thread, request, question, id]) => {
241 const key = questionAttachmentDraftId(environmentId, thread, request, question);
242 addPreparingComposerImages(key, [
243 { id, name: "screenshot.png", file: new File(["image"], "screenshot.png"), hidden: false },
244 ]);
245 changeQuestionAttachmentPreparation(key, 1);
246 return key;
247 });
248 using _cleanup = {
249 [Symbol.dispose]: () => {
250 for (const key of [...keys, target]) cancelPreparingComposerImages(key);
251 },
252 };
253
254 makeThreadRequestsResolvedAnnouncer(
255 environmentId,
256 threadId,
257 )([
258 { id: unanswered, status },
259 { id: answered, status: "resolved" },
260 ]);
261
262 expect(getPreparingComposerImages(target).map(({ id }) => id)).toEqual([
263 "move-first",
264 "move-second",
265 ]);
266 expect(keys.slice(0, 3).flatMap(getPreparingComposerImages)).toEqual([]);
267 expect(getPreparingComposerImages(keys[3]!).map(({ id }) => id)).toEqual(["stay"]);
268 },
269 );