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

ThreadComposer.tsx

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