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

composerContext.test.ts

273 lines10.1 KB

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