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

ThreadComposer.tsx

940 lines33.9 KB

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