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

ThreadDetailScreen.tsx

1,497 lines64.4 KB

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 { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
10import {
11 childThreadInputsTitle,
12 type CodexFeedbackSubmission,
13 type EnvironmentThreadStatus,
14} from "@t3tools/client-runtime/state/threads";
15import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
16import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
17import type { LegendListRef } from "@legendapp/list/react-native";
18import { HeaderHeightContext } from "@react-navigation/elements";
19import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
20import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/reserved-regions";
21import type {
22 EnvironmentId,
23 MessageId,
24 ModelSelection,
25 ProviderApprovalDecision,
26 ProviderInteractionMode,
27 RuntimeMode,
28 RuntimeRequestId,
29 ServerConfig as T3ServerConfig,
30 ThreadId,
31 UsageLimitsReport,
32} from "@t3tools/contracts";
33import {
34 appendCodexArtifactTemplateUsePrompt,
35 type CodexArtifactTemplate,
36} from "@t3tools/shared/codexArtifactTemplates";
37import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
38import {
39 presentPendingBackgroundWork,
40 presentProviderGoal,
41} from "@t3tools/client-runtime/state/thread-execution";
42import { resolveSubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
43import {
44 formatModelSelectionEffort,
45 type ProviderSubagentStatus,
46} from "@t3tools/client-runtime/state/thread-execution";
47import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
48import { isProviderNativeSubagentThread } from "@t3tools/contracts";
49import type { QueuedRunEdit } from "../../state/queued-run-edit";
50import type { FollowUpBehavior } from "../../lib/followUpBehavior";
51import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
52import * as Haptics from "expo-haptics";
53import {
54 memo,
55 useCallback,
56 useContext,
57 useEffect,
58 useLayoutEffect,
59 useMemo,
60 useRef,
61 useState,
62} from "react";
63import {
64 Alert,
65 AppState,
66 Keyboard,
67 Platform,
68 useWindowDimensions,
69 View,
70 type GestureResponderEvent,
71 type ViewInstance,
72} from "react-native";
73import {
74 KeyboardController,
75 KeyboardStickyView,
76 useKeyboardState,
77} from "react-native-keyboard-controller";
78import Animated, {
79 Easing,
80 FadeInDown,
81 FadeOut,
82 ReduceMotion,
83 useAnimatedReaction,
84 useAnimatedStyle,
85 useDerivedValue,
86 useSharedValue,
87 withTiming,
88} from "react-native-reanimated";
89import { useSafeAreaInsets } from "react-native-safe-area-context";
90import { useWorkspaceContentWidth } from "../layout/workspace-content-width";
91import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
92import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
93import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
94import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
95import type { ComposerEditorHandle } from "../../components/ComposerEditor";
96import type { StatusTone } from "../../components/StatusPill";
97import type { DraftComposerAttachment } from "../../lib/composerImages";
98import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
99import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
100import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
101import { deviceEnvironment } from "../../state/device";
102import { useEnvironmentQuery } from "../../state/query";
103import { threadDevicePreviews } from "../devices/threadDevicePreviews";
104import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
105import { useThreadServerBrowserTabs } from "../../state/preview";
106import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
107import { scopedThreadKey } from "../../lib/scopedEntities";
108import {
109 clearThreadComposerError,
110 threadComposerErrorsAtom,
111} from "../../state/thread-composer-error";
112import { threadEnvironment } from "../../state/threads";
113import { useAtomCommand } from "../../state/use-atom-command";
114import { useDelayedStatus } from "../../lib/useDelayedStatus";
115import type {
116 PendingApproval,
117 PendingUserInput,
118 PendingUserInputDraftAnswer,
119 ThreadFeedEntry,
120 ThreadFeedLatestRun,
121} from "../../lib/threadActivity";
122import { PendingApprovalCard } from "./PendingApprovalCard";
123import { ComposerErrorNotice } from "./ComposerErrorNotice";
124import { ComposerFeedback } from "./ComposerFeedback";
125import { ComposerUsageLimits } from "./ComposerUsageLimits";
126import { PendingUserInputCard } from "./PendingUserInputCard";
127import { ProviderSubagentBar } from "./ProviderSubagentBar";
128import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
129import {
130 FLOATING_WORKING_CONTROL_COVERAGE,
131 FloatingWorkingControl,
132} from "./floating-working-control";
133import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status";
134import {
135 derivePendingUserInputMaxHeight,
136 ESTIMATED_KEYBOARD_HEIGHT,
137 USER_INPUT_TOGGLE_DURATION_MS,
138} from "./pendingUserInputLayout";
139import {
140 COMPOSER_COLLAPSED_CHROME,
141 COMPOSER_EXPANDED_CHROME,
142 COMPOSER_LAYOUT_TRANSITION,
143 COMPOSER_TRANSITION_DURATION_MS,
144 ThreadComposer,
145} from "./ThreadComposer";
146import { ComposerPopoverHost } from "./ComposerPopoverHost";
147import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
148import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
149import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
150import { useThreadQueuedCount } from "./ThreadQueueControl";
151import type { ThreadContentPresentation } from "./threadContentPresentation";
152import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
153import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
154​
155export interface ThreadDetailScreenProps {
156 readonly worktreeSetup?: WorktreeSetupCardProps | null;
157 readonly setupWorkingStartedAt?: string | null;
158 readonly canOperateThread: boolean;
159 readonly selectedThread: EnvironmentThreadShell;
160 readonly contentPresentation: ThreadContentPresentation;
161 readonly screenTone: StatusTone;
162 readonly connectionError: string | null;
163 readonly environmentLabel: string | null;
164 readonly feedbackSubmissions: ReadonlyArray<CodexFeedbackSubmission>;
165 readonly onDismissFeedback: (id: MessageId) => void;
166 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
167 readonly pendingHandoff?: HandoffEndpoints | null;
168 readonly activityRun: ThreadFeedLatestRun | null;
169 readonly activeWorkStartedAt: string | null;
170 /** The live work is a provider-native subagent's runless root turn. */
171 readonly runlessWorkActive?: boolean;
172 /** Set on a provider-native subagent thread, which shows status instead of a composer. */
173 readonly providerSubagentStatus?: ProviderSubagentStatus | null;
174 readonly isCompacting: boolean;
175 /**
176 * The server has not created this thread yet. "preparing" runs while the
177 * queued creation is delivered (a worktree may be checking out); "failed"
178 * is a rejected creation whose content went back to the project draft.
179 * `serverOwned` marks a thread the server already created that is still
180 * setting up its worktree; follow-ups queue on the server behind that setup.
181 */
182 readonly creationState:
183 | {
184 readonly kind: "preparing";
185 readonly preparingWorktree: boolean;
186 readonly serverOwned: boolean;
187 }
188 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
189 | null;
190 readonly activePendingApproval: PendingApproval | null;
191 readonly respondingApprovalId: RuntimeRequestId | null;
192 readonly activePendingUserInput: PendingUserInput | null;
193 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
194 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
195 readonly respondingUserInputId: RuntimeRequestId | null;
196 readonly draftMessage: string;
197 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
198 readonly connectionStateLabel: EnvironmentConnectionPhase;
199 /** Message sync status for the selected thread (drives the composer status pill). */
200 readonly threadSyncStatus?: EnvironmentThreadStatus;
201 /** Progressive history controls for oversized mobile thread opens. */
202 readonly historyControls?: ThreadFeedHistoryControls;
203 readonly activeThreadBusy: boolean;
204 readonly canStopThread: boolean;
205 /** Set while a queued message is open in the composer for editing. */
206 readonly queuedRunEdit: QueuedRunEdit | null;
207 readonly composerDraftKey: string | null;
208 readonly followUpBehavior: FollowUpBehavior;
209 readonly canSteerActiveTurn: boolean;
210 readonly isSavingQueuedEdit: boolean;
211 readonly onCancelQueuedRunEdit: () => void;
212 readonly onRemoveQueuedEditAttachment: (attachmentId: string) => void;
213 readonly environmentId: EnvironmentId;
214 readonly projectWorkspaceRoot: string | null;
215 readonly threadCwd: string | null;
216 readonly selectedThreadQueueCount: number;
217 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
218 readonly dispatchingMessageId: MessageId | null;
219 readonly serverConfig: T3ServerConfig | null;
220 readonly layoutVariant?: LayoutVariant;
221 readonly usesAutomaticContentInsets?: boolean;
222 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
223 readonly onOpenConnectionEditor: () => void;
224 readonly onChangeDraftMessage: (value: string) => void;
225 readonly onPickDraftMedia: () => Promise<void>;
226 readonly onPickDraftFiles: () => Promise<void>;
227 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
228 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
229 readonly onRemoveDraftImage: (imageId: string) => void;
230 readonly onStopThread: () => void;
231 readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
232 readonly onReconnectEnvironment: () => void;
233 /** Whether the model picker may offer providers other than this thread's. */
234 readonly canSwitchThreadProvider: boolean;
235 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
236 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
237 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
238 readonly onRespondToApproval: (
239 requestId: RuntimeRequestId,
240 decision: ProviderApprovalDecision,
241 ) => Promise<unknown>;
242 readonly onSelectUserInputOption: (
243 requestId: RuntimeRequestId,
244 question: ThreadUserInputQuestion,
245 value: string,
246 ) => void;
247 readonly onChangeUserInputCustomAnswer: (
248 requestId: RuntimeRequestId,
249 questionId: string,
250 customAnswer: string,
251 ) => void;
252 readonly onSubmitUserInput: () => Promise<unknown>;
253 readonly onDismissUserInput: () => Promise<unknown>;
254 readonly showContent?: boolean;
256​
257function latestStreamingAssistantMessage(
258 feed: ReadonlyArray<ThreadFeedEntry>,
259): { readonly id: string; readonly textLength: number } | null {
260 for (let index = feed.length - 1; index >= 0; index -= 1) {
261 const entry = feed[index];
262 if (entry?.type !== "message") {
263 continue;
264 }
265 if (entry.message.role !== "assistant" || !entry.message.streaming) {
266 continue;
267 }
268 return {
269 id: entry.message.id,
270 textLength: entry.message.text.length,
271 };
272 }
273​
274 return null;
276​
277function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
278 const lastStreamingAssistantRef = useRef<{
279 readonly id: string;
280 readonly textLength: number;
281 } | null>(null);
282 const lastStreamHapticAtRef = useRef(0);
283 const hydratedRef = useRef(false);
284 const previousThreadIdRef = useRef(threadId);
285​
286 useEffect(() => {
287 if (previousThreadIdRef.current !== threadId) {
288 previousThreadIdRef.current = threadId;
289 hydratedRef.current = false;
290 }
291​
292 const latestStreamingMessage = latestStreamingAssistantMessage(feed);
293​
294 if (!hydratedRef.current) {
295 hydratedRef.current = true;
296 lastStreamingAssistantRef.current = latestStreamingMessage;
297 return;
298 }
299​
300 if (!latestStreamingMessage) {
301 lastStreamingAssistantRef.current = null;
302 return;
303 }
304​
305 const previousStreamingMessage = lastStreamingAssistantRef.current;
306 lastStreamingAssistantRef.current = latestStreamingMessage;
307​
308 const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
309 const textGrew =
310 previousStreamingMessage?.id === latestStreamingMessage.id &&
311 latestStreamingMessage.textLength > previousStreamingMessage.textLength;
312​
313 if (!isNewStream && !textGrew) {
314 return;
315 }
316​
317 const now = Date.now();
318 if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
319 return;
320 }
321​
322 lastStreamHapticAtRef.current = now;
323 void Haptics.selectionAsync();
324 }, [threadId, feed]);
326​
327const USER_INPUT_TOGGLE_TIMING = {
328 duration: USER_INPUT_TOGGLE_DURATION_MS,
329 easing: Easing.out(Easing.cubic),
330};
331​
332export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
333 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
334 const navigation = useNavigation();
335 const { session: voiceInputSession } = useGlobalVoiceInput();
336 const reportedModelSelection = useThreadReportedModelSelection({
337 environmentId: props.environmentId,
338 threadId: props.selectedThread.id,
339 });
340 const deviceState = useEnvironmentQuery(
341 deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
342 );
343 const devicePreviews = useMemo(
344 () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
345 [deviceState.data, props.selectedThread.id],
346 );
347 const openDevicePreview = useCallback(() => {
348 Keyboard.dismiss();
349 navigation.navigate("ThreadDevicePreview", {
350 environmentId: props.environmentId,
351 threadId: props.selectedThread.id,
352 });
353 }, [navigation, props.environmentId, props.selectedThread.id]);
354 const browserTabs = useThreadServerBrowserTabs({
355 environmentId: props.environmentId,
356 threadId: props.selectedThread.id,
357 enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,
358 });
359 const openBrowserPreview = useCallback(
360 (tabId?: string) => {
361 Keyboard.dismiss();
362 navigation.navigate("ThreadBrowserPreview", {
363 environmentId: props.environmentId,
364 threadId: props.selectedThread.id,
365 ...(tabId === undefined ? {} : { tabId }),
366 });
367 },
368 [navigation, props.environmentId, props.selectedThread.id],
369 );
370 const insets = useSafeAreaInsets();
371 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
372 const liveKeyboardHeight = useKeyboardState((state) => state.height);
373 // Android can swallow the IME hide callbacks when the app is backgrounded
374 // mid keyboard-hide (the reported repro: send — which blurs and starts the
375 // hide — then Home within a second). The keyboard library's height AND
376 // visibility then stay frozen open, so gating the sticky translation on
377 // visibility alone still strands the composer after resume. Quarantine the
378 // translation on every Android resume instead; any sign of a live keyboard
379 // stream — an owned input gaining focus, or any visibility/height movement —
380 // lifts it. A healthy resume sees no visual difference (the translation is
381 // already zero while the keyboard is closed).
382 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
383 useEffect(() => {
384 if (Platform.OS !== "android") {
385 return;
386 }
387 const subscription = AppState.addEventListener("change", (state) => {
388 if (state === "active") {
389 setKeyboardStateSuspect(true);
390 }
391 });
392 return () => {
393 subscription.remove();
394 };
395 }, []);
396 useEffect(() => {
397 setKeyboardStateSuspect(false);
398 }, [isKeyboardVisible, liveKeyboardHeight]);
399 const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
400 if (focused) {
401 setKeyboardStateSuspect(false);
402 }
403 }, []);
404 const windowHeight = useWindowDimensions().height;
405 const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
406 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
407 const columnMetrics = useNativeColumnLayoutMetrics();
408 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
409 const controlInsets = deriveBottomControlInsets(nativeMetrics);
410 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
411 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
412 const childThreadInputs = useChildThreadInputs({
413 environmentId: props.environmentId,
414 threadId: props.selectedThread.id,
415 });
416 const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null;
417 const queuedCount = useThreadQueuedCount({
418 environmentId: props.environmentId,
419 threadId: props.selectedThread.id,
420 });
421 const turnSubagents = useThreadTurnSubagents({
422 environmentId: props.environmentId,
423 threadId: props.selectedThread.id,
424 });
425 const agentsSegment = resolveSubagentPillSegment(turnSubagents);
426 const composerEditorRef = useRef<ComposerEditorHandle>(null);
427 // A provider-native subagent shows status instead of a composer.
428 const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);
429 // Entering edit mode from the queue sheet should land in a ready composer,
430 // not require a second tap on a composer already holding the message.
431 const editingRunId = props.queuedRunEdit?.runId ?? null;
432 useEffect(() => {
433 if (editingRunId === null) return;
434 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
435 return () => cancelAnimationFrame(frame);
436 }, [editingRunId]);
437 const draftMessageRef = useRef(props.draftMessage);
438 draftMessageRef.current = props.draftMessage;
439 const composerOverlayRef = useRef<ViewInstance>(null);
440 const listRef = useRef<LegendListRef>(null);
441 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
442 const selectedThreadKeyRef = useRef(selectedThreadKey);
443 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
444 const [composerExpanded, setComposerExpanded] = useState(false);
445 const [composerFocused, setComposerFocused] = useState(false);
446 const handleComposerFocusChange = useCallback(
447 (focused: boolean) => {
448 setComposerFocused(focused);
449 handleOwnedInputFocusChange(focused);
450 },
451 [handleOwnedInputFocusChange],
452 );
453 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
454 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
455 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
456 // Android keys the safe-area padding on keyboard visibility (#5988): the
457 // back gesture closes the keyboard while the editor stays focused, and a
458 // focus-keyed inset would leave the toolbar under the gesture bar. iOS must
459 // NOT use visibility — it only flips on keyboardDidHide, after the hide
460 // animation, so the composer would ride down flush to the screen edge and
461 // then snap up into the inset. On iOS blur precedes the hide, so the
462 // focus-keyed inset is already in place while the composer rides down.
463 // Dictation keeps that focus while the composer switches to its compact pill.
464 const composerBottomInset = (
465 Platform.OS === "android" ? isKeyboardVisible : composerExpanded || composerFocused
466 )
467 ? 0
468 : Math.max(insets.bottom, 12);
469 const contentPresentationKind = props.contentPresentation.kind;
470 // The raw sync status enters "synchronizing" on every full fetch, cached or
471 // not. Whether messages are already on screen decides the pill label: no
472 // data yet → "Loading messages", cached data reconciling → "Syncing".
473 const realThreadSyncLabel = (() => {
474 switch (props.threadSyncStatus) {
475 case "empty":
476 case "cached":
477 case "synchronizing":
478 if (contentPresentationKind === "ready") {
479 return "Syncing messages...";
480 }
481 return contentPresentationKind === "loading" ? "Loading messages..." : null;
482 default:
483 return null;
484 }
485 })();
486 // Opening a running thread resyncs for a few frames. The pill shows the
487 // sync label only when the sync lasts, so it does not flash before the timer.
488 const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);
489 // One floating pill above the composer: it reads the connection phase while
490 // disconnected, the sync state while messages load, then the working timer
491 // once the feed is settled.
492 // The shell's roster is the server's post-settlement view of what still runs.
493 const pendingBackgroundWork = presentPendingBackgroundWork(
494 props.selectedThread.pendingBackgroundTasks,
495 );
496 const floatingStatus = ((): FloatingWorkingStatus | null => {
497 const connectionStatus = connectionFloatingStatus({
498 connectionError: props.connectionError,
499 connectionState: props.connectionStateLabel,
500 environmentLabel: props.environmentLabel,
501 onReconnect: props.onReconnectEnvironment,
502 });
503 if (connectionStatus !== null) {
504 return connectionStatus;
505 }
506 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
507 return null;
508 }
509 if (props.creationState?.kind === "preparing") {
510 // The setup header already reports progress in the feed.
511 if (props.worktreeSetup) return null;
512 return {
513 kind: "preparing",
514 label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…",
515 };
516 }
517 if (props.creationState?.kind === "failed") {
518 return null;
519 }
520 if (threadSyncLabel !== null) {
521 return { kind: "syncing", label: threadSyncLabel };
522 }
523 const childInput = childThreadInputs[0];
524 if (childInput && contentPresentationKind === "ready") {
525 return {
526 kind: "child-input",
527 label: childThreadInputsTitle(childThreadInputs),
528 accessibilityLabel: `Open ${childInput.hasPendingApprovals ? "approval" : "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;
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 },
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();
1058 } catch (error) {
1059 Alert.alert(
1060 "Could not edit message",
1061 error instanceof Error ? error.message : "Please try again.",
1062 );
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);
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;
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;
1114 }, []);
1115​
1116 const handleFeedTouchEnd = useCallback(() => {
1117 if (feedTouchStartRef.current) {
1118 collapseComposer();
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}
1138 <View
1139 pointerEvents="none"
1140 className={
1141 Platform.OS === "android"
1142 ? "absolute inset-0 bg-thread-canvas"
1143 : "absolute inset-0 bg-screen"
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 )}
1157 <ThreadFeed
1158 environmentId={props.environmentId}
1159 threadId={props.selectedThread.id}
1160 workspaceRoot={props.threadCwd}
1161 feed={props.selectedThreadFeed}
1162 pendingHandoff={props.pendingHandoff}
1163 worktreeSetup={props.worktreeSetup}
1164 setupWorkingStartedAt={props.setupWorkingStartedAt}
1165 queuedMessages={props.queuedMessages}
1166 dispatchingMessageId={props.dispatchingMessageId}
1167 // A native subagent has no composer to edit a pending message in;
1168 // Cancel on the edit banner would discard it.
1169 onEditPendingMessage={isProviderSubagent ? null : handleEditPendingMessage}
1170 contentPresentation={props.contentPresentation}
1171 agentLabel={agentLabel}
1172 threadTitle={props.selectedThread.title}
1173 latestRun={props.activityRun}
1174 activeWorkStartedAt={props.activeWorkStartedAt}
1175 runlessWorkActive={props.runlessWorkActive ?? false}
1176 listRef={listRef}
1177 freeze={freeze}
1178 anchorMessageId={anchorMessageId}
1179 submittedMessageId={submittedMessageId}
1180 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1181 contentTopInset={0}
1182 contentBottomInset={
1183 estimatedOverlayHeight +
1184 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1186 contentMaxWidth={contentMaxWidth}
1187 historyControls={props.historyControls}
1188 contentSideInsets={nativeMetrics?.safeArea}
1189 layoutVariant={layoutVariant}
1190 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1191 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1192 onEndFollowEnabledChange={setEndFollowEnabled}
1193 skills={selectedProviderSkills}
1194 onUseArtifactTemplate={handleUseArtifactTemplate}
1195 />
1196 </RenderErrorBoundary>
1197 </View>
1198 ) : (
1199 <View className="flex-1" />
1200 )}
1201​
1202 {showContent ? (
1203 <ThreadBrowserFloat
1204 key={selectedThreadKey}
1205 environmentId={props.environmentId}
1206 threadId={props.selectedThread.id}
1207 tabs={browserTabs.tabs}
1208 loaded={browserTabs.loaded}
1209 top={navigationHeaderHeight + 8}
1210 onOpen={openBrowserPreview}
1211 />
1212 ) : null}
1213​
1214 {/* Floating composer — sticks to keyboard via KeyboardStickyView */}
1215 {showContent ? (
1216 <KeyboardStickyView
1217 // iOS emits a native animated height target on both will-show and
1218 // will-hide, so stay subscribed for the full transition. Android
1219 // retains its background/resume stale-state quarantine.
1220 enabled={Platform.OS === "ios" || (isKeyboardVisible && !keyboardStateSuspect)}
1221 pointerEvents="box-none"
1222 style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
1223 offset={{ closed: 0, opened: 0 }}
1225 <ComposerPopoverHost hidden={composerSlotHidden}>
1226 {/* The fixed sticky host gives this bottom-anchored child a stable
1227 coordinate space. Its top and height can then animate together
1228 instead of the auto-sized host jumping to Yoga's destination. */}
1229 <Animated.View
1230 layout={COMPOSER_LAYOUT_TRANSITION}
1231 pointerEvents="box-none"
1232 style={[
1234 position: "absolute",
1235 bottom: controlInsets.bottom,
1236 left: controlInsets.left,
1237 right: controlInsets.right,
1238 },
1239 composerWidthStyle,
1240 ]}
1242 {/* No paddingTop here: the overlay's measured height becomes the
1243 list's bottom inset, so any padding above the pill/composer
1244 pushes the resting content floor up by the same amount. */}
1245 <View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
1246 <FloatingWorkingControl
1247 colorScheme={isDarkMode ? "dark" : "light"}
1248 status={floatingStatus}
1249 lift={floatingControlLift}
1250 devicePreview={
1251 devicePreviews.length > 0
1252 ? { count: devicePreviews.length, onPress: openDevicePreview }
1253 : null
1255 browserPreview={
1256 browserTabs.tabs.length > 0
1257 ? { count: browserTabs.tabs.length, onPress: () => openBrowserPreview() }
1258 : null
1260 showScrollToEnd={showScrollToEndButton}
1261 onScrollToEnd={handleScrollToEnd}
1262 agents={agentsSegment}
1263 onOpenAgents={() => {
1264 Keyboard.dismiss();
1265 navigation.navigate("ThreadAgents", {
1266 environmentId: props.environmentId,
1267 threadId: props.selectedThread.id,
1268 });
1269 }}
1270 queuedCount={queuedCount}
1271 onOpenQueue={() => {
1272 Keyboard.dismiss();
1273 navigation.navigate("ThreadQueue", {
1274 environmentId: props.environmentId,
1275 threadId: props.selectedThread.id,
1276 });
1277 }}
1278 />
1279 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1280 {props.queuedRunEdit !== null ? (
1281 <Animated.View
1282 className="shrink-0"
1283 entering={FadeInDown.duration(180)}
1284 exiting={FadeOut.duration(120)}
1286 <ComposerQueuedEditBanner
1287 saving={props.isSavingQueuedEdit}
1288 onCancel={() => {
1289 voiceInputSession.cancel(props.composerDraftKey);
1290 props.onCancelQueuedRunEdit();
1291 }}
1292 />
1293 </Animated.View>
1294 ) : null}
1295 <UsageLimitRecoveryCard
1296 key={props.selectedThread.latestRun?.runId}
1297 thread={props.selectedThread}
1298 environmentId={props.environmentId}
1299 />
1300 {props.feedbackSubmissions.map((submission) => (
1301 <ComposerFeedback
1302 key={submission.id}
1303 submission={submission}
1304 onDismiss={() => props.onDismissFeedback(submission.id)}
1305 />
1306 ))}
1307 {composerError !== null ? (
1308 <Animated.View
1309 className="shrink-0"
1310 entering={FadeInDown.duration(180)}
1311 exiting={FadeOut.duration(120)}
1313 <ComposerErrorNotice
1314 message={composerError}
1315 onDismiss={() => clearThreadComposerError(selectedThreadKey)}
1316 />
1317 </Animated.View>
1318 ) : null}
1319 {usageLimitsReport && activeUserInputRequestId === null ? (
1320 <Animated.View
1321 className="shrink-0 px-4 pb-3"
1322 entering={FadeInDown.duration(220)}
1323 exiting={FadeOut.duration(140)}
1325 <ComposerUsageLimits
1326 report={usageLimitsReport}
1327 environmentId={props.environmentId}
1328 onClose={dismissUsageLimits}
1329 />
1330 </Animated.View>
1331 ) : null}
1332 {props.creationState?.kind === "failed" ? (
1333 <Animated.View
1334 className="shrink-0 px-4"
1335 style={{ paddingBottom: composerBottomInset }}
1336 entering={FadeInDown.duration(220)}
1337 exiting={FadeOut.duration(140)}
1339 <ThreadCreationFailedCard
1340 reason={props.creationState.reason}
1341 onEditTask={props.creationState.onEditTask}
1342 />
1343 </Animated.View>
1344 ) : null}
1345 {props.activePendingApproval || props.activePendingUserInput ? (
1346 <Animated.View
1347 className="shrink-0 gap-3 px-4 pb-3"
1348 // The questionnaire replaces the composer, so it must pad
1349 // the home indicator the composer normally covers.
1350 style={
1351 activeUserInputRequestId !== null
1352 ? { paddingBottom: composerBottomInset }
1353 : undefined
1355 entering={FadeInDown.duration(220)}
1356 exiting={FadeOut.duration(140)}
1358 {props.activePendingApproval ? (
1359 <PendingApprovalCard
1360 canOperateThread={props.canOperateThread}
1361 approval={props.activePendingApproval}
1362 respondingApprovalId={props.respondingApprovalId}
1363 onRespond={props.onRespondToApproval}
1364 />
1365 ) : null}
1366 {props.activePendingUserInput ? (
1367 <PendingUserInputCard
1368 canOperateThread={props.canOperateThread}
1369 pendingUserInput={props.activePendingUserInput}
1370 maxHeight={pendingUserInputMaxHeight}
1371 collapsed={userInputCollapsed}
1372 onToggleCollapsed={handleToggleUserInputCollapsed}
1373 onStopThread={props.onStopThread}
1374 cardProgress={userInputCardProgress}
1375 cardCoverage={userInputCardCoverage}
1376 onInputFocusChange={handleOwnedInputFocusChange}
1377 drafts={props.activePendingUserInputDrafts}
1378 answers={props.activePendingUserInputAnswers}
1379 respondingUserInputId={props.respondingUserInputId}
1380 onSelectOption={props.onSelectUserInputOption}
1381 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1382 onSubmit={props.onSubmitUserInput}
1383 onDismiss={props.onDismissUserInput}
1384 />
1385 ) : null}
1386 </Animated.View>
1387 ) : null}
1388 </View>
1389​
1390 {/* Hidden (not unmounted) while a user-input request owns the
1391 composer slot, so composer drafts and editor state survive.
1392 A rejected creation has no thread to send to; the failure card
1393 owns the slot instead. */}
1394 <View style={composerSlotHidden ? { display: "none" } : undefined}>
1395 {isProviderSubagent ? (
1396 <View
1397 className="self-center px-3 pt-1.5"
1398 style={{
1399 width: "100%",
1400 maxWidth: contentMaxWidth,
1401 paddingBottom: composerBottomInset + 6,
1402 }}
1404 <ProviderSubagentBar
1405 provider={providerSubagentProvider ?? null}
1406 modelLabel={
1407 providerSubagentCatalogModel?.name ??
1408 formatModelSlugName(props.selectedThread.modelSelection.model)
1410 effortLabel={formatModelSelectionEffort(
1411 props.selectedThread.modelSelection,
1412 providerSubagentProvider?.models,
1413 reportedModelSelection,
1414 )}
1415 status={props.providerSubagentStatus ?? null}
1416 onOpenParent={
1417 props.selectedThread.lineage.parentThreadId === null
1418 ? null
1419 : () =>
1420 navigation.navigate("Thread", {
1421 environmentId: String(props.environmentId),
1422 threadId: String(props.selectedThread.lineage.parentThreadId),
1423 })
1425 />
1426 </View>
1427 ) : (
1428 <>
1429 <ThreadComposer
1430 canOperateThread={props.canOperateThread}
1431 reportedModelSelection={reportedModelSelection}
1432 editorRef={composerEditorRef}
1433 draftMessage={props.draftMessage}
1434 draftAttachments={props.draftAttachments}
1435 placeholder="Ask the repo agent, or run a command…"
1436 contentMaxWidth={contentMaxWidth}
1437 connectionState={props.connectionStateLabel}
1438 environmentLabel={props.environmentLabel}
1439 selectedThread={props.selectedThread}
1440 hasCompactableConversation={
1441 hasCompactableConversation && !props.isCompacting
1443 serverConfig={props.serverConfig}
1444 queueCount={props.selectedThreadQueueCount}
1445 activeThreadBusy={props.activeThreadBusy}
1446 canStopThread={props.canStopThread}
1447 environmentId={props.environmentId}
1448 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1449 // Follow-ups typed before the server creates the thread wait in
1450 // the draft: queueing them against a thread id the server may
1451 // still reject would strand them in the outbox.
1452 sendBlockedReason={
1453 props.creationState?.kind === "preparing" &&
1454 !props.creationState.serverOwned
1455 ? "Starting the task…"
1456 : null
1458 draftKey={props.composerDraftKey ?? undefined}
1459 followUpBehavior={props.followUpBehavior}
1460 canSteerActiveTurn={props.canSteerActiveTurn}
1461 queuedEdit={
1462 props.queuedRunEdit === null
1463 ? null
1464 : {
1465 existingAttachments: props.queuedRunEdit.existingAttachments,
1466 saving: props.isSavingQueuedEdit,
1467 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1470 bottomInset={composerBottomInset}
1471 onChangeDraftMessage={props.onChangeDraftMessage}
1472 onPickDraftMedia={props.onPickDraftMedia}
1473 onPickDraftFiles={props.onPickDraftFiles}
1474 onNativePasteImages={props.onNativePasteImages}
1475 onNativePasteText={props.onNativePasteText}
1476 onRemoveDraftImage={props.onRemoveDraftImage}
1477 onStopThread={props.onStopThread}
1478 onSendMessage={handleSendMessage}
1479 onShowUsageLimits={showUsageLimits}
1480 canSwitchProvider={props.canSwitchThreadProvider}
1481 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1482 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1483 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1484 onExpandedChange={setComposerExpanded}
1485 onEditorFocusChange={handleComposerFocusChange}
1486 />
1487 </>
1488 )}
1489 </View>
1490 </View>
1491 </Animated.View>
1492 </ComposerPopoverHost>
1493 </KeyboardStickyView>
1494 ) : null}
1495 </View>
1496 );
1497});