Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailScreen.tsx

1,408 lines58.6 KB

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;
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;
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]);
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.
367 // An input that kept focus through the switch is exempt: Android restores its
368 // keyboard unchanged, so nothing would lift the quarantine.
369 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
370 const ownedInputFocusedRef = useRef(false);
371 useEffect(() => {
372 if (Platform.OS !== "android") {
373 return;
374 }
375 const subscription = AppState.addEventListener("change", (state) => {
376 if (state === "active") {
377 setKeyboardStateSuspect(!ownedInputFocusedRef.current);
378 }
379 });
380 return () => {
381 subscription.remove();
382 };
383 }, []);
384 useEffect(() => {
385 setKeyboardStateSuspect(false);
386 }, [isKeyboardVisible, liveKeyboardHeight]);
387 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
388 ownedInputFocusedRef.current = focused;
389 if (focused) {
390 setKeyboardStateSuspect(false);
391 }
392 }, []);
393 const windowHeight = useWindowDimensions().height;
394 const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
395 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
396 const columnMetrics = useNativeColumnLayoutMetrics();
397 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
398 const controlInsets = deriveBottomControlInsets(nativeMetrics);
399 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
400 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
401 const childThreadInputs = useChildThreadInputs({
402 environmentId: props.environmentId,
403 threadId: props.selectedThread.id,
404 });
405 const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null;
406 const queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef);
407 const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef);
408 const agentsSegment = resolveSubagentPillSegment(turnSubagents);
409 const composerEditorRef = useRef<ComposerEditorHandle>(null);
410 const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);
411 const editingRunId = props.queuedRunEdit?.runId ?? null;
412 useEffect(() => {
413 if (editingRunId === null) return;
414 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
415 return () => cancelAnimationFrame(frame);
416 }, [editingRunId]);
417 const draftMessageRef = useRef(props.draftMessage);
418 draftMessageRef.current = props.draftMessage;
419 const composerOverlayRef = useRef<ViewInstance>(null);
420 const listRef = useRef<LegendListRef>(null);
421 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
422 const selectedThreadKeyRef = useRef(selectedThreadKey);
423 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
424 const [composerExpanded, setComposerExpanded] = useState(false);
425 const [composerFocused, setComposerFocused] = useState(false);
426 const handleComposerFocusChange = useCallback(
427 (focused: boolean) => {
428 setComposerFocused(focused);
429 handleOwnedInputFocusChange(focused);
430 },
431 [handleOwnedInputFocusChange],
432 );
433 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
434 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
435 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
436 // Android keys the safe-area padding on keyboard visibility (#5988): the back gesture closes
437 // the keyboard while the editor stays focused, and a focus-keyed inset would leave the toolbar
438 // under the gesture bar. iOS must NOT use visibility — it only flips on keyboardDidHide, after
439 // the hide animation, so the composer would ride down flush to the screen edge and then snap up
440 // into the inset.
441 const composerBottomInset = (
442 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
443 )
444 ? 0
445 : Math.max(insets.bottom, 12);
446 const contentPresentationKind = props.contentPresentation.kind;
447 const realThreadSyncLabel = (() => {
448 switch (props.threadSyncStatus) {
449 case "empty":
450 case "cached":
451 case "synchronizing":
452 if (contentPresentationKind === "ready") {
453 return "Syncing messages...";
454 }
455 return contentPresentationKind === "loading" ? "Loading messages..." : null;
456 default:
457 return null;
458 }
459 })();
460 const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);
461 const pendingBackgroundWork = presentPendingBackgroundWork(
462 props.selectedThread.pendingBackgroundTasks,
463 );
464 const floatingStatus = ((): FloatingWorkingStatus | null => {
465 const connectionStatus = connectionFloatingStatus({
466 connectionError: props.connectionError,
467 connectionState: props.connectionStateLabel,
468 environmentLabel: props.environmentLabel,
469 onReconnect: props.onReconnectEnvironment,
470 });
471 if (connectionStatus !== null) {
472 return connectionStatus;
473 }
474 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
475 return null;
476 }
477 if (props.creationState?.kind === "preparing") {
478 if (props.worktreeSetup) return null;
479 return {
480 kind: "preparing",
481 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
482 };
483 }
484 if (props.creationState?.kind === "failed") {
485 return null;
486 }
487 if (threadSyncLabel !== null) {
488 return { kind: "syncing", label: threadSyncLabel };
489 }
490 const childInput = childThreadInputs[0];
491 if (childInput && contentPresentationKind === "ready") {
492 return {
493 kind: "child-input",
494 label: childThreadInputsTitle(childThreadInputs),
495 accessibilityLabel: `Open ${childInput.hasPendingApprovals ? "approval" : "question"} from ${childInput.title}`,
496 onPress: () => {
497 Keyboard.dismiss();
498 navigation.navigate("Thread", {
499 environmentId: props.environmentId,
500 threadId: childInput.id,
501 });
502 },
503 };
504 }
505 if (props.isCompacting && contentPresentationKind === "ready") {
506 return { kind: "compacting" };
507 }
508 if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
509 return { kind: "working", startedAt: props.activeWorkStartedAt };
510 }
511 if (pendingBackgroundWork !== null && contentPresentationKind === "ready") {
512 return {
513 kind: "background",
514 label: pendingBackgroundWork.title,
515 accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items
516 .map((item) => item.label)
517 .join(", ")}`,
518 waiting: pendingBackgroundWork.waiting,
519 };
520 }
521 if (props.selectedThread.goal !== null && contentPresentationKind === "ready") {
522 const goal = presentProviderGoal(props.selectedThread.goal, false);
523 return {
524 kind: "goal",
525 label: goal.title,
526 accessibilityLabel: `${goal.title}: ${goal.objective}`,
527 };
528 }
529 return null;
530 })();
531 const showWorkingControl = floatingStatus !== null;
532 const showFloatingStatus =
533 showWorkingControl ||
534 queuedCount > 0 ||
535 agentsSegment !== null ||
536 devicePreviews.length > 0 ||
537 browserTabs.tabs.length > 0 ||
538 props.connectionStateLabel !== "connected" ||
539 props.queuedMessages.length > 0 ||
540 props.selectedThreadFeed.some(
541 (entry) => "acknowledged" in entry && entry.acknowledged === true,
542 );
543 const selectedThreadFeed = props.selectedThreadFeed;
544 const hasCompactableConversation =
545 selectedThreadFeed.some(
546 (entry) =>
547 entry.type === "message" &&
548 entry.message.role === "user" &&
549 ((entry.message.attachments?.length ?? 0) > 0 ||
550 entry.message.text.trim().toLowerCase() !== "/compact"),
551 ) ||
552 (props.historyControls?.hasMoreHistory === true &&
553 props.selectedThread.latestUserMessageAt !== null);
554 const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
555 const composerOverlapHeight = composerChrome + composerBottomInset;
556 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
557 useState<RuntimeRequestId | null>(null);
558 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
559 const composerSlotHidden =
560 activeUserInputRequestId !== null || props.creationState?.kind === "failed";
561 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
562 readonly key: string;
563 readonly threadKey: string;
564 readonly now: number;
565 } | null>(null);
566 // A pending approval or question is part of the key: once it is answered,
567 // from this client or any other, the agent resumes and spends quota.
568 const usageLimitsKey = [
569 selectedThreadKey,
570 props.selectedThread.modelSelection.instanceId,
571 props.selectedThread.latestRun?.runId ?? "",
572 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
573 ].join(":");
574 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
575 setUsageLimitsPanel(null);
576 }
577 const usageLimitsReport = useMemo(
578 () =>
579 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
580 ? collectProviderUsageLimits(
581 props.selectedThread.modelSelection.instanceId,
582 props.serverConfig?.providers ?? [],
583 props.serverConfig?.usageLimitSources ?? [],
584 usageLimitsPanel.now,
585 )
586 : null,
587 [
588 props.selectedThread.modelSelection.instanceId,
589 props.serverConfig,
590 usageLimitsKey,
591 usageLimitsPanel,
592 ],
593 );
594 const showUsageLimits = useCallback(
595 (report: UsageLimitsReport | null) =>
596 setUsageLimitsPanel(
597 report === null
598 ? null
599 : {
600 key: usageLimitsKey,
601 threadKey: selectedThreadKey,
602 now: Date.parse(report.createdAt),
603 },
604 ),
605 [selectedThreadKey, usageLimitsKey],
606 );
607 const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
608 // A send may resolve after navigating away, so only the originating
609 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
610 const clearUsageLimitsFor = useCallback(
611 (threadKey: string) =>
612 setUsageLimitsPanel((current) =>
613 current !== null && current.threadKey === threadKey ? null : current,
614 ),
615 [],
616 );
617 const userInputCollapsed =
618 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
619 // The card's height RESERVES keyboard space at all times instead of tracking the keyboard:
620 // transforms (the sticky translation) apply same-frame on the UI thread while layout props lag
621 // a Yoga pass behind, so any height that follows the keyboard flashes the card over the nav
622 // header on the way up.
623 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
624 useEffect(() => {
625 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
626 setLastKnownKeyboardHeight(liveKeyboardHeight);
627 }
628 }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
629 const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
630 windowHeight,
631 keyboardHeight:
632 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
633 navigationHeaderHeight,
634 composerOverlapHeight: composerBottomInset,
635 });
636 const estimatedOverlayHeight = composerOverlapHeight;
637 // The overlay's measured height includes the home-indicator inset (the
638 // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
639 // UIKit add the safe-area bottom to the content inset AGAIN — leaving a
640 // dead strip between the resting content and the composer. Report the
641 // overlay height minus the safe area; UIKit adds it back, and ThreadFeed
642 // hands LegendList the same delta via contentInsetEndStaticAdjustment so
643 // its end-scroll math matches the real resting position.
644 const nativeInsetOvercount =
645 props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
646 const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
647 listRef,
648 composerOverlayRef,
649 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
650 -nativeInsetOvercount,
651 Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
652 );
653 const userInputCardProgress = useSharedValue(1);
654 const userInputInsetProgress = useSharedValue(1);
655 const userInputCardCoverage = useSharedValue(0);
656 const floatingControlCoverage = useSharedValue(
657 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
658 );
659 useEffect(() => {
660 floatingControlCoverage.value = withTiming(
661 showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
662 { duration: 180, reduceMotion: ReduceMotion.System },
663 );
664 }, [floatingControlCoverage, showFloatingStatus]);
665 // Android renders the expanded card in-flow (it cannot hit-test the iOS
666 // overlay outside the bar's bounds), so its measured overlay height already
667 // includes the card — the coverage extra is iOS-only.
668 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
669 const combinedContentInsetEndAdjustment = useSharedValue(
670 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
671 );
672 useAnimatedReaction(
673 () =>
674 contentInsetEndAdjustment.value +
675 floatingControlCoverage.value +
676 (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
677 (value) => {
678 combinedContentInsetEndAdjustment.value = value;
679 },
680 [userInputCoverageApplies],
681 );
682 const floatingControlLift = useDerivedValue(
683 () =>
684 userInputCoverageApplies ? userInputCardProgress.value * userInputCardCoverage.value : 0,
685 [userInputCoverageApplies],
686 );
687 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
688 const endFollowEnabledRef = useRef(true);
689 endFollowEnabledRef.current = endFollowEnabled;
690 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
691 const previousWorkingControlStateRef = useRef({
692 threadKey: selectedThreadKey,
693 visible: false,
694 });
695 const scheduleOverlayRepin = useCallback(
696 (delayMs: number) => {
697 if (overlayRepinTimerRef.current !== null) {
698 clearTimeout(overlayRepinTimerRef.current);
699 }
700 overlayRepinTimerRef.current = setTimeout(() => {
701 overlayRepinTimerRef.current = null;
702 if (!endFollowEnabledRef.current) {
703 return;
704 }
705 void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
706 freeze.set(false);
707 });
708 }, delayMs);
709 },
710 [freeze, scrollMessageToEnd],
711 );
712 useEffect(
713 () => () => {
714 if (overlayRepinTimerRef.current !== null) {
715 clearTimeout(overlayRepinTimerRef.current);
716 }
717 },
718 [],
719 );
720 useEffect(() => {
721 const previous = previousWorkingControlStateRef.current;
722 const threadChanged = previous.threadKey !== selectedThreadKey;
723 const visibilityChanged = previous.visible !== showFloatingStatus;
724 previousWorkingControlStateRef.current = {
725 threadKey: selectedThreadKey,
726 visible: showFloatingStatus,
727 };
728 if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
729 return;
730 }
731 // LegendList applies the larger inset but does not re-anchor short
732 // followed conversations when this floating coverage changes after the
733 // initial load. Re-pin after the finite inset transition; the callback
734 // checks follow state again so a user who scrolled up stays put.
735 scheduleOverlayRepin(230);
736 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
737 const handleToggleUserInputCollapsed = useCallback(() => {
738 if (activeUserInputRequestId === null) {
739 return;
740 }
741 if (userInputCollapsed) {
742 userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
743 userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
744 setCollapsedUserInputRequestId(null);
745 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
746 } else {
747 Keyboard.dismiss();
748 userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
749 // Instant: the sinking card still covers the strip being revealed, and
750 // animating the inset downward is what drifted the short-content end
751 // anchor.
752 userInputInsetProgress.value = 0;
753 setCollapsedUserInputRequestId(activeUserInputRequestId);
754 scheduleOverlayRepin(60);
755 }
756 }, [
757 activeUserInputRequestId,
758 scheduleOverlayRepin,
759 userInputCardProgress,
760 userInputCollapsed,
761 userInputInsetProgress,
762 ]);
763 useEffect(() => {
764 userInputCardProgress.value = 1;
765 userInputInsetProgress.value = 1;
766 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
767 const showContent = props.showContent ?? true;
768 const layoutVariant = props.layoutVariant ?? "compact";
769 const isSplitLayout = layoutVariant === "split";
770 const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
771 const providerSubagentProvider = props.serverConfig?.providers.find(
772 (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
773 );
774 const providerSubagentModelSlug = providerSubagentProvider
775 ? resolveSelectableModel(
776 providerSubagentProvider.driver,
777 props.selectedThread.modelSelection.model,
778 providerSubagentProvider.models,
779 )
780 : null;
781 const providerSubagentCatalogModel = providerSubagentProvider?.models.find(
782 (model) => model.slug === providerSubagentModelSlug,
783 );
784 const workspaceContentWidth = useWorkspaceContentWidth();
785 // Clearing animated width can retain the unfolded width after Android resumes folded.
786 const composerWidthStyle = useAnimatedStyle(() =>
787 isSplitLayout && workspaceContentWidth !== null
788 ? {
789 width: Math.max(
790 0,
791 workspaceContentWidth.value - controlInsets.left - controlInsets.right,
792 ),
793 right: undefined,
794 }
795 : { width: undefined, right: controlInsets.right },
796 );
797 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
798 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
799 const selectedProviderSkills = useMemo(() => {
800 const provider = props.serverConfig?.providers.find(
801 (candidate) => candidate.instanceId === selectedInstanceId,
802 );
803 return provider
804 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
805 : [];
806 }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
807​
808 useLayoutEffect(() => {
809 selectedThreadKeyRef.current = selectedThreadKey;
810 // A replaced or unmounted native editor may not emit a blur event.
811 setComposerFocused(false);
812 }, [selectedThreadKey, showContent]);
813​
814 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
815 const lastDispatchedVisitRef = useRef<string | null>(null);
816 const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
817 const selectedThreadId = props.selectedThread.id;
818 const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
819 const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
820 const selectedThreadCompletedAt = props.selectedThread.latestRun?.completedAt;
821 useEffect(() => {
822 if (!showContent || selectedThreadLastVisitedAt === undefined) return;
823 const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
824 if (Number.isNaN(threadUpdatedAtMs)) return;
825 const lastVisitedAtMs = selectedThreadLastVisitedAt
826 ? Date.parse(selectedThreadLastVisitedAt)
827 : NaN;
828 if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
829 const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
830 if (lastDispatchedVisitRef.current === dispatchKey) return;
831 const dispatch = () => {
832 lastDispatchedVisitRef.current = dispatchKey;
833 lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
834 void visitThread({
835 environmentId: props.environmentId,
836 input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
837 });
838 };
839 const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
840 const hasUnseenCompletion =
841 !Number.isNaN(completedAtMs) &&
842 (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
843 const previous = lastVisitDispatchRef.current;
844 const elapsed = Date.now() - previous.at;
845 if (previous.threadKey !== selectedThreadKey || hasUnseenCompletion || elapsed >= 10_000) {
846 dispatch();
847 return;
848 }
849 const timer = setTimeout(dispatch, 10_000 - elapsed);
850 return () => clearTimeout(timer);
851 }, [
852 props.environmentId,
853 selectedThreadId,
854 selectedThreadKey,
855 selectedThreadLastVisitedAt,
856 selectedThreadCompletedAt,
857 selectedThreadUpdatedAt,
858 showContent,
859 visitThread,
860 ]);
861​
862 useEffect(() => {
863 setAnchorMessageId(null);
864 setSubmittedMessageId(null);
865 lastScrolledSubmittedMessageIdRef.current = null;
866 setEndFollowEnabled(true);
867 freeze.set(false);
868 }, [freeze, selectedThreadKey]);
869​
870 useEffect(() => {
871 if (
872 submittedMessageId === null ||
873 anchorMessageId !== submittedMessageId ||
874 lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
875 contentPresentationKind !== "ready" ||
876 (!selectedThreadFeed.some(
877 (entry) => entry.type === "message" && entry.id === submittedMessageId,
878 ) &&
879 !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
880 ) {
881 return;
882 }
883​
884 const targetThreadKey = selectedThreadKey;
885 const frame = requestAnimationFrame(() => {
886 if (selectedThreadKeyRef.current !== targetThreadKey) {
887 return;
888 }
889 lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
890 // Wait for the keyboard dismissal (started by blur() on send) to finish
891 // before scrolling: scrollMessageToEnd freezes keyboard-driven inset
892 // updates while it runs, and a close event swallowed by that freeze
893 // leaves the keyboard padding permanently applied — overshooting the
894 // anchor and leaving a phantom bottom inset once the reply streams in.
895 void KeyboardController.dismiss()
896 .then(() => {
897 if (
898 selectedThreadKeyRef.current !== targetThreadKey ||
899 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
900 ) {
901 return;
902 }
903 return scrollMessageToEnd({ animated: true, closeKeyboard: false });
904 })
905 .catch(() => {
906 if (
907 selectedThreadKeyRef.current !== targetThreadKey ||
908 lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
909 ) {
910 return;
911 }
912 lastScrolledSubmittedMessageIdRef.current = null;
913 freeze.set(false);
914 });
915 });
916 return () => cancelAnimationFrame(frame);
917 }, [
918 anchorMessageId,
919 submittedMessageId,
920 freeze,
921 contentPresentationKind,
922 props.queuedMessages,
923 selectedThreadFeed,
924 scrollMessageToEnd,
925 selectedThreadKey,
926 ]);
927​
928 const handleSendMessage = useCallback(
929 async (followUp?: ActiveTurnComposerAction) => {
930 const targetThreadKey = selectedThreadKey;
931 const hasUserMessage = selectedThreadFeed.some(
932 (entry) => entry.type === "message" && entry.message.role === "user",
933 );
934 const messageId = await props.onSendMessage(followUp);
935 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
936 return messageId;
937 }
938​
939 clearUsageLimitsFor(targetThreadKey);
940​
941 setSubmittedMessageId(messageId);
942 setAnchorMessageId(
943 resolveThreadFeedSubmissionAnchor({
944 currentAnchorMessageId: anchorMessageId,
945 submittedMessageId: messageId,
946 hasStartedTurn: props.selectedThread.latestRun !== null,
947 hasUserMessage,
948 queuedMessageCount: props.selectedThreadQueueCount,
949 }),
950 );
951 composerEditorRef.current?.blur();
952 return messageId;
953 },
954 [
955 anchorMessageId,
956 clearUsageLimitsFor,
957 props.onSendMessage,
958 props.selectedThread.latestRun,
959 props.selectedThreadQueueCount,
960 selectedThreadFeed,
961 selectedThreadKey,
962 ],
963 );
964​
965 const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
966 try {
967 if (
968 (await editPendingThreadMessage(message)) &&
969 selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
970 ) {
971 composerEditorRef.current?.focus();
972 }
973 } catch (error) {
974 Dialog.alert(
975 "Could not edit message",
976 error instanceof Error ? error.message : "Please try again.",
977 );
978 }
979 }, []);
980​
981 const collapseComposer = useCallback(() => {
982 composerEditorRef.current?.blur();
983 }, []);
984​
985 const handleUseArtifactTemplate = useCallback(
986 (template: CodexArtifactTemplate) => {
987 const currentDraft = draftMessageRef.current;
988 const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
989 if (nextDraft !== currentDraft) {
990 draftMessageRef.current = nextDraft;
991 props.onChangeDraftMessage(nextDraft);
992 }
993 requestAnimationFrame(() => {
994 composerEditorRef.current?.focus();
995 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
996 });
997 },
998 [props.onChangeDraftMessage],
999 );
1000​
1001 const handleScrollToEnd = useCallback(() => {
1002 void Haptics.selectionAsync();
1003 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
1004 freeze.set(false);
1005 });
1006 }, [freeze, scrollMessageToEnd]);
1007​
1008 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
1009 const { themeAppearance } = useAppearancePreferences();
1010 const isDarkMode = themeAppearance === "dark";
1011​
1012 const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
1013 feedTouchStartRef.current = {
1014 pageX: event.nativeEvent.pageX,
1015 pageY: event.nativeEvent.pageY,
1016 };
1017 }, []);
1018​
1019 const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
1020 const start = feedTouchStartRef.current;
1021 if (!start) {
1022 return;
1024 const deltaX = event.nativeEvent.pageX - start.pageX;
1025 const deltaY = event.nativeEvent.pageY - start.pageY;
1026 if (Math.hypot(deltaX, deltaY) > 8) {
1027 feedTouchStartRef.current = null;
1029 }, []);
1030​
1031 const handleFeedTouchEnd = useCallback(() => {
1032 if (feedTouchStartRef.current) {
1033 collapseComposer();
1035 feedTouchStartRef.current = null;
1036 }, [collapseComposer]);
1037​
1038 const handleFeedTouchCancel = useCallback(() => {
1039 feedTouchStartRef.current = null;
1040 }, []);
1041​
1042 return (
1043 <View className="flex-1">
1044 {!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
1045 {showContent ? (
1046 <View
1047 style={{ flex: 1 }}
1048 onTouchStart={handleFeedTouchStart}
1049 onTouchMove={handleFeedTouchMove}
1050 onTouchEnd={handleFeedTouchEnd}
1051 onTouchCancel={handleFeedTouchCancel}
1053 <View
1054 pointerEvents="none"
1055 className={
1056 Platform.OS === "android"
1057 ? "absolute inset-0 bg-thread-canvas"
1058 : "absolute inset-0 bg-screen"
1060 />
1061 <RenderErrorBoundary
1062 key={selectedThreadKey}
1063 resetKeys={[props.threadCwd]}
1064 renderFallback={(fallback) => (
1065 <RenderFailureView
1066 {...fallback}
1067 title="The conversation couldn't be displayed"
1068 bottomInset={estimatedOverlayHeight}
1069 />
1070 )}
1072 <ThreadFeed
1073 environmentId={props.environmentId}
1074 threadId={props.selectedThread.id}
1075 workspaceRoot={props.threadCwd}
1076 feed={props.selectedThreadFeed}
1077 pendingHandoff={props.pendingHandoff}
1078 worktreeSetup={props.worktreeSetup}
1079 setupWorkingStartedAt={props.setupWorkingStartedAt}
1080 queuedMessages={props.queuedMessages}
1081 dispatchingMessageId={props.dispatchingMessageId}
1082 // A native subagent has no composer to edit a pending message in;
1083 // Cancel on the edit banner would discard it.
1084 onEditPendingMessage={isProviderSubagent ? null : handleEditPendingMessage}
1085 contentPresentation={props.contentPresentation}
1086 agentLabel={agentLabel}
1087 threadTitle={props.selectedThread.title}
1088 latestRun={props.activityRun}
1089 activeWorkStartedAt={props.activeWorkStartedAt}
1090 runlessWorkActive={props.runlessWorkActive ?? false}
1091 listRef={listRef}
1092 freeze={freeze}
1093 anchorMessageId={anchorMessageId}
1094 submittedMessageId={submittedMessageId}
1095 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1096 contentTopInset={0}
1097 contentBottomInset={
1098 estimatedOverlayHeight +
1099 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1101 contentMaxWidth={contentMaxWidth}
1102 historyControls={props.historyControls}
1103 contentSideInsets={nativeMetrics?.safeArea}
1104 layoutVariant={layoutVariant}
1105 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1106 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1107 onEndFollowEnabledChange={setEndFollowEnabled}
1108 skills={selectedProviderSkills}
1109 onUseArtifactTemplate={handleUseArtifactTemplate}
1110 />
1111 </RenderErrorBoundary>
1112 </View>
1113 ) : (
1114 <View className="flex-1" />
1115 )}
1116​
1117 {showContent ? (
1118 <ThreadBrowserFloat
1119 key={selectedThreadKey}
1120 environmentId={props.environmentId}
1121 threadId={props.selectedThread.id}
1122 tabs={browserTabs.tabs}
1123 loaded={browserTabs.loaded}
1124 top={navigationHeaderHeight + 8}
1125 onOpen={openBrowserPreview}
1126 />
1127 ) : null}
1128​
1129 {showContent ? (
1130 <KeyboardStickyView
1131 // iOS emits a native animated height target on both will-show and
1132 // will-hide, so stay subscribed for the full transition.
1133 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
1134 pointerEvents="box-none"
1135 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
1136 offset={{ closed: 0, opened: 0 }}
1138 <ComposerPopoverHost hidden={composerSlotHidden}>
1139 {/* The fixed sticky host gives this bottom-anchored child a stable
1140 coordinate space. Its top and height can then animate together
1141 instead of the auto-sized host jumping to Yoga's destination. */}
1142 <Animated.View
1143 layout={COMPOSER_LAYOUT_TRANSITION}
1144 pointerEvents="box-none"
1145 style={[
1147 position: "absolute",
1148 bottom: controlInsets.bottom,
1149 left: controlInsets.left,
1150 right: controlInsets.right,
1151 },
1152 composerWidthStyle,
1153 ]}
1155 {/* No paddingTop here: the overlay's measured height becomes the
1156 list's bottom inset, so any padding above the pill/composer
1157 pushes the resting content floor up by the same amount. */}
1158 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
1159 <FloatingWorkingControl
1160 colorScheme={isDarkMode ? "dark" : "light"}
1161 status={floatingStatus}
1162 lift={floatingControlLift}
1163 devicePreview={
1164 devicePreviews.length > 0
1165 ? { count: devicePreviews.length, onPress: openDevicePreview }
1166 : null
1168 browserPreview={
1169 browserTabs.tabs.length > 0
1170 ? { count: browserTabs.tabs.length, onPress: () => openBrowserPreview() }
1171 : null
1173 showScrollToEnd={showScrollToEndButton}
1174 onScrollToEnd={handleScrollToEnd}
1175 agents={agentsSegment}
1176 onOpenAgents={() => {
1177 Keyboard.dismiss();
1178 navigation.navigate("ThreadAgents", {
1179 environmentId: props.environmentId,
1180 threadId: props.selectedThread.id,
1181 });
1182 }}
1183 queuedCount={queuedCount}
1184 onOpenQueue={() => {
1185 Keyboard.dismiss();
1186 navigation.navigate("ThreadQueue", {
1187 environmentId: props.environmentId,
1188 threadId: props.selectedThread.id,
1189 });
1190 }}
1191 />
1192 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1193 {props.queuedRunEdit !== null ? (
1194 <Animated.View
1195 className="shrink-0"
1196 entering={FadeInDown.duration(180)}
1197 exiting={FadeOut.duration(120)}
1199 <ComposerQueuedEditBanner
1200 saving={props.isSavingQueuedEdit}
1201 onCancel={() => {
1202 voiceInputSession.cancel(props.composerDraftKey);
1203 props.onCancelQueuedRunEdit();
1204 }}
1205 />
1206 </Animated.View>
1207 ) : null}
1208 <UsageLimitRecoveryCard
1209 key={props.selectedThread.latestRun?.runId}
1210 thread={props.selectedThread}
1211 environmentId={props.environmentId}
1212 />
1213 {props.feedbackSubmissions.map((submission) => (
1214 <ComposerFeedback
1215 key={submission.id}
1216 submission={submission}
1217 onDismiss={() => props.onDismissFeedback(submission.id)}
1218 />
1219 ))}
1220 {composerError !== null ? (
1221 <Animated.View
1222 className="shrink-0"
1223 entering={FadeInDown.duration(180)}
1224 exiting={FadeOut.duration(120)}
1226 <ComposerErrorNotice
1227 message={composerError}
1228 onDismiss={() => clearThreadComposerError(selectedThreadKey)}
1229 />
1230 </Animated.View>
1231 ) : null}
1232 {usageLimitsReport && activeUserInputRequestId === null ? (
1233 <Animated.View
1234 className="shrink-0 px-4 pb-3"
1235 entering={FadeInDown.duration(220)}
1236 exiting={FadeOut.duration(140)}
1238 <ComposerUsageLimits
1239 report={usageLimitsReport}
1240 environmentId={props.environmentId}
1241 onClose={dismissUsageLimits}
1242 />
1243 </Animated.View>
1244 ) : null}
1245 {props.creationState?.kind === "failed" ? (
1246 <Animated.View
1247 className="shrink-0 px-4"
1248 style={{ paddingBottom: composerBottomInset }}
1249 entering={FadeInDown.duration(220)}
1250 exiting={FadeOut.duration(140)}
1252 <ThreadCreationFailedCard
1253 reason={props.creationState.reason}
1254 onEditTask={props.creationState.onEditTask}
1255 />
1256 </Animated.View>
1257 ) : null}
1258 {props.activePendingApproval || props.activePendingUserInput ? (
1259 <Animated.View
1260 className="shrink-0 gap-3 px-4 pb-3"
1261 style={
1262 activeUserInputRequestId !== null
1263 ? { paddingBottom: composerBottomInset }
1264 : undefined
1266 entering={FadeInDown.duration(220)}
1267 exiting={FadeOut.duration(140)}
1269 {props.activePendingApproval ? (
1270 <PendingApprovalCard
1271 canOperateThread={props.canOperateThread}
1272 approval={props.activePendingApproval}
1273 respondingApprovalId={props.respondingApprovalId}
1274 onRespond={props.onRespondToApproval}
1275 />
1276 ) : null}
1277 {props.activePendingUserInput ? (
1278 <PendingUserInputCard
1279 canOperateThread={props.canOperateThread}
1280 pendingUserInput={props.activePendingUserInput}
1281 maxHeight={pendingUserInputMaxHeight}
1282 collapsed={userInputCollapsed}
1283 onToggleCollapsed={handleToggleUserInputCollapsed}
1284 onStopThread={props.onStopThread}
1285 cardProgress={userInputCardProgress}
1286 cardCoverage={userInputCardCoverage}
1287 onInputFocusChange={handleOwnedInputFocusChange}
1288 drafts={props.activePendingUserInputDrafts}
1289 answers={props.activePendingUserInputAnswers}
1290 respondingUserInputId={props.respondingUserInputId}
1291 onSelectOption={props.onSelectUserInputOption}
1292 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1293 onSubmit={props.onSubmitUserInput}
1294 onDismiss={props.onDismissUserInput}
1295 />
1296 ) : null}
1297 </Animated.View>
1298 ) : null}
1299 </View>
1300​
1301 {/*
1302 * Hidden (not unmounted) while a user-input request owns the composer slot, so
1303 * composer drafts and editor state survive.
1304 */}
1305 <View style={composerSlotHidden ? { display: "none" } : undefined}>
1306 {isProviderSubagent ? (
1307 <View
1308 className="self-center px-3 pt-1.5"
1309 style={{
1310 width: "100%",
1311 maxWidth: contentMaxWidth,
1312 paddingBottom: composerBottomInset + 6,
1313 }}
1315 <ProviderSubagentBar
1316 provider={providerSubagentProvider ?? null}
1317 modelLabel={
1318 providerSubagentCatalogModel?.name ??
1319 formatModelSlugName(props.selectedThread.modelSelection.model)
1321 effortLabel={formatModelSelectionEffort(
1322 props.selectedThread.modelSelection,
1323 providerSubagentProvider?.models,
1324 reportedModelSelection,
1325 )}
1326 status={props.providerSubagentStatus ?? null}
1327 onOpenParent={
1328 props.selectedThread.lineage.parentThreadId === null
1329 ? null
1330 : () =>
1331 navigation.navigate("Thread", {
1332 environmentId: String(props.environmentId),
1333 threadId: String(props.selectedThread.lineage.parentThreadId),
1334 })
1336 />
1337 </View>
1338 ) : (
1339 <>
1340 <ThreadComposer
1341 canOperateThread={props.canOperateThread}
1342 reportedModelSelection={reportedModelSelection}
1343 editorRef={composerEditorRef}
1344 draftMessage={props.draftMessage}
1345 draftAttachments={props.draftAttachments}
1346 placeholder="Ask the repo agent, or run a command…"
1347 contentMaxWidth={contentMaxWidth}
1348 connectionState={props.connectionStateLabel}
1349 environmentLabel={props.environmentLabel}
1350 selectedThread={props.selectedThread}
1351 hasCompactableConversation={
1352 hasCompactableConversation && !props.isCompacting
1354 serverConfig={props.serverConfig}
1355 queueCount={props.selectedThreadQueueCount}
1356 activeThreadBusy={props.activeThreadBusy}
1357 canStopThread={props.canStopThread}
1358 environmentId={props.environmentId}
1359 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1360 // Follow-ups typed before the server creates the thread wait in
1361 // the draft: queueing them against a thread id the server may
1362 // still reject would strand them in the outbox.
1363 sendBlockedReason={
1364 props.creationState?.kind === "preparing" &&
1365 !props.creationState.serverOwned
1366 ? "Starting the task…"
1367 : null
1369 draftKey={props.composerDraftKey ?? undefined}
1370 followUpBehavior={props.followUpBehavior}
1371 canSteerActiveTurn={props.canSteerActiveTurn}
1372 queuedEdit={
1373 props.queuedRunEdit === null
1374 ? null
1375 : {
1376 existingAttachments: props.queuedRunEdit.existingAttachments,
1377 saving: props.isSavingQueuedEdit,
1378 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1381 bottomInset={composerBottomInset}
1382 onChangeDraftMessage={props.onChangeDraftMessage}
1383 onPickDraftMedia={props.onPickDraftMedia}
1384 onPickDraftFiles={props.onPickDraftFiles}
1385 onNativePasteImages={props.onNativePasteImages}
1386 onNativePasteText={props.onNativePasteText}
1387 onRemoveDraftImage={props.onRemoveDraftImage}
1388 onStopThread={props.onStopThread}
1389 onSendMessage={handleSendMessage}
1390 onShowUsageLimits={showUsageLimits}
1391 canSwitchProvider={props.canSwitchThreadProvider}
1392 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1393 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1394 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1395 onExpandedChange={setComposerExpanded}
1396 onEditorFocusChange={handleComposerFocusChange}
1397 />
1398 </>
1399 )}
1400 </View>
1401 </View>
1402 </Animated.View>
1403 </ComposerPopoverHost>
1404 </KeyboardStickyView>
1405 ) : null}
1406 </View>
1407 );
1408});