-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathChatComposerBar.tsx
More file actions
1175 lines (1110 loc) · 49.2 KB
/
Copy pathChatComposerBar.tsx
File metadata and controls
1175 lines (1110 loc) · 49.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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Tooltip } from "@base-ui/react";
import {
type MutableRefObject,
memo,
type ReactNode,
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { ComposerAttachmentCard } from "../../components/chat/ComposerAttachmentCard";
import { getUploadedFileTypeIcon } from "../../components/chat/fileTypeIcons";
import {
MentionComposer,
type MentionComposerHandle,
type MentionComposerSkill,
} from "../../components/chat/MentionComposer";
import { GitBranchSelector } from "../../components/git/GitBranchSelector";
import {
ChevronDown,
ChevronUp,
Clock3,
Globe,
GlobeOff,
Lightbulb,
LightbulbOff,
Loader2,
Maximize2,
Minimize2,
Paperclip,
Play,
Send,
Sparkle,
Square,
SquarePen,
Trash2,
} from "../../components/icons";
import { Button } from "../../components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "../../components/ui/select";
import { useLocale } from "../../i18n";
import type { PendingUploadedFile } from "../../lib/chat/uploadedFiles";
import {
getUploadedImagePreviewCacheKey,
loadUploadedImagePreview,
readUploadedImagePreviewCache,
type UploadedImagePreviewLoader,
} from "../../lib/chat/uploadedImagePreview";
import type { GitClient } from "../../lib/git/types";
import {
type ChatRuntimeControls,
DEFAULT_CHAT_RUNTIME_CONTROLS,
type ReasoningLevel,
} from "../../lib/settings";
import { cn } from "../../lib/shared/utils";
import type { WorkspaceActivityClient } from "../../lib/workspace-activity/types";
const REASONING_I18N_KEYS: Record<ReasoningLevel, string> = {
off: "settings.reasoning.off",
minimal: "settings.reasoning.minimal",
low: "settings.reasoning.low",
medium: "settings.reasoning.medium",
high: "settings.reasoning.high",
xhigh: "settings.reasoning.xhigh",
max: "settings.reasoning.max",
};
function isReasoningLevel(value: unknown): value is ReasoningLevel {
return typeof value === "string" && Object.hasOwn(REASONING_I18N_KEYS, value);
}
function RuntimeControlTooltip(props: { label: string; children: ReactNode }) {
return (
<Tooltip.Root>
<Tooltip.Trigger
delay={0}
closeOnClick
render={<span className="inline-flex shrink-0">{props.children}</span>}
/>
<Tooltip.Portal>
<Tooltip.Positioner
side="top"
align="center"
sideOffset={6}
collisionPadding={8}
className="z-[9999]"
>
<Tooltip.Popup className="max-w-64 rounded-xl border border-border/60 bg-popover px-3 py-2 text-xs font-medium leading-4 text-popover-foreground shadow-lg outline-hidden data-[open]:animate-in data-[closed]:animate-out data-[closed]:fade-out-0 data-[open]:fade-in-0 data-[closed]:zoom-out-95 data-[open]:zoom-in-95">
{props.label}
</Tooltip.Popup>
</Tooltip.Positioner>
</Tooltip.Portal>
</Tooltip.Root>
);
}
function ContextUsageRing(props: {
totalTokens?: number;
contextWindow?: number;
locale: string;
totalLabel: string;
contextWindowLabel: string;
}) {
const { totalTokens, contextWindow, locale, totalLabel, contextWindowLabel } = props;
if (typeof contextWindow !== "number" || !Number.isFinite(contextWindow) || contextWindow <= 0) {
return null;
}
const normalizedTokens =
typeof totalTokens === "number" && Number.isFinite(totalTokens) && totalTokens > 0
? Math.floor(totalTokens)
: 0;
const rawPercentage = (normalizedTokens / contextWindow) * 100;
const displayedPercentage = Math.min(999, Math.round(rawPercentage));
const ringPercentage = Math.min(100, Math.max(0, rawPercentage));
const formattedTokens = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
normalizedTokens,
);
const formattedWindow = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
contextWindow,
);
const label = `${displayedPercentage}% · ${totalLabel} ${formattedTokens} · ${contextWindowLabel} ${formattedWindow}`;
const progressClass =
rawPercentage >= 90
? "stroke-red-500 dark:stroke-red-400"
: rawPercentage >= 70
? "stroke-amber-500 dark:stroke-amber-400"
: "stroke-emerald-500 dark:stroke-emerald-400";
return (
<RuntimeControlTooltip label={label}>
<div
role="progressbar"
aria-label={label}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.min(100, displayedPercentage)}
className="relative flex h-8 w-8 shrink-0 items-center justify-center text-[calc(7px*var(--zone-font-scale,1))] font-semibold leading-none tabular-nums text-foreground/75"
>
<svg aria-hidden viewBox="0 0 24 24" className="absolute inset-0 h-8 w-8 -rotate-90">
<circle
cx="12"
cy="12"
r="9.5"
fill="none"
strokeWidth="2.25"
className="stroke-foreground/10 dark:stroke-white/10"
/>
<circle
cx="12"
cy="12"
r="9.5"
fill="none"
pathLength="100"
strokeWidth="2.25"
strokeLinecap="round"
strokeDasharray="100"
strokeDashoffset={100 - ringPercentage}
className={cn("transition-[stroke-dashoffset,stroke] duration-300", progressClass)}
/>
</svg>
<span className="relative">{displayedPercentage}%</span>
</div>
</RuntimeControlTooltip>
);
}
function useComposerUploadedImagePreview(
file: PendingUploadedFile,
workdir: string,
loader?: UploadedImagePreviewLoader,
) {
const shouldPreviewImage =
file.kind === "image" && typeof file.absolutePath === "string" && file.absolutePath.trim();
const cacheKey = shouldPreviewImage ? getUploadedImagePreviewCacheKey(workdir, file) : "";
const [imageSrc, setImageSrc] = useState<string | null | undefined>(() => {
if (!cacheKey) return null;
return readUploadedImagePreviewCache(workdir, file);
});
useEffect(() => {
if (!cacheKey) {
setImageSrc(null);
return;
}
const cached = readUploadedImagePreviewCache(workdir, file);
if (cached !== undefined) {
setImageSrc(cached);
return;
}
if (!loader) {
setImageSrc(null);
return;
}
let cancelled = false;
setImageSrc(undefined);
void loadUploadedImagePreview({ workspaceRoot: workdir, file, loader }).then((value) => {
if (!cancelled) setImageSrc(value);
});
return () => {
cancelled = true;
};
}, [cacheKey, file, loader, workdir]);
return {
imageSrc: imageSrc ?? null,
isLoading: Boolean(cacheKey && loader) && imageSrc === undefined,
};
}
function PendingComposerAttachment(props: {
file: PendingUploadedFile;
workdir: string;
disabled: boolean;
removeLabel: string;
previewLabel: string;
closePreviewLabel: string;
imagePreviewLoader?: UploadedImagePreviewLoader;
onRemove: (relativePath: string) => void;
}) {
const {
file,
workdir,
disabled,
removeLabel,
previewLabel,
closePreviewLabel,
imagePreviewLoader,
onRemove,
} = props;
const { imageSrc, isLoading } = useComposerUploadedImagePreview(
file,
workdir,
imagePreviewLoader,
);
const TypeIcon = getUploadedFileTypeIcon(file);
return (
<ComposerAttachmentCard
fileName={file.fileName}
pathTitle={file.relativePath}
imageSrc={imageSrc}
isImageLoading={isLoading}
fallbackIcon={<TypeIcon className="h-4 w-4" />}
disabled={disabled}
removeLabel={removeLabel}
previewLabel={previewLabel}
closePreviewLabel={closePreviewLabel}
onRemove={() => onRemove(file.relativePath)}
/>
);
}
export type ChatQueueTurnPreview = {
id: string;
previewText: string;
fileCount: number;
};
type QueueScrollbarState = {
visible: boolean;
thumbHeight: number;
thumbTop: number;
};
const QUEUE_SCROLLBAR_MIN_THUMB_HEIGHT = 24;
const DEFAULT_QUEUE_SCROLLBAR_STATE: QueueScrollbarState = {
visible: false,
thumbHeight: QUEUE_SCROLLBAR_MIN_THUMB_HEIGHT,
thumbTop: 0,
};
const COMPOSER_EXPAND_ANIMATION_MS = 280;
const COMPOSER_EXPAND_EASING = "cubic-bezier(0.32, 0.72, 0.22, 1)";
function prefersReducedMotion() {
return (
typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches
);
}
export const ChatComposerBar = memo(function ChatComposerBar(props: {
composerRef: MutableRefObject<MentionComposerHandle | null>;
isSending: boolean;
isUploadingFiles: boolean;
isInputDisabled: boolean;
inputPlaceholder: string;
workdir: string;
enabledSkills: MentionComposerSkill[];
isAgentMode: boolean;
chatRuntimeControls: ChatRuntimeControls;
reasoningOptions: ReasoningLevel[];
thinkingAlwaysOn: boolean;
contextUsageTokens?: number;
contextWindow?: number;
gitClient?: GitClient | null;
gitWriteEnabled?: boolean;
gitDisabledMessage?: string;
workspaceActivityClient?: WorkspaceActivityClient | null;
onSend: () => void;
onStop: () => void;
onPrepareChatRuntime?: () => void;
onComposerBusyChange: (isBusy: boolean) => void;
onChatRuntimeControlsChange: (patch: Partial<ChatRuntimeControls>) => void;
onPickReadableFiles: () => void;
onPasteFiles: (files: File[]) => void;
onLoadUploadedImagePreview?: UploadedImagePreviewLoader;
/** Prompts previously sent in this conversation for ↑/↓ recall. */
loadHistoryPrompts?: () => readonly string[];
pendingUploadedFiles: PendingUploadedFile[];
onRemovePendingUpload: (relativePath: string) => void;
queuedTurns: ChatQueueTurnPreview[];
onRunQueuedTurnNow: (id: string) => void;
onMoveQueuedTurnUp: (id: string) => void;
onEditQueuedTurn: (id: string) => void;
onRemoveQueuedTurn: (id: string) => void;
/** 输入框上方的集中审批栏(待审批时由上层注入,渲染在队列面板之上)。 */
approvalBar?: ReactNode;
}) {
const {
composerRef,
isSending,
isUploadingFiles,
isInputDisabled,
inputPlaceholder,
workdir,
enabledSkills,
isAgentMode,
chatRuntimeControls,
reasoningOptions,
thinkingAlwaysOn,
contextUsageTokens,
contextWindow,
gitClient,
gitWriteEnabled = true,
gitDisabledMessage,
workspaceActivityClient,
onSend,
onStop,
onPrepareChatRuntime,
onComposerBusyChange,
onChatRuntimeControlsChange,
onPickReadableFiles,
onPasteFiles,
onLoadUploadedImagePreview,
loadHistoryPrompts,
pendingUploadedFiles,
onRemovePendingUpload,
queuedTurns,
onRunQueuedTurnNow,
onMoveQueuedTurnUp,
onEditQueuedTurn,
onRemoveQueuedTurn,
approvalBar,
} = props;
const { t, locale } = useLocale();
const [composerIsEmpty, setComposerIsEmpty] = useState(true);
const [isComposerExpanded, setIsComposerExpanded] = useState(false);
const isComposerExpandedRef = useRef(false);
const glassCardRef = useRef<HTMLDivElement | null>(null);
const attachmentListRef = useRef<HTMLDivElement | null>(null);
const previousPendingUploadCountRef = useRef(0);
/** 切换瞬间记录的卡片旧高度,供 FLIP 动画用;消费后立即置空。 */
const expandFromHeightRef = useRef<number | null>(null);
const expandAnimationRef = useRef<Animation | null>(null);
const scheduleHeightMeasureRef = useRef<(() => void) | null>(null);
const composerLayerRef = useRef<HTMLDivElement | null>(null);
const queuePanelRef = useRef<HTMLDivElement | null>(null);
const queueListRef = useRef<HTMLUListElement | null>(null);
const queueScrollbarTrackRef = useRef<HTMLDivElement | null>(null);
const queueScrollbarDragRef = useRef<{
pointerId: number;
startScrollTop: number;
startY: number;
} | null>(null);
const queueHadTurnsRef = useRef(false);
const [queueCollapsed, setQueueCollapsed] = useState(false);
const [queueScrollbar, setQueueScrollbar] = useState<QueueScrollbarState>(
DEFAULT_QUEUE_SCROLLBAR_STATE,
);
const uploadDisabled = isInputDisabled || isUploadingFiles || !isAgentMode || !workdir;
const controlsDisabled = isInputDisabled;
const hasSendableDraft = !composerIsEmpty || pendingUploadedFiles.length > 0;
// 档位为空但恒开(deepseek-reasoner 型"恒开不可调")也算支持思考——
// 亮灯但开关与档位均不可操作;两者皆无才是真不支持。
const thinkingSupported = reasoningOptions.length > 0 || thinkingAlwaysOn;
const sendDisabled = isInputDisabled || isUploadingFiles || !hasSendableDraft;
const canQueueDraftWhileSending = isSending && !sendDisabled;
const primaryActionTitle = canQueueDraftWhileSending
? t("chat.queue.addToQueue")
: isSending
? t("chat.stopGeneration")
: t("chat.sendMessage");
// controls 已经过 normalizeChatRuntimeControlsForProvider 钳制;这里兜底
// 取表内最高档,绝不给 Select 喂表外值。
const selectedReasoning = reasoningOptions.includes(chatRuntimeControls.reasoning)
? chatRuntimeControls.reasoning
: reasoningOptions.includes(DEFAULT_CHAT_RUNTIME_CONTROLS.reasoning)
? DEFAULT_CHAT_RUNTIME_CONTROLS.reasoning
: (reasoningOptions[reasoningOptions.length - 1] ?? DEFAULT_CHAT_RUNTIME_CONTROLS.reasoning);
const uploadTooltip = isUploadingFiles
? t("chat.upload.uploading")
: !isAgentMode
? t("chat.upload.onlyInTools")
: !workdir
? t("chat.upload.requireWorkdir")
: t("chat.upload.button");
const thinkingTooltip = !thinkingSupported
? t("chat.runtime.thinkingUnavailable")
: t("chat.runtime.thinkingTooltip");
const webSearchTooltip = t("chat.runtime.webSearchTooltip");
const toggleQueueTooltip = queueCollapsed ? t("chat.queue.expand") : t("chat.queue.collapse");
const toggleComposerExpandTooltip = isComposerExpanded
? t("chat.composer.collapse")
: t("chat.composer.expand");
const toggleQueueCollapsed = useCallback(() => {
setQueueCollapsed((current) => !current);
}, []);
useLayoutEffect(() => {
const previousCount = previousPendingUploadCountRef.current;
previousPendingUploadCountRef.current = pendingUploadedFiles.length;
if (pendingUploadedFiles.length <= previousCount) return;
const attachmentList = attachmentListRef.current;
if (attachmentList) attachmentList.scrollLeft = attachmentList.scrollWidth;
}, [pendingUploadedFiles.length]);
// ref 与 state 同步更新:高度上报的 RO 回调可能先于 effect 执行,
// 必须在布局变化前就能读到最新展开态。切换前记录卡片当前高度,
// 布局翻转后由 FLIP effect 从旧高度平滑过渡到新高度。
const setComposerExpanded = useCallback((next: boolean) => {
if (next === isComposerExpandedRef.current) return;
expandFromHeightRef.current = glassCardRef.current?.getBoundingClientRect().height ?? null;
isComposerExpandedRef.current = next;
setIsComposerExpanded(next);
}, []);
// FLIP:布局已按目标态落定,把卡片高度用 min/max 双钳制钉在动画值上,
// 从旧高度平滑过渡到新高度。不能直接动 height——展开态卡片是 flex-1
// (basis 0),height 会被 flex 忽略;min/max 约束则两种布局都尊重。
// biome-ignore lint/correctness/useExhaustiveDependencies(isComposerExpanded): 函数体不读它,但它正是"布局已翻转"的触发信号。
useLayoutEffect(() => {
const card = glassCardRef.current;
const fromHeight = expandFromHeightRef.current;
expandFromHeightRef.current = null;
if (!card || fromHeight === null || typeof card.animate !== "function") return;
if (prefersReducedMotion()) return;
expandAnimationRef.current?.cancel();
const toHeight = card.getBoundingClientRect().height;
if (Math.abs(toHeight - fromHeight) < 1) return;
const animation = card.animate(
[
{ minHeight: `${fromHeight}px`, maxHeight: `${fromHeight}px` },
{ minHeight: `${toHeight}px`, maxHeight: `${toHeight}px` },
],
{ duration: COMPOSER_EXPAND_ANIMATION_MS, easing: COMPOSER_EXPAND_EASING },
);
expandAnimationRef.current = animation;
const clear = () => {
if (expandAnimationRef.current === animation) {
expandAnimationRef.current = null;
}
// 还原方向的高度上报在动画期间被冻结,落定后补测一次。
scheduleHeightMeasureRef.current?.();
};
animation.onfinish = clear;
animation.oncancel = clear;
}, [isComposerExpanded]);
useEffect(() => () => expandAnimationRef.current?.cancel(), []);
const toggleComposerExpanded = useCallback(() => {
setComposerExpanded(!isComposerExpandedRef.current);
composerRef.current?.focus();
}, [composerRef, setComposerExpanded]);
/** 发送(含排队)后退出全高编辑态,让路给回复内容。 */
const handleComposerSend = useCallback(() => {
setComposerExpanded(false);
onSend();
}, [onSend, setComposerExpanded]);
const shouldShowQueueScrollbar = !queueCollapsed && queuedTurns.length > 2;
const updateQueueScrollbar = useCallback(() => {
const list = queueListRef.current;
if (!list || !shouldShowQueueScrollbar) {
setQueueScrollbar((current) => (current.visible ? DEFAULT_QUEUE_SCROLLBAR_STATE : current));
return;
}
const { clientHeight, scrollHeight, scrollTop } = list;
const trackHeight = Math.max(clientHeight, QUEUE_SCROLLBAR_MIN_THUMB_HEIGHT);
const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
const thumbHeight =
maxScrollTop <= 1
? trackHeight
: Math.min(
trackHeight,
Math.max(
QUEUE_SCROLLBAR_MIN_THUMB_HEIGHT,
Math.round((clientHeight / scrollHeight) * trackHeight),
),
);
const maxThumbTop = Math.max(0, trackHeight - thumbHeight);
const thumbTop = maxScrollTop <= 1 ? 0 : Math.round((scrollTop / maxScrollTop) * maxThumbTop);
setQueueScrollbar((current) => {
if (current.visible && current.thumbHeight === thumbHeight && current.thumbTop === thumbTop) {
return current;
}
return { visible: true, thumbHeight, thumbTop };
});
}, [shouldShowQueueScrollbar]);
const scrollQueueToThumbPosition = useCallback(
(clientY: number) => {
const list = queueListRef.current;
const track = queueScrollbarTrackRef.current;
if (!list || !track || !shouldShowQueueScrollbar) return;
const rect = track.getBoundingClientRect();
const maxThumbTop = Math.max(1, rect.height - queueScrollbar.thumbHeight);
const nextThumbTop = Math.min(
Math.max(clientY - rect.top - queueScrollbar.thumbHeight / 2, 0),
maxThumbTop,
);
const maxScrollTop = Math.max(0, list.scrollHeight - list.clientHeight);
list.scrollTop = (nextThumbTop / maxThumbTop) * maxScrollTop;
updateQueueScrollbar();
},
[queueScrollbar.thumbHeight, shouldShowQueueScrollbar, updateQueueScrollbar],
);
const handleQueueScrollbarPointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (!shouldShowQueueScrollbar || event.button !== 0) return;
const list = queueListRef.current;
const track = queueScrollbarTrackRef.current;
if (!list || !track) return;
event.preventDefault();
const target = event.target as HTMLElement;
if (!target.closest(".chat-queue-scrollbar-thumb")) {
scrollQueueToThumbPosition(event.clientY);
}
queueScrollbarDragRef.current = {
pointerId: event.pointerId,
startScrollTop: list.scrollTop,
startY: event.clientY,
};
event.currentTarget.setPointerCapture(event.pointerId);
},
[shouldShowQueueScrollbar, scrollQueueToThumbPosition],
);
const handleQueueScrollbarPointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const drag = queueScrollbarDragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
const list = queueListRef.current;
const track = queueScrollbarTrackRef.current;
if (!list || !track) return;
const maxScrollTop = Math.max(0, list.scrollHeight - list.clientHeight);
const maxThumbTop = Math.max(1, track.clientHeight - queueScrollbar.thumbHeight);
list.scrollTop =
drag.startScrollTop + ((event.clientY - drag.startY) / maxThumbTop) * maxScrollTop;
updateQueueScrollbar();
},
[queueScrollbar.thumbHeight, updateQueueScrollbar],
);
const handleQueueScrollbarPointerUp = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
const drag = queueScrollbarDragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
queueScrollbarDragRef.current = null;
event.currentTarget.releasePointerCapture(event.pointerId);
}, []);
useEffect(() => {
const hasQueuedTurns = queuedTurns.length > 0;
if (hasQueuedTurns && !queueHadTurnsRef.current) {
setQueueCollapsed(false);
}
queueHadTurnsRef.current = hasQueuedTurns;
}, [queuedTurns.length]);
useEffect(() => {
const list = queueListRef.current;
if (!list) {
updateQueueScrollbar();
return;
}
updateQueueScrollbar();
list.addEventListener("scroll", updateQueueScrollbar, { passive: true });
const resizeObserver =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateQueueScrollbar);
resizeObserver?.observe(list);
window.addEventListener("resize", updateQueueScrollbar);
return () => {
list.removeEventListener("scroll", updateQueueScrollbar);
resizeObserver?.disconnect();
window.removeEventListener("resize", updateQueueScrollbar);
};
}, [updateQueueScrollbar]);
useEffect(() => {
const reasoningNeedsReset =
!(reasoningOptions.length > 0 && reasoningOptions.includes(chatRuntimeControls.reasoning)) &&
!(
reasoningOptions.length === 0 &&
chatRuntimeControls.reasoning === DEFAULT_CHAT_RUNTIME_CONTROLS.reasoning
);
const thinkingNeedsEnable = thinkingAlwaysOn && !chatRuntimeControls.thinkingEnabled;
if (!reasoningNeedsReset && !thinkingNeedsEnable) {
return;
}
onChatRuntimeControlsChange({
...(reasoningNeedsReset ? { reasoning: DEFAULT_CHAT_RUNTIME_CONTROLS.reasoning } : {}),
...(thinkingNeedsEnable ? { thinkingEnabled: true } : {}),
});
}, [
chatRuntimeControls.reasoning,
chatRuntimeControls.thinkingEnabled,
onChatRuntimeControlsChange,
reasoningOptions,
thinkingAlwaysOn,
]);
useEffect(() => {
const composerLayer = composerLayerRef.current;
if (!composerLayer) {
return;
}
const chatFrame = composerLayer.closest(".gateway-chat-frame");
if (!(chatFrame instanceof HTMLElement)) {
return;
}
const updateComposerOverlayHeight = () => {
// 展开态占满聊天区,保留最近一次常规高度,避免底部预留跟着跳动;
// 展开/还原动画期间高度是中间值,同样不上报,动画结束后补测。
if (isComposerExpandedRef.current || expandAnimationRef.current) return;
const composerLayerHeight = composerLayer.getBoundingClientRect().height;
const queueHeight = queuePanelRef.current?.getBoundingClientRect().height ?? 0;
chatFrame.style.setProperty(
"--gateway-chat-composer-overlay-height",
`${Math.ceil(Math.max(0, composerLayerHeight - queueHeight))}px`,
);
};
scheduleHeightMeasureRef.current = updateComposerOverlayHeight;
updateComposerOverlayHeight();
if (typeof ResizeObserver === "undefined") {
return () => {
scheduleHeightMeasureRef.current = null;
chatFrame.style.removeProperty("--gateway-chat-composer-overlay-height");
};
}
const resizeObserver = new ResizeObserver(() => {
updateComposerOverlayHeight();
});
resizeObserver.observe(composerLayer);
return () => {
scheduleHeightMeasureRef.current = null;
resizeObserver.disconnect();
chatFrame.style.removeProperty("--gateway-chat-composer-overlay-height");
};
}, []);
return (
<div
ref={composerLayerRef}
className={cn(
"gateway-composer-layer pointer-events-none absolute inset-x-0 bottom-0 z-20 flex justify-center",
// 展开态铺满 transcript stage,把整个聊天区让给输入框。
isComposerExpanded && "top-0 pt-3",
)}
>
<div
className={cn(
"gateway-chat-column pointer-events-auto relative",
// justify-end:展开动画途中卡片被钳在中间高度时保持贴底,向上生长。
isComposerExpanded && "flex min-h-0 flex-col justify-end",
)}
>
{approvalBar}
{queuedTurns.length > 0 ? (
<div
ref={queuePanelRef}
className="relative z-30 mx-auto mb-[-1px] w-[calc(100%-1.5rem)] max-w-[720px]"
>
<div
aria-hidden={queueCollapsed}
className={cn(
"grid transition-[grid-template-rows,opacity] duration-200 ease-out",
queueCollapsed ? "grid-rows-[0fr] opacity-0" : "grid-rows-[1fr] opacity-100",
)}
>
<div className="min-h-0 overflow-hidden">
<div className="rounded-t-lg border border-b-0 border-black/[0.055] bg-white/70 px-1 pb-1 pt-2 shadow-[0_8px_24px_-18px_rgba(15,23,42,0.24),inset_0_1px_0_rgba(255,255,255,0.72)] backdrop-blur-2xl backdrop-saturate-[165%] dark:border-white/[0.10] dark:bg-white/[0.06] dark:shadow-[0_8px_24px_-18px_rgba(0,0,0,0.72),inset_0_1px_0_rgba(255,255,255,0.08)]">
<div className="relative min-h-0">
<ul
ref={queueListRef}
data-scrollable={queuedTurns.length > 2 ? "true" : "false"}
className={cn(
"chat-queue-scroll flex min-w-0 flex-col gap-1 overflow-x-hidden",
queuedTurns.length > 2
? "h-[76px] overflow-y-scroll pr-3"
: "max-h-[76px] overflow-y-hidden pr-1",
)}
>
{queuedTurns.map((item, index) => (
<li
key={item.id}
className="relative grid h-9 min-h-9 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5 rounded-md border border-black/[0.035] bg-white/42 px-2 text-xs shadow-[inset_0_1px_0_rgba(255,255,255,0.56)] backdrop-blur-xl backdrop-saturate-[150%] transition-[border-color,background-color] dark:border-white/[0.06] dark:bg-white/[0.04] dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]"
>
<div className="flex shrink-0 items-center gap-0.5">
{index > 0 ? (
<button
type="button"
disabled={queueCollapsed}
onClick={() => onMoveQueuedTurnUp(item.id)}
aria-label={t("chat.queue.moveUp")}
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground disabled:pointer-events-none disabled:opacity-35"
>
<ChevronUp className="h-3 w-3" />
</button>
) : (
<span aria-hidden className="h-6 w-6" />
)}
<Clock3 className="h-3 w-3 shrink-0 text-muted-foreground/65" />
</div>
<div className="flex min-w-0 items-center gap-1.5 overflow-hidden">
<span className="block min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-[calc(11px*var(--zone-font-scale,1))] leading-4 text-foreground/88">
{item.previewText || t("chat.queue.emptyMessage")}
</span>
{item.fileCount > 0 ? (
<span className="max-w-[4.5rem] shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-[calc(9px*var(--zone-font-scale,1))] leading-4 text-muted-foreground">
{t("chat.queue.fileCount").replace(
"{count}",
String(item.fileCount),
)}
</span>
) : null}
</div>
<div className="flex shrink-0 items-center gap-0.5">
<RuntimeControlTooltip label={t("chat.queue.edit")}>
<button
type="button"
disabled={queueCollapsed}
onClick={() => onEditQueuedTurn(item.id)}
aria-label={t("chat.queue.edit")}
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground"
>
<SquarePen className="h-3 w-3" />
</button>
</RuntimeControlTooltip>
<RuntimeControlTooltip label={t("chat.queue.runNow")}>
<button
type="button"
disabled={queueCollapsed}
onClick={() => onRunQueuedTurnNow(item.id)}
aria-label={t("chat.queue.runNow")}
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground"
>
<Play className="h-3 w-3" />
</button>
</RuntimeControlTooltip>
<RuntimeControlTooltip label={t("chat.queue.delete")}>
<button
type="button"
disabled={queueCollapsed}
onClick={() => onRemoveQueuedTurn(item.id)}
aria-label={t("chat.queue.delete")}
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
>
<Trash2 className="h-3 w-3" />
</button>
</RuntimeControlTooltip>
</div>
</li>
))}
</ul>
{shouldShowQueueScrollbar ? (
<div
ref={queueScrollbarTrackRef}
aria-hidden
className="chat-queue-scrollbar"
onPointerCancel={handleQueueScrollbarPointerUp}
onPointerDown={handleQueueScrollbarPointerDown}
onPointerMove={handleQueueScrollbarPointerMove}
onPointerUp={handleQueueScrollbarPointerUp}
>
<div
className="chat-queue-scrollbar-thumb"
style={{
height: `${queueScrollbar.thumbHeight}px`,
transform: `translateY(${queueScrollbar.thumbTop}px)`,
}}
/>
</div>
) : null}
</div>
</div>
</div>
</div>
<button
type="button"
onClick={toggleQueueCollapsed}
title={toggleQueueTooltip}
aria-label={toggleQueueTooltip}
aria-expanded={!queueCollapsed}
className="absolute left-1/2 top-0 z-40 inline-flex h-[18px] -translate-x-1/2 -translate-y-1/2 items-center gap-1 rounded-full border border-black/[0.07] bg-white/90 pl-1.5 pr-2 text-muted-foreground shadow-[0_2px_10px_-4px_rgba(15,23,42,0.45),inset_0_1px_0_rgba(255,255,255,0.85)] backdrop-blur-xl backdrop-saturate-150 transition-[background-color,color,scale] hover:bg-white hover:text-foreground active:scale-95 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:border-white/[0.12] dark:bg-zinc-900/90 dark:shadow-[0_2px_10px_-4px_rgba(0,0,0,0.8),inset_0_1px_0_rgba(255,255,255,0.10)] dark:hover:bg-zinc-900"
>
{queueCollapsed ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronUp className="h-3 w-3" />
)}
<span className="text-[calc(10px*var(--zone-font-scale,1))] font-medium leading-none tabular-nums">
{queuedTurns.length}
</span>
</button>
</div>
) : null}
{/* biome-ignore lint/a11y/noStaticElementInteractions: Escape 捕获仅在展开态生效,焦点始终在内部 textbox 上,包装层不参与 Tab 序。 */}
<div
ref={glassCardRef}
onKeyDown={
isComposerExpanded
? (event) => {
// mention 弹层消费 Escape 时会 preventDefault,此处让路。
if (event.key === "Escape" && !event.defaultPrevented) {
setComposerExpanded(false);
}
}
: undefined
}
className={cn(
// 过渡只针对 focus-within 的配色/阴影;不能用 transition-all——
// 展开态切换 flex-grow 时会被一并动画,导致卡片先跳顶再长满的闪动。
// 常驻 flex-col:FLIP 动画把卡片钳在中间高度时,flex-1 的编辑器
// 区吸收多余空间,工具栏才能始终贴住卡片底边。
"composer-glass-card relative flex flex-col overflow-hidden rounded-[24px] border border-black/[0.055] bg-white/70 shadow-[0_12px_40px_-14px_rgba(15,23,42,0.22),0_2px_6px_-2px_rgba(15,23,42,0.08),inset_0_1px_0_rgba(255,255,255,0.74)] backdrop-blur-2xl backdrop-saturate-[165%] transition-[background-color,border-color,box-shadow] focus-within:border-black/[0.075] focus-within:bg-white/74 focus-within:shadow-[0_16px_46px_-14px_rgba(15,23,42,0.26),0_4px_12px_-4px_rgba(15,23,42,0.10),inset_0_1px_0_rgba(255,255,255,0.78)] dark:border-white/[0.10] dark:bg-white/[0.06] dark:shadow-[0_12px_40px_-14px_rgba(0,0,0,0.72),0_2px_6px_-2px_rgba(0,0,0,0.42),inset_0_1px_0_rgba(255,255,255,0.08)] dark:focus-within:border-white/[0.15] dark:focus-within:bg-white/[0.08]",
isComposerExpanded && "min-h-0 flex-1",
)}
>
{/* macOS material rim-light */}
<div
aria-hidden
className="pointer-events-none absolute inset-x-5 top-0 h-px rounded-full bg-gradient-to-r from-transparent via-white/85 to-transparent dark:via-white/15"
/>
{/* subtle inner gloss gradient */}
<div
aria-hidden
className="pointer-events-none absolute inset-0 rounded-[24px] bg-gradient-to-b from-white/18 to-transparent opacity-70 dark:from-white/[0.04] dark:opacity-100"
/>
{pendingUploadedFiles.length > 0 ? (
<div
ref={attachmentListRef}
className="upload-file-list relative z-10 flex shrink-0 items-center gap-1.5 overflow-x-auto overflow-y-hidden pb-1 pl-4 pr-12 pt-2"
>
{pendingUploadedFiles.map((file) => (
<PendingComposerAttachment
key={`${file.relativePath}-${file.absolutePath ?? file.fileName}`}
file={file}
workdir={workdir}
disabled={isInputDisabled}
removeLabel={t("chat.upload.removeFile")}
previewLabel={t("chat.upload.previewImage")}
closePreviewLabel={t("chat.upload.closePreview")}
imagePreviewLoader={onLoadUploadedImagePreview}
onRemove={onRemovePendingUpload}
/>
))}
</div>
) : null}
<button
type="button"
onClick={toggleComposerExpanded}
title={toggleComposerExpandTooltip}
aria-label={toggleComposerExpandTooltip}
aria-expanded={isComposerExpanded}
className="absolute right-3 top-2 z-20 inline-flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground/70 outline-hidden transition-[background-color,color,scale] hover:bg-muted/60 hover:text-foreground active:scale-90 focus-visible:bg-muted/60"
>
{isComposerExpanded ? (
<Minimize2 className="h-4 w-4" />
) : (
<Maximize2 className="h-4 w-4" />
)}
</button>
{/* 常驻 flex-1:动画把卡片钳在中间高度时由本区吸收伸缩,工具栏才能
全程贴住卡片底边。min-h-0 只在展开态加——折叠态靠自动最小高度
(= 编辑器钳制高) 撑起卡片的固有高度,加了会塌缩。 */}
<div
className={cn(
"relative flex flex-1 px-4",
pendingUploadedFiles.length > 0 ? "pt-1.5" : "pt-3.5",
isComposerExpanded && "min-h-0",
)}
onFocusCapture={onPrepareChatRuntime}
>
<MentionComposer
ref={composerRef}
onSend={handleComposerSend}
onEmptyChange={setComposerIsEmpty}
onBusyChange={onComposerBusyChange}
onPasteFiles={onPasteFiles}
loadHistoryPrompts={loadHistoryPrompts}
placeholder={inputPlaceholder}
disabled={isInputDisabled}
workdir={workdir}
enabledSkills={enabledSkills}
// !:移动端 .gateway-chat-frame .mention-composer 的 max-height 钳制特异性更高,展开态必须压过它。
className={cn("px-0 py-0 pr-8", isComposerExpanded && "h-full! max-h-none!")}
/>
</div>
<div className="relative flex items-center justify-between gap-2 px-3 pb-2 pt-1">
<div className="flex min-w-0 flex-1 items-center gap-1">
<RuntimeControlTooltip label={uploadTooltip}>
<button
type="button"
disabled={uploadDisabled}
onClick={onPickReadableFiles}
aria-label={
isUploadingFiles
? t("chat.upload.uploading")
: !isAgentMode
? t("chat.upload.onlyInTools")
: !workdir
? t("chat.upload.requireWorkdir")
: t("chat.upload.selectFiles")
}
className={cn(
"composer-toolbar-action relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full outline-hidden transition-colors hover:bg-muted/60 focus-visible:bg-muted/60",
"disabled:pointer-events-none disabled:opacity-40",
pendingUploadedFiles.length > 0
? "text-sky-600 hover:text-sky-700 dark:text-sky-300 dark:hover:text-sky-200"
: "text-muted-foreground hover:text-foreground dark:hover:text-white",
)}
>
{isUploadingFiles ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Paperclip className="h-4 w-4" />
)}
{pendingUploadedFiles.length > 0 ? (
<span
aria-hidden
className="absolute -right-0.5 -top-0.5 flex h-[15px] min-w-[15px] items-center justify-center rounded-full bg-sky-500 px-[3px] text-[calc(9px*var(--zone-font-scale,1))] font-semibold leading-none text-white shadow-[0_0_0_1.5px_rgba(255,255,255,0.95)] dark:bg-sky-400 dark:text-slate-900 dark:shadow-[0_0_0_1.5px_rgba(20,22,28,0.9)]"
>
{pendingUploadedFiles.length}
</span>
) : null}
</button>
</RuntimeControlTooltip>
<RuntimeControlTooltip label={webSearchTooltip}>
<button
type="button"
disabled={controlsDisabled}
onClick={() =>
onChatRuntimeControlsChange({
nativeWebSearchEnabled: !chatRuntimeControls.nativeWebSearchEnabled,
})
}
aria-label={
chatRuntimeControls.nativeWebSearchEnabled
? t("chat.runtime.webSearchOn")
: t("chat.runtime.webSearchOff")
}