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

ThreadFeed.tsx

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