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