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

ThreadFeed.tsx

989 lines31.2 KB

1import * as Clipboard from "expo-clipboard";
2import * as Haptics from "expo-haptics";
3import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
4import { type LegendListRef } from "@legendapp/list/react-native";
5import type { ThreadId } from "@t3tools/contracts";
6import { SymbolView } from "expo-symbols";
7import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
8import {
9 Markdown,
10 type CustomRenderers,
11 type NodeStyleOverrides,
12 type PartialMarkdownTheme,
13} from "react-native-nitro-markdown";
14import {
15 Image,
16 Pressable,
17 ScrollView,
18 StyleSheet,
19 Text as NativeText,
20 type ColorValue,
21 useColorScheme,
22 useWindowDimensions,
23 View,
24} from "react-native";
25import { TouchableOpacity } from "react-native-gesture-handler";
26import ImageViewing from "react-native-image-viewing";
27import { useSafeAreaInsets } from "react-native-safe-area-context";
28import { useThemeColor } from "../../lib/useThemeColor";
29​
30import { AppText as Text } from "../../components/AppText";
31import { EmptyState } from "../../components/EmptyState";
32import {
33 parseReviewCommentMessageSegments,
34 type ReviewInlineComment,
35} from "../review/reviewCommentSelection";
36import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
37import {
38 buildNativeReviewDiffData,
39 createNativeReviewDiffTheme,
40 NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
41 NATIVE_REVIEW_DIFF_ROW_HEIGHT,
42 NATIVE_REVIEW_DIFF_STYLE,
43} from "../review/nativeReviewDiffAdapter";
44import { buildReviewParsedDiff } from "../review/reviewModel";
45import { cn } from "../../lib/cn";
46import type { MobileLayoutVariant } from "../../lib/mobileLayout";
47import type { ThreadFeedEntry } from "../../lib/threadActivity";
48import { relativeTime } from "../../lib/time";
49import { messageImageUrl } from "./threadPresentation";
50​
51export interface ThreadFeedProps {
52 readonly threadId: ThreadId;
53 readonly feed: ReadonlyArray<ThreadFeedEntry>;
54 readonly httpBaseUrl: string | null;
55 readonly bearerToken: string | null;
56 readonly agentLabel: string;
57 readonly contentBottomInset?: number;
58 readonly refreshing?: boolean;
59 readonly onRefresh?: () => void;
60 readonly layoutVariant?: MobileLayoutVariant;
61 readonly composerExpanded?: boolean;
63​
64function stripShellWrapper(value: string): string {
65 const trimmed = value.trim();
66 const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
67 return (match?.[1] ?? trimmed).trim();
69​
70function compactActivityDetail(detail: string | null): string | null {
71 if (!detail) {
72 return null;
73 }
74​
75 const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
76 return cleaned.length > 0 ? cleaned : null;
78​
79function buildActivityRows(
80 activities: ReadonlyArray<{
81 readonly id: string;
82 readonly createdAt: string;
83 readonly summary: string;
84 readonly detail: string | null;
85 readonly status: string | null;
86 }>,
87) {
88 return activities.map<{
89 id: string;
90 createdAt: string;
91 summary: string;
92 detail: string | null;
93 status: string | null;
94 }>((activity) => ({
95 id: activity.id,
96 createdAt: activity.createdAt,
97 summary: activity.summary,
98 detail: compactActivityDetail(activity.detail),
99 status: activity.status,
100 }));
102​
103const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
104​
105function toMarkdownThemeColor(value: ColorValue): string {
106 return value as string;
108​
109interface MarkdownStyleSets {
110 readonly user: MarkdownStyleSet;
111 readonly assistant: MarkdownStyleSet;
113​
114interface MarkdownStyleSet {
115 readonly theme: PartialMarkdownTheme;
116 readonly styles: NodeStyleOverrides;
117 readonly renderers: CustomRenderers;
119​
120interface ReviewCommentColors {
121 readonly background: ColorValue;
122 readonly border: ColorValue;
123 readonly mutedBackground: ColorValue;
124 readonly text: ColorValue;
125 readonly mutedText: ColorValue;
126 readonly codeBackground: ColorValue;
128​
129function useReviewCommentColors(): ReviewCommentColors {
130 const colorScheme = useColorScheme();
131 const isDark = colorScheme === "dark";
132 const background = isDark ? "#151515" : "#ffffff";
133 const border = isDark ? "#2a2a2a" : "#d7d7d7";
134 const mutedBackground = isDark ? "#242424" : "#f2f2f2";
135 const text = isDark ? "#f3f3f3" : "#111111";
136 const mutedText = isDark ? "#8f8f8f" : "#666666";
137 const codeBackground = isDark ? "#0f0f0f" : "#ffffff";
138​
139 return useMemo(
140 () => ({
141 background,
142 border,
143 mutedBackground,
144 text,
145 mutedText,
146 codeBackground,
147 }),
148 [background, border, codeBackground, mutedBackground, mutedText, text],
149 );
151​
152function useMarkdownStyles(): MarkdownStyleSets {
153 const bodyColor = useThemeColor("--color-md-body");
154 const strongColor = useThemeColor("--color-md-strong");
155 const linkColor = useThemeColor("--color-md-link");
156 const blockquoteBg = useThemeColor("--color-md-blockquote-bg");
157 const blockquoteBorder = useThemeColor("--color-md-blockquote-border");
158 const codeBg = useThemeColor("--color-md-code-bg");
159 const codeText = useThemeColor("--color-md-code-text");
160 const hrColor = useThemeColor("--color-md-hr");
161 const userBodyColor = useThemeColor("--color-user-bubble-foreground");
162 const userCodeBg = useThemeColor("--color-md-user-code-bg");
163 const userCodeText = useThemeColor("--color-md-user-code-text");
164 const userFenceBg = useThemeColor("--color-md-user-fence-bg");
165 const userFenceText = useThemeColor("--color-md-user-fence-text");
166​
167 return useMemo(() => {
168 const markdownBodyColor = toMarkdownThemeColor(bodyColor);
169 const markdownStrongColor = toMarkdownThemeColor(strongColor);
170 const markdownLinkColor = toMarkdownThemeColor(linkColor);
171 const markdownBlockquoteBg = toMarkdownThemeColor(blockquoteBg);
172 const markdownBlockquoteBorder = toMarkdownThemeColor(blockquoteBorder);
173 const markdownCodeBg = toMarkdownThemeColor(codeBg);
174 const markdownCodeText = toMarkdownThemeColor(codeText);
175 const markdownHrColor = toMarkdownThemeColor(hrColor);
176 const markdownUserBodyColor = toMarkdownThemeColor(userBodyColor);
177 const markdownUserCodeBg = toMarkdownThemeColor(userCodeBg);
178 const markdownUserCodeText = toMarkdownThemeColor(userCodeText);
179 const markdownUserFenceBg = toMarkdownThemeColor(userFenceBg);
180 const markdownUserFenceText = toMarkdownThemeColor(userFenceText);
181​
182 const baseTheme: PartialMarkdownTheme = {
183 colors: {
184 text: markdownBodyColor,
185 heading: markdownStrongColor,
186 link: markdownLinkColor,
187 blockquote: markdownBlockquoteBorder,
188 border: markdownHrColor,
189 surfaceLight: markdownBlockquoteBg,
190 accent: markdownLinkColor,
191 tableBorder: markdownHrColor,
192 tableHeader: markdownBlockquoteBg,
193 tableHeaderText: markdownStrongColor,
194 tableRowOdd: "transparent",
195 tableRowEven: "transparent",
196 },
197 spacing: {
198 xs: 4,
199 s: 4,
200 m: 8,
201 l: 8,
202 xl: 16,
203 },
204 fontSizes: {
205 s: 13,
206 m: 15,
207 h1: 22,
208 h2: 19,
209 h3: 17,
210 h4: 15,
211 h5: 15,
212 h6: 15,
213 },
214 fontFamilies: {
215 regular: "DMSans_400Regular",
216 heading: "DMSans_700Bold",
217 mono: "ui-monospace",
218 },
219 headingWeight: "700",
220 borderRadius: {
221 s: 4,
222 m: 8,
223 l: 12,
224 },
225 showCodeLanguage: false,
226 };
227​
228 const baseStyles: NodeStyleOverrides = {
229 document: { flexShrink: 1 },
230 paragraph: { marginTop: 0, marginBottom: 8 },
231 list: { marginTop: 4, marginBottom: 4 },
232 list_item: { marginTop: 0, marginBottom: 4 },
233 task_list_item: { marginTop: 0, marginBottom: 4 },
234 text: { lineHeight: 22 },
235 bold: {
236 fontWeight: "700",
237 color: markdownStrongColor,
238 fontFamily: "DMSans_700Bold",
239 },
240 italic: { fontStyle: "italic" },
241 link: {
242 color: markdownLinkColor,
243 textDecorationLine: "underline" as const,
244 },
245 blockquote: {
246 borderLeftWidth: 3,
247 borderLeftColor: markdownBlockquoteBorder,
248 backgroundColor: markdownBlockquoteBg,
249 paddingLeft: 12,
250 paddingVertical: 6,
251 marginLeft: 0,
252 marginVertical: 4,
253 borderRadius: 4,
254 },
255 heading: {
256 fontFamily: "DMSans_700Bold",
257 color: markdownStrongColor,
258 marginTop: 12,
259 marginBottom: 6,
260 },
261 horizontal_rule: {
262 backgroundColor: markdownHrColor,
263 height: 1,
264 marginVertical: 12,
265 },
266 };
267​
268 const createCodeRenderers = (
269 inlineBackgroundColor: string,
270 inlineTextColor: string,
271 blockBackgroundColor: string,
272 blockTextColor: string,
273 ): CustomRenderers => ({
274 code_inline: ({ content }) => (
275 <NativeText
276 style={{
277 backgroundColor: inlineBackgroundColor,
278 color: inlineTextColor,
279 borderRadius: 5,
280 paddingHorizontal: 5,
281 paddingVertical: 1,
282 fontFamily: "ui-monospace",
283 fontSize: 13,
284 }}
285 >
286 {content}
287 </NativeText>
288 ),
289 code_block: ({ content }) => (
290 <View
291 style={{
292 backgroundColor: blockBackgroundColor,
293 borderRadius: 12,
294 padding: 12,
295 marginVertical: 8,
296 }}
297 >
298 <ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
299 <NativeText
300 selectable
301 style={{
302 color: blockTextColor,
303 fontFamily: "ui-monospace",
304 fontSize: 13,
305 lineHeight: 19,
306 }}
307 >
308 {content}
309 </NativeText>
310 </ScrollView>
311 </View>
312 ),
313 });
314​
315 const userTheme: PartialMarkdownTheme = {
316 ...baseTheme,
317 colors: {
318 ...baseTheme.colors,
319 text: markdownUserBodyColor,
320 heading: markdownUserBodyColor,
321 link: markdownUserBodyColor,
322 code: markdownUserCodeText,
323 codeBackground: markdownUserCodeBg,
324 border: markdownUserFenceBg,
325 },
326 };
327 const userStyles: NodeStyleOverrides = {
328 ...baseStyles,
329 paragraph: { marginTop: 0, marginBottom: 0 },
330 bold: {
331 fontWeight: "700",
332 color: markdownUserBodyColor,
333 fontFamily: "DMSans_700Bold",
334 },
335 heading: {
336 ...baseStyles.heading,
337 color: markdownUserBodyColor,
338 },
339 link: {
340 color: markdownUserBodyColor,
341 textDecorationLine: "underline" as const,
342 },
343 };
344​
345 const assistantTheme: PartialMarkdownTheme = {
346 ...baseTheme,
347 colors: {
348 ...baseTheme.colors,
349 code: markdownCodeText,
350 codeBackground: markdownCodeBg,
351 border: markdownCodeBg,
352 },
353 };
354 const assistantStyles: NodeStyleOverrides = {
355 ...baseStyles,
356 };
357​
358 return {
359 user: {
360 theme: userTheme,
361 styles: userStyles,
362 renderers: createCodeRenderers(
363 markdownUserCodeBg,
364 markdownUserCodeText,
365 markdownUserFenceBg,
366 markdownUserFenceText,
367 ),
368 },
369 assistant: {
370 theme: assistantTheme,
371 styles: assistantStyles,
372 renderers: createCodeRenderers(
373 markdownCodeBg,
374 markdownCodeText,
375 markdownCodeBg,
376 markdownCodeText,
377 ),
378 },
379 };
380 }, [
381 blockquoteBg,
382 blockquoteBorder,
383 bodyColor,
384 codeBg,
385 codeText,
386 hrColor,
387 linkColor,
388 strongColor,
389 userBodyColor,
390 userCodeBg,
391 userCodeText,
392 userFenceBg,
393 userFenceText,
394 ]);
396​
397function renderFeedEntry(
398 info: { item: ThreadFeedEntry; index: number },
399 props: Pick<ThreadFeedProps, "bearerToken" | "httpBaseUrl"> & {
400 readonly copiedRowId: string | null;
401 readonly expandedWorkGroups: Record<string, boolean>;
402 readonly onCopyWorkRow: (rowId: string, value: string) => void;
403 readonly onToggleWorkGroup: (groupId: string) => void;
404 readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
405 readonly iconSubtleColor: string | import("react-native").ColorValue;
406 readonly userBubbleColor: string | import("react-native").ColorValue;
407 readonly markdownStyles: MarkdownStyleSets;
408 readonly reviewCommentColors: ReviewCommentColors;
409 readonly reviewCommentBubbleWidth: number;
410 },
411) {
412 const entry = info.item;
413 const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
414​
415 if (entry.type === "message") {
416 const { message } = entry;
417 const isUser = message.role === "user";
418 const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
419 const timestampLabel = `${relativeTime(message.createdAt)}${message.streaming ? " • live" : ""}`;
420 const attachments = message.attachments ?? [];
421 const hasReviewCommentContext = message.text.includes("<review_comment");
422​
423 if (isUser) {
424 return (
425 <View className="mb-5 items-end">
426 <View
427 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5"
428 style={{
429 backgroundColor: userBubbleColor,
430 ...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
431 }}
432 >
433 {message.text.trim().length > 0 ? (
434 <UserMessageContent
435 text={message.text}
436 markdownStyles={styles}
437 reviewCommentColors={props.reviewCommentColors}
438 />
439 ) : null}
440 {attachments.map((attachment) => {
441 const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
442 if (!uri) {
443 return null;
444 }
445 const headers = props.bearerToken
446 ? { Authorization: `Bearer ${props.bearerToken}` }
447 : undefined;
448​
449 return (
450 <TouchableOpacity
451 key={attachment.id}
452 activeOpacity={0.7}
453 onPress={() => props.onPressImage(uri, headers)}
454 >
455 <Image
456 source={{ uri, ...(headers ? { headers } : {}) }}
457 className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
458 resizeMode="cover"
459 />
460 </TouchableOpacity>
461 );
462 })}
463 </View>
464 <Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
465 {timestampLabel}
466 </Text>
467 </View>
468 );
469 }
470​
471 // Skip empty assistant messages (no text, no attachments) — they would
472 // render as an orphaned timestamp and break adjacent activity-group merging.
473 if (message.text.trim().length === 0 && attachments.length === 0) {
474 return null;
475 }
476​
477 return (
478 <View className="mb-5 px-1">
479 {message.text.trim().length > 0 ? (
480 <Markdown
481 options={{ gfm: true }}
482 renderers={styles.renderers}
483 styles={styles.styles}
484 theme={styles.theme}
485 >
486 {message.text}
487 </Markdown>
488 ) : null}
489 {attachments.map((attachment) => {
490 const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
491 if (!uri) {
492 return null;
493 }
494 const headers = props.bearerToken
495 ? { Authorization: `Bearer ${props.bearerToken}` }
496 : undefined;
497​
498 return (
499 <TouchableOpacity
500 key={attachment.id}
501 activeOpacity={0.7}
502 className="mt-1.5"
503 onPress={() => props.onPressImage(uri, headers)}
504 >
505 <Image
506 source={{ uri, ...(headers ? { headers } : {}) }}
507 className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
508 resizeMode="cover"
509 />
510 </TouchableOpacity>
511 );
512 })}
513 <Text className="mt-1.5 font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
514 {timestampLabel}
515 </Text>
516 </View>
517 );
518 }
519​
520 if (entry.type === "queued-message") {
521 return (
522 <View className="mb-5 items-end">
523 <View
524 className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
525 style={{ backgroundColor: userBubbleColor }}
526 >
527 <Text className="font-sans text-[15px] leading-[22px] text-white">
528 {entry.queuedMessage.text}
529 </Text>
530 {entry.queuedMessage.attachments.length > 0 ? (
531 <Text className="font-t3-medium text-xs text-white/75">
532 {entry.queuedMessage.attachments.length} image
533 {entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
534 </Text>
535 ) : null}
536 </View>
537 <Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
538 {entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
539 </Text>
540 </View>
541 );
542 }
543​
544 const rows = buildActivityRows(entry.activities);
545 const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
546 const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
547 const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
548 const hiddenCount = rows.length - visibleRows.length;
549 const showHeader = hasOverflow;
550​
551 return (
552 <View className="mb-3 rounded-[20px] border border-neutral-200/80 bg-neutral-50/85 px-3 py-2 dark:border-white/[0.06] dark:bg-white/[0.025]">
553 {showHeader ? (
554 <View className="mb-1.5 flex-row items-center justify-between gap-3 px-0.5">
555 <Text className="font-t3-bold text-[10px] uppercase tracking-[0.8px] text-neutral-500 dark:text-neutral-500">
556 Tool calls ({rows.length})
557 </Text>
558 <Pressable onPress={() => props.onToggleWorkGroup(entry.id)}>
559 <Text className="font-t3-medium text-[10px] uppercase tracking-[0.8px] text-neutral-500 dark:text-neutral-500">
560 {isExpanded ? "Show less" : `Show ${hiddenCount} more`}
561 </Text>
562 </Pressable>
563 </View>
564 ) : null}
565 {visibleRows.map((row, index) => (
566 <View
567 key={row.id}
568 className={cn(
569 "flex-row items-center gap-2 rounded-lg px-1 py-1",
570 index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
571 )}
572 >
573 <View className="items-center justify-center pt-0.5">
574 <SymbolView name="terminal" size={13} tintColor={iconSubtleColor} type="monochrome" />
575 </View>
576 <ScrollView
577 horizontal
578 nestedScrollEnabled
579 directionalLockEnabled
580 showsHorizontalScrollIndicator={false}
581 bounces={false}
582 className="flex-1"
583 contentContainerStyle={{ paddingRight: 12 }}
584 style={{ flex: 1 }}
585 >
586 <Text
587 className="text-[12px] leading-[18px] text-neutral-600 dark:text-neutral-400"
588 onLongPress={() => {
589 const copyValue = row.detail ?? row.summary;
590 props.onCopyWorkRow(row.id, copyValue);
591 }}
592 style={{
593 fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, monospace",
594 }}
595 >
596 {row.detail ? `${row.summary} - ${row.detail}` : row.summary}
597 </Text>
598 </ScrollView>
599 {props.copiedRowId === row.id ? (
600 <Text className="shrink-0 font-t3-medium text-[10px] uppercase tracking-[0.8px] text-emerald-600 dark:text-emerald-400">
601 Copied
602 </Text>
603 ) : null}
604 </View>
605 ))}
606 </View>
607 );
609​
610function UserMessageContent(props: {
611 readonly text: string;
612 readonly markdownStyles: MarkdownStyleSet;
613 readonly reviewCommentColors: ReviewCommentColors;
614}) {
615 const segments = parseReviewCommentMessageSegments(props.text);
616 const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
617 if (!hasReviewComment) {
618 return (
619 <Markdown
620 options={{ gfm: true }}
621 renderers={props.markdownStyles.renderers}
622 styles={props.markdownStyles.styles}
623 theme={props.markdownStyles.theme}
624 >
625 {props.text}
626 </Markdown>
627 );
628 }
629​
630 return (
631 <View className="w-full gap-2">
632 {segments.map((segment) => {
633 if (segment.kind === "review-comment") {
634 return (
635 <ReviewCommentCard
636 key={segment.comment.id}
637 comment={segment.comment}
638 colors={props.reviewCommentColors}
639 />
640 );
641 }
642​
643 const text = segment.text.trim();
644 if (text.length === 0) {
645 return null;
646 }
647​
648 return (
649 <Markdown
650 key={segment.id}
651 options={{ gfm: true }}
652 renderers={props.markdownStyles.renderers}
653 styles={props.markdownStyles.styles}
654 theme={props.markdownStyles.theme}
655 >
656 {text}
657 </Markdown>
658 );
659 })}
660 </View>
661 );
663​
664const ReviewCommentCard = memo(function ReviewCommentCard(props: {
665 readonly comment: ReviewInlineComment;
666 readonly colors: ReviewCommentColors;
667}) {
668 const colorScheme = useColorScheme();
669 const appearanceScheme = colorScheme === "light" ? "light" : "dark";
670 const NativeReviewDiffView = resolveNativeReviewDiffView();
671 const patch = useMemo(() => buildReviewCommentPatch(props.comment), [props.comment]);
672 const parsedDiff = useMemo(
673 () => buildReviewParsedDiff(patch, `thread-review-comment:${props.comment.id}`),
674 [patch, props.comment.id],
675 );
676 const nativeReviewDiffData = useMemo(() => buildNativeReviewDiffData(parsedDiff), [parsedDiff]);
677 const compactNativeRows = useMemo(
678 () => nativeReviewDiffData.rows.filter((row) => row.kind !== "file"),
679 [nativeReviewDiffData.rows],
680 );
681 const nativeReviewDiffTheme = useMemo(
682 () => createNativeReviewDiffTheme(appearanceScheme),
683 [appearanceScheme],
684 );
685 const nativeRowsJson = useMemo(() => JSON.stringify(compactNativeRows), [compactNativeRows]);
686 const nativeThemeJson = useMemo(
687 () => JSON.stringify(nativeReviewDiffTheme),
688 [nativeReviewDiffTheme],
689 );
690 const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
691 const nativeDiffHeight = useMemo(
692 () =>
693 Math.min(
694 360,
695 Math.max(
696 112,
697 compactNativeRows.length * NATIVE_REVIEW_DIFF_ROW_HEIGHT +
698 NATIVE_REVIEW_DIFF_STYLE.fileHeaderVerticalMargin,
699 ),
700 ),
701 [compactNativeRows.length],
702 );
703 const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0;
704​
705 return (
706 <View
707 className="w-full overflow-hidden rounded-[16px] border"
708 style={{
709 backgroundColor: props.colors.background,
710 borderColor: props.colors.border,
711 borderCurve: "continuous",
712 }}
713 >
714 <View
715 className="flex-row items-center gap-2 border-b px-3 py-2"
716 style={{ borderColor: props.colors.border }}
717 >
718 <View
719 className="size-6 items-center justify-center rounded-[7px]"
720 style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
721 >
722 <SymbolView
723 name="doc.text"
724 size={13}
725 tintColor={props.colors.mutedText}
726 type="monochrome"
727 />
728 </View>
729 <View className="min-w-0 flex-1">
730 <Text
731 className="font-mono text-[12px] leading-[16px]"
732 numberOfLines={1}
733 style={{ color: props.colors.text }}
734 >
735 {compactFileName(props.comment.filePath)}
736 </Text>
737 </View>
738 </View>
739 {shouldRenderNativeDiff ? (
740 <View
741 className="border-t"
742 collapsable={false}
743 style={{
744 backgroundColor: nativeReviewDiffTheme.background,
745 borderColor: props.colors.border,
746 height: nativeDiffHeight,
747 }}
748 >
749 <NativeReviewDiffView
750 collapsable={false}
751 style={StyleSheet.absoluteFill}
752 appearanceScheme={appearanceScheme}
753 contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
754 rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
755 rowsJson={nativeRowsJson}
756 styleJson={nativeStyleJson}
757 themeJson={nativeThemeJson}
758 />
759 </View>
760 ) : props.comment.diff.trim().length > 0 ? (
761 <ScrollView
762 horizontal
763 nestedScrollEnabled
764 directionalLockEnabled
765 showsHorizontalScrollIndicator={false}
766 bounces={false}
767 className="border-t"
768 style={{ backgroundColor: props.colors.codeBackground, borderColor: props.colors.border }}
769 contentContainerStyle={{ padding: 10 }}
770 >
771 <NativeText
772 selectable
773 style={{
774 color: props.colors.text,
775 fontFamily: "ui-monospace",
776 fontSize: 12,
777 lineHeight: 18,
778 }}
779 >
780 {props.comment.diff.trim()}
781 </NativeText>
782 </ScrollView>
783 ) : null}
784 {props.comment.text.length > 0 ? (
785 <View className="border-t px-3 py-3" style={{ borderColor: props.colors.border }}>
786 <Text
787 selectable
788 className="text-[15px] leading-[21px]"
789 style={{ color: props.colors.text }}
790 >
791 {props.comment.text}
792 </Text>
793 </View>
794 ) : null}
795 </View>
796 );
797});
798​
799function buildReviewCommentPatch(comment: ReviewInlineComment): string {
800 const diff = comment.diff.trim();
801 if (!diff) {
802 return "";
803 }
804​
805 if (diff.startsWith("diff --git ")) {
806 return diff;
807 }
808​
809 const normalizedPath = comment.filePath.replaceAll("\\", "/");
810 return [
811 `diff --git a/${normalizedPath} b/${normalizedPath}`,
812 `--- a/${normalizedPath}`,
813 `+++ b/${normalizedPath}`,
814 diff,
815 ].join("\n");
817​
818function compactFileName(filePath: string): string {
819 const normalized = filePath.replaceAll("\\", "/");
820 const lastSlashIndex = normalized.lastIndexOf("/");
821 return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
823​
824const IOS_NAV_BAR_HEIGHT = 44;
825​
826export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
827 const listRef = useRef<LegendListRef>(null);
828 const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
829 const { width: viewportWidth } = useWindowDimensions();
830 const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
831 const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
832 const [expandedImage, setExpandedImage] = useState<{
833 uri: string;
834 headers?: Record<string, string>;
835 } | null>(null);
836 const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
837 const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
838 const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
839 const insets = useSafeAreaInsets();
840 const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
841 const bottomContentInset = props.contentBottomInset ?? 18;
842​
843 const iconSubtleColor = useThemeColor("--color-icon-subtle");
844 const userBubbleColor = useThemeColor("--color-user-bubble");
845 const markdownStyles = useMarkdownStyles();
846 const reviewCommentColors = useReviewCommentColors();
847​
848 useEffect(() => {
849 setCopiedRowId(null);
850 setExpandedWorkGroups({});
851 }, [props.threadId]);
852​
853 useEffect(() => {
854 return () => {
855 if (copyFeedbackTimeoutRef.current) {
856 clearTimeout(copyFeedbackTimeoutRef.current);
857 }
858 };
859 }, []);
860​
861 const onCopyWorkRow = useCallback((rowId: string, value: string) => {
862 void Clipboard.setStringAsync(value);
863 void Haptics.selectionAsync();
864 setCopiedRowId(rowId);
865 if (copyFeedbackTimeoutRef.current) {
866 clearTimeout(copyFeedbackTimeoutRef.current);
867 }
868 copyFeedbackTimeoutRef.current = setTimeout(() => {
869 setCopiedRowId((current) => (current === rowId ? null : current));
870 copyFeedbackTimeoutRef.current = null;
871 }, 1200);
872 }, []);
873​
874 const onToggleWorkGroup = useCallback((groupId: string) => {
875 setExpandedWorkGroups((current) => ({
876 ...current,
877 [groupId]: !(current[groupId] ?? false),
878 }));
879 }, []);
880​
881 const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
882 setExpandedImage({ uri, headers });
883 }, []);
884​
885 const renderItem = useCallback(
886 (info: { item: ThreadFeedEntry; index: number }) =>
887 renderFeedEntry(info, {
888 bearerToken: props.bearerToken,
889 copiedRowId,
890 httpBaseUrl: props.httpBaseUrl,
891 expandedWorkGroups,
892 onCopyWorkRow,
893 onToggleWorkGroup,
894 onPressImage,
895 iconSubtleColor,
896 userBubbleColor,
897 markdownStyles,
898 reviewCommentColors,
899 reviewCommentBubbleWidth,
900 }),
901 [
902 copiedRowId,
903 expandedWorkGroups,
904 iconSubtleColor,
905 userBubbleColor,
906 markdownStyles,
907 reviewCommentColors,
908 reviewCommentBubbleWidth,
909 onCopyWorkRow,
910 onPressImage,
911 onToggleWorkGroup,
912 props.bearerToken,
913 props.httpBaseUrl,
914 ],
915 );
916​
917 if (props.feed.length === 0) {
918 return (
919 <ScrollView
920 style={{ flex: 1 }}
921 contentInsetAdjustmentBehavior="never"
922 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
923 contentOffset={{ x: 0, y: -topContentInset }}
924 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
925 contentContainerStyle={{
926 flexGrow: 1,
927 paddingHorizontal: horizontalPadding,
928 }}
929 >
930 <EmptyState
931 title="No conversation yet"
932 detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
933 />
934 </ScrollView>
935 );
936 }
937​
938 return (
939 <>
940 <KeyboardAvoidingLegendList
941 ref={listRef}
942 key={props.threadId}
943 style={{ flex: 1 }}
944 alignItemsAtEnd
945 contentInsetAdjustmentBehavior="never"
946 contentInset={{ top: topContentInset, bottom: bottomContentInset }}
947 scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
948 data={props.feed as ThreadFeedEntry[]}
949 renderItem={renderItem}
950 keyExtractor={(entry) => `${entry.type}:${entry.id}`}
951 getItemType={(entry) =>
952 entry.type === "message" ? `message:${entry.message.role}` : entry.type
953 }
954 keyboardShouldPersistTaps="handled"
955 estimatedItemSize={180}
956 initialScrollAtEnd
957 maintainScrollAtEnd={{
958 on: { layout: true, itemLayout: true, dataChange: true },
959 }}
960 maintainScrollAtEndThreshold={0.1}
961 refreshing={props.refreshing ?? false}
962 onRefresh={props.onRefresh}
963 safeAreaInsetBottom={insets.bottom}
964 contentContainerStyle={{
965 paddingTop: 12,
966 paddingHorizontal: horizontalPadding,
967 }}
968 />
969​
970 <ImageViewing
971 images={
972 expandedImage
973 ? [
974 {
975 uri: expandedImage.uri,
976 headers: expandedImage.headers,
977 },
978 ]
979 : []
980 }
981 imageIndex={0}
982 visible={expandedImage !== null}
983 onRequestClose={() => setExpandedImage(null)}
984 swipeToCloseEnabled
985 doubleTapToZoomEnabled
986 />
987 </>
988 );
989});