@kabmo-labs/kabmo 0.14.1 → 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 (29) 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-w6jx0h0p.js → index-mx658m43.js} +506 -506
  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/package.json +1 -1
  11. package/src/client/components/mobile/LayoutWrapper.tsx +11 -10
  12. package/src/client/components/mobile/open-file-payload.test.ts +29 -1
  13. package/src/client/components/mobile/open-file-payload.ts +28 -0
  14. package/src/client/components/settings/Modal.tsx +2 -2
  15. package/src/client/components/workspace/editor/index.tsx +6 -8
  16. package/src/client/components/workspace/git-panel/branch-modal/index.tsx +4 -3
  17. package/src/client/components/workspace/git-panel/commit-modal/index.tsx +1 -1
  18. package/src/client/hooks/chat/timeline/index.ts +3 -6
  19. package/src/client/hooks/chat/timeline/jump-landing.ts +121 -0
  20. package/src/client/hooks/chat/timeline/jump-rail.ts +19 -10
  21. package/src/client/hooks/chat/timeline/row-window.ts +44 -4
  22. package/src/client/hooks/chat/timeline/scroll-probe.test-util.ts +23 -10
  23. package/src/client/hooks/chat/timeline/scroll.test.ts +61 -4
  24. package/src/client/hooks/chat/timeline/scroll.ts +77 -26
  25. package/src/client/hooks/workspace/missing-files.test.ts +20 -3
  26. package/src/client/hooks/workspace/missing-files.ts +41 -7
  27. package/src/client/tailwind.css +12 -1
  28. package/src/server/routes/fs/exists.test.ts +26 -1
  29. package/dist/client/static/js/index-bnrrw242.css +0 -1
@@ -122,9 +122,11 @@ The custom group's header is **not** a disclosure: the `+` lives in it, and a
122
122
  button inside a button is invalid HTML whose inner click never fires.
123
123
 
124
124
  A **group header** is one command FILE — it collapses its rows, and carries the
125
- count. A **row** is one command — it collapses its own output. Both use the same
126
- reveal, and a collapsed body leaves the tab order entirely (its rows cannot be
127
- reached with `Tab` or announced), so a closed group is genuinely closed.
125
+ count. Every group starts CLOSED, so the panel opens as a list of files; the
126
+ sketch above shows the ones the reader opened. A **row** is one command — it
127
+ collapses its own output. Both use the same reveal, and a collapsed body leaves
128
+ the tab order entirely (its rows cannot be reached with `Tab` or announced), so a
129
+ closed group is genuinely closed.
128
130
 
129
131
  ## Every command is a row that opens
130
132
 
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "command-runner",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "private": true,
5
5
  "description": "Lists a repository's commands and runs them, in the foreground or as background jobs.",
6
6
  "type": "module",
