-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathChatPane.tsx
More file actions
1056 lines (963 loc) · 42.3 KB
/
ChatPane.tsx
File metadata and controls
1056 lines (963 loc) · 42.3 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 React, {
useState,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useDeferredValue,
useMemo,
} from "react";
import { Lightbulb } from "lucide-react";
import { MessageListProvider } from "@/browser/features/Messages/MessageListContext";
import { cn } from "@/common/lib/utils";
import { MessageRenderer } from "@/browser/features/Messages/MessageRenderer";
import { MarkdownRenderer } from "@/browser/features/Messages/MarkdownRenderer";
import { useTranscriptContextMenu } from "@/browser/features/Messages/useTranscriptContextMenu";
import type { UserMessageNavigation } from "@/browser/features/Messages/UserMessage";
import { InterruptedBarrier } from "@/browser/features/Messages/ChatBarrier/InterruptedBarrier";
import { EditCutoffBarrier } from "@/browser/features/Messages/ChatBarrier/EditCutoffBarrier";
import { StreamingBarrier } from "@/browser/features/Messages/ChatBarrier/StreamingBarrier";
import { RetryBarrier } from "@/browser/features/Messages/ChatBarrier/RetryBarrier";
import { PinnedTodoList } from "../PinnedTodoList/PinnedTodoList";
import { VIM_ENABLED_KEY } from "@/common/constants/storage";
import { ChatInput, type ChatInputAPI } from "@/browser/features/ChatInput/index";
import type { QueueDispatchMode } from "@/browser/features/ChatInput/types";
import {
shouldShowInterruptedBarrier,
mergeConsecutiveStreamErrors,
computeBashOutputGroupInfos,
shouldBypassDeferredMessages,
} from "@/browser/utils/messages/messageUtils";
import { computeTaskReportLinking } from "@/browser/utils/messages/taskReportLinking";
import { BashOutputCollapsedIndicator } from "@/browser/features/Tools/BashOutputCollapsedIndicator";
import {
getInterruptionContext,
getLastNonDecorativeMessage,
} from "@/common/utils/messages/retryEligibility";
import { TooltipIfPresent } from "@/browser/components/Tooltip/Tooltip";
import { formatKeybind, KEYBINDS } from "@/browser/utils/ui/keybinds";
import { useAutoScroll } from "@/browser/hooks/useAutoScroll";
import { useOpenInEditor } from "@/browser/hooks/useOpenInEditor";
import { usePersistedState } from "@/browser/hooks/usePersistedState";
import {
useWorkspaceAggregator,
useWorkspaceUsage,
useWorkspaceStoreRaw,
type WorkspaceState,
} from "@/browser/stores/WorkspaceStore";
import { WorkspaceMenuBar } from "../WorkspaceMenuBar/WorkspaceMenuBar";
import type { DisplayedMessage, QueuedMessage as QueuedMessageData } from "@/common/types/message";
import type { RuntimeConfig } from "@/common/types/runtime";
import { getRuntimeTypeForTelemetry } from "@/common/telemetry";
import { useAIViewKeybinds } from "@/browser/hooks/useAIViewKeybinds";
import { QueuedMessage } from "@/browser/features/Messages/QueuedMessage";
import { CompactionWarning } from "../CompactionWarning/CompactionWarning";
import { ContextSwitchWarning as ContextSwitchWarningBanner } from "../ContextSwitchWarning/ContextSwitchWarning";
import { ConcurrentLocalWarning } from "../ConcurrentLocalWarning/ConcurrentLocalWarning";
import { BackgroundProcessesBanner } from "../BackgroundProcessesBanner/BackgroundProcessesBanner";
import { checkAutoCompaction } from "@/common/utils/compaction/autoCompactionCheck";
import { cancelCompaction } from "@/browser/utils/compaction/handler";
import type { ContextSwitchWarning } from "@/browser/utils/compaction/contextSwitchCheck";
import { useProviderOptions } from "@/browser/hooks/useProviderOptions";
import { useAutoCompactionSettings } from "../../hooks/useAutoCompactionSettings";
import { useContextSwitchWarning } from "@/browser/hooks/useContextSwitchWarning";
import { useProvidersConfig } from "@/browser/hooks/useProvidersConfig";
import { useSendMessageOptions } from "@/browser/hooks/useSendMessageOptions";
import type { TerminalSessionCreateOptions } from "@/browser/utils/terminal";
import { useAPI } from "@/browser/contexts/API";
import { useReviews } from "@/browser/hooks/useReviews";
import { ReviewsBanner } from "../ReviewsBanner/ReviewsBanner";
import type { ReviewNoteData } from "@/common/types/review";
import { useWorkspaceContext } from "@/browser/contexts/WorkspaceContext";
import {
useBackgroundBashActions,
useBackgroundBashError,
} from "@/browser/contexts/BackgroundBashContext";
import {
buildEditingStateFromDisplayed,
normalizeQueuedMessage,
type EditingMessageState,
} from "@/browser/utils/chatEditing";
import { recordSyntheticReactRenderSample } from "@/browser/utils/perf/reactProfileCollector";
// Perf e2e runs load the production bundle where React's onRender profiler callbacks may not
// fire. This marker records synthetic commit timings for selected subtrees so automated perf
// runs still capture render-path metrics for workspace-open regressions.
function PerfRenderMarker(props: { id: string; children: React.ReactNode }): React.ReactElement {
const renderStartTimeRef = useRef(performance.now());
renderStartTimeRef.current = performance.now();
const hasProfiledMountRef = useRef(false);
useLayoutEffect(() => {
if (window.api?.enableReactPerfProfile !== true) {
return;
}
const commitTime = performance.now();
const actualDuration = Math.max(0, commitTime - renderStartTimeRef.current);
const phase = hasProfiledMountRef.current ? "update" : "mount";
hasProfiledMountRef.current = true;
recordSyntheticReactRenderSample({
id: props.id,
phase,
actualDuration,
baseDuration: actualDuration,
startTime: renderStartTimeRef.current,
commitTime,
});
});
return <>{props.children}</>;
}
function isChromaticStorybookEnvironment(): boolean {
if (typeof window === "undefined") {
return false;
}
// Keep production behavior unchanged while suppressing story-only snapshot churn.
const isStorybookPreview = window.location.pathname.endsWith("iframe.html");
if (!isStorybookPreview) {
return false;
}
const chromaticRuntimeFlag = (window as Window & { chromatic?: boolean }).chromatic;
return /Chromatic/i.test(window.navigator.userAgent) || chromaticRuntimeFlag === true;
}
interface ChatPaneProps {
workspaceId: string;
workspaceState: WorkspaceState;
projectPath: string;
projectName: string;
workspaceName: string;
namedWorkspacePath: string;
leftSidebarCollapsed: boolean;
onToggleLeftSidebarCollapsed: () => void;
runtimeConfig?: RuntimeConfig;
onOpenTerminal: (options?: TerminalSessionCreateOptions) => void;
/** Hide + inactivate chat pane while immersive review overlay is active. */
immersiveHidden?: boolean;
}
type ReviewsState = ReturnType<typeof useReviews>;
export const ChatPane: React.FC<ChatPaneProps> = (props) => {
const {
workspaceId,
projectPath,
projectName,
workspaceName,
namedWorkspacePath,
leftSidebarCollapsed,
onToggleLeftSidebarCollapsed,
runtimeConfig,
onOpenTerminal,
workspaceState,
immersiveHidden = false,
} = props;
const { api } = useAPI();
const { workspaceMetadata } = useWorkspaceContext();
const chatAreaRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const chatPaneElement = chatAreaRef.current;
if (!chatPaneElement) {
return;
}
if (immersiveHidden) {
chatPaneElement.setAttribute("inert", "");
} else {
chatPaneElement.removeAttribute("inert");
}
return () => {
chatPaneElement.removeAttribute("inert");
};
}, [immersiveHidden, workspaceId]);
const storeRaw = useWorkspaceStoreRaw();
const aggregator = useWorkspaceAggregator(workspaceId);
const workspaceUsage = useWorkspaceUsage(workspaceId);
const reviews = useReviews(workspaceId);
const { autoBackgroundOnSend } = useBackgroundBashActions();
const { clearError: clearBackgroundBashError } = useBackgroundBashError();
const meta = workspaceMetadata.get(workspaceId);
const workspaceTitle = meta?.title ?? meta?.name ?? workspaceName;
const isQueuedAgentTask = Boolean(meta?.parentWorkspaceId) && meta?.taskStatus === "queued";
const queuedAgentTaskPrompt =
isQueuedAgentTask && typeof meta?.taskPrompt === "string" && meta.taskPrompt.trim().length > 0
? meta.taskPrompt
: null;
const shouldShowQueuedAgentTaskPrompt =
Boolean(queuedAgentTaskPrompt) && (workspaceState?.messages.length ?? 0) === 0;
const { has1MContext } = useProviderOptions();
// Resolve 1M context per-model (uses the pending model for the current workspace)
const pendingSendOptions = useSendMessageOptions(workspaceId);
const pendingModel = pendingSendOptions.model;
const use1M = has1MContext(pendingModel);
const { config: providersConfig } = useProvidersConfig();
const { threshold: autoCompactionThreshold } = useAutoCompactionSettings(
workspaceId,
pendingModel
);
useEffect(() => {
if (!api) {
return;
}
// Keep backend session threshold in sync with the persisted per-model slider value.
const normalizedThreshold = Math.max(0.1, Math.min(1, autoCompactionThreshold / 100));
void api.workspace.setAutoCompactionThreshold({
workspaceId,
threshold: normalizedThreshold,
});
}, [api, workspaceId, autoCompactionThreshold]);
const [editingState, setEditingState] = useState(() => ({
workspaceId,
message: undefined as EditingMessageState | undefined,
}));
const editingMessage =
editingState.workspaceId === workspaceId ? editingState.message : undefined;
const setEditingMessage = useCallback(
(message: EditingMessageState | undefined) => {
setEditingState({ workspaceId, message });
},
[workspaceId]
);
// Track which bash_output groups are expanded (keyed by first message ID)
const [expandedBashGroups, setExpandedBashGroups] = useState<Set<string>>(new Set());
// Extract state from workspace state
// Keep a ref to the latest workspace state so event handlers (passed to memoized children)
// can stay referentially stable during streaming while still reading fresh data.
const workspaceStateRef = useRef(workspaceState);
useEffect(() => {
workspaceStateRef.current = workspaceState;
}, [workspaceState]);
const {
messages,
canInterrupt,
isCompacting,
isStreamStarting,
loading,
isHydratingTranscript,
hasOlderHistory,
loadingOlderHistory,
} = workspaceState;
const shouldRenderLoadOlderMessagesButton = hasOlderHistory && !isChromaticStorybookEnvironment();
const loadOlderMessagesShortcutLabel = formatKeybind(KEYBINDS.LOAD_OLDER_MESSAGES);
const {
warning: contextSwitchWarning,
handleModelChange,
handleCompact: handleContextSwitchCompact,
handleDismiss: handleContextSwitchDismiss,
} = useContextSwitchWarning({
workspaceId,
messages,
pendingModel,
use1M,
workspaceUsage,
api: api ?? undefined,
pendingSendOptions,
providersConfig,
});
// Apply message transformations:
// 1. Merge consecutive identical stream errors
// (bash_output grouping is done at render-time, not as a transformation)
// Use useDeferredValue to allow React to defer the heavy message list rendering
// during rapid updates (streaming), keeping the UI responsive.
// Must be defined before any early returns to satisfy React Hooks rules.
const transformedMessages = useMemo(() => mergeConsecutiveStreamErrors(messages), [messages]);
const deferredTransformedMessages = useDeferredValue(transformedMessages);
// CRITICAL: Show immediate messages when streaming or when message count changes.
// useDeferredValue can defer indefinitely if React keeps getting new work (rapid deltas).
// During active streaming (reasoning, text), we MUST show immediate updates or the UI
// appears frozen while only the token counter updates (reads aggregator directly).
const shouldBypassDeferral = shouldBypassDeferredMessages(
transformedMessages,
deferredTransformedMessages
);
const deferredMessages = shouldBypassDeferral ? transformedMessages : deferredTransformedMessages;
const latestMessageId = getLastNonDecorativeMessage(deferredMessages)?.id ?? null;
const messageListContextValue = useMemo(
() => ({
workspaceId,
latestMessageId,
openTerminal: onOpenTerminal,
}),
[workspaceId, latestMessageId, onOpenTerminal]
);
const taskReportLinking = useMemo(
() => computeTaskReportLinking(deferredMessages),
[deferredMessages]
);
// Precompute bash_output grouping once per message snapshot so row rendering stays O(n).
const bashOutputGroupInfos = useMemo(
() => computeBashOutputGroupInfos(deferredMessages),
[deferredMessages]
);
const autoCompactionResult = useMemo(
() =>
checkAutoCompaction(
workspaceUsage,
pendingModel,
use1M,
autoCompactionThreshold / 100,
undefined,
providersConfig
),
[workspaceUsage, pendingModel, use1M, providersConfig, autoCompactionThreshold]
);
// Show warning when: shouldShowWarning flag is true AND not currently compacting.
// Context-switch warning takes priority so we don't show competing banners.
const shouldShowCompactionWarning =
!isCompacting && autoCompactionResult.shouldShowWarning && !contextSwitchWarning;
// Vim mode state - needed for keybind selection (Ctrl+C in vim, Esc otherwise)
const [vimEnabled] = usePersistedState<boolean>(VIM_ENABLED_KEY, false, { listener: true });
// Use auto-scroll hook for scroll management
const {
contentRef,
innerRef,
autoScroll,
setAutoScroll,
disableAutoScroll,
performAutoScroll,
jumpToBottom,
handleScroll,
markUserInteraction,
} = useAutoScroll();
// Handler to navigate (scroll) to a specific message by historyId
const handleNavigateToMessage = useCallback(
(historyId: string) => {
// Disable auto-scroll so the navigation isn't undone by streaming content
disableAutoScroll();
requestAnimationFrame(() => {
const element = contentRef.current?.querySelector(`[data-message-id="${historyId}"]`);
element?.scrollIntoView({ behavior: "smooth", block: "center" });
});
},
[contentRef, disableAutoScroll]
);
// Precompute per-user navigation objects so MessageRenderer rows receive stable prop
// references across non-message updates (usage bumps, stats updates, etc.).
const userMessageNavigationByHistoryId = useMemo(() => {
const userHistoryIds: string[] = [];
for (const message of deferredMessages) {
if (message.type === "user") {
userHistoryIds.push(message.historyId);
}
}
if (userHistoryIds.length < 2) {
return null;
}
const navigationByHistoryId = new Map<string, UserMessageNavigation>();
for (let index = 0; index < userHistoryIds.length; index++) {
navigationByHistoryId.set(userHistoryIds[index], {
prevUserMessageId: index > 0 ? userHistoryIds[index - 1] : undefined,
nextUserMessageId:
index < userHistoryIds.length - 1 ? userHistoryIds[index + 1] : undefined,
onNavigate: handleNavigateToMessage,
});
}
return navigationByHistoryId;
}, [deferredMessages, handleNavigateToMessage]);
// ChatInput API for focus management
const chatInputAPI = useRef<ChatInputAPI | null>(null);
const handleQuoteText = useCallback((quotedText: string) => {
chatInputAPI.current?.appendText(quotedText);
chatInputAPI.current?.focus();
}, []);
// Right-clicking transcript text offers quick quote/copy actions,
// using selection first and hovered text as a fallback when nothing is selected.
const transcriptContextMenu = useTranscriptContextMenu({
transcriptRootRef: contentRef,
onQuoteText: handleQuoteText,
});
// ChatPane is keyed by workspaceId (WorkspaceShell), so per-workspace UI state naturally
// resets on workspace switches. Clear background errors so they don't leak across workspaces.
useEffect(() => {
clearBackgroundBashError();
}, [clearBackgroundBashError]);
const handleChatInputReady = useCallback((api: ChatInputAPI) => {
chatInputAPI.current = api;
}, []);
// Handler for review notes from Code Review tab - adds review (starts attached)
// Depend only on addReview (not whole reviews object) to keep callback stable
const { addReview, checkReview } = reviews;
const handleCheckReviews = useCallback(
(ids: string[]) => {
for (const id of ids) {
checkReview(id);
}
},
[checkReview]
);
const handleReviewNote = useCallback(
(data: ReviewNoteData) => {
addReview(data);
// New reviews start with status "attached" so they appear in chat input immediately
},
[addReview]
);
// Handlers for editing messages
const handleEditUserMessage = useCallback(
(message: EditingMessageState) => {
setEditingMessage(message);
},
[setEditingMessage]
);
const restoreQueuedDraft = useCallback(
async (queuedMessage: QueuedMessageData) => {
const inputApi = chatInputAPI.current;
if (!inputApi) return;
await api?.workspace.clearQueue({ workspaceId });
inputApi.restoreDraft(normalizeQueuedMessage(queuedMessage));
},
[api, workspaceId]
);
const handleEditQueuedMessage = useCallback(async () => {
const queuedMessage = workspaceState?.queuedMessage;
if (!queuedMessage) return;
await restoreQueuedDraft(queuedMessage);
}, [restoreQueuedDraft, workspaceState?.queuedMessage]);
// Handler for sending queued message immediately (interrupt + send)
const handleSendQueuedImmediately = useCallback(async () => {
if (!workspaceState?.queuedMessage || !workspaceState.canInterrupt) return;
// Set "interrupting" state immediately so UI shows "interrupting..." without flash
storeRaw.setInterrupting(workspaceId);
await api?.workspace.interruptStream({
workspaceId,
options: { sendQueuedImmediately: true },
});
}, [api, workspaceId, workspaceState?.queuedMessage, workspaceState?.canInterrupt, storeRaw]);
const handleCancelCompactionFromBarrier = useCallback(() => {
if (!api || !aggregator) {
return;
}
void cancelCompaction(api, workspaceId, aggregator, setEditingMessage);
}, [api, workspaceId, aggregator, setEditingMessage]);
const handleEditLastUserMessage = useCallback(async () => {
const current = workspaceStateRef.current;
if (!current) return;
if (current.queuedMessage) {
await restoreQueuedDraft(current.queuedMessage);
return;
}
// Otherwise, edit last user message
const transformedMessages = mergeConsecutiveStreamErrors(current.messages);
const lastUserMessage = [...transformedMessages]
.reverse()
.find((msg): msg is Extract<DisplayedMessage, { type: "user" }> => msg.type === "user");
if (!lastUserMessage) {
return;
}
setEditingMessage(buildEditingStateFromDisplayed(lastUserMessage));
disableAutoScroll(); // Show jump-to-bottom indicator
// Scroll to the message being edited
requestAnimationFrame(() => {
const element = contentRef.current?.querySelector(
`[data-message-id="${lastUserMessage.historyId}"]`
);
element?.scrollIntoView({ behavior: "smooth", block: "center" });
});
}, [restoreQueuedDraft, contentRef, disableAutoScroll, setEditingMessage]);
const handleEditLastUserMessageClick = useCallback(() => {
void handleEditLastUserMessage();
}, [handleEditLastUserMessage]);
const handleCancelEdit = useCallback(() => {
setEditingMessage(undefined);
}, [setEditingMessage]);
const handleMessageSent = useCallback(
(dispatchMode: QueueDispatchMode = "tool-end") => {
// Only background foreground bashes for "tool-end" sends (Enter).
// "turn-end" sends (Ctrl/Cmd+Enter) let the stream finish naturally —
// backgrounding would disrupt a foreground bash the user wants to complete.
if (dispatchMode === "tool-end") {
autoBackgroundOnSend();
}
// Enable auto-scroll when user sends a message
setAutoScroll(true);
},
[setAutoScroll, autoBackgroundOnSend]
);
const handleClearHistory = useCallback(
async (percentage = 1.0) => {
// Enable auto-scroll after clearing
setAutoScroll(true);
// Truncate history in backend
await api?.workspace.truncateHistory({ workspaceId, percentage });
},
[workspaceId, setAutoScroll, api]
);
const openInEditor = useOpenInEditor();
const handleOpenInEditor = useCallback(() => {
void openInEditor(workspaceId, namedWorkspacePath, runtimeConfig);
}, [workspaceId, namedWorkspacePath, openInEditor, runtimeConfig]);
// Auto-scroll when messages or todos update (during streaming)
useEffect(() => {
if (autoScroll) {
performAutoScroll();
}
}, [workspaceState?.messages, workspaceState?.todos, autoScroll, performAutoScroll]);
// Scroll to bottom when workspace loads or changes
// useLayoutEffect ensures scroll happens synchronously after DOM mutations
// but before browser paint - critical for Chromatic snapshot consistency
useLayoutEffect(() => {
if (workspaceState && !workspaceState.loading && workspaceState.messages.length > 0) {
jumpToBottom();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [workspaceId, workspaceState?.loading]);
// Compute showRetryBarrier once for both keybinds and UI.
// Track if last message was interrupted or errored (for RetryBarrier).
const interruption = workspaceState
? getInterruptionContext(
workspaceState.messages,
workspaceState.pendingStreamStartTime,
workspaceState.runtimeStatus,
workspaceState.lastAbortReason,
workspaceState.awaitingUserQuestion
)
: null;
const hasInterruptedStream = interruption?.hasInterruptedStream ?? false;
// Keep rendering cached transcript rows during incremental catch-up so workspace switches
// feel stable; only show the full placeholder when there's no transcript content yet.
const showTranscriptHydrationPlaceholder = isHydratingTranscript && deferredMessages.length === 0;
const showRetryBarrier =
!isHydratingTranscript &&
!workspaceState.canInterrupt &&
!workspaceState.isStreamStarting &&
hasInterruptedStream;
const lastActionableMessage = getLastNonDecorativeMessage(workspaceState.messages);
const suppressRetryBarrier =
lastActionableMessage?.type === "stream-error" &&
lastActionableMessage.errorType === "context_exceeded";
const shouldMountRetryBarrier = !suppressRetryBarrier;
const showRetryBarrierUI = showRetryBarrier && !suppressRetryBarrier;
// Keep the transcript bottom pinned before paint when the tail changes.
// Sending a message can append a new user row and mount footer UI (streaming/retry/TODO)
// in the same turn; synchronizing here avoids a visible jump before the async
// ResizeObserver / streaming auto-scroll path runs.
useLayoutEffect(() => {
if (!autoScroll || !contentRef.current) {
return;
}
contentRef.current.scrollTop = contentRef.current.scrollHeight;
}, [
autoScroll,
contentRef,
latestMessageId,
workspaceState?.todos.length,
showRetryBarrierUI,
workspaceState?.isStreamStarting,
workspaceState?.canInterrupt,
shouldShowQueuedAgentTaskPrompt,
]);
const handleLoadOlderHistory = useCallback(() => {
if (!shouldRenderLoadOlderMessagesButton || loadingOlderHistory) {
return;
}
storeRaw.loadOlderHistory(workspaceId).catch((error) => {
console.warn(`[ChatPane] Failed to load older history for ${workspaceId}:`, error);
});
}, [loadingOlderHistory, shouldRenderLoadOlderMessagesButton, storeRaw, workspaceId]);
// Handle keyboard shortcuts (using optional refs that are safe even if not initialized)
useAIViewKeybinds({
workspaceId,
// Allow interrupt keybind even while waiting for stream-start ("starting...").
canInterrupt:
(workspaceState?.canInterrupt ?? false) || (workspaceState?.isStreamStarting ?? false),
showRetryBarrier,
chatInputAPI,
jumpToBottom,
loadOlderHistory: shouldRenderLoadOlderMessagesButton ? handleLoadOlderHistory : null,
handleOpenTerminal: onOpenTerminal,
handleOpenInEditor,
aggregator,
setEditingMessage,
vimEnabled,
});
// Clear editing state if the message being edited no longer exists
// Must be before early return to satisfy React Hooks rules
useEffect(() => {
if (!workspaceState || !editingMessage) return;
const transformedMessages = mergeConsecutiveStreamErrors(workspaceState.messages);
const editCutoffHistoryId = transformedMessages.find(
(
msg
): msg is Exclude<
DisplayedMessage,
{ type: "history-hidden" | "workspace-init" | "compaction-boundary" }
> =>
msg.type !== "history-hidden" &&
msg.type !== "workspace-init" &&
msg.type !== "compaction-boundary" &&
msg.historyId === editingMessage.id
)?.historyId;
if (!editCutoffHistoryId) {
// Message was replaced or deleted - clear editing state
setEditingMessage(undefined);
}
}, [workspaceState, editingMessage, setEditingMessage]);
// When editing, find the cutoff point
const editCutoffHistoryId = editingMessage
? transformedMessages.find(
(
msg
): msg is Exclude<
DisplayedMessage,
{ type: "history-hidden" | "workspace-init" | "compaction-boundary" }
> =>
msg.type !== "history-hidden" &&
msg.type !== "workspace-init" &&
msg.type !== "compaction-boundary" &&
msg.historyId === editingMessage.id
)?.historyId
: undefined;
// Find the ID of the latest propose_plan tool call for external edit detection
// Only the latest plan should fetch fresh content from disk
let latestProposePlanId: string | null = null;
for (let i = transformedMessages.length - 1; i >= 0; i--) {
const msg = transformedMessages[i];
if (msg.type === "tool" && msg.toolName === "propose_plan") {
latestProposePlanId = msg.id;
break;
}
}
return (
<PerfRenderMarker id="chat-pane">
<div
ref={chatAreaRef}
aria-hidden={immersiveHidden || undefined}
className={cn(
"bg-surface-primary flex min-w-96 flex-1 flex-col",
// Immersive review overlays the entire workspace, so hiding the chat pane removes
// its layout cost while preserving component state for the return transition.
immersiveHidden && "hidden",
"[@media(max-width:768px)]:max-h-full [@media(max-width:768px)]:w-full",
"[@media(max-width:768px)]:min-w-0"
)}
>
<PerfRenderMarker id="chat-pane.header">
<WorkspaceMenuBar
workspaceId={workspaceId}
projectName={projectName}
projectPath={projectPath}
workspaceName={workspaceName}
workspaceTitle={workspaceTitle}
leftSidebarCollapsed={leftSidebarCollapsed}
onToggleLeftSidebarCollapsed={onToggleLeftSidebarCollapsed}
namedWorkspacePath={namedWorkspacePath}
runtimeConfig={runtimeConfig}
onOpenTerminal={onOpenTerminal}
/>
</PerfRenderMarker>
<PerfRenderMarker id="chat-pane.transcript">
{/* Spacer for fixed mobile header - mobile-header-spacer adds padding-top on touch devices */}
<div className="mobile-header-spacer relative flex-1 overflow-hidden">
<div
ref={contentRef}
onWheel={markUserInteraction}
onTouchMove={markUserInteraction}
onScroll={handleScroll}
onContextMenu={transcriptContextMenu.onContextMenu}
role="log"
aria-live={canInterrupt ? "polite" : "off"}
aria-busy={canInterrupt || isHydratingTranscript}
aria-label="Conversation transcript"
tabIndex={0}
data-testid="message-window"
data-loaded={!loading && !isHydratingTranscript}
className="h-full overflow-x-hidden overflow-y-auto p-[15px] leading-[1.5] break-words whitespace-pre-wrap"
>
<div
ref={innerRef}
className={cn(
"max-w-4xl mx-auto",
(showTranscriptHydrationPlaceholder || deferredMessages.length === 0) && "h-full"
)}
>
{showTranscriptHydrationPlaceholder ? (
<div
data-testid="transcript-hydration-placeholder"
className="text-placeholder flex h-full flex-1 flex-col items-center justify-center text-center [&_h3]:m-0 [&_h3]:mb-2.5 [&_h3]:text-base [&_h3]:font-medium [&_p]:m-0 [&_p]:text-[13px]"
>
<h3>Loading transcript...</h3>
<p>Syncing recent messages for this workspace</p>
</div>
) : deferredMessages.length === 0 ? (
<div className="text-placeholder flex h-full flex-1 flex-col items-center justify-center text-center [&_h3]:m-0 [&_h3]:mb-2.5 [&_h3]:text-base [&_h3]:font-medium [&_p]:m-0 [&_p]:text-[13px]">
<h3>No Messages Yet</h3>
<p>Send a message below to begin</p>
<p className="text-muted mt-5 flex items-start gap-2 text-xs">
<Lightbulb aria-hidden="true" className="mt-0.5 h-3 w-3 shrink-0" />
<span>
Tip: Add a{" "}
<code className="bg-inline-code-dark-bg text-code-string rounded-[3px] px-1.5 py-0.5 font-mono text-[11px]">
.mux/init
</code>{" "}
hook to your project to run setup commands
<br />
(e.g., install dependencies, build) when creating new workspaces
</span>
</p>
</div>
) : (
<MessageListProvider value={messageListContextValue}>
<>
{shouldRenderLoadOlderMessagesButton && (
<div className="flex justify-center py-3">
<TooltipIfPresent
tooltip={`Load older messages (${loadOlderMessagesShortcutLabel})`}
side="top"
>
<button
type="button"
onClick={handleLoadOlderHistory}
disabled={loadingOlderHistory}
className="text-muted hover:text-foreground text-xs underline underline-offset-2 transition-colors disabled:opacity-50"
>
{loadingOlderHistory ? "Loading..." : "Load older messages"}
</button>
</TooltipIfPresent>
</div>
)}
{deferredMessages.map((msg, index) => {
const bashOutputGroup = bashOutputGroupInfos[index];
// For bash_output groups, use first message ID as expansion key
const groupKey = bashOutputGroup
? deferredMessages[bashOutputGroup.firstIndex]?.id
: undefined;
const isGroupExpanded = groupKey ? expandedBashGroups.has(groupKey) : false;
// Skip rendering middle items in a bash_output group (unless expanded)
if (bashOutputGroup?.position === "middle" && !isGroupExpanded) {
return null;
}
const isAtCutoff =
editCutoffHistoryId !== undefined &&
msg.type !== "history-hidden" &&
msg.type !== "workspace-init" &&
msg.type !== "compaction-boundary" &&
msg.historyId === editCutoffHistoryId;
const taskReportLinkingForMessage =
msg.type === "tool" &&
(msg.toolName === "task" || msg.toolName === "task_await")
? taskReportLinking
: undefined;
return (
<React.Fragment key={msg.id}>
<MessageRenderer
message={msg}
onEditUserMessage={handleEditUserMessage}
workspaceId={workspaceId}
isCompacting={isCompacting}
onReviewNote={handleReviewNote}
isLatestProposePlan={
msg.type === "tool" &&
msg.toolName === "propose_plan" &&
msg.id === latestProposePlanId
}
bashOutputGroup={bashOutputGroup}
taskReportLinking={taskReportLinkingForMessage}
userMessageNavigation={
msg.type === "user"
? userMessageNavigationByHistoryId?.get(msg.historyId)
: undefined
}
/>
{/* Show collapsed indicator after the first item in a bash_output group */}
{bashOutputGroup?.position === "first" && groupKey && (
<BashOutputCollapsedIndicator
processId={bashOutputGroup.processId}
collapsedCount={bashOutputGroup.collapsedCount}
isExpanded={isGroupExpanded}
onToggle={() => {
setExpandedBashGroups((prev) => {
const next = new Set(prev);
if (next.has(groupKey)) {
next.delete(groupKey);
} else {
next.add(groupKey);
}
return next;
});
}}
/>
)}
{isAtCutoff && <EditCutoffBarrier />}
{shouldShowInterruptedBarrier(msg, deferredMessages) && (
<InterruptedBarrier />
)}
</React.Fragment>
);
})}
</>
</MessageListProvider>
)}
<div style={{ overflowAnchor: "none" }}>
{/*
Keep the dynamic transcript tail out of the browser's scroll-anchoring heuristics.
ChatPane explicitly pins the bottom when auto-scroll is enabled, so anchoring to
the streaming barrier / pinned TODO stack causes a brief visible jump on send.
*/}
{shouldMountRetryBarrier && (
<RetryBarrier workspaceId={workspaceId} visible={showRetryBarrierUI} />
)}
<PinnedTodoList workspaceId={workspaceId} />
<StreamingBarrier
workspaceId={workspaceId}
vimEnabled={vimEnabled}
onCancelCompaction={handleCancelCompactionFromBarrier}
/>
{shouldShowQueuedAgentTaskPrompt && (
<div className="mt-4 mb-1 ml-auto w-fit max-w-full">
<div className="rounded-lg border border-[var(--color-user-border)] bg-[var(--color-user-surface)] px-3 py-2 text-sm">
<div className="text-muted mb-1 text-[11px] font-medium">Queued</div>
<MarkdownRenderer
content={queuedAgentTaskPrompt ?? ""}
className="user-message-markdown text-foreground"
preserveLineBreaks
style={{ overflowWrap: "break-word", wordBreak: "break-word" }}
/>
</div>
</div>
)}
<ConcurrentLocalWarning
workspaceId={workspaceId}
projectPath={projectPath}
runtimeConfig={runtimeConfig}
/>
</div>
</div>
</div>
{transcriptContextMenu.menu}
{!autoScroll && (
<button
onClick={jumpToBottom}
type="button"
className="assistant-chip font-primary text-foreground hover:assistant-chip-hover absolute bottom-2 left-1/2 z-20 -translate-x-1/2 cursor-pointer rounded-[20px] px-2 py-1 text-xs font-medium shadow-[0_4px_12px_rgba(0,0,0,0.3)] backdrop-blur-[1px] transition-all duration-200 hover:scale-105 active:scale-95"
>
Jump to bottom{" "}
<span className="mobile-hide-shortcut-hints">
({formatKeybind(KEYBINDS.JUMP_TO_BOTTOM)})
</span>
</button>
)}
</div>
</PerfRenderMarker>
<PerfRenderMarker id="chat-pane.input">
<ChatInputPane
workspaceId={workspaceId}
projectName={projectName}
workspaceName={workspaceName}
isStreamStarting={isStreamStarting}
runtimeConfig={runtimeConfig}
isQueuedAgentTask={isQueuedAgentTask}
isCompacting={isCompacting}
canInterrupt={canInterrupt}
autoCompactionResult={autoCompactionResult}
shouldShowCompactionWarning={shouldShowCompactionWarning}
contextSwitchWarning={contextSwitchWarning}
onContextSwitchCompact={handleContextSwitchCompact}
onContextSwitchDismiss={handleContextSwitchDismiss}
onModelChange={handleModelChange}
onMessageSent={handleMessageSent}
onTruncateHistory={handleClearHistory}
editingMessage={editingMessage}
onCancelEdit={handleCancelEdit}
onEditLastUserMessage={handleEditLastUserMessageClick}
onChatInputReady={handleChatInputReady}
queuedMessage={workspaceState?.queuedMessage ?? null}
onEditQueuedMessage={() => void handleEditQueuedMessage()}
onSendQueuedImmediately={
workspaceState?.canInterrupt ? handleSendQueuedImmediately : undefined
}
reviews={reviews}
onCheckReviews={handleCheckReviews}
/>
</PerfRenderMarker>
</div>
</PerfRenderMarker>
);
};
interface ChatInputPaneProps {
workspaceId: string;
projectName: string;
workspaceName: string;
runtimeConfig?: RuntimeConfig;
isQueuedAgentTask: boolean;
isCompacting: boolean;
isStreamStarting: boolean;
canInterrupt: boolean;
autoCompactionResult: ReturnType<typeof checkAutoCompaction>;
shouldShowCompactionWarning: boolean;
contextSwitchWarning: ContextSwitchWarning | null;
onContextSwitchCompact: () => void;
onContextSwitchDismiss: () => void;
onModelChange?: (model: string) => void;
onMessageSent: (dispatchMode: QueueDispatchMode) => void;
onTruncateHistory: (percentage?: number) => Promise<void>;
editingMessage: EditingMessageState | undefined;
onCancelEdit: () => void;
onEditLastUserMessage: () => void;
onChatInputReady: (api: ChatInputAPI) => void;
queuedMessage: QueuedMessageData | null;
onEditQueuedMessage: () => void;
onSendQueuedImmediately: (() => Promise<void>) | undefined;
reviews: ReviewsState;
onCheckReviews: (ids: string[]) => void;
}
const ChatInputPane: React.FC<ChatInputPaneProps> = (props) => {
const { reviews } = props;
return (
<div className="flex flex-col gap-2">
{/*
Keep optional banners/warnings on one shared stack so spacing above the chat input
stays consistent as background bash, review, and queue UI appear or disappear.
*/}
{props.shouldShowCompactionWarning && (
<CompactionWarning
usagePercentage={props.autoCompactionResult.usagePercentage}
thresholdPercentage={props.autoCompactionResult.thresholdPercentage}