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