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