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