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

ThreadDetailScreen.tsx

1,159 lines48.5 KB

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