The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 1,997 lines 87 KB
Raw
1 import { ChildThreadApprovals } from "./ChildThreadApprovals";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { useOpenThreadInspector } from "./thread-inspector-navigation";
4 import { useSidebarWorkspaceTabs } from "../layout/workspace/useSystemWorkspaceTabBar";
5 import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
6 import {
7 isAtomCommandInterrupted,
8 settlePromise,
9 squashAtomCommandFailure,
10 } from "@t3tools/client-runtime/state/runtime";
11 import { AsyncResult, Atom } from "effect/reactivity";
12 import * as Dialog from "../../components/ui/Dialog";
13 import { useAtomMount, useAtomValue } from "@effect/atom-react";
14 import { mobilePreferencesAtom } from "../../state/preferences";
15 import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
16 import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
17 import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
18 import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
19 import { useFocusEffect, useNavigation } from "@react-navigation/native";
20 import {
21 effectiveSnoozed,
22 threadWokeAt,
23 isThreadWokeUnseen,
24 snoozeWakeLabel,
25 } from "@t3tools/client-runtime/state/thread-settled";
26 import type { WorktreeSetupCardProps } from "./worktree-setup-card";
27 import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
28 import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
29 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
30 import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
31 import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";
32 import {
33 childThreadInputsTitle,
34 type CodexFeedbackSubmission,
35 } from "@t3tools/client-runtime/state/threads";
36 import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
37 import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
38 import type { LegendListRef } from "@legendapp/list/react-native";
39 import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
40 import {
41 deriveBottomControlInsets,
42 deriveContentSideInsets,
43 type NativeLayoutMetrics,
44 } from "../../lib/reserved-regions";
45 import type {
46 EnvironmentId,
47 MessageId,
48 RuntimeRequestId,
49 ScopedThreadRef,
50 ServerConfig as T3ServerConfig,
51 UsageLimitsReport,
52 RunId,
53 } from "@t3tools/contracts";
54 import {
55 appendCodexArtifactTemplateUsePrompt,
56 type CodexArtifactTemplate,
57 } from "@t3tools/shared/codexArtifactTemplates";
58 import {
59 declinePendingApprovals,
60 sendApprovalFeedback,
61 type ApprovalResponder,
62 type ThreadUserInputQuestion,
63 } from "@t3tools/client-runtime/state/thread-requests";
64 import { useDeadlinePassed } from "../../lib/clock";
65 import {
66 BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
67 type BackgroundWorkStopRequest,
68 isBackgroundWorkStopPending,
69 limitRecoveryOwnsSnooze,
70 presentPendingBackgroundWork,
71 presentProviderGoal,
72 } from "@t3tools/client-runtime/state/thread-execution";
73 import { resolveSubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
74 import {
75 formatModelSelectionEffort,
76 type ProviderSubagentStatus,
77 } from "@t3tools/client-runtime/state/thread-execution";
78 import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
79 import { isProviderNativeSubagentThread } from "@t3tools/contracts";
80 import type { QueuedRunEdit } from "../../state/queued-run-edit";
81 import type { FollowUpBehavior } from "../../lib/followUpBehavior";
82 import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
83 import * as Haptics from "expo-haptics";
84 import {
85 useCallback,
86 useEffect,
87 useEffectEvent,
88 useRef,
89 useState,
90 useSyncExternalStore,
91 } from "react";
92 import { useGT, useMessages } from "gt-react-native";
93 import { m } from "../../i18n/messages";
94 import {
95 AppState,
96 Keyboard,
97 Platform,
98 useWindowDimensions,
99 View,
100 type GestureResponderEvent,
101 type LayoutChangeEvent,
102 } from "react-native";
103 import {
104 KeyboardController,
105 KeyboardStickyView,
106 useKeyboardState,
107 useReanimatedKeyboardAnimation,
108 } from "react-native-keyboard-controller";
109 import Animated, {
110 Easing,
111 FadeInDown,
112 FadeOut,
113 ReduceMotion,
114 useAnimatedReaction,
115 useAnimatedStyle,
116 useDerivedValue,
117 useReducedMotion,
118 useSharedValue,
119 withTiming,
120 } from "react-native-reanimated";
121 import { useBarOverlap } from "../../components/ui/useBarInset";
122 import {
123 useWorkspaceContentWidth,
124 WorkspaceSettledContentWidthContext,
125 useWorkspaceSettledContentWidth,
126 } from "../layout/workspace-content-width";
127 import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
128 import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
129 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
130 import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
131 import type { ComposerEditorHandle } from "../../components/ComposerEditor";
132 import type { StatusTone } from "../../components/StatusPill";
133 import {
134 captureComposerDraftInsertion,
135 getComposerDraftSnapshot,
136 setFreshSessionPending,
137 insertComposerDraftText,
138 } from "../../state/use-composer-drafts";
139 import { assistantCitationDraftWithinLimit } from "../../lib/composerContext";
140 import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
141 import type { AssistantCitation } from "@t3tools/contracts";
142 import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
143 import {
144 ANDROID_READING_MAX_WIDTH,
145 CHAT_CONTENT_MAX_WIDTH,
146 type LayoutVariant,
147 } from "../../lib/layout";
148 import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
149 import { environmentCatalog } from "../../connection/catalog";
150 import { deviceEnvironment } from "../../state/device";
151 import { useEnvironmentQuery } from "../../state/query";
152 import { threadDevicePreviews } from "../devices/threadDevicePreviews";
153 import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
154 import { useThreadServerBrowserTabs } from "../../state/preview";
155 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
156 import { scopedThreadKey } from "../../lib/scopedEntities";
157 import {
158 finishThreadMessageJump,
159 pendingThreadMessageJump,
160 subscribeThreadMessageJump,
161 } from "./threadMessageJump";
162 import {
163 clearThreadComposerError,
164 threadComposerErrorsAtom,
165 } from "../../state/thread-composer-error";
166 import {
167 environmentThreadDetails,
168 environmentThreadShells,
169 threadEnvironment,
170 } from "../../state/threads";
171 import { appAtomRegistry } from "../../state/atom-registry";
172 import { threadStreamHaptics } from "./threadStreamHaptics";
173 import { useAtomCommand } from "../../state/use-atom-command";
174 import { orchestrationEnvironment } from "../../state/orchestration";
175 import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
176 import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";
177 import type {
178 PendingApproval,
179 PendingUserInput,
180 ThreadFeedEntry,
181 ThreadFeedLatestRun,
182 } from "../../lib/threadActivity";
183 import { PendingApprovalCard } from "./PendingApprovalCard";
184 import { ComposerErrorNotice } from "./ComposerErrorNotice";
185 import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
186 import { FreshSessionNotice } from "./FreshSessionNotice";
187 import { ComposerFeedback } from "./ComposerFeedback";
188 import { ComposerUsageLimits } from "./ComposerUsageLimits";
189 import { PendingUserInputCard } from "./PendingUserInputCard";
190 import { ProviderSubagentBar } from "./ProviderSubagentBar";
191 import { ThreadCreationFailedCard } from "./ThreadCreationFailedCard";
192 import {
193 FLOATING_WORKING_CONTROL_COVERAGE,
194 FloatingWorkingControl,
195 } from "./floating-working-control";
196 import {
197 connectionFloatingStatus,
198 type FloatingStatusAction,
199 type FloatingWorkingStatus,
200 } from "./floating-working-status";
201 import type { ThreadStatusLineModel } from "./thread-context-divider";
202 import {
203 derivePendingUserInputMaxHeight,
204 ESTIMATED_KEYBOARD_HEIGHT,
205 USER_INPUT_TOGGLE_DURATION_MS,
206 } from "./pendingUserInputLayout";
207 import { useComposerBottomInset } from "../../components/ComposerSurface";
208 import {
209 COMPOSER_COLLAPSED_CHROME,
210 ThreadComposer,
211 type ThreadComposerProps,
212 } from "./ThreadComposer";
213 import { ComposerPopoverHost } from "./ComposerPopoverHost";
214 import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
215 import { WorkspaceMutationIdProvider } from "./WorkspaceMutationIdProvider";
216 import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
217 import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
218 import { useThreadQueuedCount } from "./ThreadQueueControl";
219 import { ThreadGuestShareBar } from "./ThreadGuestShareBar";
220 import { ThreadSideChatsRow } from "./ThreadSideChatsRow";
221 import type { ThreadContentPresentation } from "./threadContentPresentation";
222 import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-scroll-position";
223 import { useOpenLinkedThread } from "./useOpenLinkedThread";
224 import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
225 import type { OrchestrationV2ProviderSession } from "@t3tools/contracts";
226 import { voiceInputBlocksSubmission } from "@t3tools/client-runtime/voice-input";
227
228 export interface ThreadDetailScreenProps {
229 readonly header?: React.ReactNode;
230 readonly draftMode?: {
231 /** viewportHeight excludes the composer so draft chrome can resize it without feedback. */
232 readonly content: (
233 headerInset: number,
234 bottomInset: number,
235 viewportHeight: number,
236 ) => React.ReactNode;
237 readonly controls: (viewportHeight: number) => React.ReactNode;
238 readonly editorRef: React.RefObject<ComposerEditorHandle | null>;
239 readonly sendBlockedReason: string | null;
240 readonly interactionLocked: boolean;
241 };
242 readonly worktreeSetup?: WorktreeSetupCardProps | null;
243 readonly canOperateThread: boolean;
244 readonly selectedThread: EnvironmentThreadShell;
245 /** Use this for detail reads; it stays null until queued creation reaches the server. */
246 readonly selectedThreadDetailRef: ScopedThreadRef | null;
247 readonly contentPresentation: ThreadContentPresentation;
248 readonly screenTone: StatusTone;
249 readonly connectionError: string | null;
250 readonly environmentLabel: string | null;
251 readonly feedbackSubmissions: ReadonlyArray<CodexFeedbackSubmission>;
252 readonly onDismissFeedback: (id: MessageId) => void;
253 readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
254 readonly pendingHandoff?: HandoffEndpoints | null;
255 readonly activityRun: ThreadFeedLatestRun | null;
256 readonly activeWorkStartedAt: string | null;
257 readonly runlessWorkActive?: boolean;
258 readonly providerSubagentStatus?: ProviderSubagentStatus | null;
259 readonly extensionStatuses?: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
260 readonly isCompacting: boolean;
261 /** Set while the next send compacts the thread first. */
262 readonly compactBeforeSend?: ThreadComposerProps["compactBeforeSend"];
263 readonly creationState:
264 | {
265 readonly kind: "preparing";
266 readonly preparingWorktree: boolean;
267 readonly serverOwned: boolean;
268 }
269 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
270 | null;
271 readonly activePendingApproval: PendingApproval | null;
272 readonly activePendingApprovals: ReadonlyArray<PendingApproval>;
273 readonly respondingApprovalId: RuntimeRequestId | null;
274 readonly activePendingUserInput: PendingUserInput | null;
275 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
276 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
277 readonly respondingUserInputId: RuntimeRequestId | null;
278 readonly connectionStateLabel: EnvironmentConnectionPhase;
279 readonly historyControls?: ThreadFeedHistoryControls;
280 readonly activeThreadBusy: boolean;
281 readonly canStopThread: boolean;
282 readonly queuedRunEdit: QueuedRunEdit | null;
283 readonly composerDraftKey: string | null;
284 readonly followUpBehavior: FollowUpBehavior;
285 readonly canSteerActiveTurn: boolean;
286 readonly isSavingQueuedEdit: boolean;
287 readonly onCancelQueuedRunEdit: () => void;
288 readonly onRemoveQueuedEditAttachment: (attachmentId: string) => void;
289 readonly environmentId: EnvironmentId;
290 readonly projectWorkspaceRoot: string | null;
291 readonly threadCwd: string | null;
292 readonly selectedThreadQueueCount: number;
293 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
294 readonly dispatchingMessageId: MessageId | null;
295 readonly serverConfig: T3ServerConfig | null;
296 readonly layoutVariant?: LayoutVariant;
297 readonly usesAutomaticContentInsets?: boolean;
298 readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
299 readonly onOpenConnectionEditor: () => void;
300 readonly onChangeDraftMessage: (value: string) => void;
301 readonly onPickDraftMedia: () => Promise<void>;
302 readonly onPickDraftFiles: () => Promise<void>;
303 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
304 readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
305 readonly onRemoveDraftImage: (imageId: string) => void;
306 readonly onStopThread: () => void;
307 /** Present while the thread's queue is held. */
308 readonly onResumeQueue: (() => Promise<void>) | null;
309 readonly offersSideChat: boolean;
310 readonly onSendMessage: (
311 followUp?: ActiveTurnComposerAction,
312 beforeDispatch?: (
313 text: string,
314 hasAttachmentsOrContext: boolean,
315 ) => Promise<boolean | "responded">,
316 onWillEnqueue?: () => void,
317 ) => Promise<MessageId | null>;
318 /** Queues a standalone text command, such as `/goal clear`, without touching the draft. */
319 readonly onSendCommand: (text: string) => Promise<MessageId | null>;
320 readonly onReconnectEnvironment: () => void;
321 readonly canSwitchThreadProvider: boolean;
322 readonly onRespondToApproval: ApprovalResponder;
323 readonly onSelectUserInputOption: (
324 requestId: RuntimeRequestId,
325 question: ThreadUserInputQuestion,
326 value: string,
327 ) => void;
328 readonly onChangeUserInputCustomAnswer: (
329 requestId: RuntimeRequestId,
330 questionId: string,
331 customAnswer: string,
332 ) => void;
333 readonly onSubmitUserInput: () => Promise<unknown>;
334 readonly onDismissUserInput: () => Promise<unknown>;
335 readonly showContent?: boolean;
336 }
337
338 // iOS questions overlay the controls; Android questions stack with child approvals.
339 const ComposerPanels = Platform.OS === "android" ? Animated.ScrollView : Animated.View;
340
341 /**
342 * Hands the feed the screen width measured for a native column; elsewhere keeps the inherited one.
343 * Always the same element, so the feed below is not remounted when the width arrives.
344 */
345 function ColumnWidth(props: { readonly width: number | null; readonly children: React.ReactNode }) {
346 const inherited = useWorkspaceSettledContentWidth();
347 return (
348 <WorkspaceSettledContentWidthContext value={props.width ?? inherited}>
349 {props.children}
350 </WorkspaceSettledContentWidthContext>
351 );
352 }
353 const USAGE_LIMITS_PANEL_GAP = 12;
354 const FEED_END_GAP = 12;
355 const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44;
356
357 const USER_INPUT_TOGGLE_TIMING = {
358 duration: USER_INPUT_TOGGLE_DURATION_MS,
359 easing: Easing.out(Easing.cubic),
360 };
361
362 // A scheduled wake can happen without a newer server update, so the tracker
363 // is told when one takes effect. The shell's updatedAt ticks while a run
364 // streams; the tracker follows it outside React.
365 const wakeAwareVisitShell = Atom.family((key: string) => {
366 const ref = parseThreadKey(key);
367 return Atom.make((get) => {
368 const shell = get(environmentThreadShells.threadShellAtom(ref));
369 if (shell === null) return null;
370 const nowMs = Date.now();
371 const wokeAt = threadWokeAt(shell, { now: new Date(nowMs).toISOString() });
372 const wakeAtMs = shell.snoozedUntil == null ? NaN : Date.parse(shell.snoozedUntil);
373 if (wokeAt === null && wakeAtMs > nowMs) {
374 const timer = setTimeout(
375 () => get.refreshSelf(),
376 Math.min(wakeAtMs - nowMs + 50, 2_147_483_647),
377 );
378 get.addFinalizer(() => clearTimeout(timer));
379 }
380 return { ...shell, wokeAt };
381 }).pipe(Atom.withLabel(`mobile-thread-visit-shell:${key}`));
382 });
383
384 const threadVisitTracker = createThreadVisitTracker({
385 threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)),
386 sessionGenerationAtom: environmentCatalog.sessionGenerationAtom,
387 visit: threadEnvironment.visit,
388 });
389
390 // Past the composer's 180 ms height animation.
391 const COMPOSER_HEIGHT_SETTLE_MS = 220;
392 const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(
393 Atom.withLabel("mobile-thread-run-stop:empty"),
394 );
395
396 // Anchors, the submitted message, follow state and pending scrolls belong to
397 // one thread, so the body remounts when the thread changes.
398 export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
399 const [statusRequests, setStatusRequests] = useState<
400 Record<string, BackgroundWorkStopRequest | undefined>
401 >({});
402 return (
403 <ThreadDetailBody
404 key={scopedThreadKey(props.environmentId, props.selectedThread.id)}
405 {...props}
406 statusRequests={statusRequests}
407 setStatusRequests={setStatusRequests}
408 />
409 );
410 }
411
412 function ThreadDetailBody(
413 props: ThreadDetailScreenProps & {
414 statusRequests: Record<string, BackgroundWorkStopRequest | undefined>;
415 setStatusRequests: React.Dispatch<
416 React.SetStateAction<Record<string, BackgroundWorkStopRequest | undefined>>
417 >;
418 },
419 ) {
420 const gt = useGT();
421 const messages = useMessages();
422 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
423 const deviceType = useDeviceType();
424 const workspace = useWorkspaceTabs();
425 const sidebarSearchActive =
426 deviceType === "duo-unfolded" &&
427 workspace?.state.tabs[workspace.state.selectedTab].searchMode === "active";
428 // Keep the last input owner through keyboard dismissal, so closing sidebar
429 // search cannot briefly lift the composer into the keyboard's closing frame.
430 const [composerOwnsKeyboard, setComposerOwnsKeyboard] = useState(false);
431 if (sidebarSearchActive && composerOwnsKeyboard) setComposerOwnsKeyboard(false);
432 const navigation = useNavigation();
433 const openLinkedThread = useOpenLinkedThread();
434 const openInspector = useOpenThreadInspector();
435 const { session: voiceInputSession } = useGlobalVoiceInput();
436 const reportedModelSelection = useThreadReportedModelSelection(props.selectedThreadDetailRef);
437 const deviceState = useEnvironmentQuery(
438 deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
439 );
440 const devicePreviews = threadDevicePreviews(deviceState.data, props.selectedThread.id);
441 const openDevicePreview = () => {
442 Keyboard.dismiss();
443 if (
444 openInspector(
445 { environmentId: props.environmentId, threadId: props.selectedThread.id },
446 { type: "device", environmentId: props.environmentId, threadId: props.selectedThread.id },
447 )
448 )
449 return;
450 navigation.navigate("ThreadDevicePreview", {
451 environmentId: props.environmentId,
452 threadId: props.selectedThread.id,
453 });
454 };
455 const browserTabs = useThreadServerBrowserTabs({
456 environmentId: props.environmentId,
457 threadId: props.selectedThread.id,
458 enabled:
459 !props.draftMode && props.serverConfig?.environment.capabilities.serverBrowser === true,
460 });
461 const openBrowserPreview = (tabId?: string) => {
462 Keyboard.dismiss();
463 navigation.navigate("ThreadBrowserPreview", {
464 environmentId: props.environmentId,
465 threadId: props.selectedThread.id,
466 ...(tabId === undefined ? {} : { tabId }),
467 });
468 };
469 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
470 const liveKeyboardHeight = useKeyboardState((state) => state.height);
471 // Android can lose IME hide callbacks on backgrounding. Quarantine translation on resume unless focused input retained its keyboard.
472 const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
473 const ownedInputFocusedRef = useRef(false);
474 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to AppState on Android to mark keyboard state suspect when the app resumes
475 useEffect(() => {
476 if (Platform.OS !== "android") {
477 return;
478 }
479 const subscription = AppState.addEventListener("change", (state) => {
480 if (state === "active") {
481 setKeyboardStateSuspect(!ownedInputFocusedRef.current);
482 }
483 });
484 return () => {
485 subscription.remove();
486 };
487 }, []);
488 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the suspect flag whenever the native keyboard reports a visibility or height change
489 useEffect(() => {
490 // oxlint-disable-next-line react/set-state-in-effect -- Any native keyboard report clears the suspect flag set when the app resumed.
491 setKeyboardStateSuspect(false);
492 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Any keyboard visibility or height report clears the suspect flag set when the app resumed.
493 }, [isKeyboardVisible, liveKeyboardHeight]);
494 const handleOwnedInputFocusChange = (focused: boolean) => {
495 ownedInputFocusedRef.current = focused;
496 if (focused) {
497 if (deviceType === "duo-folded" || deviceType === "duo-unfolded")
498 setComposerOwnsKeyboard(true);
499 setKeyboardStateSuspect(false);
500 }
501 };
502 const windowHeight = useWindowDimensions().height;
503 const navigationHeaderHeight = useBarOverlap();
504 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
505 const columnMetrics = useNativeColumnLayoutMetrics();
506 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
507 const controlInsets = deriveBottomControlInsets(nativeMetrics);
508 const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
509 const childThreadInputs = useChildThreadInputs({
510 environmentId: props.environmentId,
511 threadId: props.selectedThread.id,
512 });
513 const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null;
514 const preferences = useAtomValue(mobilePreferencesAtom);
515 const toolCallVisibility = AsyncResult.isSuccess(preferences)
516 ? (preferences.value.toolCallVisibility ?? "showAll")
517 : "showAll";
518 const queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef);
519 const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef);
520 const agentsSegment = resolveSubagentPillSegment(turnSubagents, messages);
521 const defaultComposerEditorRef = useRef<ComposerEditorHandle>(null);
522 const composerEditorRef = props.draftMode?.editorRef ?? defaultComposerEditorRef;
523 const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);
524 const editingRunId = props.queuedRunEdit?.runId ?? null;
525 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the composer editor on the next animation frame when a queued run edit starts
526 useEffect(() => {
527 if (editingRunId === null) return;
528 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
529 return () => cancelAnimationFrame(frame);
530 }, [editingRunId, composerEditorRef]);
531 const listRef = useRef<LegendListRef>(null);
532 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
533 // Aborted when this thread's body unmounts, so async work started for it
534 // stops touching a list or composer that now shows another thread.
535 // Aborted when the screen hides or unmounts; a hidden Activity pane keeps its state but re-runs
536 // effects when shown, so each show arms a fresh scope.
537 const threadScope = useRef(new AbortController());
538 const [composerHeight, setComposerHeight] = useState<number | null>(null);
539 // The composer animates its height and reports a layout every frame. The feed follows those
540 // frames on the UI thread through onComposerLayout; this is only an estimate, so committing
541 // each frame would re-render the whole screen for the length of the animation.
542 const composerHeightSettle = useRef<ReturnType<typeof setTimeout> | null>(null);
543 const handleComposerHeightChange = (height: number) => {
544 setComposerHeight((current) => current ?? height);
545 if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
546 composerHeightSettle.current = setTimeout(() => {
547 composerHeightSettle.current = null;
548 setComposerHeight(height);
549 }, COMPOSER_HEIGHT_SETTLE_MS);
550 };
551 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
552 const [isAtEnd, setIsAtEnd] = useState(true);
553 const [sendingWithKeyboard, setSendingWithKeyboard] = useState(false);
554 if (sendingWithKeyboard && !isKeyboardVisible) setSendingWithKeyboard(false);
555 const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
556 const composerBottomInset = useComposerBottomInset();
557 const composerKeyboardOffset = composerBottomInset;
558 const contentPresentationKind = props.contentPresentation.kind;
559 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {
560 reportFailure: false,
561 });
562 const unsnoozeThread = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
563 const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
564 const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
565 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
566 const anyRunStop = useAtomValue(
567 props.selectedThreadDetailRef === null
568 ? NO_RUN_STOP_ATOM
569 : environmentThreadDetails.runStopAtom(props.selectedThreadDetailRef),
570 );
571 // A background Stop matters only while that work is still pending.
572 const runStop =
573 anyRunStop?.background && props.selectedThread.pendingBackgroundTasks.length === 0
574 ? null
575 : anyRunStop;
576 const forceStopThread = useAtomCommand(orchestrationEnvironment.forceStopThread, {
577 reportFailure: false,
578 });
579 const canForceStop =
580 useAtomValue(orchestrationEnvironment.forceStopThread.permissionAtom(props.environmentId)) &&
581 props.serverConfig?.environment.capabilities.threadForceStop === true;
582 const [forceStoppingKey, setForceStoppingKey] = useState<string | null>(null);
583 // The run that ignored Stop, so a confirmation left open cannot hit a newer run.
584 const forceStop = async (runId: RunId | undefined) => {
585 const threadKey = selectedThreadKey;
586 setForceStoppingKey(threadKey);
587 const result = await forceStopThread({
588 environmentId: props.environmentId,
589 input:
590 runId === undefined
591 ? { threadId: props.selectedThread.id }
592 : { threadId: props.selectedThread.id, runId },
593 });
594 setForceStoppingKey((current) => (current === threadKey ? null : current));
595 if (result._tag === "Failure") {
596 if (!isAtomCommandInterrupted(result)) Dialog.alert(gt("Could not force stop the agent"));
597 return;
598 }
599 const others = result.value.sharedWithThreadIds.length;
600 if (result.value.outcome === "releasing") {
601 Dialog.alert(gt("Turn stopped; the agent is still shutting down"));
602 }
603 if (result.value.outcome === "shared") {
604 Dialog.alert(
605 gt("Turn stopped; the agent process kept running"),
606 gt(
607 "{count, plural, =0 {It is shared with other working threads. Stop those to free it.} one {It is shared with {count} working thread. Stop those to free it.} other {It is shared with {count} working threads. Stop those to free it.}}",
608 { count: others },
609 ),
610 );
611 }
612 };
613 const statusRequest = props.statusRequests[selectedThreadKey] ?? null;
614 const statusPending = isBackgroundWorkStopPending(
615 statusRequest,
616 selectedThreadKey,
617 props.selectedThread.pendingBackgroundTasks,
618 useDeadlinePassed(statusRequest?.retryAt ?? null),
619 );
620 const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());
621 useFocusEffect(
622 useCallback(() => {
623 setLifecycleNow(new Date().toISOString());
624 const timer = setInterval(() => setLifecycleNow(new Date().toISOString()), 60_000);
625 return () => clearInterval(timer);
626 }, []),
627 );
628 const configLoaded = props.serverConfig !== null;
629 const snoozed = configLoaded && effectiveSnoozed(props.selectedThread, { now: lifecycleNow });
630 const snoozedUntil = props.selectedThread.snoozedUntil;
631 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- arms a timer that refreshes the lifecycle clock when the thread's snooze expires
632 useEffect(() => {
633 if (!snoozed || snoozedUntil === null) return;
634 const timer = setTimeout(
635 () => setLifecycleNow(new Date().toISOString()),
636 Math.min(Math.max(0, Date.parse(snoozedUntil) - Date.now()) + 50, 2_147_483_647),
637 );
638 return () => clearTimeout(timer);
639 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-arm if timer clamping fires before the wake time.
640 }, [snoozed, snoozedUntil, lifecycleNow]);
641 // The usage-limit recovery card shows this snooze and its Wake now.
642 const lifecycleSnoozed =
643 snoozed &&
644 !limitRecoveryOwnsSnooze({
645 runId:
646 props.selectedThread.runtime?.status === "failed" &&
647 props.selectedThread.runtime.lastErrorClass === "usage_limit"
648 ? props.selectedThread.latestRun?.runId
649 : null,
650 resetAt: props.selectedThread.runtime?.usageLimitResetAt,
651 recovery: props.selectedThread.limitRecovery,
652 snoozedUntil,
653 });
654 const settled = configLoaded && props.selectedThread.settledOverride === "settled";
655 const wokeAt = configLoaded ? threadWokeAt(props.selectedThread, { now: lifecycleNow }) : null;
656 const woke = isThreadWokeUnseen({
657 wokeAt,
658 settled,
659 lastVisitedAt: props.selectedThread.lastVisitedAt,
660 latestRunCompletedAt: props.selectedThread.latestRun?.completedAt ?? null,
661 });
662 const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => {
663 if (statusPending || !props.canOperateThread) return;
664 const request: BackgroundWorkStopRequest = {
665 threadKey: selectedThreadKey,
666 taskIds:
667 action === "stop"
668 ? props.selectedThread.pendingBackgroundTasks.map((task) => task.taskId)
669 : [],
670 retryAt: null,
671 };
672 props.setStatusRequests((current) => ({ ...current, [request.threadKey]: request }));
673 const target = {
674 environmentId: props.environmentId,
675 input: { threadId: props.selectedThread.id },
676 };
677 const recovery = props.selectedThread.limitRecovery;
678 const recoveryOwnsSnooze =
679 recovery?.snooze === true &&
680 recovery.runId === props.selectedThread.latestRun?.runId &&
681 snoozedUntil !== null &&
682 Date.parse(snoozedUntil) === Date.parse(recovery.resetAt);
683 const result =
684 action === "stop"
685 ? await interruptThreadTurn(target)
686 : action === "wake"
687 ? recoveryOwnsSnooze
688 ? await updateMetadata({
689 ...target,
690 input: {
691 ...target.input,
692 limitRecovery: {
693 runId: recovery.runId,
694 resetAt: recovery.resetAt,
695 snooze: false,
696 },
697 },
698 })
699 : await unsnoozeThread({ ...target, input: { ...target.input, reason: "user" } })
700 : action === "unsettle"
701 ? await unsettleThread({ ...target, input: { ...target.input, reason: "user" } })
702 : await visitThread({
703 ...target,
704 input: { ...target.input, visitedAt: wokeAt ?? lifecycleNow },
705 });
706 props.setStatusRequests((current) =>
707 current[request.threadKey] !== request
708 ? current
709 : {
710 ...current,
711 [request.threadKey]:
712 action === "stop" && result._tag !== "Failure"
713 ? { ...request, retryAt: Date.now() + BACKGROUND_WORK_STOP_RETRY_AFTER_MS }
714 : undefined,
715 },
716 );
717 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
718 const error = squashAtomCommandFailure(result);
719 Dialog.alert(
720 gt("Could not update thread"),
721 errorDisplayMessage(error, m) ?? gt("Try again."),
722 );
723 }
724 };
725 const [goalCommandPending, setGoalCommandPending] = useState(false);
726 const runGoalCommand = async (command: string) => {
727 if (goalCommandPending || !props.canOperateThread) return;
728 setGoalCommandPending(true);
729 // No `finally`: React Compiler cannot lower it.
730 try {
731 await props.onSendCommand(command);
732 } catch (error) {
733 Dialog.alert(
734 gt("Could not update goal"),
735 error instanceof Error ? error.message : gt("Try again."),
736 );
737 }
738 setGoalCommandPending(false);
739 };
740 const pendingBackgroundWork = presentPendingBackgroundWork(
741 props.selectedThread.pendingBackgroundTasks,
742 messages,
743 );
744 const extensionStatus = props.extensionStatuses?.length
745 ? {
746 label: `Pi · ${props.extensionStatuses.map((status) => status.text).join(" · ")}`,
747 onPress: () =>
748 Dialog.alert("Pi", props.extensionStatuses?.map((status) => status.text).join("\n\n")),
749 }
750 : null;
751 const backgroundLine = ((): ThreadStatusLineModel | null => {
752 if (pendingBackgroundWork === null || contentPresentationKind !== "ready") return null;
753 return {
754 key: "background",
755 icon: pendingBackgroundWork.waiting ? "person.2" : "terminal",
756 label: pendingBackgroundWork.title,
757 accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items
758 .map((item) => item.label)
759 .join(", ")}`,
760 onOpen: () => {
761 Keyboard.dismiss();
762 navigation.navigate("ThreadBackgroundWork", {
763 environmentId: props.environmentId,
764 threadId: props.selectedThread.id,
765 });
766 },
767 action: {
768 label: statusPending ? gt("Stopping...") : gt("Stop", { $context: "verb, button" }),
769 accessibilityLabel: gt("Stop background work"),
770 disabled: !props.canOperateThread || statusPending,
771 onPress: () => void runStatusAction("stop"),
772 },
773 };
774 })();
775 const lifecycleLine = ((): ThreadStatusLineModel | null => {
776 if (contentPresentationKind !== "ready" || !(lifecycleSnoozed || settled || woke)) return null;
777 const actionLabel = lifecycleSnoozed
778 ? gt("Wake now")
779 : settled
780 ? gt("Un-settle", { $context: "verb, thread action" })
781 : gt("Dismiss");
782 const wake =
783 lifecycleSnoozed &&
784 snoozedUntil !== null &&
785 Date.parse(snoozedUntil) > Date.parse(lifecycleNow)
786 ? snoozeWakeLabel(snoozedUntil, { now: lifecycleNow }, messages)
787 : null;
788 return {
789 key: "lifecycle",
790 icon: settled && !lifecycleSnoozed ? "checkmark.circle" : "alarm",
791 label: lifecycleSnoozed
792 ? wake === null
793 ? gt("Snoozed", { $context: "thread state" })
794 : gt("Snoozed, {time} left", { time: wake })
795 : settled
796 ? gt("Settled", { $context: "thread state" })
797 : gt("Woke from snooze"),
798 action: {
799 label: statusPending
800 ? lifecycleSnoozed
801 ? gt("Waking...")
802 : settled
803 ? gt("Un-settling...")
804 : gt("Dismissing...")
805 : actionLabel,
806 accessibilityLabel: actionLabel,
807 disabled: !props.canOperateThread || statusPending,
808 onPress: () =>
809 void runStatusAction(lifecycleSnoozed ? "wake" : settled ? "unsettle" : "dismiss"),
810 },
811 };
812 })();
813 const statusLines = [backgroundLine, lifecycleLine].filter((line) => line !== null);
814 const floatingStatus = ((): FloatingWorkingStatus | null => {
815 const connectionStatus = connectionFloatingStatus(
816 {
817 connectionError: props.connectionError,
818 connectionState: props.connectionStateLabel,
819 environmentLabel: props.environmentLabel,
820 onReconnect: props.onReconnectEnvironment,
821 },
822 messages,
823 );
824 if (connectionStatus !== null && !props.draftMode) {
825 return connectionStatus;
826 }
827 // Before the request check: an agent stuck on an approval may also ignore Stop.
828 if (runStop !== null && contentPresentationKind === "ready") {
829 const unresponsive = runStop.state === "unresponsive";
830 return {
831 kind: "stop",
832 unresponsive,
833 label: unresponsive ? gt("Not responding to Stop") : gt("Stopping…"),
834 action:
835 unresponsive && canForceStop
836 ? {
837 label:
838 forceStoppingKey === selectedThreadKey
839 ? gt("Force stopping...")
840 : gt("Force stop"),
841 accessibilityLabel: gt("Force stop the agent"),
842 disabled: forceStoppingKey === selectedThreadKey,
843 onPress: () =>
844 Dialog.confirm({
845 title: gt("Force stop the agent?"),
846 message: gt(
847 "It has not answered Stop. Force stop ends the turn and kills the agent's processes, unless other working threads share them.",
848 ),
849 confirmText: gt("Force stop"),
850 destructive: true,
851 onConfirm: () => void forceStop(runStop.runId),
852 }),
853 }
854 : null,
855 };
856 }
857 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
858 return null;
859 }
860 if (props.creationState?.kind === "preparing") {
861 // The feed shows worktree setup in place, so only a plain start needs the pill.
862 if (props.worktreeSetup || props.creationState.preparingWorktree) return null;
863 return { kind: "preparing", label: gt("Starting…") };
864 }
865 if (props.creationState?.kind === "failed") {
866 return null;
867 }
868 const childInput = childThreadInputs[0];
869 if (childInput && contentPresentationKind === "ready") {
870 return {
871 kind: "child-input",
872 label: childThreadInputsTitle(childThreadInputs, messages),
873 accessibilityLabel: childInput.hasPendingApprovals
874 ? gt("Open approval from {title}", { title: childInput.title })
875 : gt("Open question from {title}", { title: childInput.title }),
876 onPress: () => {
877 Keyboard.dismiss();
878 openLinkedThread({ environmentId: childInput.environmentId, threadId: childInput.id });
879 },
880 };
881 }
882 if (props.selectedThread.goal !== null && contentPresentationKind === "ready") {
883 const goal = presentProviderGoal(props.selectedThread.goal, false, messages);
884 const goalDriver = props.serverConfig?.providers.find(
885 (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
886 )?.driver;
887 const goalAction = (
888 label: string,
889 accessibilityLabel: string,
890 command: string,
891 ): FloatingStatusAction => ({
892 label,
893 accessibilityLabel,
894 disabled: !props.canOperateThread || goalCommandPending,
895 onPress: () => void runGoalCommand(command),
896 });
897 // The server rejects Antigravity goal controls and Claude resume. Resume would stop
898 // unrelated work, so it waits for the thread to go idle.
899 const goalActions =
900 goalDriver === "antigravity"
901 ? []
902 : [
903 ...(goal.canResume && goalDriver !== "claudeAgent" && !props.activeThreadBusy
904 ? [goalAction(gt("Resume"), gt("Resume goal"), "/goal resume")]
905 : []),
906 goalAction(gt("Clear"), gt("Clear goal"), "/goal clear"),
907 ];
908 return {
909 kind: "goal",
910 label: goal.title,
911 accessibilityLabel: `${goal.title}: ${goal.objective}`,
912 actions: goalActions,
913 };
914 }
915 if (extensionStatus !== null && contentPresentationKind === "ready") {
916 return { kind: "extension", ...extensionStatus };
917 }
918 return null;
919 })();
920 const showWorkingControl = floatingStatus !== null;
921 const showFloatingStatus =
922 showWorkingControl ||
923 queuedCount > 0 ||
924 agentsSegment !== null ||
925 devicePreviews.length > 0 ||
926 browserTabs.tabs.length > 0;
927 const selectedThreadFeed = props.selectedThreadFeed;
928 // A palette message result opens the thread at that message: earlier
929 // history loads until the message is in the feed, which then scrolls to it.
930 const jumpMessageId = useSyncExternalStore(subscribeThreadMessageJump, () =>
931 pendingThreadMessageJump(selectedThreadKey),
932 );
933 const jumpMessageLoaded =
934 jumpMessageId !== null &&
935 selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === jumpMessageId);
936 const historyForJump = props.historyControls;
937 // History down to the message in one request; another page if it is not
938 // there yet.
939 const loadEarlierForJump = useEffectEvent(() => {
940 if (jumpMessageId !== null) historyForJump?.onLoadThrough(jumpMessageId);
941 });
942 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests earlier history from the server until the jump target message loads, or ends the jump
943 useEffect(() => {
944 if (jumpMessageId === null || jumpMessageLoaded || contentPresentationKind !== "ready") return;
945 if (historyForJump?.loading) return;
946 if (!historyForJump?.hasMoreHistory || historyForJump.error !== null) {
947 finishThreadMessageJump(selectedThreadKey);
948 return;
949 }
950 loadEarlierForJump();
951 }, [
952 contentPresentationKind,
953 historyForJump?.error,
954 historyForJump?.hasMoreHistory,
955 historyForJump?.loading,
956 jumpMessageId,
957 jumpMessageLoaded,
958 selectedThreadKey,
959 ]);
960 // A queued-run edit, question or approval owns the composer, and its send carries no fresh session.
961 const freshSessionAvailable =
962 !props.draftMode &&
963 props.canOperateThread &&
964 props.queuedRunEdit === null &&
965 props.activePendingApproval === null &&
966 props.activePendingUserInput === null &&
967 props.selectedThread.latestRun != null &&
968 props.serverConfig?.environment.capabilities.freshContext === true;
969 const hasCompactableConversation =
970 selectedThreadFeed.some(
971 (entry) =>
972 entry.type === "message" &&
973 entry.message.role === "user" &&
974 ((entry.message.attachments?.length ?? 0) > 0 ||
975 entry.message.text.trim().toLowerCase() !== "/compact"),
976 ) ||
977 (props.historyControls?.hasMoreHistory === true &&
978 props.selectedThread.latestUserMessageAt !== null);
979 const composerOverlapHeight =
980 composerHeight ??
981 COMPOSER_COLLAPSED_CHROME +
982 (!isProviderSubagent && (deviceType === "pad" || hasSidebarTabBar) ? 14 : 0) +
983 composerBottomInset;
984 // The last collapse toggle; it only applies to the request it was made on.
985 const [userInputToggle, setUserInputToggle] = useState<{
986 readonly requestId: RuntimeRequestId;
987 readonly collapsed: boolean;
988 } | null>(null);
989 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
990 const questionInFlow = Platform.OS === "android" && activeUserInputRequestId !== null;
991 const composerSlotHidden =
992 activeUserInputRequestId !== null || props.creationState?.kind === "failed";
993 const pendingMessageEditBlocked =
994 queuedRunEditBlockedReason(
995 { openQuestionCount: activeUserInputRequestId === null ? 0 : 1 },
996 messages,
997 ) !== null;
998 const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
999 readonly key: string;
1000 readonly threadKey: string;
1001 readonly now: number;
1002 } | null>(null);
1003 // Approval/question identity invalidates quota: answering on any client resumes spending.
1004 const usageLimitsKey = [
1005 selectedThreadKey,
1006 props.selectedThread.modelSelection.instanceId,
1007 props.selectedThread.latestRun?.runId ?? "",
1008 props.activePendingApproval?.requestId ?? props.activePendingUserInput?.requestId ?? "",
1009 ].join(":");
1010 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
1011 setUsageLimitsPanel(null);
1012 }
1013 const usageLimitsReport =
1014 usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
1015 ? collectProviderUsageLimits(
1016 props.selectedThread.modelSelection.instanceId,
1017 props.serverConfig?.providers ?? [],
1018 props.serverConfig?.usageLimitSources ?? [],
1019 usageLimitsPanel.now,
1020 props.selectedThread.modelSelection.model,
1021 )
1022 : null;
1023 const showUsageLimits = (report: UsageLimitsReport | null) =>
1024 setUsageLimitsPanel(
1025 report === null
1026 ? null
1027 : {
1028 key: usageLimitsKey,
1029 threadKey: selectedThreadKey,
1030 now: Date.parse(report.createdAt),
1031 },
1032 );
1033 const dismissUsageLimits = () => setUsageLimitsPanel(null);
1034 // Late sends clear only their originating thread's limits panel.
1035 const clearUsageLimitsFor = (threadKey: string) =>
1036 setUsageLimitsPanel((current) =>
1037 current !== null && current.threadKey === threadKey ? null : current,
1038 );
1039 const userInputToggled =
1040 userInputToggle !== null && userInputToggle.requestId === activeUserInputRequestId;
1041 const userInputCollapsed = userInputToggled && userInputToggle.collapsed;
1042 // A height React sets from keyboard state lags the sticky translation by a Yoga pass and
1043 // flashes over the nav header on the way up, so the usage panel reserves the keyboard instead.
1044 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
1045 if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
1046 setLastKnownKeyboardHeight(liveKeyboardHeight);
1047 }
1048 const reservedKeyboardHeight =
1049 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT;
1050 // Waiting for a visibility render misses the first keyboard frames.
1051 const keyboardStickyEnabled =
1052 Platform.OS === "ios"
1053 ? deviceType !== "duo-unfolded" || (composerOwnsKeyboard && !sidebarSearchActive)
1054 : !keyboardStateSuspect;
1055 const estimatedOverlayHeight = composerOverlapHeight;
1056 const contentInsetEndAdjustment = useSharedValue(estimatedOverlayHeight);
1057 const onComposerLayout = useCallback(
1058 (event: LayoutChangeEvent) => {
1059 // The composer already animates its measured height on each layout.
1060 contentInsetEndAdjustment.set(event.nativeEvent.layout.height);
1061 },
1062 [contentInsetEndAdjustment],
1063 );
1064 // Android lays the screen out below its opaque header and reports a zero
1065 // header height, so the window height overstates the room by the header.
1066 const [screenHeight, setScreenHeight] = useState<number | null>(null);
1067 const [screenWidth, setScreenWidth] = useState<number | null>(null);
1068 const handleScreenLayout = (event: LayoutChangeEvent) => {
1069 setScreenHeight(event.nativeEvent.layout.height);
1070 const width = Math.round(event.nativeEvent.layout.width);
1071 setScreenWidth((current) =>
1072 current !== null && Math.abs(current - width) <= 1 ? current : width,
1073 );
1074 };
1075 const screenAreaHeight = screenHeight ?? windowHeight;
1076 const draftViewportHeight = screenAreaHeight - navigationHeaderHeight - liveKeyboardHeight;
1077 // The question card reads the keyboard frame on the UI thread, in the same frame the sticky
1078 // view translates, so it gets the full height while the keyboard is closed and never crosses
1079 // the header while the keyboard moves.
1080 const { height: keyboardTranslation } = useReanimatedKeyboardAnimation();
1081 const pendingUserInputMaxHeight = useDerivedValue(() =>
1082 derivePendingUserInputMaxHeight({
1083 windowHeight: screenAreaHeight,
1084 keyboardHeight: keyboardStickyEnabled ? -keyboardTranslation.value : 0,
1085 navigationHeaderHeight,
1086 // An in-flow question shares the room above it with the floating control.
1087 composerOverlapHeight:
1088 composerBottomInset +
1089 (questionInFlow && showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0),
1090 }),
1091 );
1092 // A question pads itself clear of the bottom inset, below the card's own height limit.
1093 const questionBottomInset = activeUserInputRequestId !== null ? composerBottomInset : 0;
1094 const composerPanelsHeightStyle = useAnimatedStyle(() => ({
1095 maxHeight: pendingUserInputMaxHeight.value + questionBottomInset,
1096 flexGrow: 0,
1097 }));
1098 // Questions overlay the composer on iOS; an approval sits above it, so it gives up its height.
1099 const approvalHeightStyle = useAnimatedStyle(() => ({
1100 maxHeight: derivePendingUserInputMaxHeight({
1101 windowHeight: screenAreaHeight,
1102 keyboardHeight: keyboardStickyEnabled ? -keyboardTranslation.value : 0,
1103 navigationHeaderHeight,
1104 composerOverlapHeight,
1105 }),
1106 flexGrow: 0,
1107 }));
1108 // The usage panel stacks with the composer and any approval card, so it gets
1109 // whatever room they leave below the header. Measured only while it is open
1110 // so typing in the composer does not re-render the screen.
1111 const usageLimitsOpen = usageLimitsReport !== null && activeUserInputRequestId === null;
1112 const [usageLimitsLayout, setUsageLimitsLayout] = useState({ overlay: 0, panel: 0 });
1113 const handleComposerOverlayLayout = (event: LayoutChangeEvent) => {
1114 if (!questionInFlow) onComposerLayout(event);
1115 if (!usageLimitsOpen) return;
1116 const overlay = event.nativeEvent.layout.height;
1117 setUsageLimitsLayout((current) =>
1118 current.overlay === overlay ? current : { ...current, overlay },
1119 );
1120 };
1121 const handleUsageLimitsLayout = (event: LayoutChangeEvent) => {
1122 const panel = event.nativeEvent.layout.height;
1123 setUsageLimitsLayout((current) => (current.panel === panel ? current : { ...current, panel }));
1124 };
1125 const overlayBesideUsageLimits =
1126 usageLimitsLayout.overlay > 0
1127 ? usageLimitsLayout.overlay - usageLimitsLayout.panel
1128 : composerOverlapHeight;
1129 // The floor keeps the close row on screen when the stack below leaves no room at all.
1130 const usageLimitsMaxHeight = Math.max(
1131 USAGE_LIMITS_PANEL_MIN_HEIGHT,
1132 Math.min(
1133 Math.round(screenAreaHeight * 0.4),
1134 screenAreaHeight -
1135 navigationHeaderHeight -
1136 reservedKeyboardHeight -
1137 overlayBesideUsageLimits -
1138 USAGE_LIMITS_PANEL_GAP * 2,
1139 ),
1140 );
1141 // A toggle animates the card; a new request starts expanded at once.
1142 const userInputMotion = !userInputToggled
1143 ? "fresh"
1144 : userInputCollapsed
1145 ? "collapsed"
1146 : "expanded";
1147 const userInputCardProgress = useDerivedValue<number>(
1148 () =>
1149 userInputMotion === "fresh"
1150 ? 1
1151 : withTiming(userInputMotion === "collapsed" ? 0 : 1, USER_INPUT_TOGGLE_TIMING),
1152 [userInputMotion],
1153 );
1154 // Collapsing the inset is instant: the sinking card still covers the strip
1155 // being revealed, and animating the inset downward drifted the short-content
1156 // end anchor.
1157 const userInputInsetProgress = useDerivedValue<number>(() => {
1158 if (userInputMotion === "collapsed") return 0;
1159 return userInputMotion === "fresh" ? 1 : withTiming(1, USER_INPUT_TOGGLE_TIMING);
1160 }, [userInputMotion]);
1161 const userInputCardCoverage = useSharedValue(0);
1162 const composerPopoverHeight = useSharedValue(0);
1163 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
1164 const reduceMotion = useReducedMotion();
1165 const floatingCoverageTarget = showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0;
1166 const floatingControlCoverage = useDerivedValue(
1167 () => withTiming(floatingCoverageTarget, { duration: 180, reduceMotion: ReduceMotion.System }),
1168 [floatingCoverageTarget],
1169 );
1170 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
1171 const questionStatusSpace = useAnimatedStyle(() => ({ height: floatingControlCoverage.value }));
1172 const combinedContentInsetEndAdjustment = useSharedValue(estimatedOverlayHeight);
1173 useAnimatedReaction(
1174 () =>
1175 questionInFlow
1176 ? 0
1177 : contentInsetEndAdjustment.value +
1178 // The feed's last row keeps a gap above the composer; the status row grows from it.
1179 Math.max(FEED_END_GAP, floatingControlCoverage.value) +
1180 (userInputCoverageApplies
1181 ? userInputInsetProgress.value * userInputCardCoverage.value
1182 : 0),
1183 (value) => {
1184 combinedContentInsetEndAdjustment.set(value);
1185 },
1186 [questionInFlow, userInputCoverageApplies],
1187 );
1188 const composerPopoverLift = useDerivedValue(() =>
1189 withTiming(
1190 !composerSlotHidden && composerPopoverHeight.value > 0 ? composerPopoverHeight.value + 8 : 0,
1191 { duration: 180, easing: Easing.out(Easing.cubic), reduceMotion: ReduceMotion.System },
1192 ),
1193 );
1194 const floatingControlLift = useDerivedValue(
1195 () =>
1196 Math.max(
1197 userInputCoverageApplies ? userInputCardProgress.value * userInputCardCoverage.value : 0,
1198 composerPopoverLift.value,
1199 ),
1200 [userInputCoverageApplies],
1201 );
1202 // A jump this thread never reached lets go when it closes.
1203 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the thread scope, clears its timers and ends a pending message jump when the thread changes
1204 useEffect(() => {
1205 if (threadScope.current.signal.aborted) threadScope.current = new AbortController();
1206 const scope = threadScope.current;
1207 return () => {
1208 scope.abort();
1209 if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
1210 finishThreadMessageJump(selectedThreadKey);
1211 };
1212 }, [selectedThreadKey]);
1213 const handleToggleUserInputCollapsed = () => {
1214 if (activeUserInputRequestId === null) {
1215 return;
1216 }
1217 if (userInputCollapsed) {
1218 setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false });
1219 } else {
1220 Keyboard.dismiss();
1221 setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true });
1222 }
1223 };
1224 const showContent = props.showContent ?? true;
1225 // Showing the thread counts as viewing it, before its live shell arrives too.
1226 useAtomMount(
1227 threadVisitTracker(
1228 showContent && !props.draftMode
1229 ? { environmentId: props.environmentId, threadId: props.selectedThread.id }
1230 : null,
1231 ),
1232 );
1233 const layoutVariant = props.layoutVariant ?? "compact";
1234 const isSplitLayout = layoutVariant !== "compact";
1235 const contentMaxWidth =
1236 Platform.OS === "android"
1237 ? ANDROID_READING_MAX_WIDTH
1238 : isSplitLayout
1239 ? CHAT_CONTENT_MAX_WIDTH
1240 : undefined;
1241 const providerSubagentProvider = props.serverConfig?.providers.find(
1242 (provider) => provider.instanceId === props.selectedThread.modelSelection.instanceId,
1243 );
1244 const providerSubagentModelSlug = providerSubagentProvider
1245 ? resolveSelectableModel(
1246 providerSubagentProvider.driver,
1247 props.selectedThread.modelSelection.model,
1248 providerSubagentProvider.models,
1249 )
1250 : null;
1251 const providerSubagentCatalogModel = providerSubagentProvider?.models.find(
1252 (model) => model.slug === providerSubagentModelSlug,
1253 );
1254 const workspaceContentWidth = useWorkspaceContentWidth();
1255 // Clearing animated width can retain the unfolded width after Android resumes folded.
1256 const composerWidthStyle = useAnimatedStyle(() =>
1257 isSplitLayout && workspaceContentWidth !== null
1258 ? {
1259 width: Math.max(
1260 0,
1261 workspaceContentWidth.value - controlInsets.left - controlInsets.right,
1262 ),
1263 right: undefined,
1264 }
1265 : { width: "auto", right: controlInsets.right },
1266 );
1267 // A native column resizes the screen before JS hears of it. The feed and the composer take the
1268 // measured width in one render, so they change size together rather than the composer first.
1269 const columnWidth = usesNativeWorkspaceColumns && isSplitLayout ? screenWidth : null;
1270 const columnComposerWidthStyle =
1271 columnWidth === null
1272 ? null
1273 : { width: Math.max(0, columnWidth - controlInsets.left - controlInsets.right) };
1274 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
1275 useAtomMount(threadStreamHaptics(props.selectedThreadDetailRef));
1276 const selectedProviderSkills = (() => {
1277 const provider = props.serverConfig?.providers.find(
1278 (candidate) => candidate.instanceId === selectedInstanceId,
1279 );
1280 return provider
1281 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
1282 : [];
1283 })();
1284
1285 const currentPendingApprovals = () =>
1286 props.selectedThreadDetailRef === null
1287 ? []
1288 : (appAtomRegistry.get(
1289 environmentThreadDetails.pendingRequestsAtom(props.selectedThreadDetailRef),
1290 )?.approvals ?? []);
1291 const handleSendMessage = async (
1292 followUp?: ActiveTurnComposerAction,
1293 stillSendable?: () => boolean,
1294 ) => {
1295 const scope = threadScope.current.signal;
1296 const targetThreadKey = selectedThreadKey;
1297 const hasUserMessage = selectedThreadFeed.some(
1298 (entry) => entry.type === "message" && entry.message.role === "user",
1299 );
1300 // Runs only once the send path has validated the draft and is about to deliver it, so an
1301 // empty submit, a queued-message edit, or `/feedback` leaves approvals alone.
1302 const approvalsToDecline = props.activePendingApprovals;
1303 const declineBeforeDispatch =
1304 approvalsToDecline.length > 0 && props.activePendingUserInput === null
1305 ? async (text: string, hasAttachmentsOrContext: boolean) => {
1306 if (scope.aborted || stillSendable?.() === false || props.respondingApprovalId !== null)
1307 return false;
1308 const feedbackTarget = approvalsToDecline[0];
1309 if (feedbackTarget?.supportsFeedback) {
1310 if (hasAttachmentsOrContext) {
1311 Dialog.alert(
1312 gt("Approval feedback"),
1313 gt("Send approval feedback without attachments or added context."),
1314 );
1315 return false;
1316 }
1317 return (await sendApprovalFeedback(feedbackTarget, text, props.onRespondToApproval))
1318 ? ("responded" as const)
1319 : false;
1320 }
1321 return (
1322 props.respondingApprovalId === null &&
1323 (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
1324 !scope.aborted &&
1325 // A draft edited or pasted into during the decline isn't what the user sent.
1326 stillSendable?.() !== false &&
1327 // An approval that arrived during the decline would block the redirect; the draft
1328 // stays so the next send declines it too.
1329 !currentPendingApprovals().some(
1330 (approval) =>
1331 !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
1332 )
1333 );
1334 }
1335 : undefined;
1336 let dismissingKeyboard = false;
1337 const messageId = await props.onSendMessage(followUp, declineBeforeDispatch, () => {
1338 if (
1339 scope.aborted ||
1340 Platform.OS !== "ios" ||
1341 !hasUserMessage ||
1342 !KeyboardController.isVisible()
1343 )
1344 return;
1345 setSendingWithKeyboard(true);
1346 dismissingKeyboard = true;
1347 });
1348 if (messageId === null || scope.aborted) {
1349 return messageId;
1350 }
1351
1352 clearUsageLimitsFor(targetThreadKey);
1353
1354 const nextAnchorMessageId = resolveThreadFeedSubmissionAnchor({
1355 currentAnchorMessageId: anchorMessageId,
1356 submittedMessageId: messageId,
1357 hasStartedTurn: props.selectedThread.latestRun !== null,
1358 hasUserMessage,
1359 queuedMessageCount: props.selectedThreadQueueCount,
1360 deliveryDeferred: props.connectionStateLabel !== "connected",
1361 });
1362 setAnchorMessageId(nextAnchorMessageId);
1363 if (!dismissingKeyboard) composerEditorRef.current?.blur();
1364 const followSubmission =
1365 contentPresentationKind === "ready" &&
1366 (dismissingKeyboard || nextAnchorMessageId === messageId);
1367 if (dismissingKeyboard || followSubmission) {
1368 // Commit the optimistic row before UIKit chooses the closing scroll offset.
1369 requestAnimationFrame(() => {
1370 if (scope.aborted) return;
1371 // Scrolling freezes the keyboard inset, so wait until dismissal has removed it.
1372 void KeyboardController.dismiss()
1373 .then(() => {
1374 if (!followSubmission || scope.aborted) return;
1375 return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false });
1376 })
1377 .catch(() => {
1378 if (!scope.aborted) freeze.set(false);
1379 });
1380 });
1381 }
1382 return messageId;
1383 };
1384
1385 const handleEditPendingMessage = async (message: QueuedThreadMessage) => {
1386 if (pendingMessageEditBlocked) return;
1387 const scope = threadScope.current.signal;
1388 const edited = await settlePromise(() => editPendingThreadMessage(message));
1389 if (AsyncResult.isFailure(edited)) {
1390 const error = squashAtomCommandFailure(edited);
1391 Dialog.alert(
1392 gt("Could not edit message"),
1393 errorDisplayMessage(error, m) ?? gt("Please try again."),
1394 );
1395 return;
1396 }
1397 if (
1398 edited.value &&
1399 !scope.aborted &&
1400 selectedThreadKey === scopedThreadKey(message.environmentId, message.threadId)
1401 ) {
1402 composerEditorRef.current?.focus();
1403 }
1404 };
1405
1406 const collapseComposer = () => {
1407 composerEditorRef.current?.blur();
1408 };
1409
1410 const canCiteAssistantText =
1411 props.composerDraftKey !== null &&
1412 !isProviderSubagent &&
1413 !composerSlotHidden &&
1414 !props.isSavingQueuedEdit &&
1415 !props.draftMode?.interactionLocked &&
1416 !(
1417 voiceInputSession.ownerKey === props.composerDraftKey &&
1418 voiceInputBlocksSubmission(voiceInputSession.controller.currentState)
1419 );
1420 const handleCiteAssistantText = (citation: AssistantCitation) => {
1421 if (!canCiteAssistantText || props.composerDraftKey === null) return;
1422 const target = captureComposerDraftInsertion(props.composerDraftKey);
1423 const prefix = target.start > 0 && !/\s/.test(target.text[target.start - 1]!) ? " " : "";
1424 const value = `${prefix}${serializeAssistantCitation(citation)} `;
1425 const text = target.text.slice(0, target.start) + value + target.text.slice(target.end);
1426 if (!assistantCitationDraftWithinLimit(text)) {
1427 Dialog.alert(
1428 gt("Could not add quote"),
1429 gt(
1430 "This quote would make the message too long to send. Shorten the draft or select less text.",
1431 ),
1432 );
1433 return;
1434 }
1435 insertComposerDraftText(props.composerDraftKey, value, target);
1436 composerEditorRef.current?.focus();
1437 };
1438
1439 const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
1440 const draftMessage =
1441 props.composerDraftKey === null ? "" : getComposerDraftSnapshot(props.composerDraftKey).text;
1442 const nextDraft = appendCodexArtifactTemplateUsePrompt(draftMessage, template);
1443 if (nextDraft !== draftMessage) props.onChangeDraftMessage(nextDraft);
1444 requestAnimationFrame(() => {
1445 composerEditorRef.current?.focus();
1446 composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
1447 });
1448 };
1449
1450 const handleScrollToEnd = () => {
1451 void Haptics.selectionAsync();
1452 void scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false }).catch(() => {
1453 freeze.set(false);
1454 });
1455 };
1456
1457 const showScrollToEndButton = !props.draftMode && contentPresentationKind === "ready" && !isAtEnd;
1458 const { themeAppearance } = useAppearancePreferences();
1459 const isDarkMode = themeAppearance === "dark";
1460
1461 const handleFeedTouchStart = (event: GestureResponderEvent) => {
1462 feedTouchStartRef.current = {
1463 pageX: event.nativeEvent.pageX,
1464 pageY: event.nativeEvent.pageY,
1465 };
1466 };
1467
1468 const handleFeedTouchMove = (event: GestureResponderEvent) => {
1469 const start = feedTouchStartRef.current;
1470 if (!start) {
1471 return;
1472 }
1473 const deltaX = event.nativeEvent.pageX - start.pageX;
1474 const deltaY = event.nativeEvent.pageY - start.pageY;
1475 if (Math.hypot(deltaX, deltaY) > 8) {
1476 feedTouchStartRef.current = null;
1477 }
1478 };
1479
1480 const handleFeedTouchEnd = () => {
1481 if (feedTouchStartRef.current) {
1482 collapseComposer();
1483 }
1484 feedTouchStartRef.current = null;
1485 };
1486
1487 const handleFeedTouchCancel = () => {
1488 feedTouchStartRef.current = null;
1489 };
1490
1491 return (
1492 <View className="flex-1" onLayout={handleScreenLayout}>
1493 {!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
1494 {props.draftMode ? (
1495 props.draftMode.content(
1496 navigationHeaderHeight,
1497 liveKeyboardHeight + estimatedOverlayHeight + 24,
1498 draftViewportHeight,
1499 )
1500 ) : showContent ? (
1501 <View
1502 style={{ flex: 1 }}
1503 onTouchStart={handleFeedTouchStart}
1504 onTouchMove={handleFeedTouchMove}
1505 onTouchEnd={handleFeedTouchEnd}
1506 onTouchCancel={handleFeedTouchCancel}
1507 >
1508 <View
1509 pointerEvents="none"
1510 className={
1511 Platform.OS === "android"
1512 ? "absolute inset-0 bg-thread-canvas"
1513 : "absolute inset-0 bg-screen"
1514 }
1515 />
1516 <RenderErrorBoundary
1517 key={selectedThreadKey}
1518 resetKeys={[props.threadCwd]}
1519 renderFallback={(fallback) => (
1520 <RenderFailureView
1521 {...fallback}
1522 title={gt("The conversation couldn't be displayed")}
1523 bottomInset={estimatedOverlayHeight}
1524 />
1525 )}
1526 >
1527 <WorkspaceMutationIdProvider threadRef={props.selectedThreadDetailRef}>
1528 <ColumnWidth width={columnWidth}>
1529 <ThreadFeed
1530 toolCallVisibility={toolCallVisibility}
1531 environmentId={props.environmentId}
1532 threadId={props.selectedThread.id}
1533 detailRef={props.selectedThreadDetailRef}
1534 workspaceRoot={props.threadCwd}
1535 feed={props.selectedThreadFeed}
1536 pendingHandoff={props.pendingHandoff}
1537 statusLines={statusLines}
1538 worktreeSetup={props.worktreeSetup}
1539 preparingWorktree={
1540 props.creationState?.kind === "preparing" &&
1541 props.creationState.preparingWorktree &&
1542 !props.worktreeSetup
1543 }
1544 queuedMessages={props.queuedMessages}
1545 dispatchingMessageId={props.dispatchingMessageId}
1546 // A native subagent has no composer to edit a pending message in;
1547 // Cancel on the edit banner would discard it.
1548 onEditPendingMessage={
1549 isProviderSubagent || pendingMessageEditBlocked
1550 ? null
1551 : handleEditPendingMessage
1552 }
1553 contentPresentation={props.contentPresentation}
1554 threadTitle={props.selectedThread.title}
1555 latestRun={props.activityRun}
1556 activeWorkStartedAt={props.activeWorkStartedAt}
1557 runlessWorkActive={props.runlessWorkActive ?? false}
1558 listRef={listRef}
1559 freeze={freeze}
1560 anchorMessageId={anchorMessageId}
1561 jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1562 onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1563 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1564 keyboardOffset={composerKeyboardOffset}
1565 sendingWithKeyboard={sendingWithKeyboard}
1566 fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
1567 contentBottomInset={
1568 questionInFlow
1569 ? 0
1570 : estimatedOverlayHeight +
1571 (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : FEED_END_GAP)
1572 }
1573 contentMaxWidth={contentMaxWidth}
1574 historyControls={props.historyControls}
1575 contentSideInsets={deriveContentSideInsets(nativeMetrics)}
1576 layoutVariant={layoutVariant}
1577 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1578 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1579 onIsAtEndChange={setIsAtEnd}
1580 skills={selectedProviderSkills}
1581 onCiteAssistantText={canCiteAssistantText ? handleCiteAssistantText : undefined}
1582 onUseArtifactTemplate={handleUseArtifactTemplate}
1583 />
1584 </ColumnWidth>
1585 </WorkspaceMutationIdProvider>
1586 </RenderErrorBoundary>
1587 </View>
1588 ) : (
1589 <View className="flex-1" />
1590 )}
1591
1592 {showContent ? (
1593 <ThreadBrowserFloat
1594 key={selectedThreadKey}
1595 environmentId={props.environmentId}
1596 threadId={props.selectedThread.id}
1597 tabs={browserTabs.tabs}
1598 loaded={browserTabs.loaded}
1599 top={navigationHeaderHeight + 8}
1600 onOpen={openBrowserPreview}
1601 />
1602 ) : null}
1603
1604 {showContent ? (
1605 <KeyboardStickyView
1606 enabled={keyboardStickyEnabled}
1607 pointerEvents="box-none"
1608 style={
1609 questionInFlow
1610 ? {
1611 marginLeft: controlInsets.left,
1612 marginRight: controlInsets.right,
1613 marginBottom: controlInsets.bottom,
1614 }
1615 : { position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }
1616 }
1617 offset={{ closed: 0, opened: composerKeyboardOffset }}
1618 >
1619 {questionInFlow ? (
1620 <Animated.View pointerEvents="none" style={questionStatusSpace} />
1621 ) : null}
1622 <ComposerPopoverHost
1623 hidden={composerSlotHidden}
1624 popoverHeight={composerPopoverHeight}
1625 inFlow={questionInFlow}
1626 >
1627 {/* The fixed sticky host gives this bottom-anchored child a stable
1628 coordinate space. Its top and height can then animate together
1629 instead of the auto-sized host jumping to Yoga's destination. */}
1630 <Animated.View
1631 pointerEvents="box-none"
1632 style={
1633 questionInFlow
1634 ? (columnComposerWidthStyle ?? (isSplitLayout ? composerWidthStyle : undefined))
1635 : columnComposerWidthStyle
1636 ? [
1637 {
1638 position: "absolute",
1639 bottom: controlInsets.bottom,
1640 left: controlInsets.left,
1641 },
1642 columnComposerWidthStyle,
1643 ]
1644 : [
1645 {
1646 position: "absolute",
1647 bottom: controlInsets.bottom,
1648 left: controlInsets.left,
1649 right: controlInsets.right,
1650 },
1651 composerWidthStyle,
1652 ]
1653 }
1654 >
1655 {/* No paddingTop here: the overlay's measured height becomes the
1656 list's bottom inset, so any padding above the pill/composer
1657 pushes the resting content floor up by the same amount. */}
1658 <View onLayout={handleComposerOverlayLayout} className="w-full">
1659 <View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1660 <FloatingWorkingControl
1661 colorScheme={isDarkMode ? "dark" : "light"}
1662 status={floatingStatus}
1663 extensionStatus={
1664 floatingStatus !== null && floatingStatus.kind === "goal"
1665 ? extensionStatus
1666 : null
1667 }
1668 lift={floatingControlLift}
1669 devicePreview={
1670 devicePreviews.length > 0
1671 ? { count: devicePreviews.length, onPress: openDevicePreview }
1672 : null
1673 }
1674 browserPreview={
1675 browserTabs.tabs.length > 0
1676 ? { count: browserTabs.tabs.length, onPress: () => openBrowserPreview() }
1677 : null
1678 }
1679 showScrollToEnd={showScrollToEndButton}
1680 onScrollToEnd={handleScrollToEnd}
1681 agents={agentsSegment}
1682 onOpenAgents={() => {
1683 Keyboard.dismiss();
1684 navigation.navigate("ThreadAgents", {
1685 environmentId: props.environmentId,
1686 threadId: props.selectedThread.id,
1687 });
1688 }}
1689 queuedCount={queuedCount}
1690 onOpenQueue={() => {
1691 Keyboard.dismiss();
1692 navigation.navigate("ThreadQueue", {
1693 environmentId: props.environmentId,
1694 threadId: props.selectedThread.id,
1695 });
1696 }}
1697 />
1698 <ComposerPanels
1699 className="w-full"
1700 style={Platform.OS === "android" ? composerPanelsHeightStyle : undefined}
1701 keyboardShouldPersistTaps="handled"
1702 nestedScrollEnabled
1703 >
1704 {props.queuedRunEdit !== null ? (
1705 <Animated.View
1706 className="shrink-0"
1707 entering={FadeInDown.duration(180)}
1708 exiting={FadeOut.duration(120)}
1709 >
1710 <ComposerQueuedEditBanner
1711 saving={props.isSavingQueuedEdit}
1712 onCancel={() => {
1713 voiceInputSession.cancel(props.composerDraftKey);
1714 props.onCancelQueuedRunEdit();
1715 }}
1716 />
1717 </Animated.View>
1718 ) : null}
1719 <UsageLimitRecoveryCard
1720 key={props.selectedThread.latestRun?.runId}
1721 thread={props.selectedThread}
1722 environmentId={props.environmentId}
1723 />
1724 <ChildThreadApprovals
1725 threadRef={props.selectedThreadDetailRef}
1726 maxHeight={pendingUserInputMaxHeight}
1727 />
1728 <ThreadGuestShareBar
1729 threadRef={props.selectedThreadDetailRef}
1730 canOperateThread={props.canOperateThread}
1731 />
1732 {props.draftMode ? null : (
1733 <ThreadSideChatsRow
1734 environmentId={props.environmentId}
1735 threadId={props.selectedThread.id}
1736 />
1737 )}
1738 {props.feedbackSubmissions.map((submission) => (
1739 <ComposerFeedback
1740 key={submission.id}
1741 submission={submission}
1742 onDismiss={() => props.onDismissFeedback(submission.id)}
1743 />
1744 ))}
1745 {freshSessionAvailable ? (
1746 <FreshSessionNotice threadKey={selectedThreadKey} />
1747 ) : null}
1748 {props.canOperateThread ? (
1749 <ManagedRuntimeModeNotice
1750 threadKey={selectedThreadKey}
1751 threadRuntimeMode={props.selectedThread.runtimeMode}
1752 supportedRuntimeModes={
1753 props.serverConfig?.providers.find(
1754 (provider) =>
1755 provider.instanceId ===
1756 props.selectedThread.modelSelection.instanceId,
1757 )?.supportedRuntimeModes
1758 }
1759 policy={props.serverConfig?.managedPolicy}
1760 />
1761 ) : null}
1762 {composerError !== null ? (
1763 <Animated.View
1764 className="shrink-0"
1765 entering={FadeInDown.duration(180)}
1766 exiting={FadeOut.duration(120)}
1767 >
1768 <ComposerErrorNotice
1769 message={composerError}
1770 onDismiss={() => clearThreadComposerError(selectedThreadKey)}
1771 />
1772 </Animated.View>
1773 ) : null}
1774 {usageLimitsReport && activeUserInputRequestId === null ? (
1775 <Animated.View
1776 className="shrink-0 px-4"
1777 style={{ paddingBottom: USAGE_LIMITS_PANEL_GAP }}
1778 onLayout={handleUsageLimitsLayout}
1779 entering={FadeInDown.duration(220)}
1780 exiting={FadeOut.duration(140)}
1781 >
1782 <ComposerUsageLimits
1783 report={usageLimitsReport}
1784 environmentId={props.environmentId}
1785 maxHeight={usageLimitsMaxHeight}
1786 onClose={dismissUsageLimits}
1787 />
1788 </Animated.View>
1789 ) : null}
1790 {props.creationState?.kind === "failed" ? (
1791 <Animated.View
1792 className="shrink-0 px-4"
1793 style={{ paddingBottom: composerBottomInset }}
1794 entering={FadeInDown.duration(220)}
1795 exiting={FadeOut.duration(140)}
1796 >
1797 <ThreadCreationFailedCard
1798 reason={props.creationState.reason}
1799 onEditTask={props.creationState.onEditTask}
1800 />
1801 </Animated.View>
1802 ) : null}
1803 {props.activePendingApproval || props.activePendingUserInput ? (
1804 <Animated.View
1805 className="shrink-0 gap-3 px-4 pb-3"
1806 style={
1807 activeUserInputRequestId !== null
1808 ? { paddingBottom: composerBottomInset }
1809 : undefined
1810 }
1811 entering={FadeInDown.duration(220)}
1812 exiting={FadeOut.duration(140)}
1813 >
1814 {props.activePendingApproval ? (
1815 <Animated.ScrollView
1816 key={props.activePendingApproval.requestId}
1817 style={approvalHeightStyle}
1818 keyboardShouldPersistTaps="handled"
1819 nestedScrollEnabled
1820 >
1821 <PendingApprovalCard
1822 canOperateThread={props.canOperateThread}
1823 approval={props.activePendingApproval}
1824 respondingApprovalId={props.respondingApprovalId}
1825 onRespond={props.onRespondToApproval}
1826 />
1827 </Animated.ScrollView>
1828 ) : null}
1829 {props.activePendingUserInput ? (
1830 <PendingUserInputCard
1831 environmentId={props.environmentId}
1832 threadId={props.selectedThread.id}
1833 workspaceRoot={props.threadCwd}
1834 canOperateThread={props.canOperateThread}
1835 pendingUserInput={props.activePendingUserInput}
1836 maxHeight={pendingUserInputMaxHeight}
1837 collapsed={userInputCollapsed}
1838 onToggleCollapsed={handleToggleUserInputCollapsed}
1839 onStopThread={props.onStopThread}
1840 cardProgress={userInputCardProgress}
1841 cardCoverage={userInputCardCoverage}
1842 onInputFocusChange={handleOwnedInputFocusChange}
1843 drafts={props.activePendingUserInputDrafts}
1844 answers={props.activePendingUserInputAnswers}
1845 respondingUserInputId={props.respondingUserInputId}
1846 onSelectOption={props.onSelectUserInputOption}
1847 onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}
1848 onSubmit={props.onSubmitUserInput}
1849 onDismiss={props.onDismissUserInput}
1850 />
1851 ) : null}
1852 </Animated.View>
1853 ) : null}
1854 </ComposerPanels>
1855 </View>
1856
1857 <View style={composerSlotHidden ? { display: "none" } : undefined}>
1858 {isProviderSubagent ? (
1859 <View
1860 className="self-center px-3 pt-1.5"
1861 style={{
1862 width: "100%",
1863 maxWidth: contentMaxWidth,
1864 paddingBottom: composerBottomInset + 6,
1865 }}
1866 >
1867 <ProviderSubagentBar
1868 provider={providerSubagentProvider ?? null}
1869 modelLabel={
1870 providerSubagentCatalogModel?.name ??
1871 formatModelSlugName(props.selectedThread.modelSelection.model)
1872 }
1873 effortLabel={formatModelSelectionEffort(
1874 props.selectedThread.modelSelection,
1875 providerSubagentProvider?.models,
1876 reportedModelSelection,
1877 )}
1878 status={props.providerSubagentStatus ?? null}
1879 inspect={
1880 providerSubagentProvider?.driver === "antigravity"
1881 ? {
1882 environmentId: props.environmentId,
1883 threadId: props.selectedThread.id,
1884 }
1885 : null
1886 }
1887 onOpenParent={
1888 props.selectedThread.lineage.parentThreadId === null
1889 ? null
1890 : () =>
1891 openLinkedThread({
1892 environmentId: String(props.environmentId),
1893 threadId: String(props.selectedThread.lineage.parentThreadId),
1894 })
1895 }
1896 />
1897 </View>
1898 ) : (
1899 <>
1900 <ThreadComposer
1901 isDraft={Boolean(props.draftMode)}
1902 canOperateThread={props.canOperateThread}
1903 reportedModelSelection={reportedModelSelection}
1904 editorRef={composerEditorRef}
1905 placeholder={
1906 props.activePendingApproval
1907 ? props.activePendingApproval.supportsFeedback
1908 ? gt("Send feedback to decline this request")
1909 : gt("Send a message to decline and redirect the agent")
1910 : gt("Ask anything")
1911 }
1912 contentMaxWidth={contentMaxWidth}
1913 draftControls={props.draftMode?.controls(draftViewportHeight)}
1914 connectionState={props.connectionStateLabel}
1915 environmentLabel={props.environmentLabel}
1916 selectedThread={props.selectedThread}
1917 compactBeforeSend={props.compactBeforeSend ?? null}
1918 hasCompactableConversation={
1919 hasCompactableConversation && !props.isCompacting
1920 }
1921 {...(freshSessionAvailable
1922 ? {
1923 onFreshSession: () => setFreshSessionPending(selectedThreadKey, true),
1924 }
1925 : {})}
1926 offersSideChat={
1927 props.offersSideChat &&
1928 !props.draftMode &&
1929 props.canOperateThread &&
1930 props.queuedRunEdit === null &&
1931 props.activePendingApproval === null &&
1932 props.activePendingUserInput === null
1933 }
1934 serverConfig={props.serverConfig}
1935 queueCount={props.selectedThreadQueueCount}
1936 activeThreadBusy={props.activeThreadBusy}
1937 redirectsApproval={
1938 props.activePendingApprovals.length > 0 &&
1939 props.activePendingUserInput === null
1940 }
1941 canStopThread={props.canStopThread}
1942 environmentId={props.environmentId}
1943 projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
1944 // Keep follow-ups in the draft until server creation succeeds, or rejection strands them in the outbox.
1945 sendBlockedReason={
1946 props.draftMode
1947 ? props.draftMode.sendBlockedReason
1948 : props.creationState?.kind === "preparing" &&
1949 !props.creationState.serverOwned
1950 ? gt("Starting the task…")
1951 : null
1952 }
1953 interactionLocked={props.draftMode?.interactionLocked}
1954 draftKey={props.composerDraftKey ?? undefined}
1955 followUpBehavior={
1956 props.activePendingApprovals.length > 0 &&
1957 props.activePendingUserInput === null
1958 ? "steer"
1959 : props.followUpBehavior
1960 }
1961 canSteerActiveTurn={props.canSteerActiveTurn}
1962 hidden={composerSlotHidden}
1963 queuedEdit={
1964 props.queuedRunEdit === null
1965 ? null
1966 : {
1967 existingAttachments: props.queuedRunEdit.existingAttachments,
1968 saving: props.isSavingQueuedEdit,
1969 onRemoveExistingAttachment: props.onRemoveQueuedEditAttachment,
1970 }
1971 }
1972 bottomInset={composerBottomInset}
1973 onChangeDraftMessage={props.onChangeDraftMessage}
1974 onPickDraftMedia={props.onPickDraftMedia}
1975 onPickDraftFiles={props.onPickDraftFiles}
1976 onNativePasteImages={props.onNativePasteImages}
1977 onNativePasteText={props.onNativePasteText}
1978 onRemoveDraftImage={props.onRemoveDraftImage}
1979 onStopThread={props.onStopThread}
1980 onResumeQueue={props.onResumeQueue}
1981 onSendMessage={handleSendMessage}
1982 onShowUsageLimits={showUsageLimits}
1983 canSwitchProvider={props.canSwitchThreadProvider}
1984 onHeightChange={handleComposerHeightChange}
1985 onEditorFocusChange={handleOwnedInputFocusChange}
1986 />
1987 </>
1988 )}
1989 </View>
1990 </View>
1991 </Animated.View>
1992 </ComposerPopoverHost>
1993 </KeyboardStickyView>
1994 ) : null}
1995 </View>
1996 );
1997 }