Open History to see the last commit
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 TerminalContextRecord,
18 ThreadId,
19} from "@t3tools/contracts";
20import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
21import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
22import {
23 collectComposerContextReferences,
24 sanitizeComposerContextLabel,
25} from "@t3tools/shared/composerContextReferences";
26
27import {
28 type ComposerContextReference,
29 producerIdFromComposerContextId,
30 toKindScopedComposerContextId,
31} from "./composerContextReferences";
32import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
33import type { AttachmentUploadState } from "./attachmentUploadState";
34import { normalizeElementContextSelection } from "./elementContext";
35import {
36 formatTerminalContextLabel,
37 normalizeTerminalContextText,
38 type TerminalContextDraft,
39} from "./terminalContext";
40import type { ReviewCommentContext } from "~/reviewCommentContext";
41
42/**
43 * Builds the wire records behind a draft's inline references, and the reverse for reading a
44 * message. Draft shapes stay what the producing panels emit; only the send boundary converts.
45 */
46
47const PREVIEW_LABEL_MAX_CHARS = 48;
48
49/**
50 * A review selection can be arbitrarily large, but the wire schema bounds `text` and `diff`.
51 * Clamp at the same boundary so an oversized selection still sends, marked where it was cut,
52 * rather than failing to encode at send time.
53 */
54const TRUNCATION_MARKER = "\n… truncated …";
55
56function clampContextText(value: string, max: number): string {
57 if (value.length <= max) return value;
58 return `${value.slice(0, Math.max(0, max - TRUNCATION_MARKER.length))}${TRUNCATION_MARKER}`;
59}
60
61type ReviewCommentPresentation = ReviewCommentContext | ReviewCommentContextRecord;
62
63function basename(filePath: string): string {
64 return filePath.split(/[\\/]/).at(-1) ?? filePath;
65}
66
67export function reviewCommentContextLabel(comment: ReviewCommentPresentation): string {
68 const pullRequestNumber = pullRequestContextNumber(comment);
69 if (isPullRequestSummaryContext(comment) && pullRequestNumber !== null) {
70 return `#${pullRequestNumber}`;
71 }
72 const diffRange = /^([+-])(\d+)(?: to \1(\d+))?$/u.exec(comment.rangeLabel);
73 const rangeLabel = diffRange
74 ? `L${diffRange[2]}${diffRange[3] ? ` to L${diffRange[3]}` : ""}${diffRange[1] === "-" ? " (before)" : ""}`
75 : comment.rangeLabel;
76 return `${basename(comment.filePath)} ${rangeLabel}`;
77}
78
79export function isPullRequestSummaryContext(comment: ReviewCommentPresentation): boolean {
80 if (comment.pullRequest !== undefined) return true;
81 return (
82 comment.sectionId.startsWith("pull-request:") &&
83 comment.diff.trim().length === 0 &&
84 /^PR #\d+$/u.test(comment.filePath)
85 );
86}
87
88function pullRequestContextNumber(comment: ReviewCommentPresentation): number | null {
89 if (comment.pullRequest !== undefined) return comment.pullRequest.number;
90 const legacyNumber = /^PR #(\d+)$/u.exec(comment.filePath)?.[1];
91 return legacyNumber === undefined ? null : Number(legacyNumber);
92}
93
94export type PullRequestContextDisplayState = "open" | "draft" | "merged" | "closed";
95
96export function pullRequestContextDisplayState(
97 comment: ReviewCommentPresentation,
98): PullRequestContextDisplayState | null {
99 const pullRequest = comment.pullRequest;
100 if (pullRequest === undefined) return null;
101 return pullRequest.state === "open" && pullRequest.isDraft ? "draft" : pullRequest.state;
102}
103
104export function pullRequestContextKindLabel(comment: ReviewCommentPresentation): string {
105 const state = pullRequestContextDisplayState(comment);
106 if (state === null) return "Pull request";
107 return `${state[0]!.toUpperCase()}${state.slice(1)} pull request`;
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
128/** Review producers mint ids in their own grammars; the context id is a folded form of them. */
129export function reviewCommentContextId(commentId: string): ComposerContextId {
130 return toKindScopedComposerContextId("review-comment", commentId);
131}
132
133/** Distinct from the screenshot image, which reuses the annotation id as its attachment id. */
134export function previewAnnotationContextId(annotationId: string): ComposerContextId {
135 return toKindScopedComposerContextId("preview-annotation", annotationId);
136}
137
138export function reviewCommentContextReference(
139 comment: ReviewCommentContext,
140): ComposerContextReference {
141 return {
142 kind: "review-comment",
143 contextId: reviewCommentContextId(comment.id),
144 label: reviewCommentContextLabel(comment),
145 };
146}
147
148export function previewAnnotationContextReference(
149 annotation: PreviewAnnotationPayload,
150): ComposerContextReference {
151 return {
152 kind: "preview-annotation",
153 contextId: previewAnnotationContextId(annotation.id),
154 label: previewAnnotationContextLabel(annotation),
155 };
156}
157
158export function terminalContextRecord(context: TerminalContextDraft): TerminalContextRecord {
159 return {
160 version: 1,
161 contextId: toKindScopedComposerContextId("terminal", context.id),
162 kind: "terminal",
163 label: sanitizeComposerContextLabel(formatTerminalContextLabel(context), "terminal"),
164 terminalId: context.terminalId,
165 terminalLabel: context.terminalLabel,
166 lineStart: context.lineStart,
167 lineEnd: context.lineEnd,
168 text: normalizeTerminalContextText(context.text),
169 };
170}
171
172export function reviewCommentContextRecord(
173 comment: ReviewCommentContext,
174): ReviewCommentContextRecord {
175 return {
176 version: 1,
177 contextId: reviewCommentContextId(comment.id),
178 kind: "review-comment",
179 label: sanitizeComposerContextLabel(reviewCommentContextLabel(comment), "review-comment"),
180 sectionId: comment.sectionId,
181 sectionTitle: comment.sectionTitle,
182 filePath: comment.filePath,
183 startIndex: comment.startIndex,
184 endIndex: comment.endIndex,
185 rangeLabel: comment.rangeLabel,
186 text: clampContextText(comment.text, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
187 diff: clampContextText(comment.diff, COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
188 ...(comment.fenceLanguage !== undefined ? { fenceLanguage: comment.fenceLanguage } : {}),
189 ...(comment.pullRequest !== undefined ? { pullRequest: comment.pullRequest } : {}),
190 };
191}
192
193function previewAnnotationTargetSummary(annotation: PreviewAnnotationPayload): string {
194 const parts: string[] = [];
195 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
196 if (annotation.elements.length > 0)
197 parts.push(plural(annotation.elements.length, "selected element"));
198 if (annotation.regions.length > 0) parts.push(plural(annotation.regions.length, "marked region"));
199 if (annotation.strokes.length > 0) parts.push(plural(annotation.strokes.length, "drawing"));
200 return parts.join(", ");
201}
202
203export function previewAnnotationContextRecord(
204 annotation: PreviewAnnotationPayload,
205 options?: { screenshotContextId?: string | undefined },
206): PreviewAnnotationContextRecord {
207 const targets = annotation.elements.flatMap((target) => {
208 const element = normalizeElementContextSelection(target.element);
209 return element ? [{ id: target.id, element }] : [];
210 });
211 return {
212 version: 1,
213 contextId: previewAnnotationContextId(annotation.id),
214 kind: "preview-annotation",
215 label: sanitizeComposerContextLabel(
216 previewAnnotationContextLabel(annotation),
217 "preview-annotation",
218 ),
219 annotationId: annotation.id,
220 pageUrl: annotation.pageUrl,
221 pageTitle: annotation.pageTitle,
222 comment: annotation.comment.trim(),
223 targetSummary: previewAnnotationTargetSummary(annotation),
224 styleChanges: annotation.styleChanges.map(
225 (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,
226 ),
227 ...(targets.length > 0
228 ? {
229 elements: targets.map((target) => target.element),
230 elementIds: targets.map((target) => target.id),
231 }
232 : {}),
233 styleChangeDetails: annotation.styleChanges.map((change) => ({ ...change })),
234 ...(annotation.regions.length > 0 ? { regionCount: annotation.regions.length } : {}),
235 ...(annotation.strokes.length > 0 ? { strokeCount: annotation.strokes.length } : {}),
236 ...(options?.screenshotContextId !== undefined
237 ? { screenshotContextId: toKindScopedComposerContextId("image", options.screenshotContextId) }
238 : {}),
239 };
240}
241
242export function imageContextReference(image: ComposerImageAttachment): ComposerContextReference {
243 return {
244 kind: "image",
245 contextId: toKindScopedComposerContextId("image", image.id),
246 label: image.name,
247 };
248}
249
250export function fileContextReference(file: ComposerFileAttachment): ComposerContextReference {
251 return {
252 kind: "file",
253 contextId: toKindScopedComposerContextId("file", file.id),
254 label: file.name,
255 };
256}
257
258/** Binds a draft attachment to the id the receiving side will know it by. */
259export interface BoundComposerAttachment {
260 attachment: ComposerImageAttachment | ComposerFileAttachment;
261 attachmentId: string;
262}
263
264/** Clipboard payloads may only point at attachments that already exist on the server. */
265export function uploadedAttachmentContextRecord(
266 attachment: ComposerImageAttachment | ComposerFileAttachment,
267 upload: AttachmentUploadState | undefined,
268): ImageContextRecord | FileContextRecord | null {
269 const attachmentId =
270 attachment.type === "file" && attachment.uploadedAttachmentId !== undefined
271 ? attachment.uploadedAttachmentId
272 : upload?.status === "ready"
273 ? upload.attachmentId
274 : undefined;
275 return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId });
276}
277
278export function attachmentContextRecord(
279 bound: BoundComposerAttachment,
280): ImageContextRecord | FileContextRecord {
281 const { attachment, attachmentId } = bound;
282 const base = {
283 version: 1 as const,
284 contextId: toKindScopedComposerContextId(attachment.type, attachment.id),
285 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
286 attachmentId,
287 name: attachment.name,
288 mimeType: attachment.mimeType,
289 sizeBytes: attachment.sizeBytes,
290 };
291 return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };
292}
293
294export function buildMessageContext(input: {
295 terminalContexts: ReadonlyArray<TerminalContextDraft>;
296 reviewComments: ReadonlyArray<ReviewCommentContext>;
297 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
298 attachments?: ReadonlyArray<BoundComposerAttachment>;
299}): OrchestrationMessageContext | undefined {
300 // An annotation's screenshot travels as the image attachment that reuses its id.
301 const screenshotAttachmentIds = new Set(
302 (input.attachments ?? []).flatMap(({ attachment }) =>
303 attachment.type === "image" ? [attachment.id] : [],
304 ),
305 );
306 const records: ComposerContextRecord[] = [
307 ...input.terminalContexts.map(terminalContextRecord),
308 ...input.reviewComments.map(reviewCommentContextRecord),
309 ...input.previewAnnotations.map((annotation) =>
310 previewAnnotationContextRecord(annotation, {
311 screenshotContextId: screenshotAttachmentIds.has(annotation.id) ? annotation.id : undefined,
312 }),
313 ),
314 ...(input.attachments ?? []).map(attachmentContextRecord),
315 ];
316 return records.length === 0 ? undefined : { version: 1, records };
317}
318
319/**
320 * Narrows away the unknown-kind member. Its `kind` is an open string, so a plain
321 * `record.kind === "terminal"` check cannot discriminate the union on its own.
322 */
323export function asKnownContextRecord(
324 record: ComposerContextRecord | undefined,
325): KnownComposerContextRecord | undefined {
326 if (!record || "payload" in record) return undefined;
327 return record as KnownComposerContextRecord;
328}
329
330/** Candidate keys for finding the draft record an imported wire record would reconstruct. */
331export function composerContextImportLookupIds(
332 record: KnownComposerContextRecord,
333): ReadonlyArray<ComposerContextId> {
334 const destinationId = toKindScopedComposerContextId(
335 record.kind,
336 producerIdFromComposerContextId(record.kind, record.contextId),
337 );
338 return destinationId === record.contextId
339 ? [record.contextId]
340 : [destinationId, record.contextId];
341}
342
343export interface ResolvedUserMessageContext {
344 text: string;
345 records: ReadonlyArray<ComposerContextRecord>;
346 recordsById: ReadonlyMap<string, ComposerContextRecord>;
347}
348
349/**
350 * The clipboard fragment behind a timeline message selection: only records for
351 * chips actually inside the selection travel, so copying prose next to an
352 * image never starts importing that image somewhere else. Returns null when no
353 * selected chip has backing records.
354 */
355export function selectedMessageContextFragment(input: {
356 readonly markdown: string;
357 readonly records: ReadonlyArray<ComposerContextRecord>;
358 readonly environmentId: EnvironmentId;
359 readonly threadId?: ThreadId;
360 readonly messageId: MessageId;
361}): string | null {
362 const selectedIds = new Set(
363 collectComposerContextReferences(input.markdown).map((occurrence) => occurrence.contextId),
364 );
365 const records = input.records.filter((record) => selectedIds.has(record.contextId));
366 if (records.length === 0) return null;
367 return encodeComposerContextFragment({
368 version: 1,
369 source: {
370 environmentId: input.environmentId,
371 ...(input.threadId ? { threadId: input.threadId } : {}),
372 messageId: input.messageId,
373 },
374 records,
375 });
376}
377
378/** A message's canonical text plus records; old messages are upgraded in memory on read. */
379export function resolveUserMessageContext(message: {
380 text: string;
381 context?: OrchestrationMessageContext | undefined;
382}): ResolvedUserMessageContext {
383 const resolved = message.context
384 ? { text: message.text, records: message.context.records }
385 : upgradeLegacyContextMessage(message.text);
386 return {
387 text: resolved.text,
388 records: resolved.records,
389 recordsById: new Map(resolved.records.map((record) => [record.contextId, record])),
390 };
391}
392
393// ---------------------------------------------------------------------------
394// Records back into draft shapes (paste)
395// ---------------------------------------------------------------------------
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 };
411}
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 };
427}
428
429/** Lossy on purpose: geometry and screenshot do not travel; the agent-facing detail does. */
430export function previewAnnotationFromRecord(
431 record: PreviewAnnotationContextRecord,
432): PreviewAnnotationPayload {
433 return {
434 id:
435 record.annotationId ||
436 producerIdFromComposerContextId("preview-annotation", record.contextId),
437 pageUrl: record.pageUrl,
438 pageTitle: record.pageTitle,
439 comment: record.comment,
440 elements: (record.elements ?? []).map((element, index) => ({
441 id: record.elementIds?.[index] ?? `${record.contextId}-element-${index + 1}`,
442 rect: { x: 0, y: 0, width: 0, height: 0 },
443 element: { ...element, stack: [], pickedAt: new Date().toISOString() },
444 })),
445 // Geometry does not travel, but the counts do, so the rebuilt summary still reports
446 // what the annotation marked.
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 };
476}
477
478/**
479 * Whether two records carry the same payload, ignoring the label (display text, never
480 * identity). Context ids are a folded form of producer ids, so a collision alone does not mean
481 * the records are the same excerpt; the paste path compares payloads before de-duplicating.
482 */
483export function isSameComposerContextPayload(
484 left: ComposerContextRecord,
485 right: ComposerContextRecord,
486): boolean {
487 if (left.kind !== right.kind) return false;
488 const stableKey = (record: ComposerContextRecord) => {
489 // Labels are display text and context ids are folded producer ids: neither
490 // distinguishes excerpts, so an imported legacy id must still match the
491 // canonical id reconstructed for the same payload instead of duplicating it.
492 const { label: _label, contextId: _contextId, ...rest } = record;
493 const sortDeep = (value: unknown): unknown => {
494 if (Array.isArray(value)) return value.map(sortDeep);
495 if (value === null || typeof value !== "object") return value;
496 return Object.fromEntries(
497 Object.entries(value)
498 .toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
499 .map(([key, nested]) => [key, sortDeep(nested)]),
500 );
501 };
502 return JSON.stringify(sortDeep(rest));
503 };
504 return stableKey(left) === stableKey(right);
505}