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

ThreadComposer.tsx

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