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

ThreadComposer.tsx

918 lines33.4 KB

1import type {
2 EnvironmentId,
3 MessageId,
4 ModelSelection,
5 OrchestrationThreadShell,
6 ProviderInteractionMode,
7 RuntimeMode,
8 ServerConfig as T3ServerConfig,
9} from "@t3tools/contracts";
10import {
11 detectComposerTrigger,
12 replaceTextRange,
13 serializeComposerFileLink,
14 type ComposerTrigger,
15} from "@t3tools/shared/composerTrigger";
16import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
17import type { ReactNode } from "react";
18import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
19import {
20 ActivityIndicator,
21 Image,
22 Platform,
23 Pressable,
24 StyleSheet,
25 View,
26 type ViewStyle,
27} from "react-native";
28import ImageViewing from "react-native-image-viewing";
29import Animated, {
30 FadeIn,
31 FadeInDown,
32 FadeOut,
33 FadeOutDown,
34 LinearTransition,
35} from "react-native-reanimated";
36import { useThemeColor } from "../../lib/useThemeColor";
37import { themeColorWithAlpha } from "../../lib/mobileTheme";
38import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
39import { scopedThreadKey } from "../../lib/scopedEntities";
40​
41import { AppText as Text } from "../../components/AppText";
42import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
43import { GlassSurface } from "../../components/GlassSurface";
44import {
45 ComposerEditor,
46 type ComposerEditorHandle,
47 type ComposerEditorSelection,
48} from "../../components/ComposerEditor";
49import {
50 ComposerInlineControl,
51 ComposerToolbarButton,
52 ComposerToolbarRow,
53 ComposerToolbarScroller,
54} from "../../components/ComposerToolbar";
55import { ControlPill } from "../../components/ControlPill";
56import { ProviderIcon } from "../../components/ProviderIcon";
57import type { DraftComposerImageAttachment } from "../../lib/composerImages";
58import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
59import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
60import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
61import type { RemoteClientConnectionState } from "../../lib/connection";
62import {
63 insertRankedSearchResult,
64 normalizeSearchQuery,
65 scoreQueryMatch,
66} from "@t3tools/shared/searchRanking";
67import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
68import { useComposerPathSearch } from "../../state/use-composer-path-search";
69import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
70import {
71 type ExistingThreadSettingsRouteSession,
72 useExistingThreadSettingsRoutePresentation,
73} from "./ThreadSettingsSheet";
74import {
75 useThreadSettingsSheetPresentation,
76 type NavigationWithFinishTransitioning,
77} from "./use-thread-settings-sheet-presentation";
78​
79/**
80 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
81 * Exported so the parent can compute feed overlap / content insets.
82 */
83export const COMPOSER_COLLAPSED_CHROME = 60;
84​
85/**
86 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
87 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
88 */
89export const COMPOSER_EXPANDED_CHROME = 156;
90​
91export interface ThreadComposerProps {
92 readonly draftMessage: string;
93 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
94 readonly placeholder: string;
95 readonly contentMaxWidth?: number;
96 readonly bottomInset?: number;
97 readonly connectionState: RemoteClientConnectionState;
98 readonly connectionError: string | null;
99 readonly environmentLabel: string | null;
100 /**
101 * Message sync phase for the selected thread (drives the status pill):
102 * "loading" = first fetch, nothing to show yet; "syncing" = cached messages
103 * are on screen while they reconcile with the server.
104 */
105 readonly threadSyncPhase?: "loading" | "syncing" | null;
106 readonly selectedThread: OrchestrationThreadShell;
107 readonly serverConfig: T3ServerConfig | null;
108 readonly queueCount: number;
109 readonly environmentId: EnvironmentId;
110 readonly projectCwd: string | null;
111 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
112 readonly onChangeDraftMessage: (value: string) => void;
113 readonly onPickDraftImages: () => Promise<void>;
114 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
115 readonly onRemoveDraftImage: (imageId: string) => void;
116 readonly onStopThread: () => void;
117 readonly onSendMessage: () => Promise<MessageId | null>;
118 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
119 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
120 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
121 readonly onReconnectEnvironment: () => void;
122 readonly onExpandedChange?: (expanded: boolean) => void;
123 /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
124 readonly onEditorFocusChange?: (focused: boolean) => void;
126​
127/**
128 * The pill / card container — renders with Expo's native GlassView on supported
129 * iOS 26+ devices and keeps the existing opaque fallback elsewhere.
130 * Exported so NewTaskDraftScreen can render the same composer chrome.
131 */
132// One timing for every piece of the expanded↔compact morph so the surface,
133// toolbar, and siblings move together instead of popping between layouts.
134// Android gets NO layout transition: the composer rides the keyboard via
135// KeyboardStickyView (frame-synced to the IME), and a time-based morph
136// running alongside that translate reads as jitter. Snapping the layout and
137// letting the keyboard-synced slide be the only motion looks native there.
138const COMPOSER_LAYOUT_TRANSITION =
139 Platform.OS === "android" ? undefined : LinearTransition.duration(220);
140​
141export function ComposerSurface(props: {
142 readonly children: ReactNode;
143 readonly style: ViewStyle;
144 readonly isDarkMode: boolean;
145 /** Existing thread composers morph between pill and card layouts. */
146 readonly animateLayout?: boolean;
147}) {
148 const cardColor = useThemeColor("--color-card-translucent");
149 const borderColor = useThemeColor("--color-border");
150 const shadowColor = useThemeColor("--color-primary-shadow");
151 // Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself
152 // (needed to clip content to the pill shape) would clip the shadow on iOS.
153 const shadowStyle: ViewStyle = {
154 borderRadius: props.style.borderRadius,
155 shadowColor,
156 shadowOpacity: props.isDarkMode ? 0.35 : 0.12,
157 shadowRadius: 14,
158 shadowOffset: { width: 0, height: 6 },
159 elevation: 10,
160 };
161​
162 return (
163 <Animated.View
164 layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}
165 style={shadowStyle}
166 >
167 <GlassSurface
168 chrome="none"
169 fallbackStyle={{
170 backgroundColor: cardColor,
171 borderWidth: 1,
172 borderColor,
173 }}
174 glassEffectStyle="regular"
175 // The composer is a passive material containing interactive controls.
176 // Expo GlassView defaults to non-interactive and both layouts share it.
177 tintColor="transparent"
178 style={props.style}
179 >
180 {props.children}
181 </GlassSurface>
182 </Animated.View>
183 );
185​
186type ComposerStatusPillState = {
187 readonly kind: "unavailable" | "reconnecting" | "syncing";
188 readonly label: string;
189};
190​
191function composerConnectionStatus(input: {
192 readonly connectionError: string | null;
193 readonly connectionState: RemoteClientConnectionState;
194 readonly environmentLabel: string | null;
195 readonly threadSyncPhase?: "loading" | "syncing" | null;
196}): ComposerStatusPillState | null {
197 const environmentLabel = input.environmentLabel ?? "Environment";
198​
199 switch (input.connectionState) {
200 case "connecting":
201 case "reconnecting":
202 return {
203 kind: "reconnecting",
204 label:
205 input.connectionError === null
206 ? `Reconnecting to ${environmentLabel}...`
207 : `Failed to connect. Retrying ${environmentLabel}...`,
208 };
209 case "offline":
210 return { kind: "unavailable", label: "You are offline" };
211 case "error":
212 return {
213 kind: "unavailable",
214 label: input.connectionError
215 ? `Failed to connect to ${environmentLabel}: ${input.connectionError}`
216 : `Failed to connect to ${environmentLabel}`,
217 };
218 case "available":
219 return { kind: "unavailable", label: `${environmentLabel} is not connected` };
220 case "connected":
221 break;
222 }
223​
224 // Connected: the pill is the single loading/sync indicator. One stable
225 // label per open — "Loading" when starting from scratch, "Syncing" when
226 // cached messages are already visible.
227 switch (input.threadSyncPhase) {
228 case "loading":
229 return { kind: "syncing", label: "Loading messages..." };
230 case "syncing":
231 return { kind: "syncing", label: "Syncing messages..." };
232 default:
233 return null;
234 }
236​
237const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
238 readonly onPress: () => void;
239 readonly status: ComposerStatusPillState;
240}) {
241 const isReconnecting = props.status.kind !== "unavailable";
242 const indicatorColor = useThemeColor("--color-icon-muted");
243​
244 return (
245 <Animated.View
246 className="absolute inset-x-0 bottom-full items-center pb-2"
247 entering={FadeInDown.duration(180)}
248 exiting={FadeOutDown.duration(140)}
249 pointerEvents="box-none"
250 >
251 <Pressable
252 accessibilityRole="button"
253 onPress={props.onPress}
254 className="max-w-full flex-row items-center gap-2 rounded-full bg-card px-3 py-2 shadow-sm active:opacity-70"
255 >
256 {isReconnecting ? (
257 <ActivityIndicator size="small" color={indicatorColor} />
258 ) : (
259 <View className="h-2 w-2 rounded-full bg-red-500" />
260 )}
261 <Text
262 className="max-w-[260px] text-sm font-t3-bold leading-snug text-foreground"
263 numberOfLines={1}
264 >
265 {props.status.label}
266 </Text>
267 </Pressable>
268 </Animated.View>
269 );
270});
271​
272export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
273 const navigation = useNavigation();
274 const { themeAppearance } = useAppearancePreferences();
275 const isDarkMode = themeAppearance === "dark";
276 const foregroundColor = useThemeColor("--color-foreground");
277 const bodyText = useScaledTextRole("body");
278 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
279 const inputRef = props.editorRef ?? fallbackInputRef;
280 const [isFocused, setIsFocused] = useState(false);
281 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
282 editorRef: inputRef,
283 isEditorFocused: isFocused,
284 });
285 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
286 const settingsRoutePresentedRef = useRef(false);
287 const wasExpandedBeforePreviewRef = useRef(false);
288 const inFlightThreadIdsRef = useRef(new Set<string>());
289 const { onExpandedChange } = props;
290​
291 const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
292 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
293 // Opening and presentation count as active so the composer stays expanded
294 // while focus moves between its native editor and the settings picker.
295 const isExpanded = isFocused || settingsSheetPresentation.isActive;
296 const canSend = hasContent;
297​
298 // Notify the parent from the derived value, not focus events: the parent
299 // sizes the feed inset from this, and blur-during-sheet would otherwise
300 // report collapsed while the composer still renders expanded.
301 useEffect(() => {
302 onExpandedChange?.(isExpanded);
303 }, [isExpanded, onExpandedChange]);
304​
305 const onPressImage = useCallback(
306 (uri: string) => {
307 wasExpandedBeforePreviewRef.current = isFocused;
308 setPreviewImageUri(uri);
309 },
310 [isFocused],
311 );
312​
313 const closePreview = useCallback(() => {
314 setPreviewImageUri(null);
315 if (wasExpandedBeforePreviewRef.current) {
316 setTimeout(() => inputRef.current?.focus(), 100);
317 }
318 }, [inputRef]);
319​
320 const onEditorFocusChange = props.onEditorFocusChange;
321 const handleFocus = useCallback(() => {
322 setIsFocused(true);
323 onEditorFocusChange?.(true);
324 }, [onEditorFocusChange]);
325​
326 const handleBlur = useCallback(() => {
327 setIsFocused(false);
328 onEditorFocusChange?.(false);
329 }, [onEditorFocusChange]);
330 const showStopAction =
331 props.selectedThread.session?.status === "running" ||
332 props.selectedThread.session?.status === "starting";
333​
334 const sendLabel =
335 props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
336 const currentModelSelection = props.selectedThread.modelSelection;
337 const currentRuntimeMode = props.selectedThread.runtimeMode;
338 const connectionStatus = composerConnectionStatus({
339 connectionError: props.connectionError,
340 connectionState: props.connectionState,
341 environmentLabel: props.environmentLabel,
342 threadSyncPhase: props.threadSyncPhase,
343 });
344 const toolbarSurface = String(useThemeColor("--color-card"));
345 const backdropSurface = String(useThemeColor("--color-screen"));
346 const toolbarFadeOpaque = themeColorWithAlpha(toolbarSurface, 0.95);
347 const toolbarFadeTransparent = themeColorWithAlpha(toolbarSurface, 0);
348 const backdropGradient = `linear-gradient(to bottom, ${themeColorWithAlpha(backdropSurface, 0)} 0%, ${themeColorWithAlpha(backdropSurface, 0.6)} 55%, ${themeColorWithAlpha(backdropSurface, 0.9)} 100%)`;
349 const selectedProviderStatus = useMemo(() => {
350 if (!props.serverConfig) return null;
351 return (
352 props.serverConfig.providers.find(
353 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
354 ) ?? null
355 );
356 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
357​
358 // ── Trigger detection ────────────────────────────────────
359 const [composerSelection, setComposerSelection] = useState(() => ({
360 start: props.draftMessage.length,
361 end: props.draftMessage.length,
362 }));
363​
364 const handleSelectionChange = useCallback((selection: ComposerEditorSelection) => {
365 setComposerSelection(selection);
366 }, []);
367 useEffect(() => {
368 const end = props.draftMessage.length;
369 setComposerSelection((selection) => {
370 const start = Math.min(selection.start, end);
371 const selectionEnd = Math.min(selection.end, end);
372 if (start === selection.start && selectionEnd === selection.end) {
373 return selection;
374 }
375 return { start, end: selectionEnd };
376 });
377 }, [props.draftMessage.length]);
378​
379 const composerTrigger = useMemo<ComposerTrigger | null>(() => {
380 if (composerSelection.start !== composerSelection.end) {
381 return null;
382 }
383 return detectComposerTrigger(props.draftMessage, composerSelection.end);
384 }, [composerSelection, props.draftMessage]);
385 const pathSearch = useComposerPathSearch({
386 environmentId: props.environmentId,
387 cwd: composerTrigger?.kind === "path" ? props.projectCwd : null,
388 query: composerTrigger?.kind === "path" ? composerTrigger.query : null,
389 });
390​
391 const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
392 if (!composerTrigger) return [];
393​
394 if (composerTrigger.kind === "slash-command") {
395 const q = composerTrigger.query.toLowerCase();
396 const allBuiltIn = [
397 {
398 id: "cmd:model",
399 type: "slash-command" as const,
400 command: "model",
401 label: "/model",
402 description: "Switch model",
403 },
404 {
405 id: "cmd:plan",
406 type: "slash-command" as const,
407 command: "plan",
408 label: "/plan",
409 description: "Switch to plan mode",
410 },
411 {
412 id: "cmd:default",
413 type: "slash-command" as const,
414 command: "default",
415 label: "/default",
416 description: "Switch to default mode",
417 },
418 ];
419 const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
420​
421 const providerCommands: ComposerCommandItem[] = [];
422 for (const cmd of selectedProviderStatus?.slashCommands ?? []) {
423 if (!cmd.name.toLowerCase().includes(q)) continue;
424 providerCommands.push({
425 id: `pcmd:${cmd.name}`,
426 type: "provider-slash-command" as const,
427 command: cmd,
428 label: `/${cmd.name}`,
429 description: cmd.description ?? "",
430 });
431 }
432​
433 return [...builtIn, ...providerCommands];
434 }
435​
436 if (composerTrigger.kind === "skill") {
437 const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled);
438 const normalizedQuery = normalizeSearchQuery(composerTrigger.query, {
439 trimLeadingPattern: /^\$+/,
440 });
441​
442 if (!normalizedQuery) {
443 return enabledSkills.slice(0, 20).map((skill) => ({
444 id: `skill:${skill.name}`,
445 type: "skill" as const,
446 skill,
447 label: skill.displayName ?? skill.name,
448 description: skill.shortDescription ?? skill.description ?? "",
449 }));
450 }
451​
452 const ranked: Array<{
453 item: (typeof enabledSkills)[number];
454 score: number;
455 tieBreaker: string;
456 }> = [];
457 for (const skill of enabledSkills) {
458 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
459 const scores = [
460 scoreQueryMatch({
461 value: skill.name.toLowerCase(),
462 query: normalizedQuery,
463 exactBase: 0,
464 prefixBase: 2,
465 boundaryBase: 4,
466 includesBase: 6,
467 fuzzyBase: 100,
468 boundaryMarkers: ["-", "_", "/"],
469 }),
470 scoreQueryMatch({
471 value: displayLabel,
472 query: normalizedQuery,
473 exactBase: 1,
474 prefixBase: 3,
475 boundaryBase: 5,
476 includesBase: 7,
477 fuzzyBase: 110,
478 }),
479 scoreQueryMatch({
480 value: skill.shortDescription?.toLowerCase() ?? "",
481 query: normalizedQuery,
482 exactBase: 20,
483 prefixBase: 22,
484 boundaryBase: 24,
485 includesBase: 26,
486 }),
487 scoreQueryMatch({
488 value: skill.description?.toLowerCase() ?? "",
489 query: normalizedQuery,
490 exactBase: 30,
491 prefixBase: 32,
492 boundaryBase: 34,
493 includesBase: 36,
494 }),
495 ].filter((s): s is number => s !== null);
496​
497 if (scores.length > 0) {
498 insertRankedSearchResult(
499 ranked,
500 {
501 item: skill,
502 score: Math.min(...scores),
503 tieBreaker: `${displayLabel}\u0000${skill.name}`,
504 },
505 20,
506 );
507 }
508 }
509​
510 return ranked.map(({ item: skill }) => ({
511 id: `skill:${skill.name}`,
512 type: "skill" as const,
513 skill,
514 label: skill.displayName ?? skill.name,
515 description: skill.shortDescription ?? skill.description ?? "",
516 }));
517 }
518​
519 if (composerTrigger.kind === "path") {
520 return pathSearch.entries.map((entry) => {
521 const parts = entry.path.split("/");
522 return {
523 id: `path:${entry.path}`,
524 type: "path" as const,
525 path: entry.path,
526 kind: entry.kind,
527 label: parts[parts.length - 1] ?? entry.path,
528 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
529 };
530 });
531 }
532​
533 return [];
534 }, [composerTrigger, pathSearch.entries, selectedProviderStatus]);
535​
536 // ── Handle command selection ──────────────────────────────
537 const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
538​
539 const handleSend = useCallback(async () => {
540 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
541 if (inFlightThreadIdsRef.current.has(threadKey)) return;
542 inFlightThreadIdsRef.current.add(threadKey);
543 try {
544 await onSendMessage();
545 // Sending a prompt starts agent work: arm the lock-screen card while the
546 // app is foregrounded and the activity token can be registered. Armed
547 // after the send so its preference read and native Activity start don't
548 // contend with the queued-message feedback on the tap frame.
549 armAgentAwarenessLiveActivityForLocalWork({
550 environmentId: props.environmentId,
551 threadTitle: props.selectedThread.title,
552 projectTitle: props.environmentLabel ?? "T3 Code",
553 });
554 } finally {
555 inFlightThreadIdsRef.current.delete(threadKey);
556 }
557 }, [
558 onSendMessage,
559 props.environmentId,
560 props.environmentLabel,
561 props.selectedThread.id,
562 props.selectedThread.title,
563 ]);
564 const handleCommandSelect = useCallback(
565 (item: ComposerCommandItem) => {
566 if (!composerTrigger) return;
567​
568 if (
569 item.type === "slash-command" &&
570 (item.command === "plan" || item.command === "default")
571 ) {
572 const result = replaceTextRange(
573 draftMessage,
574 composerTrigger.rangeStart,
575 composerTrigger.rangeEnd,
576 "",
577 );
578 setComposerSelection({ start: result.cursor, end: result.cursor });
579 onChangeDraftMessage(result.text);
580 onUpdateInteractionMode(item.command);
581 return;
582 }
583​
584 let replacement = "";
585 if (item.type === "path") {
586 replacement = `${serializeComposerFileLink(item.path)} `;
587 } else if (item.type === "skill") {
588 replacement = `$${item.skill.name} `;
589 } else if (item.type === "slash-command") {
590 replacement = `/${item.command} `;
591 } else if (item.type === "provider-slash-command") {
592 replacement = `/${item.command.name} `;
593 }
594​
595 const result = replaceTextRange(
596 draftMessage,
597 composerTrigger.rangeStart,
598 composerTrigger.rangeEnd,
599 replacement,
600 );
601 setComposerSelection({ start: result.cursor, end: result.cursor });
602 onChangeDraftMessage(result.text);
603 },
604 [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
605 );
606​
607 // ── Model menu ───────────────────────────────────────────
608 const modelOptions = useMemo(
609 () => buildModelOptions(props.serverConfig, currentModelSelection),
610 [props.serverConfig, currentModelSelection],
611 );
612 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
613 // An existing thread is bound to its harness: sessions can't move between
614 // provider instances, so the picker only offers the thread's own group.
615 const threadProviderGroups = useMemo(
616 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
617 [providerGroups, currentModelSelection.instanceId],
618 );
619 const currentModelOption =
620 modelOptions.find(
621 (option) =>
622 option.selection.instanceId === currentModelSelection.instanceId &&
623 option.selection.model === currentModelSelection.model,
624 ) ?? null;
625 const providerOptionDescriptors = useMemo(
626 () =>
627 resolveProviderOptionDescriptors({
628 capabilities: currentModelOption?.capabilities,
629 selections: currentModelSelection.options,
630 }),
631 [currentModelOption?.capabilities, currentModelSelection.options],
632 );
633 const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
634 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
635 () => ({
636 ownerId: settingsOwnerId,
637 providerGroups: threadProviderGroups,
638 selectedModel: currentModelSelection,
639 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
640 optionDescriptors: providerOptionDescriptors,
641 onUpdateOptionSelections: (options) =>
642 props.onUpdateModelSelection({ ...currentModelSelection, options }),
643 runtimeMode: currentRuntimeMode,
644 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
645 }),
646 [
647 currentModelSelection,
648 currentRuntimeMode,
649 props.onUpdateModelSelection,
650 props.onUpdateRuntimeMode,
651 providerOptionDescriptors,
652 settingsOwnerId,
653 threadProviderGroups,
654 ],
655 );
656 const openSettings = useCallback(() => {
657 settingsRoutePresentation.present(settingsRouteSession);
658 settingsSheetPresentation.open();
659 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
660​
661 useEffect(() => {
662 if (settingsSheetPresentation.isActive) {
663 settingsRoutePresentation.present(settingsRouteSession);
664 }
665 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
666​
667 useEffect(() => {
668 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
669 return;
670 }
671​
672 settingsRoutePresentedRef.current = true;
673 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
674 }, [navigation, settingsSheetPresentation.isVisible]);
675​
676 useFocusEffect(
677 useCallback(() => {
678 if (!settingsRoutePresentedRef.current) {
679 return;
680 }
681​
682 settingsRoutePresentedRef.current = false;
683 settingsSheetPresentation.onDismissed();
684 settingsRoutePresentation.clear(settingsOwnerId);
685 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
686 );
687​
688 useEffect(
689 () =>
690 // UIKit's completion callback for the sheet dismissal, surfaced by the
691 // native-stack patch. This is when the queued keyboard restore runs.
692 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
693 "finishTransitioning",
694 settingsSheetPresentation.onStackTransitionsFinished,
695 ),
696 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
697 );
698​
699 return (
700 <Animated.View
701 className="px-4"
702 layout={COMPOSER_LAYOUT_TRANSITION}
703 style={{
704 paddingTop: isExpanded ? 8 : 6,
705 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
706 }}
707 >
708 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
709 silently drops experimental_backgroundImage on Android, which left this
710 strip fully transparent and the feed text legible through the composer. */}
711 <View
712 pointerEvents="none"
713 style={[
714 StyleSheet.absoluteFill,
715 {
716 experimental_backgroundImage: backdropGradient,
717 },
718 ]}
719 />
720 <Animated.View
721 className="relative w-full self-center"
722 layout={COMPOSER_LAYOUT_TRANSITION}
723 style={{ maxWidth: props.contentMaxWidth }}
724 >
725 {composerTrigger && composerMenuItems.length > 0 ? (
726 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
727 <ComposerCommandPopover
728 items={composerMenuItems}
729 triggerKind={composerTrigger.kind}
730 isLoading={pathSearch.isPending}
731 onSelect={handleCommandSelect}
732 />
733 </View>
734 ) : null}
735​
736 {connectionStatus ? (
737 <ComposerConnectionStatusPill
738 status={connectionStatus}
739 onPress={props.onReconnectEnvironment}
740 />
741 ) : null}
742​
743 <ComposerSurface
744 isDarkMode={isDarkMode}
745 style={
746 isExpanded
747 ? {
748 borderRadius: 26,
749 minHeight: 140,
750 overflow: "hidden" as const,
751 paddingBottom: 6,
752 paddingHorizontal: 14,
753 paddingTop: 14,
754 }
755 : {
756 borderRadius: 999,
757 overflow: "hidden" as const,
758 flexDirection: "row" as const,
759 alignItems: "center" as const,
760 paddingLeft: 18,
761 paddingRight: 5,
762 paddingVertical: 5,
763 }
764 }
765 >
766 {/* Attachment strip — inside the card, above the text input */}
767 {isExpanded ? (
768 <Animated.View
769 className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
770 entering={FadeIn.duration(160)}
771 exiting={FadeOut.duration(120)}
772 >
773 <ComposerAttachmentStrip
774 attachments={props.draftAttachments}
775 onRemove={props.onRemoveDraftImage}
776 onPressImage={onPressImage}
777 />
778 </Animated.View>
779 ) : null}
780​
781 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>
782 <ComposerEditor
783 ref={inputRef}
784 multiline
785 value={props.draftMessage}
786 skills={selectedProviderStatus?.skills ?? []}
787 selection={composerSelection}
788 onChangeText={props.onChangeDraftMessage}
789 onSelectionChange={handleSelectionChange}
790 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
791 placeholder={props.placeholder}
792 onFocus={handleFocus}
793 onBlur={handleBlur}
794 onSubmit={handleSend}
795 scrollEnabled={isExpanded}
796 // Android: collapsed single line centers natively (gravity) in
797 // a pill-height box matching the send button; iOS keeps insets.
798 singleLineCentered={!isExpanded}
799 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
800 style={
801 isExpanded
802 ? {
803 minHeight: 72,
804 maxHeight: 160,
805 paddingHorizontal: 4,
806 paddingVertical: 4,
807 }
808 : {
809 height: 36,
810 }
811 }
812 textStyle={{
813 ...bodyText,
814 color: foregroundColor,
815 }}
816 />
817 </View>
818 {!isExpanded && props.draftAttachments.length > 0 ? (
819 <View className="flex-row gap-1 pl-1">
820 {props.draftAttachments.slice(0, 3).map((image) => (
821 <Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
822 <Image
823 source={{ uri: image.previewUri }}
824 className="size-[30px] rounded-lg bg-subtle"
825 resizeMode="cover"
826 />
827 </Pressable>
828 ))}
829 {props.draftAttachments.length > 3 ? (
830 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
831 <Text className="text-foreground-muted text-2xs font-t3-bold">
832 +{props.draftAttachments.length - 3}
833 </Text>
834 </View>
835 ) : null}
836 </View>
837 ) : null}
838 {!isExpanded ? (
839 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
840 {showStopAction ? (
841 <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
842 ) : (
843 <ControlPill
844 icon="arrow.up"
845 variant="primary"
846 disabled={!canSend}
847 onPress={handleSend}
848 />
849 )}
850 </Animated.View>
851 ) : null}
852 {isExpanded ? (
853 <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
854 <ComposerToolbarScroller
855 fadeOpaque={toolbarFadeOpaque}
856 fadeTransparent={toolbarFadeTransparent}
857 contentPaddingRight={8}
858 >
859 <ComposerToolbarButton
860 accessibilityLabel="Add attachment"
861 icon="plus"
862 onPress={() => void props.onPickDraftImages()}
863 showChevron={false}
864 />
865 <ComposerInlineControl
866 accessibilityLabel="Model and reasoning settings"
867 emphasized
868 iconNode={
869 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
870 }
871 label={currentModelOption?.label ?? currentModelSelection.model}
872 maxWidth={152}
873 onPress={openSettings}
874 />
875 {showStopAction ? (
876 <ComposerToolbarButton
877 accessibilityLabel="Stop"
878 icon="stop.fill"
879 variant="danger"
880 onPress={props.onStopThread}
881 showChevron={false}
882 />
883 ) : null}
884 </ComposerToolbarScroller>
885 <ComposerToolbarButton
886 accessibilityLabel={sendLabel}
887 icon="arrow.up"
888 variant="primary"
889 disabled={!canSend}
890 onPress={handleSend}
891 showChevron={false}
892 />
893 </ComposerToolbarRow>
894 ) : null}
895 </ComposerSurface>
896​
897 {/* Queue count */}
898 {props.queueCount > 0 ? (
899 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
900 <Text className="pt-2 text-xs text-foreground-muted">
901 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
902 automatically.
903 </Text>
904 </Animated.View>
905 ) : null}
906 </Animated.View>
907​
908 <ImageViewing
909 images={previewImageUri ? [{ uri: previewImageUri }] : []}
910 imageIndex={0}
911 visible={previewImageUri !== null}
912 onRequestClose={closePreview}
913 swipeToCloseEnabled
914 doubleTapToZoomEnabled
915 />
916 </Animated.View>
917 );
918});