Open History to see the last commit
1import {
2 type ComposerContextId,
3 EnvironmentId,
4 MessageId,
5 OrchestrationMessageContext,
6 ThreadId,
7 type PreviewAnnotationPayload,
8} from "@t3tools/contracts";
9import * as Schema from "effect/Schema";
10import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
11
12import {
13 formatInlineContextReference,
14 removeInlineContextReference,
15} from "./composerContextReferences";
16import { describe, expect, it } from "vite-plus/test";
17
18import {
19 asKnownContextRecord,
20 buildMessageContext,
21 composerContextImportLookupIds,
22 isSameComposerContextPayload,
23 previewAnnotationContextRecord,
24 previewAnnotationFromRecord,
25 resolveUserMessageContext,
26 selectedMessageContextFragment,
27 reviewCommentContextRecord,
28 terminalContextRecord,
29 terminalContextReference,
30 terminalContextDraftFromRecord,
31 uploadedAttachmentContextRecord,
32} from "./composerContextRecords";
33
34const decodeMessageContext = Schema.decodeUnknownSync(OrchestrationMessageContext);
35
36const annotation: PreviewAnnotationPayload = {
37 id: "ann_1",
38 pageUrl: "http://localhost:3000/checkout",
39 pageTitle: "Checkout",
40 comment: " Make this bigger ",
41 elements: [
42 {
43 id: "el_1",
44 rect: { x: 0, y: 0, width: 10, height: 10 },
45 element: {
46 pageUrl: "http://localhost:3000/checkout",
47 pageTitle: "Checkout",
48 tagName: "BUTTON",
49 selector: "#pay",
50 htmlPreview: '<button id="pay">Pay</button>',
51 componentName: "Button",
52 source: null,
53 stack: [],
54 styles: "color: red;",
55 pickedAt: "2026-01-01T00:00:00.000Z",
56 },
57 },
58 ],
59 regions: [],
60 strokes: [],
61 styleChanges: [
62 { targetId: "el_1", selector: "#pay", property: "font-size", previousValue: "", value: "20px" },
63 ],
64 screenshot: null,
65 createdAt: "2026-01-01T00:00:00.000Z",
66};
67
68describe("composerContextRecords", () => {
69 it("copies only ready or persisted server-side attachment IDs", () => {
70 const environmentId = EnvironmentId.make("env");
71 const image = {
72 type: "image" as const,
73 id: "local-image",
74 name: "shot.png",
75 mimeType: "image/png",
76 sizeBytes: 1,
77 file: new File(["x"], "shot.png"),
78 previewUrl: "blob:shot",
79 };
80 expect(uploadedAttachmentContextRecord(image, undefined)).toBeNull();
81 expect(
82 uploadedAttachmentContextRecord(image, { status: "uploading", environmentId, progress: 0.5 }),
83 ).toBeNull();
84 expect(
85 uploadedAttachmentContextRecord(image, {
86 status: "failed",
87 environmentId,
88 reason: "offline",
89 attachmentId: "unfinished",
90 }),
91 ).toBeNull();
92 expect(
93 uploadedAttachmentContextRecord(image, {
94 status: "ready",
95 environmentId,
96 attachmentId: "uploaded-image",
97 }),
98 ).toMatchObject({ attachmentId: "uploaded-image", contextId: "image_local-image" });
99 const file = {
100 type: "file" as const,
101 id: "local-file",
102 name: "notes.txt",
103 mimeType: "text/plain",
104 sizeBytes: 1,
105 file: null,
106 };
107 expect(uploadedAttachmentContextRecord(file, undefined)).toBeNull();
108 expect(
109 uploadedAttachmentContextRecord(
110 { ...file, uploadedAttachmentId: "persisted-file", uploadEnvironmentId: environmentId },
111 undefined,
112 ),
113 ).toMatchObject({ attachmentId: "persisted-file", contextId: "file_local-file" });
114 });
115 it("does not bind an annotation screenshot to a same-ID file", () => {
116 const context = buildMessageContext({
117 terminalContexts: [],
118 reviewComments: [],
119 previewAnnotations: [annotation],
120 attachments: [
121 {
122 attachment: {
123 type: "file",
124 id: annotation.id,
125 name: "notes.txt",
126 mimeType: "text/plain",
127 sizeBytes: 1,
128 file: null,
129 },
130 attachmentId: "uploaded-file",
131 },
132 ],
133 })!;
134 expect(context.records.map((record) => record.kind)).toEqual(["preview-annotation", "file"]);
135 expect(context.records[0]).not.toHaveProperty("screenshotContextId");
136 });
137 it.each(["x", "terminal_x"])(
138 "preserves canonical terminal IDs across repeated imports: %s",
139 (id) => {
140 const threadId = ThreadId.make("t1");
141 const record = terminalContextRecord({
142 id,
143 threadId,
144 terminalId: "default",
145 terminalLabel: "Terminal",
146 lineStart: 1,
147 lineEnd: 1,
148 text: "output",
149 createdAt: "2026-01-01T00:00:00.000Z",
150 });
151 const restored = terminalContextRecord(terminalContextDraftFromRecord(record, threadId));
152 expect(restored).toEqual(record);
153 expect(terminalContextRecord(terminalContextDraftFromRecord(restored, threadId))).toEqual(
154 record,
155 );
156 },
157 );
158 it("scopes colliding producer ids and links the annotation to its screenshot record", () => {
159 const id = "same.id:1";
160 const context = buildMessageContext({
161 terminalContexts: [
162 {
163 id,
164 threadId: ThreadId.make("t1"),
165 terminalId: "default",
166 terminalLabel: "Terminal",
167 lineStart: 1,
168 lineEnd: 1,
169 text: "output",
170 createdAt: "2026-01-01T00:00:00.000Z",
171 },
172 ],
173 reviewComments: [
174 {
175 id,
176 sectionId: "s",
177 sectionTitle: "Review",
178 filePath: "file.ts",
179 startIndex: 0,
180 endIndex: 0,
181 rangeLabel: "L1",
182 text: "Review",
183 diff: "",
184 },
185 ],
186 previewAnnotations: [{ ...annotation, id }],
187 attachments: [
188 {
189 attachment: {
190 type: "image",
191 id,
192 name: "shot.png",
193 mimeType: "image/png",
194 sizeBytes: 1,
195 file: new File(["x"], "shot.png"),
196 previewUrl: "blob:shot",
197 },
198 attachmentId: "uploaded-image",
199 },
200 {
201 attachment: {
202 type: "file",
203 id,
204 name: "file.txt",
205 mimeType: "text/plain",
206 sizeBytes: 1,
207 file: null,
208 },
209 attachmentId: "uploaded-file",
210 },
211 ],
212 })!;
213 expect(decodeMessageContext(context).records).toHaveLength(5);
214 const preview = context.records.find((record) => record.kind === "preview-annotation");
215 const image = context.records.find((record) => record.kind === "image");
216 expect(preview).toMatchObject({ screenshotContextId: image!.contextId });
217 expect(image).toMatchObject({ attachmentId: "uploaded-image" });
218 });
219
220 it("restores multiple edits on one target without parsing display strings", () => {
221 const styleChanges = [
222 ...annotation.styleChanges,
223 {
224 targetId: "el_1",
225 selector: "#pay",
226 property: "content",
227 previousValue: "a → b",
228 value: "first\nsecond → third",
229 },
230 ];
231 const restored = previewAnnotationFromRecord(
232 previewAnnotationContextRecord({ ...annotation, styleChanges }),
233 );
234 expect(restored.styleChanges).toEqual(styleChanges);
235 expect(restored.elements[0]?.id).toBe("el_1");
236 });
237
238 it("removes an expired terminal chip by its kind-scoped id, not the producer id", () => {
239 const context = {
240 id: "term-1",
241 threadId: ThreadId.make("t"),
242 createdAt: "2026-01-01T00:00:00.000Z",
243 terminalId: "default",
244 terminalLabel: "Terminal 1",
245 lineStart: 3,
246 lineEnd: 4,
247 text: "boom",
248 };
249 const reference = terminalContextReference(context);
250 expect(reference.contextId).toBe("terminal_term-1");
251
252 const prompt = `prose ${formatInlineContextReference(reference)} tail`;
253 expect(removeInlineContextReference(prompt, context.id).prompt).toBe(prompt);
254 expect(removeInlineContextReference(prompt, reference.contextId).prompt).toBe("prose tail");
255 });
256
257 it("clamps an oversized review selection so the record still encodes", () => {
258 const build = (diffLength: number) =>
259 reviewCommentContextRecord({
260 id: "rc-big",
261 sectionId: "file:a/b.ts",
262 sectionTitle: "File comment",
263 filePath: "a/b.ts",
264 startIndex: 0,
265 endIndex: 1,
266 rangeLabel: "L1",
267 text: "Why?",
268 diff: "d".repeat(diffLength),
269 });
270
271 const atLimit = build(32_000);
272 expect(atLimit.diff).toHaveLength(32_000);
273 const overLimit = build(32_001);
274 expect(overLimit.diff.length).toBeLessThanOrEqual(32_000);
275 expect(overLimit.diff.endsWith("… truncated …")).toBe(true);
276 expect(() => decodeMessageContext({ version: 1, records: [atLimit] })).not.toThrow();
277 expect(() => decodeMessageContext({ version: 1, records: [overLimit] })).not.toThrow();
278 });
279
280 it("finds the destination collision for different legacy terminal messages", () => {
281 const legacy = (text: string) =>
282 asKnownContextRecord(
283 upgradeLegacyContextMessage(
284 `Inspect this\n\n<terminal_context>\n- Terminal 1 line 1:\n 1 | ${text}\n</terminal_context>`,
285 ).records[0],
286 )!;
287 const first = legacy("A");
288 const second = legacy("B");
289 if (first.kind !== "terminal" || second.kind !== "terminal") {
290 throw new Error("Expected legacy terminal records");
291 }
292 const destinationId = terminalContextReference(
293 terminalContextDraftFromRecord(first, ThreadId.make("t")),
294 ).contextId;
295
296 expect(destinationId).toBe("terminal_legacy_terminal_1");
297 expect(composerContextImportLookupIds(second)[0]).toBe(destinationId);
298 expect(isSameComposerContextPayload(first, second)).toBe(false);
299 });
300
301 it("treats an imported legacy id and its canonical reconstruction as the same excerpt", () => {
302 const draft = {
303 id: "term-1",
304 threadId: ThreadId.make("t"),
305 createdAt: "2026-01-01T00:00:00.000Z",
306 terminalId: "default",
307 terminalLabel: "Terminal 1",
308 lineStart: 1,
309 lineEnd: 2,
310 text: "A",
311 };
312 const canonical = terminalContextRecord(draft);
313 const imported = { ...canonical, contextId: "legacy_terminal_1" as ComposerContextId };
314
315 expect(isSameComposerContextPayload(canonical, imported)).toBe(true);
316 expect(isSameComposerContextPayload(canonical, { ...canonical, text: "B" })).toBe(false);
317 });
318
319 it("resolves structured context directly and upgrades legacy text otherwise", () => {
320 const structured = resolveUserMessageContext({
321 text: "hi [b.ts L4](t3-context://v1/review-comment/rc-1)",
322 context: {
323 version: 1,
324 records: [
325 reviewCommentContextRecord({
326 id: "rc-1",
327 sectionId: "s",
328 sectionTitle: "t",
329 filePath: "a/b.ts",
330 startIndex: 3,
331 endIndex: 3,
332 rangeLabel: "L4",
333 text: "",
334 diff: "",
335 }),
336 ],
337 },
338 });
339 expect(structured.recordsById.get("review-comment_rc-1")?.kind).toBe("review-comment");
340 const legacy = resolveUserMessageContext({
341 text: "hi\n\n<terminal_context>\n- T line 1:\n 1 | x\n</terminal_context>",
342 });
343 expect(legacy.text).toBe("hi\n\n[T line 1](t3-context://v1/terminal/legacy_terminal_1)");
344 expect(legacy.recordsById.get("legacy_terminal_1")?.kind).toBe("terminal");
345 });
346});
347
348describe("producer ids that do not fit the grammar", () => {
349 it("folds review comment ids and keeps the raw id in the draft shape", () => {
350 const record = reviewCommentContextRecord({
351 id: "pull-request-finding:42",
352 sectionId: "s",
353 sectionTitle: "t",
354 filePath: "a/b.ts",
355 startIndex: 0,
356 endIndex: 0,
357 rangeLabel: "L1",
358 text: "",
359 diff: "",
360 });
361 expect(record.contextId).toMatch(/^review-comment_pull-request-finding-42-[0-9a-f]{16}$/);
362 expect(
363 resolveUserMessageContext({
364 text: `[b.ts L1](t3-context://v1/review-comment/${record.contextId})`,
365 context: { version: 1, records: [record] },
366 }).recordsById.has(record.contextId),
367 ).toBe(true);
368 });
369});
370
371describe("selectedMessageContextFragment", () => {
372 const terminal = terminalContextRecord({
373 id: "term-1",
374 threadId: ThreadId.make("t"),
375 createdAt: "2026-01-01T00:00:00.000Z",
376 terminalId: "default",
377 terminalLabel: "Terminal 1",
378 lineStart: 1,
379 lineEnd: 1,
380 text: "A",
381 });
382 const review = reviewCommentContextRecord({
383 id: "rc-1",
384 sectionId: "s",
385 sectionTitle: "t",
386 filePath: "a/b.ts",
387 startIndex: 3,
388 endIndex: 3,
389 rangeLabel: "L4",
390 text: "",
391 diff: "",
392 });
393 const input = {
394 records: [terminal, review],
395 environmentId: EnvironmentId.make("env"),
396 threadId: ThreadId.make("t"),
397 messageId: MessageId.make("msg-1"),
398 };
399
400 it("carries only records for chips inside the selection", () => {
401 const fragment = selectedMessageContextFragment({
402 ...input,
403 markdown: `see [b.ts L4](t3-context://v1/review-comment/${review.contextId})`,
404 });
405
406 expect(fragment).toContain(review.contextId);
407 expect(fragment).not.toContain(terminal.contextId);
408 });
409});