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

ThreadComposer.tsx

854 lines29.4 KB

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