-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseScrollLifecycle.ts
More file actions
759 lines (668 loc) · 27.3 KB
/
Copy pathuseScrollLifecycle.ts
File metadata and controls
759 lines (668 loc) · 27.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
/**
* useScrollLifecycle
*
* Simplified chat scroll lifecycle: always scroll to the bottom on task
* switch and auto-follow new messages while the user stays at the bottom.
*
* **Task switch:** enters `HYDRATING_PINNED_TO_BOTTOM`, fires a deferred
* scroll-to-bottom, then transitions to `ANCHORED_FOLLOWING` so
* `followOutput="auto"` keeps the list pinned.
*
* **Hydration window:** retries up to `MAX_HYDRATION_RETRIES` at
* `HYDRATION_RETRY_WINDOW_MS` intervals before giving up and entering
* `ANCHORED_FOLLOWING`.
*
* **User escape intent** (wheel-up / keyboard-nav-up / pointer-scroll-up /
* row expansion) moves to `USER_BROWSING_HISTORY`, sets
* `followOutput=false`.
*
* **Scroll-to-bottom button visibility:** `showScrollToBottom` reflects
* `!isAtBottom` in every lifecycle phase (except during the hydration
* window, where it is suppressed to avoid flicker). This means the button
* appears even during ANCHORED_FOLLOWING when transient layout changes
* momentarily pull the user off the bottom — the old behaviour required an
* explicit user scroll-up gesture first. The caller is expected to layer
* a blink / pulse animation on top of the button when a pending approval
* or question coexists with the scroll cue.
*/
import React, { useCallback, useEffect, useRef, useState } from "react"
import { useEvent } from "react-use"
import type { VirtuosoHandle } from "react-virtuoso"
import { vscode } from "@src/utils/vscode"
const HYDRATION_WINDOW_MS = 600
const HYDRATION_RETRY_WINDOW_MS = 160
const MAX_HYDRATION_RETRIES = 3
// ---------------------------------------------------------------------------
// Debug logging gate — set to true during scroll development only.
// Logs are posted to the Shofer Output Channel via webviewLog IPC.
// ---------------------------------------------------------------------------
const SCROLL_DEBUG = false
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type ScrollPhase = "HYDRATING_PINNED_TO_BOTTOM" | "ANCHORED_FOLLOWING" | "USER_BROWSING_HISTORY"
export type ScrollFollowDisengageSource = "wheel-up" | "row-expansion" | "keyboard-nav-up" | "pointer-scroll-up"
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const isEditableKeyboardTarget = (target: EventTarget | null): boolean => {
if (!(target instanceof HTMLElement)) {
return false
}
if (target.isContentEditable) {
return true
}
const tagName = target.tagName
return tagName === "INPUT" || tagName === "TEXTAREA" || tagName === "SELECT"
}
// ---------------------------------------------------------------------------
// Hook interface
// ---------------------------------------------------------------------------
export interface UseScrollLifecycleOptions {
virtuosoRef: React.RefObject<VirtuosoHandle | null>
scrollContainerRef: React.RefObject<HTMLDivElement | null>
taskTs: number | undefined
isStreaming: boolean
isHidden: boolean
hasTask: boolean
/** When true, skip the hydration scroll-to-bottom cycle on task switch.
* Use for re-entering already-completed or previously-viewed tasks
* where the user's scroll position should be preserved.
* The caller is responsible for snapshoting and restoring scrollTop
* per task (externally, via the Virtuoso's scrollable element). */
skipHydration?: boolean
}
export interface UseScrollLifecycleReturn {
scrollPhase: ScrollPhase
showScrollToBottom: boolean
handleRowHeightChange: (isTaller: boolean) => void
handleScrollToBottomClick: () => void
enterUserBrowsingHistory: (source: ScrollFollowDisengageSource) => void
followOutputCallback: () => "auto" | false
atBottomStateChangeCallback: (isAtBottom: boolean) => void
scrollToBottomAuto: () => void
isAtBottomRef: React.MutableRefObject<boolean>
scrollPhaseRef: React.MutableRefObject<ScrollPhase>
}
// ---------------------------------------------------------------------------
// Hook implementation
// ---------------------------------------------------------------------------
export function useScrollLifecycle({
virtuosoRef,
scrollContainerRef,
taskTs,
isStreaming,
isHidden,
hasTask,
skipHydration = false,
}: UseScrollLifecycleOptions): UseScrollLifecycleReturn {
// --- Mounted guard ---
const isMountedRef = useRef(true)
// --- Phase state ---
const [scrollPhase, setScrollPhase] = useState<ScrollPhase>("USER_BROWSING_HISTORY")
const scrollPhaseRef = useRef<ScrollPhase>("USER_BROWSING_HISTORY")
// --- Visibility state ---
const [showScrollToBottom, setShowScrollToBottom] = useState(false)
// --- Bottom detection ---
const isAtBottomRef = useRef(false)
// --- Hydration window ---
const isHydratingRef = useRef(false)
const hydrationTimeoutRef = useRef<number | null>(null)
const hydrationRetryCountRef = useRef(0)
// --- Pointer scroll tracking ---
const pointerScrollActiveRef = useRef(false)
const pointerScrollElementRef = useRef<HTMLElement | null>(null)
const pointerScrollLastTopRef = useRef<number | null>(null)
// --- Re-anchor frame ---
const reanchorAnimationFrameRef = useRef<number | null>(null)
// --- Disengage immune window ---
// Set when the user explicitly enters browse mode. While active,
// atBottomStateChange(true) from an in-flight programmatic scroll
// cannot snap the user back to ANCHORED_FOLLOWING.
const userDisengagedRef = useRef(false)
const userDisengagedTimeoutRef = useRef<number | null>(null)
// --- User-intent scroll-up flag ---
// Set synchronously by escape-intent detectors (wheel, keyboard, pointer)
// BEFORE calling enterUserBrowsingHistory. Checked by
// atBottomStateChangeCallback to prevent the "not-at-bottom during
// ANCHORED_FOLLOWING+streaming → auto-scroll-back" path from fighting
// genuine user scroll-up intent. Cleared on re-anchor or after a brief
// safety timeout.
const userIntentScrollUpRef = useRef(false)
const userIntentScrollUpTimeoutRef = useRef<number | null>(null)
// --- Previous taskTs tracker ---
// Tracks the last taskTs seen during render so we can detect task
// switches synchronously (before the new Virtuoso mounts).
const prevTaskTsRef = useRef(taskTs)
// -----------------------------------------------------------------------
// Render-phase ref synchronization (task switch)
// -----------------------------------------------------------------------
// When taskTs changes, synchronize scroll refs DURING the render phase
// — before the new Virtuoso mounts and fires atBottomStateChangeCallback.
// Without this, the callback reads stale refs from the previous task.
//
// This mirrors the Preload-Before-Publish Rule: refs that the Virtuoso
// consumes must be set before the Virtuoso is "published" (mounted).
if (taskTs !== prevTaskTsRef.current) {
const prevTs = prevTaskTsRef.current
prevTaskTsRef.current = taskTs
isAtBottomRef.current = false
userDisengagedRef.current = false
userIntentScrollUpRef.current = false
if (userDisengagedTimeoutRef.current !== null) {
window.clearTimeout(userDisengagedTimeoutRef.current)
userDisengagedTimeoutRef.current = null
}
if (userIntentScrollUpTimeoutRef.current !== null) {
window.clearTimeout(userIntentScrollUpTimeoutRef.current)
userIntentScrollUpTimeoutRef.current = null
}
const nextPhase: ScrollPhase = taskTs && !skipHydration ? "HYDRATING_PINNED_TO_BOTTOM" : "USER_BROWSING_HISTORY"
scrollPhaseRef.current = nextPhase
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text:
`[scroll:taskSwitch] prevTs=${prevTs ?? "none"} taskTs=${taskTs ?? "none"} ` +
`skipHydration=${skipHydration} → phase=${nextPhase}`,
})
}
}
// -----------------------------------------------------------------------
// Phase transitions
// -----------------------------------------------------------------------
const transitionScrollPhase = useCallback(
(nextPhase: ScrollPhase, _reason?: string) => {
if (scrollPhaseRef.current === nextPhase) {
return
}
const prev = scrollPhaseRef.current
scrollPhaseRef.current = nextPhase
setScrollPhase(nextPhase)
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text:
`[scroll:phase] ${prev} → ${nextPhase} ` +
`reason=${_reason ?? "?"} taskTs=${taskTs} isAtBottom=${isAtBottomRef.current}`,
})
}
},
[taskTs],
)
// -----------------------------------------------------------------------
// Scroll commands
// -----------------------------------------------------------------------
// Must be declared before the phase-transition callbacks that depend on them.
const scrollToBottomAuto = useCallback(() => {
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text: `[scroll:auto] scrollToIndex LAST taskTs=${taskTs}`,
})
}
virtuosoRef.current?.scrollToIndex({
index: "LAST",
align: "end",
behavior: "auto",
})
}, [virtuosoRef, taskTs])
const cancelReanchorFrame = useCallback(() => {
if (reanchorAnimationFrameRef.current !== null) {
cancelAnimationFrame(reanchorAnimationFrameRef.current)
reanchorAnimationFrameRef.current = null
}
}, [])
const enterAnchoredFollowing = useCallback(
(reason?: string) => {
transitionScrollPhase("ANCHORED_FOLLOWING", reason)
setShowScrollToBottom(false)
// Clear the user-intent flag when re-engaging follow mode.
userIntentScrollUpRef.current = false
},
[transitionScrollPhase],
)
const enterUserBrowsingHistory = useCallback(
(_source: ScrollFollowDisengageSource) => {
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text:
`[scroll:disengage] source=${_source} ` +
`prevPhase=${scrollPhaseRef.current} isAtBottom=${isAtBottomRef.current} ` +
`taskTs=${taskTs}`,
})
}
transitionScrollPhase("USER_BROWSING_HISTORY", _source)
setShowScrollToBottom(true)
// atBottomStateChangeCallback also sets showScrollToBottom
// based on isAtBottom, so the flag is always coherent even
// when Virtuoso hasn't yet reported the new scroll position.
// Open a brief immune window so any in-flight programmatic
// scroll-to-bottom that completes after this point cannot
// pull the user back to ANCHORED_FOLLOWING.
userDisengagedRef.current = true
if (userDisengagedTimeoutRef.current !== null) {
window.clearTimeout(userDisengagedTimeoutRef.current)
}
userDisengagedTimeoutRef.current = window.setTimeout(() => {
userDisengagedRef.current = false
userDisengagedTimeoutRef.current = null
// If the user scrolled back to the bottom *during* the immune
// window, atBottomStateChangeCallback's re-anchor was blocked by
// the `!userDisengagedRef` guard and nothing re-evaluates on its
// own — leaving us stuck in USER_BROWSING_HISTORY while sitting at
// the bottom with the scroll-to-bottom button still showing.
// Re-check now that the window has closed.
if (scrollPhaseRef.current === "USER_BROWSING_HISTORY" && isAtBottomRef.current) {
enterAnchoredFollowing("immune-window-expired-at-bottom")
}
}, 500)
// Clear the user-intent-scroll-up flag after a brief safety
// window. By this point atBottomStateChangeCallback has had
// time to see the flag and skip the auto-scroll-back.
if (userIntentScrollUpTimeoutRef.current !== null) {
window.clearTimeout(userIntentScrollUpTimeoutRef.current)
}
userIntentScrollUpTimeoutRef.current = window.setTimeout(() => {
userIntentScrollUpRef.current = false
userIntentScrollUpTimeoutRef.current = null
}, 200)
},
[transitionScrollPhase, taskTs, enterAnchoredFollowing],
)
const clearHydrationWindow = useCallback(() => {
isHydratingRef.current = false
hydrationRetryCountRef.current = 0
if (hydrationTimeoutRef.current !== null) {
window.clearTimeout(hydrationTimeoutRef.current)
hydrationTimeoutRef.current = null
}
}, [])
// -----------------------------------------------------------------------
// Scroll-to-bottom hydration (for new / never-viewed tasks)
// -----------------------------------------------------------------------
const finishHydrationWindow = useCallback(() => {
if (!isMountedRef.current || !isHydratingRef.current) {
return
}
if (scrollPhaseRef.current === "HYDRATING_PINNED_TO_BOTTOM") {
if (isAtBottomRef.current) {
enterAnchoredFollowing("hydration-complete")
} else if (hydrationRetryCountRef.current < MAX_HYDRATION_RETRIES) {
hydrationRetryCountRef.current++
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text: `[scroll:hydrate] retry ${hydrationRetryCountRef.current}/${MAX_HYDRATION_RETRIES} taskTs=${taskTs}`,
})
}
scrollToBottomAuto()
hydrationTimeoutRef.current = window.setTimeout(() => {
finishHydrationWindow()
}, HYDRATION_RETRY_WINDOW_MS)
return
} else {
// Retry budget exhausted. Keep anchored follow rather than
// downgrading to browsing mode due to non-user transient drift.
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text: `[scroll:hydrate] retries exhausted taskTs=${taskTs}`,
})
}
enterAnchoredFollowing("hydration-retry-exhausted")
}
}
clearHydrationWindow()
}, [clearHydrationWindow, enterAnchoredFollowing, scrollToBottomAuto, taskTs])
const startHydrationWindow = useCallback(() => {
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text: `[scroll:hydrate] START taskTs=${taskTs} windowMs=${HYDRATION_WINDOW_MS}`,
})
}
isHydratingRef.current = true
hydrationRetryCountRef.current = 0
if (hydrationTimeoutRef.current !== null) {
window.clearTimeout(hydrationTimeoutRef.current)
}
hydrationTimeoutRef.current = window.setTimeout(() => {
finishHydrationWindow()
}, HYDRATION_WINDOW_MS)
// Defer the initial scroll-to-bottom by two animation frames so the
// Virtuoso — which is re-keyed on task.ts — has time to mount and
// measure its items before we command a scroll.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (isHydratingRef.current) {
scrollToBottomAuto()
}
})
})
}, [finishHydrationWindow, scrollToBottomAuto, taskTs])
// -----------------------------------------------------------------------
// Lifecycle effects
// -----------------------------------------------------------------------
// Mounted guard + global cleanup
useEffect(() => {
isMountedRef.current = true
return () => {
isMountedRef.current = false
clearHydrationWindow()
cancelReanchorFrame()
if (userDisengagedTimeoutRef.current !== null) {
window.clearTimeout(userDisengagedTimeoutRef.current)
}
if (userIntentScrollUpTimeoutRef.current !== null) {
window.clearTimeout(userIntentScrollUpTimeoutRef.current)
}
}
}, [cancelReanchorFrame, clearHydrationWindow])
// Keep phase ref in sync with state
useEffect(() => {
scrollPhaseRef.current = scrollPhase
}, [scrollPhase])
// Task switch: enter hydration and scroll to the bottom.
// When skipHydration is true (e.g. re-entering a completed task),
// stay in USER_BROWSING_HISTORY so the user's previous scroll
// position is preserved.
useEffect(() => {
isAtBottomRef.current = false
clearHydrationWindow()
cancelReanchorFrame()
// Clear any disengage immune window from the previous task.
userDisengagedRef.current = false
if (userDisengagedTimeoutRef.current !== null) {
window.clearTimeout(userDisengagedTimeoutRef.current)
userDisengagedTimeoutRef.current = null
}
if (taskTs && !skipHydration) {
transitionScrollPhase("HYDRATING_PINNED_TO_BOTTOM")
setShowScrollToBottom(false)
startHydrationWindow()
} else {
transitionScrollPhase("USER_BROWSING_HISTORY")
setShowScrollToBottom(false)
}
return () => {
clearHydrationWindow()
cancelReanchorFrame()
}
}, [cancelReanchorFrame, clearHydrationWindow, skipHydration, startHydrationWindow, taskTs, transitionScrollPhase])
// -----------------------------------------------------------------------
// Row height change handler
// -----------------------------------------------------------------------
const handleRowHeightChange = useCallback(
(isTaller: boolean) => {
// Strict: while not in ANCHORED_FOLLOWING, never auto-scroll
if (
scrollPhaseRef.current === "USER_BROWSING_HISTORY" ||
scrollPhaseRef.current === "HYDRATING_PINNED_TO_BOTTOM"
) {
return
}
const shouldForcePinForAnchoredStreaming =
scrollPhaseRef.current === "ANCHORED_FOLLOWING" && isStreaming && !userIntentScrollUpRef.current
if (isAtBottomRef.current || shouldForcePinForAnchoredStreaming) {
if (SCROLL_DEBUG && shouldForcePinForAnchoredStreaming && !isAtBottomRef.current) {
vscode.postMessage({
type: "webviewLog",
text:
`[scroll:forcePin] isTaller=${isTaller} isAtBottom=${isAtBottomRef.current} ` +
`userIntent=${userIntentScrollUpRef.current} taskTs=${taskTs}`,
})
}
scrollToBottomAuto()
}
},
[isStreaming, scrollToBottomAuto, taskTs],
)
// -----------------------------------------------------------------------
// Scroll-to-bottom click handler
// -----------------------------------------------------------------------
const handleScrollToBottomClick = useCallback(() => {
enterAnchoredFollowing("scroll-to-bottom-click")
scrollToBottomAuto()
cancelReanchorFrame()
reanchorAnimationFrameRef.current = requestAnimationFrame(() => {
reanchorAnimationFrameRef.current = null
if (scrollPhaseRef.current === "ANCHORED_FOLLOWING") {
scrollToBottomAuto()
}
})
}, [cancelReanchorFrame, enterAnchoredFollowing, scrollToBottomAuto])
// -----------------------------------------------------------------------
// Virtuoso callback: followOutput
// -----------------------------------------------------------------------
const followOutputCallback = useCallback((): "auto" | false => {
return scrollPhaseRef.current === "USER_BROWSING_HISTORY" ? false : "auto"
}, [])
// -----------------------------------------------------------------------
// Virtuoso callback: atBottomStateChange
// -----------------------------------------------------------------------
//
// Scroll-to-bottom button visibility is computed FIRST (before any
// phase-transition or auto-scroll logic) so that the button is visible
// in EVERY case where the user is not at the bottom — including during
// ANCHORED_FOLLOWING when transient layout changes momentarily pull the
// user off the bottom. The only exception is the hydration window
// (initial scroll-to-bottom after a task switch), where we suppress the
// button to avoid a distracting flash.
//
// Previously the button only appeared after the phase had transitioned to
// USER_BROWSING_HISTORY, which required an explicit scroll-up gesture
// first. Now the caller (ChatView) can layer a blink
// animation on the button when a pending approval also exists, prompting
// the user to scroll down before they can see and act on the buttons.
const atBottomStateChangeCallback = useCallback(
(isAtBottom: boolean) => {
isAtBottomRef.current = isAtBottom
const currentPhase = scrollPhaseRef.current
// --- Scroll-to-bottom button visibility (computed first) ---
// Show the button in these cases:
// 1. USER_BROWSING_HISTORY — always show (re-anchor CTA).
// 2. ANCHORED_FOLLOWING / HYDRATING where !isAtBottom AND
// we are NOT about to auto-scroll-back:
// - Hydration: suppress during the hydration window.
// - Streaming safety-net: suppress when we're about to
// call scrollToBottomAuto() (line ~547 below) — avoids
// a one-frame flash before the re-scroll.
const streamingSafetyNet =
currentPhase === "ANCHORED_FOLLOWING" && isStreaming && !userIntentScrollUpRef.current
const shouldShow =
currentPhase === "USER_BROWSING_HISTORY"
? true
: !isAtBottom && !isHydratingRef.current && !streamingSafetyNet
setShowScrollToBottom(shouldShow)
// --- Phase-transition and auto-scroll logic ---
if (currentPhase === "USER_BROWSING_HISTORY") {
// Re-engage anchored follow when the user manually scrolls
// back to the bottom — but NOT during the brief disengage
// immune window (set by enterUserBrowsingHistory). Without
// this guard an in-flight programmatic scroll-to-bottom
// (e.g. hydration) would repin the user right after they
// escaped.
if (isAtBottom && !userDisengagedRef.current) {
enterAnchoredFollowing("user-scrolled-to-bottom")
}
return
}
if (!isAtBottom && isHydratingRef.current) {
return
}
if (isAtBottom) {
enterAnchoredFollowing("atBottomStateChange")
return
}
if (currentPhase === "ANCHORED_FOLLOWING" && !isAtBottom && pointerScrollActiveRef.current) {
enterUserBrowsingHistory("pointer-scroll-up")
return
}
if (currentPhase === "ANCHORED_FOLLOWING" && isStreaming && !userIntentScrollUpRef.current) {
if (SCROLL_DEBUG) {
vscode.postMessage({
type: "webviewLog",
text:
`[scroll:safetyNet] streaming re-scroll ` +
`isAtBottom=${isAtBottom} userIntentScrollUp=${userIntentScrollUpRef.current} ` +
`taskTs=${taskTs}`,
})
}
scrollToBottomAuto()
return
}
// Not-at-bottom while ANCHORED_FOLLOWING (non-streaming).
// Cause C: a bare not-at-bottom is NOT a reliable "user scrolled up"
// signal — it also fires when a row collapses, a late image loads, or
// the FileChangesPanel appears/resizes. Disengaging on those spuriously
// ejected the user from follow-mode and flashed the scroll-to-bottom
// button. Genuine scroll-up gestures (wheel / keyboard / pointer-drag)
// already set `userIntentScrollUpRef` and disengage via their own
// handlers, so require that corroborating flag here before disengaging.
if (currentPhase === "ANCHORED_FOLLOWING" && !isAtBottom && !isStreaming && userIntentScrollUpRef.current) {
enterUserBrowsingHistory("pointer-scroll-up")
return
}
},
[enterAnchoredFollowing, enterUserBrowsingHistory, isStreaming, scrollToBottomAuto, taskTs],
)
// -----------------------------------------------------------------------
// User intent: wheel
// -----------------------------------------------------------------------
const handleWheel = useCallback(
(event: Event) => {
const wheelEvent = event as WheelEvent
if (wheelEvent.deltaY < 0 && scrollContainerRef.current?.contains(wheelEvent.target as Node)) {
// Set the flag synchronously BEFORE the phase transition so
// atBottomStateChangeCallback can see it even if it fires
// before enterUserBrowsingHistory completes.
userIntentScrollUpRef.current = true
enterUserBrowsingHistory("wheel-up")
}
},
[enterUserBrowsingHistory, scrollContainerRef],
)
// Capture phase: must fire BEFORE the wheel event reaches Virtuoso's
// internal scrollable element. Without this, Virtuoso processes the
// scroll first → atBottomStateChange(false) fires while
// scrollPhaseRef is still ANCHORED_FOLLOWING + isStreaming →
// scrollToBottomAuto() snaps the user back to the bottom before
// handleWheel ever gets a chance to set userIntentScrollUpRef.
useEvent("wheel", handleWheel, window, { passive: true, capture: true })
// -----------------------------------------------------------------------
// User intent: pointer drag
// -----------------------------------------------------------------------
const handlePointerDown = useCallback(
(event: Event) => {
const pointerEvent = event as PointerEvent
const pointerTarget = pointerEvent.target
if (!(pointerTarget instanceof HTMLElement)) {
pointerScrollActiveRef.current = false
pointerScrollElementRef.current = null
pointerScrollLastTopRef.current = null
return
}
if (!scrollContainerRef.current?.contains(pointerTarget)) {
pointerScrollActiveRef.current = false
pointerScrollElementRef.current = null
pointerScrollLastTopRef.current = null
return
}
const scroller =
(pointerTarget.closest(".scrollable") as HTMLElement | null) ??
(pointerTarget.scrollHeight > pointerTarget.clientHeight ? pointerTarget : null)
pointerScrollActiveRef.current = scroller !== null
pointerScrollElementRef.current = scroller
pointerScrollLastTopRef.current = scroller?.scrollTop ?? null
},
[scrollContainerRef],
)
const handlePointerEnd = useCallback(() => {
pointerScrollActiveRef.current = false
pointerScrollElementRef.current = null
pointerScrollLastTopRef.current = null
}, [])
const handlePointerActiveScroll = useCallback(
(event: Event) => {
if (!pointerScrollActiveRef.current) {
return
}
const scrollTarget = event.target
if (!(scrollTarget instanceof HTMLElement)) {
return
}
if (!scrollContainerRef.current?.contains(scrollTarget)) {
return
}
if (pointerScrollElementRef.current !== scrollTarget) {
return
}
const previousTop = pointerScrollLastTopRef.current
const currentTop = scrollTarget.scrollTop
pointerScrollLastTopRef.current = currentTop
if (previousTop !== null && currentTop < previousTop) {
// Set the flag synchronously BEFORE the phase transition so
// atBottomStateChangeCallback can see it even if it fires
// before enterUserBrowsingHistory completes.
userIntentScrollUpRef.current = true
enterUserBrowsingHistory("pointer-scroll-up")
}
},
[enterUserBrowsingHistory, scrollContainerRef],
)
useEvent("pointerdown", handlePointerDown, window, { passive: true })
useEvent("pointerup", handlePointerEnd, window, { passive: true })
useEvent("pointercancel", handlePointerEnd, window, { passive: true })
useEvent("scroll", handlePointerActiveScroll, window, { passive: true, capture: true })
// -----------------------------------------------------------------------
// User intent: keyboard navigation
// -----------------------------------------------------------------------
const handleScrollKeyDown = useCallback(
(event: Event) => {
const keyEvent = event as KeyboardEvent
if (!hasTask || isHidden) {
return
}
if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey) {
return
}
if (keyEvent.key !== "PageUp" && keyEvent.key !== "Home" && keyEvent.key !== "ArrowUp") {
return
}
if (isEditableKeyboardTarget(keyEvent.target)) {
return
}
const activeElement = document.activeElement
const focusInsideChat =
activeElement instanceof HTMLElement && !!scrollContainerRef.current?.contains(activeElement)
const eventTargetInsideChat =
keyEvent.target instanceof Node && !!scrollContainerRef.current?.contains(keyEvent.target)
if (focusInsideChat || eventTargetInsideChat || activeElement === document.body) {
// Set the flag synchronously BEFORE the phase transition so
// atBottomStateChangeCallback can see it even if it fires
// before enterUserBrowsingHistory completes.
userIntentScrollUpRef.current = true
enterUserBrowsingHistory("keyboard-nav-up")
}
},
[enterUserBrowsingHistory, hasTask, isHidden, scrollContainerRef],
)
useEvent("keydown", handleScrollKeyDown, window)
// -----------------------------------------------------------------------
// Return public API
// -----------------------------------------------------------------------
return {
scrollPhase,
showScrollToBottom,
handleRowHeightChange,
handleScrollToBottomClick,
enterUserBrowsingHistory,
followOutputCallback,
atBottomStateChangeCallback,
scrollToBottomAuto,
isAtBottomRef,
scrollPhaseRef,
}
}