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

ThreadDetailScreen.tsx

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