@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 716 lines 25.3 KB
Raw
1 import {
2 capitalizeTerm,
3 sourceControlClients,
4 } from "@t3tools/client-runtime/source-control-clients";
5 import {
6 COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS,
7 COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS,
8 COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS,
9 COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS,
10 } from "@t3tools/contracts";
11 import type {
12 ComposerContextId,
13 ComposerContextRecord,
14 EnvironmentContextRecord,
15 EnvironmentId,
16 FileContextRecord,
17 ImageContextRecord,
18 KnownComposerContextRecord,
19 MessageId,
20 OrchestrationMessageContext,
21 PreviewAnnotationContextRecord,
22 PreviewAnnotationPayload,
23 ResponseContextRecord,
24 ReviewCommentContextRecord,
25 TerminalContextRecord,
26 ThreadContextRecord,
27 ThreadId,
28 } from "@t3tools/contracts";
29 import { decodeMsg, msg } from "gt-react";
30 import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
31 import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
32 import {
33 collectComposerContextReferences,
34 sanitizeComposerContextLabel,
35 toKindScopedComposerContextId,
36 } from "@t3tools/shared/composerContextReferences";
37
38 import {
39 type ComposerContextReference,
40 producerIdFromComposerContextId,
41 } from "./composerContextReferences";
42 import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
43 import type { AttachmentUploadState } from "./attachmentUploadState";
44 import { normalizeElementContextSelection } from "./elementContext";
45 import {
46 formatTerminalContextLabel,
47 normalizeTerminalContextText,
48 type TerminalContextDraft,
49 } from "./terminalContext";
50 import type { ReviewCommentContext } from "~/reviewCommentContext";
51 import type { MessageResolver } from "~/i18n/messages";
52 import { changeRequestTermKind } from "~/components/pullRequest/changeRequestTerm";
53
54 const PREVIEW_LABEL_MAX_CHARS = 48;
55 const RESPONSE_LABEL_MAX_CHARS = 64;
56
57 // Truncate selections to wire bounds before persistence to avoid send-time encoding failures.
58 const TRUNCATION_MARKER = "\n… truncated …";
59
60 function clampContextText(value: string, max: number): string {
61 if (value.length <= max) return value;
62 let end = Math.max(0, max - TRUNCATION_MARKER.length);
63 // Never end on a lone high surrogate.
64 const last = value.charCodeAt(end - 1);
65 if (last >= 0xd800 && last <= 0xdbff) end -= 1;
66 return `${value.slice(0, end)}${TRUNCATION_MARKER}`;
67 }
68
69 type ReviewCommentPresentation = ReviewCommentContext | ReviewCommentContextRecord;
70
71 function basename(filePath: string): string {
72 return filePath.split(/[\\/]/).at(-1) ?? filePath;
73 }
74
75 function diffRangeLabel(
76 start: string,
77 end: string | undefined,
78 before: boolean,
79 resolve: MessageResolver | undefined,
80 ): string {
81 if (resolve === undefined) {
82 return `L${start}${end ? ` to L${end}` : ""}${before ? " (before)" : ""}`;
83 }
84 if (end === undefined) {
85 return before
86 ? resolve(msg("L{start} (before)", { $context: "line in the old version of a diff" }), {
87 start,
88 })
89 : `L${start}`;
90 }
91 return before
92 ? resolve(
93 msg("L{start} to L{end} (before)", { $context: "line range in the old version of a diff" }),
94 { start, end },
95 )
96 : resolve(msg("L{start} to L{end}", { $context: "line range in a diff" }), { start, end });
97 }
98
99 /** Without `resolve` the label stays English, for records sent to the agent. */
100 export function reviewCommentContextLabel(
101 comment: ReviewCommentPresentation,
102 resolve?: MessageResolver,
103 ): string {
104 const pullRequestNumber = pullRequestContextNumber(comment);
105 if (isPullRequestSummaryContext(comment) && pullRequestNumber !== null) {
106 return `#${pullRequestNumber}`;
107 }
108 const diffRange = /^([+-])(\d+)(?: to \1(\d+))?$/u.exec(comment.rangeLabel);
109 const rangeLabel = diffRange
110 ? diffRangeLabel(diffRange[2]!, diffRange[3], diffRange[1] === "-", resolve)
111 : comment.rangeLabel;
112 const sectionPullRequest = /^pull-request:(\d+)$/u.exec(comment.sectionId)?.[1];
113 const prefix = sectionPullRequest === undefined ? "" : `#${sectionPullRequest} `;
114 return `${prefix}${basename(comment.filePath)} ${rangeLabel}`;
115 }
116
117 const REVIEW_SECTION_TITLES: ReadonlyMap<string, string> = new Map([
118 ["File comment", msg("File comment")],
119 ["Review guide", msg("Review guide")],
120 ]);
121
122 /** A stored review comment `sectionTitle` for display; the record itself stays English. */
123 export function reviewCommentSectionText(sectionTitle: string, resolve: MessageResolver): string {
124 const known = REVIEW_SECTION_TITLES.get(sectionTitle);
125 if (known !== undefined) return resolve(known);
126 const number = /^PR #(\d+) review$/u.exec(sectionTitle)?.[1];
127 return number === undefined ? sectionTitle : resolve(msg("PR #{number} review", { number }));
128 }
129
130 /** A stored `rangeLabel` such as "+12 to +15" or "L3 to L9" for display. */
131 export function reviewCommentRangeText(rangeLabel: string, resolve: MessageResolver): string {
132 const range = /^([+-]?L?\d+) to ([+-]?L?\d+)$/u.exec(rangeLabel);
133 return range === null
134 ? rangeLabel
135 : resolve(msg("{start} to {end}", { $context: "a range of lines in a file or diff" }), {
136 start: range[1]!,
137 end: range[2]!,
138 });
139 }
140
141 /** A preview annotation record's `targetSummary` rebuilt in the UI language when it has counts. */
142 export function previewAnnotationTargetText(
143 record: Pick<
144 PreviewAnnotationContextRecord,
145 "targetSummary" | "elementIds" | "regionCount" | "strokeCount"
146 >,
147 resolve: MessageResolver,
148 ): string {
149 const parts: string[] = [];
150 // The stored summary also counts selected elements whose details failed to normalize.
151 const summaryElements = /^(\d+) selected elements?\b/.exec(record.targetSummary)?.[1];
152 const elements =
153 summaryElements === undefined ? (record.elementIds?.length ?? 0) : Number(summaryElements);
154 if (elements > 0) {
155 parts.push(
156 resolve(
157 msg("{count, plural, one {{count} selected element} other {{count} selected elements}}", {
158 count: elements,
159 }),
160 ),
161 );
162 }
163 if ((record.regionCount ?? 0) > 0) {
164 parts.push(
165 resolve(
166 msg("{count, plural, one {{count} marked region} other {{count} marked regions}}", {
167 count: record.regionCount!,
168 }),
169 ),
170 );
171 }
172 if ((record.strokeCount ?? 0) > 0) {
173 parts.push(
174 resolve(
175 msg("{count, plural, one {{count} drawing} other {{count} drawings}}", {
176 count: record.strokeCount!,
177 }),
178 ),
179 );
180 }
181 // Older records carry only the English summary.
182 return parts.length === 0 ? record.targetSummary : parts.join(", ");
183 }
184
185 export function isPullRequestSummaryContext(comment: ReviewCommentPresentation): boolean {
186 if (comment.pullRequest !== undefined) return true;
187 return (
188 comment.sectionId.startsWith("pull-request:") &&
189 comment.diff.trim().length === 0 &&
190 /^PR #\d+$/u.test(comment.filePath)
191 );
192 }
193
194 function pullRequestContextNumber(comment: ReviewCommentPresentation): number | null {
195 if (comment.pullRequest !== undefined) return comment.pullRequest.number;
196 const legacyNumber = /^PR #(\d+)$/u.exec(comment.filePath)?.[1];
197 return legacyNumber === undefined ? null : Number(legacyNumber);
198 }
199
200 export type PullRequestContextDisplayState = "open" | "draft" | "merged" | "closed";
201
202 export function pullRequestContextDisplayState(
203 comment: ReviewCommentPresentation,
204 ): PullRequestContextDisplayState | null {
205 const pullRequest = comment.pullRequest;
206 if (pullRequest === undefined) return null;
207 return pullRequest.state === "open" && pullRequest.isDraft ? "draft" : pullRequest.state;
208 }
209
210 /** Without `resolve` the label stays English. */
211 export function pullRequestContextKindLabel(
212 comment: ReviewCommentPresentation,
213 resolve?: MessageResolver,
214 ): string {
215 const url = comment.pullRequest?.url;
216 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
217 const term = (host ?? sourceControlClients.get(undefined)).changeRequest.singular;
218 const state = pullRequestContextDisplayState(comment);
219 if (resolve !== undefined) {
220 const variables = { term: changeRequestTermKind({ singular: term }) };
221 switch (state) {
222 case null:
223 return resolve(
224 msg("{term, select, mr {Merge request} cr {Change request} other {Pull request}}"),
225 variables,
226 );
227 case "open":
228 return resolve(
229 msg(
230 "{term, select, mr {Open merge request} cr {Open change request} other {Open pull request}}",
231 ),
232 variables,
233 );
234 case "draft":
235 return resolve(
236 msg(
237 "{term, select, mr {Draft merge request} cr {Draft change request} other {Draft pull request}}",
238 ),
239 variables,
240 );
241 case "merged":
242 return resolve(
243 msg(
244 "{term, select, mr {Merged merge request} cr {Merged change request} other {Merged pull request}}",
245 ),
246 variables,
247 );
248 case "closed":
249 return resolve(
250 msg(
251 "{term, select, mr {Closed merge request} cr {Closed change request} other {Closed pull request}}",
252 ),
253 variables,
254 );
255 }
256 }
257 if (state === null) return capitalizeTerm(term);
258 return `${capitalizeTerm(state)} ${term}`;
259 }
260
261 /** Without `resolve` the fallback stays English, for records sent to the agent. */
262 export function previewAnnotationContextLabel(
263 annotation: PreviewAnnotationPayload,
264 resolve?: MessageResolver,
265 ): string {
266 const comment = annotation.comment.trim().replace(/\s+/g, " ");
267 if (comment) {
268 if (comment.length <= PREVIEW_LABEL_MAX_CHARS) return comment;
269 let end = PREVIEW_LABEL_MAX_CHARS - 1;
270 const previous = comment.charCodeAt(end - 1);
271 const next = comment.charCodeAt(end);
272 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end -= 1;
273 return `${comment.slice(0, end)}…`;
274 }
275 const fallback = msg("Preview annotation");
276 return annotation.pageTitle?.trim() || (resolve ? resolve(fallback) : decodeMsg(fallback));
277 }
278
279 export function terminalContextReference(context: TerminalContextDraft): ComposerContextReference {
280 return {
281 kind: "terminal",
282 contextId: toKindScopedComposerContextId("terminal", context.id),
283 label: formatTerminalContextLabel(context),
284 };
285 }
286
287 export function reviewCommentContextId(commentId: string): ComposerContextId {
288 return toKindScopedComposerContextId("review-comment", commentId);
289 }
290
291 export function previewAnnotationContextId(annotationId: string): ComposerContextId {
292 return toKindScopedComposerContextId("preview-annotation", annotationId);
293 }
294
295 export function reviewCommentContextReference(
296 comment: ReviewCommentContext,
297 ): ComposerContextReference {
298 return {
299 kind: "review-comment",
300 contextId: reviewCommentContextId(comment.id),
301 label: reviewCommentContextLabel(comment),
302 };
303 }
304
305 export function previewAnnotationContextReference(
306 annotation: PreviewAnnotationPayload,
307 ): ComposerContextReference {
308 return {
309 kind: "preview-annotation",
310 contextId: previewAnnotationContextId(annotation.id),
311 label: previewAnnotationContextLabel(annotation),
312 };
313 }
314
315 export function threadContextReference(record: ThreadContextRecord): ComposerContextReference {
316 return { kind: "thread", contextId: record.contextId, label: record.label };
317 }
318
319 export function isResponseContextRecord(
320 record: ComposerContextRecord,
321 ): record is ResponseContextRecord {
322 return record.kind === "response" && "citation" in record;
323 }
324
325 export function responseContextReference(record: ResponseContextRecord): ComposerContextReference {
326 return { kind: "response", contextId: record.contextId, label: record.label };
327 }
328
329 function responseContextLabel(text: string): string {
330 const last = text.charCodeAt(RESPONSE_LABEL_MAX_CHARS - 1);
331 const end =
332 last >= 0xd800 && last <= 0xdbff ? RESPONSE_LABEL_MAX_CHARS - 1 : RESPONSE_LABEL_MAX_CHARS;
333 return sanitizeComposerContextLabel(text.slice(0, end), "response");
334 }
335
336 /** One record per response, so replying to it again reuses the same reference. */
337 export function responseContextRecord(
338 input: Pick<ResponseContextRecord, "citation" | "itemId"> & {
339 readonly subagents: ReadonlyArray<{
340 readonly threadId: ThreadId;
341 readonly title: string;
342 readonly environmentId?: EnvironmentId;
343 }>;
344 },
345 ): ResponseContextRecord {
346 return {
347 version: 1,
348 kind: "response",
349 contextId: toKindScopedComposerContextId("response", input.citation.messageId),
350 label: responseContextLabel(input.citation.text),
351 citation: input.citation,
352 itemId: input.itemId,
353 ...(input.subagents.length > 0
354 ? {
355 subagents: input.subagents.slice(0, 20).map(({ title, ...subagent }) => ({
356 ...subagent,
357 title: sanitizeComposerContextLabel(title, "response"),
358 })),
359 }
360 : {}),
361 };
362 }
363
364 /** One record per machine: mentioning the same machine twice reuses the chip. */
365 export function environmentContextReference(
366 record: EnvironmentContextRecord,
367 ): ComposerContextReference {
368 return { kind: "environment", contextId: record.contextId, label: record.label };
369 }
370
371 export function environmentContextRecord(
372 environmentId: EnvironmentId,
373 label: string,
374 ): EnvironmentContextRecord {
375 return {
376 version: 1,
377 kind: "environment",
378 contextId: toKindScopedComposerContextId("environment", environmentId),
379 label: sanitizeComposerContextLabel(label, "environment"),
380 environmentId,
381 };
382 }
383
384 export function terminalContextRecord(context: TerminalContextDraft): TerminalContextRecord {
385 return {
386 version: 1,
387 contextId: toKindScopedComposerContextId("terminal", context.id),
388 kind: "terminal",
389 label: sanitizeComposerContextLabel(formatTerminalContextLabel(context), "terminal"),
390 terminalId: context.terminalId,
391 terminalLabel: context.terminalLabel,
392 lineStart: context.lineStart,
393 lineEnd: context.lineEnd,
394 text: clampContextText(
395 normalizeTerminalContextText(context.text),
396 COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS,
397 ),
398 };
399 }
400
401 export function reviewCommentContextRecord(
402 comment: ReviewCommentContext,
403 ): ReviewCommentContextRecord {
404 return {
405 version: 1,
406 contextId: reviewCommentContextId(comment.id),
407 kind: "review-comment",
408 label: sanitizeComposerContextLabel(reviewCommentContextLabel(comment), "review-comment"),
409 sectionId: comment.sectionId,
410 sectionTitle: comment.sectionTitle,
411 filePath: comment.filePath,
412 startIndex: comment.startIndex,
413 endIndex: comment.endIndex,
414 rangeLabel: comment.rangeLabel,
415 text: clampContextText(comment.text, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
416 diff: clampContextText(comment.diff, COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
417 ...(comment.fenceLanguage !== undefined ? { fenceLanguage: comment.fenceLanguage } : {}),
418 ...(comment.pullRequest !== undefined ? { pullRequest: comment.pullRequest } : {}),
419 };
420 }
421
422 // Stored in the record and read by the agent, so it stays English.
423 function previewAnnotationTargetSummary(annotation: PreviewAnnotationPayload): string {
424 const parts: string[] = [];
425 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
426 if (annotation.elements.length > 0)
427 parts.push(plural(annotation.elements.length, "selected element"));
428 if (annotation.regions.length > 0) parts.push(plural(annotation.regions.length, "marked region"));
429 if (annotation.strokes.length > 0) parts.push(plural(annotation.strokes.length, "drawing"));
430 return parts.join(", ");
431 }
432
433 export function previewAnnotationContextRecord(
434 annotation: PreviewAnnotationPayload,
435 options?: { screenshotContextId?: string | undefined },
436 ): PreviewAnnotationContextRecord {
437 const targets = annotation.elements.flatMap((target) => {
438 const element = normalizeElementContextSelection(target.element);
439 return element ? [{ id: target.id, element }] : [];
440 });
441 return {
442 version: 1,
443 contextId: previewAnnotationContextId(annotation.id),
444 kind: "preview-annotation",
445 label: sanitizeComposerContextLabel(
446 previewAnnotationContextLabel(annotation),
447 "preview-annotation",
448 ),
449 annotationId: annotation.id,
450 pageUrl: annotation.pageUrl,
451 pageTitle: annotation.pageTitle,
452 comment: clampContextText(
453 annotation.comment.trim(),
454 COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS,
455 ),
456 targetSummary: previewAnnotationTargetSummary(annotation),
457 styleChanges: annotation.styleChanges.map(
458 (change) => `${change.property}: ${change.previousValue || "(unset)"} → ${change.value}`,
459 ),
460 ...(targets.length > 0
461 ? {
462 elements: targets.map((target) => target.element),
463 elementIds: targets.map((target) => target.id),
464 }
465 : {}),
466 styleChangeDetails: annotation.styleChanges.map((change) => ({ ...change })),
467 ...(annotation.regions.length > 0 ? { regionCount: annotation.regions.length } : {}),
468 ...(annotation.strokes.length > 0 ? { strokeCount: annotation.strokes.length } : {}),
469 ...(options?.screenshotContextId !== undefined
470 ? { screenshotContextId: toKindScopedComposerContextId("image", options.screenshotContextId) }
471 : {}),
472 };
473 }
474
475 export function imageContextReference(image: ComposerImageAttachment): ComposerContextReference {
476 return {
477 kind: "image",
478 contextId: toKindScopedComposerContextId("image", image.id),
479 label: image.name,
480 };
481 }
482
483 export function fileContextReference(file: ComposerFileAttachment): ComposerContextReference {
484 return {
485 kind: "file",
486 contextId: toKindScopedComposerContextId("file", file.id),
487 label: file.name,
488 };
489 }
490
491 export interface BoundComposerAttachment {
492 attachment: ComposerImageAttachment | ComposerFileAttachment;
493 attachmentId: string;
494 }
495
496 /** Returns null until the attachment has a server id. */
497 export function uploadedAttachmentContextRecord(
498 attachment: ComposerImageAttachment | ComposerFileAttachment,
499 upload: AttachmentUploadState | undefined,
500 ): ImageContextRecord | FileContextRecord | null {
501 const attachmentId =
502 attachment.type === "file" && attachment.uploadedAttachmentId !== undefined
503 ? attachment.uploadedAttachmentId
504 : upload?.status === "ready"
505 ? upload.attachmentId
506 : undefined;
507 return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId });
508 }
509
510 export function attachmentContextRecord(
511 bound: BoundComposerAttachment,
512 ): ImageContextRecord | FileContextRecord {
513 const { attachment, attachmentId } = bound;
514 const base = {
515 version: 1 as const,
516 contextId: toKindScopedComposerContextId(attachment.type, attachment.id),
517 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
518 attachmentId,
519 name: attachment.name,
520 mimeType: attachment.mimeType,
521 sizeBytes: attachment.sizeBytes,
522 };
523 return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" };
524 }
525
526 export function buildMessageContext(input: {
527 terminalContexts: ReadonlyArray<TerminalContextDraft>;
528 reviewComments: ReadonlyArray<ReviewCommentContext>;
529 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
530 threadContexts?: ReadonlyArray<ThreadContextRecord>;
531 environmentContexts?: ReadonlyArray<EnvironmentContextRecord>;
532 replyTo?: ResponseContextRecord | null;
533 attachments?: ReadonlyArray<BoundComposerAttachment>;
534 }): OrchestrationMessageContext | undefined {
535 const screenshotAttachmentIds = new Set(
536 (input.attachments ?? []).flatMap(({ attachment }) =>
537 attachment.type === "image" ? [attachment.id] : [],
538 ),
539 );
540 const records: ComposerContextRecord[] = [
541 ...input.terminalContexts.map(terminalContextRecord),
542 ...input.reviewComments.map(reviewCommentContextRecord),
543 ...(input.threadContexts ?? []),
544 ...(input.environmentContexts ?? []),
545 ...(input.replyTo ? [input.replyTo] : []),
546 ...input.previewAnnotations.map((annotation) =>
547 previewAnnotationContextRecord(annotation, {
548 screenshotContextId: screenshotAttachmentIds.has(annotation.id) ? annotation.id : undefined,
549 }),
550 ),
551 ...(input.attachments ?? []).map(attachmentContextRecord),
552 ];
553 return records.length === 0 ? undefined : { version: 1, records };
554 }
555
556 export function asKnownContextRecord(
557 record: ComposerContextRecord | undefined,
558 ): KnownComposerContextRecord | undefined {
559 if (!record || "payload" in record) return undefined;
560 return record;
561 }
562
563 export function composerContextImportLookupIds(
564 record: KnownComposerContextRecord,
565 ): ReadonlyArray<ComposerContextId> {
566 const destinationId = toKindScopedComposerContextId(
567 record.kind,
568 producerIdFromComposerContextId(record.kind, record.contextId),
569 );
570 return destinationId === record.contextId
571 ? [record.contextId]
572 : [destinationId, record.contextId];
573 }
574
575 export interface ResolvedUserMessageContext {
576 text: string;
577 records: ReadonlyArray<ComposerContextRecord>;
578 recordsById: ReadonlyMap<string, ComposerContextRecord>;
579 }
580
581 export function selectedMessageContextFragment(input: {
582 readonly markdown: string;
583 readonly records: ReadonlyArray<ComposerContextRecord>;
584 readonly environmentId: EnvironmentId;
585 readonly threadId?: ThreadId;
586 readonly messageId: MessageId;
587 }): string | null {
588 const selectedIds = new Set(
589 collectComposerContextReferences(input.markdown).map((occurrence) => occurrence.contextId),
590 );
591 const records = input.records.filter((record) => selectedIds.has(record.contextId));
592 if (records.length === 0) return null;
593 return encodeComposerContextFragment({
594 version: 1,
595 source: {
596 environmentId: input.environmentId,
597 ...(input.threadId ? { threadId: input.threadId } : {}),
598 messageId: input.messageId,
599 },
600 records,
601 });
602 }
603
604 export function resolveUserMessageContext(message: {
605 text: string;
606 context?: OrchestrationMessageContext | undefined;
607 }): ResolvedUserMessageContext {
608 const resolved = message.context
609 ? { text: message.text, records: message.context.records }
610 : upgradeLegacyContextMessage(message.text);
611 return {
612 text: resolved.text,
613 records: resolved.records,
614 recordsById: new Map(resolved.records.map((record) => [record.contextId, record])),
615 };
616 }
617
618 export function terminalContextDraftFromRecord(
619 record: TerminalContextRecord,
620 threadId: ThreadId,
621 ): TerminalContextDraft {
622 return {
623 id: producerIdFromComposerContextId("terminal", record.contextId),
624 threadId,
625 createdAt: new Date().toISOString(),
626 terminalId: record.terminalId,
627 terminalLabel: record.terminalLabel,
628 lineStart: record.lineStart,
629 lineEnd: record.lineEnd,
630 text: record.text,
631 };
632 }
633
634 export function reviewCommentFromRecord(record: ReviewCommentContextRecord): ReviewCommentContext {
635 return {
636 id: producerIdFromComposerContextId("review-comment", record.contextId),
637 sectionId: record.sectionId,
638 sectionTitle: record.sectionTitle,
639 filePath: record.filePath,
640 startIndex: record.startIndex,
641 endIndex: record.endIndex,
642 rangeLabel: record.rangeLabel,
643 text: record.text,
644 diff: record.diff,
645 ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),
646 ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
647 };
648 }
649
650 export function previewAnnotationFromRecord(
651 record: PreviewAnnotationContextRecord,
652 ): PreviewAnnotationPayload {
653 return {
654 id:
655 record.annotationId ||
656 producerIdFromComposerContextId("preview-annotation", record.contextId),
657 pageUrl: record.pageUrl,
658 pageTitle: record.pageTitle,
659 comment: record.comment,
660 elements: (record.elements ?? []).map((element, index) => ({
661 id: record.elementIds?.[index] ?? `${record.contextId}-element-${index + 1}`,
662 rect: { x: 0, y: 0, width: 0, height: 0 },
663 element: { ...element, stack: [], pickedAt: new Date().toISOString() },
664 })),
665 regions: Array.from({ length: record.regionCount ?? 0 }, (_unused, index) => ({
666 id: `${record.contextId}-region-${index + 1}`,
667 rect: { x: 0, y: 0, width: 0, height: 0 },
668 })),
669 strokes: Array.from({ length: record.strokeCount ?? 0 }, (_unused, index) => ({
670 id: `${record.contextId}-stroke-${index + 1}`,
671 color: "",
672 width: 0,
673 points: [],
674 bounds: { x: 0, y: 0, width: 0, height: 0 },
675 })),
676 styleChanges:
677 record.styleChangeDetails ??
678 record.styleChanges.flatMap((change) => {
679 const match = /^(.+?): ([\s\S]*?) → ([\s\S]*)$/.exec(change);
680 if (!match) return [];
681 return [
682 {
683 targetId: record.elementIds?.[0] ?? `${record.contextId}-element-1`,
684 selector: null,
685 property: match[1]!,
686 previousValue: match[2] === "(unset)" ? "" : match[2]!,
687 value: match[3]!,
688 },
689 ];
690 }),
691 screenshot: null,
692 createdAt: new Date().toISOString(),
693 };
694 }
695
696 /** Labels are display-only; folded ids can collide, so paste deduplication compares payloads. */
697 export function isSameComposerContextPayload(
698 left: ComposerContextRecord,
699 right: ComposerContextRecord,
700 ): boolean {
701 if (left.kind !== right.kind) return false;
702 const stableKey = (record: ComposerContextRecord) => {
703 const { label: _label, contextId: _contextId, ...rest } = record;
704 const sortDeep = (value: unknown): unknown => {
705 if (Array.isArray(value)) return value.map(sortDeep);
706 if (value === null || typeof value !== "object") return value;
707 return Object.fromEntries(
708 Object.entries(value)
709 .toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
710 .map(([key, nested]) => [key, sortDeep(nested)]),
711 );
712 };
713 return JSON.stringify(sortDeep(rest));
714 };
715 return stableKey(left) === stableKey(right);
716 }