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

composerContextRecords.ts

499 lines17.9 KB

1import {
2 COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS,
3 COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS,
4} from "@t3tools/contracts";
5import type {
6 ComposerContextId,
7 ComposerContextRecord,
8 EnvironmentId,
9 FileContextRecord,
10 ImageContextRecord,
11 KnownComposerContextRecord,
12 MessageId,
13 OrchestrationMessageContext,
14 PreviewAnnotationContextRecord,
15 PreviewAnnotationPayload,
16 ReviewCommentContextRecord,
17 ScopedThreadRef,
18 TerminalContextRecord,
19 ThreadContextRecord,
20 ThreadId,
21} from "@t3tools/contracts";
22import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
23import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
24import {
25 collectComposerContextReferences,
26 sanitizeComposerContextLabel,
27 toKindScopedComposerContextId,
28} from "@t3tools/shared/composerContextReferences";
29​
30import {
31 type ComposerContextReference,
32 producerIdFromComposerContextId,
33} from "./composerContextReferences";
34import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
35import type { AttachmentUploadState } from "./attachmentUploadState";
36import { normalizeElementContextSelection } from "./elementContext";
37import {
38 formatTerminalContextLabel,
39 normalizeTerminalContextText,
40 type TerminalContextDraft,
41} from "./terminalContext";
42import type { ReviewCommentContext } from "~/reviewCommentContext";
43​
44const PREVIEW_LABEL_MAX_CHARS = 48;
45​
46/**
47 * A review selection can be arbitrarily large, but the wire schema bounds `text` and `diff`.
48 * Clamp at the same boundary so an oversized selection still sends, marked where it was cut,
49 * rather than failing to encode at send time.
50 */
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 state = pullRequestContextDisplayState(comment);
103 if (state === null) return "Pull request";
104 return `${state[0]!.toUpperCase()}${state.slice(1)} pull request`;
106​
107export function previewAnnotationContextLabel(annotation: PreviewAnnotationPayload): string {
108 const comment = annotation.comment.trim().replace(/\s+/g, " ");
109 if (comment) {
110 return comment.length > PREVIEW_LABEL_MAX_CHARS
111 ? `${comment.slice(0, PREVIEW_LABEL_MAX_CHARS - 1)}…`
112 : comment;
113 }
114 return annotation.pageTitle?.trim() || "Preview annotation";
116​
117export function terminalContextReference(context: TerminalContextDraft): ComposerContextReference {
118 return {
119 kind: "terminal",
120 contextId: toKindScopedComposerContextId("terminal", context.id),
121 label: formatTerminalContextLabel(context),
122 };
124​
125export function reviewCommentContextId(commentId: string): ComposerContextId {
126 return toKindScopedComposerContextId("review-comment", commentId);
128​
129export function previewAnnotationContextId(annotationId: string): ComposerContextId {
130 return toKindScopedComposerContextId("preview-annotation", annotationId);
132​
133export function reviewCommentContextReference(
134 comment: ReviewCommentContext,
135): ComposerContextReference {
136 return {
137 kind: "review-comment",
138 contextId: reviewCommentContextId(comment.id),
139 label: reviewCommentContextLabel(comment),
140 };
142​
143export function previewAnnotationContextReference(
144 annotation: PreviewAnnotationPayload,
145): ComposerContextReference {
146 return {
147 kind: "preview-annotation",
148 contextId: previewAnnotationContextId(annotation.id),
149 label: previewAnnotationContextLabel(annotation),
150 };
152​
153function threadContextId(threadId: ThreadId): ComposerContextId {
154 return toKindScopedComposerContextId("thread", threadId);
156​
157export function threadContextReference(record: ThreadContextRecord): ComposerContextReference {
158 return { kind: "thread", contextId: record.contextId, label: record.label };
160​
161export function threadContextRecord(ref: ScopedThreadRef, title: string): ThreadContextRecord {
162 const label = sanitizeComposerContextLabel(title, "thread");
163 return {
164 version: 1,
165 kind: "thread",
166 contextId: threadContextId(ref.threadId),
167 label,
168 environmentId: ref.environmentId,
169 threadId: ref.threadId,
170 title: label,
171 };
173​
174export function terminalContextRecord(context: TerminalContextDraft): TerminalContextRecord {
175 return {
176 version: 1,
177 contextId: toKindScopedComposerContextId("terminal", context.id),
178 kind: "terminal",
179 label: sanitizeComposerContextLabel(formatTerminalContextLabel(context), "terminal"),
180 terminalId: context.terminalId,
181 terminalLabel: context.terminalLabel,
182 lineStart: context.lineStart,
183 lineEnd: context.lineEnd,
184 text: normalizeTerminalContextText(context.text),
185 };
187​
188export function reviewCommentContextRecord(
189 comment: ReviewCommentContext,
190): ReviewCommentContextRecord {
191 return {
192 version: 1,
193 contextId: reviewCommentContextId(comment.id),
194 kind: "review-comment",
195 label: sanitizeComposerContextLabel(reviewCommentContextLabel(comment), "review-comment"),
196 sectionId: comment.sectionId,
197 sectionTitle: comment.sectionTitle,
198 filePath: comment.filePath,
199 startIndex: comment.startIndex,
200 endIndex: comment.endIndex,
201 rangeLabel: comment.rangeLabel,
202 text: clampContextText(comment.text, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
203 diff: clampContextText(comment.diff, COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
204 ...(comment.fenceLanguage !== undefined ? { fenceLanguage: comment.fenceLanguage } : {}),
205 ...(comment.pullRequest !== undefined ? { pullRequest: comment.pullRequest } : {}),
206 };
208​
209function previewAnnotationTargetSummary(annotation: PreviewAnnotationPayload): string {
210 const parts: string[] = [];
211 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
212 if (annotation.elements.length > 0)
213 parts.push(plural(annotation.elements.length, "selected element"));
214 if (annotation.regions.length > 0) parts.push(plural(annotation.regions.length, "marked region"));
215 if (annotation.strokes.length > 0) parts.push(plural(annotation.strokes.length, "drawing"));
216 return parts.join(", ");
218​
219export function previewAnnotationContextRecord(
220 annotation: PreviewAnnotationPayload,
221 options?: { screenshotContextId?: string | undefined },
222): PreviewAnnotationContextRecord {
223 const targets = annotation.elements.flatMap((target) => {
224 const element = normalizeElementContextSelection(target.element);
225 return element ? [{ id: target.id, element }] : [];
226 });
227 return {
228 version: 1,
229 contextId: previewAnnotationContextId(annotation.id),
230 kind: "preview-annotation",
231 label: sanitizeComposerContextLabel(
232 previewAnnotationContextLabel(annotation),
233 "preview-annotation",
234 ),
235 annotationId: annotation.id,
236 pageUrl: annotation.pageUrl,
237 pageTitle: annotation.pageTitle,
238 comment: annotation.comment.trim(),
239 targetSummary: previewAnnotationTargetSummary(annotation),
240 styleChanges: annotation.styleChanges.map(
241 (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,
242 ),
243 ...(targets.length > 0
244 ? {
245 elements: targets.map((target) => target.element),
246 elementIds: targets.map((target) => target.id),
247 }
248 : {}),
249 styleChangeDetails: annotation.styleChanges.map((change) => ({ ...change })),
250 ...(annotation.regions.length > 0 ? { regionCount: annotation.regions.length } : {}),
251 ...(annotation.strokes.length > 0 ? { strokeCount: annotation.strokes.length } : {}),
252 ...(options?.screenshotContextId !== undefined
253 ? { screenshotContextId: toKindScopedComposerContextId("image", options.screenshotContextId) }
254 : {}),
255 };
257​
258export function imageContextReference(image: ComposerImageAttachment): ComposerContextReference {
259 return {
260 kind: "image",
261 contextId: toKindScopedComposerContextId("image", image.id),
262 label: image.name,
263 };
265​
266export function fileContextReference(file: ComposerFileAttachment): ComposerContextReference {
267 return {
268 kind: "file",
269 contextId: toKindScopedComposerContextId("file", file.id),
270 label: file.name,
271 };
273​
274export interface BoundComposerAttachment {
275 attachment: ComposerImageAttachment | ComposerFileAttachment;
276 attachmentId: string;
278​
279/** Clipboard payloads may only point at attachments that already exist on the server. */
280export function uploadedAttachmentContextRecord(
281 attachment: ComposerImageAttachment | ComposerFileAttachment,
282 upload: AttachmentUploadState | undefined,
283): ImageContextRecord | FileContextRecord | null {
284 const attachmentId =
285 attachment.type === "file" && attachment.uploadedAttachmentId !== undefined
286 ? attachment.uploadedAttachmentId
287 : upload?.status === "ready"
288 ? upload.attachmentId
289 : undefined;
290 return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId });
292​
293export function attachmentContextRecord(
294 bound: BoundComposerAttachment,
295): ImageContextRecord | FileContextRecord {
296 const { attachment, attachmentId } = bound;
297 const base = {
298 version: 1 as const,
299 contextId: toKindScopedComposerContextId(attachment.type, attachment.id),
300 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
301 attachmentId,
302 name: attachment.name,
303 mimeType: attachment.mimeType,
304 sizeBytes: attachment.sizeBytes,
305 };
306 return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };
308​
309export function buildMessageContext(input: {
310 terminalContexts: ReadonlyArray<TerminalContextDraft>;
311 reviewComments: ReadonlyArray<ReviewCommentContext>;
312 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
313 threadContexts?: ReadonlyArray<ThreadContextRecord>;
314 attachments?: ReadonlyArray<BoundComposerAttachment>;
315}): OrchestrationMessageContext | undefined {
316 const screenshotAttachmentIds = new Set(
317 (input.attachments ?? []).flatMap(({ attachment }) =>
318 attachment.type === "image" ? [attachment.id] : [],
319 ),
320 );
321 const records: ComposerContextRecord[] = [
322 ...input.terminalContexts.map(terminalContextRecord),
323 ...input.reviewComments.map(reviewCommentContextRecord),
324 ...(input.threadContexts ?? []),
325 ...input.previewAnnotations.map((annotation) =>
326 previewAnnotationContextRecord(annotation, {
327 screenshotContextId: screenshotAttachmentIds.has(annotation.id) ? annotation.id : undefined,
328 }),
329 ),
330 ...(input.attachments ?? []).map(attachmentContextRecord),
331 ];
332 return records.length === 0 ? undefined : { version: 1, records };
334​
335export function asKnownContextRecord(
336 record: ComposerContextRecord | undefined,
337): KnownComposerContextRecord | undefined {
338 if (!record || "payload" in record) return undefined;
339 return record as KnownComposerContextRecord;
341​
342export function composerContextImportLookupIds(
343 record: KnownComposerContextRecord,
344): ReadonlyArray<ComposerContextId> {
345 const destinationId = toKindScopedComposerContextId(
346 record.kind,
347 producerIdFromComposerContextId(record.kind, record.contextId),
348 );
349 return destinationId === record.contextId
350 ? [record.contextId]
351 : [destinationId, record.contextId];
353​
354export interface ResolvedUserMessageContext {
355 text: string;
356 records: ReadonlyArray<ComposerContextRecord>;
357 recordsById: ReadonlyMap<string, ComposerContextRecord>;
359​
360export function selectedMessageContextFragment(input: {
361 readonly markdown: string;
362 readonly records: ReadonlyArray<ComposerContextRecord>;
363 readonly environmentId: EnvironmentId;
364 readonly threadId?: ThreadId;
365 readonly messageId: MessageId;
366}): string | null {
367 const selectedIds = new Set(
368 collectComposerContextReferences(input.markdown).map((occurrence) => occurrence.contextId),
369 );
370 const records = input.records.filter((record) => selectedIds.has(record.contextId));
371 if (records.length === 0) return null;
372 return encodeComposerContextFragment({
373 version: 1,
374 source: {
375 environmentId: input.environmentId,
376 ...(input.threadId ? { threadId: input.threadId } : {}),
377 messageId: input.messageId,
378 },
379 records,
380 });
382​
383export function resolveUserMessageContext(message: {
384 text: string;
385 context?: OrchestrationMessageContext | undefined;
386}): ResolvedUserMessageContext {
387 const resolved = message.context
388 ? { text: message.text, records: message.context.records }
389 : upgradeLegacyContextMessage(message.text);
390 return {
391 text: resolved.text,
392 records: resolved.records,
393 recordsById: new Map(resolved.records.map((record) => [record.contextId, record])),
394 };
396​
397export function terminalContextDraftFromRecord(
398 record: TerminalContextRecord,
399 threadId: ThreadId,
400): TerminalContextDraft {
401 return {
402 id: producerIdFromComposerContextId("terminal", record.contextId),
403 threadId,
404 createdAt: new Date().toISOString(),
405 terminalId: record.terminalId,
406 terminalLabel: record.terminalLabel,
407 lineStart: record.lineStart,
408 lineEnd: record.lineEnd,
409 text: record.text,
410 };
412​
413export function reviewCommentFromRecord(record: ReviewCommentContextRecord): ReviewCommentContext {
414 return {
415 id: producerIdFromComposerContextId("review-comment", record.contextId),
416 sectionId: record.sectionId,
417 sectionTitle: record.sectionTitle,
418 filePath: record.filePath,
419 startIndex: record.startIndex,
420 endIndex: record.endIndex,
421 rangeLabel: record.rangeLabel,
422 text: record.text,
423 diff: record.diff,
424 ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),
425 ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
426 };
428​
429export function previewAnnotationFromRecord(
430 record: PreviewAnnotationContextRecord,
431): PreviewAnnotationPayload {
432 return {
433 id:
434 record.annotationId ||
435 producerIdFromComposerContextId("preview-annotation", record.contextId),
436 pageUrl: record.pageUrl,
437 pageTitle: record.pageTitle,
438 comment: record.comment,
439 elements: (record.elements ?? []).map((element, index) => ({
440 id: record.elementIds?.[index] ?? `${record.contextId}-element-${index + 1}`,
441 rect: { x: 0, y: 0, width: 0, height: 0 },
442 element: { ...element, stack: [], pickedAt: new Date().toISOString() },
443 })),
444 regions: Array.from({ length: record.regionCount ?? 0 }, (_unused, index) => ({
445 id: `${record.contextId}-region-${index + 1}`,
446 rect: { x: 0, y: 0, width: 0, height: 0 },
447 })),
448 strokes: Array.from({ length: record.strokeCount ?? 0 }, (_unused, index) => ({
449 id: `${record.contextId}-stroke-${index + 1}`,
450 color: "",
451 width: 0,
452 points: [],
453 bounds: { x: 0, y: 0, width: 0, height: 0 },
454 })),
455 styleChanges:
456 record.styleChangeDetails ??
457 record.styleChanges.flatMap((change) => {
458 const match = /^(.+?): ([\s\S]*?) → ([\s\S]*)$/.exec(change);
459 if (!match) return [];
460 return [
461 {
462 targetId: record.elementIds?.[0] ?? `${record.contextId}-element-1`,
463 selector: null,
464 property: match[1]!,
465 previousValue: match[2] === "(unset)" ? "" : match[2]!,
466 value: match[3]!,
467 },
468 ];
469 }),
470 screenshot: null,
471 createdAt: new Date().toISOString(),
472 };
474​
475/**
476 * Whether two records carry the same payload, ignoring the label (display text, never
477 * identity). Context ids are a folded form of producer ids, so a collision alone does not mean
478 * the records are the same excerpt; the paste path compares payloads before de-duplicating.
479 */
480export function isSameComposerContextPayload(
481 left: ComposerContextRecord,
482 right: ComposerContextRecord,
483): boolean {
484 if (left.kind !== right.kind) return false;
485 const stableKey = (record: ComposerContextRecord) => {
486 const { label: _label, contextId: _contextId, ...rest } = record;
487 const sortDeep = (value: unknown): unknown => {
488 if (Array.isArray(value)) return value.map(sortDeep);
489 if (value === null || typeof value !== "object") return value;
490 return Object.fromEntries(
491 Object.entries(value)
492 .toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
493 .map(([key, nested]) => [key, sortDeep(nested)]),
494 );
495 };
496 return JSON.stringify(sortDeep(rest));
497 };
498 return stableKey(left) === stableKey(right);