7
7
  "kabmo": {
8
8
  "id": "command-runner",
9
9
  "name": "Runner",
10
- "version": "0.1.2",
10
+ "version": "0.2.0",
11
11
  "description": "Lists a repository's commands and runs them, in the foreground or as background jobs.",
12
12
  "app": "dist/app.js",
13
13
  "server": "dist/server.js",
@@ -77,9 +77,9 @@ function CommandRunnerPanel() {
77
77
  // prefix is what keeps a plugin out of the host's key space. They are the two
78
78
  // panel-wide checkboxes this panel used to carry (`Output`, `Background`),
79
79
  // moved onto each command because the answer differs per command.
80
- // Which FILES the reader collapsed. Absent means expanded — the same shape the
81
- // todo panel uses for its phases, and the reason a workspace seen for the first
82
- // time shows its commands rather than hiding them.
80
+ // Which FILES the reader expanded. Absent means COLLAPSED — a workspace seen
81
+ // for the first time opens as a list of command files rather than every
82
+ // command in the repository; only an explicit `false` keeps one open.
83
83
  const [collapsedGroups, setCollapsedGroups] = useSessionState<Record<string, boolean>>(
84
84
  'commandRunner.collapsedGroups',
85
85
  {},
@@ -171,38 +171,32 @@ function rowDisclosures(): HTMLButtonElement[] {
171
171
  }
172
172
 
173
173
  describe('CommandGroups', () => {
174
- test('renders one collapsible group per file, expanded by default', async () => {
174
+ test('renders one collapsible group per file, collapsed by default', async () => {
175
175
  await mount();
176
176
 
177
177
  const headers = groupHeaders();
178
178
  expect(headers).toHaveLength(2);
179
179
  expect(headers[0].textContent).toContain('package.json');
180
180
  expect(headers[1].textContent).toContain('Makefile');
181
- // Absent from the map means EXPANDED: a workspace seen for the first time
182
- // must show its commands.
183
- expect(headers.every((h) => h.getAttribute('aria-expanded') === 'true')).toBe(true);
184
- // The group bodies are expanded, and every command row is inside one — the
185
- // two levels default independently: a group shows its rows, a row does not
186
- // show output it was never asked to keep.
181
+ // Absent from the map means COLLAPSED: the panel opens as a list of files,
182
+ // not every command in the repository.
183
+ expect(headers.every((h) => h.getAttribute('aria-expanded') === 'false')).toBe(true);
187
184
  for (const header of headers) {
188
- expect(bodyOf(header).getAttribute('data-expanded')).toBe('true');
185
+ expect(bodyOf(header).getAttribute('data-expanded')).toBe('false');
186
+ expect(bodyOf(header).hasAttribute('inert')).toBe(true);
189
187
  }
188
+ // The row level is independent: a row still does not show output it was
189
+ // never asked to keep.
190
190
  for (const row of rowDisclosures()) {
191
191
  expect(row.getAttribute('aria-expanded')).toBe('false');
192
192
  }
193
193
  });
194
194
 
195
- test('a collapsed group hides its rows AND takes them out of the tab order', async () => {
196
- await mount({ collapsedGroups: { 'package.json': true } });
195
+ test('an explicitly expanded group shows its rows AND puts them back in the tab order', async () => {
196
+ // Only the map's explicit `false` opens a group; the other file, absent
197
+ // from it, stays closed — an expansion is per file.
198
+ await mount({ collapsedGroups: { Makefile: false } });
197
199
 
198
- const pkgHeader = headerFor('package.json');
199
- expect(pkgHeader.getAttribute('aria-expanded')).toBe('false');
200
-
201
- const pkgBody = bodyOf(pkgHeader);
202
- expect(pkgBody.getAttribute('data-expanded')).toBe('false');
203
- expect(pkgBody.hasAttribute('inert')).toBe(true);
204
-
205
- // The OTHER group is untouched — a collapse is per file.
206
200
  const makeHeader = headerFor('Makefile');
207
201
  expect(makeHeader.getAttribute('aria-expanded')).toBe('true');
208
202
  const makeBody = bodyOf(makeHeader);
@@ -213,6 +207,13 @@ describe('CommandGroups', () => {
213
207
  // from whether the group hides it.)
214
208
  const row = rowDisclosures().find((b) => makeBody.contains(b))!;
215
209
  expect(hasInertAncestor(row)).toBe(false);
210
+
211
+ // The OTHER group is untouched — a collapse is per file.
212
+ const pkgHeader = headerFor('package.json');
213
+ expect(pkgHeader.getAttribute('aria-expanded')).toBe('false');
214
+ const pkgBody = bodyOf(pkgHeader);
215
+ expect(pkgBody.getAttribute('data-expanded')).toBe('false');
216
+ expect(pkgBody.hasAttribute('inert')).toBe(true);
216
217
  // In the COLLAPSED group the same question answers yes: the group is what
217
218
  // takes its rows out of the tab order.
218
219
  const hiddenRow = rowDisclosures().find((b) => pkgBody.contains(b))!;
@@ -221,9 +222,10 @@ describe('CommandGroups', () => {
221
222
 
222
223
  test('the group toggle reports the FILE, so the caller can persist it per file', async () => {
223
224
  await mount();
225
+ // The group starts collapsed, so the first click EXPANDS it.
224
226
  await act(async () => headerFor('Makefile').click());
225
227
  // Reporting an index would break the moment the scan reorders the list.
226
- expect(calls).toEqual(['group:Makefile:true']);
228
+ expect(calls).toEqual(['group:Makefile:false']);
227
229
  });
228
230
 
229
231
  test('every group header carries aria-controls naming its own body', async () => {
@@ -238,9 +240,11 @@ describe('CommandGroups', () => {
238
240
 
239
241
  test('a command row collapses independently of its group', async () => {
240
242
  // A run, so the row has something to open — without one its disclosure is
241
- // disabled, which is a different test.
243
+ // disabled, which is a different test. The group is explicitly opened, or
244
+ // the row's controls are inert behind it.
242
245
  const dev = finishedRun('package.json#package:dev', 'run-dev');
243
- await mount({ runs: [dev] });
246
+ await mount({ runs: [dev], collapsedGroups: { 'package.json': false } });
247
+ expect(headerFor('package.json').getAttribute('aria-expanded')).toBe('true');
244
248
 
245
249
  const rowDisclosure = rowDisclosures()[0];
246
250
  // A run OPENS the row, so it starts expanded and the click closes it.
@@ -266,7 +266,10 @@ export function CommandGroups({
266
266
  key={group.file}
267
267
  group={group}
268
268
  latest={latest}
269
- collapsed={collapsedGroups[group.file] === true}
269
+ // Absent means COLLAPSED: the panel opens as a list of files, and a
270
+ // reader opens the one they came for. Only an explicit `false`
271
+ // (the user expanded it) shows the rows.
272
+ collapsed={collapsedGroups[group.file] !== false}
270
273
  background={background}
271
274
  logs={logs}
272
275
  onToggleGroup={onToggleGroup}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kabmo-labs/kabmo",
3
- "version": "0.14.1",
3
+ "version": "0.15.0",
4
4
  "description": "Web console and diagnostic workbench for AI coding agents — Elysia + Preact on Bun.",
5
5
  "license": "MIT",
6
6
  "author": "Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",
@@ -19,7 +19,7 @@ import { ToastStack } from '@/client/components/common/ToastStack';
19
19
  import { useEditorDrop, type EditorDropResult } from '@/client/hooks/editor/use-editor-drop';
20
20
  import { EditorDropOverlay } from '@/client/components/workspace/editor/EditorDropOverlay';
21
21
  import { PluginBootstrap } from '@/client/lib/plugins/bootstrap';
22
- import { mobileEditorFileFrom, type MobileEditorFile } from '@/client/components/mobile/open-file-payload';
22
+ import { mobileEditorFileFrom, mobileProbeTabs, type MobileEditorFile } from '@/client/components/mobile/open-file-payload';
23
23
  import { useLeftDock } from '@/client/hooks/workspace/left-dock';
24
24
  import { useSessionStateContext } from '@/client/hooks/workspace/session-state/context';
25
25
  import { setSessionKey } from '@/shared/lib/workspace/session-state/store';
@@ -61,13 +61,11 @@ export function MobileLayoutWrapper({ onDesktopToggle, appSettings = {} }: Mobil
61
61
  // The phone's full-screen editor shows ONE file at a time, so the probe has a
62
62
  // single subject and a constant id. `refreshKey` is what carries a deletion
63
63
  // here: the Files panel's delete, an agent `rm` that triggers a workspace
64
- // refresh, and the editor's own save all bump it.
65
- const mobileEditorMissingIds = useMissingFiles(
66
- mobileEditorFile?.path
67
- ? [{ id: 'mobile-editor', path: mobileEditorFile.path, root: mobileEditorFile.root }]
68
- : [],
69
- refreshKey,
70
- );
64
+ // refresh, and the editor's own save all bump it. The scope comes from
65
+ // `mobileProbeTabs` so `repo` travels with it — without it the server resolved
66
+ // a nested-repo file against the workspace root and answered "gone" for a file
67
+ // that had just been read.
68
+ const mobileEditorMissingIds = useMissingFiles(mobileProbeTabs(mobileEditorFile), refreshKey);
71
69
  const { toasts, pushToast, dismissToast } = useToasts();
72
70
  const handleDropResult = useCallback(
73
71
  (result: EditorDropResult) => pushToast(result.message, result.ok ? 'success' : 'error'),
@@ -118,10 +116,13 @@ export function MobileLayoutWrapper({ onDesktopToggle, appSettings = {} }: Mobil
118
116
  // never receive the first drop.
119
117
  const editorDrop = useEditorDrop({ enabled: hasContext, onResult: handleDropResult });
120
118
 
121
- // Listen to open-file event on mobile
119
+ // Listen to open-file event on mobile. The active project is the fallback
120
+ // root, exactly as the desktop tab opener applies it: a payload with no root
121
+ // of its own (a chat link, a plugin readout) then reads AND probes against the
122
+ // workspace it belongs to instead of the server's default root.
122
123
  useKabmoEvent('omp:open-file', (e) => {
123
124
  const customEvent = e as CustomEvent<unknown>;
124
- const next = mobileEditorFileFrom(customEvent.detail);
125
+ const next = mobileEditorFileFrom(customEvent.detail, activeProjectPath);
125
126
  if (next) setMobileEditorFile(next);
126
127
  });
127
128
 
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { describe, expect, test } from 'bun:test';
19
- import { mobileEditorFileFrom } from '@/client/components/mobile/open-file-payload';
19
+ import { mobileEditorFileFrom, mobileProbeTabs } from '@/client/components/mobile/open-file-payload';
20
20
 
21
21
  describe('mobileEditorFileFrom', () => {
22
22
  test('carries repo and handleId through', () => {
@@ -34,6 +34,7 @@ describe('mobileEditorFileFrom', () => {
34
34
  root: '/ws',
35
35
  repo: 'projects/token',
36
36
  handleId: 'handle-7',
37
+ deviceFile: undefined,
37
38
  });
38
39
  });
39
40
 
@@ -68,4 +69,31 @@ describe('mobileEditorFileFrom', () => {
68
69
  expect(result?.repo).toBeUndefined();
69
70
  expect(result?.handleId).toBeUndefined();
70
71
  });
72
+
73
+ test('a device file is marked, so the existence probe refuses it', () => {
74
+ expect(mobileEditorFileFrom({ path: 'report.md', deviceFile: true })?.deviceFile).toBe(true);
75
+ expect(mobileEditorFileFrom({ path: 'x.md', deviceFile: 'yes' })?.deviceFile).toBeUndefined();
76
+ });
77
+ });
78
+
79
+ describe('mobileProbeTabs', () => {
80
+ test('carries the tree the file was opened from — repo included', () => {
81
+ // The regression: the phone's probe sent `root` + `path` and dropped `repo`,
82
+ // so the server resolved a nested-repo file against the workspace root and
83
+ // answered "gone" for a file the editor had just read.
84
+ const file = mobileEditorFileFrom({ path: 'src/inner.ts', root: '/ws', repo: 'pkg/nested' });
85
+ expect(mobileProbeTabs(file)).toEqual([{
86
+ id: 'mobile-editor',
87
+ path: 'src/inner.ts',
88
+ root: '/ws',
89
+ repo: 'pkg/nested',
90
+ content: undefined,
91
+ handleId: undefined,
92
+ deviceFile: undefined,
93
+ }]);
94
+ });
95
+
96
+ test('nothing open means nothing to probe', () => {
97
+ expect(mobileProbeTabs(null)).toEqual([]);
98
+ });
71
99
  });
@@ -14,6 +14,8 @@
14
14
  * server-reachable path, so its bytes come from the live handle instead).
15
15
  */
16
16
 
17
+ import type { ProbeableTab } from '@/client/hooks/workspace/missing-files';
18
+
17
19
  /** The one file the phone's full-screen editor has open. */
18
20
  export interface MobileEditorFile {
19
21
  name: string;
@@ -24,6 +26,8 @@ export interface MobileEditorFile {
24
26
  repo?: string;
25
27
  /** A dropped/launched file's live handle — its bytes have no server path. */
26
28
  handleId?: string;
29
+ /** The bytes came from the DEVICE: renderable, with no path the server can stat. */
30
+ deviceFile?: boolean;
27
31
  }
28
32
 
29
33
  function readString(source: Record<string, unknown>, key: string): string | undefined {
@@ -56,5 +60,29 @@ export function mobileEditorFileFrom(payload: unknown, fallbackRoot?: string | n
56
60
  root: readString(source, 'root') ?? fallbackRoot ?? undefined,
57
61
  repo: readString(source, 'repo'),
58
62
  handleId: readString(source, 'handleId'),
63
+ deviceFile: source.deviceFile === true ? true : undefined,
59
64
  };
60
65
  }
66
+
67
+ /**
68
+ * The scope the phone's "is this file still there?" probe must ask about.
69
+ *
70
+ * `repo` is load-bearing and used to be dropped here: the server resolves
71
+ * `root` + `repo` + `path` exactly as the READ route does, so a file opened from
72
+ * a nested repository — the tree lists it relative to that repo — was read
73
+ * successfully and then reported as deleted by a probe that named the workspace
74
+ * root instead. Everything else (inline content, a launched handle, a device
75
+ * file) is carried through so `isProbeableTab` can refuse it in one place.
76
+ */
77
+ export function mobileProbeTabs(file: MobileEditorFile | null): ProbeableTab[] {
78
+ if (!file) return [];
79
+ return [{
80
+ id: 'mobile-editor',
81
+ path: file.path,
82
+ root: file.root,
83
+ repo: file.repo,
84
+ content: file.content,
85
+ handleId: file.handleId,
86
+ deviceFile: file.deviceFile,
87
+ }];
88
+ }
@@ -187,11 +187,11 @@ export function SettingsModal({
187
187
  onClick={onClose}
188
188
  >
189
189
  <div
190
- className="relative bg-paper border border-ink/15 md:rounded-2xl shadow-2xl w-full h-full md:max-w-4xl lg:max-w-5xl xl:max-w-[1150px] md:h-[782px] md:max-h-[92vh] flex flex-col md:flex-row overflow-hidden text-ink"
190
+ className="relative bg-paper border border-ink/15 md:rounded-2xl shadow-2xl w-full h-full md:max-w-5xl lg:max-w-6xl xl:max-w-[1280px] md:h-[min(90vh,900px)] md:max-h-[92vh] flex flex-col md:flex-row overflow-hidden text-ink"
191
191
  onClick={(e) => e.stopPropagation()}
192
192
  >
193
193
  {/* DESKTOP VIEW: 2-Column Split */}
194
- <div className="hidden md:flex w-64 flex-shrink-0 h-full">
194
+ <div className="hidden md:flex w-72 flex-shrink-0 h-full">
195
195
  <SettingsSidebar
196
196
  activeCategory={activeCategory}
197
197
  onSelectCategory={(catId) => setActiveCategory(catId)}
@@ -79,14 +79,12 @@ export function Editor({
79
79
  const editorTheme = useEditorTheme();
80
80
 
81
81
  // A deleted file keeps its tab (its buffer is still on screen), but the tab
82
- // strip must say so. Only a plain FILE tab is probed: a diff tab's path names
83
- // a change rather than a document, and an attachment chip carries inline
84
- // `content` with no file behind its `path` at all — probing that name would
85
- // strike the chip through the moment it was opened.
86
- const missingIds = useMissingFiles(
87
- openedFiles.filter((file) => !file.isDiff && file.content === undefined),
88
- refreshKey,
89
- );
82
+ // strip must say so. Which tabs can be probed is the hook's own rule
83
+ // (`isProbeableTab`): a diff tab's path names a change rather than a document,
84
+ // and an attachment chip carries inline `content` with no file behind its
85
+ // `path` at all — probing that name would strike the chip through the moment
86
+ // it was opened.
87
+ const missingIds = useMissingFiles(openedFiles, refreshKey);
90
88
  const activeFileMissing = Boolean(activeFile && missingIds.has(activeFile.id));
91
89
 
92
90
  const editor = useFileEditor(activeFile ?? null, {
@@ -39,9 +39,10 @@ interface GitBranchModalProps {
39
39
  * actions — the row's click is already checkout — and a row that both checks
40
40
  * out and merges is a row whose click means two things.
41
41
  *
42
- * Follows the commit modal's shell (`lg:w-[min(96vw,980px)] lg:h-[88vh]`,
43
- * full-screen on phones), so this is a sibling of an existing surface rather
44
- * than a new convention.
42
+ * Follows the commit modal's shell SHAPE — a desktop-capped, centred card that
43
+ * is full-screen on phones — but takes its own width from `Modal`
44
+ * (`max-w-[min(96vw,720px)]`): a branch list is one column, while the commit
45
+ * history spends the extra width on the graph gutter and the message column.
45
46
  *
46
47
  * **Everything the row shows comes from ONE read** (`?branches=1`, a single
47
48
  * `for-each-ref` with the upstream/ahead-behind/date/subject fields), fetched
@@ -232,7 +232,7 @@ export function GitCommitModal({
232
232
  <div
233
233
  className="bg-paper border-ink/20 shadow-2xl flex flex-col overflow-hidden
234
234
  w-full h-full rounded-none border-0
235
- lg:w-[min(96vw,980px)] lg:h-[88vh] lg:rounded-xl lg:border
235
+ lg:w-[min(94vw,1200px)] lg:h-[88vh] lg:rounded-xl lg:border
236
236
  pt-[env(safe-area-inset-top,0px)] lg:pt-0"
237
237
  onClick={(e) => e.stopPropagation()}
238
238
  >
@@ -48,9 +48,8 @@ export function useChatTimeline({
48
48
  // without re-creating it (useSessionLoad is defined below the scroll hook).
49
49
  const loadOlderRef = useRef<() => void>(() => {});
50
50
 
51
- const { scrollRef, scrollNodeRef, scrollNode, contentRef, showScrollBottom, readingBack, handleScroll, scrollToBottom, jumpToBottom, followRef, jumpActiveRef, jumpCountRef } = useChatTimelineScroll({
52
- onScrollTop: () => loadOlderRef.current(),
53
- });
51
+ const scroll = useChatTimelineScroll({ onScrollTop: () => loadOlderRef.current() });
52
+ const { scrollRef, scrollNodeRef, contentRef, showScrollBottom, readingBack, handleScroll, scrollToBottom, jumpToBottom, jumpActiveRef, jumpCountRef } = scroll;
54
53
 
55
54
  const { inputValue, setInputValue, inputAttachments, setInputAttachments } = useComposerDraft();
56
55
  const [localMessages, setLocalMessages] = useState<ChatMessageData[]>([]);
@@ -158,9 +157,7 @@ export function useChatTimeline({
158
157
  sessionId,
159
158
  messages: localMessages,
160
159
  jumpToTurn,
161
- followRef,
162
- scrollRef,
163
- scrollNode,
160
+ scroll,
164
161
  });
165
162
 
166
163
  // The composer's model/thinking mirrors and the mid-run stash (see the hook).
@@ -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
  }