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