-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathChatPane.tsx
More file actions
1829 lines (1677 loc) · 75.9 KB
/
Copy pathChatPane.tsx
File metadata and controls
1829 lines (1677 loc) · 75.9 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 { ChatInstructionsChatDecoration } from "@/browser/components/InstructionsTab/AdditionalSystemContextScratchpad";
import { MessageRenderer } from "@/browser/features/Messages/MessageRenderer";
import { WorkBundleMessage } from "@/browser/features/Messages/WorkBundleMessage";
import { OperationalBundleMessage } from "@/browser/features/Messages/OperationalBundleMessage";
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 { ChatInputDecorationStackLane, TranscriptTailStackLane } from "./LayoutStackLane";
import { computeChatViewReveal, useChatViewDataReady } from "./useChatViewDataReady";
import { TranscriptHydrationSkeleton } from "./TranscriptHydrationSkeleton";
import {
createChatInputDecorationStackItem,
createTranscriptTailStackItem,
type ChatInputDecorationStackItem,
type TranscriptTailStackItem,
} from "./layoutStack";
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 { BashCollapsedSummaryModeProvider } from "@/browser/features/Tools/BashCollapsedSummaryModeContext";
import { BashOutputCollapsedIndicator } from "@/browser/features/Tools/BashOutputCollapsedIndicator";
import {
getInterruptionContext,
getLastMainRetryCandidateMessage,
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,
useWorkspaceState,
useWorkspaceUsage,
useWorkspaceStoreRaw,
} 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 {
ConcurrentLocalWarningDecoration,
useConcurrentLocalStreamingWorkspaceName,
} 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 { useChatTranscriptFullWidth } from "@/browser/hooks/useChatTranscriptFullWidth";
import { useTranscriptDensity } from "@/browser/hooks/useTranscriptDensity";
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,
canEditDisplayedUserMessage,
normalizeQueuedMessage,
type EditingMessageState,
} from "@/browser/utils/chatEditing";
import {
findActiveSideQuestionScrollHoldTarget,
findSideQuestionScrollHoldTarget,
type SideQuestionScrollHoldState,
} from "./sideQuestionScrollHold";
import {
computeOperationalBundleInfos,
computeWorkBundleInfos,
} from "@/browser/utils/messages/transcriptRenderProjection";
import { isBlockedPreStreamTaskStatus } from "@/browser/utils/ui/workspaceFiltering";
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.
const TRANSCRIPT_ONLY_NOTICE =
"This workspace's worktree is no longer available. This is a read-only chat transcript kept for historical and usage-tracking reasons.";
function findTailProposePlanToolId(messages: readonly DisplayedMessage[]): string | null {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.type !== "tool") {
continue;
}
return message.toolName === "propose_plan" ? message.id : null;
}
return null;
}
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;
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 ChatPaneContentProps = Omit<
ChatPaneProps,
"leftSidebarCollapsed" | "onToggleLeftSidebarCollapsed" | "immersiveHidden"
>;
type ReviewsState = ReturnType<typeof useReviews>;
// Bottom-stick is owned by native CSS scroll anchoring (see useAutoScroll). While
// locked, the transcript content opts OUT of anchoring so the only eligible anchor
// is the 0-height bottom sentinel; the browser then keeps that sentinel pinned as
// rows/tokens/the streaming barrier append above it — no per-frame scrollTop chase.
// When unlocked (manual reading) we drop this so the browser anchors to an onscreen
// row and preserves the reading position while off-screen content above settles.
const TRANSCRIPT_CONTENT_NO_ANCHOR_STYLE = { overflowAnchor: "none" } as const;
// The sentinel is the sole anchor candidate while locked.
const TRANSCRIPT_BOTTOM_SENTINEL_STYLE = { overflowAnchor: "auto" } as const;
// The composer dock is normal scroll content (sticky to the scrollport bottom),
// so the transcript's bottom clearance is reserved by flow layout in the SAME
// layout pass a decoration/textarea height change happens — there is no
// measured channel (the old --composer-h ResizeObserver) that could lag actual
// layout by a frame and tear. The dock must never be a scroll-anchoring
// candidate: while locked the sentinel owns anchoring, and while released the
// browser must anchor to a transcript row, not the sticky dock.
const COMPOSER_DOCK_STYLE = { overflowAnchor: "none" } as const;
function findTranscriptMessageElement(
scrollContainer: HTMLElement,
historyId: string
): HTMLElement | undefined {
return Array.from(scrollContainer.querySelectorAll<HTMLElement>("[data-message-id]")).find(
(element) => element.getAttribute("data-message-id") === historyId
);
}
export const ChatPane: React.FC<ChatPaneProps> = (props) => {
const workspaceId = props.workspaceId;
const immersiveHidden = props.immersiveHidden ?? false;
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 meta = workspaceMetadata.get(workspaceId);
const workspaceTitle = meta?.title ?? meta?.name ?? props.workspaceName;
return (
<PerfRenderMarker id="chat-pane">
<div
ref={chatAreaRef}
aria-hidden={immersiveHidden || undefined}
className={cn(
"bg-surface-primary relative 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={props.projectName}
projectPath={props.projectPath}
workspaceName={props.workspaceName}
workspaceTitle={workspaceTitle}
leftSidebarCollapsed={props.leftSidebarCollapsed}
onToggleLeftSidebarCollapsed={props.onToggleLeftSidebarCollapsed}
namedWorkspacePath={props.namedWorkspacePath}
runtimeConfig={props.runtimeConfig}
onOpenTerminal={props.onOpenTerminal}
/>
</PerfRenderMarker>
<ChatPaneContent
workspaceId={workspaceId}
projectPath={props.projectPath}
projectName={props.projectName}
workspaceName={props.workspaceName}
namedWorkspacePath={props.namedWorkspacePath}
runtimeConfig={props.runtimeConfig}
onOpenTerminal={props.onOpenTerminal}
/>
</div>
</PerfRenderMarker>
);
};
const ChatPaneContent: React.FC<ChatPaneContentProps> = (props) => {
const {
workspaceId,
projectPath,
projectName,
workspaceName,
namedWorkspacePath,
runtimeConfig,
onOpenTerminal,
} = props;
const workspaceState = useWorkspaceState(workspaceId);
const chatTranscriptFullWidth = useChatTranscriptFullWidth();
const [transcriptDensity] = useTranscriptDensity();
const { api } = useAPI();
const { workspaceMetadata } = useWorkspaceContext();
const storeRaw = useWorkspaceStoreRaw();
const aggregator = useWorkspaceAggregator(workspaceId);
const workspaceUsage = useWorkspaceUsage(workspaceId);
const reviews = useReviews(workspaceId);
const { autoBackgroundOnSend } = useBackgroundBashActions();
const { clearError: clearBackgroundBashError } = useBackgroundBashError();
// Transcript-only workspaces preserve historical chat and usage after the worktree is deleted,
// so the transcript stays readable while new sends remain disabled.
const meta = workspaceMetadata.get(workspaceId);
const transcriptOnly = meta?.transcriptOnly ?? false;
const isPreStreamAgentTask =
Boolean(meta?.parentWorkspaceId) && isBlockedPreStreamTaskStatus(meta?.taskStatus);
const preStreamAgentTaskLabel = meta?.taskStatus === "starting" ? "Starting" : "Queued";
const queuedAgentTaskPrompt =
isPreStreamAgentTask &&
typeof meta?.taskPrompt === "string" &&
meta.taskPrompt.trim().length > 0
? meta.taskPrompt
: null;
const shouldShowQueuedAgentTaskPrompt =
Boolean(queuedAgentTaskPrompt) && (workspaceState?.messages.length ?? 0) === 0;
const concurrentLocalStreamingWorkspaceName = useConcurrentLocalStreamingWorkspaceName({
workspaceId,
projectPath,
runtimeConfig,
});
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();
// First-paint readiness barrier: all decoration data sources known (or the
// resilience deadline passed). Gates the reveal so decorations can't pop in
// after the transcript is visible.
const chatViewDataReady = useChatViewDataReady(workspaceId);
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: transcriptOnly ? undefined : message,
});
},
[workspaceId, transcriptOnly]
);
// Transcript-only workspaces swap the composer for a read-only notice, so clear any
// stale edit state instead of leaving the transcript stuck at an edit cutoff.
useEffect(() => {
if (transcriptOnly && editingMessage) {
setEditingState({ workspaceId, message: undefined });
}
}, [editingMessage, transcriptOnly, workspaceId]);
// Track which bash_output groups are expanded (keyed by first message ID)
const [expandedBashGroups, setExpandedBashGroups] = useState<Set<string>>(new Set());
const [workBundleExpansionOverrides, setWorkBundleExpansionOverrides] = useState<
Map<string, boolean>
>(new Map());
const [operationalBundleExpansionOverrides, setOperationalBundleExpansionOverrides] = useState<
Map<string, boolean>
>(new Map());
// 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,
isTranscriptCaughtUp,
hasOlderHistory,
loadingOlderHistory,
} = workspaceState;
const shouldShowPinnedTodoList = workspaceState.todos.length > 0;
const shouldShowReviewsBanner = reviews.reviews.length > 0;
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 immediateMessageSnapshot = useMemo(
() => ({ workspaceId, messages: transformedMessages }),
[workspaceId, transformedMessages]
);
const deferredMessageSnapshot = useDeferredValue(immediateMessageSnapshot);
// 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).
// Also bypass the deferred snapshot when it still belongs to the previous workspace so
// chat switches cannot briefly render stale transcript rows from the old workspace.
const shouldBypassDeferral = shouldBypassDeferredMessages(
immediateMessageSnapshot.messages,
deferredMessageSnapshot.messages,
{
immediateWorkspaceId: workspaceId,
deferredWorkspaceId: deferredMessageSnapshot.workspaceId,
}
);
const deferredMessages = shouldBypassDeferral
? immediateMessageSnapshot.messages
: deferredMessageSnapshot.messages;
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 workBundleInfos = useMemo(
() => (transcriptDensity === "hyper" ? computeWorkBundleInfos(deferredMessages) : undefined),
[deferredMessages, transcriptDensity]
);
const operationalBundleInfos = useMemo(
() =>
transcriptDensity === "hyper"
? computeOperationalBundleInfos(deferredMessages, {
isTurnActive: isStreamStarting || canInterrupt,
})
: undefined,
[canInterrupt, deferredMessages, isStreamStarting, transcriptDensity]
);
// A tail propose_plan usually means the agent paused for user review; reveal only the
// containing hyper-density bundles by default so historical plans stay collapsed.
const tailProposePlanToolId =
transcriptDensity === "hyper" ? findTailProposePlanToolId(deferredMessages) : null;
const tailProposePlanIndex =
tailProposePlanToolId === null
? -1
: deferredMessages.findIndex((message) => message.id === tailProposePlanToolId);
const tailProposePlanWorkBundleKey =
tailProposePlanIndex === -1 ? null : (workBundleInfos?.[tailProposePlanIndex]?.key ?? null);
const tailProposePlanOperationalBundleKey =
tailProposePlanIndex === -1
? null
: (operationalBundleInfos?.[tailProposePlanIndex]?.key ?? null);
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,
sentinelRef,
autoScroll,
disableAutoScroll,
jumpToBottom,
handleScroll,
markUserScrollIntent,
handleScrollContainerWheel,
handleScrollContainerMouseDown,
handleScrollContainerMouseMove,
handleScrollContainerMouseUp,
handleScrollContainerKeyDown,
} = useAutoScroll();
// The composer dock lives inside the scrollport (sticky to its bottom), so
// mousedown/keydown events from the composer bubble to the transcript
// handlers. They must not open a scroll-intent window or clear the
// side-question hold: typing or clicking in the composer is not transcript
// scroll intent. Wheel/touch are intentionally NOT filtered — those gestures
// really do scroll the transcript (native scroll chaining), so they must keep
// marking user intent or the bottom lock would fight the user's scroll.
const composerDockRef = useRef<HTMLDivElement>(null);
const isComposerDockEvent = useCallback((target: EventTarget | null): boolean => {
return target instanceof Node && (composerDockRef.current?.contains(target) ?? false);
}, []);
const sideQuestionScrollHoldRef = useRef<SideQuestionScrollHoldState>({
initialized: false,
heldSideQuestionIds: new Set<string>(),
previouslyStreamingSideAnswerIds: new Set<string>(),
heldSideAnswerIds: new Set<string>(),
});
const activeSideQuestionScrollHoldTargetRef = useRef<string | null>(null);
const clearActiveSideQuestionScrollHold = useCallback(() => {
activeSideQuestionScrollHoldTargetRef.current = null;
}, []);
useLayoutEffect(() => {
sideQuestionScrollHoldRef.current = {
initialized: false,
heldSideQuestionIds: new Set<string>(),
previouslyStreamingSideAnswerIds: new Set<string>(),
heldSideAnswerIds: new Set<string>(),
};
activeSideQuestionScrollHoldTargetRef.current = null;
}, [workspaceId]);
useLayoutEffect(() => {
if (loading || isHydratingTranscript || deferredMessages.length === 0) {
return;
}
const { nextState, targetHistoryId: detectedTargetHistoryId } =
findSideQuestionScrollHoldTarget(deferredMessages, sideQuestionScrollHoldRef.current);
sideQuestionScrollHoldRef.current = nextState;
const activeTargetHistoryId = activeSideQuestionScrollHoldTargetRef.current;
const activeHold = findActiveSideQuestionScrollHoldTarget(
deferredMessages,
activeTargetHistoryId
);
const continuingTargetHistoryId =
activeHold.targetHistoryId === activeTargetHistoryId ? activeHold.targetHistoryId : undefined;
const shouldStartHold = detectedTargetHistoryId !== undefined && autoScroll;
const targetHistoryId = shouldStartHold ? detectedTargetHistoryId : continuingTargetHistoryId;
if (!targetHistoryId) {
if (!activeHold.keepActive) {
activeSideQuestionScrollHoldTargetRef.current = null;
}
return;
}
const scrollContainer = contentRef.current;
if (!scrollContainer) {
return;
}
const alignSideBranchStart = (): HTMLElement | undefined => {
const targetElement = findTranscriptMessageElement(scrollContainer, targetHistoryId);
targetElement?.scrollIntoView({
block: "start",
inline: "nearest",
});
return targetElement;
};
const currentHold = findActiveSideQuestionScrollHoldTarget(deferredMessages, targetHistoryId);
const releaseSettledHold = (): void => {
if (
currentHold.keepActive ||
activeSideQuestionScrollHoldTargetRef.current !== targetHistoryId
) {
return;
}
activeSideQuestionScrollHoldTargetRef.current = null;
};
// The main stream can now keep rendering below an active /btw branch. Once
// that happens, bottom-lock would otherwise follow the main tail and yank
// the user away from the aside they just requested. Release bottom-lock once
// per interrupted side branch, then let the finite hold expire as soon as
// both the side answer and interrupted main stream are settled.
if (shouldStartHold) {
activeSideQuestionScrollHoldTargetRef.current = targetHistoryId;
disableAutoScroll();
}
alignSideBranchStart();
releaseSettledHold();
const win = typeof window !== "undefined" ? window : undefined;
const raf = win?.requestAnimationFrame?.bind(win);
const cancelRaf = win?.cancelAnimationFrame?.bind(win);
if (!raf || !cancelRaf) {
return;
}
const frameId = raf(() => {
alignSideBranchStart();
releaseSettledHold();
});
return () => cancelRaf(frameId);
}, [autoScroll, contentRef, deferredMessages, disableAutoScroll, isHydratingTranscript, loading]);
const handleTranscriptWheel = useCallback(
(event: React.WheelEvent<HTMLDivElement>) => {
if (event.deltaX !== 0 || event.deltaY !== 0) {
clearActiveSideQuestionScrollHold();
}
handleScrollContainerWheel(event);
},
[clearActiveSideQuestionScrollHold, handleScrollContainerWheel]
);
const handleTranscriptMouseDown = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
if (isComposerDockEvent(event.target)) {
return;
}
clearActiveSideQuestionScrollHold();
handleScrollContainerMouseDown(event);
},
[clearActiveSideQuestionScrollHold, handleScrollContainerMouseDown, isComposerDockEvent]
);
const handleTranscriptTouchMove = useCallback(() => {
clearActiveSideQuestionScrollHold();
markUserScrollIntent();
}, [clearActiveSideQuestionScrollHold, markUserScrollIntent]);
const handleTranscriptKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (isComposerDockEvent(event.target)) {
return;
}
clearActiveSideQuestionScrollHold();
handleScrollContainerKeyDown(event);
},
[clearActiveSideQuestionScrollHold, handleScrollContainerKeyDown, isComposerDockEvent]
);
const handleJumpToBottom = useCallback(() => {
clearActiveSideQuestionScrollHold();
jumpToBottom();
}, [clearActiveSideQuestionScrollHold, jumpToBottom]);
// 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 scrollContainer = contentRef.current;
if (!scrollContainer) return;
findTranscriptMessageElement(scrollContainer, historyId)?.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,
hasInputTarget: !transcriptOnly,
});
// Workspace switches should not leak background bash errors into the newly selected chat.
useEffect(() => {
clearBackgroundBashError();
}, [clearBackgroundBashError, workspaceId]);
useEffect(() => {
setEditingState({ workspaceId, message: undefined });
setExpandedBashGroups(new Set());
setWorkBundleExpansionOverrides(new Map());
setOperationalBundleExpansionOverrides(new Map());
}, [workspaceId]);
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]);
const sendQueuedImmediatelyInFlightRef = useRef<string | null>(null);
// The backend can resolve the interrupt RPC before the queued-message-cleared
// event renders, so keep duplicate send-now attempts blocked until the queued
// message id changes or clears.
useEffect(() => {
const queuedMessageId = workspaceState?.queuedMessage?.id ?? null;
if (queuedMessageId !== sendQueuedImmediatelyInFlightRef.current) {
sendQueuedImmediatelyInFlightRef.current = null;
}
}, [workspaceState?.queuedMessage?.id]);
// Handler for sending queued message immediately (interrupt + send)
const handleSendQueuedImmediately = useCallback(async () => {
const queuedMessage = workspaceState?.queuedMessage;
if (
!api ||
!queuedMessage ||
!workspaceState.canInterrupt ||
sendQueuedImmediatelyInFlightRef.current === queuedMessage.id
) {
return;
}
sendQueuedImmediatelyInFlightRef.current = queuedMessage.id;
// Release the duplicate-send guard only if it still points at this attempt; a
// newer queued message (or a clear) may have already reset it in the meantime.
const clearInFlightGuardIfCurrent = () => {
if (sendQueuedImmediatelyInFlightRef.current === queuedMessage.id) {
sendQueuedImmediatelyInFlightRef.current = null;
}
};
try {
// Set "interrupting" state immediately so UI shows "interrupting..." without flash.
storeRaw.setInterrupting(workspaceId);
const interruptResult = await api.workspace.interruptStream({
workspaceId,
options: { sendQueuedImmediately: true },
});
if (!interruptResult.success) {
clearInFlightGuardIfCurrent();
}
} catch (error) {
clearInFlightGuardIfCurrent();
throw error;
}
}, [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 () => {
if (transcriptOnly) return;
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" && canEditDisplayedUserMessage(msg)
);
if (!lastUserMessage) {
return;
}
setEditingMessage(buildEditingStateFromDisplayed(lastUserMessage));
disableAutoScroll(); // Show jump-to-bottom indicator
// Scroll to the message being edited
requestAnimationFrame(() => {
const scrollContainer = contentRef.current;
if (!scrollContainer) return;
findTranscriptMessageElement(scrollContainer, lastUserMessage.historyId)?.scrollIntoView({
behavior: "smooth",
block: "center",
});
});
}, [restoreQueuedDraft, contentRef, disableAutoScroll, setEditingMessage, transcriptOnly]);
const handleEditLastUserMessageClick = useCallback(() => {
void handleEditLastUserMessage();
}, [handleEditLastUserMessage]);
const handleCancelEdit = useCallback(() => {
setEditingMessage(undefined);
}, [setEditingMessage]);
const handleMessageSendStarted = useCallback(() => {
// Re-arm and pin before the send request crosses the IPC boundary. Waiting for
// send success can be too late because the backend may not resolve until the
// stream has already produced rows, leaving the first deltas offscreen when the
// user had previously scrolled up.
handleJumpToBottom();
}, [handleJumpToBottom]);
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();
}
// Slash-command send paths still report after backend success; keep this
// harmless duplicate pin so those paths also re-arm auto-scroll.
handleJumpToBottom();
},
[autoBackgroundOnSend, handleJumpToBottom]
);
const handleClearHistory = useCallback(
async (percentage = 1.0) => {
// Re-arm the tail before clearing so the empty/starting state owns the bottom.
handleJumpToBottom();
// Truncate history in backend
await api?.workspace.truncateHistory({ workspaceId, percentage });
},
[workspaceId, handleJumpToBottom, api]
);
const handleResetContext = useCallback(async (): Promise<"reset" | "noop"> => {
handleJumpToBottom();
const result = await api?.workspace.resetContext({ workspaceId });
if (!result?.success) {
throw new Error(result?.error ?? "Failed to reset context");
}
return result.data;
}, [workspaceId, handleJumpToBottom, api]);
const openInEditor = useOpenInEditor();
const handleOpenInEditor = useCallback(() => {
void openInEditor(workspaceId, namedWorkspacePath, runtimeConfig);
}, [workspaceId, namedWorkspacePath, openInEditor, runtimeConfig]);
// Intentionally no message/todo-driven auto-scroll effect here. Bottom pinning is
// owned by the scrollport/content ResizeObservers inside `useAutoScroll`, which
// pins viewport or content-size changes before paint. Calling `performAutoScroll`
// as a separate double-RAF on every delta used to race the RO pin, occasionally
// painting one frame at the wrong scrollTop (visible as a brief downward jitter).
const hasLoadedTranscriptRows = !workspaceState.loading && workspaceState.messages.length > 0;
// Reset transcript scroll ownership when switching workspaces. `jumpToBottom` both re-arms
// the ref-backed auto-scroll flag and pins any cached rows before paint; if rows are still
// hydrating, the next content resize owns the tail instead of showing the prior workspace's state.
useLayoutEffect(() => {
handleJumpToBottom();