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

ThreadComposer.tsx

933 lines33.2 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, {
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;
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 );
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 }
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 // Sending a prompt starts agent work: arm the lock-screen card now, while
522 // the app is foregrounded and the activity token can be registered.
523 armAgentAwarenessLiveActivityForLocalWork({
524 threadTitle: props.selectedThread.title,
525 projectTitle: props.environmentLabel ?? "T3 Code",
526 });
527 try {
528 await onSendMessage();
529 } finally {
530 inFlightThreadIdsRef.current.delete(threadKey);
531 }
532 }, [
533 onSendMessage,
534 props.environmentId,
535 props.environmentLabel,
536 props.selectedThread.id,
537 props.selectedThread.title,
538 ]);
539 const handleCommandSelect = useCallback(
540 (item: ComposerCommandItem) => {
541 if (!composerTrigger) return;
542​
543 if (
544 item.type === "slash-command" &&
545 (item.command === "plan" || item.command === "default")
546 ) {
547 const result = replaceTextRange(
548 draftMessage,
549 composerTrigger.rangeStart,
550 composerTrigger.rangeEnd,
551 "",
552 );
553 setComposerSelection({ start: result.cursor, end: result.cursor });
554 onChangeDraftMessage(result.text);
555 onUpdateInteractionMode(item.command);
556 return;
557 }
558​
559 let replacement = "";
560 if (item.type === "path") {
561 replacement = `${serializeComposerFileLink(item.path)} `;
562 } else if (item.type === "skill") {
563 replacement = `$${item.skill.name} `;
564 } else if (item.type === "slash-command") {
565 replacement = `/${item.command} `;
566 } else if (item.type === "provider-slash-command") {
567 replacement = `/${item.command.name} `;
568 }
569​
570 const result = replaceTextRange(
571 draftMessage,
572 composerTrigger.rangeStart,
573 composerTrigger.rangeEnd,
574 replacement,
575 );
576 setComposerSelection({ start: result.cursor, end: result.cursor });
577 onChangeDraftMessage(result.text);
578 },
579 [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
580 );
581​
582 // ── Model menu ───────────────────────────────────────────
583 const modelOptions = useMemo(
584 () => buildModelOptions(props.serverConfig, currentModelSelection),
585 [props.serverConfig, currentModelSelection],
586 );
587 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
588 const currentModelOption =
589 modelOptions.find(
590 (option) =>
591 option.selection.instanceId === currentModelSelection.instanceId &&
592 option.selection.model === currentModelSelection.model,
593 ) ?? null;
594 const providerOptionDescriptors = useMemo(
595 () =>
596 resolveProviderOptionDescriptors({
597 capabilities: currentModelOption?.capabilities,
598 selections: currentModelSelection.options,
599 }),
600 [currentModelOption?.capabilities, currentModelSelection.options],
601 );
602 const configurationLabel = useMemo(
603 () => providerOptionsConfigurationLabel(providerOptionDescriptors),
604 [providerOptionDescriptors],
605 );
606 const modelMenuActions = useMemo(
607 () =>
608 providerGroups.map((group) => ({
609 id: `provider:${group.providerKey}`,
610 title: group.providerLabel,
611 subtitle: group.models.find(
612 (model) =>
613 model.selection.instanceId === currentModelSelection.instanceId &&
614 model.selection.model === currentModelSelection.model,
615 )?.label,
616 subactions: group.models.map((option) => ({
617 id: `model:${option.key}`,
618 title: option.label,
619 state:
620 option.selection.instanceId === currentModelSelection.instanceId &&
621 option.selection.model === currentModelSelection.model
622 ? ("on" as const)
623 : undefined,
624 })),
625 })),
626 [providerGroups, currentModelSelection],
627 );
628​
629 // ── Options menu ─────────────────────────────────────────
630 const optionsMenuActions = useMemo(
631 () => [
632 ...buildProviderOptionMenuActions(providerOptionDescriptors),
633 {
634 id: "options-runtime",
635 title: "Runtime",
636 subtitle:
637 currentRuntimeMode === "approval-required"
638 ? "Approve actions"
639 : currentRuntimeMode === "auto-accept-edits"
640 ? "Auto-accept edits"
641 : currentRuntimeMode === "auto"
642 ? "Auto"
643 : "Full access",
644 subactions: [
645 { id: "options:runtime:approval-required", title: "Approve actions" },
646 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
647 { id: "options:runtime:auto", title: "Auto" },
648 { id: "options:runtime:full-access", title: "Full access" },
649 ].map((option) => {
650 const value = option.id.replace("options:runtime:", "");
651 return {
652 id: option.id,
653 title: option.title,
654 state: currentRuntimeMode === value ? ("on" as const) : undefined,
655 };
656 }),
657 },
658 {
659 id: "options-interaction",
660 title: "Interaction",
661 subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
662 subactions: [
663 { id: "options:interaction:default", title: "Default" },
664 { id: "options:interaction:plan", title: "Plan" },
665 ].map((option) => {
666 const value = option.id.replace("options:interaction:", "");
667 return {
668 id: option.id,
669 title: option.title,
670 state: currentInteractionMode === value ? ("on" as const) : undefined,
671 };
672 }),
673 },
674 ],
675 [currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
676 );
677​
678 // ── Menu handlers ────────────────────────────────────────
679 function handleModelMenuAction(event: string) {
680 if (!event.startsWith("model:")) {
681 return;
682 }
683 const modelKey = event.slice("model:".length);
684 const option = modelOptions.find((o) => o.key === modelKey);
685 if (option) {
686 props.onUpdateModelSelection(option.selection);
687 }
688 }
689​
690 function handleOptionsMenuAction(event: string) {
691 const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
692 if (providerOptions) {
693 props.onUpdateModelSelection({
694 ...currentModelSelection,
695 options: providerOptions,
696 });
697 return;
698 }
699 if (event.startsWith("options:runtime:")) {
700 const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
701 props.onUpdateRuntimeMode(runtimeMode);
702 return;
703 }
704 if (event.startsWith("options:interaction:")) {
705 const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
706 props.onUpdateInteractionMode(interactionMode);
707 }
708 }
709​
710 return (
711 <Animated.View
712 className="px-4"
713 layout={COMPOSER_LAYOUT_TRANSITION}
714 style={{
715 paddingTop: isExpanded ? 8 : 6,
716 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
717 experimental_backgroundImage: isDarkMode
718 ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
719 : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
720 }}
721 >
722 <Animated.View
723 className="relative w-full self-center"
724 layout={COMPOSER_LAYOUT_TRANSITION}
725 style={{ maxWidth: props.contentMaxWidth }}
726 >
727 {composerTrigger && composerMenuItems.length > 0 ? (
728 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
729 <ComposerCommandPopover
730 items={composerMenuItems}
731 triggerKind={composerTrigger.kind}
732 isLoading={pathSearch.isPending}
733 onSelect={handleCommandSelect}
734 />
735 </View>
736 ) : null}
737​
738 {connectionStatus ? (
739 <ComposerConnectionStatusPill
740 status={connectionStatus}
741 onPress={props.onReconnectEnvironment}
742 />
743 ) : null}
744​
745 <ComposerSurface
746 isDarkMode={isDarkMode}
747 style={
748 isExpanded
749 ? {
750 borderRadius: 20,
751 overflow: "hidden" as const,
752 paddingHorizontal: 14,
753 paddingVertical: 12,
754 }
755 : {
756 borderRadius: 999,
757 overflow: "hidden" as const,
758 flexDirection: "row" as const,
759 alignItems: "center" as const,
760 paddingLeft: 18,
761 paddingRight: 5,
762 paddingVertical: 5,
763 }
764 }
765 >
766 {/* Attachment strip — inside the card, above the text input */}
767 {isExpanded ? (
768 <Animated.View
769 className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
770 entering={FadeIn.duration(160)}
771 exiting={FadeOut.duration(120)}
772 >
773 <ComposerAttachmentStrip
774 attachments={props.draftAttachments}
775 onRemove={props.onRemoveDraftImage}
776 onPressImage={onPressImage}
777 />
778 </Animated.View>
779 ) : null}
780​
781 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>
782 <ComposerEditor
783 ref={inputRef}
784 multiline
785 value={props.draftMessage}
786 skills={selectedProviderStatus?.skills ?? []}
787 selection={composerSelection}
788 onChangeText={props.onChangeDraftMessage}
789 onSelectionChange={handleSelectionChange}
790 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
791 placeholder={props.placeholder}
792 onFocus={handleFocus}
793 onBlur={handleBlur}
794 onSubmit={handleSend}
795 scrollEnabled={isExpanded}
796 // Android: collapsed single line centers natively (gravity) in
797 // a pill-height box matching the send button; iOS keeps insets.
798 singleLineCentered={!isExpanded}
799 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
800 style={
801 isExpanded
802 ? {
803 minHeight: 80,
804 maxHeight: 160,
805 paddingHorizontal: 4,
806 paddingVertical: 4,
807 }
808 : {
809 height: 36,
810 }
811 }
812 textStyle={{
813 ...bodyText,
814 color: foregroundColor,
815 }}
816 />
817 </View>
818 {!isExpanded && props.draftAttachments.length > 0 ? (
819 <View className="flex-row gap-1 pl-1">
820 {props.draftAttachments.slice(0, 3).map((image) => (
821 <Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
822 <Image
823 source={{ uri: image.previewUri }}
824 className="size-[30px] rounded-lg bg-subtle"
825 resizeMode="cover"
826 />
827 </Pressable>
828 ))}
829 {props.draftAttachments.length > 3 ? (
830 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
831 <Text className="text-foreground-muted text-2xs font-t3-bold">
832 +{props.draftAttachments.length - 3}
833 </Text>
834 </View>
835 ) : null}
836 </View>
837 ) : null}
838 {!isExpanded ? (
839 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
840 {showStopAction ? (
841 <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
842 ) : (
843 <ControlPill
844 icon="arrow.up"
845 variant="primary"
846 disabled={!canSend}
847 onPress={handleSend}
848 />
849 )}
850 </Animated.View>
851 ) : null}
852 </ComposerSurface>
853​
854 {isExpanded ? (
855 // Toolbar row — matches draft page layout (expanded only)
856 <Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
857 <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
858 <ComposerToolbarScroller
859 fadeOpaque={toolbarFadeOpaque}
860 fadeTransparent={toolbarFadeTransparent}
861 >
862 <ComposerToolbarButton
863 accessibilityLabel="Add attachment"
864 icon="plus"
865 onPress={() => void props.onPickDraftImages()}
866 showChevron={false}
867 />
868 <ControlPillMenu
869 actions={modelMenuActions}
870 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
871 >
872 <ComposerToolbarTrigger
873 accessibilityLabel="Model"
874 iconNode={
875 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
876 }
877 label={currentModelOption?.label ?? currentModelSelection.model}
878 />
879 </ControlPillMenu>
880 <ControlPillMenu
881 actions={optionsMenuActions}
882 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
883 >
884 <ComposerToolbarTrigger
885 accessibilityLabel="Configuration"
886 icon="slider.horizontal.3"
887 label={configurationLabel}
888 />
889 </ControlPillMenu>
890 {showStopAction ? (
891 <ComposerToolbarButton
892 accessibilityLabel="Stop"
893 icon="stop.fill"
894 variant="danger"
895 onPress={props.onStopThread}
896 showChevron={false}
897 />
898 ) : null}
899 </ComposerToolbarScroller>
900 <ComposerToolbarButton
901 accessibilityLabel={sendLabel}
902 icon="arrow.up"
903 variant="primary"
904 disabled={!canSend}
905 onPress={handleSend}
906 showChevron={false}
907 />
908 </ComposerToolbarRow>
909 </Animated.View>
910 ) : null}
911​
912 {/* Queue count */}
913 {props.queueCount > 0 ? (
914 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
915 <Text className="pt-2 text-xs text-foreground-muted">
916 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
917 automatically.
918 </Text>
919 </Animated.View>
920 ) : null}
921 </Animated.View>
922​
923 <ImageViewing
924 images={previewImageUri ? [{ uri: previewImageUri }] : []}
925 imageIndex={0}
926 visible={previewImageUri !== null}
927 onRequestClose={closePreview}
928 swipeToCloseEnabled
929 doubleTapToZoomEnabled
930 />
931 </Animated.View>
932 );
933});