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

ThreadComposer.tsx

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