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