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