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

ThreadComposer.tsx

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