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