Open History to see the last commit
1import {
2 capitalizeTerm,
3 sourceControlClients,
4} from "@t3tools/client-runtime/source-control-clients";
5import {
6 COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS,
7 COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS,
8 COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS,
9} from "@t3tools/contracts";
10import type {
11 ComposerContextId,
12 ComposerContextRecord,
13 EnvironmentContextRecord,
14 EnvironmentId,
15 FileContextRecord,
16 ImageContextRecord,
17 KnownComposerContextRecord,
18 MessageId,
19 OrchestrationMessageContext,
20 PreviewAnnotationContextRecord,
21 PreviewAnnotationPayload,
22 ReviewCommentContextRecord,
23 TerminalContextRecord,
24 ThreadContextRecord,
25 ThreadId,
26} from "@t3tools/contracts";
27import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
28import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
29import {
30 collectComposerContextReferences,
31 sanitizeComposerContextLabel,
32 toKindScopedComposerContextId,
33} from "@t3tools/shared/composerContextReferences";
34
35import {
36 type ComposerContextReference,
37 producerIdFromComposerContextId,
38} from "./composerContextReferences";
39import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
40import type { AttachmentUploadState } from "./attachmentUploadState";
41import { normalizeElementContextSelection } from "./elementContext";
42import {
43 formatTerminalContextLabel,
44 normalizeTerminalContextText,
45 type TerminalContextDraft,
46} from "./terminalContext";
47import type { ReviewCommentContext } from "~/reviewCommentContext";
48
49const PREVIEW_LABEL_MAX_CHARS = 48;
50
51// Truncate selections to wire bounds before persistence to avoid send-time encoding failures.
52const TRUNCATION_MARKER = "\n… truncated …";
53
54function clampContextText(value: string, max: number): string {
55 if (value.length <= max) return value;
56 let end = Math.max(0, max - TRUNCATION_MARKER.length);
57 // Never end on a lone high surrogate.
58 const last = value.charCodeAt(end - 1);
59 if (last >= 0xd800 && last <= 0xdbff) end -= 1;
60 return `${value.slice(0, end)}${TRUNCATION_MARKER}`;
61}
62
63type ReviewCommentPresentation = ReviewCommentContext | ReviewCommentContextRecord;
64
65function basename(filePath: string): string {
66 return filePath.split(/[\\/]/).at(-1) ?? filePath;
67}
68
69export function reviewCommentContextLabel(comment: ReviewCommentPresentation): string {
70 const pullRequestNumber = pullRequestContextNumber(comment);
71 if (isPullRequestSummaryContext(comment) && pullRequestNumber !== null) {
72 return `#${pullRequestNumber}`;
73 }
74 const diffRange = /^([+-])(\d+)(?: to \1(\d+))?$/u.exec(comment.rangeLabel);
75 const rangeLabel = diffRange
76 ? `L${diffRange[2]}${diffRange[3] ? ` to L${diffRange[3]}` : ""}${diffRange[1] === "-" ? " (before)" : ""}`
77 : comment.rangeLabel;
78 const sectionPullRequest = /^pull-request:(\d+)$/u.exec(comment.sectionId)?.[1];
79 const prefix = sectionPullRequest === undefined ? "" : `#${sectionPullRequest} `;
80 return `${prefix}${basename(comment.filePath)} ${rangeLabel}`;
81}
82
83export function isPullRequestSummaryContext(comment: ReviewCommentPresentation): boolean {
84 if (comment.pullRequest !== undefined) return true;
85 return (
86 comment.sectionId.startsWith("pull-request:") &&
87 comment.diff.trim().length === 0 &&
88 /^PR #\d+$/u.test(comment.filePath)
89 );
90}
91
92function pullRequestContextNumber(comment: ReviewCommentPresentation): number | null {
93 if (comment.pullRequest !== undefined) return comment.pullRequest.number;
94 const legacyNumber = /^PR #(\d+)$/u.exec(comment.filePath)?.[1];
95 return legacyNumber === undefined ? null : Number(legacyNumber);
96}
97
98export type PullRequestContextDisplayState = "open" | "draft" | "merged" | "closed";
99
100export function pullRequestContextDisplayState(
101 comment: ReviewCommentPresentation,
102): PullRequestContextDisplayState | null {
103 const pullRequest = comment.pullRequest;
104 if (pullRequest === undefined) return null;
105 return pullRequest.state === "open" && pullRequest.isDraft ? "draft" : pullRequest.state;
106}
107
108export function pullRequestContextKindLabel(comment: ReviewCommentPresentation): string {
109 const url = comment.pullRequest?.url;
110 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
111 const term = (host ?? sourceControlClients.get(undefined)).changeRequest.singular;
112 const state = pullRequestContextDisplayState(comment);
113 if (state === null) return capitalizeTerm(term);
114 return `${capitalizeTerm(state)} ${term}`;
115}
116
117export function previewAnnotationContextLabel(annotation: PreviewAnnotationPayload): string {
118 const comment = annotation.comment.trim().replace(/\s+/g, " ");
119 if (comment) {
120 if (comment.length <= PREVIEW_LABEL_MAX_CHARS) return comment;
121 let end = PREVIEW_LABEL_MAX_CHARS - 1;
122 const previous = comment.charCodeAt(end - 1);
123 const next = comment.charCodeAt(end);
124 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end -= 1;
125 return `${comment.slice(0, end)}…`;
126 }
127 return annotation.pageTitle?.trim() || "Preview annotation";
128}
129
130export function terminalContextReference(context: TerminalContextDraft): ComposerContextReference {
131 return {
132 kind: "terminal",
133 contextId: toKindScopedComposerContextId("terminal", context.id),
134 label: formatTerminalContextLabel(context),
135 };
136}
137
138export function reviewCommentContextId(commentId: string): ComposerContextId {
139 return toKindScopedComposerContextId("review-comment", commentId);
140}
141
142export function previewAnnotationContextId(annotationId: string): ComposerContextId {
143 return toKindScopedComposerContextId("preview-annotation", annotationId);
144}
145
146export function reviewCommentContextReference(
147 comment: ReviewCommentContext,
148): ComposerContextReference {
149 return {
150 kind: "review-comment",
151 contextId: reviewCommentContextId(comment.id),
152 label: reviewCommentContextLabel(comment),
153 };
154}
155
156export function previewAnnotationContextReference(
157 annotation: PreviewAnnotationPayload,
158): ComposerContextReference {
159 return {
160 kind: "preview-annotation",
161 contextId: previewAnnotationContextId(annotation.id),
162 label: previewAnnotationContextLabel(annotation),
163 };
164}
165
166export function threadContextReference(record: ThreadContextRecord): ComposerContextReference {
167 return { kind: "thread", contextId: record.contextId, label: record.label };
168}
169
170/** One record per machine: mentioning the same machine twice reuses the chip. */
171export function environmentContextReference(
172 record: EnvironmentContextRecord,
173): ComposerContextReference {
174 return { kind: "environment", contextId: record.contextId, label: record.label };
175}
176
177export function environmentContextRecord(
178 environmentId: EnvironmentId,
179 label: string,
180): EnvironmentContextRecord {
181 return {
182 version: 1,
183 kind: "environment",
184 contextId: toKindScopedComposerContextId("environment", environmentId),
185 label: sanitizeComposerContextLabel(label, "environment"),
186 environmentId,
187 };
188}
189
190export function terminalContextRecord(context: TerminalContextDraft): TerminalContextRecord {
191 return {
192 version: 1,
193 contextId: toKindScopedComposerContextId("terminal", context.id),
194 kind: "terminal",
195 label: sanitizeComposerContextLabel(formatTerminalContextLabel(context), "terminal"),
196 terminalId: context.terminalId,
197 terminalLabel: context.terminalLabel,
198 lineStart: context.lineStart,
199 lineEnd: context.lineEnd,
200 text: clampContextText(
201 normalizeTerminalContextText(context.text),
202 COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS,
203 ),
204 };
205}
206
207export function reviewCommentContextRecord(
208 comment: ReviewCommentContext,
209): ReviewCommentContextRecord {
210 return {
211 version: 1,
212 contextId: reviewCommentContextId(comment.id),
213 kind: "review-comment",
214 label: sanitizeComposerContextLabel(reviewCommentContextLabel(comment), "review-comment"),
215 sectionId: comment.sectionId,
216 sectionTitle: comment.sectionTitle,
217 filePath: comment.filePath,
218 startIndex: comment.startIndex,
219 endIndex: comment.endIndex,
220 rangeLabel: comment.rangeLabel,
221 text: clampContextText(comment.text, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
222 diff: clampContextText(comment.diff, COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
223 ...(comment.fenceLanguage !== undefined ? { fenceLanguage: comment.fenceLanguage } : {}),
224 ...(comment.pullRequest !== undefined ? { pullRequest: comment.pullRequest } : {}),
225 };
226}
227
228function previewAnnotationTargetSummary(annotation: PreviewAnnotationPayload): string {
229 const parts: string[] = [];
230 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
231 if (annotation.elements.length > 0)
232 parts.push(plural(annotation.elements.length, "selected element"));
233 if (annotation.regions.length > 0) parts.push(plural(annotation.regions.length, "marked region"));
234 if (annotation.strokes.length > 0) parts.push(plural(annotation.strokes.length, "drawing"));
235 return parts.join(", ");
236}
237
238export function previewAnnotationContextRecord(
239 annotation: PreviewAnnotationPayload,
240 options?: { screenshotContextId?: string | undefined },
241): PreviewAnnotationContextRecord {
242 const targets = annotation.elements.flatMap((target) => {
243 const element = normalizeElementContextSelection(target.element);
244 return element ? [{ id: target.id, element }] : [];
245 });
246 return {
247 version: 1,
248 contextId: previewAnnotationContextId(annotation.id),
249 kind: "preview-annotation",
250 label: sanitizeComposerContextLabel(
251 previewAnnotationContextLabel(annotation),
252 "preview-annotation",
253 ),
254 annotationId: annotation.id,
255 pageUrl: annotation.pageUrl,
256 pageTitle: annotation.pageTitle,
257 comment: annotation.comment.trim(),
258 targetSummary: previewAnnotationTargetSummary(annotation),
259 styleChanges: annotation.styleChanges.map(
260 (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,
261 ),
262 ...(targets.length > 0
263 ? {
264 elements: targets.map((target) => target.element),
265 elementIds: targets.map((target) => target.id),
266 }
267 : {}),
268 styleChangeDetails: annotation.styleChanges.map((change) => ({ ...change })),
269 ...(annotation.regions.length > 0 ? { regionCount: annotation.regions.length } : {}),
270 ...(annotation.strokes.length > 0 ? { strokeCount: annotation.strokes.length } : {}),
271 ...(options?.screenshotContextId !== undefined
272 ? { screenshotContextId: toKindScopedComposerContextId("image", options.screenshotContextId) }
273 : {}),
274 };
275}
276
277export function imageContextReference(image: ComposerImageAttachment): ComposerContextReference {
278 return {
279 kind: "image",
280 contextId: toKindScopedComposerContextId("image", image.id),
281 label: image.name,
282 };
283}
284
285export function fileContextReference(file: ComposerFileAttachment): ComposerContextReference {
286 return {
287 kind: "file",
288 contextId: toKindScopedComposerContextId("file", file.id),
289 label: file.name,
290 };
291}
292
293export interface BoundComposerAttachment {
294 attachment: ComposerImageAttachment | ComposerFileAttachment;
295 attachmentId: string;
296}
297
298/** Returns null until the attachment has a server id. */
299export function uploadedAttachmentContextRecord(
300 attachment: ComposerImageAttachment | ComposerFileAttachment,
301 upload: AttachmentUploadState | undefined,
302): ImageContextRecord | FileContextRecord | null {
303 const attachmentId =
304 attachment.type === "file" && attachment.uploadedAttachmentId !== undefined
305 ? attachment.uploadedAttachmentId
306 : upload?.status === "ready"
307 ? upload.attachmentId
308 : undefined;
309 return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId });
310}
311
312export function attachmentContextRecord(
313 bound: BoundComposerAttachment,
314): ImageContextRecord | FileContextRecord {
315 const { attachment, attachmentId } = bound;
316 const base = {
317 version: 1 as const,
318 contextId: toKindScopedComposerContextId(attachment.type, attachment.id),
319 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
320 attachmentId,
321 name: attachment.name,
322 mimeType: attachment.mimeType,
323 sizeBytes: attachment.sizeBytes,
324 };
325 return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };
326}
327
328export function buildMessageContext(input: {
329 terminalContexts: ReadonlyArray<TerminalContextDraft>;
330 reviewComments: ReadonlyArray<ReviewCommentContext>;
331 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
332 threadContexts?: ReadonlyArray<ThreadContextRecord>;
333 environmentContexts?: ReadonlyArray<EnvironmentContextRecord>;
334 attachments?: ReadonlyArray<BoundComposerAttachment>;
335}): OrchestrationMessageContext | undefined {
336 const screenshotAttachmentIds = new Set(
337 (input.attachments ?? []).flatMap(({ attachment }) =>
338 attachment.type === "image" ? [attachment.id] : [],
339 ),
340 );
341 const records: ComposerContextRecord[] = [
342 ...input.terminalContexts.map(terminalContextRecord),
343 ...input.reviewComments.map(reviewCommentContextRecord),
344 ...(input.threadContexts ?? []),
345 ...(input.environmentContexts ?? []),
346 ...input.previewAnnotations.map((annotation) =>
347 previewAnnotationContextRecord(annotation, {
348 screenshotContextId: screenshotAttachmentIds.has(annotation.id) ? annotation.id : undefined,
349 }),
350 ),
351 ...(input.attachments ?? []).map(attachmentContextRecord),
352 ];
353 return records.length === 0 ? undefined : { version: 1, records };
354}
355
356export function asKnownContextRecord(
357 record: ComposerContextRecord | undefined,
358): KnownComposerContextRecord | undefined {
359 if (!record || "payload" in record) return undefined;
360 return record;
361}
362
363export function composerContextImportLookupIds(
364 record: KnownComposerContextRecord,
365): ReadonlyArray<ComposerContextId> {
366 const destinationId = toKindScopedComposerContextId(
367 record.kind,
368 producerIdFromComposerContextId(record.kind, record.contextId),
369 );
370 return destinationId === record.contextId
371 ? [record.contextId]
372 : [destinationId, record.contextId];
373}
374
375export interface ResolvedUserMessageContext {
376 text: string;
377 records: ReadonlyArray<ComposerContextRecord>;
378 recordsById: ReadonlyMap<string, ComposerContextRecord>;
379}
380
381export function selectedMessageContextFragment(input: {
382 readonly markdown: string;
383 readonly records: ReadonlyArray<ComposerContextRecord>;
384 readonly environmentId: EnvironmentId;
385 readonly threadId?: ThreadId;
386 readonly messageId: MessageId;
387}): string | null {
388 const selectedIds = new Set(
389 collectComposerContextReferences(input.markdown).map((occurrence) => occurrence.contextId),
390 );
391 const records = input.records.filter((record) => selectedIds.has(record.contextId));
392 if (records.length === 0) return null;
393 return encodeComposerContextFragment({
394 version: 1,
395 source: {
396 environmentId: input.environmentId,
397 ...(input.threadId ? { threadId: input.threadId } : {}),
398 messageId: input.messageId,
399 },
400 records,
401 });
402}
403
404export function resolveUserMessageContext(message: {
405 text: string;
406 context?: OrchestrationMessageContext | undefined;
407}): ResolvedUserMessageContext {
408 const resolved = message.context
409 ? { text: message.text, records: message.context.records }
410 : upgradeLegacyContextMessage(message.text);
411 return {
412 text: resolved.text,
413 records: resolved.records,
414 recordsById: new Map(resolved.records.map((record) => [record.contextId, record])),
415 };
416}
417
418export function terminalContextDraftFromRecord(
419 record: TerminalContextRecord,
420 threadId: ThreadId,
421): TerminalContextDraft {
422 return {
423 id: producerIdFromComposerContextId("terminal", record.contextId),
424 threadId,
425 createdAt: new Date().toISOString(),
426 terminalId: record.terminalId,
427 terminalLabel: record.terminalLabel,
428 lineStart: record.lineStart,
429 lineEnd: record.lineEnd,
430 text: record.text,
431 };
432}
433
434export function reviewCommentFromRecord(record: ReviewCommentContextRecord): ReviewCommentContext {
435 return {
436 id: producerIdFromComposerContextId("review-comment", record.contextId),
437 sectionId: record.sectionId,
438 sectionTitle: record.sectionTitle,
439 filePath: record.filePath,
440 startIndex: record.startIndex,
441 endIndex: record.endIndex,
442 rangeLabel: record.rangeLabel,
443 text: record.text,
444 diff: record.diff,
445 ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),
446 ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
447 };
448}
449
450export function previewAnnotationFromRecord(
451 record: PreviewAnnotationContextRecord,
452): PreviewAnnotationPayload {
453 return {
454 id:
455 record.annotationId ||
456 producerIdFromComposerContextId("preview-annotation", record.contextId),
457 pageUrl: record.pageUrl,
458 pageTitle: record.pageTitle,
459 comment: record.comment,
460 elements: (record.elements ?? []).map((element, index) => ({
461 id: record.elementIds?.[index] ?? `${record.contextId}-element-${index + 1}`,
462 rect: { x: 0, y: 0, width: 0, height: 0 },
463 element: { ...element, stack: [], pickedAt: new Date().toISOString() },
464 })),
465 regions: Array.from({ length: record.regionCount ?? 0 }, (_unused, index) => ({
466 id: `${record.contextId}-region-${index + 1}`,
467 rect: { x: 0, y: 0, width: 0, height: 0 },
468 })),
469 strokes: Array.from({ length: record.strokeCount ?? 0 }, (_unused, index) => ({
470 id: `${record.contextId}-stroke-${index + 1}`,
471 color: "",
472 width: 0,
473 points: [],
474 bounds: { x: 0, y: 0, width: 0, height: 0 },
475 })),
476 styleChanges:
477 record.styleChangeDetails ??
478 record.styleChanges.flatMap((change) => {
479 const match = /^(.+?): ([\s\S]*?) → ([\s\S]*)$/.exec(change);
480 if (!match) return [];
481 return [
482 {
483 targetId: record.elementIds?.[0] ?? `${record.contextId}-element-1`,
484 selector: null,
485 property: match[1]!,
486 previousValue: match[2] === "(unset)" ? "" : match[2]!,
487 value: match[3]!,
488 },
489 ];
490 }),
491 screenshot: null,
492 createdAt: new Date().toISOString(),
493 };
494}
495
496/** Labels are display-only; folded ids can collide, so paste deduplication compares payloads. */
497export function isSameComposerContextPayload(
498 left: ComposerContextRecord,
499 right: ComposerContextRecord,
500): boolean {
501 if (left.kind !== right.kind) return false;
502 const stableKey = (record: ComposerContextRecord) => {
503 const { label: _label, contextId: _contextId, ...rest } = record;
504 const sortDeep = (value: unknown): unknown => {
505 if (Array.isArray(value)) return value.map(sortDeep);
506 if (value === null || typeof value !== "object") return value;
507 return Object.fromEntries(
508 Object.entries(value)
509 .toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
510 .map(([key, nested]) => [key, sortDeep(nested)]),
511 );
512 };
513 return JSON.stringify(sortDeep(rest));
514 };
515 return stableKey(left) === stableKey(right);
516}