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

ThreadComposer.tsx

929 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 await onSendMessage();
556 // Sending a prompt starts agent work: arm the lock-screen card while the
557 // app is foregrounded and the activity token can be registered. Armed
558 // after the send so its preference read and native Activity start don't
559 // contend with the queued-message feedback on the tap frame.
560 armAgentAwarenessLiveActivityForLocalWork({
561 environmentId: props.environmentId,
562 threadTitle: props.selectedThread.title,
563 projectTitle: props.environmentLabel ?? "T3 Code",
564 });
565 } finally {
566 inFlightThreadIdsRef.current.delete(threadKey);
567 }
568 }, [
569 onSendMessage,
570 props.environmentId,
571 props.environmentLabel,
572 props.selectedThread.id,
573 props.selectedThread.title,
574 ]);
575 const handleCommandSelect = useCallback(
576 (item: ComposerCommandItem) => {
577 if (!composerTrigger) return;
578​
579 if (
580 item.type === "slash-command" &&
581 (item.command === "plan" || item.command === "default")
582 ) {
583 const result = replaceTextRange(
584 draftMessage,
585 composerTrigger.rangeStart,
586 composerTrigger.rangeEnd,
587 "",
588 );
589 setComposerSelection({ start: result.cursor, end: result.cursor });
590 onChangeDraftMessage(result.text);
591 onUpdateInteractionMode(item.command);
592 return;
593 }
594​
595 let replacement = "";
596 if (item.type === "path") {
597 replacement = `${serializeComposerFileLink(item.path)} `;
598 } else if (item.type === "skill") {
599 replacement = `$${item.skill.name} `;
600 } else if (item.type === "slash-command") {
601 replacement = `/${item.command} `;
602 } else if (item.type === "provider-slash-command") {
603 replacement = `/${item.command.name} `;
604 }
605​
606 const result = replaceTextRange(
607 draftMessage,
608 composerTrigger.rangeStart,
609 composerTrigger.rangeEnd,
610 replacement,
611 );
612 setComposerSelection({ start: result.cursor, end: result.cursor });
613 onChangeDraftMessage(result.text);
614 },
615 [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
616 );
617​
618 // ── Model menu ───────────────────────────────────────────
619 const modelOptions = useMemo(
620 () => buildModelOptions(props.serverConfig, currentModelSelection),
621 [props.serverConfig, currentModelSelection],
622 );
623 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
624 // An existing thread is bound to its harness: sessions can't move between
625 // provider instances, so the picker only offers the thread's own group.
626 const threadProviderGroups = useMemo(
627 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
628 [providerGroups, currentModelSelection.instanceId],
629 );
630 const currentModelOption =
631 modelOptions.find(
632 (option) =>
633 option.selection.instanceId === currentModelSelection.instanceId &&
634 option.selection.model === currentModelSelection.model,
635 ) ?? null;
636 const providerOptionDescriptors = useMemo(
637 () =>
638 resolveProviderOptionDescriptors({
639 capabilities: currentModelOption?.capabilities,
640 selections: currentModelSelection.options,
641 }),
642 [currentModelOption?.capabilities, currentModelSelection.options],
643 );
644 const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
645 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
646 () => ({
647 ownerId: settingsOwnerId,
648 providerGroups: threadProviderGroups,
649 selectedModel: currentModelSelection,
650 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
651 optionDescriptors: providerOptionDescriptors,
652 onUpdateOptionSelections: (options) =>
653 props.onUpdateModelSelection({ ...currentModelSelection, options }),
654 runtimeMode: currentRuntimeMode,
655 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
656 }),
657 [
658 currentModelSelection,
659 currentRuntimeMode,
660 props.onUpdateModelSelection,
661 props.onUpdateRuntimeMode,
662 providerOptionDescriptors,
663 settingsOwnerId,
664 threadProviderGroups,
665 ],
666 );
667 const openSettings = useCallback(() => {
668 settingsRoutePresentation.present(settingsRouteSession);
669 settingsSheetPresentation.open();
670 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
671​
672 useEffect(() => {
673 if (settingsSheetPresentation.isActive) {
674 settingsRoutePresentation.present(settingsRouteSession);
675 }
676 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
677​
678 useEffect(() => {
679 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
680 return;
681 }
682​
683 settingsRoutePresentedRef.current = true;
684 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
685 }, [navigation, settingsSheetPresentation.isVisible]);
686​
687 useFocusEffect(
688 useCallback(() => {
689 if (!settingsRoutePresentedRef.current) {
690 return;
691 }
692​
693 settingsRoutePresentedRef.current = false;
694 settingsSheetPresentation.onDismissed();
695 settingsRoutePresentation.clear(settingsOwnerId);
696 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
697 );
698​
699 useEffect(
700 () =>
701 // UIKit's completion callback for the sheet dismissal, surfaced by the
702 // native-stack patch. This is when the queued keyboard restore runs.
703 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
704 "finishTransitioning",
705 settingsSheetPresentation.onStackTransitionsFinished,
706 ),
707 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
708 );
709​
710 return (
711 <Animated.View
712 className="px-4"
713 layout={COMPOSER_LAYOUT_TRANSITION}
714 style={{
715 paddingTop: isExpanded ? 8 : 6,
716 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
717 }}
718 >
719 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
720 silently drops experimental_backgroundImage on Android, which left this
721 strip fully transparent and the feed text legible through the composer. */}
722 <View
723 pointerEvents="none"
724 style={[
725 StyleSheet.absoluteFill,
726 {
727 experimental_backgroundImage: backdropGradient,
728 },
729 ]}
730 />
731 <Animated.View
732 className="relative w-full self-center"
733 layout={COMPOSER_LAYOUT_TRANSITION}
734 style={{ maxWidth: props.contentMaxWidth }}
735 >
736 {composerTrigger && composerMenuItems.length > 0 ? (
737 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
738 <ComposerCommandPopover
739 items={composerMenuItems}
740 triggerKind={composerTrigger.kind}
741 isLoading={pathSearch.isPending}
742 onSelect={handleCommandSelect}
743 />
744 </View>
745 ) : null}
746​
747 {connectionStatus ? (
748 <ComposerConnectionStatusPill
749 status={connectionStatus}
750 onPress={props.onReconnectEnvironment}
751 />
752 ) : null}
753​
754 <ComposerSurface
755 isDarkMode={isDarkMode}
756 style={
757 isExpanded
758 ? {
759 borderRadius: 26,
760 minHeight: 140,
761 overflow: "hidden" as const,
762 paddingBottom: 6,
763 paddingHorizontal: 14,
764 paddingTop: 14,
765 }
766 : {
767 borderRadius: 999,
768 overflow: "hidden" as const,
769 flexDirection: "row" as const,
770 alignItems: "center" as const,
771 paddingLeft: 18,
772 paddingRight: 5,
773 paddingVertical: 5,
774 }
775 }
776 >
777 {/* Attachment strip — inside the card, above the text input */}
778 {isExpanded ? (
779 <Animated.View
780 className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
781 entering={FadeIn.duration(160)}
782 exiting={FadeOut.duration(120)}
783 >
784 <ComposerAttachmentStrip
785 attachments={props.draftAttachments}
786 onRemove={props.onRemoveDraftImage}
787 onPressImage={onPressImage}
788 />
789 </Animated.View>
790 ) : null}
791​
792 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>
793 <ComposerEditor
794 ref={inputRef}
795 multiline
796 value={props.draftMessage}
797 skills={selectedProviderStatus?.skills ?? []}
798 selection={composerSelection}
799 onChangeText={props.onChangeDraftMessage}
800 onSelectionChange={handleSelectionChange}
801 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
802 placeholder={props.placeholder}
803 onFocus={handleFocus}
804 onBlur={handleBlur}
805 onSubmit={handleSend}
806 scrollEnabled={isExpanded}
807 // Android: collapsed single line centers natively (gravity) in
808 // a pill-height box matching the send button; iOS keeps insets.
809 singleLineCentered={!isExpanded}
810 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
811 style={
812 isExpanded
813 ? {
814 minHeight: 72,
815 maxHeight: 160,
816 paddingHorizontal: 4,
817 paddingVertical: 4,
818 }
819 : {
820 height: 36,
821 }
822 }
823 textStyle={{
824 ...bodyText,
825 color: foregroundColor,
826 }}
827 />
828 </View>
829 {!isExpanded && props.draftAttachments.length > 0 ? (
830 <View className="flex-row gap-1 pl-1">
831 {props.draftAttachments.slice(0, 3).map((image) => (
832 <Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
833 <Image
834 source={{ uri: image.previewUri }}
835 className="size-[30px] rounded-lg bg-subtle"
836 resizeMode="cover"
837 />
838 </Pressable>
839 ))}
840 {props.draftAttachments.length > 3 ? (
841 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
842 <Text className="text-foreground-muted text-2xs font-t3-bold">
843 +{props.draftAttachments.length - 3}
844 </Text>
845 </View>
846 ) : null}
847 </View>
848 ) : null}
849 {!isExpanded ? (
850 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
851 {showStopAction ? (
852 <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
853 ) : (
854 <ControlPill
855 icon="arrow.up"
856 variant="primary"
857 disabled={!canSend}
858 onPress={handleSend}
859 />
860 )}
861 </Animated.View>
862 ) : null}
863 {isExpanded ? (
864 <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
865 <ComposerToolbarScroller
866 fadeOpaque={toolbarFadeOpaque}
867 fadeTransparent={toolbarFadeTransparent}
868 contentPaddingRight={8}
869 >
870 <ComposerToolbarButton
871 accessibilityLabel="Add attachment"
872 icon="plus"
873 onPress={() => void props.onPickDraftImages()}
874 showChevron={false}
875 />
876 <ComposerInlineControl
877 accessibilityLabel="Model and reasoning settings"
878 emphasized
879 iconNode={
880 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
881 }
882 label={currentModelOption?.label ?? currentModelSelection.model}
883 maxWidth={152}
884 onPress={openSettings}
885 />
886 {showStopAction ? (
887 <ComposerToolbarButton
888 accessibilityLabel="Stop"
889 icon="stop.fill"
890 variant="danger"
891 onPress={props.onStopThread}
892 showChevron={false}
893 />
894 ) : null}
895 </ComposerToolbarScroller>
896 <ComposerToolbarButton
897 accessibilityLabel={sendLabel}
898 icon="arrow.up"
899 variant="primary"
900 disabled={!canSend}
901 onPress={handleSend}
902 showChevron={false}
903 />
904 </ComposerToolbarRow>
905 ) : null}
906 </ComposerSurface>
907​
908 {/* Queue count */}
909 {props.queueCount > 0 ? (
910 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
911 <Text className="pt-2 text-xs text-foreground-muted">
912 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
913 automatically.
914 </Text>
915 </Animated.View>
916 ) : null}
917 </Animated.View>
918​
919 <ImageViewing
920 images={previewImageUri ? [{ uri: previewImageUri }] : []}
921 imageIndex={0}
922 visible={previewImageUri !== null}
923 onRequestClose={closePreview}
924 swipeToCloseEnabled
925 doubleTapToZoomEnabled
926 />
927 </Animated.View>
928 );
929});