@kabmo-labs/kabmo 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +1 -1
  3. package/dist/client/static/js/index-28pwtt69.css +1 -0
  4. package/dist/client/static/js/{index-nfsg1jpt.js → index-mx658m43.js} +624 -624
  5. package/marketplace/plugins/command-runner/README.md +5 -3
  6. package/marketplace/plugins/command-runner/package.json +2 -2
  7. package/marketplace/plugins/command-runner/src/app.tsx +3 -3
  8. package/marketplace/plugins/command-runner/src/panel/Groups.test.tsx +25 -21
  9. package/marketplace/plugins/command-runner/src/panel/Groups.tsx +4 -1
  10. package/marketplace/plugins/command-runner/src/server/ring.test.ts +41 -0
  11. package/marketplace/plugins/command-runner/src/server/run-types.ts +6 -0
  12. package/marketplace/plugins/command-runner/src/server/runner-harness.ts +69 -0
  13. package/marketplace/plugins/command-runner/src/server/runner-path.test.ts +127 -0
  14. package/marketplace/plugins/command-runner/src/server/runner.test.ts +2 -72
  15. package/marketplace/plugins/command-runner/src/server/runner.ts +31 -3
  16. package/package.json +2 -2
  17. package/src/client/components/common/session-row/index.tsx +11 -1
  18. package/src/client/components/common/session-row/session-row.test.tsx +10 -0
  19. package/src/client/components/layout/session-sidebar/modern/Skeleton.tsx +5 -4
  20. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +11 -2
  21. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +111 -0
  22. package/src/client/components/mobile/LayoutWrapper.tsx +11 -10
  23. package/src/client/components/mobile/open-file-payload.test.ts +29 -1
  24. package/src/client/components/mobile/open-file-payload.ts +28 -0
  25. package/src/client/components/settings/Modal.tsx +2 -2
  26. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +1 -0
  27. package/src/client/components/workspace/chat-timeline/ThinkingSection.test.tsx +117 -0
  28. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +10 -9
  29. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +21 -1
  30. package/src/client/components/workspace/editor/index.tsx +6 -8
  31. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +16 -2
  32. package/src/client/components/workspace/git-panel/branch-modal/index.tsx +4 -3
  33. package/src/client/components/workspace/git-panel/commit-modal/index.tsx +1 -1
  34. package/src/client/hooks/chat/timeline/index.ts +3 -6
  35. package/src/client/hooks/chat/timeline/jump-landing.ts +121 -0
  36. package/src/client/hooks/chat/timeline/jump-rail.ts +19 -10
  37. package/src/client/hooks/chat/timeline/row-window-reveal.ts +130 -0
  38. package/src/client/hooks/chat/timeline/row-window.test.ts +35 -0
  39. package/src/client/hooks/chat/timeline/row-window.ts +100 -134
  40. package/src/client/hooks/chat/timeline/scroll-probe.test-util.ts +23 -10
  41. package/src/client/hooks/chat/timeline/scroll.test.ts +61 -4
  42. package/src/client/hooks/chat/timeline/scroll.ts +77 -26
  43. package/src/client/hooks/chat/timeline/thinking-open.ts +67 -0
  44. package/src/client/hooks/workspace/missing-files.test.ts +20 -3
  45. package/src/client/hooks/workspace/missing-files.ts +41 -7
  46. package/src/client/tailwind.css +12 -1
  47. package/src/server/routes/fs/exists.test.ts +26 -1
  48. package/src/shared/lib/chat/timeline/trace-groups.test.ts +12 -0
  49. package/src/shared/lib/chat/timeline/trace-groups.ts +29 -2
  50. package/src/shared/lib/workspace/session-state/store.ts +5 -0
  51. package/dist/client/static/js/index-tsgy3gd1.css +0 -1
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The bottom jump's LANDING: who owns the viewport, and for how long.
8
+ *
9
+ * Split out of `scroll.ts` so that hook stays under the repo's per-file
10
+ * ceiling; the loop is self-contained and talks to the hook only through refs,
11
+ * which is what lets it run for a couple of seconds without a re-render.
12
+ *
13
+ * A one-shot `scrollTo` is not enough on this timeline, for two reasons that
14
+ * both come from the mounted row window (`row-window.ts`):
15
+ *
16
+ * - The rows a jump passes over mount as it goes, and every measurement
17
+ * replaces an estimate with a real height — so `scrollHeight` changes DURING
18
+ * the jump and the target it was issued against is stale. A landing short of
19
+ * the tail re-reads as "the reader is a few hundred px up", which is exactly
20
+ * the state the scroll-bottom button exists for: the button stays up, and the
21
+ * next click finishes the job. That is the reported "it sometimes does not
22
+ * work until I scroll the rest myself".
23
+ * - A measurement above the viewport moves the tail down, and the row window's
24
+ * own correction then writes a position under the animation. So while this
25
+ * watch is armed it is the ONLY writer: the content observer and the row
26
+ * window both stand down (`jumpActiveRef`), and a competing instant pin is
27
+ * what made a landing read as a snap instead of one scroll.
28
+ *
29
+ * The guard is released by the LANDING, never by a clock: a timer released it
30
+ * while a long session was still measuring, and the observer then finished the
31
+ * jump with a snap.
32
+ */
33
+
34
+ import type { RefObject } from 'preact/compat';
35
+
36
+ /** Frames the viewport must sit at the tail before a jump counts as landed.
37
+ * Three, not one: the correction that lands a stalled jump produces its own
38
+ * scroll event, and a single frame of stillness can be the gap between two
39
+ * layout commits that are still moving the tail. */
40
+ const JUMP_SETTLE_FRAMES = 3;
41
+
42
+ /** Frames without any movement, with the tail still out of reach, that mean
43
+ * the smooth animation is not running (dropped, or never started). */
44
+ const JUMP_STALL_FRAMES = 4;
45
+
46
+ /** A jump's landing deadline. A layout that never settles must not spin the
47
+ * watch forever; past this the viewport is released and the content
48
+ * observer's normal follow pin takes over. */
49
+ const JUMP_DEADLINE_MS = 2000;
50
+
51
+ export interface JumpLandingDeps {
52
+ /** The timeline's scroll container, read at call time. */
53
+ scrollRef: RefObject<HTMLDivElement>;
54
+ /** The guard this watch owns. `true` while a landing is in flight. */
55
+ jumpActiveRef: RefObject<boolean>;
56
+ /** Re-aim at the tail, keeping the animation continuous. */
57
+ pinToBottom: (behavior: ScrollBehavior) => void;
58
+ }
59
+
60
+ export interface JumpLanding {
61
+ /** Take the viewport: releases the guard when the tail is reached. */
62
+ start: () => void;
63
+ /** Abandon the current landing (unmount, or a new jump replacing it). */
64
+ stop: () => void;
65
+ }
66
+
67
+ /** Build the watch. Stable for the life of the hook; a second `start` replaces
68
+ * the first, so two clicks cannot leave two loops fighting for the viewport. */
69
+ export function createJumpLanding({ scrollRef, jumpActiveRef, pinToBottom }: JumpLandingDeps): JumpLanding {
70
+ let frame: number | null = null;
71
+ let deadline = 0;
72
+
73
+ const stop = (): void => {
74
+ if (frame !== null) cancelAnimationFrame(frame);
75
+ frame = null;
76
+ };
77
+
78
+ const start = (): void => {
79
+ stop();
80
+ deadline = performance.now() + JUMP_DEADLINE_MS;
81
+ let lastTop = -1;
82
+ let still = 0;
83
+ let stalled = 0;
84
+ const step = (): void => {
85
+ frame = null;
86
+ const el = scrollRef.current;
87
+ if (!el || !jumpActiveRef.current) return;
88
+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
89
+ const moved = Math.abs(el.scrollTop - lastTop) > 1;
90
+ lastTop = el.scrollTop;
91
+ if (distance <= 1) {
92
+ stalled = 0;
93
+ still += 1;
94
+ if (still >= JUMP_SETTLE_FRAMES) {
95
+ jumpActiveRef.current = false;
96
+ return;
97
+ }
98
+ } else {
99
+ still = 0;
100
+ stalled = moved ? 0 : stalled + 1;
101
+ // Still for a few frames with the tail out of reach: the animation is
102
+ // not running (a browser drops a smooth programmatic scroll when the
103
+ // content it scrolls through is replaced), or it landed against a
104
+ // target the measurements have since outgrown. Re-aim — smooth, so a
105
+ // continuation never reads as a second, separate jump.
106
+ if (stalled >= JUMP_STALL_FRAMES) {
107
+ stalled = 0;
108
+ pinToBottom('smooth');
109
+ }
110
+ }
111
+ if (performance.now() > deadline) {
112
+ jumpActiveRef.current = false;
113
+ return;
114
+ }
115
+ frame = requestAnimationFrame(step);
116
+ };
117
+ frame = requestAnimationFrame(step);
118
+ };
119
+
120
+ return { start, stop };
121
+ }
@@ -18,8 +18,8 @@
18
18
  */
