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

composerContextRecords.ts

498 lines17.8 KB

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 EnvironmentId,
13 FileContextRecord,
14 ImageContextRecord,
15 KnownComposerContextRecord,
16 MessageId,
17 OrchestrationMessageContext,
18 PreviewAnnotationContextRecord,
19 PreviewAnnotationPayload,
20 ReviewCommentContextRecord,
21 ScopedThreadRef,
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}`;
57​
58type ReviewCommentPresentation = ReviewCommentContext | ReviewCommentContextRecord;
59​
60function basename(filePath: string): string {
61 return filePath.split(/[\\/]/).at(-1) ?? filePath;
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}`;
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 );
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);
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;
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}`;
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";
119​
120export function terminalContextReference(context: TerminalContextDraft): ComposerContextReference {
121 return {
122 kind: "terminal",
123 contextId: toKindScopedComposerContextId("terminal", context.id),
124 label: formatTerminalContextLabel(context),
125 };
127​
128export function reviewCommentContextId(commentId: string): ComposerContextId {
129 return toKindScopedComposerContextId("review-comment", commentId);
131​
132export function previewAnnotationContextId(annotationId: string): ComposerContextId {
133 return toKindScopedComposerContextId("preview-annotation", annotationId);
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 };
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 };
155​
156function threadContextId(threadId: ThreadId): ComposerContextId {
157 return toKindScopedComposerContextId("thread", threadId);
159​
160export function threadContextReference(record: ThreadContextRecord): ComposerContextReference {
161 return { kind: "thread", contextId: record.contextId, label: record.label };
163​
164export function threadContextRecord(ref: ScopedThreadRef, title: string): ThreadContextRecord {
165 const label = sanitizeComposerContextLabel(title, "thread");
166 return {
167 version: 1,
168 kind: "thread",
169 contextId: threadContextId(ref.threadId),
170 label,
171 environmentId: ref.environmentId,
172 threadId: ref.threadId,
173 title: label,
174 };
176​
177export function terminalContextRecord(context: TerminalContextDraft): TerminalContextRecord {
178 return {
179 version: 1,
180 contextId: toKindScopedComposerContextId("terminal", context.id),
181 kind: "terminal",
182 label: sanitizeComposerContextLabel(formatTerminalContextLabel(context), "terminal"),
183 terminalId: context.terminalId,
184 terminalLabel: context.terminalLabel,
185 lineStart: context.lineStart,
186 lineEnd: context.lineEnd,
187 text: normalizeTerminalContextText(context.text),
188 };
190​
191export function reviewCommentContextRecord(
192 comment: ReviewCommentContext,
193): ReviewCommentContextRecord {
194 return {
195 version: 1,
196 contextId: reviewCommentContextId(comment.id),
197 kind: "review-comment",
198 label: sanitizeComposerContextLabel(reviewCommentContextLabel(comment), "review-comment"),
199 sectionId: comment.sectionId,
200 sectionTitle: comment.sectionTitle,
201 filePath: comment.filePath,
202 startIndex: comment.startIndex,
203 endIndex: comment.endIndex,
204 rangeLabel: comment.rangeLabel,
205 text: clampContextText(comment.text, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
206 diff: clampContextText(comment.diff, COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
207 ...(comment.fenceLanguage !== undefined ? { fenceLanguage: comment.fenceLanguage } : {}),
208 ...(comment.pullRequest !== undefined ? { pullRequest: comment.pullRequest } : {}),
209 };
211​
212function previewAnnotationTargetSummary(annotation: PreviewAnnotationPayload): string {
213 const parts: string[] = [];
214 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
215 if (annotation.elements.length > 0)
216 parts.push(plural(annotation.elements.length, "selected element"));
217 if (annotation.regions.length > 0) parts.push(plural(annotation.regions.length, "marked region"));
218 if (annotation.strokes.length > 0) parts.push(plural(annotation.strokes.length, "drawing"));
219 return parts.join(", ");
221​
222export function previewAnnotationContextRecord(
223 annotation: PreviewAnnotationPayload,
224 options?: { screenshotContextId?: string | undefined },
225): PreviewAnnotationContextRecord {
226 const targets = annotation.elements.flatMap((target) => {
227 const element = normalizeElementContextSelection(target.element);
228 return element ? [{ id: target.id, element }] : [];
229 });
230 return {
231 version: 1,
232 contextId: previewAnnotationContextId(annotation.id),
233 kind: "preview-annotation",
234 label: sanitizeComposerContextLabel(
235 previewAnnotationContextLabel(annotation),
236 "preview-annotation",
237 ),
238 annotationId: annotation.id,
239 pageUrl: annotation.pageUrl,
240 pageTitle: annotation.pageTitle,
241 comment: annotation.comment.trim(),
242 targetSummary: previewAnnotationTargetSummary(annotation),
243 styleChanges: annotation.styleChanges.map(
244 (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,
245 ),
246 ...(targets.length > 0
247 ? {
248 elements: targets.map((target) => target.element),
249 elementIds: targets.map((target) => target.id),
250 }
251 : {}),
252 styleChangeDetails: annotation.styleChanges.map((change) => ({ ...change })),
253 ...(annotation.regions.length > 0 ? { regionCount: annotation.regions.length } : {}),
254 ...(annotation.strokes.length > 0 ? { strokeCount: annotation.strokes.length } : {}),
255 ...(options?.screenshotContextId !== undefined
256 ? { screenshotContextId: toKindScopedComposerContextId("image", options.screenshotContextId) }
257 : {}),
258 };
260​
261export function imageContextReference(image: ComposerImageAttachment): ComposerContextReference {
262 return {
263 kind: "image",
264 contextId: toKindScopedComposerContextId("image", image.id),
265 label: image.name,
266 };
268​
269export function fileContextReference(file: ComposerFileAttachment): ComposerContextReference {
270 return {
271 kind: "file",
272 contextId: toKindScopedComposerContextId("file", file.id),
273 label: file.name,
274 };
276​
277export interface BoundComposerAttachment {
278 attachment: ComposerImageAttachment | ComposerFileAttachment;
279 attachmentId: string;
281​
282/** Returns null until the attachment has a server id. */
283export function uploadedAttachmentContextRecord(
284 attachment: ComposerImageAttachment | ComposerFileAttachment,
285 upload: AttachmentUploadState | undefined,
286): ImageContextRecord | FileContextRecord | null {
287 const attachmentId =
288 attachment.type === "file" && attachment.uploadedAttachmentId !== undefined
289 ? attachment.uploadedAttachmentId
290 : upload?.status === "ready"
291 ? upload.attachmentId
292 : undefined;
293 return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId });
295​
296export function attachmentContextRecord(
297 bound: BoundComposerAttachment,
298): ImageContextRecord | FileContextRecord {
299 const { attachment, attachmentId } = bound;
300 const base = {
301 version: 1 as const,
302 contextId: toKindScopedComposerContextId(attachment.type, attachment.id),
303 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
304 attachmentId,
305 name: attachment.name,
306 mimeType: attachment.mimeType,
307 sizeBytes: attachment.sizeBytes,
308 };
309 return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };
311​
312export function buildMessageContext(input: {
313 terminalContexts: ReadonlyArray<TerminalContextDraft>;
314 reviewComments: ReadonlyArray<ReviewCommentContext>;
315 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
316 threadContexts?: ReadonlyArray<ThreadContextRecord>;
317 attachments?: ReadonlyArray<BoundComposerAttachment>;
318}): OrchestrationMessageContext | undefined {
319 const screenshotAttachmentIds = new Set(
320 (input.attachments ?? []).flatMap(({ attachment }) =>
321 attachment.type === "image" ? [attachment.id] : [],
322 ),
323 );
324 const records: ComposerContextRecord[] = [
325 ...input.terminalContexts.map(terminalContextRecord),
326 ...input.reviewComments.map(reviewCommentContextRecord),
327 ...(input.threadContexts ?? []),
328 ...input.previewAnnotations.map((annotation) =>
329 previewAnnotationContextRecord(annotation, {
330 screenshotContextId: screenshotAttachmentIds.has(annotation.id) ? annotation.id : undefined,
331 }),
332 ),
333 ...(input.attachments ?? []).map(attachmentContextRecord),
334 ];
335 return records.length === 0 ? undefined : { version: 1, records };
337​
338export function asKnownContextRecord(
339 record: ComposerContextRecord | undefined,
340): KnownComposerContextRecord | undefined {
341 if (!record || "payload" in record) return undefined;
342 return record as KnownComposerContextRecord;
344​
345export function composerContextImportLookupIds(
346 record: KnownComposerContextRecord,
347): ReadonlyArray<ComposerContextId> {
348 const destinationId = toKindScopedComposerContextId(
349 record.kind,
350 producerIdFromComposerContextId(record.kind, record.contextId),
351 );
352 return destinationId === record.contextId
353 ? [record.contextId]
354 : [destinationId, record.contextId];
356​
357export interface ResolvedUserMessageContext {
358 text: string;
359 records: ReadonlyArray<ComposerContextRecord>;
360 recordsById: ReadonlyMap<string, ComposerContextRecord>;
362​
363export function selectedMessageContextFragment(input: {
364 readonly markdown: string;
365 readonly records: ReadonlyArray<ComposerContextRecord>;
366 readonly environmentId: EnvironmentId;
367 readonly threadId?: ThreadId;
368 readonly messageId: MessageId;
369}): string | null {
370 const selectedIds = new Set(
371 collectComposerContextReferences(input.markdown).map((occurrence) => occurrence.contextId),
372 );
373 const records = input.records.filter((record) => selectedIds.has(record.contextId));
374 if (records.length === 0) return null;
375 return encodeComposerContextFragment({
376 version: 1,
377 source: {
378 environmentId: input.environmentId,
379 ...(input.threadId ? { threadId: input.threadId } : {}),
380 messageId: input.messageId,
381 },
382 records,
383 });
385​
386export function resolveUserMessageContext(message: {
387 text: string;
388 context?: OrchestrationMessageContext | undefined;
389}): ResolvedUserMessageContext {
390 const resolved = message.context
391 ? { text: message.text, records: message.context.records }
392 : upgradeLegacyContextMessage(message.text);
393 return {
394 text: resolved.text,
395 records: resolved.records,
396 recordsById: new Map(resolved.records.map((record) => [record.contextId, record])),
397 };
399​
400export function terminalContextDraftFromRecord(
401 record: TerminalContextRecord,
402 threadId: ThreadId,
403): TerminalContextDraft {
404 return {
405 id: producerIdFromComposerContextId("terminal", record.contextId),
406 threadId,
407 createdAt: new Date().toISOString(),
408 terminalId: record.terminalId,
409 terminalLabel: record.terminalLabel,
410 lineStart: record.lineStart,
411 lineEnd: record.lineEnd,
412 text: record.text,
413 };
415​
416export function reviewCommentFromRecord(record: ReviewCommentContextRecord): ReviewCommentContext {
417 return {
418 id: producerIdFromComposerContextId("review-comment", record.contextId),
419 sectionId: record.sectionId,
420 sectionTitle: record.sectionTitle,
421 filePath: record.filePath,
422 startIndex: record.startIndex,
423 endIndex: record.endIndex,
424 rangeLabel: record.rangeLabel,
425 text: record.text,
426 diff: record.diff,
427 ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),
428 ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
429 };
431​
432export function previewAnnotationFromRecord(
433 record: PreviewAnnotationContextRecord,
434): PreviewAnnotationPayload {
435 return {
436 id:
437 record.annotationId ||
438 producerIdFromComposerContextId("preview-annotation", record.contextId),
439 pageUrl: record.pageUrl,
440 pageTitle: record.pageTitle,
441 comment: record.comment,
442 elements: (record.elements ?? []).map((element, index) => ({
443 id: record.elementIds?.[index] ?? `${record.contextId}-element-${index + 1}`,
444 rect: { x: 0, y: 0, width: 0, height: 0 },
445 element: { ...element, stack: [], pickedAt: new Date().toISOString() },
446 })),
447 regions: Array.from({ length: record.regionCount ?? 0 }, (_unused, index) => ({
448 id: `${record.contextId}-region-${index + 1}`,
449 rect: { x: 0, y: 0, width: 0, height: 0 },
450 })),
451 strokes: Array.from({ length: record.strokeCount ?? 0 }, (_unused, index) => ({
452 id: `${record.contextId}-stroke-${index + 1}`,
453 color: "",
454 width: 0,
455 points: [],
456 bounds: { x: 0, y: 0, width: 0, height: 0 },
457 })),
458 styleChanges:
459 record.styleChangeDetails ??
460 record.styleChanges.flatMap((change) => {
461 const match = /^(.+?): ([\s\S]*?) → ([\s\S]*)$/.exec(change);
462 if (!match) return [];
463 return [
464 {
465 targetId: record.elementIds?.[0] ?? `${record.contextId}-element-1`,
466 selector: null,
467 property: match[1]!,
468 previousValue: match[2] === "(unset)" ? "" : match[2]!,
469 value: match[3]!,
470 },
471 ];
472 }),
473 screenshot: null,
474 createdAt: new Date().toISOString(),
475 };
477​
478/** Labels are display-only; folded ids can collide, so paste deduplication compares payloads. */
479export function isSameComposerContextPayload(
480 left: ComposerContextRecord,
481 right: ComposerContextRecord,
482): boolean {
483 if (left.kind !== right.kind) return false;
484 const stableKey = (record: ComposerContextRecord) => {
485 const { label: _label, contextId: _contextId, ...rest } = record;
486 const sortDeep = (value: unknown): unknown => {
487 if (Array.isArray(value)) return value.map(sortDeep);
488 if (value === null || typeof value !== "object") return value;
489 return Object.fromEntries(
490 Object.entries(value)
491 .toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
492 .map(([key, nested]) => [key, sortDeep(nested)]),
493 );
494 };
495 return JSON.stringify(sortDeep(rest));
496 };
497 return stableKey(left) === stableKey(right);