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