19
19
 
20
20
  import { useMemo } from 'preact/hooks';
21
- import type { RefObject } from 'preact/compat';
22
21
  import { useTimelineRowWindow, type TimelineRowWindow } from '@/client/hooks/chat/timeline/row-window';
22
+ import type { ChatTimelineScrollResult } from '@/client/hooks/chat/timeline/scroll';
23
23
  import { useRailJump } from '@/client/hooks/chat/timeline/rail-jump';
24
24
  import { useUserTurns } from '@/client/hooks/chat/timeline/user-turns';
25
25
  import type { ChatMessageData, UserTurnRef } from '@/shared/types';
@@ -30,12 +30,15 @@ export interface UseTimelineJumpRailDeps {
30
30
  messages: ChatMessageData[];
31
31
  /** Pages history until the turn's row is mounted (session-pagination). */
32
32
  jumpToTurn: (id: string, index: number) => Promise<boolean>;
33
- /** Scroll hook's follow flag, held off for the whole jump. */
34
- followRef: RefObject<boolean>;
35
- /** The timeline's scroll container. */
36
- scrollRef: RefObject<HTMLDivElement>;
37
- /** The same container as state — see `useTimelineRowWindow`. */
38
- scrollNode: HTMLDivElement | null;
33
+ /**
34
+ * The scroll hook's own state. Three of its refs are the row window's
35
+ * contract, and taking the result keeps them described in ONE place:
36
+ * `followRef` (held off for the whole jump), the container (`scrollRef` and
37
+ * `scrollNode`), `jumpActiveRef` (the row window writes no position while a
38
+ * bottom jump lands) and `jumpCountRef` (a new value claims the tail, so the
39
+ * landing is not corrected back to the reading anchor).
40
+ */
41
+ scroll: ChatTimelineScrollResult;
39
42
  }
