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

ThreadComposer.tsx

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