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

composerContext.test.ts

339 lines12.4 KB

1import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
2import { buildProjectThreadStartTurnInput } from "./projectThreadStartTurn";
3import {
4 ProjectId,
5 ProviderInstanceId,
6 ComposerContextId,
7 EnvironmentId,
8 ThreadId,
9 type OrchestrationMessageContext,
10} from "@t3tools/contracts";
11import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
12import {
13 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
14 collectComposerContextReferences,
15 formatComposerContextReference,
16 projectComposerContextForProvider,
17} from "@t3tools/shared/composerContextReferences";
18import { describe, expect, it } from "vite-plus/test";
19import {
20 composerContextEditorTokens,
21 composerContextSendBlockReason,
22 composerMentionPath,
23 createComposerContextHistory,
24 referencedComposerContext,
25 reidentifyComposerContext,
26 uploadedComposerContext,
27 serializeComposerMessageForServer,
28 pullRequestComposerContext,
29 threadComposerContext,
30} from "./composerContext";
31​
32const terminal = {
33 version: 1 as const,
34 kind: "terminal" as const,
35 contextId: ComposerContextId.make("terminal-1"),
36 label: "Build output",
37 terminalId: "main",
38 terminalLabel: "Terminal",
39 lineStart: 4,
40 lineEnd: 5,
41 text: "build failed\nretry",
42};
43const image = {
44 version: 1 as const,
45 kind: "image" as const,
46 contextId: ComposerContextId.make("image-1"),
47 label: "Screenshot",
48 attachmentId: "local-image",
49 name: "shot.png",
50 mimeType: "image/png",
51 sizeBytes: 123,
52};
53const annotation = {
54 version: 1 as const,
55 kind: "preview-annotation" as const,
56 contextId: ComposerContextId.make("preview-1"),
57 label: "Button",
58 annotationId: "button-1",
59 pageUrl: "https://example.com",
60 pageTitle: null,
61 comment: "Keep the cart",
62 targetSummary: "Button",
63 styleChanges: [],
64 screenshotContextId: image.contextId,
65};
66​
67describe("mobile composer context", () => {
68 it("rejects a malformed record instead of allowing the wire decoder to drop its payload", () => {
69 expect(
70 composerContextSendBlockReason({
71 version: 1,
72 records: [{ ...terminal, label: "x".repeat(201) }],
73 }),
74 ).not.toBeNull();
75 });
76 it("does not evict live recovery payloads from the editor's bounded undo history", () => {
77 const records = Array.from({ length: 400 }, (_, index) => ({
78 ...terminal,
79 contextId: ComposerContextId.make(`terminal-${index}`),
80 }));
81 const text = records.map(formatComposerContextReference).join(" ");
82 const restore = createComposerContextHistory();
83 expect(restore(text, { version: 1, records })?.records).toEqual(records);
84 expect(
85 restore(records.slice(1).map(formatComposerContextReference).join(" "), {
86 version: 1,
87 records,
88 })?.records,
89 ).toEqual(records.slice(1));
90 });
91​
92 it("blocks a context payload that exceeds the aggregate wire budget", () => {
93 const record = {
94 ...annotation,
95 styleChangeDetails: Array.from({ length: 200 }, () => ({
96 targetId: "element",
97 selector: null,
98 property: "content",
99 previousValue: "x".repeat(8_000),
100 value: "y".repeat(8_000),
101 })),
102 };
103 expect(composerContextSendBlockReason({ version: 1, records: [record] })).toBeNull();
104 expect(
105 composerContextSendBlockReason({
106 version: 1,
107 records: Array.from({ length: 6 }, (_, index) => ({
108 ...record,
109 contextId: ComposerContextId.make(`preview-${index}`),
110 })),
111 }),
112 ).toContain("too much context");
113 });
114​
115 it("blocks over-limit recovery drafts until enough context has been removed", () => {
116 const records = Array.from({ length: 201 }, (_, index) => ({
117 ...terminal,
118 contextId: ComposerContextId.make(`terminal-${index}`),
119 }));
120 expect(composerContextSendBlockReason({ version: 1, records })).toContain("at most 200");
121 expect(
122 composerContextSendBlockReason({ version: 1, records: records.slice(0, 200) }),
123 ).toBeNull();
124 expect(composerContextSendBlockReason()).toBeNull();
125 });
126​
127 it("opens the full file path from bare, quoted, and canonical mentions", () => {
128 expect(composerMentionPath("@src/Checkout.tsx")).toBe("src/Checkout.tsx");
129 expect(composerMentionPath('@"src/My Checkout.tsx"')).toBe("src/My Checkout.tsx");
130 expect(composerMentionPath("[Checkout.tsx](src/Checkout.tsx)")).toBe("src/Checkout.tsx");
131 const mention = {
132 version: 1 as const,
133 kind: "mention" as const,
134 contextId: ComposerContextId.make("mention-1"),
135 label: "Checkout.tsx",
136 path: "src/Checkout.tsx",
137 };
138 expect(
139 composerMentionPath(formatComposerContextReference(mention), {
140 version: 1,
141 records: [mention],
142 }),
143 ).toBe("src/Checkout.tsx");
144 expect(composerMentionPath(formatComposerContextReference(mention))).toBeNull();
145 expect(composerMentionPath("$playwright")).toBeNull();
146 expect(
147 composerMentionPath(formatComposerContextReference(terminal), {
148 version: 1,
149 records: [terminal],
150 }),
151 ).toBeNull();
152 });
153​
154 it("restores deleted payloads on undo without adding removed context to the current draft", () => {
155 const restore = createComposerContextHistory();
156 const source = formatComposerContextReference(annotation);
157 const initial = { version: 1 as const, records: [annotation, image] };
158 expect(restore("deleted", initial)).toBeUndefined();
159 expect(restore(source)?.records).toEqual(initial.records);
160 expect(restore("deleted")?.records ?? []).toEqual([]);
161 expect(createComposerContextHistory()(source)?.records).toEqual([]);
162 });
163 it("keeps exact source positions and repeated references alongside existing native tokens", () => {
164 const reference = formatComposerContextReference(terminal);
165 const text = `Use $playwright and [app.ts](src/app.ts) with ${reference} then ${reference}`;
166 const tokens = composerContextEditorTokens(text, collectComposerInlineTokens(text));
167 expect(tokens.map((token) => token.type)).toEqual(["skill", "mention", "context", "context"]);
168 for (const token of tokens) expect(text.slice(token.start, token.end)).toBe(token.source);
169 });
170​
171 it("removes deleted payloads but keeps the screenshot linked to a remaining annotation", () => {
172 const context: OrchestrationMessageContext = {
173 version: 1,
174 records: [terminal, annotation, image],
175 };
176 expect(
177 referencedComposerContext(formatComposerContextReference(annotation), context)?.records,
178 ).toEqual([annotation, image]);
179 expect(referencedComposerContext("plain text", context)).toBeUndefined();
180 });
181​
182 it("reidentifies pasted records and their screenshot binding without changing repeated-reference identity", () => {
183 let next = 0;
184 const text = `${formatComposerContextReference(annotation)} ${formatComposerContextReference(annotation)}`;
185 const imported = reidentifyComposerContext(text, [annotation, image], () => `copy-${++next}`);
186 expect(collectComposerContextReferences(imported.text).map((ref) => ref.contextId)).toEqual([
187 "copy-1",
188 "copy-1",
189 ]);
190 expect(imported.context.records[0]).toMatchObject({
191 contextId: "copy-1",
192 screenshotContextId: "copy-2",
193 });
194 expect(annotation.contextId).toBe("preview-1");
195 });
196​
197 it("binds uploaded files to their wire ids and preserves terminal payloads for every provider", () => {
198 const context = uploadedComposerContext(
199 { version: 1, records: [terminal, image] },
200 [{ id: "local-image" }],
201 [{ id: "uploaded-image" }],
202 );
203 expect(context?.records).toEqual([terminal, { ...image, attachmentId: "uploaded-image" }]);
204 const prompt = projectComposerContextForProvider({
205 text: formatComposerContextReference(terminal),
206 records: context!.records,
207 });
208 expect(prompt).toContain("4 | build failed\n5 | retry");
209 expect(prompt).not.toContain('unavailable="true"');
210 });
211});
212​
213describe("host context compatibility", () => {
214 it("sends an image-only prompt as the attachment-only prompt and keeps the image", () => {
215 const context: OrchestrationMessageContext = { version: 1, records: [image] };
216 const reference = formatComposerContextReference(image);
217 expect(serializeComposerMessageForServer(reference, context, true)).toEqual({
218 text: ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
219 context,
220 });
221 const withProse = `${reference} what is this?`;
222 expect(serializeComposerMessageForServer(withProse, context, true)).toEqual({
223 text: withProse,
224 context,
225 });
226 });
227​
228 it("carries the current PR diff file within the composer wire limits", () => {
229 const metadata = {
230 number: 42,
231 title: "Fix checkout",
232 url: "https://github.com/example/repo/pull/42",
233 headBranch: "fix-checkout",
234 baseBranch: "main",
235 state: "open" as const,
236 isDraft: false,
237 };
238 const record = pullRequestComposerContext(metadata, "pr-42", "src/checkout.ts");
239 expect(record.filePath).toBe("src/checkout.ts");
240 const prompt = projectComposerContextForProvider({
241 text: formatComposerContextReference(record),
242 records: [record],
243 });
244 expect(prompt).toContain(metadata.url);
245 expect(prompt).toContain("src/checkout.ts");
246 expect(composerContextSendBlockReason({ version: 1, records: [record] })).toBeNull();
247 const large = pullRequestComposerContext(
248 {
249 ...metadata,
250 title: "x".repeat(3000),
251 headBranch: "y".repeat(3000),
252 baseBranch: "z".repeat(3000),
253 },
254 "pr-42",
255 `src/${"[long file]".repeat(500)}.ts`,
256 );
257 expect(composerContextSendBlockReason({ version: 1, records: [large] })).toBeNull();
258 });
259​
260 it.each(["existing-thread", "new-task"])("serializes %s sends for an older host", (path) => {
261 const pr = pullRequestComposerContext(
262 {
263 number: 42,
264 title: "Fix checkout",
265 url: "https://github.com/example/repo/pull/42",
266 headBranch: "fix-checkout",
267 baseBranch: "main",
268 state: "open",
269 isDraft: false,
270 },
271 "pr-42",
272 );
273 const review = {
274 ...pr,
275 contextId: ComposerContextId.make("review-1"),
276 sectionId: "review",
277 filePath: "checkout.ts",
278 text: "Handle the empty cart",
279 diff: "- old\n+ new",
280 };
281 const context: OrchestrationMessageContext = { version: 1, records: [terminal, review, pr] };
282 const text = context.records.map(formatComposerContextReference).join(" ");
283 const wire = serializeComposerMessageForServer(text, context, false);
284 const message =
285 path === "existing-thread"
286 ? wire
287 : buildProjectThreadStartTurnInput({
288 ...wire,
289 projectId: ProjectId.make("project"),
290 projectCwd: "/workspace",
291 threadId: "thread",
292 commandId: "command",
293 messageId: "message",
294 createdAt: "2026-01-01T00:00:00Z",
295 uploadedAttachments: [],
296 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
297 runtimeMode: "full-access",
298 interactionMode: "default",
299 workspaceMode: "local",
300 branch: null,
301 worktreePath: null,
302 startFromOrigin: false,
303 worktreeBranchName: "unused",
304 }).message;
305 expect(message).not.toHaveProperty("context");
306 expect(message.text).not.toContain("t3-context://");
307 expect(
308 upgradeLegacyContextMessage(message.text).records.find(
309 (record) => record.kind === "terminal",
310 ),
311 ).toMatchObject({
312 text: terminal.text,
313 lineStart: terminal.lineStart,
314 lineEnd: terminal.lineEnd,
315 });
316 expect(message.text).toContain(review.text);
317 expect(message.text).toContain(review.diff);
318 expect(message.text).toContain(pr.pullRequest!.url);
319 expect(serializeComposerMessageForServer(text, context, true)).toEqual({ text, context });
320 expect(context.records).toEqual([terminal, review, pr]);
321 });
322});
323​
324describe("threadComposerContext", () => {
325 it("mints a schema-valid, stable id for agent-spawned thread ids", () => {
326 const environmentId = EnvironmentId.make("env-1");
327 const ref = {
328 environmentId,
329 threadId: ThreadId.make(`thread:mcp:${encodeURIComponent("3f2b:delegate")}:review:0`),
330 };
331 const contextId = threadComposerContext(ref, "Review").contextId;
332​
333 expect(() => ComposerContextId.make(contextId)).not.toThrow();
334 expect(threadComposerContext(ref, "Renamed").contextId).toBe(contextId);
335 expect(
336 threadComposerContext({ environmentId, threadId: ThreadId.make("abc-123") }, "t").contextId,
337 ).toBe("thread_abc-123");
338 });
339});