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

ThreadComposer.tsx

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