40
43
 
41
44
  export interface TimelineJumpRail {
@@ -49,15 +52,21 @@ export interface TimelineJumpRail {
49
52
  }
50
53
 
51
54
  export function useTimelineJumpRail(deps: UseTimelineJumpRailDeps): TimelineJumpRail {
52
- const { sessionId, messages, jumpToTurn, followRef, scrollRef, scrollNode } = deps;
55
+ const { sessionId, messages, jumpToTurn, scroll } = deps;
53
56
  const rowIds = useMemo(() => messages.map((message) => message.id), [messages]);
54
- const rowWindow = useTimelineRowWindow({ ids: rowIds, scrollRef, scrollNode });
57
+ const rowWindow = useTimelineRowWindow({
58
+ ids: rowIds,
59
+ scrollRef: scroll.scrollRef,
60
+ scrollNode: scroll.scrollNode,
61
+ jumpActiveRef: scroll.jumpActiveRef,
62
+ jumpCountRef: scroll.jumpCountRef,
63
+ });
55
64
  const { turns: userTurns, jumping: jumpingTurn, jumpToTurn: pagedJumpToTurn } = useUserTurns({
56
65
  sessionId,
57
66
  messages,
58
67
  jumpToTurn,
59
68
  revealRow: rowWindow.revealRow,
60
69
  });
61
- const jumpToUserTurn = useRailJump(pagedJumpToTurn, { followRef, scrollRef });
70
+ const jumpToUserTurn = useRailJump(pagedJumpToTurn, { followRef: scroll.followRef, scrollRef: scroll.scrollRef });
62
71
  return { userTurns, jumpingTurn, jumpToUserTurn, rowWindow };
63
72
  }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `revealRow` — scroll a row into the middle of the viewport, mounting it if the
8
+ * window does not cover it yet.
9
+ *
10
+ * Split out of `row-window.ts` so that hook stays under the repo's per-file
11
+ * ceiling; the loop is a self-contained piece with its own timing rules, and it
12
+ * talks to the hook only through refs (which is what lets it keep correcting for
13
+ * seconds without a re-render).
14
+ *
15
+ * The landing is never a single write. The rows a jump just mounted are
16
+ * measured on later commits — a tool card's output arrives through a deferred
17
+ * highlight, an image decodes, an accordion opens — and every measurement above
18
+ * the target moves it. Measured here, a fixed short window left a jump to the
19
+ * newest turn 300 px short of the tail: outside `scroll.ts`'s 100 px follow
20
+ * threshold, so the stream silently stopped following after the jump.
21
+ */
22
+
23
+ import type { RowLayout } from '@/shared/lib/chat/timeline/row-window';
24
+ import { rowIndex, rowScrollOffset } from '@/shared/lib/chat/timeline/row-window';
25
+
26
+ /** How long a reveal keeps correcting after it first moves the viewport. */
27
+ const REVEAL_SETTLE_MS = 3000;
28
+
29
+ /** Consecutive still frames that end a reveal early — the layout has settled. */
30
+ const REVEAL_STILL_FRAMES = 10;
31
+
32
+ /** How long a reveal waits for a row the pager is still bringing in. */
33
+ const REVEAL_DEADLINE_MS = 3000;
34
+
35
+ /**
36
+ * Write a scroll position that is meant to LAND, not to animate.
37
+ *
38
+ * The timeline container carries Tailwind's `scroll-smooth`, and CSS
39
+ * `scroll-behavior` applies to a `scrollTop` ASSIGNMENT too (CSSOM-View:
40
+ * the setter scrolls with `behavior: auto`, which resolves to the element's
41
+ * computed `scroll-behavior`). So `el.scrollTop = target` started a smooth
42
+ * animation, the reveal's correction loop re-targeted it every frame, and the
43
+ * jump was left mid-flight wherever the loop stopped — measured on a
44
+ * 240-message session: the trace walked 9 804 → 6 504 px and stayed there.
45
+ * `behavior: 'instant'` is the one value CSS cannot override.
46
+ */
47
+ export function writeScrollTop(el: HTMLElement, top: number): void {
48
+ if (Math.abs(el.scrollTop - top) <= 1) return;
49
+ el.scrollTo({ top, behavior: 'instant' });
50
+ }
51
+
52
+ export interface RevealRowDeps {
53
+ /** The timeline's scroll container, read at call time (it is swapped in late). */
54
+ scrollRef: { current: HTMLDivElement | null };
55
+ idsRef: { current: readonly string[] };
56
+ layoutRef: { current: RowLayout };
57
+ viewportRef: { current: number };
58
+ /** Set when the landing is the newest turn; the tail is an anchor of its own. */
59
+ tailPinRef: { current: boolean };
60
+ /** True while a reveal owns the viewport, so a measurement stands down. */
61
+ revealingRef: { current: boolean };
62
+ /** Bumped per reveal: a superseded one stops writing. */
63
+ generationRef: { current: number };
64
+ }
65
+
66
+ /**
67
+ * Build the reveal function. Every dep is a ref, so the returned function is
68
+ * stable for the life of the hook and never re-creates the loop mid-flight.
69
+ */
70
+ export function createRevealRow(deps: RevealRowDeps): (id: string) => Promise<void> {
71
+ return (id: string): Promise<void> => {
72
+ const el = deps.scrollRef.current;
73
+ if (!el) return Promise.resolve();
74
+ const deadline = Date.now() + REVEAL_DEADLINE_MS;
75
+ const settleBy = Date.now() + REVEAL_SETTLE_MS;
76
+ // Supersedes an earlier reveal: two rail clicks in a row must land on the
77
+ // SECOND turn, not race each other to the first one's position.
78
+ const generation = (deps.generationRef.current += 1);
79
+ deps.revealingRef.current = true;
80
+ const { promise, resolve } = Promise.withResolvers<void>();
81
+ let stillFrames = 0;
82
+ let lastTop = -1;
83
+ const finish = (): void => {
84
+ // Only the reveal that still owns the generation clears the flag: a
85
+ // superseded one must not hand the viewport to a correction while its
86
+ // successor is still flying.
87
+ if (generation === deps.generationRef.current) deps.revealingRef.current = false;
88
+ resolve();
89
+ };
90
+ const step = (): void => {
91
+ if (generation !== deps.generationRef.current) {
92
+ finish();
93
+ return;
94
+ }
95
+ const rows = deps.idsRef.current;
96
+ const index = rowIndex(rows, id);
97
+ if (index < 0) {
98
+ // The pager may still be bringing the row in; keep asking until the
99
+ // deadline rather than scrolling to a row that does not exist yet.
100
+ if (Date.now() < deadline) requestAnimationFrame(step);
101
+ else finish();
102
+ return;
103
+ }
104
+ const current = deps.layoutRef.current;
105
+ const view = el.clientHeight || deps.viewportRef.current;
106
+ // The newest turn is the TAIL, not the centre of the last row: that is
107
+ // what the reader means by jumping there, and it is what lets follow mode
108
+ // re-engage (the scroll handler's threshold is 100 px).
109
+ deps.tailPinRef.current = index === rows.length - 1;
110
+ writeScrollTop(
111
+ el,
112
+ deps.tailPinRef.current
113
+ ? Math.max(0, el.scrollHeight - view)
114
+ : rowScrollOffset(current, index, view),
115
+ );
116
+ // A row that was just mounted is measured on a later commit; the
117
+ // corrections land on the MEASURED position rather than the estimate the
118
+ // first write used.
119
+ stillFrames = Math.abs(el.scrollTop - lastTop) <= 1 ? stillFrames + 1 : 0;
120
+ lastTop = el.scrollTop;
121
+ if (stillFrames >= REVEAL_STILL_FRAMES || Date.now() >= settleBy) {
122
+ finish();
123
+ return;
124
+ }
125
+ requestAnimationFrame(step);
126
+ };
127
+ requestAnimationFrame(step);
128
+ return promise;
129
+ };
130
+ }
@@ -208,4 +208,39 @@ describe('useTimelineRowWindow', () => {
208
208
 
209
209
  expect(scroller.scrollTop).toBe(soloTop);
210
210
  });
211
+
212
+ test('a row growing above the viewport keeps the mounted window and the reader', async () => {
213
+ // An expanded thinking block grows the row it sits in. The correction has
214
+ // to land in the SAME commit as the measurement: a deferred restore runs
215
+ // with the pre-measurement layout, so the next commit has no anchor left,
216
+ // the window re-derives from a stale `scrollTop`, and the rows at its edge
217
+ // unmount — measured in the browser as three rows removed and re-added per
218
+ // expand, which throws away every block's local state (an expanded thought
219
+ // snapping shut).
220
+ const scroller = installScroller(20_000);
221
+ const heights = new Map<string, number>();
222
+ for (let i = 0; i < ROWS; i += 1) {
223
+ const node = document.createElement('div');
224
+ node.dataset.rowId = `r-${i}`;
225
+ node.getBoundingClientRect = () => ({ height: heights.get(node.dataset.rowId!) ?? ROW_HEIGHT }) as DOMRect;
226
+ scroller.appendChild(node);
227
+ }
228
+ await mount(scroller);
229
+ await act(async () => {});
230
+ const opened = rowWindow!.start;
231
+ const before = scroller.scrollTop;
232
+ expect(opened).toBeGreaterThan(0);
233
+
234
+ heights.set('r-50', ROW_HEIGHT + 1_000);
235
+ // What the timeline does on the click: a re-render, then the measure
236
+ // effect adopts the grown row.
237
+ await act(async () => { render(h(Probe, { node: scroller }), container); });
238
+ drainFrames();
239
+ await act(async () => {});
240
+
241
+ expect(rowWindow!.start).toBe(opened);
242
+ // The row the reader was on kept its place: the 1 000 px that appeared
243
+ // above it moved the offset by exactly that much.
244
+ expect(scroller.scrollTop).toBe(before + 1_000);
245
+ });
211
246
  });
