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

main
tsx 4,549 lines 173 KB
Raw
1 import { CollapsibleUserMessageBody } from "./CollapsibleUserMessageBody";
2 import { msg, T, useGT, useLocale, useMessages } from "gt-react-native";
3 import { m } from "../../i18n/messages";
4 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
5 import { toServerClock } from "@t3tools/client-runtime/clock";
6 import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
7 import { Sheet } from "../../components/ui/Sheet";
8 import { ListActionRow } from "../../components/ui/ListActionRow";
9 import { ListSection } from "../../components/ui/ListSection";
10 import { collectMobileAssistantTextSelectors } from "../../lib/assistantCitationSelection";
11 import { Button } from "../../components/ui/Button";
12 import * as Dialog from "../../components/ui/Dialog";
13 import { ASSISTANT_CITATION_MAX_TEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
14 import { useOpenPullRequest } from "../../native/useOpenPullRequest";
15 import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
16 import { useVisibleSecondClock } from "./use-visible-second-clock";
17 import {
18 ThreadMarkdownVideo,
19 ThreadMediaRetainContext,
20 ThreadMediaVisibleContext,
21 } from "./ThreadMarkdownVideo";
22 import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
23 import {
24 enrichedContextLinkCustomization,
25 enrichedThreadLinkCustomization,
26 withChipIcon,
27 } from "../../native/useEnrichedLinkVariants";
28 import {
29 enrichedSkillInstructionsPath,
30 enrichedSkillReference,
31 } from "../../lib/enrichedLinkPresentation";
32 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
33 import {
34 ThreadContextDivider,
35 ThreadStatusLine,
36 type ThreadStatusLineModel,
37 } from "./thread-context-divider";
38 import {
39 ThreadHandoffDivider,
40 ThreadHandoffRow,
41 ThreadModelSwitchDivider,
42 } from "./thread-handoff-row";
43 import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";
44 import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";
45 import { LinkRequestCard } from "./LinkRequestCard";
46 import { SecretRequestCard } from "./SecretRequestCard";
47 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
48 import {
49 WorktreePreparingHeader,
50 WorktreeSetupCard,
51 WorktreeSetupDetails,
52 WorktreeSetupFoldChip,
53 worktreeSetupHandedOff,
54 type WorktreeSetupCardProps,
55 } from "./worktree-setup-card";
56 import * as Haptics from "expo-haptics";
57 import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
58 import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
59 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
60 import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
61 import {
62 IDLE_COMPACTING_LABELS,
63 resolveUserMessageFileCards,
64 resolveUserMessagePresentation,
65 } from "@t3tools/client-runtime/user-message";
66 import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
67 import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
68 import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
69 import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
70 import {
71 AuthFilesystemReadScope,
72 idleCompactionOf,
73 isOrchestrationV2WorkActive,
74 type OrchestrationMessageContext,
75 ThreadId,
76 type ChatAttachment,
77 type ChatFileAttachment,
78 type ChatImageAttachment,
79 type EnvironmentId,
80 type MessageId,
81 type OrchestrationV2ProjectedTurnItem,
82 type RunId,
83 type ScheduledTaskId,
84 type ScopedThreadRef,
85 } from "@t3tools/contracts";
86 import type { ToolCallVisibility } from "@t3tools/contracts/settings";
87 import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
88 import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
89 import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";
90 import {
91 parseComposerContextHref,
92 collectComposerContextReferences,
93 replaceComposerContextReferences,
94 formatComposerContextReference,
95 } from "@t3tools/shared/composerContextReferences";
96 import { ComposerContextSheet } from "../../components/ComposerContextSheet";
97 import { writeComposerContextClipboard } from "../../lib/composerContextClipboard";
98 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
99 import { codexArtifactTemplatePresentationLabel } from "@t3tools/shared/codexArtifactTemplatesCopy";
100 import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
101 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
102 import {
103 executeAtomQuery,
104 isAtomCommandInterrupted,
105 settlePromise,
106 squashAtomCommandFailure,
107 } from "@t3tools/client-runtime/state/runtime";
108 import {
109 classifyMarkdownImageSource,
110 markdownImageSourceFragment,
111 } from "@t3tools/client-runtime/markdown-images";
112 import {
113 contextCompactionTokenCounts,
114 resolveViewedImageAsset,
115 } from "@t3tools/client-runtime/work-log/presentation";
116 import {
117 renderCodexInlineDirectivesAsMarkdown,
118 splitCodexArtifactTemplateMarkdown,
119 } from "@t3tools/shared/codexMarkdownDirectives";
120 import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
121 import { imageMimeType } from "@t3tools/shared/image";
122 import { videoMimeType } from "@t3tools/shared/video";
123 import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
124 import { textDirection } from "@t3tools/shared/textDirection";
125 import { useFocusEffect, useIsFocused, useNavigation } from "@react-navigation/native";
126 import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
127 import { useDeviceType } from "../../native/native-layout-metrics";
128 import { isDuoDevice } from "../../lib/device-type";
129 import {
130 memo,
131 useCallback,
132 useEffect,
133 useEffectEvent,
134 useLayoutEffect,
135 useMemo,
136 useRef,
137 useState,
138 useSyncExternalStore,
139 useId,
140 type ComponentPropsWithRef,
141 type Dispatch,
142 type ReactNode,
143 type RefObject,
144 type SetStateAction,
145 } from "react";
146 import {
147 Image,
148 ScrollView,
149 Platform,
150 type LayoutChangeEvent,
151 type NativeScrollEvent,
152 type NativeSyntheticEvent,
153 Pressable,
154 StyleSheet,
155 type ColorValue,
156 useWindowDimensions,
157 View,
158 } from "react-native";
159 import { Image as ExpoImage } from "expo-image";
160 import { useResolveClassNames } from "uniwind";
161 import { useReduceMotionEnabled } from "../../lib/appState";
162 import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery";
163 import { assetImageSource } from "../../lib/assetImageSource";
164 import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery";
165 import { composerImageGallery } from "../../lib/composerImageGallery";
166 import {
167 isFileBackedComposerAttachment,
168 type FileBackedComposerAttachment,
169 } from "../../lib/composerImages";
170 import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
171 import {
172 rememberSentImage,
173 sentImageHandoff,
174 type SentImageHandoff,
175 } from "../../lib/sentImageHandoff";
176 import { messageImageGallery } from "./messageImageGallery";
177 import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
178 import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
179 import { inlineFilePreviewKind, isPdfFile } from "../../lib/filePreview";
180 import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview";
181 import { flattenThemeColor, themeColorWithContrast } from "../../lib/mobileTheme";
182 import { PresentationSource } from "../../components/ui/NativePresentation";
183 import { NativeScrollViewMarker } from "../../native/NativeScrollViewMarker";
184 import Animated, { FadeIn, FadeInDown, type SharedValue } from "react-native-reanimated";
185 import { useUniwindTheme } from "../../lib/useUniwindTheme";
186 import { FONT_FAMILIES } from "../../lib/fontFamilies";
187 import { scopedThreadKey } from "../../lib/scopedEntities";
188 import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
189 import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
190 import { splitMarkdownDetails } from "../../lib/markdownDetails";
191 import { markdownReferenceDefinitions, withReferenceDefinitions } from "../../lib/markdownDocument";
192 import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
193 import {
194 SelectableMarkdownText,
195 type MarkdownFileContextMenu,
196 type MarkdownImageRenderer,
197 type MarkdownImageSourceResolver,
198 type MarkdownLinkCustomization,
199 type NativeMarkdownTextStyle,
200 type SelectableMarkdownSkill,
201 } from "../../native/SelectableMarkdownText";
202
203 import { AppText as Text } from "../../components/ui/AppText";
204 import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
205 import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
206 import {
207 attachmentVideoPreviewSource,
208 mediaVideoThumbnailKey,
209 type MediaVideoPreviewSource,
210 } from "../../lib/videoPreviewSource";
211 import { CopyTextButton } from "./CopyTextButton";
212 import { getReviewSectionIdForCheckpoint } from "../review/reviewModel";
213 import { setReviewSelectedSectionId } from "../review/reviewState";
214 import { Menu } from "../../components/ui/Menu";
215 import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
216 import { useBarInset, useContentTopInset } from "../../components/ui/useBarInset";
217 import { copyPromptLink } from "../prompt-links/prompt-link-actions";
218 import { parseReviewCommentMessageSegments } from "../review/reviewCommentSelection";
219 import {
220 ReviewCommentCard,
221 useReviewCommentColors,
222 type ReviewCommentColors,
223 } from "../review/ReviewCommentCard";
224 import { cn } from "../../lib/cn";
225 import {
226 deriveCenteredContentHorizontalPadding,
227 deriveThreadWorkLogSizing,
228 type LayoutVariant,
229 } from "../../lib/layout";
230 import { uuidv4 } from "../../lib/uuid";
231 import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences";
232 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
233 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
234 import {
235 normalizeNativeMarkdownUrl,
236 resolveMarkdownLinkPresentation,
237 } from "../../lib/markdownLinks";
238 import {
239 createThreadFeedCache,
240 threadFeedCompactionLabels,
241 failedFeedRunIds,
242 deriveThreadFeedPresentation,
243 threadFeedRunIsUnsettled,
244 isContextCompactionActivityGroup,
245 isContextHandoffActivityGroup,
246 isLinkRequestActivityGroup,
247 isSecretRequestActivityGroup,
248 type ThreadFeedEntry,
249 type ThreadFeedLatestRun,
250 messageFoldRunId,
251 } from "../../lib/threadActivity";
252 import type { ThreadContentPresentation } from "./threadContentPresentation";
253 import { type ThreadWorkGroupScrollPosition } from "./thread-feed-scroll-position";
254 import {
255 collapsedWorkLogHeight,
256 ThreadDisclosureChevron,
257 THREAD_DISCLOSURE_TRANSITION_MS,
258 ThreadWorkGroupToggle,
259 ThreadThinkingRow,
260 ThreadWorkLog,
261 WORK_GROUP_TOGGLE_HEIGHT,
262 } from "./thread-work-log";
263 import {
264 appendGuestPendingMessages,
265 appendPendingThreadMessages,
266 createPendingTurnAppender,
267 createThreadFeedGrouping,
268 isCompactionCommandFeedEntry,
269 type GroupedThreadFeedRow,
270 type ThreadFeedRow,
271 } from "./pending-thread-feed";
272 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
273 import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
274 import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender";
275 import { htmlRenderRowHeight, ThreadHtmlRender } from "./HtmlRenderWebView";
276 import { ThreadMcpApp } from "./McpAppWebView";
277 import { assetEnvironment, useAssetUrl, useRefreshAssetUrl } from "../../state/assets";
278 import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
279 import { readEnvironmentScope, usePreparedConnection } from "../../state/session";
280 import { environmentProjects, projectEnvironment } from "../../state/projects";
281 import {
282 agentWorkingDirectories,
283 findAgentDirectoryMatch,
284 needsWorkspaceBasenameLookup,
285 pickProjectLinkMatch,
286 pickWorkspaceLinkMatch,
287 WORKSPACE_BASENAME_LOOKUP_LIMIT,
288 workspaceLinkLookupQuery,
289 } from "@t3tools/client-runtime/workspace-basename-lookup";
290 import {
291 resolveThreadLink,
292 useEnvironmentPreviewTunnelOff,
293 useLiveThreadLinkLabels,
294 useQuietThreadShell,
295 useThreadChipIcons,
296 } from "../../state/entities";
297 import { useEnvironmentPresentation } from "../../state/presentation";
298 import { useThreadSelection } from "../../state/use-thread-selection";
299 import { useEnvironmentQuery } from "../../state/query";
300 import { useLinkedEnvironments } from "../../state/peerLinks";
301 import { serverEnvironment } from "../../state/server";
302 import { useModelMentions } from "../../state/model-mentions";
303 import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
304 import * as Option from "effect/Option";
305 import { appAtomRegistry } from "../../state/atom-registry";
306 import {
307 environmentThreadDetails,
308 environmentThreadShells,
309 threadEnvironment,
310 } from "../../state/threads";
311 import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening";
312 import { useAtomCommand } from "../../state/use-atom-command";
313 import { useV2ItemSupport } from "../../state/v2-item-support";
314 import {
315 fileRoutePathSegments,
316 isAbsolutePath,
317 resolveFileLinkPath,
318 resolveWorkspaceFilePath,
319 resolveWorkspaceRelativeFilePath,
320 } from "../files/filePath";
321 import { waitForThreadShell } from "./threadForkNavigation";
322 import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
323 import { fileChipClipboardPath, fileChipMenu, resolveFileChipTarget } from "./fileChipMenu";
324 import { useFileChipShare } from "./useFileChipShare";
325 import { useOpenLinkedThread } from "./useOpenLinkedThread";
326 import { useOpenThreadLink } from "./useOpenThreadLink";
327 import {
328 MarkdownImageAvailableWidthContext,
329 ThreadMarkdownImage,
330 ThreadMarkdownImageUnavailable,
331 ThreadMarkdownImageView,
332 } from "./ThreadMarkdownImage";
333 import { ZoomableImagePressable } from "./ZoomableImagePressable";
334 import { openSettings } from "../settings/settings-navigation";
335 import { loopbackUrlForDevice } from "../browser/browserTabs";
336 import { useOpenLocalPreview } from "../browser/useOpenLocalPreview";
337 import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
338 import { useMessageTimeFormatter } from "./useMessageTimeFormatter";
339
340 const WIDE_MARKDOWN_BLOCK_OPTIONS = {
341 // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width.
342 includeBlockquotes: Platform.OS === "ios",
343 includeOrderedLists: Platform.OS === "android",
344 } as const;
345
346 const TURN_FOLD_HEIGHT = 42;
347 const FEED_PADDING_TOP = 12;
348 const VIEWED_IMAGE_GAP = 8;
349 const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
350 const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;
351 // Virtualization remounts old rows; only newly created content should replay an entrance.
352 const FRESH_ENTRY_WINDOW_MS = 3_000;
353 function isFreshTimestamp(input: string): boolean {
354 const timestamp = Date.parse(input);
355 return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
356 }
357
358 export interface ThreadFeedHistoryControls {
359 readonly hasMoreHistory: boolean;
360 readonly loading: boolean;
361 readonly error: string | null;
362 readonly onLoadEarlier: () => void;
363 /** Loads earlier history down to the entry, in one request. */
364 readonly onLoadThrough: (entryId: string) => void;
365 }
366
367 export interface ThreadFeedProps {
368 readonly toolCallVisibility?: ToolCallVisibility;
369 readonly worktreeSetup?: WorktreeSetupCardProps | null;
370 readonly preparingWorktree?: boolean;
371 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
372 readonly dispatchingMessageId: MessageId | null;
373 readonly onEditPendingMessage: ((message: QueuedThreadMessage) => void) | null;
374 readonly environmentId: EnvironmentId;
375 readonly threadId: ThreadId;
376 /** Null while the thread's creation is queued: reading detail then caches a not-found as deleted. */
377 readonly detailRef: ScopedThreadRef | null;
378 readonly threadTitle: string;
379 readonly workspaceRoot?: string | null;
380 readonly feed: ReadonlyArray<ThreadFeedEntry>;
381 readonly pendingHandoff?: HandoffEndpoints | null;
382 /** Thread states that close the feed: background work, then snooze or settle. */
383 readonly statusLines?: ReadonlyArray<ThreadStatusLineModel>;
384 readonly contentPresentation: ThreadContentPresentation;
385 readonly latestRun: ThreadFeedLatestRun | null;
386 readonly activeWorkStartedAt: string | null;
387 readonly runlessWorkActive?: boolean;
388 readonly listRef: RefObject<LegendListRef | null>;
389 readonly freeze: SharedValue<boolean>;
390 readonly anchorMessageId: MessageId | null;
391 /** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */
392 readonly jumpToMessageId?: MessageId | null;
393 readonly onJumpedToMessage?: () => void;
394 readonly contentInsetEndAdjustment: SharedValue<number>;
395 readonly keyboardOffset: number;
396 readonly sendingWithKeyboard?: boolean;
397 readonly fitShortFeedToViewport?: boolean;
398 readonly contentBottomInset?: number;
399 readonly historyControls?: ThreadFeedHistoryControls;
400 readonly contentMaxWidth?: number;
401 readonly contentSideInsets?: { readonly left: number; readonly right: number };
402 readonly layoutVariant?: LayoutVariant;
403 readonly usesAutomaticContentInsets?: boolean;
404 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
405 readonly onIsAtEndChange?: (isAtEnd: boolean) => void;
406 readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
407 readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
408 readonly onCiteAssistantText?: (citation: AssistantCitation) => void;
409 }
410
411 const USER_MESSAGE_COPY_MENU_ACTIONS = [
412 { id: "copy-prompt-link", title: msg("Copy prompt link"), image: "link" },
413 ];
414
415 function UserMessageCopyButton(props: {
416 readonly text: string;
417 readonly onCopy: (() => Promise<void>) | undefined;
418 readonly tintColor: ColorValue;
419 }) {
420 const gt = useGT();
421 const m = useMessages();
422 const button = (
423 <CopyTextButton
424 accessibilityLabel={gt("Copy message")}
425 text={props.text}
426 onCopy={props.onCopy}
427 tintColor={props.tintColor}
428 buttonSize={28}
429 iconSize={13}
430 />
431 );
432 const linkText = replaceComposerContextReferences(props.text, (reference) => reference.label);
433 if (linkText.length > PROMPT_LINK_MAX_PROMPT_LENGTH) return button;
434 return (
435 <Menu
436 actions={USER_MESSAGE_COPY_MENU_ACTIONS.map((action) => ({
437 ...action,
438 title: m(action.title),
439 }))}
440 onPressAction={({ nativeEvent }) => {
441 if (nativeEvent.event === "copy-prompt-link") void copyPromptLink(linkText);
442 }}
443 shouldOpenOnLongPress
444 >
445 {button}
446 </Menu>
447 );
448 }
449
450 function AssistantForkButton(props: {
451 readonly environmentId: EnvironmentId;
452 readonly iconColor: ColorValue;
453 readonly buttonSize: number;
454 readonly iconSize: number;
455 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
456 readonly sourceTitle: string;
457 }) {
458 const support = useV2ItemSupport({
459 environmentId: props.environmentId,
460 sourceThreadId: props.projectedItem.sourceThreadId,
461 sourceItemId: props.projectedItem.sourceItemId,
462 });
463 const gt = useGT();
464 const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
465 const selectDetail = useSelectWorkspaceDetail();
466 const [busy, setBusy] = useState(false);
467 const canFork = canForkProjectedAssistantItem({
468 projectedItem: props.projectedItem,
469 capabilities: support.providerSession?.capabilities,
470 });
471 const runId = props.projectedItem.item.runId;
472
473 if (!canFork || runId === null) return null;
474
475 return (
476 <Pressable
477 accessibilityRole="button"
478 accessibilityLabel={gt("Fork from this response")}
479 disabled={busy}
480 onPress={() => {
481 const targetThreadId = ThreadId.make(uuidv4());
482 setBusy(true);
483 void Haptics.selectionAsync();
484 void forkFromRun({
485 environmentId: props.environmentId,
486 input: {
487 sourceThreadId: props.projectedItem.sourceThreadId,
488 targetThreadId,
489 runId,
490 title: `${props.sourceTitle} fork`,
491 creationSource: "mobile",
492 },
493 })
494 .then(async (result) => {
495 if (isAtomCommandInterrupted(result)) return;
496 if (result._tag !== "Success") {
497 Dialog.alert(
498 gt("Could not confirm fork"),
499 gt("Reconnect and check the thread list before trying again."),
500 );
501 return;
502 }
503 const targetThreadReady = await waitForThreadShell(
504 scopeThreadRef(props.environmentId, targetThreadId),
505 );
506 if (!targetThreadReady) {
507 Dialog.alert(
508 gt("Fork created"),
509 gt(
510 "Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
511 ),
512 );
513 return;
514 }
515 selectDetail({
516 name: "Thread",
517 params: { environmentId: props.environmentId, threadId: targetThreadId },
518 });
519 })
520 .finally(() => setBusy(false));
521 }}
522 className="h-7 w-7 items-center justify-center disabled:opacity-40"
523 style={
524 Platform.OS === "android"
525 ? { width: props.buttonSize, height: props.buttonSize }
526 : undefined
527 }
528 >
529 {busy ? (
530 <AppActivityIndicator size="small" />
531 ) : (
532 <SymbolView
533 name="arrow.triangle.branch"
534 size={props.iconSize}
535 tintColor={props.iconColor}
536 type="monochrome"
537 />
538 )}
539 </Pressable>
540 );
541 }
542
543 function MessageImage(props: {
544 readonly source: ComponentPropsWithRef<typeof ExpoImage>["source"];
545 readonly className: string;
546 readonly maxWidth?: number;
547 readonly height?: number;
548 readonly accessibilityLabel: string;
549 readonly handoff?: SentImageHandoff;
550 readonly onPress: () => void;
551 readonly onLoad?: (size: { readonly width: number; readonly height: number }) => void;
552 readonly onError?: () => void;
553 }) {
554 const imageStyle = useResolveClassNames(props.className);
555 const [loadedSize, setSize] = useState<{ width: number; height: number } | null>(null);
556 // Until it loads, assume a handed-off image is a photo larger than the bubble's caps.
557 const size =
558 loadedSize ??
559 (props.handoff ? { width: props.handoff.aspectRatio * 4096, height: 4096 } : null);
560 const contentFit = props.maxWidth === undefined ? "cover" : "contain";
561 const displaySize =
562 props.maxWidth !== undefined && size !== null
563 ? resolveMarkdownImageDisplaySize({
564 sourceWidth: size.width,
565 sourceHeight: size.height,
566 availableWidth: props.maxWidth,
567 })
568 : null;
569 return (
570 <ZoomableImagePressable
571 accessibilityRole="imagebutton"
572 accessibilityLabel={props.accessibilityLabel}
573 onPress={props.onPress}
574 style={[
575 imageStyle,
576 { overflow: "hidden" },
577 props.maxWidth !== undefined
578 ? (displaySize ?? {
579 width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH),
580 aspectRatio: 1.3,
581 })
582 : props.height !== undefined
583 ? { height: props.height }
584 : undefined,
585 ]}
586 >
587 <ExpoImage
588 source={props.source}
589 cachePolicy="memory-disk"
590 style={{ width: "100%", height: "100%" }}
591 contentFit={contentFit}
592 placeholder={props.handoff ? { uri: props.handoff.uri } : undefined}
593 placeholderContentFit={contentFit}
594 onLoad={(event) => {
595 if (props.maxWidth !== undefined) setSize(event.source);
596 props.onLoad?.(event.source);
597 }}
598 onError={props.onError}
599 />
600 </ZoomableImagePressable>
601 );
602 }
603
604 function MessageAttachmentImage(props: {
605 readonly environmentId: EnvironmentId;
606 readonly attachmentId: string;
607 readonly name: string;
608 readonly mimeType: string;
609 readonly className: string;
610 readonly maxWidth?: number;
611 readonly height?: number;
612 readonly handoff?: SentImageHandoff;
613 readonly onImageLoad?: (image: SentImageHandoff) => void;
614 readonly onPressPreview: (source: FilePreviewSource) => void;
615 }) {
616 const gt = useGT();
617 const withGallery = useFilePreviewGallery();
618 const resource = {
619 _tag: "attachment" as const,
620 attachmentId: props.attachmentId,
621 fileName: props.name,
622 mimeType: props.mimeType,
623 };
624 const sourceIdentifier = filePreviewSourceIdentifier({
625 kind: "image",
626 environmentId: props.environmentId,
627 resource,
628 });
629 const uri = useAssetUrl(props.environmentId, resource);
630 const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource);
631 const retriedImage = useRef(false);
632 const { handoff } = props;
633 const source =
634 uri !== null
635 ? assetImageSource(props.environmentId, resource, uri)
636 : handoff !== undefined
637 ? { uri: handoff.uri }
638 : null;
639
640 if (source === null) {
641 return (
642 <View
643 className={`${props.className} items-center justify-center`}
644 style={
645 props.maxWidth !== undefined
646 ? { width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH), aspectRatio: 1.3 }
647 : props.height !== undefined
648 ? { height: props.height }
649 : undefined
650 }
651 >
652 <AppActivityIndicator />
653 </View>
654 );
655 }
656
657 return (
658 <PresentationSource identifier={sourceIdentifier}>
659 <MessageImage
660 key={props.attachmentId}
661 source={source}
662 className={props.className}
663 maxWidth={props.maxWidth}
664 height={props.height}
665 accessibilityLabel={gt("Open {name}", { name: props.name })}
666 {...handoffProps(handoff)}
667 onPress={() =>
668 props.onPressPreview(
669 withGallery({
670 kind: "image",
671 environmentId: props.environmentId,
672 resource,
673 name: props.name,
674 sourceIdentifier,
675 actionsSource: {
676 name: props.name,
677 mimeType: props.mimeType,
678 environmentId: props.environmentId,
679 resource,
680 },
681 }),
682 )
683 }
684 onLoad={(size) => {
685 retriedImage.current = false;
686 if (handoff)
687 props.onImageLoad?.({ uri: handoff.uri, aspectRatio: size.width / size.height });
688 }}
689 onError={() => {
690 if (retriedImage.current) return;
691 retriedImage.current = true;
692 void refreshAssetUrl();
693 }}
694 />
695 </PresentationSource>
696 );
697 }
698
699 function isImageAttachment(attachment: ChatAttachment): attachment is ChatImageAttachment {
700 return attachment.type === "image" || imageMimeType(attachment) !== null;
701 }
702
703 function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAttachment {
704 return attachment.type === "file";
705 }
706
707 function isMediaAttachment(attachment: ChatAttachment): boolean {
708 return (
709 isImageAttachment(attachment) ||
710 (isFileAttachment(attachment) && videoMimeType(attachment) !== null)
711 );
712 }
713
714 function MessageAttachmentFile(props: {
715 readonly environmentId: EnvironmentId;
716 readonly attachment: ChatFileAttachment;
717 readonly onPressPreview: (source: FilePreviewSource) => void;
718 readonly onPlaybackStart: () => void;
719 readonly standaloneFile?: boolean;
720 readonly available?: boolean;
721 }) {
722 const gt = useGT();
723 const messages = useMessages();
724 const sourceIdentifier = useId();
725 const navigation = useNavigation();
726 const { selectedThread } = useThreadSelection();
727 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
728 refresh: true,
729 reportFailure: false,
730 });
731 const preparedConnection = usePreparedConnection(props.environmentId);
732 const { attachment } = props;
733 const videoType = videoMimeType(attachment);
734 const isPdf = isPdfFile(attachment);
735 const fileTypeLabel = isPdf
736 ? "PDF"
737 : (attachment.name.match(/\.([a-z0-9]{1,8})$/i)?.[1]?.toUpperCase() ??
738 gt("File", { $context: "generic file type label" }));
739 const sizeLabel = formatAttachmentSize(attachment.sizeBytes, messages);
740 const httpBaseUrl = Option.isSome(preparedConnection)
741 ? preparedConnection.value.httpBaseUrl
742 : null;
743 const openingRef = useRef<AbortController | null>(null);
744 const [opening, setOpening] = useState(false);
745
746 useFocusEffect(
747 useCallback(() => {
748 setOpening(false);
749 return () => {
750 openingRef.current?.abort();
751 openingRef.current = null;
752 };
753 // oxlint-disable-next-line react/memo-dependencies -- Changing the attachment or connection cancels the previous file open even while this screen stays focused.
754 }, [props.environmentId, attachment.id, httpBaseUrl]),
755 );
756
757 const shareFile = (sourceIdentifier?: string) => {
758 if (props.available === false || httpBaseUrl === null || openingRef.current) return;
759 const controller = new AbortController();
760 openingRef.current = controller;
761 setOpening(true);
762 const finish = (message: string | null) => {
763 if (message !== null && !controller.signal.aborted) {
764 Dialog.alert(gt("Could not open attachment"), message);
765 }
766 if (openingRef.current === controller) {
767 openingRef.current = null;
768 setOpening(false);
769 }
770 };
771 void (async () => {
772 const result = await createAssetUrl({
773 environmentId: props.environmentId,
774 input: {
775 resource: {
776 _tag: "attachment",
777 attachmentId: attachment.id,
778 fileName: attachment.name,
779 mimeType: attachment.mimeType,
780 },
781 },
782 });
783 if (controller.signal.aborted) return finish(null);
784 if (result._tag === "Failure") {
785 const error = squashAtomCommandFailure(result);
786 return finish(errorDisplayMessage(error, m) ?? gt("The attachment is unavailable."));
787 }
788 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
789 if (url === null) return finish(gt("The attachment could not be opened."));
790 const shared = await settlePromise(() =>
791 downloadAndShareAttachment({
792 url,
793 attachment,
794 signal: controller.signal,
795 sourceIdentifier,
796 }),
797 );
798 if (shared._tag === "Failure") {
799 const error = squashAtomCommandFailure(shared);
800 return finish(errorDisplayMessage(error, m) ?? gt("The attachment is unavailable."));
801 }
802 finish(null);
803 })();
804 };
805
806 const openAttachment = () =>
807 isPdf
808 ? props.onPressPreview({
809 kind: "pdf",
810 name: attachment.name,
811 environmentId: props.environmentId,
812 resource: {
813 _tag: "attachment",
814 attachmentId: attachment.id,
815 fileName: attachment.name,
816 mimeType: "application/pdf",
817 },
818 sourceIdentifier,
819 })
820 : navigation.navigate("ThreadAttachment", {
821 environmentId: String(props.environmentId),
822 ...(selectedThread ? { threadId: String(selectedThread.id) } : {}),
823 attachmentId: attachment.id,
824 name: attachment.name,
825 mimeType: attachment.mimeType,
826 sizeBytes: String(attachment.sizeBytes),
827 });
828 const inlineKind = inlineFilePreviewKind(attachment);
829 if (inlineKind) {
830 return (
831 <PresentationSource identifier={sourceIdentifier}>
832 <ThreadInlineFilePreview
833 key={attachment.id}
834 source={{
835 kind: "document",
836 name: attachment.name,
837 mimeType: attachment.mimeType,
838 environmentId: props.environmentId,
839 resource: {
840 _tag: "attachment",
841 attachmentId: attachment.id,
842 fileName: attachment.name,
843 mimeType: attachment.mimeType,
844 disposition: "inline",
845 },
846 }}
847 sizeBytes={attachment.sizeBytes}
848 onOpen={openAttachment}
849 onPlaybackStart={props.onPlaybackStart}
850 onLongPress={() => shareFile(sourceIdentifier)}
851 />
852 </PresentationSource>
853 );
854 }
855
856 if (videoType !== null) {
857 return (
858 <View className="my-1" style={{ width: 224, maxWidth: "100%" }}>
859 <ThreadMarkdownVideo
860 source={attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier)}
861 onPlaybackStart={props.onPlaybackStart}
862 />
863 </View>
864 );
865 }
866
867 const disabled = props.available === false || opening || httpBaseUrl === null;
868 return (
869 <PresentationSource
870 identifier={sourceIdentifier}
871 className="my-1"
872 style={{ width: 280, maxWidth: "100%" }}
873 >
874 <View className="min-w-0 flex-row items-center overflow-hidden rounded-xl border border-border bg-card">
875 <Pressable
876 accessibilityRole="button"
877 accessibilityLabel={gt("Open {name}", { name: attachment.name })}
878 accessibilityValue={{ text: `${fileTypeLabel}, ${sizeLabel}` }}
879 accessibilityState={{ disabled, busy: opening }}
880 disabled={disabled}
881 className="min-w-0 flex-1 flex-row items-center gap-3 p-3 active:bg-subtle"
882 onLongPress={() => shareFile(sourceIdentifier)}
883 onPress={openAttachment}
884 >
885 <View className="h-12 w-10 shrink-0 items-center justify-center rounded-lg bg-subtle">
886 {opening ? (
887 <AppActivityIndicator size="small" />
888 ) : (
889 <PierreEntryIcon path={attachment.name} kind="file" size={26} />
890 )}
891 </View>
892 <View className="min-w-0 flex-1 gap-1">
893 <Text className="font-t3-medium text-sm text-foreground" numberOfLines={2}>
894 {attachment.name}
895 </Text>
896 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
897 {fileTypeLabel} · {sizeLabel}
898 </Text>
899 </View>
900 <SymbolView
901 name="chevron.right"
902 size={12}
903 tintColorClassName="accent-foreground-muted"
904 type="monochrome"
905 />
906 </Pressable>
907 {props.standaloneFile ? (
908 <Pressable
909 accessibilityRole="button"
910 accessibilityLabel={gt("Download {name}", { name: attachment.name })}
911 accessibilityState={{ disabled, busy: opening }}
912 disabled={disabled}
913 className="mr-1 min-h-11 w-11 items-center justify-center rounded-lg active:bg-subtle disabled:opacity-40"
914 onPress={() => shareFile(sourceIdentifier)}
915 >
916 <SymbolView name="arrow.down" size={16} tintColorClassName="accent-foreground-muted" />
917 </Pressable>
918 ) : null}
919 </View>
920 </PresentationSource>
921 );
922 }
923
924 const handoffProps = (handoff: SentImageHandoff | undefined) => (handoff ? { handoff } : {});
925
926 function UserMessageMedia(props: {
927 readonly messageId: string;
928 readonly attachments: ReadonlyArray<ChatAttachment>;
929 readonly pendingAttachments: QueuedThreadMessage["attachments"];
930 readonly environmentId: EnvironmentId;
931 readonly maxWidth: number;
932 readonly onPressPreview: (source: FilePreviewSource) => void;
933 readonly onPlaybackStart: () => void;
934 }) {
935 const attachments = [...props.pendingAttachments, ...props.attachments];
936 const collage = attachments.length > 1 && attachments.every(isImageAttachment);
937 const imageProps = (index: number) => ({
938 className: "w-full bg-user-bubble-foreground/15",
939 maxWidth: collage ? undefined : props.maxWidth,
940 height: !collage
941 ? undefined
942 : attachments.length === 2 || (attachments.length === 3 && index === 0)
943 ? 192
944 : attachments.length === 3
945 ? (192 - StyleSheet.hairlineWidth) / 2
946 : 96,
947 });
948 const media = [
949 ...props.pendingAttachments.map((attachment, index) => {
950 const image = isImageAttachment(attachment);
951 return {
952 image,
953 content:
954 image && attachment.uploadedAttachmentId ? (
955 <MessageAttachmentImage
956 environmentId={props.environmentId}
957 attachmentId={attachment.uploadedAttachmentId}
958 name={attachment.name}
959 mimeType={attachment.mimeType}
960 {...imageProps(index)}
961 {...handoffProps(sentImageHandoff(props.messageId, index, attachment.id))}
962 onImageLoad={(loaded) => rememberSentImage(props.messageId, index, loaded)}
963 onPressPreview={props.onPressPreview}
964 />
965 ) : !image ? (
966 <UserMessageVideo
967 environmentId={props.environmentId}
968 messageId={props.messageId}
969 index={index}
970 local={isFileBackedComposerAttachment(attachment) ? attachment : null}
971 uploaded={
972 attachment.uploadedAttachmentId === undefined
973 ? null
974 : { ...attachment, type: "file", id: attachment.uploadedAttachmentId }
975 }
976 onPlaybackStart={props.onPlaybackStart}
977 />
978 ) : (
979 <PendingMessageImage
980 attachment={attachment}
981 {...imageProps(index)}
982 {...handoffProps(sentImageHandoff(props.messageId, index, attachment.id))}
983 onImageLoad={(image) => rememberSentImage(props.messageId, index, image)}
984 onPressPreview={props.onPressPreview}
985 />
986 ),
987 };
988 }),
989 ...props.attachments.map((attachment, index) => ({
990 image: isImageAttachment(attachment),
991 content: isImageAttachment(attachment) ? (
992 <MessageAttachmentImage
993 environmentId={props.environmentId}
994 attachmentId={attachment.id}
995 name={attachment.name}
996 mimeType={attachment.mimeType}
997 {...imageProps(props.pendingAttachments.length + index)}
998 {...handoffProps(sentImageHandoff(props.messageId, index))}
999 onPressPreview={props.onPressPreview}
1000 />
1001 ) : isFileAttachment(attachment) ? (
1002 <UserMessageVideo
1003 environmentId={props.environmentId}
1004 messageId={props.messageId}
1005 index={index}
1006 local={null}
1007 uploaded={attachment}
1008 onPlaybackStart={props.onPlaybackStart}
1009 />
1010 ) : null,
1011 })),
1012 ];
1013 return collage ? (
1014 <View
1015 className="overflow-hidden rounded-[20px] bg-border"
1016 style={{ width: 320, maxWidth: "100%", alignSelf: "flex-end", gap: StyleSheet.hairlineWidth }}
1017 >
1018 {media.length === 3 ? (
1019 <View className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
1020 <View className="min-w-0" style={{ flex: 3 }}>
1021 {media[0]!.content}
1022 </View>
1023 <View className="min-w-0" style={{ flex: 2, gap: StyleSheet.hairlineWidth }}>
1024 {media[1]!.content}
1025 {media[2]!.content}
1026 </View>
1027 </View>
1028 ) : (
1029 media
1030 .filter((_, index) => index % 2 === 0)
1031 .map((item, index) => (
1032 // oxlint-disable-next-line react/no-array-index-key -- delivery re-ids attachments; position is the stable identity
1033 <View key={index} className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
1034 <View className="min-w-0 flex-1">{item.content}</View>
1035 {media[index * 2 + 1] ? (
1036 <View className="min-w-0 flex-1">{media[index * 2 + 1]!.content}</View>
1037 ) : null}
1038 </View>
1039 ))
1040 )}
1041 <View pointerEvents="none" className="absolute inset-0 rounded-[20px] border border-border" />
1042 </View>
1043 ) : (
1044 <View className="items-end gap-2">
1045 {media.map((item, index) => (
1046 <View
1047 // oxlint-disable-next-line react/no-array-index-key -- delivery re-ids attachments; a new key would remount the media
1048 key={index}
1049 className="overflow-hidden rounded-[20px]"
1050 style={{ width: item.image ? undefined : 320, maxWidth: "100%" }}
1051 >
1052 {item.content}
1053 <View
1054 pointerEvents="none"
1055 className="absolute inset-0 rounded-[20px] border border-border"
1056 />
1057 </View>
1058 ))}
1059 </View>
1060 );
1061 }
1062
1063 function PendingMessageImage(props: {
1064 readonly attachment: QueuedThreadMessage["attachments"][number];
1065 readonly className: string;
1066 readonly maxWidth?: number;
1067 readonly height?: number;
1068 readonly handoff?: SentImageHandoff;
1069 readonly onImageLoad?: (image: SentImageHandoff) => void;
1070 readonly onPressPreview: (source: FilePreviewSource) => void;
1071 }) {
1072 const gt = useGT();
1073 const withGallery = useFilePreviewGallery();
1074 const { attachment, handoff } = props;
1075 const fileBacked = isFileBackedComposerAttachment(attachment);
1076 const preview = useLocalAttachmentPreview(fileBacked ? attachment : null);
1077 // The composer already showed this image; reuse its pixels and shape instead of a blank box.
1078 const uri =
1079 handoff?.uri ?? (fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri));
1080 return (
1081 <MessageImage
1082 key={attachment.id}
1083 source={uri == null ? undefined : { uri }}
1084 className={props.className}
1085 maxWidth={props.maxWidth}
1086 height={props.height}
1087 accessibilityLabel={gt("Open {name}", { name: attachment.name })}
1088 {...handoffProps(handoff)}
1089 onLoad={(size) => {
1090 if (uri) props.onImageLoad?.({ uri, aspectRatio: size.width / size.height });
1091 }}
1092 onPress={() => {
1093 const source = composerImageGallery([attachment])[0];
1094 if (source) props.onPressPreview(withGallery(source));
1095 }}
1096 />
1097 );
1098 }
1099
1100 /**
1101 * A sent video from queueing through delivery. Every stage renders this one player under a
1102 * thumbnail key of message and position, so swapping the local file for the server copy keeps
1103 * the poster on screen instead of remounting to black and extracting a frame again.
1104 */
1105 function UserMessageVideo(props: {
1106 readonly environmentId: EnvironmentId;
1107 readonly messageId: string;
1108 readonly index: number;
1109 readonly local: FileBackedComposerAttachment | null;
1110 readonly uploaded: ChatFileAttachment | null;
1111 readonly onPlaybackStart: () => void;
1112 }) {
1113 const sourceIdentifier = useId();
1114 const preview = useLocalAttachmentPreview(props.local);
1115 const current: MediaVideoPreviewSource | null =
1116 props.local !== null && preview.uri !== null
1117 ? {
1118 type: "media",
1119 name: props.local.name,
1120 mimeType: props.local.mimeType,
1121 uri: preview.uri,
1122 }
1123 : props.uploaded !== null
1124 ? attachmentVideoPreviewSource(props.environmentId, props.uploaded, sourceIdentifier)
1125 : null;
1126 // Each copy of a message reopens its local file; keep the last source while the next one loads.
1127 const [shown, setShown] = useState(current);
1128 if (
1129 current !== null &&
1130 (shown === null || mediaVideoThumbnailKey(current) !== mediaVideoThumbnailKey(shown))
1131 ) {
1132 setShown(current);
1133 }
1134 const source = current ?? shown;
1135 if (source === null) {
1136 return (
1137 <View className="aspect-video items-center justify-center bg-black">
1138 {preview.error ? (
1139 <Text className="p-3 text-center text-xs text-white/70">{preview.error.message}</Text>
1140 ) : (
1141 <AppActivityIndicator />
1142 )}
1143 </View>
1144 );
1145 }
1146 return (
1147 <ThreadMarkdownVideo
1148 source={source}
1149 thumbnailKey={JSON.stringify(["user-message-video", props.messageId, props.index])}
1150 onPlaybackStart={props.onPlaybackStart}
1151 borderRadius={20}
1152 />
1153 );
1154 }
1155
1156 /** A message's files as its bubble shows them; a guest's waiting message uses it too. */
1157 function MessageAttachmentList(props: {
1158 readonly attachments: ReadonlyArray<ChatAttachment>;
1159 readonly environmentId: EnvironmentId;
1160 readonly onPressPreview: (source: FilePreviewSource) => void;
1161 readonly onPlaybackStart: () => void;
1162 }) {
1163 return props.attachments.map((attachment) =>
1164 isImageAttachment(attachment) ? (
1165 <MessageAttachmentImage
1166 key={attachment.id}
1167 environmentId={props.environmentId}
1168 attachmentId={attachment.id}
1169 name={attachment.name}
1170 mimeType={attachment.mimeType}
1171 className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-subtle-strong"
1172 onPressPreview={props.onPressPreview}
1173 />
1174 ) : isFileAttachment(attachment) ? (
1175 <MessageAttachmentFile
1176 key={attachment.id}
1177 environmentId={props.environmentId}
1178 attachment={attachment}
1179 onPressPreview={props.onPressPreview}
1180 onPlaybackStart={props.onPlaybackStart}
1181 />
1182 ) : (
1183 <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
1184 ),
1185 );
1186 }
1187
1188 function MessageAttachmentUnknown(props: { readonly name: string }) {
1189 return (
1190 <View className="flex-row items-center gap-2 py-1">
1191 <PierreEntryIcon path={props.name} kind="file" size={16} />
1192 <Text className="min-w-0 flex-1 text-sm text-foreground" numberOfLines={1}>
1193 {props.name}
1194 </Text>
1195 </View>
1196 );
1197 }
1198
1199 // LegendList only computes hook visibility when the list has a viewability config.
1200 const THREAD_MEDIA_VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 0 };
1201
1202 // The composer and overlays beside the feed keep UIKit from finding it on its own, so
1203 // register it with the screen controller. Header minimization observes this scroll view.
1204 function ThreadFeedScrollView(props: ComponentPropsWithRef<typeof Animated.ScrollView>) {
1205 return (
1206 <NativeScrollViewMarker style={{ flex: 1 }}>
1207 <Animated.ScrollView {...props} />
1208 </NativeScrollViewMarker>
1209 );
1210 }
1211
1212 function ThreadMediaVisibility(props: {
1213 readonly rowId: string;
1214 readonly setRetainedRowId: Dispatch<SetStateAction<string | null>>;
1215 readonly children: ReactNode;
1216 }) {
1217 const { rowId, setRetainedRowId } = props;
1218 const [visible, setVisible] = useState(false);
1219 useViewabilityAmount<ThreadFeedEntry>(
1220 useCallback((token) => setVisible(token.sizeVisible > 0), []),
1221 );
1222 const retain = useCallback(
1223 (retained: boolean) =>
1224 setRetainedRowId((current) => (retained ? rowId : current === rowId ? null : current)),
1225 [rowId, setRetainedRowId],
1226 );
1227 return (
1228 <ThreadMediaRetainContext value={retain}>
1229 <ThreadMediaVisibleContext value={visible}>{props.children}</ThreadMediaVisibleContext>
1230 </ThreadMediaRetainContext>
1231 );
1232 }
1233
1234 /** The reply a link sits in; a file it cites may be where the agent worked before writing it. */
1235 type MarkdownLinkReply = Pick<OrchestrationV2ProjectedTurnItem, "sourceThreadId" | "sourceItemId">;
1236
1237 interface MarkdownLinkHandlers {
1238 readonly onLinkPress: (href: string, reply?: MarkdownLinkReply) => void;
1239 readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
1240 readonly onFileContextMenuAction: (
1241 href: string,
1242 actionId: string,
1243 reply?: MarkdownLinkReply,
1244 ) => void;
1245 /** `withGallery` pages the image through its message's images; the feed's viewer sits outside that scope. */
1246 readonly onImagePress?: (
1247 href: string,
1248 withGallery?: (source: FilePreviewSource) => FilePreviewSource,
1249 ) => void;
1250 readonly resolveImageSource?: MarkdownImageSourceResolver;
1251 readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
1252 readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined;
1253 }
1254
1255 interface MarkdownStyleSets {
1256 readonly user: MarkdownStyleSet;
1257 readonly assistant: MarkdownStyleSet;
1258 }
1259
1260 interface MarkdownStyleSet {
1261 readonly nativeTextStyle: NativeMarkdownTextStyle;
1262 }
1263
1264 const ARTIFACT_TEMPLATE_SYMBOL_BY_KIND: Record<
1265 CodexArtifactTemplate["artifactKind"],
1266 AppSymbolName
1267 > = {
1268 document: "doc.text",
1269 presentation: "chart.bar.xaxis",
1270 spreadsheet: "chart.bar.xaxis",
1271 site: "safari",
1272 "google-docs": "doc.text",
1273 "google-slides": "chart.bar.xaxis",
1274 "google-sheets": "chart.bar.xaxis",
1275 image: "camera",
1276 email: "text.bubble",
1277 slack: "text.bubble",
1278 };
1279
1280 function ArtifactTemplateCard(props: {
1281 readonly template: CodexArtifactTemplate;
1282 readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined;
1283 }) {
1284 const gt = useGT();
1285 const messages = useMessages();
1286 const direction = textDirection(props.template.displayName);
1287 return (
1288 <View
1289 className="my-2 min-w-0 flex-row items-center gap-3 rounded-2xl border border-border bg-card px-3 py-3"
1290 style={direction ? { direction } : undefined}
1291 >
1292 <View className="h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border bg-subtle">
1293 <SymbolView
1294 name={ARTIFACT_TEMPLATE_SYMBOL_BY_KIND[props.template.artifactKind]}
1295 size={20}
1296 tintColorClassName="accent-foreground-muted"
1297 type="monochrome"
1298 />
1299 </View>
1300 <View className="min-w-0 flex-1">
1301 <Text className="font-t3-bold text-sm text-foreground" numberOfLines={1}>
1302 {props.template.displayName}
1303 </Text>
1304 <Text className="text-xs text-foreground-muted">
1305 {codexArtifactTemplatePresentationLabel(props.template.artifactKind, messages)}
1306 </Text>
1307 </View>
1308 {props.onUse ? (
1309 <Button
1310 label={gt("Use template")}
1311 tone="secondary"
1312 accessibilityLabel={gt("Use {name} template", { name: props.template.displayName })}
1313 onPress={() => props.onUse?.(props.template)}
1314 />
1315 ) : null}
1316 </View>
1317 );
1318 }
1319
1320 const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
1321 readonly markdown: string;
1322 readonly environmentId: EnvironmentId;
1323 readonly citationSource?: Pick<AssistantCitation, "threadId" | "messageId">;
1324 readonly onCiteAssistantText?: (citation: AssistantCitation) => void;
1325 readonly markdownStyles: MarkdownStyleSet;
1326 readonly linkHandlers: MarkdownLinkHandlers;
1327 readonly reply?: MarkdownLinkReply | undefined;
1328 readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
1329 readonly renderImage: MarkdownImageRenderer;
1330 readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
1331 }) {
1332 const gt = useGT();
1333 const liveMarkdown = useLiveThreadLinkLabels(
1334 props.markdown,
1335 props.environmentId,
1336 useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null),
1337 );
1338 const [quoteSelection, setQuoteSelection] = useState<{
1339 markdown: string;
1340 selectors: ReturnType<typeof collectMobileAssistantTextSelectors>;
1341 } | null>(null);
1342 if (quoteSelection !== null && quoteSelection.markdown !== liveMarkdown) setQuoteSelection(null);
1343 const quoteChoices = quoteSelection?.selectors ?? [];
1344 const cite = ({ selector }: (typeof quoteChoices)[number]) => {
1345 if (!props.citationSource || !props.onCiteAssistantText) return;
1346 setQuoteSelection(null);
1347 props.onCiteAssistantText({
1348 version: 1,
1349 environmentId: props.environmentId,
1350 ...props.citationSource,
1351 ...selector,
1352 });
1353 };
1354 const models = useModelMentions(props.environmentId, props.markdown);
1355 const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
1356 const withGallery = useFilePreviewGallery();
1357 const onImagePress = props.linkHandlers.onImagePress;
1358 const linkHandlers: MarkdownLinkHandlers = {
1359 ...props.linkHandlers,
1360 ...(onImagePress ? { onImagePress: (href: string) => onImagePress(href, withGallery) } : {}),
1361 onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply),
1362 onFileContextMenuAction: (href, actionId) =>
1363 props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply),
1364 linkCustomization: (href) =>
1365 withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
1366 };
1367
1368 return (
1369 <>
1370 <AssistantMarkdownBlocks
1371 markdown={liveMarkdown}
1372 onCiteText={
1373 props.onCiteAssistantText && props.citationSource
1374 ? (text, path) => {
1375 if (!text.trim()) return;
1376 if (text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH) {
1377 Dialog.alert(
1378 gt("Quote is too long"),
1379 gt("Select up to {max} characters to cite.", {
1380 max: ASSISTANT_CITATION_MAX_TEXT_LENGTH.toLocaleString(),
1381 }),
1382 );
1383 return;
1384 }
1385 const selectors = collectMobileAssistantTextSelectors(liveMarkdown, path, text);
1386 if (selectors.length === 0) {
1387 Dialog.alert(
1388 gt("Unable to locate quote"),
1389 gt("Select more surrounding text to cite its source accurately."),
1390 );
1391 return;
1392 }
1393 if (selectors.length === 1) cite(selectors[0]!);
1394 else setQuoteSelection({ markdown: liveMarkdown, selectors });
1395 }
1396 : undefined
1397 }
1398 markdownStyles={props.markdownStyles}
1399 linkHandlers={linkHandlers}
1400 onUseArtifactTemplate={props.onUseArtifactTemplate}
1401 renderImage={props.renderImage}
1402 skills={props.skills}
1403 models={models}
1404 />
1405 {quoteChoices.length > 0 && props.onCiteAssistantText ? (
1406 <Sheet title={gt("Choose quote source")} onClose={() => setQuoteSelection(null)}>
1407 <ScrollView
1408 contentInsetAdjustmentBehavior="automatic"
1409 contentContainerStyle={{ padding: 20 }}
1410 >
1411 <ListSection
1412 title={gt("This text appears more than once. Choose the passage you selected.")}
1413 >
1414 {quoteChoices.map((choice) => (
1415 <ListActionRow
1416 key={choice.selector.start}
1417 label={gt("Occurrence {index} of {count}", {
1418 index: choice.index + 1,
1419 count: choice.count,
1420 })}
1421 description={`${choice.selector.prefix}${choice.selector.text}${choice.selector.suffix}`}
1422 onPress={() => cite(choice)}
1423 />
1424 ))}
1425 </ListSection>
1426 </ScrollView>
1427 </Sheet>
1428 ) : null}
1429 </>
1430 );
1431 });
1432
1433 // Folds split first, so an artifact card inside a fold stays inside it.
1434 function AssistantMarkdownBlocks(props: {
1435 readonly markdown: string;
1436 readonly citationPath?: string;
1437 readonly onCiteText?: (text: string, path: string) => void;
1438 /** The reply's reference definitions, passed down by the enclosing fold. */
1439 readonly definitions?: ReadonlyArray<string> | undefined;
1440 readonly markdownStyles: MarkdownStyleSet;
1441 readonly linkHandlers: MarkdownLinkHandlers;
1442 readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
1443 readonly renderImage: MarkdownImageRenderer;
1444 readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
1445 readonly models: ReturnType<typeof useModelMentions>;
1446 }) {
1447 const m = useMessages();
1448 const { blocks, definitions } = useMemo(() => {
1449 const blocks = splitMarkdownDetails(props.markdown, m).map((block) =>
1450 block.kind === "details"
1451 ? block
1452 : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) },
1453 );
1454 const [first] = blocks;
1455 // A reply rendered as one document resolves its own references; skip the extra parse.
1456 const whole = blocks.length === 1 && first?.kind === "markdown" && first.segments.length === 1;
1457 return {
1458 blocks,
1459 definitions: props.definitions ?? (whole ? [] : markdownReferenceDefinitions(props.markdown)),
1460 };
1461 }, [m, props.markdown, props.definitions]);
1462 return blocks.map((block, blockIndex) => {
1463 if (block.kind === "details") {
1464 return (
1465 <MarkdownDetailsFold
1466 key={`details:${block.sourceOffset}`}
1467 summary={block.summary}
1468 initiallyOpen={block.open}
1469 >
1470 <AssistantMarkdownBlocks
1471 {...props}
1472 markdown={block.body}
1473 definitions={definitions}
1474 citationPath={`${props.citationPath ?? ""}${blockIndex}/`}
1475 />
1476 </MarkdownDetailsFold>
1477 );
1478 }
1479 return block.segments.map((segment, segmentIndex) => {
1480 const offset = block.sourceOffset + segment.sourceOffset;
1481 if (segment.kind === "artifact-template") {
1482 return (
1483 <ArtifactTemplateCard
1484 key={`artifact-template:${offset}`}
1485 template={segment.template}
1486 onUse={props.onUseArtifactTemplate}
1487 />
1488 );
1489 }
1490 if (segment.markdown.trim().length === 0) return null;
1491 return (
1492 <SelectableMarkdownText
1493 key={`markdown:${offset}`}
1494 markdown={renderCodexInlineDirectivesAsMarkdown(
1495 withReferenceDefinitions(segment.markdown, definitions),
1496 )}
1497 skills={props.skills}
1498 models={props.models}
1499 textStyle={props.markdownStyles.nativeTextStyle}
1500 onCiteText={
1501 props.onCiteText
1502 ? (text) =>
1503 props.onCiteText?.(
1504 text,
1505 `${props.citationPath ?? ""}${blockIndex}:${segmentIndex}`,
1506 )
1507 : undefined
1508 }
1509 {...props.linkHandlers}
1510 renderImage={props.renderImage}
1511 />
1512 );
1513 });
1514 });
1515 }
1516
1517 function MarkdownDetailsFold(props: {
1518 readonly summary: string;
1519 readonly initiallyOpen: boolean;
1520 readonly children: ReactNode;
1521 }) {
1522 const [expanded, setExpanded] = useState(props.initiallyOpen);
1523 const iconSubtleColor = useUniwindTheme()["--color-icon-subtle"];
1524 return (
1525 <View className="my-2 border-y border-border">
1526 <Pressable
1527 accessibilityRole="button"
1528 accessibilityLabel={props.summary}
1529 accessibilityState={{ expanded }}
1530 hitSlop={4}
1531 className="min-h-10 flex-row items-center gap-2 py-2"
1532 onPress={() => {
1533 void Haptics.selectionAsync();
1534 setExpanded((value) => !value);
1535 }}
1536 >
1537 <ThreadDisclosureChevron
1538 expanded={expanded}
1539 collapsedDirection="right"
1540 size={12}
1541 tintColor={iconSubtleColor}
1542 />
1543 <Text className="min-w-0 shrink font-t3-medium text-sm text-foreground">
1544 {props.summary}
1545 </Text>
1546 </Pressable>
1547 {expanded ? <View className="pb-3 pl-5">{props.children}</View> : null}
1548 </View>
1549 );
1550 }
1551
1552 function useMarkdownStyles(): MarkdownStyleSets {
1553 const { appearance } = useAppearancePreferences();
1554 const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);
1555 const theme = useUniwindTheme();
1556 const markdownBodyColor = theme["--color-md-body"];
1557 const markdownStrongColor = theme["--color-md-strong"];
1558 const markdownLinkColor = theme["--color-md-link"];
1559 const markdownBlockquoteBorder = theme["--color-md-blockquote-border"];
1560 const markdownCodeBg = theme["--color-md-code-bg"];
1561 const markdownCodeText = theme["--color-md-code-text"];
1562 const markdownInlineCodeText = theme["--color-foreground-secondary"];
1563 const markdownHrColor = theme["--color-md-hr"];
1564 // Native chip drawing parses opaque hex only, and this role is translucent.
1565 const contextChipBorderColor = flattenThemeColor(
1566 theme["--color-border"],
1567 theme["--color-user-bubble"],
1568 );
1569 const markdownUserBodyColor = theme["--color-user-bubble-foreground"];
1570 const markdownUserCodeBg = theme["--color-md-user-code-bg"];
1571 const markdownUserCodeText = theme["--color-md-user-code-text"];
1572 const markdownUserInlineCodeText = theme["--color-user-bubble-foreground-muted"];
1573 const markdownUserFenceBg = theme["--color-md-user-fence-bg"];
1574 const regularFontFamily = FONT_FAMILIES.regular;
1575 const boldFontFamily = FONT_FAMILIES.bold;
1576
1577 return {
1578 user: {
1579 nativeTextStyle: {
1580 color: markdownUserBodyColor,
1581 strongColor: markdownUserBodyColor,
1582 mutedColor: markdownUserBodyColor,
1583 linkColor: themeColorWithContrast(markdownLinkColor, theme["--color-user-bubble"]),
1584 inlineCodeColor: markdownUserInlineCodeText,
1585 codeColor: markdownUserCodeText,
1586 codeBackgroundColor: markdownUserCodeBg,
1587 codeBlockBackgroundColor: markdownUserFenceBg,
1588 fileTextColor: markdownUserBodyColor,
1589 quoteMarkerColor: markdownUserBodyColor,
1590 dividerColor: markdownUserBodyColor,
1591 contextChipBorderColor,
1592 fontSize: nativeMarkdownTypography.fontSize,
1593 lineHeight: nativeMarkdownTypography.lineHeight,
1594 headingFontSizes: nativeMarkdownTypography.headingFontSizes,
1595 fontFamily: regularFontFamily,
1596 headingFontFamily: boldFontFamily,
1597 boldFontFamily,
1598 },
1599 },
1600 assistant: {
1601 nativeTextStyle: {
1602 color: markdownBodyColor,
1603 strongColor: markdownStrongColor,
1604 mutedColor: markdownBodyColor,
1605 linkColor: markdownLinkColor,
1606 inlineCodeColor: markdownInlineCodeText,
1607 codeColor: markdownCodeText,
1608 codeBackgroundColor: markdownCodeBg,
1609 codeBlockBackgroundColor: markdownCodeBg,
1610 fileTextColor: markdownCodeText,
1611 quoteMarkerColor: markdownBlockquoteBorder,
1612 dividerColor: markdownHrColor,
1613 contextChipBorderColor,
1614 fontSize: nativeMarkdownTypography.fontSize,
1615 lineHeight: nativeMarkdownTypography.lineHeight,
1616 headingFontSizes: nativeMarkdownTypography.headingFontSizes,
1617 fontFamily: regularFontFamily,
1618 headingFontFamily: boldFontFamily,
1619 boldFontFamily,
1620 },
1621 },
1622 };
1623 }
1624
1625 /** Messages from other agents fold to one line so the user's own messages stay easy to find. */
1626 function AgentMessageFoldHeader(props: {
1627 readonly environmentId: EnvironmentId;
1628 readonly senderThreadId?: ThreadId;
1629 /** A linked environment's sender title, for when this client cannot reach it. */
1630 readonly senderTitle?: string;
1631 readonly summary: string;
1632 readonly expanded: boolean;
1633 readonly onToggle: () => void;
1634 readonly iconSubtleColor: ColorValue;
1635 }) {
1636 const senderShell = useQuietThreadShell(
1637 props.senderThreadId ? scopeThreadRef(props.environmentId, props.senderThreadId) : null,
1638 );
1639 const gt = useGT();
1640 const label = senderShell?.title.trim() || props.senderTitle?.trim() || gt("Agent");
1641 return (
1642 <Pressable
1643 accessibilityRole="button"
1644 accessibilityLabel={gt("{label}: {summary}", { label, summary: props.summary })}
1645 accessibilityHint={
1646 props.expanded
1647 ? gt("Double tap to hide the message.")
1648 : gt("Double tap to show the message.")
1649 }
1650 accessibilityState={{ expanded: props.expanded }}
1651 hitSlop={4}
1652 className="min-h-10 flex-row items-center gap-1.5 px-3.5 py-2"
1653 onPress={() => {
1654 void Haptics.selectionAsync();
1655 props.onToggle();
1656 }}
1657 >
1658 <SymbolView
1659 name="bubble.left.and.bubble.right"
1660 size={14}
1661 weight="medium"
1662 tintColorClassName="accent-user-bubble-foreground-muted"
1663 type="monochrome"
1664 />
1665 <Text
1666 numberOfLines={1}
1667 className="max-w-[50%] shrink-0 font-t3-medium text-sm text-user-bubble-foreground-muted"
1668 >
1669 {label}
1670 </Text>
1671 <Text numberOfLines={1} className="min-w-0 shrink text-sm text-user-bubble-foreground">
1672 {props.summary}
1673 </Text>
1674 <ThreadDisclosureChevron
1675 expanded={props.expanded}
1676 collapsedDirection="down"
1677 size={11}
1678 tintColor={props.iconSubtleColor}
1679 />
1680 </Pressable>
1681 );
1682 }
1683
1684 function OpenSenderThreadButton(props: {
1685 readonly environmentId: EnvironmentId;
1686 readonly senderThreadId: ThreadId;
1687 /** In a linked environment, shown only when this client is connected to it. */
1688 readonly linked?: boolean;
1689 }) {
1690 const openLinkedThread = useOpenLinkedThread();
1691 const linkedEnvironment = useEnvironmentPresentation(props.linked ? props.environmentId : null);
1692 if (props.linked && linkedEnvironment.presentation === null) return null;
1693 return (
1694 <Pressable
1695 accessibilityRole="link"
1696 hitSlop={6}
1697 onPress={() =>
1698 openLinkedThread({
1699 environmentId: String(props.environmentId),
1700 threadId: String(props.senderThreadId),
1701 })
1702 }
1703 >
1704 <Text className="font-t3-medium text-xs text-foreground-secondary">
1705 <T>Open thread</T>
1706 </Text>
1707 </Pressable>
1708 );
1709 }
1710
1711 /** Automation prompts are long, repeated runbooks; a folded bubble keeps them out of the way. */
1712 function ThreadAutomationMessageRow(props: {
1713 readonly environmentId: EnvironmentId;
1714 readonly text: string;
1715 readonly context?: OrchestrationMessageContext;
1716 readonly scheduledTaskId: ScheduledTaskId | undefined;
1717 readonly timestampLabel: string;
1718 readonly expanded: boolean;
1719 readonly onToggle: () => void;
1720 readonly bubbleColor: ColorValue;
1721 readonly bubbleMaxWidth: number | "85%";
1722 readonly contentMaxWidth: number;
1723 readonly iconSubtleColor: ColorValue;
1724 readonly markdownStyles: MarkdownStyleSet;
1725 readonly reviewCommentColors: ReviewCommentColors;
1726 readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
1727 readonly linkHandlers: MarkdownLinkHandlers;
1728 readonly renderImage: MarkdownImageRenderer;
1729 }) {
1730 const gt = useGT();
1731 const navigation = useNavigation();
1732 const tasks = useEnvironmentQuery(
1733 props.scheduledTaskId
1734 ? serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} })
1735 : null,
1736 );
1737 const taskTitle = tasks.data?.tasks.find((task) => task.id === props.scheduledTaskId)?.title;
1738 const summary = taskTitle ?? props.text.trim().split(/\r?\n/, 1)[0] ?? "";
1739
1740 return (
1741 <View className="mb-2 items-end">
1742 <View
1743 className="min-w-0 rounded-[20px]"
1744 style={{
1745 backgroundColor: props.bubbleColor,
1746 maxWidth: props.bubbleMaxWidth,
1747 ...(props.expanded ? { width: props.bubbleMaxWidth } : null),
1748 }}
1749 >
1750 <Pressable
1751 accessibilityRole="button"
1752 accessibilityLabel={gt("Automation: {summary}", { summary })}
1753 accessibilityHint={
1754 props.expanded
1755 ? gt("Double tap to hide the prompt.")
1756 : gt("Double tap to show the prompt.")
1757 }
1758 accessibilityState={{ expanded: props.expanded }}
1759 hitSlop={4}
1760 className="min-h-10 flex-row items-center gap-1.5 px-3.5 py-2"
1761 onPress={() => {
1762 void Haptics.selectionAsync();
1763 props.onToggle();
1764 }}
1765 >
1766 <SymbolView
1767 name="calendar.badge.clock"
1768 size={14}
1769 weight="medium"
1770 tintColorClassName="accent-user-bubble-foreground-muted"
1771 type="monochrome"
1772 />
1773 <Text className="font-t3-medium text-sm text-user-bubble-foreground-muted">
1774 <T>Automation</T>
1775 </Text>
1776 <Text numberOfLines={1} className="min-w-0 shrink text-sm text-user-bubble-foreground">
1777 {summary}
1778 </Text>
1779 <ThreadDisclosureChevron
1780 expanded={props.expanded}
1781 collapsedDirection="down"
1782 size={11}
1783 tintColor={props.iconSubtleColor}
1784 />
1785 </Pressable>
1786 {props.expanded ? (
1787 <View className="px-3.5 pb-2.5">
1788 <MarkdownImageAvailableWidthContext value={props.contentMaxWidth}>
1789 <UserMessageContent
1790 text={props.text}
1791 environmentId={props.environmentId}
1792 context={props.context}
1793 markdownStyles={props.markdownStyles}
1794 reviewCommentColors={props.reviewCommentColors}
1795 skills={props.skills}
1796 linkHandlers={props.linkHandlers}
1797 renderImage={props.renderImage}
1798 />
1799 </MarkdownImageAvailableWidthContext>
1800 </View>
1801 ) : null}
1802 </View>
1803 {props.expanded ? (
1804 <View className="mt-1 flex-row items-center justify-end gap-2 pr-0.5">
1805 {props.scheduledTaskId ? (
1806 <Pressable
1807 accessibilityRole="link"
1808 hitSlop={6}
1809 onPress={() => openSettings(navigation, "SettingsScheduledTasks")}
1810 >
1811 <Text className="font-t3-medium text-xs text-foreground-secondary">
1812 <T>Open automation</T>
1813 </Text>
1814 </Pressable>
1815 ) : null}
1816 <Text className="font-t3-medium text-xs tabular-nums text-foreground-secondary">
1817 {props.timestampLabel}
1818 </Text>
1819 <UserMessageCopyButton
1820 text={props.text}
1821 onCopy={undefined}
1822 tintColor={props.iconSubtleColor}
1823 />
1824 </View>
1825 ) : null}
1826 </View>
1827 );
1828 }
1829
1830 /** Leads with why T3 Code compacted, when it did so without being asked. */
1831 function compactionLabel(
1832 label: string,
1833 title: string | undefined,
1834 item: OrchestrationV2ProjectedTurnItem["item"],
1835 m: ReturnType<typeof useMessages>,
1836 ) {
1837 const compacted =
1838 item.type === "compaction" &&
1839 item.status !== "failed" &&
1840 item.status !== "cancelled" &&
1841 item.status !== "interrupted" &&
1842 !isOrchestrationV2WorkActive(item.status);
1843 const tokens = compacted ? contextCompactionTokenCounts(item) : null;
1844 const text =
1845 title === undefined || !compacted
1846 ? label
1847 : tokens
1848 ? m(msg("{title} {before} → {after} tokens", { title, ...tokens }))
1849 : title;
1850 // Non-breaking spaces keep "549K → 16.8K tokens" on one line when the label wraps.
1851 return text.replace(/ (→|tokens)/g, "\u00A0$1").replace(/→ /g, "→\u00A0");
1852 }
1853
1854 function RunFoldWorking(props: {
1855 environmentId: EnvironmentId;
1856 startedAt: string;
1857 rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1858 }) {
1859 const nowMs = toServerClock(props.environmentId, useVisibleSecondClock(true));
1860 const seconds = Math.floor((nowMs - Date.parse(props.startedAt)) / 1_000);
1861 const gt = useGT();
1862 const messages = useMessages();
1863 return (
1864 <View
1865 className="min-h-11 min-w-0 flex-1 flex-row items-center"
1866 style={{ minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, props.rowSizing.estimatedRowHeight) }}
1867 >
1868 <Text
1869 key={props.rowSizing.textSizeKey}
1870 numberOfLines={1}
1871 className="shrink font-t3-medium text-sm tabular-nums text-foreground-muted"
1872 >
1873 {gt("Working for {duration}", {
1874 duration:
1875 seconds > 0
1876 ? formatDuration(seconds * 1_000, messages)
1877 : gt("{seconds}s", { seconds: 0 }),
1878 })}
1879 </Text>
1880 </View>
1881 );
1882 }
1883
1884 function RunFoldButton({
1885 entry,
1886 environmentId,
1887 threadId,
1888 onToggle,
1889 rowSizing,
1890 iconColor,
1891 }: {
1892 entry: Extract<ThreadFeedEntry, { type: "run-fold" }>;
1893 environmentId: EnvironmentId;
1894 threadId: ThreadId;
1895 onToggle: (runId: RunId) => void;
1896 rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1897 iconColor: ColorValue;
1898 }) {
1899 const gt = useGT();
1900 const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false });
1901 const anchorsKey = entry.deferredWorkItemIds?.join("\n") ?? "";
1902 const [failed, setFailed] = useState(false);
1903 const load = () => {
1904 if (!anchorsKey) return;
1905 void Promise.all(
1906 anchorsKey
1907 .split("\n")
1908 .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),
1909 ).then((results) =>
1910 setFailed(
1911 results.some((result) => result._tag === "Failure" || result.value._tag === "error"),
1912 ),
1913 );
1914 };
1915 const loadOnExpand = useEffectEvent(load);
1916 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount.
1917 useEffect(() => {
1918 if (entry.expanded && anchorsKey && environmentId && threadId) loadOnExpand();
1919 }, [entry.expanded, anchorsKey, environmentId, threadId]);
1920 const error = anchorsKey && failed ? gt("Couldn't load work. Tap to retry.") : null;
1921 const loading = entry.expanded && anchorsKey !== "" && !failed;
1922 const toggle = () => {
1923 setFailed(false);
1924 if (error && entry.expanded) load();
1925 else onToggle(entry.runId);
1926 };
1927
1928 return (
1929 <View className="min-w-0 flex-1">
1930 <Pressable
1931 accessibilityRole="button"
1932 accessibilityState={{ expanded: entry.expanded, busy: loading }}
1933 onPress={toggle}
1934 hitSlop={4}
1935 className="min-h-11 min-w-0 flex-1 flex-row items-center gap-2"
1936 style={{ minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, rowSizing.estimatedRowHeight) }}
1937 >
1938 <Text
1939 key={rowSizing.textSizeKey}
1940 numberOfLines={1}
1941 className="shrink font-t3-medium text-sm tabular-nums text-foreground-muted"
1942 >
1943 {entry.label}
1944 {error ? ` · ${error}` : ""}
1945 </Text>
1946 <ThreadDisclosureChevron
1947 expanded={entry.expanded}
1948 collapsedDirection="right"
1949 size={15}
1950 tintColor={iconColor}
1951 />
1952 </Pressable>
1953 {loading ? (
1954 <View
1955 accessible={false}
1956 importantForAccessibility="no-hide-descendants"
1957 className="gap-2 px-1 pb-2"
1958 >
1959 {(["40%", "60%", "33%"] as const).map((width) => (
1960 <View key={width} className="flex-row items-center gap-2">
1961 <View className="size-3 rounded bg-subtle-strong" />
1962 <View className="h-2.5 rounded-full bg-subtle-strong" style={{ width }} />
1963 </View>
1964 ))}
1965 </View>
1966 ) : null}
1967 </View>
1968 );
1969 }
1970
1971 function renderFeedEntry(
1972 info: { item: ThreadFeedRow; index: number },
1973 props: Pick<
1974 ThreadFeedProps,
1975 | "environmentId"
1976 | "onUseArtifactTemplate"
1977 | "onCiteAssistantText"
1978 | "skills"
1979 | "dispatchingMessageId"
1980 | "onEditPendingMessage"
1981 | "threadId"
1982 | "workspaceRoot"
1983 | "worktreeSetup"
1984 > & {
1985 /** The fold row of the turn the worktree setup handed off to. */
1986 readonly setupFoldRowId: string | null;
1987 readonly setupDetailsOpen: boolean;
1988 readonly onOpenSetupDetails: () => void;
1989 readonly pendingFoldMessageId: string | null;
1990 readonly formatMessageTime: (input: string) => string;
1991 readonly copiedRowId: string | null;
1992 readonly expandedWorkRows: Record<string, boolean>;
1993 readonly workRowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
1994 readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
1995 readonly terminalAssistantMessageIds: ReadonlySet<string>;
1996 readonly unsettledTurnId: RunId | null;
1997 readonly compactionLabelsByEntryId: ReadonlyMap<string, { title: string; compacting: string }>;
1998 readonly failedRunIds: ReadonlySet<RunId>;
1999 readonly onCopyWorkRow: (rowId: string, value: string) => void;
2000 readonly onToggleWorkGroup: (groupId: string, anchorKey?: string) => void;
2001 readonly onToggleWorkRow: (rowId: string, anchorKey?: string, groupId?: string) => void;
2002 readonly onToggleUserMessage: (rowId: string, anchorKey: string) => void;
2003 readonly onToggleTurnFold: (runId: RunId) => void;
2004 readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void;
2005 readonly onPressPreview: (source: FilePreviewSource) => void;
2006 readonly onPlaybackStart: () => void;
2007 readonly markdownLinkHandlers: MarkdownLinkHandlers;
2008 readonly renderMarkdownImage: MarkdownImageRenderer;
2009 readonly renderViewedImage: MarkdownImageRenderer;
2010 readonly renderReasoning: (text: string) => ReactNode;
2011 readonly iconSubtleColor: string | import("react-native").ColorValue;
2012 readonly replyActionSize: { readonly button: number; readonly icon: number };
2013 readonly screenColor: string;
2014 readonly userBubbleColor: string | import("react-native").ColorValue;
2015 readonly markdownStyles: MarkdownStyleSets;
2016 readonly reviewCommentColors: ReviewCommentColors;
2017 readonly reviewCommentBubbleWidth: number;
2018 readonly themeAppearance: "light" | "dark";
2019 readonly duoColumns: boolean;
2020 readonly userBubbleMaxWidth: number;
2021 readonly markdownContentWidth: number;
2022 readonly contentWidth: number;
2023 readonly threadTitle: string;
2024 readonly workflowOpening: WorkflowOpening | null;
2025 readonly userMessageGrouping: GroupedThreadFeedRow["userMessageGrouping"];
2026 readonly m: ReturnType<typeof useMessages>;
2027 },
2028 ) {
2029 const entry = info.item;
2030 const { markdownStyles, iconSubtleColor, userBubbleColor, m } = props;
2031
2032 if (entry.type === "guest-pending") {
2033 return (
2034 <ThreadGuestPendingMessage
2035 threadRef={scopeThreadRef(props.environmentId, props.threadId)}
2036 guestName={entry.guestName}
2037 message={entry.message}
2038 bubbleMaxWidth={props.duoColumns ? "85%" : props.userBubbleMaxWidth}
2039 renderAttachments={(attachments) => (
2040 <MessageAttachmentList
2041 attachments={attachments}
2042 environmentId={props.environmentId}
2043 onPressPreview={props.onPressPreview}
2044 onPlaybackStart={props.onPlaybackStart}
2045 />
2046 )}
2047 />
2048 );
2049 }
2050
2051 if (entry.type === "pending-fold") {
2052 return (
2053 <View className="mb-1 flex-row items-center border-b border-border-subtle px-2">
2054 <View
2055 className="min-h-11 min-w-0 flex-1 flex-row items-center"
2056 style={{
2057 minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, props.workRowSizing.estimatedRowHeight),
2058 }}
2059 >
2060 <Text
2061 key={props.workRowSizing.textSizeKey}
2062 numberOfLines={1}
2063 className="shrink font-t3-medium text-sm text-foreground-muted"
2064 >
2065 {m(msg("Pending", { $context: "message not yet sent" }))}
2066 </Text>
2067 </View>
2068 </View>
2069 );
2070 }
2071
2072 if (entry.type === "run-fold") {
2073 return (
2074 <View className="mb-1 flex-row items-center border-b border-border-subtle px-2">
2075 {entry.workingSince ? (
2076 <RunFoldWorking
2077 environmentId={props.environmentId}
2078 startedAt={entry.workingSince}
2079 rowSizing={props.workRowSizing}
2080 />
2081 ) : (
2082 <RunFoldButton
2083 key={entry.id}
2084 entry={entry}
2085 environmentId={props.environmentId}
2086 threadId={props.threadId}
2087 onToggle={props.onToggleTurnFold}
2088 rowSizing={props.workRowSizing}
2089 iconColor={iconSubtleColor}
2090 />
2091 )}
2092 {props.worktreeSetup && entry.id === props.setupFoldRowId ? (
2093 <WorktreeSetupFoldChip
2094 {...props.worktreeSetup}
2095 detailsOpen={props.setupDetailsOpen}
2096 onOpenDetails={props.onOpenSetupDetails}
2097 />
2098 ) : null}
2099 {entry.checkpointSummary ? (
2100 <TurnDiffStat
2101 checkpoint={entry.checkpointSummary}
2102 onOpenTurnDiff={props.onOpenTurnDiff}
2103 />
2104 ) : null}
2105 </View>
2106 );
2107 }
2108
2109 if (entry.type === "thinking") {
2110 return (
2111 <ThreadThinkingRow
2112 rowSizing={props.workRowSizing}
2113 iconSubtleColor={iconSubtleColor}
2114 label={entry.label}
2115 providerStartingLabel={entry.providerStartingLabel}
2116 />
2117 );
2118 }
2119
2120 if (entry.type === "html-render") {
2121 return (
2122 <ThreadHtmlRender
2123 environmentId={props.environmentId}
2124 threadId={props.threadId}
2125 render={entry.render}
2126 frameWidth={props.contentWidth}
2127 iconColor={iconSubtleColor}
2128 />
2129 );
2130 }
2131
2132 if (entry.type === "sent-message") {
2133 return (
2134 <View className="mb-1 px-1">
2135 <MarkdownImageAvailableWidthContext value={props.markdownContentWidth}>
2136 <AssistantMarkdownContent
2137 markdown={entry.text}
2138 environmentId={props.environmentId}
2139 markdownStyles={markdownStyles.assistant}
2140 linkHandlers={props.markdownLinkHandlers}
2141 onUseArtifactTemplate={props.onUseArtifactTemplate}
2142 renderImage={props.renderMarkdownImage}
2143 skills={props.skills}
2144 />
2145 </MarkdownImageAvailableWidthContext>
2146 </View>
2147 );
2148 }
2149
2150 if (entry.type === "viewed-images") {
2151 const thumbnailWidth = Math.floor((props.contentWidth - VIEWED_IMAGE_GAP) / 2);
2152 return (
2153 <View className="flex-row flex-wrap pb-2" style={{ gap: VIEWED_IMAGE_GAP }}>
2154 {entry.paths.map((path) => (
2155 <View key={path} style={{ width: thumbnailWidth }}>
2156 {props.renderViewedImage({ href: path, alt: null, title: null })}
2157 </View>
2158 ))}
2159 </View>
2160 );
2161 }
2162
2163 if (entry.type === "mcp-app") {
2164 return (
2165 <ThreadMcpApp
2166 key={entry.app.attachmentId}
2167 environmentId={props.environmentId}
2168 threadId={entry.sourceThreadId}
2169 conversationThreadId={props.threadId}
2170 itemId={entry.itemId}
2171 revision={entry.revision}
2172 app={entry.app}
2173 width={props.contentWidth}
2174 />
2175 );
2176 }
2177
2178 if (entry.type === "work-toggle") {
2179 return (
2180 <ThreadWorkGroupToggle
2181 environmentId={props.environmentId}
2182 rowSizing={props.workRowSizing}
2183 expanded={entry.expanded}
2184 hiddenCount={entry.hiddenCount}
2185 iconSubtleColor={iconSubtleColor}
2186 summary={entry.summary}
2187 summaryKind={entry.summaryKind}
2188 themeAppearance={props.themeAppearance}
2189 toolSurface={entry.toolSurface}
2190 toolIcon={entry.toolIcon}
2191 summaryToolIcon={entry.summaryToolIcon}
2192 hasFailure={entry.hasFailure}
2193 shimmer={entry.shimmer}
2194 thought={entry.thought}
2195 trailing={
2196 entry.checkpointSummary ? (
2197 <TurnDiffStat
2198 checkpoint={entry.checkpointSummary}
2199 onOpenTurnDiff={props.onOpenTurnDiff}
2200 />
2201 ) : null
2202 }
2203 onToggle={() => props.onToggleWorkGroup(entry.groupId, entry.id)}
2204 />
2205 );
2206 }
2207
2208 if (entry.type === "activity-group" && isContextHandoffActivityGroup(entry)) {
2209 return (
2210 <ThreadHandoffRow
2211 environmentId={props.environmentId}
2212 projectedItem={entry.activities[0]!.projectedItem}
2213 iconColor={iconSubtleColor}
2214 surfaceColor={props.screenColor}
2215 />
2216 );
2217 }
2218
2219 if (entry.type === "activity-group" && isSecretRequestActivityGroup(entry)) {
2220 return (
2221 <SecretRequestCard
2222 environmentId={props.environmentId}
2223 projectedItem={entry.activities[0]!.projectedItem}
2224 iconColor={iconSubtleColor}
2225 />
2226 );
2227 }
2228
2229 if (entry.type === "activity-group" && isLinkRequestActivityGroup(entry)) {
2230 return (
2231 <LinkRequestCard
2232 environmentId={props.environmentId}
2233 projectedItem={entry.activities[0]!.projectedItem}
2234 iconColor={iconSubtleColor}
2235 />
2236 );
2237 }
2238
2239 if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
2240 const label = entry.activities[0]!.summary;
2241 const item = entry.activities[0]!.projectedItem.item;
2242 const active =
2243 props.unsettledTurnId !== null &&
2244 entry.runId === props.unsettledTurnId &&
2245 item.status === "running";
2246 const labels = props.compactionLabelsByEntryId.get(entry.id);
2247 const failure =
2248 item.type === "compaction" && item.status === "failed" ? item.summary?.trim() : undefined;
2249 return (
2250 <ThreadContextDivider
2251 label={
2252 failure
2253 ? `${label} · ${failure}`
2254 : active && labels
2255 ? labels.compacting
2256 : compactionLabel(label, labels?.title, item, m)
2257 }
2258 icon={
2259 item.status === "failed" ? "exclamationmark.circle" : "arrow.down.right.and.arrow.up.left"
2260 }
2261 iconColor={iconSubtleColor}
2262 active={active}
2263 failed={item.status === "failed"}
2264 />
2265 );
2266 }
2267
2268 if (entry.type === "message") {
2269 const { message } = entry;
2270 const isUser = message.role === "user";
2271 const presentation = resolveUserMessagePresentation(message);
2272 const renderedText = presentation.text;
2273 const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
2274 const timestampLabel = props.formatMessageTime(isUser ? message.createdAt : message.updatedAt);
2275 const attachments = message.attachments ?? [];
2276 const hasReviewCommentContext = presentation.text.includes("<review_comment");
2277 // Android does not reposition children after maxWidth clamps bubbles; definite width prevents wide-block overlap.
2278 const hasWideBlock = hasWideMarkdownBlock(renderedText, WIDE_MARKDOWN_BLOCK_OPTIONS);
2279 const assistantTurnStillInProgress =
2280 message.role === "assistant" &&
2281 props.unsettledTurnId !== null &&
2282 message.runId === props.unsettledTurnId;
2283 const showAssistantMeta =
2284 message.role === "assistant" &&
2285 props.terminalAssistantMessageIds.has(message.id) &&
2286 !assistantTurnStillInProgress &&
2287 !message.streaming;
2288
2289 if (isUser && props.workflowOpening?.messageId === message.id) {
2290 return (
2291 <ThreadWorkflowOpening
2292 environmentId={props.environmentId}
2293 threadId={props.threadId}
2294 opening={props.workflowOpening}
2295 />
2296 );
2297 }
2298 if (isCompactionCommandFeedEntry(entry)) {
2299 // Stands in for the compaction item until the provider reports it.
2300 const active = props.unsettledTurnId !== null && message.runId === props.unsettledTurnId;
2301 const reason = idleCompactionOf(message);
2302 return (
2303 <ThreadContextDivider
2304 label={
2305 !active
2306 ? m(msg("Context compaction"))
2307 : reason === undefined
2308 ? m(msg("Compacting context"))
2309 : props.m(IDLE_COMPACTING_LABELS[reason])
2310 }
2311 icon="arrow.down.right.and.arrow.up.left"
2312 iconColor={iconSubtleColor}
2313 active={active}
2314 />
2315 );
2316 }
2317 if (isUser && presentation.attribution === "automation") {
2318 const rowId = `automation:${message.id}`;
2319 return (
2320 <ThreadAutomationMessageRow
2321 environmentId={props.environmentId}
2322 text={presentation.text}
2323 context={message.context}
2324 scheduledTaskId={presentation.scheduledTaskId}
2325 timestampLabel={timestampLabel}
2326 expanded={props.expandedWorkRows[rowId] ?? false}
2327 onToggle={() => props.onToggleWorkRow(rowId, entry.id)}
2328 bubbleColor={userBubbleColor}
2329 bubbleMaxWidth={props.duoColumns ? "85%" : props.userBubbleMaxWidth}
2330 contentMaxWidth={props.userBubbleMaxWidth - USER_BUBBLE_HORIZONTAL_PADDING * 2}
2331 iconSubtleColor={iconSubtleColor}
2332 markdownStyles={markdownStyles.user}
2333 reviewCommentColors={props.reviewCommentColors}
2334 skills={props.skills}
2335 linkHandlers={props.markdownLinkHandlers}
2336 renderImage={props.renderMarkdownImage}
2337 />
2338 );
2339 }
2340 if (isUser) {
2341 const enterAnimated = isFreshTimestamp(message.createdAt);
2342 const foldRowId = presentation.attribution === "agent" ? `agent:${message.id}` : null;
2343 // A linked environment's agent sent it from a thread there.
2344 const senderRef =
2345 message.linkedSender ??
2346 (message.senderThreadId
2347 ? scopeThreadRef(props.environmentId, message.senderThreadId)
2348 : null);
2349 const foldExpanded = foldRowId !== null && (props.expandedWorkRows[foldRowId] ?? false);
2350 const bubbleBodyVisible = foldRowId === null || foldExpanded;
2351 const intentBadge = props.userMessageGrouping.continuesSteer
2352 ? null
2353 : resolveUserMessageIntentBadge(
2354 message.inputIntent,
2355 message.projectedItem?.item.status === "pending",
2356 props.m,
2357 );
2358 const referenceIds = new Set(
2359 collectComposerContextReferences(message.text).map((reference) => reference.contextId),
2360 );
2361 const inlineAttachmentIds = new Set(
2362 message.context?.records.flatMap((record) =>
2363 "attachmentId" in record && referenceIds.has(record.contextId)
2364 ? [record.attachmentId]
2365 : [],
2366 ),
2367 );
2368 const standaloneMedia = foldRowId === null && presentation.attribution !== "guest";
2369 const mediaAttachments = standaloneMedia ? attachments.filter(isMediaAttachment) : [];
2370 const visibleAttachments = attachments.filter(
2371 (attachment) =>
2372 !(standaloneMedia && isMediaAttachment(attachment)) &&
2373 (isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id)),
2374 );
2375 const pendingAttachments = entry.pendingMessage?.attachments ?? [];
2376 const pendingMedia = standaloneMedia ? pendingAttachments.filter(isMediaAttachment) : [];
2377 const pendingBubbleAttachments = standaloneMedia
2378 ? pendingAttachments.filter(
2379 (attachment) =>
2380 !isMediaAttachment(attachment) && !inlineAttachmentIds.has(attachment.id),
2381 )
2382 : pendingAttachments;
2383 const fileCards = standaloneMedia
2384 ? resolveUserMessageFileCards({
2385 text: presentation.text,
2386 attachments: attachments.length > 0 ? attachments : pendingAttachments,
2387 context: message.context,
2388 })
2389 : null;
2390 const hasBubble =
2391 fileCards === null &&
2392 (foldRowId !== null ||
2393 presentation.text.trim().length > 0 ||
2394 visibleAttachments.length + pendingBubbleAttachments.length > 0);
2395 return (
2396 <Animated.View
2397 // A prompt sits close to its own response; the answer's margin separates turns.
2398 className={cn("items-end", props.userMessageGrouping.groupedWithNext ? "mb-1" : "mb-2")}
2399 {...(enterAnimated ? { entering: FadeInDown.duration(220) } : {})}
2400 >
2401 {presentation.attribution === "t3code" ? (
2402 <Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
2403 {m(msg("Sent by T3 Code"))}
2404 </Text>
2405 ) : null}
2406 {presentation.guestName !== undefined ? (
2407 <GuestMessageName name={presentation.guestName} />
2408 ) : null}
2409 {mediaAttachments.length + pendingMedia.length > 0 ? (
2410 <View
2411 className={hasBubble ? "mb-2" : undefined}
2412 style={{ width: props.duoColumns ? "85%" : props.userBubbleMaxWidth }}
2413 >
2414 <UserMessageMedia
2415 messageId={message.id}
2416 attachments={mediaAttachments}
2417 pendingAttachments={pendingMedia}
2418 environmentId={props.environmentId}
2419 maxWidth={props.userBubbleMaxWidth}
2420 onPressPreview={props.onPressPreview}
2421 onPlaybackStart={props.onPlaybackStart}
2422 />
2423 </View>
2424 ) : null}
2425 {fileCards ? (
2426 <View
2427 className="items-end"
2428 style={{ maxWidth: props.duoColumns ? "85%" : props.userBubbleMaxWidth }}
2429 >
2430 {fileCards.map((file) => {
2431 const pendingFile = pendingAttachments.find(
2432 (attachment) => attachment.id === file.id,
2433 );
2434 return (
2435 <MessageAttachmentFile
2436 key={file.id}
2437 environmentId={props.environmentId}
2438 attachment={
2439 pendingFile?.uploadedAttachmentId
2440 ? { ...file, id: pendingFile.uploadedAttachmentId }
2441 : file
2442 }
2443 available={
2444 pendingFile === undefined || pendingFile.uploadedAttachmentId !== undefined
2445 }
2446 onPressPreview={props.onPressPreview}
2447 onPlaybackStart={props.onPlaybackStart}
2448 standaloneFile
2449 />
2450 );
2451 })}
2452 </View>
2453 ) : null}
2454 {hasBubble ? (
2455 <View
2456 className="min-w-0 rounded-[20px]"
2457 style={{
2458 backgroundColor: userBubbleColor,
2459 maxWidth: props.duoColumns ? "85%" : props.userBubbleMaxWidth,
2460 ...(!bubbleBodyVisible
2461 ? null
2462 : hasReviewCommentContext
2463 ? { width: props.reviewCommentBubbleWidth }
2464 : hasWideBlock || foldExpanded
2465 ? { width: props.duoColumns ? "85%" : props.userBubbleMaxWidth }
2466 : null),
2467 }}
2468 >
2469 {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
2470 {foldRowId !== null ? (
2471 <AgentMessageFoldHeader
2472 environmentId={senderRef?.environmentId ?? props.environmentId}
2473 senderThreadId={senderRef?.threadId}
2474 {...(message.linkedSender ? { senderTitle: message.linkedSender.title } : {})}
2475 summary={
2476 replaceComposerContextReferences(presentation.text, (ref) => ref.label)
2477 .split(/\r?\n/)
2478 .find((line) => line.trim().length > 0)
2479 ?.trim() ?? ""
2480 }
2481 expanded={foldExpanded}
2482 onToggle={() => props.onToggleWorkRow(foldRowId, entry.id)}
2483 iconSubtleColor={iconSubtleColor}
2484 />
2485 ) : null}
2486 {bubbleBodyVisible ? (
2487 <View className={cn("gap-2 px-3.5 pb-2.5", foldRowId === null && "pt-2.5")}>
2488 {pendingBubbleAttachments.map((attachment) =>
2489 attachment.type === "image" && attachment.uploadedAttachmentId ? (
2490 <MessageAttachmentImage
2491 key={attachment.id}
2492 environmentId={props.environmentId}
2493 attachmentId={attachment.uploadedAttachmentId}
2494 name={attachment.name}
2495 mimeType={attachment.mimeType}
2496 className="h-[140px] w-[180px] rounded-[14px]"
2497 onPressPreview={props.onPressPreview}
2498 />
2499 ) : attachment.type === "image" ? (
2500 <Pressable
2501 key={attachment.id}
2502 accessibilityRole="imagebutton"
2503 accessibilityLabel={m(msg("Open {name}", { name: attachment.name }))}
2504 onPress={() => {
2505 const source = composerImageGallery([attachment])[0];
2506 if (source)
2507 props.onPressPreview({
2508 ...source,
2509 gallery: composerImageGallery(
2510 entry.pendingMessage?.attachments ?? [],
2511 props.environmentId,
2512 ),
2513 });
2514 }}
2515 >
2516 <Image
2517 source={{ uri: attachment.previewUri }}
2518 style={{ width: 180, height: 140, borderRadius: 14 }}
2519 />
2520 </Pressable>
2521 ) : (
2522 <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
2523 ),
2524 )}
2525 {/* An empty container still takes a gap, which pads every attachment-free bubble. */}
2526 {visibleAttachments.length > 0 ? (
2527 <View
2528 className={inlineAttachmentIds.size ? "flex-row flex-wrap gap-2" : "gap-2"}
2529 >
2530 {visibleAttachments.map((attachment) => {
2531 return isImageAttachment(attachment) ? (
2532 <MessageAttachmentImage
2533 key={attachment.id}
2534 environmentId={props.environmentId}
2535 attachmentId={attachment.id}
2536 name={attachment.name}
2537 mimeType={attachment.mimeType}
2538 className={
2539 inlineAttachmentIds.size
2540 ? "h-24 w-24 rounded-[14px] bg-user-bubble-foreground/15"
2541 : "aspect-[1.3] w-full rounded-[14px] bg-user-bubble-foreground/15"
2542 }
2543 onPressPreview={props.onPressPreview}
2544 />
2545 ) : isFileAttachment(attachment) ? (
2546 <MessageAttachmentFile
2547 key={attachment.id}
2548 environmentId={props.environmentId}
2549 attachment={attachment}
2550 onPressPreview={props.onPressPreview}
2551 onPlaybackStart={props.onPlaybackStart}
2552 />
2553 ) : (
2554 <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
2555 );
2556 })}
2557 </View>
2558 ) : null}
2559 {presentation.text.trim().length > 0 ? (
2560 <MarkdownImageAvailableWidthContext
2561 value={props.userBubbleMaxWidth - USER_BUBBLE_HORIZONTAL_PADDING * 2}
2562 >
2563 <CollapsibleUserMessageBody
2564 collapsible={foldRowId === null}
2565 expanded={props.expandedWorkRows[`message:${message.id}`] ?? false}
2566 onToggle={() =>
2567 props.onToggleUserMessage(`message:${message.id}`, entry.id)
2568 }
2569 bubbleColor={userBubbleColor}
2570 >
2571 <UserMessageContent
2572 text={renderedText}
2573 environmentId={props.environmentId}
2574 context={message.context}
2575 markdownStyles={styles}
2576 reviewCommentColors={props.reviewCommentColors}
2577 skills={props.skills}
2578 linkHandlers={props.markdownLinkHandlers}
2579 renderImage={props.renderMarkdownImage}
2580 />
2581 </CollapsibleUserMessageBody>
2582 </MarkdownImageAvailableWidthContext>
2583 ) : null}
2584 </View>
2585 ) : null}
2586 </View>
2587 ) : null}
2588 {bubbleBodyVisible ? (
2589 <View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
2590 {foldRowId !== null && senderRef ? (
2591 <OpenSenderThreadButton
2592 environmentId={senderRef.environmentId}
2593 senderThreadId={senderRef.threadId}
2594 linked={message.linkedSender !== undefined}
2595 />
2596 ) : null}
2597 {intentBadge ? (
2598 <View
2599 accessible
2600 accessibilityLabel={intentBadge.accessibilityLabel}
2601 className="flex-row items-center gap-1"
2602 >
2603 <SymbolView name="arrow.uturn.forward" size={12} tintColor={iconSubtleColor} />
2604 <Text className="font-t3-medium text-xs text-foreground-secondary">
2605 {intentBadge.label}
2606 </Text>
2607 </View>
2608 ) : null}
2609 {intentBadge ? (
2610 <Text
2611 accessible={false}
2612 accessibilityElementsHidden
2613 importantForAccessibility="no"
2614 className="font-t3-medium text-xs text-foreground-secondary"
2615 >
2616 ·
2617 </Text>
2618 ) : null}
2619 <Text className="font-t3-medium text-xs tabular-nums text-foreground-secondary">
2620 {entry.pendingMessage &&
2621 !entry.acknowledged &&
2622 entry.id !== props.pendingFoldMessageId
2623 ? m(msg("Pending", { $context: "message not yet sent" }))
2624 : timestampLabel}
2625 </Text>
2626 {props.onEditPendingMessage !== null &&
2627 entry.pendingMessage &&
2628 !entry.acknowledged &&
2629 !entry.pendingMessage.creation &&
2630 entry.pendingMessage.messageId !== props.dispatchingMessageId ? (
2631 <Pressable
2632 accessibilityRole="button"
2633 accessibilityLabel={m(msg("Edit pending message"))}
2634 hitSlop={8}
2635 className="size-7 items-center justify-center"
2636 onPress={() => {
2637 if (entry.pendingMessage && props.onEditPendingMessage) {
2638 props.onEditPendingMessage(entry.pendingMessage);
2639 }
2640 }}
2641 >
2642 <SymbolView name="pencil" size={14} tintColor={iconSubtleColor} />
2643 </Pressable>
2644 ) : null}
2645 {presentation.text.trim().length > 0 ? (
2646 <UserMessageCopyButton
2647 text={presentation.text}
2648 onCopy={
2649 message.context && presentation.attribution !== "guest"
2650 ? () =>
2651 writeComposerContextClipboard(message.text, {
2652 version: 1,
2653 source: { environmentId: props.environmentId, messageId: message.id },
2654 records: message.context!.records,
2655 })
2656 : undefined
2657 }
2658 tintColor={iconSubtleColor}
2659 />
2660 ) : null}
2661 </View>
2662 ) : null}
2663 </Animated.View>
2664 );
2665 }
2666
2667 if (renderedText.trim().length === 0 && attachments.length === 0) {
2668 return null;
2669 }
2670
2671 const enterAnimated = isFreshTimestamp(message.createdAt);
2672 return (
2673 <Animated.View
2674 className={cn(
2675 showAssistantMeta && !(message.runId && props.failedRunIds.has(message.runId))
2676 ? "mb-5 px-1"
2677 : "mb-1 px-1",
2678 hasWideBlock && "w-full",
2679 )}
2680 {...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}
2681 >
2682 {renderedText.trim().length > 0 ? (
2683 <MarkdownImageAvailableWidthContext value={props.markdownContentWidth}>
2684 <AssistantMarkdownContent
2685 markdown={renderedText}
2686 environmentId={props.environmentId}
2687 citationSource={{ threadId: props.threadId, messageId: message.id }}
2688 onCiteAssistantText={props.onCiteAssistantText}
2689 markdownStyles={styles}
2690 linkHandlers={props.markdownLinkHandlers}
2691 reply={message.projectedItem}
2692 onUseArtifactTemplate={props.onUseArtifactTemplate}
2693 renderImage={props.renderMarkdownImage}
2694 skills={props.skills}
2695 />
2696 </MarkdownImageAvailableWidthContext>
2697 ) : null}
2698 <MessageAttachmentList
2699 attachments={attachments}
2700 environmentId={props.environmentId}
2701 onPressPreview={props.onPressPreview}
2702 onPlaybackStart={props.onPlaybackStart}
2703 />
2704 {showAssistantMeta && message.checkpointSummary ? (
2705 <TurnDiffStat
2706 checkpoint={message.checkpointSummary}
2707 onOpenTurnDiff={props.onOpenTurnDiff}
2708 />
2709 ) : null}
2710 {showAssistantMeta ? (
2711 <View className="mt-1 flex-row items-center gap-1">
2712 <CopyTextButton
2713 accessibilityLabel={m(msg("Copy message"))}
2714 text={renderedText}
2715 tintColor={iconSubtleColor}
2716 buttonSize={props.replyActionSize.button}
2717 iconSize={props.replyActionSize.icon}
2718 />
2719 {message.projectedItem ? (
2720 <AssistantForkButton
2721 environmentId={props.environmentId}
2722 iconColor={iconSubtleColor}
2723 buttonSize={props.replyActionSize.button}
2724 iconSize={props.replyActionSize.icon}
2725 projectedItem={message.projectedItem}
2726 sourceTitle={props.threadTitle}
2727 />
2728 ) : null}
2729 <Text className="font-t3-medium text-xs tabular-nums text-foreground-secondary">
2730 {timestampLabel}
2731 </Text>
2732 </View>
2733 ) : null}
2734 </Animated.View>
2735 );
2736 }
2737
2738 return (
2739 <ThreadWorkLog
2740 activities={entry.activities}
2741 continuesWorkLog={entry.continuesWorkLog}
2742 environmentId={props.environmentId}
2743 workspaceRoot={props.workspaceRoot}
2744 anchorKey={entry.id}
2745 copiedRowId={props.copiedRowId}
2746 expandedRows={props.expandedWorkRows}
2747 rowSizing={props.workRowSizing}
2748 scrollPositions={props.workGroupScrollPositions}
2749 iconSubtleColor={iconSubtleColor}
2750 edgeFadeColor={props.screenColor}
2751 themeAppearance={props.themeAppearance}
2752 onCopyRow={props.onCopyWorkRow}
2753 onToggleRow={props.onToggleWorkRow}
2754 renderImage={props.renderViewedImage}
2755 renderReasoning={props.renderReasoning}
2756 onPressPreview={props.onPressPreview}
2757 />
2758 );
2759 }
2760
2761 function TurnDiffStat(props: {
2762 readonly checkpoint: ThreadCheckpointSummary;
2763 readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void;
2764 }) {
2765 const { files } = props.checkpoint;
2766 const additions = files.reduce((total, file) => total + file.additions, 0);
2767 const deletions = files.reduce((total, file) => total + file.deletions, 0);
2768 const gt = useGT();
2769 return (
2770 <Pressable
2771 accessibilityRole="button"
2772 accessibilityLabel={gt(
2773 "{files, plural, one {Review {files} file changed, {additions} additions, {deletions} deletions} other {Review {files} files changed, {additions} additions, {deletions} deletions}}",
2774 { files: files.length, additions, deletions },
2775 )}
2776 onPress={() => props.onOpenTurnDiff(props.checkpoint)}
2777 className="min-h-11 shrink-0 flex-row items-center gap-2 px-2 active:bg-subtle"
2778 >
2779 <Text className="font-t3-medium text-xs tabular-nums text-adaptive-emerald-700-300">
2780 +{formatDiffCount(additions)}
2781 </Text>
2782 <Text className="font-t3-medium text-xs tabular-nums text-adaptive-rose-700-300">
2783 −{formatDiffCount(deletions)}
2784 </Text>
2785 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-foreground-muted" />
2786 </Pressable>
2787 );
2788 }
2789
2790 type UserMessageContentProps = {
2791 readonly text: string;
2792 readonly environmentId: EnvironmentId;
2793 readonly context?: OrchestrationMessageContext;
2794 readonly markdownStyles: MarkdownStyleSet;
2795 readonly reviewCommentColors: ReviewCommentColors;
2796 readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
2797 readonly linkHandlers: MarkdownLinkHandlers;
2798 readonly renderImage: MarkdownImageRenderer;
2799 };
2800
2801 function UserMessageContent(props: UserMessageContentProps) {
2802 const gt = useGT();
2803 const [selected, setSelected] = useState<{ contextId: string; label: string } | null>(null);
2804 const navigation = useNavigation();
2805 const openThreadLink = useOpenThreadLink(props.environmentId);
2806 const { selectedThread } = useThreadSelection();
2807 const liveText = useLiveThreadLinkLabels(
2808 props.text,
2809 props.environmentId,
2810 useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null),
2811 );
2812 const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records);
2813 const text = replaceComposerContextReferences(liveText, (ref) => {
2814 const available = props.context?.records.some((record) => record.contextId === ref.contextId);
2815 const label = available ? ref.label : gt("{label} (unavailable)", { label: ref.label });
2816 return `[${label}](t3-context://v1/${ref.kind}/${ref.contextId})`;
2817 });
2818 const onLinkPress = (href: string) => {
2819 const reference = parseComposerContextHref(href);
2820 if (!reference) return props.linkHandlers.onLinkPress?.(href);
2821 const record = props.context?.records.find(
2822 (record) => record.contextId === reference.contextId,
2823 );
2824 if (record?.kind === "mention" && "path" in record) {
2825 props.linkHandlers.onLinkPress?.(record.path);
2826 return;
2827 }
2828 if (record?.kind === "thread" && "threadId" in record) {
2829 openThreadLink(scopeThreadRef(record.environmentId, record.threadId));
2830 return;
2831 }
2832 const document = composerDocumentAttachmentRecord(record);
2833 if (document) {
2834 navigation.navigate("ThreadAttachment", {
2835 environmentId: String(props.environmentId),
2836 ...(selectedThread ? { threadId: String(selectedThread.id) } : {}),
2837 attachmentId: document.attachmentId,
2838 name: document.name,
2839 mimeType: document.mimeType,
2840 sizeBytes: String(document.sizeBytes),
2841 });
2842 return;
2843 }
2844 setSelected({
2845 contextId: reference.contextId,
2846 label: record?.label ?? gt("Context unavailable"),
2847 });
2848 };
2849 return (
2850 <>
2851 <UserMessageMarkdownContent
2852 {...props}
2853 text={text}
2854 linkHandlers={{
2855 ...props.linkHandlers,
2856 onLinkPress,
2857 fileContextMenu: (href) => {
2858 const reference = parseComposerContextHref(href);
2859 if (!reference) return props.linkHandlers.fileContextMenu(href);
2860 const record = props.context?.records.find(
2861 (item) => item.contextId === reference.contextId,
2862 );
2863 return {
2864 title: record?.label ?? gt("Context unavailable"),
2865 actions: [
2866 { id: "open-context", title: gt("Open context") },
2867 { id: "copy-context", title: gt("Copy context"), disabled: !record },
2868 ],
2869 };
2870 },
2871 onFileContextMenuAction: (href, actionId) => {
2872 const reference = parseComposerContextHref(href);
2873 if (!reference) return props.linkHandlers.onFileContextMenuAction(href, actionId);
2874 if (actionId === "open-context") return onLinkPress(href);
2875 const record = props.context?.records.find(
2876 (item) => item.contextId === reference.contextId,
2877 );
2878 if (actionId === "copy-context" && record) {
2879 void writeComposerContextClipboard(
2880 formatComposerContextReference({
2881 ...reference,
2882 label: record.label,
2883 }),
2884 {
2885 version: 1,
2886 source: { environmentId: props.environmentId },
2887 records: [record],
2888 },
2889 )
2890 .then(() => Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success))
2891 .catch(() => {
2892 Dialog.alert(gt("Could not copy context"), gt("Try copying this context again."));
2893 });
2894 }
2895 },
2896 linkCustomization: (href) =>
2897 withChipIcon(
2898 enrichedContextLinkCustomization(href, props.context?.records ?? []) ??
2899 props.linkHandlers.linkCustomization?.(href),
2900 threadIcons.get(href),
2901 ),
2902 }}
2903 />
2904 {selected ? (
2905 <ComposerContextSheet
2906 label={selected.label}
2907 environmentId={props.environmentId}
2908 records={props.context?.records}
2909 record={props.context?.records.find((record) => record.contextId === selected.contextId)}
2910 onClose={() => setSelected(null)}
2911 />
2912 ) : null}
2913 </>
2914 );
2915 }
2916
2917 function UserMessageMarkdownContent(props: UserMessageContentProps) {
2918 const text = props.text;
2919 const models = useModelMentions(props.environmentId, text);
2920 const messages = useMessages();
2921 const segments = parseReviewCommentMessageSegments(text, messages);
2922 const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
2923 const contextClipboardFragment = props.context
2924 ? (encodeComposerContextFragment({
2925 version: 1,
2926 source: { environmentId: props.environmentId },
2927 records: props.context.records,
2928 }) ?? undefined)
2929 : undefined;
2930 if (!hasReviewComment) {
2931 return (
2932 <SelectableMarkdownText
2933 markdown={text}
2934 contextClipboardFragment={contextClipboardFragment}
2935 skills={props.skills}
2936 models={models}
2937 textStyle={props.markdownStyles.nativeTextStyle}
2938 preserveSoftBreaks
2939 {...props.linkHandlers}
2940 renderImage={props.renderImage}
2941 />
2942 );
2943 }
2944
2945 return (
2946 <View className="w-full gap-2">
2947 {segments.map((segment) => {
2948 if (segment.kind === "review-comment") {
2949 return (
2950 <ReviewCommentCard
2951 key={segment.comment.id}
2952 comment={segment.comment}
2953 colors={props.reviewCommentColors}
2954 />
2955 );
2956 }
2957
2958 const text = segment.text.trim();
2959 if (text.length === 0) {
2960 return null;
2961 }
2962
2963 return (
2964 <SelectableMarkdownText
2965 key={segment.id}
2966 markdown={text}
2967 contextClipboardFragment={contextClipboardFragment}
2968 skills={props.skills}
2969 models={models}
2970 textStyle={props.markdownStyles.nativeTextStyle}
2971 preserveSoftBreaks
2972 {...props.linkHandlers}
2973 renderImage={props.renderImage}
2974 />
2975 );
2976 })}
2977 </View>
2978 );
2979 }
2980
2981 function ThreadFeedPlaceholder(props: {
2982 readonly bottomInset: number;
2983 readonly detail: string;
2984 readonly horizontalPadding: number;
2985 readonly title: string;
2986 readonly topInset: number;
2987 }) {
2988 return (
2989 <View
2990 style={{
2991 flex: 1,
2992 flexGrow: 1,
2993 alignItems: "center",
2994 justifyContent: "center",
2995 paddingTop: props.topInset,
2996 paddingBottom: props.bottomInset,
2997 paddingHorizontal: props.horizontalPadding + 24,
2998 }}
2999 >
3000 <View className="max-w-[320px] items-center gap-2">
3001 <Text className="text-center font-t3-bold text-lg text-foreground">{props.title}</Text>
3002 <Text className="text-center text-sm leading-normal text-foreground-secondary">
3003 {props.detail}
3004 </Text>
3005 </View>
3006 </View>
3007 );
3008 }
3009
3010 // A hook's return value is frozen to the compiler, so ThreadFeed's later
3011 // hooks can't drag this derivation into an uncached scope.
3012 function useThreadFeedPresentation(
3013 props: ThreadFeedProps,
3014 expandedTurnIds: ReadonlySet<RunId>,
3015 expandedWorkGroups: Record<string, boolean>,
3016 revealedMessageId: MessageId | null,
3017 ) {
3018 const [feedCache] = useState(createThreadFeedCache);
3019 const messages = useMessages();
3020 const locale = useLocale();
3021 return appendPendingThreadMessages(
3022 deriveThreadFeedPresentation(
3023 props.feed,
3024 props.latestRun,
3025 expandedTurnIds,
3026 new Set(
3027 Object.entries(expandedWorkGroups)
3028 .filter(([, expanded]) => expanded)
3029 .map(([groupId]) => groupId),
3030 ),
3031 props.activeWorkStartedAt,
3032 props.runlessWorkActive ?? false,
3033 feedCache,
3034 { toolCallVisibility: props.toolCallVisibility ?? "showAll", revealedMessageId },
3035 messages,
3036 locale,
3037 ),
3038 props.feed,
3039 props.queuedMessages,
3040 );
3041 }
3042
3043 type DisclosureLayout = {
3044 /** Each row's top relative to the anchor row's top, before the toggle. */
3045 positions: ReadonlyMap<string, number>;
3046 anchorIndex: number;
3047 /** Distance from the anchor's top to the end of the content, before the toggle. */
3048 anchorToEnd: number;
3049 list: LegendListRef;
3050 playing: boolean;
3051 };
3052 const DISCLOSURE_DETAIL_DELAY_MS = 135;
3053 const DISCLOSURE_DETAIL_FADE_MS = 70;
3054 const unsubscribeNothing = () => {};
3055
3056 function feedContentEnd(state: ReturnType<LegendListRef["getState"]>): number | undefined {
3057 const last = state.data.length - 1;
3058 if (last < 0) return undefined;
3059 const position = state.positionAtIndex(last);
3060 return position === undefined ? undefined : position + state.sizeAtIndex(last);
3061 }
3062
3063 function DisclosureRow(props: {
3064 itemKey: string;
3065 index: number;
3066 layout: DisclosureLayout | null;
3067 children: ReactNode;
3068 }) {
3069 const { itemKey, layout } = props;
3070 const previous = layout?.positions.get(itemKey);
3071 const subscribe = useCallback(
3072 (notify: () => void) => {
3073 if (!layout || layout.playing || previous === undefined) return unsubscribeNothing;
3074 const state = layout.list.getState();
3075 const stops = [
3076 state.listenToPosition(itemKey, notify),
3077 state.listen("totalSize", notify),
3078 state.listen("isAtEnd", notify),
3079 state.listen("isFollowingEnd", notify),
3080 ];
3081 return () => {
3082 for (const stop of stops) stop();
3083 };
3084 },
3085 [itemKey, layout, previous],
3086 );
3087 // Rows hold their old screen spot relative to whatever stays still: the content end
3088 // while the feed sits at the bottom (end follow, or a collapse that clamps the scroll),
3089 // otherwise the anchored disclosure row.
3090 const getOffset = () => {
3091 if (!layout || layout.playing || previous === undefined) return 0;
3092 const state = layout.list.getState();
3093 const position = state.positionAtIndex(props.index);
3094 if (position === undefined) return 0;
3095 if (state.isFollowingEnd || state.isAtEnd) {
3096 const end = feedContentEnd(state);
3097 return end === undefined ? 0 : previous - layout.anchorToEnd - (position - end);
3098 }
3099 if (previous <= 0) return 0;
3100 const anchor = state.positionAtIndex(layout.anchorIndex);
3101 return anchor === undefined ? 0 : previous - (position - anchor);
3102 };
3103 const offset = useSyncExternalStore(subscribe, getOffset, getOffset);
3104 const entering = !!layout && previous === undefined;
3105 return (
3106 <Animated.View
3107 collapsable={false}
3108 style={
3109 layout
3110 ? {
3111 opacity: entering && !layout.playing ? 0 : 1,
3112 transform: [{ translateY: offset }],
3113 transitionProperty: layout?.playing ? (entering ? "opacity" : "transform") : "none",
3114 transitionDuration: entering
3115 ? DISCLOSURE_DETAIL_FADE_MS
3116 : THREAD_DISCLOSURE_TRANSITION_MS,
3117 transitionDelay: entering ? DISCLOSURE_DETAIL_DELAY_MS : 0,
3118 transitionTimingFunction: "ease-out",
3119 }
3120 : undefined
3121 }
3122 >
3123 {props.children}
3124 </Animated.View>
3125 );
3126 }
3127
3128 const THREAD_FEED_MAINTAIN_SCROLL_AT_END = {
3129 animated: false,
3130 on: { dataChange: true, itemLayout: true, layout: true },
3131 } as const;
3132
3133 // A thread switch remounts the feed. Starting from the last split pane's size lays rows out once,
3134 // instead of at width 0 and again when the new feed's own layout reports the same width.
3135 let lastSplitViewport: { windowWidth: number; width: number; height: number } | null = null;
3136
3137 export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3138 const gt = useGT();
3139 const m = useMessages();
3140 const formatMessageTime = useMessageTimeFormatter();
3141 const { listRef, onIsAtEndChange, onHeaderMaterialVisibilityChange } = props;
3142 const workflowOpening = useWorkflowOpening(props.detailRef);
3143 const guestShare = useThreadGuestShare(props.detailRef);
3144 const deviceType = useDeviceType();
3145 const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType);
3146 const openPullRequest = useOpenPullRequest();
3147 const navigation = useNavigation();
3148 const openThreadLink = useOpenThreadLink(props.environmentId);
3149 const openLocalPreview = useOpenLocalPreview();
3150 const previewTunnelOff = useEnvironmentPreviewTunnelOff(props.environmentId);
3151 // Without the tunnel, loopback links fall through to the system browser like any other link.
3152 const deviceLoopbackUrl = (href: string) =>
3153 previewTunnelOff ? null : loopbackUrlForDevice(href);
3154 // Recycling a row disposes its native audio player, so a started clip's row stays rendered.
3155 const [retainedMediaRowId, setRetainedMediaRowId] = useState<string | null>(null);
3156 const focused = useIsFocused();
3157 if (!focused && retainedMediaRowId !== null) setRetainedMediaRowId(null);
3158 const onOpenTurnDiff = useCallback(
3159 (checkpoint: ThreadCheckpointSummary) => {
3160 setReviewSelectedSectionId(
3161 scopedThreadKey(props.environmentId, props.threadId),
3162 getReviewSectionIdForCheckpoint(checkpoint),
3163 );
3164 navigation.navigate("ThreadReview", {
3165 environmentId: props.environmentId,
3166 threadId: props.threadId,
3167 });
3168 },
3169 [navigation, props.environmentId, props.threadId],
3170 );
3171 const { themeAppearance } = useAppearancePreferences();
3172 const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
3173 const headerMaterialVisibleRef = useRef(false);
3174 const { width: windowWidth, fontScale } = useWindowDimensions();
3175 const { appearance } = useAppearancePreferences();
3176 const workRowSizing = deriveThreadWorkLogSizing({
3177 baseFontSize: appearance.baseFontSize,
3178 fontScale,
3179 });
3180 const settledPaneWidth = useWorkspaceSettledContentWidth();
3181 const splitLayout = (props.layoutVariant ?? "compact") !== "compact";
3182 const [initialSplitViewport] = useState(() =>
3183 splitLayout && lastSplitViewport?.windowWidth === windowWidth ? lastSplitViewport : null,
3184 );
3185 const [measuredViewportWidth, setViewportWidth] = useState(() =>
3186 splitLayout ? (initialSplitViewport?.width ?? 0) : windowWidth,
3187 );
3188 const viewportWidth =
3189 settledPaneWidth !== null ? Math.round(settledPaneWidth) : measuredViewportWidth;
3190 const [viewportHeight, setViewportHeight] = useState(() => initialSplitViewport?.height ?? 0);
3191 const [disclosureLayout, setDisclosureLayout] = useState<DisclosureLayout | null>(null);
3192 const disclosureMotionRef = useRef<DisclosureLayout | null>(null);
3193 const disclosureMotionTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
3194 const disclosureSettleFrameRef = useRef<number | null>(null);
3195 const disclosureSettleSecondFrameRef = useRef<number | null>(null);
3196 const reduceMotion = useReduceMotionEnabled();
3197 const [interactionState, setInteractionState] = useState<{
3198 readonly copiedRowId: string | null;
3199 readonly expandedWorkGroups: Record<string, boolean>;
3200 readonly expandedWorkRows: Record<string, boolean>;
3201 readonly expandedTurnIds: ReadonlySet<RunId>;
3202 readonly revealedMessageId: MessageId | null;
3203 }>({
3204 copiedRowId: null,
3205 expandedWorkGroups: {},
3206 expandedWorkRows: {},
3207 expandedTurnIds: new Set(),
3208 revealedMessageId: null,
3209 });
3210 const { copiedRowId, expandedWorkGroups, expandedWorkRows, expandedTurnIds, revealedMessageId } =
3211 interactionState;
3212 const markdownLinkRequest = useRef<AbortController | null>(null);
3213 const onInlinePlaybackStart = () => {
3214 markdownLinkRequest.current?.abort();
3215 };
3216 useFocusEffect(useCallback(() => () => markdownLinkRequest.current?.abort(), []));
3217 // A preview belongs to the thread and presentation it was opened from: a change closes it and
3218 // aborts a pending lookup.
3219 const markdownLinkScope = JSON.stringify([
3220 props.environmentId,
3221 props.threadId,
3222 props.contentPresentation.kind,
3223 ]);
3224 // oxlint-disable-next-line react/exhaustive-effect-dependencies, t3code/no-unreasoned-state-sync -- A scope change (thread or presentation) aborts the pending link lookup opened from the old scope.
3225 useLayoutEffect(() => () => markdownLinkRequest.current?.abort(), [markdownLinkScope]);
3226 const [preview, setPreview] = useState<{
3227 readonly scope: string;
3228 readonly file: FilePreviewSource | null;
3229 readonly video: VideoPreviewSource | null;
3230 } | null>(null);
3231 if (preview !== null && preview.scope !== markdownLinkScope) setPreview(null);
3232 const expandedFile = preview?.scope === markdownLinkScope ? preview.file : null;
3233 const expandedVideo = preview?.scope === markdownLinkScope ? preview.video : null;
3234 const openPreview = (
3235 scope: string,
3236 media: { file: FilePreviewSource } | { video: VideoPreviewSource },
3237 ) =>
3238 setPreview((current) => {
3239 const live = current?.scope === scope ? current : null;
3240 return {
3241 scope,
3242 file: "file" in media ? media.file : (live?.file ?? null),
3243 video: "video" in media ? media.video : (live?.video ?? null),
3244 };
3245 });
3246 const closeFilePreview = () =>
3247 setPreview((current) => (current === null ? null : { ...current, file: null }));
3248 const closeVideoPreview = () =>
3249 setPreview((current) => (current === null ? null : { ...current, video: null }));
3250 const fileShareSourceIdentifier = useId();
3251 const shareFileChip = useFileChipShare(
3252 props.environmentId,
3253 props.threadId,
3254 fileShareSourceIdentifier,
3255 );
3256 const horizontalPadding = splitLayout ? 20 : 16;
3257 const contentLeftInset = props.contentSideInsets?.left ?? 0;
3258 const contentRightInset = props.contentSideInsets?.right ?? 0;
3259 const usableViewportWidth = Math.max(0, viewportWidth - contentLeftInset - contentRightInset);
3260 const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({
3261 viewportWidth: usableViewportWidth,
3262 maxContentWidth: props.contentMaxWidth ?? null,
3263 minimumPadding: horizontalPadding,
3264 });
3265 const contentWidth = Math.max(0, usableViewportWidth - contentHorizontalPadding * 2);
3266 const userBubbleMaxWidth = contentWidth * 0.85;
3267 const markdownContentWidth = Math.max(0, contentWidth - ASSISTANT_ROW_HORIZONTAL_PADDING * 2);
3268 const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
3269 const barInset = useBarInset();
3270 const columnTopInset = useContentTopInset();
3271 const bottomContentInset = props.contentBottomInset ?? 18;
3272 const usesNativeAutomaticInsets =
3273 props.usesAutomaticContentInsets === true && Platform.OS === "ios";
3274 // Without the native contentInset, a list-header spacer clears the bar the column lays content under.
3275 const topContentInset = usesNativeAutomaticInsets ? 0 : columnTopInset;
3276 const anchorTopInset = usesNativeAutomaticInsets ? barInset : topContentInset;
3277
3278 const theme = useUniwindTheme();
3279 const iconSubtleColor = theme["--color-icon-subtle"];
3280 const { buttonSize: androidButtonSize, smallIconSize: androidIconSize } =
3281 useAndroidControlSizing();
3282 const replyActionSize = useMemo(
3283 () =>
3284 Platform.OS === "android"
3285 ? { button: androidButtonSize, icon: androidIconSize }
3286 : { button: 28, icon: 13 },
3287 [androidButtonSize, androidIconSize],
3288 );
3289 const screenColor = theme["--color-screen"];
3290 const userBubbleColor = theme["--color-user-bubble"];
3291 const openSkillInstructions = (path: string) => {
3292 void Haptics.selectionAsync();
3293 navigation.navigate("ThreadFile", {
3294 environmentId: String(props.environmentId),
3295 threadId: String(props.threadId),
3296 path: fileRoutePathSegments(path),
3297 });
3298 };
3299 const resolveLinkedThread = (href: string) => {
3300 const link = parseThreadLinkHref(href);
3301 if (!link) return null;
3302 const resolved = resolveThreadLink(
3303 (atom) => appAtomRegistry.get(atom),
3304 link,
3305 props.environmentId,
3306 );
3307 if (resolved !== null || link.environmentId !== null) return resolved;
3308 // A v1 link names no environment, so it falls back to this message's.
3309 return scopeThreadRef(props.environmentId, link.threadId);
3310 };
3311 // The file a chat link names: in this workspace, else in the one other project that has it.
3312 const findFileLinkTarget = async (
3313 linkPath: string,
3314 path: string,
3315 signal: AbortSignal,
3316 reply: MarkdownLinkReply | undefined,
3317 ): Promise<string> => {
3318 const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path);
3319 if (
3320 !props.workspaceRoot ||
3321 !relativePath ||
3322 /[\\/]$/.test(linkPath) ||
3323 workspaceLinkLookupQuery(linkPath, props.workspaceRoot) === null ||
3324 !readEnvironmentScope(props.environmentId, AuthFilesystemReadScope)
3325 ) {
3326 return relativePath ?? path;
3327 }
3328 const workspaceRoot = props.workspaceRoot;
3329 const originalPath = resolveWorkspaceFilePath(workspaceRoot, relativePath);
3330 const queryOptions = { signal, reportFailure: false, reportDefect: false };
3331 const searchRoot = (root: string) =>
3332 executeAtomQuery(
3333 appAtomRegistry,
3334 projectEnvironment.searchEntries({
3335 environmentId: props.environmentId,
3336 input: {
3337 cwd: root,
3338 query: workspaceLinkLookupQuery(relativePath, root) ?? relativePath,
3339 kind: "file",
3340 limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,
3341 },
3342 }),
3343 queryOptions,
3344 ).then((result) => ({
3345 root,
3346 entries: result._tag === "Success" ? result.value.entries : [],
3347 }));
3348 const metadataOf = (target: string) =>
3349 executeAtomQuery(
3350 appAtomRegistry,
3351 projectEnvironment.fileMetadata({
3352 environmentId: props.environmentId,
3353 input: { path: target },
3354 }),
3355 queryOptions,
3356 );
3357 const lookup = async () => {
3358 const own = await searchRoot(workspaceRoot);
3359 let match = pickWorkspaceLinkMatch(relativePath, workspaceRoot, own.entries);
3360 const otherProject = match === null;
3361 if (otherProject) {
3362 const threadProjectId = appAtomRegistry.get(
3363 environmentThreadShells.threadShellAtom(
3364 scopeThreadRef(props.environmentId, props.threadId),
3365 ),
3366 )?.projectId;
3367 const otherRoots = appAtomRegistry
3368 .get(environmentProjects.projectsAtom)
3369 .flatMap((project) =>
3370 project.environmentId === props.environmentId &&
3371 project.id !== threadProjectId &&
3372 project.workspaceRoot !== workspaceRoot
3373 ? [project.workspaceRoot]
3374 : [],
3375 );
3376 match =
3377 otherRoots.length === 0
3378 ? null
3379 : pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot)));
3380 }
3381 if (match === null && reply !== undefined && !signal.aborted) {
3382 // No project has the file, so it opens where the agent last worked, as written.
3383 const agentRoots = agentWorkingDirectories(
3384 appAtomRegistry.get(
3385 environmentThreadDetails.quietThreadAtom(
3386 scopeThreadRef(props.environmentId, props.threadId),
3387 ),
3388 )?.projection.visibleTurnItems ?? [],
3389 reply,
3390 ).filter((root) => root !== workspaceRoot);
3391 const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(root, relativePath));
3392 if (agentPaths.length === 0) return relativePath;
3393 const [original, ...found] = await Promise.all(
3394 [originalPath, ...agentPaths].map(metadataOf),
3395 );
3396 if (original?._tag !== "Success" || original.value !== null) return relativePath;
3397 const index = found.findIndex(
3398 (result) => result._tag === "Success" && result.value?.kind === "file",
3399 );
3400 const literal = agentPaths[index];
3401 if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) {
3402 return literal ?? relativePath;
3403 }
3404 return (
3405 (await findAgentDirectoryMatch(relativePath, agentRoots, searchRoot)) ?? relativePath
3406 );
3407 }
3408 if (!match || match === relativePath || signal.aborted) return relativePath;
3409 const metadata = await metadataOf(originalPath);
3410 // Another project's file never replaces a thread-local file the search missed.
3411 return metadata._tag === "Success" &&
3412 (needsWorkspaceBasenameLookup(relativePath) && !otherProject
3413 ? metadata.value?.kind !== "directory"
3414 : metadata.value === null)
3415 ? match
3416 : relativePath;
3417 };
3418 return lookup().catch(() => relativePath);
3419 };
3420 const onMarkdownLinkPress = (
3421 href: string,
3422 imageEmbed = false,
3423 reply?: MarkdownLinkReply,
3424 withGallery?: (source: FilePreviewSource) => FilePreviewSource,
3425 ) => {
3426 markdownLinkRequest.current?.abort();
3427 const request = new AbortController();
3428 markdownLinkRequest.current = request;
3429 const skill = enrichedSkillReference(href, props.skills);
3430 if (skill) {
3431 const instructionsPath = enrichedSkillInstructionsPath(skill);
3432 if (instructionsPath) openSkillInstructions(instructionsPath);
3433 return;
3434 }
3435 // Safari would open the phone's own localhost, so these open on the device by default.
3436 const deviceUrl = deviceLoopbackUrl(href);
3437 if (deviceUrl) {
3438 openLocalPreview(
3439 { environmentId: String(props.environmentId), threadId: String(props.threadId) },
3440 deviceUrl,
3441 );
3442 return;
3443 }
3444 if (parseThreadLinkHref(href)) {
3445 const target = resolveLinkedThread(href);
3446 if (target) openThreadLink(target);
3447 return;
3448 }
3449 const media = resolveMarkdownMediaPreview(href, {
3450 environmentId: props.environmentId,
3451 threadId: props.threadId,
3452 workspaceRoot: props.workspaceRoot,
3453 imageEmbed,
3454 });
3455 if (media && media.kind !== "file") {
3456 void Haptics.selectionAsync();
3457 const scope = markdownLinkScope;
3458 const openMediaPreview = () => {
3459 if (request.signal.aborted) return;
3460 openPreview(
3461 scope,
3462 media.kind === "video"
3463 ? { video: media.source }
3464 : { file: withGallery ? withGallery(media.source) : media.source },
3465 );
3466 };
3467 const resource = "resource" in media.source ? media.source.resource : null;
3468 const mediaPath = resource && "path" in resource ? resource.path : null;
3469 if (
3470 typeof mediaPath === "string" &&
3471 readEnvironmentScope(props.environmentId, AuthFilesystemReadScope)
3472 ) {
3473 void executeAtomQuery(
3474 appAtomRegistry,
3475 projectEnvironment.fileMetadata({
3476 environmentId: props.environmentId,
3477 input: { path: mediaPath },
3478 }),
3479 { signal: request.signal, reportFailure: false, reportDefect: false },
3480 ).then((result) => {
3481 if (request.signal.aborted) return;
3482 if (result._tag === "Success" && result.value?.kind === "directory") {
3483 navigation.navigate("ThreadFile", {
3484 environmentId: String(props.environmentId),
3485 threadId: String(props.threadId),
3486 path: fileRoutePathSegments(mediaPath),
3487 });
3488 } else openMediaPreview();
3489 }, openMediaPreview);
3490 } else openMediaPreview();
3491 return;
3492 }
3493
3494 const presentation = resolveMarkdownLinkPresentation(href);
3495 if (presentation.kind === "file") {
3496 const path = resolveFileLinkPath(props.workspaceRoot, presentation.path);
3497 if (path === null) return;
3498 void findFileLinkTarget(presentation.path, path, request.signal, reply).then((target) => {
3499 if (request.signal.aborted) return;
3500 void Haptics.selectionAsync();
3501 navigation.navigate("ThreadFile", {
3502 environmentId: String(props.environmentId),
3503 threadId: String(props.threadId),
3504 path: fileRoutePathSegments(target),
3505 ...(presentation.line ? { line: String(presentation.line) } : {}),
3506 });
3507 });
3508 return;
3509 }
3510
3511 if (presentation.href) {
3512 if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
3513 openPreview(markdownLinkScope, {
3514 file: { kind: "pdf", uri: presentation.href, name: "Document.pdf" },
3515 });
3516 return;
3517 }
3518 void openPullRequest(presentation.href);
3519 }
3520 };
3521 const resolveImageSource = useMarkdownImageSource({
3522 environmentId: props.environmentId,
3523 threadId: props.threadId,
3524 workspaceRoot: props.workspaceRoot ?? null,
3525 });
3526 const markdownLinkHandlers: MarkdownLinkHandlers = {
3527 fileEmbedLabel: (href, standalone) =>
3528 markdownFileEmbedLabel(
3529 href,
3530 {
3531 environmentId: props.environmentId,
3532 threadId: props.threadId,
3533 workspaceRoot: props.workspaceRoot,
3534 },
3535 standalone,
3536 ),
3537 onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply),
3538 linkCustomization: enrichedThreadLinkCustomization,
3539 onImagePress: (href, withGallery) => onMarkdownLinkPress(href, true, undefined, withGallery),
3540 resolveImageSource,
3541 fileContextMenu: (href) => {
3542 const skill = enrichedSkillReference(href, props.skills);
3543 if (skill) {
3544 return {
3545 title: formatProviderSkillDisplayName(skill),
3546 actions: [
3547 {
3548 id: "open-skill",
3549 title: gt("View instructions"),
3550 disabled: !enrichedSkillInstructionsPath(skill),
3551 },
3552 { id: "copy-skill", title: gt("Copy skill") },
3553 ],
3554 };
3555 }
3556 const thread = resolveLinkedThread(href);
3557 if (thread) {
3558 return {
3559 title:
3560 appAtomRegistry.get(environmentThreadShells.threadShellAtom(thread))?.title ??
3561 gt("Thread"),
3562 actions: [
3563 { id: "open-thread", title: gt("Open thread") },
3564 { id: "copy-thread-link", title: gt("Copy link") },
3565 ],
3566 };
3567 }
3568 // The environment's localhost, which this device can only reach through the tunnel.
3569 if (deviceLoopbackUrl(href)) {
3570 return {
3571 title: href,
3572 actions: [
3573 { id: "open-on-device", title: gt("Open on this device") },
3574 { id: "copy-link", title: gt("Copy link") },
3575 ],
3576 };
3577 }
3578 const target = resolveFileChipTarget(href, props.workspaceRoot);
3579 return target ? fileChipMenu(target) : undefined;
3580 },
3581 onFileContextMenuAction: (href, actionId, reply) => {
3582 const skill = enrichedSkillReference(href, props.skills);
3583 if (skill) {
3584 const instructionsPath = enrichedSkillInstructionsPath(skill);
3585 if (actionId === "open-skill" && instructionsPath) openSkillInstructions(instructionsPath);
3586 else if (actionId === "copy-skill") copyTextWithHaptic(`$${skill.name}`);
3587 return;
3588 }
3589 const thread = resolveLinkedThread(href);
3590 if (thread) {
3591 if (actionId === "open-thread") onMarkdownLinkPress(href);
3592 else if (actionId === "copy-thread-link") copyTextWithHaptic(hostedThreadLink(thread));
3593 return;
3594 }
3595 const deviceUrl = deviceLoopbackUrl(href);
3596 if (deviceUrl) {
3597 if (actionId === "open-on-device") {
3598 markdownLinkRequest.current?.abort();
3599 openLocalPreview(
3600 { environmentId: String(props.environmentId), threadId: String(props.threadId) },
3601 deviceUrl,
3602 );
3603 } else if (actionId === "copy-link") copyTextWithHaptic(href);
3604 return;
3605 }
3606 const target = resolveFileChipTarget(href, props.workspaceRoot);
3607 if (!target) return;
3608 switch (actionId) {
3609 case "copy-full-path":
3610 case "copy-relative-path": {
3611 const presentation = resolveMarkdownLinkPresentation(href);
3612 const path =
3613 presentation.kind === "file"
3614 ? resolveFileLinkPath(props.workspaceRoot, presentation.path)
3615 : null;
3616 if (presentation.kind !== "file" || path === null) return;
3617 markdownLinkRequest.current?.abort();
3618 const request = new AbortController();
3619 markdownLinkRequest.current = request;
3620 void findFileLinkTarget(presentation.path, path, request.signal, reply).then((found) => {
3621 if (request.signal.aborted) return;
3622 const fullPath =
3623 props.workspaceRoot && !isAbsolutePath(found)
3624 ? resolveWorkspaceFilePath(props.workspaceRoot, found)
3625 : found;
3626 const clipboardPath = fileChipClipboardPath(
3627 {
3628 ...target,
3629 ...(target.fullPath ? { fullPath } : {}),
3630 ...(target.relativePath
3631 ? {
3632 relativePath:
3633 resolveWorkspaceRelativeFilePath(props.workspaceRoot, fullPath) ??
3634 target.relativePath,
3635 }
3636 : {}),
3637 },
3638 actionId,
3639 );
3640 if (clipboardPath !== undefined) copyTextWithHaptic(clipboardPath);
3641 });
3642 return;
3643 }
3644 case "open-file":
3645 onMarkdownLinkPress(href, false, reply);
3646 return;
3647 case "save":
3648 shareFileChip(target);
3649 return;
3650 }
3651 },
3652 };
3653 const renderMarkdownImage: MarkdownImageRenderer = (image) => {
3654 const media = resolveMarkdownMediaPreview(image.href, {
3655 environmentId: props.environmentId,
3656 threadId: props.threadId,
3657 workspaceRoot: props.workspaceRoot,
3658 imageEmbed: true,
3659 });
3660 if (media?.kind === "video") {
3661 return (
3662 <ThreadMarkdownVideo
3663 key={image.href}
3664 source={{ ...media.source, name: image.alt ?? media.source.name }}
3665 onPlaybackStart={onInlinePlaybackStart}
3666 />
3667 );
3668 }
3669 if (media?.kind === "audio") {
3670 return (
3671 <ThreadInlineFilePreview
3672 key={image.href}
3673 source={media.source}
3674 onOpen={() => onMarkdownLinkPress(image.href, true)}
3675 onPlaybackStart={onInlinePlaybackStart}
3676 />
3677 );
3678 }
3679 const fileLink = resolveMarkdownLinkPresentation(image.href);
3680 if (
3681 (media && (media.kind === "pdf" || media.kind === "document" || media.kind === "file")) ||
3682 (fileLink.kind === "file" && fileLink.line !== undefined)
3683 ) {
3684 const name =
3685 media?.source.name ?? (fileLink.kind === "file" ? fileLink.label : gt("Open file"));
3686 return (
3687 <Text
3688 accessibilityRole="link"
3689 accessibilityLabel={gt("Open {name}", { name })}
3690 onPress={() => onMarkdownLinkPress(image.href, true)}
3691 style={{
3692 color: markdownStyles.assistant.nativeTextStyle.linkColor,
3693 fontSize: markdownStyles.assistant.nativeTextStyle.fontSize,
3694 lineHeight: markdownStyles.assistant.nativeTextStyle.lineHeight,
3695 }}
3696 >
3697 {name}
3698 </Text>
3699 );
3700 }
3701 const imageSource = classifyMarkdownImageSource(image.href, props.workspaceRoot ?? null);
3702 if (imageSource._tag === "Direct") {
3703 return (
3704 <ThreadMarkdownImageView
3705 uri={normalizeNativeMarkdownUrl(imageSource.uri)}
3706 sourceKey={imageSource.uri}
3707 format={
3708 /\.svg(?:[?#]|$)/i.test(imageSource.uri) ||
3709 imageSource.uri.startsWith("data:image/svg+xml")
3710 ? "svg"
3711 : undefined
3712 }
3713 unavailable={false}
3714 alt={image.alt}
3715 actionsSource={media?.source.actionsSource}
3716 onPressPreview={onPressPreview}
3717 />
3718 );
3719 }
3720 if (imageSource._tag === "Blocked") {
3721 return <ThreadMarkdownImageUnavailable alt={image.alt} />;
3722 }
3723 return (
3724 <ThreadMarkdownImage
3725 environmentId={props.environmentId}
3726 resource={{
3727 _tag: "media-file",
3728 threadId: props.threadId,
3729 path: imageSource.path,
3730 }}
3731 alt={image.alt}
3732 srcFragment={markdownImageSourceFragment(image.href)}
3733 actionsSource={media?.source.actionsSource}
3734 onPressPreview={onPressPreview}
3735 />
3736 );
3737 };
3738 const renderViewedImage: MarkdownImageRenderer = (image) => {
3739 const viewedImage = resolveViewedImageAsset(image.href, {
3740 threadId: props.threadId,
3741 workspaceRoot: props.workspaceRoot,
3742 });
3743 const media = viewedImage
3744 ? resolveMarkdownMediaPreview(image.href, {
3745 environmentId: props.environmentId,
3746 threadId: props.threadId,
3747 workspaceRoot: props.workspaceRoot,
3748 imageEmbed: true,
3749 })
3750 : null;
3751 const actionsSource = media?.source.actionsSource;
3752 return viewedImage ? (
3753 <ThreadMarkdownImage
3754 environmentId={props.environmentId}
3755 resource={viewedImage.resource}
3756 alt={viewedImage.alt}
3757 srcFragment={viewedImage.srcFragment}
3758 actionsSource={
3759 actionsSource && "resource" in actionsSource
3760 ? { ...actionsSource, resource: viewedImage.resource }
3761 : undefined
3762 }
3763 onPressPreview={onPressPreview}
3764 />
3765 ) : null;
3766 };
3767 const markdownStyles = useMarkdownStyles();
3768 const renderReasoning = (text: string) => (
3769 <AssistantMarkdownContent
3770 markdown={text}
3771 environmentId={props.environmentId}
3772 markdownStyles={markdownStyles.assistant}
3773 linkHandlers={markdownLinkHandlers}
3774 renderImage={renderMarkdownImage}
3775 skills={props.skills}
3776 />
3777 );
3778 const reviewCommentColors = useReviewCommentColors();
3779 const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
3780 const compactionLabelsByEntryId = useMemo(
3781 () => threadFeedCompactionLabels(props.feed, m),
3782 [props.feed, m],
3783 );
3784 // LegendList does not invalidate visible rows when only the renderItem closure changes.
3785 // Include turn completion so unchanged message rows reveal their footer and spacing
3786 // even when the final message update arrives before the turn settles.
3787 // One sheet for the setup's card, chip, and summary row, so it stays open as setup moves between them.
3788 const [setupDetailsThreadId, setSetupDetailsThreadId] = useState<string | null>(null);
3789 const setupDetailsOpen = setupDetailsThreadId === props.threadId && !!props.worktreeSetup;
3790 const openSetupDetails = () => setSetupDetailsThreadId(props.threadId);
3791 const listAppearanceData = {
3792 gt,
3793 setupDetailsOpen,
3794 disclosureLayout,
3795 reduceMotion,
3796 onCiteAssistantText: props.onCiteAssistantText,
3797 formatMessageTime,
3798 worktreeSetup: props.worktreeSetup,
3799 preparingWorktree: props.preparingWorktree,
3800 dispatchingMessageId: props.dispatchingMessageId,
3801 unsettledTurnId,
3802 copiedRowId,
3803 expandedWorkGroups,
3804 expandedWorkRows,
3805 workRowSizing,
3806 iconSubtleColor,
3807 markdownStyles,
3808 reviewCommentColors,
3809 themeAppearance,
3810 userBubbleColor,
3811 viewportWidth,
3812 contentWidth,
3813 skills: props.skills,
3814 workflowOpening,
3815 };
3816 const reportHeaderMaterialVisibility = (visible: boolean) => {
3817 if (headerMaterialVisibleRef.current === visible) {
3818 return;
3819 }
3820 headerMaterialVisibleRef.current = visible;
3821 onHeaderMaterialVisibilityChange?.(visible);
3822 };
3823 const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
3824 const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
3825 const [landedListKey, setLandedListKey] = useState<string | null>(null);
3826 // LegendList reports ready, and shows its rows, while rows measured during its initial scroll can
3827 // still leave it hundreds of points short of the end; isAtEnd stays true through that.
3828 const settling = props.feed.length > 0 && landedListKey !== feedThreadKey;
3829 const landingFallback = useRef<ReturnType<typeof setTimeout> | null>(null);
3830 const reportMetrics = (ready: boolean) => {
3831 const state = listRef.current?.getState();
3832 if (!state) return;
3833 if (
3834 settling &&
3835 ready &&
3836 (state.distanceFromEnd <= 2 || !state.isFollowingEnd || props.jumpToMessageId)
3837 ) {
3838 setLandedListKey(feedThreadKey);
3839 }
3840 // Offset 0 before the first positioning, and the gaps while rows measure in, are not the
3841 // user leaving the end; only a scroll away stops end following.
3842 onIsAtEndChange?.(settling || state.isAtEnd || state.isFollowingEnd);
3843 };
3844 const handleMetricsChange = () => reportMetrics(loadedListKey === feedThreadKey);
3845 const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
3846 reportHeaderMaterialVisibility(
3847 event.nativeEvent.contentOffset.y + (usesNativeAutomaticInsets ? barInset : 0) > 6,
3848 );
3849 handleMetricsChange();
3850 };
3851 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the list's end state to report it to the parent
3852 useLayoutEffect(() => {
3853 const state = listRef.current?.getState();
3854 if (!state) return;
3855 handleMetricsChange();
3856 const stops = [
3857 state.listen("isAtEnd", handleMetricsChange),
3858 state.listen("isFollowingEnd", handleMetricsChange),
3859 state.listen("totalSize", handleMetricsChange),
3860 state.listen("footerSize", handleMetricsChange),
3861 state.listen("headerSize", handleMetricsChange),
3862 ];
3863 return () => {
3864 for (const stop of stops) stop();
3865 };
3866 }, [listRef, handleMetricsChange]);
3867 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the landing fallback timer when the feed unmounts
3868 useEffect(
3869 () => () => {
3870 if (landingFallback.current !== null) clearTimeout(landingFallback.current);
3871 },
3872 [],
3873 );
3874 const [workGroupScrollPositions] = useState(
3875 () => new Map<string, ThreadWorkGroupScrollPosition>(),
3876 );
3877
3878 // Opening at a message: once the filled list has loaded, the render that sees
3879 // the jump unfolds a run hiding the message and stops following the end, so
3880 // the committed list holds the target row with end maintenance off.
3881 const { jumpToMessageId } = props;
3882 const jumpReady = !!jumpToMessageId && loadedListKey === feedThreadKey;
3883 if (jumpReady && revealedMessageId !== jumpToMessageId) {
3884 setInteractionState((current) => ({ ...current, revealedMessageId: jumpToMessageId }));
3885 }
3886 const [appendPendingTurn] = useState(createPendingTurnAppender);
3887 const presentedFeed = appendGuestPendingMessages(
3888 appendPendingTurn(
3889 useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups, revealedMessageId),
3890 { zen: props.toolCallVisibility === "zen" },
3891 m,
3892 ),
3893 guestShare,
3894 m,
3895 );
3896 const pendingFoldMessageId =
3897 presentedFeed.findLast((entry) => entry.type === "pending-fold")?.messageId ?? null;
3898 const jumpRunId =
3899 jumpReady &&
3900 !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId)
3901 ? messageFoldRunId(props.feed, jumpToMessageId, presentedFeed)
3902 : null;
3903 if (jumpRunId && !expandedTurnIds.has(jumpRunId)) {
3904 setInteractionState((current) => ({
3905 ...current,
3906 expandedTurnIds: new Set(current.expandedTurnIds).add(jumpRunId),
3907 }));
3908 }
3909 const setupAnchorIndex = presentedFeed.findIndex(
3910 (entry) => entry.type === "message" && entry.message.role === "user",
3911 );
3912 // As on web, setup still running after the agent took the turn rides on the live Working row.
3913 const setupFoldRowId =
3914 props.worktreeSetup &&
3915 worktreeSetupHandedOff(props.worktreeSetup) &&
3916 props.worktreeSetup.snapshot.phase === "running"
3917 ? (presentedFeed.find(
3918 (entry, index) =>
3919 index > setupAnchorIndex &&
3920 entry.type === "run-fold" &&
3921 entry.workingSince !== undefined,
3922 )?.id ?? null)
3923 : null;
3924 const [groupFeed] = useState(createThreadFeedGrouping);
3925 const groupedFeed = groupFeed(presentedFeed, {
3926 workflowOpeningMessageId: workflowOpening?.messageId,
3927 setupAnchorIndex: props.worktreeSetup || props.preparingWorktree ? setupAnchorIndex : undefined,
3928 });
3929 const { contentInsetEndAdjustment } = props;
3930 const attachList = (list: LegendListRef | null) => {
3931 listRef.current = list;
3932 const bottom = contentInsetEndAdjustment.get();
3933 if (list && bottom > 0) list.reportContentInset({ bottom });
3934 };
3935 const jumpIndex = jumpReady
3936 ? presentedFeed.findIndex((entry) => entry.type === "message" && entry.id === jumpToMessageId)
3937 : null;
3938 const landJump = useEffectEvent((index: number) => {
3939 const list = listRef.current;
3940 if (!list) return;
3941 let cancelled = false;
3942 const positioning =
3943 index === -1 ? undefined : list.scrollToIndex({ index, viewPosition: 0.2, animated: false });
3944 void Promise.resolve(positioning).then(() => {
3945 if (!cancelled && listRef.current === list) props.onJumpedToMessage?.();
3946 });
3947 return () => {
3948 cancelled = true;
3949 };
3950 });
3951 // A jump can unfold a run; keep end maintenance off until its position settles.
3952 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the native list to the jump target after the commit that rendered its row
3953 useEffect(() => {
3954 if (jumpIndex !== null) return landJump(jumpIndex);
3955 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Jumping to a different message whose row index is unchanged must still land the jump.
3956 }, [jumpToMessageId, jumpIndex]);
3957
3958 const handleViewportLayout = (event: LayoutChangeEvent) => {
3959 const nextWidth = Math.round(event.nativeEvent.layout.width);
3960 const nextHeight = Math.round(event.nativeEvent.layout.height);
3961 if (splitLayout) lastSplitViewport = { windowWidth, width: nextWidth, height: nextHeight };
3962 setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
3963 setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
3964 };
3965
3966 const anchoredEndSpace = resolveChatListAnchoredEndSpace(
3967 presentedFeed,
3968 props.anchorMessageId,
3969 (entry) => (entry.type === "message" ? entry.id : null),
3970 { anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
3971 );
3972 const failedRunIds = failedFeedRunIds(props.feed, props.latestRun);
3973 const terminalAssistantMessageIds = (() => {
3974 const terminalIdsByTurn = new Map<RunId, string>();
3975 for (const entry of props.feed) {
3976 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
3977 terminalIdsByTurn.set(entry.message.runId, entry.message.id);
3978 }
3979 }
3980 return new Set(terminalIdsByTurn.values());
3981 })();
3982 // An interrupted run unfolds; a run that is no longer latest folds back.
3983 const [previousLatestRun, setPreviousLatestRun] = useState(props.latestRun);
3984 if (previousLatestRun !== props.latestRun) {
3985 setPreviousLatestRun(props.latestRun);
3986 const latest = props.latestRun;
3987 const previous = previousLatestRun;
3988 if (latest && previous) {
3989 if (latest.runId !== previous.runId) {
3990 if (expandedTurnIds.has(previous.runId)) {
3991 setInteractionState((current) => {
3992 const next = new Set(current.expandedTurnIds);
3993 next.delete(previous.runId);
3994 return { ...current, expandedTurnIds: next };
3995 });
3996 }
3997 } else if (previous.status === "running" && latest.status === "interrupted") {
3998 setInteractionState((current) => ({
3999 ...current,
4000 expandedTurnIds: new Set(current.expandedTurnIds).add(latest.runId),
4001 }));
4002 }
4003 }
4004 }
4005
4006 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears copy feedback and disclosure animation timers and frames on unmount
4007 useEffect(
4008 () => () => {
4009 if (copyFeedbackTimeoutRef.current) clearTimeout(copyFeedbackTimeoutRef.current);
4010 if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
4011 if (disclosureSettleFrameRef.current !== null) {
4012 cancelAnimationFrame(disclosureSettleFrameRef.current);
4013 }
4014 if (disclosureSettleSecondFrameRef.current !== null) {
4015 cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
4016 }
4017 },
4018 [],
4019 );
4020
4021 const settleDisclosureAfterLayout = () => {
4022 if (disclosureSettleFrameRef.current !== null) {
4023 cancelAnimationFrame(disclosureSettleFrameRef.current);
4024 }
4025 if (disclosureSettleSecondFrameRef.current !== null) {
4026 cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
4027 }
4028 disclosureSettleFrameRef.current = requestAnimationFrame(() => {
4029 disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
4030 const motion = disclosureMotionRef.current;
4031 if (motion && !motion.playing) {
4032 const playing = { ...motion, playing: true };
4033 disclosureMotionRef.current = playing;
4034 setDisclosureLayout(playing);
4035 disclosureMotionTimer.current = setTimeout(
4036 () => {
4037 disclosureMotionRef.current = null;
4038 setDisclosureLayout(null);
4039 disclosureMotionTimer.current = null;
4040 },
4041 DISCLOSURE_DETAIL_DELAY_MS + DISCLOSURE_DETAIL_FADE_MS + 16,
4042 );
4043 }
4044 disclosureSettleFrameRef.current = null;
4045 disclosureSettleSecondFrameRef.current = null;
4046 });
4047 });
4048 };
4049
4050 const preserveDisclosurePosition = (anchorKey: string | null) => {
4051 const list = listRef.current;
4052 const working = props.activeWorkStartedAt !== null || props.runlessWorkActive === true;
4053 // An anchor ends end-follow until the reader scrolls, so a streaming turn keeps the live end.
4054 if (anchorKey !== null && list && !(working && list.getState().isFollowingEnd)) {
4055 list.cancelScroll();
4056 list.anchorVisibleContent({ key: anchorKey });
4057 }
4058 if (list && anchorKey && !reduceMotion) {
4059 const state = list.getState();
4060 const anchorIndex = state.indexByKey(anchorKey);
4061 if (anchorIndex !== undefined) {
4062 const anchor = state.positionAtIndex(anchorIndex);
4063 const anchorTop = state.elementAtIndex(anchorIndex)?.getBoundingClientRect().top;
4064 const positions = new Map<string, number>();
4065 for (let i = state.startBuffered; i <= state.endBuffered; i++) {
4066 const item = groupedFeed[i];
4067 if (!item) continue;
4068 const displayed =
4069 disclosureMotionRef.current &&
4070 state.elementAtIndex(i)?.firstElementChild?.getBoundingClientRect().top;
4071 positions.set(
4072 item.id,
4073 displayed != null && anchorTop !== undefined
4074 ? displayed - anchorTop
4075 : state.positionAtIndex(i) - anchor,
4076 );
4077 }
4078 const motion = {
4079 positions,
4080 anchorIndex,
4081 anchorToEnd: (feedContentEnd(state) ?? anchor) - anchor,
4082 list,
4083 playing: false,
4084 };
4085 if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
4086 disclosureMotionRef.current = motion;
4087 setDisclosureLayout(motion);
4088 settleDisclosureAfterLayout();
4089 }
4090 }
4091 };
4092
4093 const handleItemSizeChanged = () => {
4094 if (disclosureMotionRef.current && !disclosureMotionRef.current.playing) {
4095 settleDisclosureAfterLayout();
4096 }
4097 };
4098
4099 const onCopyWorkRow = (rowId: string, value: string) => {
4100 copyTextWithHaptic(value, {
4101 target: "thread-work-row",
4102 feedback: "selection",
4103 });
4104 setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
4105 if (copyFeedbackTimeoutRef.current) {
4106 clearTimeout(copyFeedbackTimeoutRef.current);
4107 }
4108 copyFeedbackTimeoutRef.current = setTimeout(() => {
4109 setInteractionState((current) =>
4110 current.copiedRowId === rowId ? { ...current, copiedRowId: null } : current,
4111 );
4112 copyFeedbackTimeoutRef.current = null;
4113 }, 1200);
4114 };
4115
4116 const onToggleWorkGroup = (groupId: string, anchorKey?: string) => {
4117 preserveDisclosurePosition(anchorKey ?? `work-toggle:${groupId}`);
4118 setInteractionState((current) => ({
4119 ...current,
4120 expandedWorkGroups: {
4121 ...current.expandedWorkGroups,
4122 [groupId]: !(current.expandedWorkGroups[groupId] ?? false),
4123 },
4124 }));
4125 };
4126
4127 // Lone rows share their group's disclosure state so opened details survive a second call joining.
4128 const onToggleWorkRow = (rowId: string, anchorKey?: string, groupId?: string) => {
4129 preserveDisclosurePosition(anchorKey ?? null);
4130 setInteractionState((current) => {
4131 const expanded = !(current.expandedWorkRows[rowId] ?? false);
4132 return {
4133 ...current,
4134 expandedWorkRows: { ...current.expandedWorkRows, [rowId]: expanded },
4135 ...(groupId === undefined
4136 ? {}
4137 : { expandedWorkGroups: { ...current.expandedWorkGroups, [groupId]: expanded } }),
4138 };
4139 });
4140 };
4141
4142 const onToggleUserMessage = (rowId: string, anchorKey: string) => {
4143 const list = listRef.current;
4144 if (expandedWorkRows[rowId] && list) {
4145 const anchor = list.anchorVisibleContent({ key: anchorKey, hold: false });
4146 const nextKey = groupedFeed[groupedFeed.findIndex((item) => item.id === anchorKey) + 1]?.id;
4147 // Once the message top is scrolled away, collapse toward it like the web: what follows stays put.
4148 if (anchor && anchor.offset > 0 && nextKey) {
4149 onToggleWorkRow(rowId, nextKey);
4150 return;
4151 }
4152 }
4153 onToggleWorkRow(rowId, anchorKey);
4154 };
4155
4156 const onToggleTurnFold = (runId: RunId) => {
4157 preserveDisclosurePosition(`run-fold:${runId}`);
4158 setInteractionState((current) => {
4159 const next = new Set(current.expandedTurnIds);
4160 if (next.has(runId)) {
4161 next.delete(runId);
4162 } else {
4163 next.add(runId);
4164 }
4165 return { ...current, expandedTurnIds: next };
4166 });
4167 };
4168
4169 const onPressPreview = (source: FilePreviewSource) => {
4170 markdownLinkRequest.current?.abort();
4171 openPreview(markdownLinkScope, { file: source });
4172 };
4173
4174 // Without this, every row above the viewport is assumed to be
4175 // estimatedItemSize tall, and scrolling up through unmeasured content
4176 // corrects each row's height as it mounts — the feed visibly jumps.
4177 const getFixedItemSize = (entry: ThreadFeedRow) => {
4178 if (entry.type === "guest-pending") return undefined;
4179 if (entry.type === "pending-fold") {
4180 return workRowSizing.fixedRowHeight === undefined
4181 ? undefined
4182 : resolveThreadFeedFixedItemSize("run-fold");
4183 }
4184 if (entry.type === "html-render") {
4185 return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));
4186 }
4187 if (workRowSizing.fixedRowHeight === undefined || entry.checkpointSummary) {
4188 return undefined;
4189 }
4190 switch (entry.type) {
4191 case "run-fold":
4192 return resolveThreadFeedFixedItemSize(entry.type);
4193 case "work-toggle":
4194 return entry.thought ? undefined : WORK_GROUP_TOGGLE_HEIGHT;
4195 case "thinking":
4196 return WORK_GROUP_TOGGLE_HEIGHT;
4197 case "activity-group":
4198 if (entry.activities[0]?.projectedItem.item.type === "subagent") {
4199 return undefined;
4200 }
4201 if (isContextCompactionActivityGroup(entry) || isContextHandoffActivityGroup(entry)) {
4202 return undefined;
4203 }
4204 if (
4205 entry.activities[0]?.groupedToolDetail &&
4206 entry.activities.every((activity) => activity.workEntry.itemType === "reasoning")
4207 ) {
4208 return undefined;
4209 }
4210 return entry.activities.some(
4211 (activity) => activity.prominent || expandedWorkRows[activity.id],
4212 )
4213 ? undefined
4214 : collapsedWorkLogHeight(entry.activities, entry.continuesWorkLog);
4215 default:
4216 return undefined;
4217 }
4218 };
4219 // Row geometry inputs mostly arrive as props with no handler here. LegendList
4220 // reads getFixedItemSize only when it renders, so its size cache is cleared
4221 // after the commit that hands it rows at the new geometry; clearing earlier
4222 // re-caches old sizes.
4223 const { textSizeKey } = workRowSizing;
4224 const hasHtmlRenders = presentedFeed.some((entry) => entry.type === "html-render");
4225 const previousRowGeometry = useRef({ textSizeKey, contentWidth });
4226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears LegendList size caches after the commit that brings new row geometry
4227 useLayoutEffect(() => {
4228 const previous = previousRowGeometry.current;
4229 if (previous.textSizeKey === textSizeKey && previous.contentWidth === contentWidth) return;
4230 previousRowGeometry.current = { textSizeKey, contentWidth };
4231 if (previous.textSizeKey !== textSizeKey || hasHtmlRenders) {
4232 listRef.current?.clearCaches({ mode: "sizes" });
4233 }
4234 }, [textSizeKey, contentWidth, hasHtmlRenders, listRef]);
4235
4236 const renderItem = (info: { item: GroupedThreadFeedRow; index: number }) => (
4237 <DisclosureRow
4238 key={info.item.id}
4239 itemKey={info.item.id}
4240 index={info.index}
4241 layout={disclosureLayout}
4242 >
4243 <MessageImageGalleryScope
4244 entry={info.item}
4245 environmentId={props.environmentId}
4246 threadId={props.threadId}
4247 workspaceRoot={props.workspaceRoot}
4248 >
4249 <ThreadMediaVisibility rowId={info.item.id} setRetainedRowId={setRetainedMediaRowId}>
4250 {info.item.type === "message" &&
4251 info.item.message.projectedItem?.item.type === "user_message" &&
4252 info.item.message.projectedItem.item.freshContext ? (
4253 <ThreadContextDivider
4254 label={gt("New session")}
4255 icon="arrow.clockwise"
4256 iconColor={iconSubtleColor}
4257 />
4258 ) : null}
4259 {info.item.type === "message" &&
4260 !isCompactionCommandFeedEntry(info.item) &&
4261 info.item.message.projectedItem?.item.type === "user_message" &&
4262 info.item.message.projectedItem.item.modelSwitch ? (
4263 <ThreadModelSwitchDivider
4264 environmentId={props.environmentId}
4265 modelSwitch={info.item.message.projectedItem.item.modelSwitch}
4266 iconColor={iconSubtleColor}
4267 />
4268 ) : null}
4269 {renderFeedEntry(info, {
4270 m,
4271 userMessageGrouping: info.item.userMessageGrouping,
4272 formatMessageTime,
4273 environmentId: props.environmentId,
4274 dispatchingMessageId: props.dispatchingMessageId,
4275 pendingFoldMessageId,
4276 setupFoldRowId,
4277 worktreeSetup: props.worktreeSetup,
4278 setupDetailsOpen,
4279 onOpenSetupDetails: openSetupDetails,
4280 onEditPendingMessage: props.onEditPendingMessage,
4281 onUseArtifactTemplate: props.onUseArtifactTemplate,
4282 onCiteAssistantText: props.onCiteAssistantText,
4283 threadId: props.threadId,
4284 copiedRowId,
4285 expandedWorkRows,
4286 workRowSizing,
4287 workGroupScrollPositions,
4288 terminalAssistantMessageIds,
4289 unsettledTurnId,
4290 compactionLabelsByEntryId,
4291 failedRunIds,
4292 onCopyWorkRow,
4293 onToggleWorkGroup,
4294 onToggleWorkRow,
4295 onToggleUserMessage,
4296 onToggleTurnFold,
4297 onOpenTurnDiff,
4298 onPressPreview,
4299 onPlaybackStart: onInlinePlaybackStart,
4300 markdownLinkHandlers,
4301 renderMarkdownImage,
4302 renderViewedImage,
4303 renderReasoning,
4304 iconSubtleColor,
4305 replyActionSize,
4306 screenColor,
4307 userBubbleColor,
4308 markdownStyles,
4309 reviewCommentColors,
4310 reviewCommentBubbleWidth,
4311 themeAppearance,
4312 duoColumns,
4313 userBubbleMaxWidth,
4314 markdownContentWidth,
4315 contentWidth,
4316 threadTitle: props.threadTitle,
4317 skills: props.skills,
4318 workspaceRoot: props.workspaceRoot,
4319 workflowOpening,
4320 })}
4321 {props.worktreeSetup && info.index === setupAnchorIndex ? (
4322 <WorktreeSetupCard
4323 key={props.threadId}
4324 {...props.worktreeSetup}
4325 detailsOpen={setupDetailsOpen}
4326 onOpenDetails={openSetupDetails}
4327 />
4328 ) : props.preparingWorktree && info.index === setupAnchorIndex ? (
4329 <WorktreePreparingHeader />
4330 ) : null}
4331 </ThreadMediaVisibility>
4332 </MessageImageGalleryScope>
4333 </DisclosureRow>
4334 );
4335
4336 if (props.contentPresentation.kind === "unavailable" && props.queuedMessages.length === 0) {
4337 return (
4338 <View style={{ flex: 1, marginLeft: contentLeftInset, marginRight: contentRightInset }}>
4339 <ThreadFeedPlaceholder
4340 title={props.contentPresentation.title}
4341 detail={props.contentPresentation.detail}
4342 topInset={topContentInset}
4343 bottomInset={bottomContentInset}
4344 horizontalPadding={horizontalPadding}
4345 />
4346 </View>
4347 );
4348 }
4349
4350 return (
4351 <PresentationSource identifier={fileShareSourceIdentifier} style={{ flex: 1 }}>
4352 <View className="flex-1" onLayout={handleViewportLayout}>
4353 {/* In a split, rows only re-wrap in the render that hands the list its new width. A native
4354 column resize would re-wrap them first, and the list would place the taller or shorter
4355 rows at their old offsets until their measurements came back. */}
4356 <View
4357 className="flex-1"
4358 style={splitLayout && viewportWidth > 0 ? { width: viewportWidth } : undefined}
4359 >
4360 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
4361 <KeyboardAwareLegendList
4362 ref={attachList}
4363 dataKey={feedThreadKey}
4364 style={settling ? { flex: 1, opacity: 0 } : { flex: 1 }}
4365 // RN 0.81+ drops inset-area touches (facebook/react-native#54123), making blank post-send space unscrollable.
4366 applyWorkaroundForContentInsetHitTestBug
4367 {...(Platform.OS === "ios" ? { ScrollViewComponent: ThreadFeedScrollView } : {})}
4368 contentInsetAdjustmentBehavior="never"
4369 automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
4370 scrollIndicatorInsets={{ top: anchorTopInset, bottom: 0 }}
4371 {...(anchoredEndSpace ? { anchoredEndSpace } : {})}
4372 contentInsetEndAdjustment={props.contentInsetEndAdjustment}
4373 keyboardOffset={props.keyboardOffset}
4374 {...(usesNativeAutomaticInsets ? { contentInset: { top: anchorTopInset } } : {})}
4375 freeze={props.freeze}
4376 maintainScrollAtEnd={jumpReady ? false : THREAD_FEED_MAINTAIN_SCROLL_AT_END}
4377 maintainVisibleContentPosition
4378 data={groupedFeed}
4379 extraData={listAppearanceData}
4380 renderItem={renderItem}
4381 viewabilityConfig={THREAD_MEDIA_VIEWABILITY_CONFIG}
4382 keyExtractor={(entry) => entry.id}
4383 getItemType={(entry) => {
4384 // Same container as the live fold that replaces it.
4385 if (entry.type === "pending-fold") return "run-fold";
4386 if (entry.type !== "message") return entry.type;
4387 if (isCompactionCommandFeedEntry(entry)) return "message:compaction";
4388 if (
4389 entry.message.role === "assistant" &&
4390 !terminalAssistantMessageIds.has(entry.message.id)
4391 ) {
4392 return "message:assistant-progress";
4393 }
4394 const { attribution } = resolveUserMessagePresentation(entry.message);
4395 return attribution === "automation" || attribution === "agent"
4396 ? `message:${attribution}`
4397 : `message:${entry.message.role}`;
4398 }}
4399 getFixedItemSize={getFixedItemSize}
4400 drawDistance={500}
4401 {...(retainedMediaRowId ? { alwaysRender: { keys: [retainedMediaRowId] } } : {})}
4402 keyboardShouldPersistTaps="always"
4403 keyboardDismissMode="none"
4404 // Android scrolls a tapped selectable message into view when it takes focus, which reads
4405 // as a user scroll and drops end following before the keyboard closes.
4406 scrollsChildToFocus={false}
4407 keyboardLiftBehavior={props.sendingWithKeyboard ? "persistent" : "whenAtEnd"}
4408 // Seed the initial viewport before native onLayout.
4409 {...(viewportHeight > 0 && viewportWidth > 0
4410 ? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
4411 : {})}
4412 scrollToOverflowEnabled
4413 estimatedItemSize={180}
4414 alignItemsAtEnd
4415 initialScrollAtEnd
4416 onReady={() => {
4417 setLoadedListKey(feedThreadKey);
4418 reportMetrics(true);
4419 // Never leave the feed hidden if end following stalls short of the end.
4420 landingFallback.current = setTimeout(() => setLandedListKey(feedThreadKey), 1000);
4421 }}
4422 onLayout={handleMetricsChange}
4423 onItemSizeChanged={handleItemSizeChanged}
4424 onScroll={handleScroll}
4425 scrollEventThrottle={16}
4426 ListHeaderComponent={
4427 <>
4428 {usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
4429 {setupAnchorIndex < 0 && props.worktreeSetup ? (
4430 <WorktreeSetupCard
4431 key={props.threadId}
4432 {...props.worktreeSetup}
4433 detailsOpen={setupDetailsOpen}
4434 onOpenDetails={openSetupDetails}
4435 />
4436 ) : setupAnchorIndex < 0 && props.preparingWorktree ? (
4437 <WorktreePreparingHeader />
4438 ) : null}
4439 {props.historyControls ? (
4440 <ThreadFeedLoadEarlierControl {...props.historyControls} />
4441 ) : null}
4442 </>
4443 }
4444 ListFooterComponent={
4445 props.pendingHandoff || props.statusLines?.length ? (
4446 <>
4447 {props.pendingHandoff ? (
4448 <ThreadHandoffDivider
4449 environmentId={props.environmentId}
4450 endpoints={props.pendingHandoff}
4451 iconColor={iconSubtleColor}
4452 surfaceColor={screenColor}
4453 label={gt("Context handoff pending")}
4454 />
4455 ) : null}
4456 {props.statusLines?.map((line) => (
4457 <ThreadStatusLine key={line.key} line={line} iconColor={iconSubtleColor} />
4458 ))}
4459 </>
4460 ) : null
4461 }
4462 contentContainerStyle={{
4463 ...(props.fitShortFeedToViewport ? { minHeight: "100%" } : {}),
4464 paddingTop: FEED_PADDING_TOP,
4465 paddingLeft: contentHorizontalPadding + contentLeftInset,
4466 paddingRight: contentHorizontalPadding + contentRightInset,
4467 }}
4468 />
4469 </View>
4470 {presentedFeed.length === 0 &&
4471 !props.worktreeSetup &&
4472 props.activeWorkStartedAt === null &&
4473 props.contentPresentation.kind === "ready" ? (
4474 <View
4475 pointerEvents="none"
4476 style={[StyleSheet.absoluteFill, { left: contentLeftInset, right: contentRightInset }]}
4477 >
4478 <ThreadFeedPlaceholder
4479 title={gt("No conversation yet")}
4480 detail={gt(
4481 "Ask the agent to inspect the repo, run a command, or continue the active thread.",
4482 )}
4483 topInset={topContentInset}
4484 bottomInset={bottomContentInset}
4485 horizontalPadding={horizontalPadding}
4486 />
4487 </View>
4488 ) : null}
4489 <VideoPreviewModal source={expandedVideo} onRequestClose={closeVideoPreview} />
4490 {setupDetailsOpen && props.worktreeSetup ? (
4491 <WorktreeSetupDetails
4492 {...props.worktreeSetup}
4493 onClose={() => setSetupDetailsThreadId(null)}
4494 />
4495 ) : null}
4496 <FilePreviewModal source={expandedFile} onRequestClose={closeFilePreview} />
4497 </View>
4498 </PresentationSource>
4499 );
4500 });
4501
4502 function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {
4503 const gt = useGT();
4504 const theme = useUniwindTheme();
4505 const mutedColor = theme["--color-icon-subtle"];
4506 if (!props.hasMoreHistory && props.error === null) {
4507 return null;
4508 }
4509 return (
4510 <View className="mb-3 items-center gap-1.5 px-2">
4511 {props.hasMoreHistory ? (
4512 <View className="self-center">
4513 <Button
4514 label={props.loading ? gt("Loading earlier activity…") : gt("Load earlier activity")}
4515 tone="secondary"
4516 accessibilityLabel={gt("Load earlier activity")}
4517 disabled={props.loading}
4518 onPress={props.onLoadEarlier}
4519 icon="chevron.up"
4520 loading={props.loading}
4521 />
4522 </View>
4523 ) : null}
4524 {props.error !== null ? (
4525 <Text className="text-center text-xs" style={{ color: mutedColor }}>
4526 {props.error}
4527 </Text>
4528 ) : null}
4529 </View>
4530 );
4531 }
4532
4533 function MessageImageGalleryScope(props: {
4534 entry: ThreadFeedRow;
4535 environmentId: EnvironmentId;
4536 threadId: ThreadId;
4537 workspaceRoot: string | null | undefined;
4538 children: ReactNode;
4539 }) {
4540 const { entry, environmentId, threadId, workspaceRoot } = props;
4541 const images =
4542 entry.type === "message"
4543 ? [
4544 ...messageImageGallery(entry.message, { environmentId, threadId, workspaceRoot }),
4545 ...composerImageGallery(entry.pendingMessage?.attachments ?? [], environmentId),
4546 ]
4547 : [];
4548 return <FilePreviewGallery value={images}>{props.children}</FilePreviewGallery>;
4549 }