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