@@ -30,26 +30,9 @@
30
30
  */
31
31
 
32
32
  import type { RefObject } from 'preact/compat';
33
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
34
- import { layoutTimelineRows, rowIndex, rowScrollOffset, timelineWindow } from '@/shared/lib/chat/timeline/row-window';
35
-
36
- /**
37
- * How long a reveal keeps correcting after it first moves the viewport.
38
- *
39
- * Wall-clock rather than a frame count: the rows it just mounted are measured on
40
- * later commits (a tool card's output arrives through a deferred highlight, an
41
- * image decodes), and every measurement above the target moves it. Measured
42
- * here, a fixed short window left a jump to the newest turn 300 px short of the
43
- * tail — outside the follow-mode threshold, so the stream stopped following
44
- * after the jump.
45
- */
46
- const REVEAL_SETTLE_MS = 3000;
47
-
48
- /** Consecutive still frames that end a reveal early — the layout has settled. */
49
- const REVEAL_STILL_FRAMES = 10;
50
-
51
- /** How long a reveal waits for a row the pager is still bringing in. */
52
- const REVEAL_DEADLINE_MS = 3000;
33
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
34
+ import { layoutTimelineRows, rowIndex, timelineWindow } from '@/shared/lib/chat/timeline/row-window';
35
+ import { createRevealRow, writeScrollTop } from '@/client/hooks/chat/timeline/row-window-reveal';
53
36
 
