Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
3import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
4import { useNavigation } from "@react-navigation/native";
5import type { WorktreeSetupCardProps } from "./worktree-setup-card";
6import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
7import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
8import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
9import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
10import type {
11 CodexFeedbackSubmission,
12 EnvironmentThreadStatus,
13} from "@t3tools/client-runtime/state/threads";
14import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
15import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
16import type { LegendListRef } from "@legendapp/list/react-native";
17import { HeaderHeightContext } from "@react-navigation/elements";
18import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
19import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/reserved-regions";
20import type {
21 EnvironmentId,
22 MessageId,
23 ModelSelection,
24 ProviderApprovalDecision,
25 ProviderInteractionMode,
26 RuntimeMode,
27 RuntimeRequestId,
28 ServerConfig as T3ServerConfig,
29 ThreadId,
30 UsageLimitsReport,
31} from "@t3tools/contracts";
32import {
33 appendCodexArtifactTemplateUsePrompt,
34 type CodexArtifactTemplate,
35} from "@t3tools/shared/codexArtifactTemplates";
36import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
37import {
38 presentPendingBackgroundWork,
39 presentProviderGoal,
40} from "@t3tools/client-runtime/state/thread-execution";
41import { resolveSubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
42import {
43 formatModelSelectionEffort,
44 type ProviderSubagentStatus,
45} from "@t3tools/client-runtime/state/thread-execution";
46import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
47import { isProviderNativeSubagentThread } from "@t3tools/contracts";
48import type { QueuedRunEdit } from "../../state/queued-run-edit";
49import type { FollowUpBehavior } from "../../lib/followUpBehavior";
50import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
51import * as Haptics from "expo-haptics";
52import {
53 memo,
54 useCallback,
55 useContext,
56 useEffect,
57 useLayoutEffect,
58 useMemo,
59 useRef,
60 useState,
61} from "react";
62import {
63 Alert,
64 AppState,
65 Keyboard,
66 Platform,
67 useWindowDimensions,
68 View,
69 type GestureResponderEvent,
70 type ViewInstance,
71} from "react-native";
72import {
73 KeyboardController,
74 KeyboardStickyView,
75 useKeyboardState,
76} from "react-native-keyboard-controller";
77import Animated, {
78 Easing,
79 FadeInDown,
80 FadeOut,
81 ReduceMotion,
82 useAnimatedReaction,
83 useAnimatedStyle,
84 useDerivedValue,
85 useSharedValue,
86 withTiming,
87} from "react-native-reanimated";
88import { useSafeAreaInsets } from "react-native-safe-area-context";
89import { useWorkspaceContentWidth } from "../layout/workspace-content-width";
90import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
91import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
92import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
93import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
94import type { ComposerEditorHandle } from "../../components/ComposerEditor";
95import type { StatusTone } from "../../components/StatusPill";
96import type { DraftComposerAttachment } from "../../lib/composerImages";
97import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
98import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
99import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
100import { deviceEnvironment } from "../../state/device";
101import { useEnvironmentQuery } from "../../state/query";
102import { threadDevicePreviews } from "../devices/threadDevicePreviews";
103import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
104import { useThreadServerBrowserTabs } from "../../state/preview";
105import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
106import { scopedThreadKey } from "../../lib/scopedEntities";
107import {
108 clearThreadComposerError,
109 threadComposerErrorsAtom,
110} from "../../state/thread-composer-error";
111import { threadEnvironment } from "../../state/threads";
112import { useAtomCommand } from "../../state/use-atom-command";
113import { useDelayedStatus } from "../../lib/useDelayedStatus";
114import type {
115 PendingApproval,
116 PendingUserInput,
117 PendingUserInputDraftAnswer,
118 ThreadFeedEntry,
119 ThreadFeedLatestRun,
120} from "../../lib/threadActivity";
121import { PendingApprovalCard } from "./PendingApprovalCard";
122import { ComposerErrorNotice } from "./ComposerErrorNotice";
123import { ComposerFeedback } from "./ComposerFeedback";
124import { ComposerUsageLimits } from "./ComposerUsageLimits";
125import { PendingUserInputCard } from "./PendingUserInputCard";
126import { ProviderSubagentBar } from "./ProviderSubagentBar";
127import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
128import {
129 FLOATING_WORKING_CONTROL_COVERAGE,
130 FloatingWorkingControl,
131} from "./floating-working-control";
132import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status";
133import {
134 derivePendingUserInputMaxHeight,
135 ESTIMATED_KEYBOARD_HEIGHT,
136 USER_INPUT_TOGGLE_DURATION_MS,
137} from "./pendingUserInputLayout";
138import {
139 COMPOSER_COLLAPSED_CHROME,
140 COMPOSER_EXPANDED_CHROME,
141 COMPOSER_LAYOUT_TRANSITION,
142 COMPOSER_TRANSITION_DURATION_MS,
143 ThreadComposer,
144} from "./ThreadComposer";
145import { ComposerPopoverHost } from "./ComposerPopoverHost";
146import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
147import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
148import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
149import { useThreadQueuedCount } from "./ThreadQueueControl";
150import type { ThreadContentPresentation } from "./threadContentPresentation";
151import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
152import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
153
154export interface ThreadDetailScreenProps {
155 readonly worktreeSetup?: WorktreeSetupCardProps | null;
156 readonly setupWorkingStartedAt?: string | null;
157 readonly canOperateThread: boolean;
158 readonly selectedThread: EnvironmentThreadShell;
159 readonly contentPresentation: ThreadContentPresentation;
160 readonly screenTone: StatusTone;
161 readonly connectionError: string | null;
162 readonly environmentLabel: string | null;
163 readonly feedbackSubmissions: ReadonlyArray<CodexFeedbackSubmission>;
164 readonly onDismissFeedback: (id: MessageId) => void;
165 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
166 readonly pendingHandoff?: HandoffEndpoints | null;
167 readonly activityRun: ThreadFeedLatestRun | null;
168 readonly activeWorkStartedAt: string | null;
169 /** The live work is a provider-native subagent's runless root turn. */
170 readonly runlessWorkActive?: boolean;
171 /** Set on a provider-native subagent thread, which shows status instead of a composer. */
172 readonly providerSubagentStatus?: ProviderSubagentStatus | null;
173 readonly isCompacting: boolean;
174 /**
175 * The server has not created this thread yet. "preparing" runs while the
176 * queued creation is delivered (a worktree may be checking out); "failed"
177 * is a rejected creation whose content went back to the project draft.
178 * `serverOwned` marks a thread the server already created that is still
179 * setting up its worktree; follow-ups queue on the server behind that setup.
180 */
181 readonly creationState:
182 | {
183 readonly kind: "preparing";
184 readonly preparingWorktree: boolean;
185 readonly serverOwned: boolean;
186 }
187 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
188 | null;
189 readonly activePendingApproval: PendingApproval | null;
190 readonly respondingApprovalId: RuntimeRequestId | null;
191 readonly activePendingUserInput: PendingUserInput | null;
192 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
193 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
194 readonly respondingUserInputId: RuntimeRequestId | null;
195 readonly draftMessage: string;
196 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
197 readonly connectionStateLabel: EnvironmentConnectionPhase;
198 /** Message sync status for the selected thread (drives the composer status pill). */
199 readonly threadSyncStatus?: EnvironmentThreadStatus;
200 /** Progressive history controls for oversized mobile thread opens. */
201 readonly historyControls?: ThreadFeedHistoryControls;
202 readonly activeThreadBusy: boolean;
203 readonly canStopThread: boolean;
204 /** Set while a queued message is open in the composer for editing. */
205 readonly queuedRunEdit: QueuedRunEdit | null;
206 readonly composerDraftKey: string | null;
207 readonly followUpBehavior: FollowUpBehavior;
208 readonly canSteerActiveTurn: boolean;
209 readonly isSavingQueuedEdit: boolean;
210 readonly onCancelQueuedRunEdit: () => void;
211 readonly onRemoveQueuedEditAttachment: (attachmentId: string) => void;
212 readonly environmentId: EnvironmentId;
213 readonly projectWorkspaceRoot: string | null;
214 readonly threadCwd: string | null;
215 readonly selectedThreadQueueCount: number;
216 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
217 readonly dispatchingMessageId: MessageId | null;
218 readonly serverConfig: T3ServerConfig | null;
219 readonly layoutVariant?: LayoutVariant;
220 readonly usesAutomaticContentInsets?: boolean;
221 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
222 readonly onOpenConnectionEditor: () => void;
223 readonly onChangeDraftMessage: (value: string) => void;
224 readonly onPickDraftMedia: () => Promise<void>;
225 readonly onPickDraftFiles: () => Promise<void>;
226 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
227 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
228 readonly onRemoveDraftImage: (imageId: string) => void;
229 readonly onStopThread: () => void;
230 readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
231 readonly onReconnectEnvironment: () => void;
232 /** Whether the model picker may offer providers other than this thread's. */
233 readonly canSwitchThreadProvider: boolean;
234 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
235 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
236 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
237 readonly onRespondToApproval: (
238 requestId: RuntimeRequestId,
239 decision: ProviderApprovalDecision,
240 ) => Promise<unknown>;
241 readonly onSelectUserInputOption: (
242 requestId: RuntimeRequestId,
243 question: ThreadUserInputQuestion,
244 value: string,
245 ) => void;
246 readonly onChangeUserInputCustomAnswer: (
247 requestId: RuntimeRequestId,
248 questionId: string,
249 customAnswer: string,
250 ) => void;
251 readonly onSubmitUserInput: () => Promise<unknown>;
252 readonly onDismissUserInput: () => Promise<unknown>;
253 readonly showContent?: boolean;
254}
255
256function latestStreamingAssistantMessage(
257 feed: ReadonlyArray<ThreadFeedEntry>,
258): { readonly id: string; readonly textLength: number } | null {
259 for (let index = feed.length - 1; index >= 0; index -= 1) {
260 const entry = feed[index];
261 if (entry?.type !== "message") {
262 continue;
263 }
264 if (entry.message.role !== "assistant" || !entry.message.streaming) {
265 continue;
266 }
267 return {
268 id: entry.message.id,
269 textLength: entry.message.text.length,
270 };
271 }
272
273 return null;
274}
275
276function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
277 const lastStreamingAssistantRef = useRef<{
278 readonly id: string;
279 readonly textLength: number;
280 } | null>(null);
281 const lastStreamHapticAtRef = useRef(0);
282 const hydratedRef = useRef(false);
283 const previousThreadIdRef = useRef(threadId);
284
285 useEffect(() => {
286 if (previousThreadIdRef.current !== threadId) {
287 previousThreadIdRef.current = threadId;
288 hydratedRef.current = false;
289 }
290
291 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
292
293 if (!hydratedRef.current) {
294 hydratedRef.current = true;
295 lastStreamingAssistantRef.current = latestStreamingMessage;
296 return;
297 }
298
299 if (!latestStreamingMessage) {
300 lastStreamingAssistantRef.current = null;
301 return;
302 }
303
304 const previousStreamingMessage = lastStreamingAssistantRef.current;
305 lastStreamingAssistantRef.current = latestStreamingMessage;
306
307 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
308 const textGrew =
309 previousStreamingMessage?.id === latestStreamingMessage.id &&
310 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
311
312 if (!isNewStream && !textGrew) {
313 return;
314 }
315
316 const now = Date.now();
317 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
318 return;
319 }
320
321 lastStreamHapticAtRef.current = now;
322 void Haptics.selectionAsync();
323 }, [threadId, feed]);
324}
325
326const USER_INPUT_TOGGLE_TIMING = {
327 duration: USER_INPUT_TOGGLE_DURATION_MS,
328 easing: Easing.out(Easing.cubic),
329};
330
331export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
332 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
333 const navigation = useNavigation();
334 const { session: voiceInputSession } = useGlobalVoiceInput();
335 const reportedModelSelection = useThreadReportedModelSelection({
336 environmentId: props.environmentId,
337 threadId: props.selectedThread.id,
338 });
339 const deviceState = useEnvironmentQuery(
340 deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
341 );
342 const devicePreviews = useMemo(
343 () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
344 [deviceState.data, props.selectedThread.id],
345 );
346 const openDevicePreview = useCallback(() => {
347 Keyboard.dismiss();
348 navigation.navigate("ThreadDevicePreview", {
349 environmentId: props.environmentId,
350 threadId: props.selectedThread.id,
351 });
352 }, [navigation, props.environmentId, props.selectedThread.id]);
353 const browserTabs = useThreadServerBrowserTabs({
354 environmentId: props.environmentId,
355 threadId: props.selectedThread.id,
356 enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,
357 });
358 const openBrowserPreview = useCallback(
359 (tabId?: string) => {
360 Keyboard.dismiss();
361 navigation.navigate("ThreadBrowserPreview", {
362 environmentId: props.environmentId,
363 threadId: props.selectedThread.id,
364 ...(tabId === undefined ? {} : { tabId }),
365 });
366 },
367 [navigation, props.environmentId, props.selectedThread.id],
368 );
369 const insets = useSafeAreaInsets();
370 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
371 const liveKeyboardHeight = useKeyboardState((state) => state.height);
372 // Android can swallow the IME hide callbacks when the app is backgrounded
373 // mid keyboard-hide (the reported repro: send — which blurs and starts the
374 // hide — then Home within a second). The keyboard library's height AND
375 // visibility then stay frozen open, so gating the sticky translation on
376 // visibility alone still strands the composer after resume. Quarantine the
377 // translation on every Android resume instead; any sign of a live keyboard
378 // stream — an owned input gaining focus, or any visibility/height movement —
379 // lifts it. A healthy resume sees no visual difference (the translation is
380 // already zero while the keyboard is closed).
381 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
382 useEffect(() => {
383 if (Platform.OS !== "android") {
384 return;
385 }
386 const subscription = AppState.addEventListener("change", (state) => {
387 if (state === "active") {
388 setKeyboardStateSuspect(true);
389 }
390 });
391 return () => {
392 subscription.remove();
393 };
394 }, []);
395 useEffect(() => {
396 setKeyboardStateSuspect(false);
397 }, [isKeyboardVisible, liveKeyboardHeight]);
398 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
399 if (focused) {
400 setKeyboardStateSuspect(false);
401 }
402 }, []);
403 const windowHeight = useWindowDimensions().height;
404 const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
405 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
406 const columnMetrics = useNativeColumnLayoutMetrics();
407 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
408 const controlInsets = deriveBottomControlInsets(nativeMetrics);
409 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
410 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
411 const childThreadInputs = useChildThreadInputs({
412 environmentId: props.environmentId,
413 threadId: props.selectedThread.id,
414 });
415 const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null;
416 const queuedCount = useThreadQueuedCount({
417 environmentId: props.environmentId,
418 threadId: props.selectedThread.id,
419 });
420 const turnSubagents = useThreadTurnSubagents({
421 environmentId: props.environmentId,
422 threadId: props.selectedThread.id,
423 });
424 const agentsSegment = resolveSubagentPillSegment(turnSubagents);
425 const composerEditorRef = useRef<ComposerEditorHandle>(null);
426 // A provider-native subagent shows status instead of a composer.
427 const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);
428 // Entering edit mode from the queue sheet should land in a ready composer,
429 // not require a second tap on a composer already holding the message.
430 const editingRunId = props.queuedRunEdit?.runId ?? null;
431 useEffect(() => {
432 if (editingRunId === null) return;
433 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
434 return () => cancelAnimationFrame(frame);
435 }, [editingRunId]);
436 const draftMessageRef = useRef(props.draftMessage);
437 draftMessageRef.current = props.draftMessage;
438 const composerOverlayRef = useRef<ViewInstance>(null);
439 const listRef = useRef<LegendListRef>(null);
440 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
441 const selectedThreadKeyRef = useRef(selectedThreadKey);
442 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
443 const [composerExpanded, setComposerExpanded] = useState(false);
444 const [composerFocused, setComposerFocused] = useState(false);
445 const handleComposerFocusChange = useCallback(
446 (focused: boolean) => {
447 setComposerFocused(focused);
448 handleOwnedInputFocusChange(focused);
449 },
450 [handleOwnedInputFocusChange],
451 );
452 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
453 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
454 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
455 // Android keys the safe-area padding on keyboard visibility (#5988): the
456 // back gesture closes the keyboard while the editor stays focused, and a
457 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
458 // NOT use visibility — it only flips on keyboardDidHide, after the hide
459 // animation, so the composer would ride down flush to the screen edge and
460 // then snap up into the inset. On iOS blur precedes the hide, so the
461 // focus-keyed inset is already in place while the composer rides down.
462 // Dictation keeps that focus while the composer switches to its compact pill.
463 const composerBottomInset = (
464 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
465 )
466 ? 0
467 : Math.max(insets.bottom, 12);
468 const contentPresentationKind = props.contentPresentation.kind;
469 // The raw sync status enters "synchronizing" on every full fetch, cached or
470 // not. Whether messages are already on screen decides the pill label: no
471 // data yet → "Loading messages", cached data reconciling → "Syncing".
472 const realThreadSyncLabel = (() => {
473 switch (props.threadSyncStatus) {
474 case "empty":
475 case "cached":
476 case "synchronizing":
477 if (contentPresentationKind === "ready") {
478 return "Syncing messages...";
479 }
480 return contentPresentationKind === "loading" ? "Loading messages..." : null;
481 default:
482 return null;
483 }
484 })();
485 // Opening a running thread resyncs for a few frames. The pill shows the
486 // sync label only when the sync lasts, so it does not flash before the timer.
487 const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);
488 // One floating pill above the composer: it reads the connection phase while
489 // disconnected, the sync state while messages load, then the working timer
490 // once the feed is settled.
491 // The shell's roster is the server's post-settlement view of what still runs.
492 const pendingBackgroundWork = presentPendingBackgroundWork(
493 props.selectedThread.pendingBackgroundTasks,
494 );
495 const floatingStatus = ((): FloatingWorkingStatus | null => {
496 const connectionStatus = connectionFloatingStatus({
497 connectionError: props.connectionError,
498 connectionState: props.connectionStateLabel,
499 environmentLabel: props.environmentLabel,
500 onReconnect: props.onReconnectEnvironment,
501 });
502 if (connectionStatus !== null) {
503 return connectionStatus;
504 }
505 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
506 return null;
507 }
508 if (props.creationState?.kind === "preparing") {
509 // The setup header already reports progress in the feed.
510 if (props.worktreeSetup) return null;
511 return {
512 kind: "preparing",
513 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
514 };
515 }
516 if (props.creationState?.kind === "failed") {
517 return null;
518 }
519 if (threadSyncLabel !== null) {
520 return { kind: "syncing", label: threadSyncLabel };
521 }
522 const childInput = childThreadInputs[0];
523 if (childInput && contentPresentationKind === "ready") {
524 return {
525 kind: "child-input",
526 label:
527 childThreadInputs.length === 1
528 ? "Subagent needs input"
529 : `${childThreadInputs.length} subagents need input`,
530 accessibilityLabel: `Open question from ${childInput.title}`,
531 onPress: () => {
532 Keyboard.dismiss();
533 navigation.navigate("Thread", {
534 environmentId: props.environmentId,
535 threadId: childInput.id,
536 });
537 },
538 };
539 }
540 if (props.isCompacting && contentPresentationKind === "ready") {
541 return { kind: "compacting" };
542 }
543 if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
544 return { kind: "working", startedAt: props.activeWorkStartedAt };
545 }
546 if (pendingBackgroundWork !== null && contentPresentationKind === "ready") {
547 return {
548 kind: "background",
549 label: pendingBackgroundWork.title,
550 accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items
551 .map((item) => item.label)
552 .join(", ")}`,
553 waiting: pendingBackgroundWork.waiting,
554 };
555 }
556 if (props.selectedThread.goal !== null && contentPresentationKind === "ready") {
557 const goal = presentProviderGoal(props.selectedThread.goal, false);
558 return {
559 kind: "goal",
560 label: goal.title,
561 accessibilityLabel: `${goal.title}: ${goal.objective}`,
562 };
563 }
564 return null;
565 })();
566 const showWorkingControl = floatingStatus !== null;
567 // Connection and working status occupy the same space. Keep the feed inset
568 // stable when reconnecting hands off to syncing and then to a running turn.
569 const showFloatingStatus =
570 showWorkingControl ||
571 queuedCount > 0 ||
572 agentsSegment !== null ||
573 devicePreviews.length > 0 ||
574 browserTabs.tabs.length > 0 ||
575 props.connectionStateLabel !== "connected" ||
576 props.queuedMessages.length > 0 ||
577 props.selectedThreadFeed.some(
578 (entry) => "acknowledged" in entry && entry.acknowledged === true,
579 );
580 const selectedThreadFeed = props.selectedThreadFeed;
581 const hasCompactableConversation =
582 selectedThreadFeed.some(
583 (entry) =>
584 entry.type === "message" &&
585 entry.message.role === "user" &&
586 ((entry.message.attachments?.length ?? 0) > 0 ||
587 entry.message.text.trim().toLowerCase() !== "/compact"),
588 ) ||
589 (props.historyControls?.hasMoreHistory === true &&
590 props.selectedThread.latestUserMessageAt !== null);
591 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
592 const composerOverlapHeight = composerChrome + composerBottomInset;
593 // While a user-input request is pending, the questionnaire owns the
594 // composer slot outright: expanded it is the full card, collapsed it is a
595 // composer-style bar in the same place (with its own stop control). The
596 // composer never mounts into the transition, which keeps the collapse and
597 // keyboard animations coherent. Collapse state is keyed by request id so a
598 // new request re-expands automatically.
599 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
600 useState<RuntimeRequestId | null>(null);
601 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
602 // A pending user-input request or a failed creation owns the composer slot.
603 const composerSlotHidden =
604 activeUserInputRequestId !== null || props.creationState?.kind === "failed";
605 // The open /usage-limits panel for this thread, model and turn. Only the open
606 // moment is stored: the rows read live provider data, so a redeemed reset
607 // credit or refreshed probe shows through. Anything that spends quota closes
608 // it: a new turn from any source, or the agent resuming after an approval or
609 // answered question.
610 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
611 readonly key: string;
612 readonly threadKey: string;
613 readonly now: number;
614 } | null>(null);
615 // A pending approval or question is part of the key: once it is answered,
616 // from this client or any other, the agent resumes and spends quota.
617 const usageLimitsKey = [
618 selectedThreadKey,
619 props.selectedThread.modelSelection.instanceId,
620 props.selectedThread.latestRun?.runId ?? "",
621 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
622 ].join(":");
623 // Drop the snapshot as soon as the key changes so it cannot resurface stale.
624 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
625 setUsageLimitsPanel(null);
626 }
627 const usageLimitsReport = useMemo(
628 () =>
629 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
630 ? collectProviderUsageLimits(
631 props.selectedThread.modelSelection.instanceId,
632 props.serverConfig?.providers ?? [],
633 props.serverConfig?.usageLimitSources ?? [],
634 usageLimitsPanel.now,
635 )
636 : null,
637 [
638 props.selectedThread.modelSelection.instanceId,
639 props.serverConfig,
640 usageLimitsKey,
641 usageLimitsPanel,
642 ],
643 );
644 const showUsageLimits = useCallback(
645 (report: UsageLimitsReport | null) =>
646 setUsageLimitsPanel(
647 report === null
648 ? null
649 : {
650 key: usageLimitsKey,
651 threadKey: selectedThreadKey,
652 now: Date.parse(report.createdAt),
653 },
654 ),
655 [selectedThreadKey, usageLimitsKey],
656 );
657 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
658 // A send may resolve after navigating away, so only the originating
659 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
660 const clearUsageLimitsFor = useCallback(
661 (threadKey: string) =>
662 setUsageLimitsPanel((current) =>
663 current !== null && current.threadKey === threadKey ? null : current,
664 ),
665 [],
666 );
667 const userInputCollapsed =
668 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
669 // The card's height RESERVES keyboard space at all times instead of
670 // tracking the keyboard: transforms (the sticky translation) apply
671 // same-frame on the UI thread while layout props lag a Yoga pass behind,
672 // so any height that follows the keyboard flashes the card over the nav
673 // header on the way up. With a constant height the keyboard transition is
674 // pure translation — frame-perfect by construction — and the resting card
675 // stays compact over the transcript. Before the first open the reserve is
676 // an estimate; once a real height is known the card corrects once,
677 // discretely.
678 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
679 useEffect(() => {
680 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
681 setLastKnownKeyboardHeight(liveKeyboardHeight);
682 }
683 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
684 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
685 windowHeight,
686 keyboardHeight:
687 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
688 navigationHeaderHeight,
689 // The questionnaire owns the composer slot, so only the composer's
690 // bottom inset still overlaps.
691 composerOverlapHeight: composerBottomInset,
692 });
693 const estimatedOverlayHeight = composerOverlapHeight;
694 // The overlay's measured height includes the home-indicator inset (the
695 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
696 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
697 // dead strip between the resting content and the composer. Report the
698 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
699 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
700 // its end-scroll math matches the real resting position.
701 const nativeInsetOvercount =
702 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
703 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
704 listRef,
705 composerOverlayRef,
706 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
707 -nativeInsetOvercount,
708 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
709 );
710 // The expanded questionnaire is an absolute overlay on iOS, so it never
711 // changes the measured overlay height (that constancy is what keeps the
712 // feed from snapping on collapse/expand). The toggle choreography runs on
713 // SHARED VALUES set directly in the tap handler — one JS hop, then the
714 // card's rise/sink and the feed's end-inset glide animate in lockstep on
715 // the UI thread, keyboard-style, instead of waiting on React mount +
716 // onLayout + state round trips. Coverage (how far the card extends above
717 // the bar) is measured straight into a shared value by the card's
718 // onLayout, with no re-render.
719 const userInputCardProgress = useSharedValue(1);
720 const userInputInsetProgress = useSharedValue(1);
721 const userInputCardCoverage = useSharedValue(0);
722 const floatingControlCoverage = useSharedValue(
723 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
724 );
725 useEffect(() => {
726 floatingControlCoverage.value = withTiming(
727 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
728 { duration: 180, reduceMotion: ReduceMotion.System },
729 );
730 }, [floatingControlCoverage, showFloatingStatus]);
731 // Android renders the expanded card in-flow (it cannot hit-test the iOS
732 // overlay outside the bar's bounds), so its measured overlay height already
733 // includes the card — the coverage extra is iOS-only.
734 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
735 const combinedContentInsetEndAdjustment = useSharedValue(
736 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
737 );
738 useAnimatedReaction(
739 () =>
740 contentInsetEndAdjustment.value +
741 floatingControlCoverage.value +
742 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
743 (value) => {
744 combinedContentInsetEndAdjustment.value = value;
745 },
746 [userInputCoverageApplies],
747 );
748 // The floating control is anchored to the bar's top edge, so ride it up
749 // with the expanded card instead of drawing it over the questions.
750 const floatingControlLift = useDerivedValue(
751 () =>
752 userInputCoverageApplies ? userInputCardProgress.value * userInputCardCoverage.value : 0,
753 [userInputCoverageApplies],
754 );
755 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
756 const endFollowEnabledRef = useRef(true);
757 endFollowEnabledRef.current = endFollowEnabled;
758 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
759 const previousWorkingControlStateRef = useRef({
760 threadKey: selectedThreadKey,
761 visible: false,
762 });
763 // The list's own corrections for these inset changes drift on short
764 // content (and the error compounds across toggles), so deterministically
765 // re-pin the end once a toggle settles: a no-op when the resting position
766 // is already right, corrective when it is not. Follow state is re-checked
767 // inside the callback — the user may grab the list during the settle
768 // window, and yanking them back would override a live gesture.
769 const scheduleOverlayRepin = useCallback(
770 (delayMs: number) => {
771 if (overlayRepinTimerRef.current !== null) {
772 clearTimeout(overlayRepinTimerRef.current);
773 }
774 overlayRepinTimerRef.current = setTimeout(() => {
775 overlayRepinTimerRef.current = null;
776 if (!endFollowEnabledRef.current) {
777 return;
778 }
779 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
780 freeze.set(false);
781 });
782 }, delayMs);
783 },
784 [freeze, scrollMessageToEnd],
785 );
786 useEffect(
787 () => () => {
788 if (overlayRepinTimerRef.current !== null) {
789 clearTimeout(overlayRepinTimerRef.current);
790 }
791 },
792 [],
793 );
794 useEffect(() => {
795 const previous = previousWorkingControlStateRef.current;
796 const threadChanged = previous.threadKey !== selectedThreadKey;
797 const visibilityChanged = previous.visible !== showFloatingStatus;
798 previousWorkingControlStateRef.current = {
799 threadKey: selectedThreadKey,
800 visible: showFloatingStatus,
801 };
802 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
803 return;
804 }
805 // LegendList applies the larger inset but does not re-anchor short
806 // followed conversations when this floating coverage changes after the
807 // initial load. Re-pin after the finite inset transition; the callback
808 // checks follow state again so a user who scrolled up stays put.
809 scheduleOverlayRepin(230);
810 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
811 const handleToggleUserInputCollapsed = useCallback(() => {
812 if (activeUserInputRequestId === null) {
813 return;
814 }
815 if (userInputCollapsed) {
816 // Expanding: card and feed glide start NOW, on the UI thread.
817 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
818 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
819 setCollapsedUserInputRequestId(null);
820 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
821 } else {
822 // Collapsing hides the custom-answer inputs; release the keyboard with
823 // them instead of leaving it up over a dead responder.
824 Keyboard.dismiss();
825 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
826 // Instant: the sinking card still covers the strip being revealed, and
827 // animating the inset downward is what drifted the short-content end
828 // anchor.
829 userInputInsetProgress.value = 0;
830 setCollapsedUserInputRequestId(activeUserInputRequestId);
831 scheduleOverlayRepin(60);
832 }
833 }, [
834 activeUserInputRequestId,
835 scheduleOverlayRepin,
836 userInputCardProgress,
837 userInputCollapsed,
838 userInputInsetProgress,
839 ]);
840 useEffect(() => {
841 // A new request always arrives expanded.
842 userInputCardProgress.value = 1;
843 userInputInsetProgress.value = 1;
844 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
845 const showContent = props.showContent ?? true;
846 const layoutVariant = props.layoutVariant ?? "compact";
847 const isSplitLayout = layoutVariant === "split";
848 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
849 const providerSubagentProvider = props.serverConfig?.providers.find(
850 (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
851 );
852 // Providers can report a dated id or alias (claude-haiku-4-5-20251001).
853 const providerSubagentModelSlug = providerSubagentProvider
854 ? resolveSelectableModel(
855 providerSubagentProvider.driver,
856 props.selectedThread.modelSelection.model,
857 providerSubagentProvider.models,
858 )
859 : null;
860 const providerSubagentCatalogModel = providerSubagentProvider?.models.find(
861 (model) => model.slug === providerSubagentModelSlug,
862 );
863 const workspaceContentWidth = useWorkspaceContentWidth();
864 // Clearing animated width can retain the unfolded width after Android resumes folded.
865 // Assign both layouts explicitly so the dock always follows its current parent.
866 const composerWidthStyle = useAnimatedStyle(() =>
867 isSplitLayout && workspaceContentWidth !== null
868 ? {
869 width: Math.max(
870 0,
871 workspaceContentWidth.value - controlInsets.left - controlInsets.right,
872 ),
873 right: undefined,
874 }
875 : { width: undefined, right: controlInsets.right },
876 );
877 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
878 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
879 const selectedProviderSkills = useMemo(() => {
880 const provider = props.serverConfig?.providers.find(
881 (candidate) => candidate.instanceId === selectedInstanceId,
882 );
883 return provider
884 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
885 : [];
886 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
887
888 useLayoutEffect(() => {
889 selectedThreadKeyRef.current = selectedThreadKey;
890 // A replaced or unmounted native editor may not emit a blur event.
891 setComposerFocused(false);
892 }, [selectedThreadKey, showContent]);
893
894 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
895 const lastDispatchedVisitRef = useRef<string | null>(null);
896 const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
897 const selectedThreadId = props.selectedThread.id;
898 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
899 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
900 const selectedThreadCompletedAt = props.selectedThread.latestRun?.completedAt;
901 useEffect(() => {
902 // Records the server-side visited watermark while the thread is on
903 // screen (mirror of web ChatView), so the "Done" marker clears on every
904 // device. Field absent → the server predates visited tracking.
905 if (!showContent || selectedThreadLastVisitedAt === undefined) return;
906 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
907 if (Number.isNaN(threadUpdatedAtMs)) return;
908 const lastVisitedAtMs = selectedThreadLastVisitedAt
909 ? Date.parse(selectedThreadLastVisitedAt)
910 : NaN;
911 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
912 // Dedupe per watermark — the effect re-runs before the command echo lands.
913 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
914 if (lastDispatchedVisitRef.current === dispatchKey) return;
915 const dispatch = () => {
916 lastDispatchedVisitRef.current = dispatchKey;
917 lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
918 void visitThread({
919 environmentId: props.environmentId,
920 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
921 });
922 };
923 // Completion clears unread state immediately; streaming watermarks use the
924 // same ten-second trailing throttle as web, keeping the newest update.
925 const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
926 const hasUnseenCompletion =
927 !Number.isNaN(completedAtMs) &&
928 (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
929 const previous = lastVisitDispatchRef.current;
930 const elapsed = Date.now() - previous.at;
931 if (previous.threadKey !== selectedThreadKey || hasUnseenCompletion || elapsed >= 10_000) {
932 dispatch();
933 return;
934 }
935 const timer = setTimeout(dispatch, 10_000 - elapsed);
936 return () => clearTimeout(timer);
937 }, [
938 props.environmentId,
939 selectedThreadId,
940 selectedThreadKey,
941 selectedThreadLastVisitedAt,
942 selectedThreadCompletedAt,
943 selectedThreadUpdatedAt,
944 showContent,
945 visitThread,
946 ]);
947
948 useEffect(() => {
949 setAnchorMessageId(null);
950 setSubmittedMessageId(null);
951 lastScrolledSubmittedMessageIdRef.current = null;
952 setEndFollowEnabled(true);
953 freeze.set(false);
954 }, [freeze, selectedThreadKey]);
955
956 useEffect(() => {
957 if (
958 submittedMessageId === null ||
959 anchorMessageId !== submittedMessageId ||
960 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
961 contentPresentationKind !== "ready" ||
962 (!selectedThreadFeed.some(
963 (entry) => entry.type === "message" && entry.id === submittedMessageId,
964 ) &&
965 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
966 ) {
967 return;
968 }
969
970 const targetThreadKey = selectedThreadKey;
971 const frame = requestAnimationFrame(() => {
972 if (selectedThreadKeyRef.current !== targetThreadKey) {
973 return;
974 }
975 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
976 // Wait for the keyboard dismissal (started by blur() on send) to finish
977 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
978 // updates while it runs, and a close event swallowed by that freeze
979 // leaves the keyboard padding permanently applied — overshooting the
980 // anchor and leaving a phantom bottom inset once the reply streams in.
981 void KeyboardController.dismiss()
982 .then(() => {
983 if (
984 selectedThreadKeyRef.current !== targetThreadKey ||
985 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
986 ) {
987 return;
988 }
989 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
990 })
991 .catch(() => {
992 if (
993 selectedThreadKeyRef.current !== targetThreadKey ||
994 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
995 ) {
996 return;
997 }
998 lastScrolledSubmittedMessageIdRef.current = null;
999 freeze.set(false);
1000 });
1001 });
1002 return () => cancelAnimationFrame(frame);
1003 }, [
1004 anchorMessageId,
1005 submittedMessageId,
1006 freeze,
1007 contentPresentationKind,
1008 props.queuedMessages,
1009 selectedThreadFeed,
1010 scrollMessageToEnd,
1011 selectedThreadKey,
1012 ]);
1013
1014 const handleSendMessage = useCallback(
1015 async (followUp?: ActiveTurnComposerAction) => {
1016 const targetThreadKey = selectedThreadKey;
1017 const hasUserMessage = selectedThreadFeed.some(
1018 (entry) => entry.type === "message" && entry.message.role === "user",
1019 );
1020 const messageId = await props.onSendMessage(followUp);
1021 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
1022 return messageId;
1023 }
1024
1025 // A sent message makes the snapshot stale; a refused send leaves it in place.
1026 clearUsageLimitsFor(targetThreadKey);
1027
1028 setSubmittedMessageId(messageId);
1029 setAnchorMessageId(
1030 resolveThreadFeedSubmissionAnchor({
1031 currentAnchorMessageId: anchorMessageId,
1032 submittedMessageId: messageId,
1033 hasStartedTurn: props.selectedThread.latestRun !== null,
1034 hasUserMessage,
1035 queuedMessageCount: props.selectedThreadQueueCount,
1036 }),
1037 );
1038 composerEditorRef.current?.blur();
1039 return messageId;
1040 },
1041 [
1042 anchorMessageId,
1043 clearUsageLimitsFor,
1044 props.onSendMessage,
1045 props.selectedThread.latestRun,
1046 props.selectedThreadQueueCount,
1047 selectedThreadFeed,
1048 selectedThreadKey,
1049 ],
1050 );
1051
1052 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
1053 try {
1054 if (
1055 (await editPendingThreadMessage(message)) &&
1056 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
1057 ) {
1058 composerEditorRef.current?.focus();
1059 }
1060 } catch (error) {
1061 Alert.alert(
1062 "Could not edit message",
1063 error instanceof Error ? error.message : "Please try again.",
1064 );
1065 }
1066 }, []);
1067
1068 const collapseComposer = useCallback(() => {
1069 composerEditorRef.current?.blur();
1070 }, []);
1071
1072 const handleUseArtifactTemplate = useCallback(
1073 (template: CodexArtifactTemplate) => {
1074 const currentDraft = draftMessageRef.current;
1075 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
1076 if (nextDraft !== currentDraft) {
1077 draftMessageRef.current = nextDraft;
1078 props.onChangeDraftMessage(nextDraft);
1079 }
1080 requestAnimationFrame(() => {
1081 composerEditorRef.current?.focus();
1082 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
1083 });
1084 },
1085 [props.onChangeDraftMessage],
1086 );
1087
1088 const handleScrollToEnd = useCallback(() => {
1089 void Haptics.selectionAsync();
1090 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
1091 freeze.set(false);
1092 });
1093 }, [freeze, scrollMessageToEnd]);
1094
1095 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
1096 const { themeAppearance } = useAppearancePreferences();
1097 const isDarkMode = themeAppearance === "dark";
1098
1099 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
1100 feedTouchStartRef.current = {
1101 pageX: event.nativeEvent.pageX,
1102 pageY: event.nativeEvent.pageY,
1103 };
1104 }, []);
1105
1106 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
1107 const start = feedTouchStartRef.current;
1108 if (!start) {
1109 return;
1110 }
1111 const deltaX = event.nativeEvent.pageX - start.pageX;
1112 const deltaY = event.nativeEvent.pageY - start.pageY;
1113 if (Math.hypot(deltaX, deltaY) > 8) {
1114 feedTouchStartRef.current = null;
1115 }
1116 }, []);
1117
1118 const handleFeedTouchEnd = useCallback(() => {
1119 if (feedTouchStartRef.current) {
1120 collapseComposer();
1121 }
1122 feedTouchStartRef.current = null;
1123 }, [collapseComposer]);
1124
1125 const handleFeedTouchCancel = useCallback(() => {
1126 feedTouchStartRef.current = null;
1127 }, []);
1128
1129 return (
1130 <View className="flex-1">
1131 {!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
1132 {showContent ? (
1133 <View
1134 style={{ flex: 1 }}
1135 onTouchStart={handleFeedTouchStart}
1136 onTouchMove={handleFeedTouchMove}
1137 onTouchEnd={handleFeedTouchEnd}
1138 onTouchCancel={handleFeedTouchCancel}
1139 >
1140 <View
1141 pointerEvents="none"
1142 className={
1143 Platform.OS === "android"
1144 ? "absolute inset-0 bg-thread-canvas"
1145 : "absolute inset-0 bg-screen"
1146 }
1147 />
1148 <RenderErrorBoundary
1149 key={selectedThreadKey}
1150 resetKeys={[props.threadCwd]}
1151 renderFallback={(fallback) => (
1152 <RenderFailureView
1153 {...fallback}
1154 title="The conversation couldn't be displayed"
1155 bottomInset={estimatedOverlayHeight}
1156 />
1157 )}
1158 >
1159 <ThreadFeed
1160 environmentId={props.environmentId}
1161 threadId={props.selectedThread.id}
1162 workspaceRoot={props.threadCwd}
1163 feed={props.selectedThreadFeed}
1164 pendingHandoff={props.pendingHandoff}
1165 worktreeSetup={props.worktreeSetup}
1166 setupWorkingStartedAt={props.setupWorkingStartedAt}
1167 queuedMessages={props.queuedMessages}
1168 dispatchingMessageId={props.dispatchingMessageId}
1169 // A native subagent has no composer to edit a pending message in;
1170 // Cancel on the edit banner would discard it.
1171 onEditPendingMessage={isProviderSubagent ? null : handleEditPendingMessage}
1172 contentPresentation={props.contentPresentation}
1173 agentLabel={agentLabel}
1174 threadTitle={props.selectedThread.title}
1175 latestRun={props.activityRun}
1176 activeWorkStartedAt={props.activeWorkStartedAt}
1177 runlessWorkActive={props.runlessWorkActive ?? false}
1178 listRef={listRef}
1179 freeze={freeze}
1180 anchorMessageId={anchorMessageId}
1181 submittedMessageId={submittedMessageId}
1182 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1183 contentTopInset={0}
1184 contentBottomInset={
1185 estimatedOverlayHeight +
1186 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1187 }
1188 contentMaxWidth={contentMaxWidth}
1189 historyControls={props.historyControls}
1190 contentSideInsets={nativeMetrics?.safeArea}
1191 layoutVariant={layoutVariant}
1192 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1193 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1194 onEndFollowEnabledChange={setEndFollowEnabled}
1195 skills={selectedProviderSkills}
1196 onUseArtifactTemplate={handleUseArtifactTemplate}
1197 />
1198 </RenderErrorBoundary>
1199 </View>
1200 ) : (
1201 <View className="flex-1" />
1202 )}
1203
1204 {showContent ? (
1205 <ThreadBrowserFloat
1206 key={selectedThreadKey}
1207 environmentId={props.environmentId}
1208 threadId={props.selectedThread.id}
1209 tabs={browserTabs.tabs}
1210 loaded={browserTabs.loaded}
1211 top={navigationHeaderHeight + 8}
1212 onOpen={openBrowserPreview}
1213 />
1214 ) : null}
1215
1216 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
1217 {showContent ? (
1218 <KeyboardStickyView
1219 // iOS emits a native animated height target on both will-show and
1220 // will-hide, so stay subscribed for the full transition. Android
1221 // retains its background/resume stale-state quarantine.
1222 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
1223 pointerEvents="box-none"
1224 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
1225 offset={{ closed: 0, opened: 0 }}
1226 >
1227 <ComposerPopoverHost hidden={composerSlotHidden}>
1228 {/* The fixed sticky host gives this bottom-anchored child a stable
1229 coordinate space. Its top and height can then animate together
1230 instead of the auto-sized host jumping to Yoga's destination. */}
1231 <Animated.View
1232 layout={COMPOSER_LAYOUT_TRANSITION}
1233 pointerEvents="box-none"
1234 style={[
1235 {
1236 position: "absolute",
1237 bottom: controlInsets.bottom,
1238 left: controlInsets.left,
1239 right: controlInsets.right,
1240 },
1241 composerWidthStyle,
1242 ]}
1243 >
1244 {/* No paddingTop here: the overlay's measured height becomes the
1245 list's bottom inset, so any padding above the pill/composer
1246 pushes the resting content floor up by the same amount. */}
1247 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
1248 <FloatingWorkingControl
1249 colorScheme={isDarkMode ? "dark" : "light"}
1250 status={floatingStatus}
1251 lift={floatingControlLift}
1252 devicePreview={
1253 devicePreviews.length > 0
1254 ? { count: devicePreviews.length, onPress: openDevicePreview }
1255 : null
1256 }
1257 browserPreview={
1258 browserTabs.tabs.length > 0
1259 ? { count: browserTabs.tabs.length, onPress: () => openBrowserPreview() }
1260 : null
1261 }
1262 showScrollToEnd={showScrollToEndButton}
1263 onScrollToEnd={handleScrollToEnd}
1264 agents={agentsSegment}
1265 onOpenAgents={() => {
1266 Keyboard.dismiss();
1267 navigation.navigate("ThreadAgents", {
1268 environmentId: props.environmentId,
1269 threadId: props.selectedThread.id,
1270 });
1271 }}
1272 queuedCount={queuedCount}
1273 onOpenQueue={() => {
1274 Keyboard.dismiss();
1275 navigation.navigate("ThreadQueue", {
1276 environmentId: props.environmentId,
1277 threadId: props.selectedThread.id,
1278 });
1279 }}
1280 />
1281 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1282 {props.queuedRunEdit !== null ? (
1283 <Animated.View
1284 className="shrink-0"
1285 entering={FadeInDown.duration(180)}
1286 exiting={FadeOut.duration(120)}
1287 >
1288 <ComposerQueuedEditBanner
1289 saving={props.isSavingQueuedEdit}
1290 onCancel={() => {
1291 voiceInputSession.cancel(props.composerDraftKey);
1292 props.onCancelQueuedRunEdit();
1293 }}
1294 />
1295 </Animated.View>
1296 ) : null}
1297 <UsageLimitRecoveryCard
1298 key={props.selectedThread.latestRun?.runId}
1299 thread={props.selectedThread}
1300 environmentId={props.environmentId}
1301 />
1302 {props.feedbackSubmissions.map((submission) => (
1303 <ComposerFeedback
1304 key={submission.id}
1305 submission={submission}
1306 onDismiss={() => props.onDismissFeedback(submission.id)}
1307 />
1308 ))}
1309 {composerError !== null ? (
1310 <Animated.View
1311 className="shrink-0"
1312 entering={FadeInDown.duration(180)}
1313 exiting={FadeOut.duration(120)}
1314 >
1315 <ComposerErrorNotice
1316 message={composerError}
1317 onDismiss={() => clearThreadComposerError(selectedThreadKey)}
1318 />
1319 </Animated.View>
1320 ) : null}
1321 {usageLimitsReport && activeUserInputRequestId === null ? (
1322 <Animated.View
1323 className="shrink-0 px-4 pb-3"
1324 entering={FadeInDown.duration(220)}
1325 exiting={FadeOut.duration(140)}
1326 >
1327 <ComposerUsageLimits
1328 report={usageLimitsReport}
1329 environmentId={props.environmentId}
1330 onClose={dismissUsageLimits}
1331 />
1332 </Animated.View>
1333 ) : null}
1334 {props.creationState?.kind === "failed" ? (
1335 <Animated.View
1336 className="shrink-0 px-4"
1337 style={{ paddingBottom: composerBottomInset }}
1338 entering={FadeInDown.duration(220)}
1339 exiting={FadeOut.duration(140)}
1340 >
1341 <ThreadCreationFailedCard
1342 reason={props.creationState.reason}
1343 onEditTask={props.creationState.onEditTask}
1344 />
1345 </Animated.View>
1346 ) : null}
1347 {props.activePendingApproval || props.activePendingUserInput ? (
1348 <Animated.View
1349 className="shrink-0 gap-3 px-4 pb-3"
1350 // The questionnaire replaces the composer, so it must pad
1351 // the home indicator the composer normally covers.
1352 style={
1353 activeUserInputRequestId !== null
1354 ? { paddingBottom: composerBottomInset }
1355 : undefined
1356 }
1357 entering={FadeInDown.duration(220)}
1358 exiting={FadeOut.duration(140)}
1359 >
1360 {props.activePendingApproval ? (
1361 <PendingApprovalCard
1362 canOperateThread={props.canOperateThread}
1363 approval={props.activePendingApproval}
1364 respondingApprovalId={props.respondingApprovalId}
1365 onRespond={props.onRespondToApproval}
1366 />
1367 ) : null}
1368 {props.activePendingUserInput ? (
1369 <PendingUserInputCard
1370 canOperateThread={props.canOperateThread}
1371 pendingUserInput={props.activePendingUserInput}
1372 maxHeight={pendingUserInputMaxHeight}
1373 collapsed={userInputCollapsed}
1374 onToggleCollapsed={handleToggleUserInputCollapsed}
1375 onStopThread={props.onStopThread}
1376 cardProgress={userInputCardProgress}
1377 cardCoverage={userInputCardCoverage}
1378 onInputFocusChange={handleOwnedInputFocusChange}
1379 drafts={props.activePendingUserInputDrafts}
1380 answers={props.activePendingUserInputAnswers}
1381 respondingUserInputId={props.respondingUserInputId}
1382 onSelectOption={props.onSelectUserInputOption}
1383 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1384 onSubmit={props.onSubmitUserInput}
1385 onDismiss={props.onDismissUserInput}
1386 />
1387 ) : null}
1388 </Animated.View>
1389 ) : null}
1390 </View>
1391
1392 {/* Hidden (not unmounted) while a user-input request owns the
1393 composer slot, so composer drafts and editor state survive.
1394 A rejected creation has no thread to send to; the failure card
1395 owns the slot instead. */}
1396 <View style={composerSlotHidden ? { display: "none" } : undefined}>
1397 {isProviderSubagent ? (
1398 <View
1399 className="self-center px-3 pt-1.5"
1400 style={{
1401 width: "100%",
1402 maxWidth: contentMaxWidth,
1403 paddingBottom: composerBottomInset + 6,
1404 }}
1405 >
1406 <ProviderSubagentBar
1407 provider={providerSubagentProvider ?? null}
1408 modelLabel={
1409 providerSubagentCatalogModel?.name ??
1410 formatModelSlugName(props.selectedThread.modelSelection.model)
1411 }
1412 effortLabel={formatModelSelectionEffort(
1413 props.selectedThread.modelSelection,
1414 providerSubagentProvider?.models,
1415 reportedModelSelection,
1416 )}
1417 status={props.providerSubagentStatus ?? null}
1418 onOpenParent={
1419 props.selectedThread.lineage.parentThreadId === null
1420 ? null
1421 : () =>
1422 navigation.navigate("Thread", {
1423 environmentId: String(props.environmentId),
1424 threadId: String(props.selectedThread.lineage.parentThreadId),
1425 })
1426 }
1427 />
1428 </View>
1429 ) : (
1430 <>
1431 <ThreadComposer
1432 canOperateThread={props.canOperateThread}
1433 reportedModelSelection={reportedModelSelection}
1434 editorRef={composerEditorRef}
1435 draftMessage={props.draftMessage}
1436 draftAttachments={props.draftAttachments}
1437 placeholder="Ask the repo agent, or run a command…"
1438 contentMaxWidth={contentMaxWidth}
1439 connectionState={props.connectionStateLabel}
1440 environmentLabel={props.environmentLabel}
1441 selectedThread={props.selectedThread}
1442 hasCompactableConversation={
1443 hasCompactableConversation && !props.isCompacting
1444 }
1445 serverConfig={props.serverConfig}
1446 queueCount={props.selectedThreadQueueCount}
1447 activeThreadBusy={props.activeThreadBusy}
1448 canStopThread={props.canStopThread}
1449 environmentId={props.environmentId}
1450 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1451 // Follow-ups typed before the server creates the thread wait in
1452 // the draft: queueing them against a thread id the server may
1453 // still reject would strand them in the outbox.
1454 sendBlockedReason={
1455 props.creationState?.kind === "preparing" &&
1456 !props.creationState.serverOwned
1457 ? "Starting the task…"
1458 : null
1459 }
1460 draftKey={props.composerDraftKey ?? undefined}
1461 followUpBehavior={props.followUpBehavior}
1462 canSteerActiveTurn={props.canSteerActiveTurn}
1463 queuedEdit={
1464 props.queuedRunEdit === null
1465 ? null
1466 : {
1467 existingAttachments: props.queuedRunEdit.existingAttachments,
1468 saving: props.isSavingQueuedEdit,
1469 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1470 }
1471 }
1472 bottomInset={composerBottomInset}
1473 onChangeDraftMessage={props.onChangeDraftMessage}
1474 onPickDraftMedia={props.onPickDraftMedia}
1475 onPickDraftFiles={props.onPickDraftFiles}
1476 onNativePasteImages={props.onNativePasteImages}
1477 onNativePasteText={props.onNativePasteText}
1478 onRemoveDraftImage={props.onRemoveDraftImage}
1479 onStopThread={props.onStopThread}
1480 onSendMessage={handleSendMessage}
1481 onShowUsageLimits={showUsageLimits}
1482 canSwitchProvider={props.canSwitchThreadProvider}
1483 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1484 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1485 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1486 onExpandedChange={setComposerExpanded}
1487 onEditorFocusChange={handleComposerFocusChange}
1488 />
1489 </>
1490 )}
1491 </View>
1492 </View>
1493 </Animated.View>
1494 </ComposerPopoverHost>
1495 </KeyboardStickyView>
1496 ) : null}
1497 </View>
1498 );
1499});