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

ThreadDetailScreen.tsx

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