54
37
  /** A measurement is only adopted when it differs by more than this. */
55
38
  const MEASURE_EPSILON_PX = 0.5;
@@ -58,23 +41,6 @@ const MEASURE_EPSILON_PX = 0.5;
58
41
  * `FOLLOW_BOTTOM_THRESHOLD_PX` in `scroll.ts`: below it, follow mode is on. */
59
42
  const TAIL_ANCHOR_PX = 100;
60
43
 
61
- /**
62
- * Write a scroll position that is meant to LAND, not to animate.
63
- *
64
- * The timeline container carries Tailwind's `scroll-smooth`, and CSS
65
- * `scroll-behavior` applies to a `scrollTop` ASSIGNMENT too (CSSOM-View:
66
- * the setter scrolls with `behavior: auto`, which resolves to the element's
67
- * computed `scroll-behavior`). So `el.scrollTop = target` started a smooth
68
- * animation, the reveal's correction loop re-targeted it every frame, and the
69
- * jump was left mid-flight wherever the loop stopped — measured on a
70
- * 240-message session: the trace walked 9 804 → 6 504 px and stayed there.
71
- * `behavior: 'instant'` is the one value CSS cannot override.
72
- */
73
- function writeScrollTop(el: HTMLElement, top: number): void {
74
- if (Math.abs(el.scrollTop - top) <= 1) return;
75
- el.scrollTo({ top, behavior: 'instant' });
76
- }
77
-
78
44
  export interface TimelineRowWindow {
79
45
  /** First mounted row index (inclusive). */
80
46
  start: number;
@@ -111,11 +77,30 @@ export interface UseTimelineRowWindowDeps {
111
77
  * wrote `scrollTop` into a spacer and mounted nothing.
112
78
  */
113
79
  scrollNode: HTMLDivElement | null;
80
+ /** The scroll hook's bottom-jump guard. While a jump to the tail is landing
81
+ * it OWNS the position: this hook still adopts measurements and still
82
+ * re-lays the window, but writes no `scrollTop` — a correction written under
83
+ * the animation drags the viewport back and the jump has to be re-aimed,
84
+ * which is what reads as the button "jumping in pieces". */
85
+ jumpActiveRef?: RefObject<boolean>;
86
+ /** The scroll hook's bottom-jump counter. A new value means the reader asked
87
+ * for the TAIL, so this hook claims the tail pin: without it the very next
88
+ * measurement wrote the OLD reading anchor back over the landing (measured:
89
+ * the jump reached the bottom and the correction pulled the viewport
90
+ * 2 000 px back up, 217 px short of the tail once the stream grew again). */
91
+ jumpCountRef?: RefObject<number>;
114
92
  /** False renders every row (a short list, or a surface without a scroller). */
115
93
  enabled?: boolean;
116
94
  }
117
95
 
118
- export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = true }: UseTimelineRowWindowDeps): TimelineRowWindow {
96
+ export function useTimelineRowWindow({
97
+ ids,
98
+ scrollRef,
99
+ scrollNode,
100
+ jumpActiveRef,
101
+ jumpCountRef,
102
+ enabled = true,
103
+ }: UseTimelineRowWindowDeps): TimelineRowWindow {
119
104
  // Heights of rows that have been on screen at least once, by id — so a row
120
105
  // keeps its height across being unmounted, which is what keeps the scrollbar
121
106
  // steady while the reader moves through a long session.
@@ -126,12 +111,6 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
126
111
  const [viewport, setViewport] = useState(0);
127
112
  // The scroll container. STATE, not the ref: see `scrollNode` in the deps.
128
113
  const element = scrollNode;
129
- // The row at the top of the viewport, captured before a re-layout so the
130
- // reader's position can be restored after it. `scrollTop` is recorded with it
131
- // so a restore can tell that SOMETHING ELSE moved the viewport in between —
132
- // the opening jump to the tail, a rail jump, the follow pin — and stand down
133
- // instead of writing the reader's old position back over it.
134
- const anchorRef = useRef<{ id: string; offset: number; scrollTop: number; tail: boolean } | null>(null);
135
114
  /**
136
115
  * The viewport belongs to the BOTTOM until the reader scrolls away.
137
116
  *
@@ -143,6 +122,17 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
143
122
  * the stream stopped following after the jump.
144
123
  */
145
124
  const tailPinRef = useRef(false);
125
+ // Bottom jumps this hook has already claimed for the tail. A new count means
126
+ // the reader asked for the BOTTOM, so the tail pin belongs on: without it the
127
+ // next measurement corrected the viewport back to the reading anchor it had
128
+ // before the jump, and the landing was undone the moment the jump settled.
129
+ const seenJumpCountRef = useRef(jumpCountRef?.current ?? 0);
130
+ useLayoutEffect(() => {
131
+ const count = jumpCountRef?.current ?? 0;
132
+ if (count === seenJumpCountRef.current) return;
133
+ seenJumpCountRef.current = count;
134
+ tailPinRef.current = true;
135
+ });
146
136
 
147
137
  const layout = useMemo(
148
138
  () => layoutTimelineRows(ids, measuredRef.current),
@@ -157,6 +147,12 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
157
147
  viewportRef.current = viewport;
158
148
  // Bumped per reveal so a superseded one stops writing.
159
149
  const revealGenerationRef = useRef(0);
150
+ /**
151
+ * A reveal is flying: it re-writes its target every frame until it settles,
152
+ * so a measurement must not correct the position underneath it (the two
153
+ * would trade the viewport). See `adopt`.
154
+ */
155
+ const revealingRef = useRef(false);
160
156
 
161
157
  const range = useMemo(
162
158
  () => (enabled ? timelineWindow(layout, scrollTop, viewport) : { start: 0, end: ids.length, padTop: 0, padBottom: 0 }),
@@ -220,26 +216,54 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
220
216
  return changed;
221
217
  };
222
218
  const adopt = (): void => {
219
+ // Which row the reader is looking at, under the geometry they are still
220
+ // seeing: `el.scrollTop` has not moved yet (a browser does not adjust it
221
+ // when content above grows), so the OLD layout is the right one to read
222
+ // the anchor from.
223
223
  const current = timelineWindow(layout, el.scrollTop, el.clientHeight, 0);
224
224
  const anchorId = ids[current.start];
225
- if (anchorId) {
226
- anchorRef.current = {
227
- id: anchorId,
228
- offset: el.scrollTop - layout.offsets[current.start],
229
- scrollTop: el.scrollTop,
230
- // A reader parked at the tail follows the TAIL, not the row that
231
- // happened to be at the top of the viewport: the rows below it are
232
- // estimates until they mount, so a row anchor would leave the
233
- // viewport short of the bottom — measured at 775 px on an opened
234
- // session, which is past the 100 px threshold that decides whether
235
- // the stream keeps following.
236
- // Measured against the PREVIOUS layout, not the DOM: this effect runs
237
- // after the content already grew, so the DOM's own distance is the
238
- // growth itself. A reader who was at the bottom before a row was
239
- // measured taller must stay at the bottom — measured against the DOM
240
- // they were left 2 080 px short, i.e. outside follow mode.
241
- tail: layout.total - scrollTop - (viewport || el.clientHeight) <= TAIL_ANCHOR_PX,
242
- };
225
+ // A reader parked at the tail follows the TAIL, not the row that happened
226
+ // to be at the top of the viewport: the rows below it are estimates until
227
+ // they mount, so a row anchor would leave the viewport short of the
228
+ // bottom — measured at 775 px on an opened session, which is past the
229
+ // 100 px threshold that decides whether the stream keeps following.
230
+ // Measured against the PREVIOUS layout, not the DOM: this effect runs
231
+ // after the content already grew, so the DOM's own distance is the
232
+ // growth itself. A reader who was at the bottom before a row was measured
233
+ // taller must stay at the bottom — measured against the DOM they were
234
+ // left 2 080 px short, i.e. outside follow mode.
235
+ // A jump to the tail is a claim about the BOTTOM, exactly like a reveal
236
+ // of the last row: mid-flight the viewport is far from it, so the
237
+ // geometry test below would read "reading back" and clear the claim the
238
+ // jump just made.
239
+ const tail = tailPinRef.current
240
+ || Boolean(jumpActiveRef?.current)
241
+ || layout.total - scrollTop - (viewport || el.clientHeight) <= TAIL_ANCHOR_PX;
242
+ const offset = anchorId ? el.scrollTop - layout.offsets[current.start] : 0;
243
+
244
+ // The correction is written HERE, against the new layout, not deferred to
245
+ // an effect that runs after this commit. Deferring it is what made an
246
+ // expanded thinking block snap shut: the restore effect for the SAME
247
+ // commit still holds the pre-measurement layout, so it consumed the
248
+ // anchor and wrote the reader's old offset; the next commit then had no
249
+ // anchor left, `scrollTop` was still stale, and the mounted WINDOW moved
250
+ // one row — unmounting and remounting the rows at its edge (measured in
251
+ // the browser: three rows removed and re-added per expand), which throws
252
+ // away every block's local state.
253
+ const next = layoutTimelineRows(ids, measuredRef.current);
254
+ const target = tail || !anchorId
255
+ ? Math.max(0, el.scrollHeight - el.clientHeight)
256
+ : next.offsets[rowIndex(ids, anchorId)] + offset;
257
+ tailPinRef.current = tail;
258
+ // A reveal OWNS the viewport until it settles: it re-writes its target
259
+ // every frame, so a correction here would be written back over it and the
260
+ // two would trade the viewport (measured before this guard existed: the
261
+ // reveal and the restore alternated `0` and its target for the whole
262
+ // animation). A bottom JUMP owns it for the same reason. The measurement
263
+ // is still adopted; only the position waits.
264
+ if (!revealingRef.current && !jumpActiveRef?.current) {
265
+ setScrollTop(target);
266
+ writeScrollTop(el, target);
243
267
  }
244
268
  setVersion((value) => value + 1);
245
269
  };
@@ -266,80 +290,22 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
266
290
 
267
291
  // Restore the reading position after the layout moved under it.
268
292
  useLayoutEffect(() => {
269
- const anchor = anchorRef.current;
270
- if (!anchor) return;
271
- anchorRef.current = null;
272
293
  const el = element;
273
- if (!el) return;
274
- // The viewport moved between the capture and this commit: a rail jump, the
275
- // opening jump to the tail, the follow pin, the reader's own scroll. That
276
- // mover owns the position — writing the captured one back is how a jump
277
- // landed and was then dragged to the tail, and how the reveal and this
278
- // effect ping-ponged a viewport between `0` and its target every frame
279
- // (measured: `scrollTo` writes alternating 4 913 / 0 for the whole reveal).
280
- if (anchor.tail || tailPinRef.current) {
281
- // The bottom edge is the anchor. `writeScrollTop`, because the container
282
- // carries `scroll-smooth`: a bare `scrollTop` assignment animates, and a
283
- // correction that animates is a correction that arrives late.
284
- writeScrollTop(el, Math.max(0, el.scrollHeight - el.clientHeight));
285
- return;
286
- }
287
- const index = rowIndex(ids, anchor.id);
288
- if (index < 0) return;
289
- const target = layout.offsets[index] + anchor.offset;
290
- writeScrollTop(el, target);
291
- }, [layout, ids, element]);
294
+ if (!el || !tailPinRef.current) return;
295
+ // A jump to the tail owns the position while it lands; its own watch is
296
+ // what puts the viewport at the bottom, and a second writer here is a
297
+ // second animation.
298
+ if (jumpActiveRef?.current) return;
299
+ // The tail pin outlives a commit: the rows above it are estimates until
300
+ // they mount, so every measurement can move the bottom by its own error.
301
+ // The bottom edge is the anchor. `writeScrollTop`, because the container
302
+ // carries `scroll-smooth`: a bare `scrollTop` assignment animates, and a
303
+ // correction that animates is a correction that arrives late.
304
+ writeScrollTop(el, Math.max(0, el.scrollHeight - el.clientHeight));
305
+ }, [layout, element, jumpActiveRef]);
292
306
 
293
- const revealRow = useCallback(
294
- (id: string): Promise<void> => {
295
- const el = scrollRef.current;
296
- if (!el) return Promise.resolve();
297
- const deadline = Date.now() + REVEAL_DEADLINE_MS;
298
- const settleBy = Date.now() + REVEAL_SETTLE_MS;
299
- // Supersedes an earlier reveal: two rail clicks in a row must land on the
300
- // SECOND turn, not race each other to the first one's position.
301
- const generation = (revealGenerationRef.current += 1);
302
- return new Promise<void>((resolve) => {
303
- let stillFrames = 0;
304
- let lastTop = -1;
305
- const step = (): void => {
306
- if (generation !== revealGenerationRef.current) {
307
- resolve();
308
- return;
309
- }
310
- const rows = idsRef.current;
311
- const index = rowIndex(rows, id);
312
- if (index < 0) {
313
- // The pager may still be bringing the row in; keep asking until the
314
- // deadline rather than scrolling to a row that does not exist yet.
315
- if (Date.now() < deadline) requestAnimationFrame(step);
316
- else resolve();
317
- return;
318
- }
319
- const current = layoutRef.current;
320
- const view = el.clientHeight || viewportRef.current;
321
- // The newest turn is the TAIL, not the centre of the last row: that
322
- // is what the reader means by jumping there, and it is what lets
323
- // follow mode re-engage (the scroll handler's threshold is 100 px).
324
- tailPinRef.current = index === rows.length - 1;
325
- const target = tailPinRef.current
326
- ? Math.max(0, el.scrollHeight - view)
327
- : rowScrollOffset(current, index, view);
328
- writeScrollTop(el, target);
329
- // A row that was just mounted is measured on a later commit; the
330
- // corrections land on the MEASURED position rather than the estimate
331
- // the first write used.
332
- stillFrames = Math.abs(el.scrollTop - lastTop) <= 1 ? stillFrames + 1 : 0;
333
- lastTop = el.scrollTop;
334
- if (stillFrames >= REVEAL_STILL_FRAMES || Date.now() >= settleBy) {
335
- resolve();
336
- return;
337
- }
338
- requestAnimationFrame(step);
339
- };
340
- requestAnimationFrame(step);
341
- });
342
- },
307
+ const revealRow = useMemo(
308
+ () => createRevealRow({ scrollRef, idsRef, layoutRef, viewportRef, tailPinRef, revealingRef, generationRef: revealGenerationRef }),
343
309
  [scrollRef],
344
310
  );
345
311