@kabmo-labs/kabmo 0.14.1 → 0.16.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 (76) hide show
  1. package/README.md +1 -0
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +374 -356
  4. package/dist/client/static/js/{index-w6jx0h0p.js → index-cpydmygd.js} +661 -661
  5. package/dist/client/static/js/index-fjnq2z2d.css +1 -0
  6. package/marketplace/plugins/command-runner/README.md +5 -3
  7. package/marketplace/plugins/command-runner/package.json +2 -2
  8. package/marketplace/plugins/command-runner/src/app.tsx +3 -3
  9. package/marketplace/plugins/command-runner/src/panel/Groups.test.tsx +25 -21
  10. package/marketplace/plugins/command-runner/src/panel/Groups.tsx +4 -1
  11. package/marketplace/plugins/stats/README.md +27 -8
  12. package/marketplace/plugins/stats/package.json +2 -2
  13. package/marketplace/plugins/stats/src/HeaderReadout.test.tsx +2 -1
  14. package/marketplace/plugins/stats/src/HeaderReadout.tsx +6 -2
  15. package/marketplace/plugins/stats/src/KillConfirm.test.tsx +159 -0
  16. package/marketplace/plugins/stats/src/KillConfirm.tsx +145 -0
  17. package/marketplace/plugins/stats/src/ProcessTable.tsx +54 -8
  18. package/marketplace/plugins/stats/src/TotalsBar.test.tsx +5 -2
  19. package/marketplace/plugins/stats/src/TotalsBar.tsx +13 -3
  20. package/marketplace/plugins/stats/src/app.test.tsx +100 -4
  21. package/marketplace/plugins/stats/src/app.tsx +51 -4
  22. package/marketplace/plugins/stats/src/groups.test.ts +1 -1
  23. package/marketplace/plugins/stats/src/kill.test.ts +131 -0
  24. package/marketplace/plugins/stats/src/kill.ts +74 -0
  25. package/marketplace/plugins/stats/src/labels.test.ts +1 -0
  26. package/marketplace/plugins/stats/src/machine.test.ts +77 -0
  27. package/marketplace/plugins/stats/src/machine.ts +115 -0
  28. package/marketplace/plugins/stats/src/proc/darwin.ts +38 -0
  29. package/marketplace/plugins/stats/src/proc/linux.ts +4 -0
  30. package/marketplace/plugins/stats/src/proc/ps.ts +1 -0
  31. package/marketplace/plugins/stats/src/proc/types.ts +11 -0
  32. package/marketplace/plugins/stats/src/sampler.test.ts +42 -4
  33. package/marketplace/plugins/stats/src/sampler.ts +32 -18
  34. package/marketplace/plugins/stats/src/server.ts +29 -2
  35. package/marketplace/plugins/stats/src/snapshot.ts +31 -3
  36. package/package.json +3 -2
  37. package/src/client/components/common/Modal.tsx +7 -0
  38. package/src/client/components/layout/LeftDock.tsx +1 -0
  39. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +1 -0
  40. package/src/client/components/mobile/LayoutWrapper.tsx +11 -10
  41. package/src/client/components/mobile/RightSidebar.tsx +1 -0
  42. package/src/client/components/mobile/mobile-session-sidebar/use-dock.ts +1 -0
  43. package/src/client/components/mobile/open-file-payload.test.ts +29 -1
  44. package/src/client/components/mobile/open-file-payload.ts +28 -0
  45. package/src/client/components/settings/Modal.tsx +2 -2
  46. package/src/client/components/workspace/editor/index.tsx +6 -8
  47. package/src/client/components/workspace/git-panel/branch-modal/index.tsx +4 -3
  48. package/src/client/components/workspace/git-panel/commit-modal/index.tsx +1 -1
  49. package/src/client/components/workspace/model-dropdown/Panel.tsx +7 -2
  50. package/src/client/components/workspace/model-dropdown/Section.test.tsx +13 -0
  51. package/src/client/components/workspace/model-dropdown/Section.tsx +5 -1
  52. package/src/client/components/workspace/panels/builtin.tsx +7 -0
  53. package/src/client/components/workspace/wiki-panel/NavModal.test.tsx +136 -0
  54. package/src/client/components/workspace/wiki-panel/NavModal.tsx +94 -0
  55. package/src/client/components/workspace/wiki-panel/PageView.tsx +16 -10
  56. package/src/client/components/workspace/wiki-panel/index.tsx +44 -9
  57. package/src/client/hooks/chat/timeline/index.ts +3 -6
  58. package/src/client/hooks/chat/timeline/jump-landing.ts +121 -0
  59. package/src/client/hooks/chat/timeline/jump-rail.ts +19 -10
  60. package/src/client/hooks/chat/timeline/row-window.ts +44 -4
  61. package/src/client/hooks/chat/timeline/scroll-probe.test-util.ts +23 -10
  62. package/src/client/hooks/chat/timeline/scroll.test.ts +61 -4
  63. package/src/client/hooks/chat/timeline/scroll.ts +77 -26
  64. package/src/client/hooks/workspace/missing-files.test.ts +20 -3
  65. package/src/client/hooks/workspace/missing-files.ts +41 -7
  66. package/src/client/tailwind.css +12 -1
  67. package/src/server/lib/db/schema.ts +11 -0
  68. package/src/server/lib/lifecycle/memory.test.ts +41 -1
  69. package/src/server/lib/lifecycle/memory.ts +131 -14
  70. package/src/server/lib/omp/session/subagent-presence-scan.test.ts +137 -0
  71. package/src/server/lib/omp/session/subagent-presence-scan.ts +120 -0
  72. package/src/server/lib/omp/session/subagent-presence-store.test.ts +120 -0
  73. package/src/server/lib/omp/session/subagent-presence-store.ts +65 -0
  74. package/src/server/lib/omp/session/subagent-presence.ts +52 -15
  75. package/src/server/routes/fs/exists.test.ts +26 -1
  76. package/dist/client/static/js/index-bnrrw242.css +0 -1
@@ -77,11 +77,30 @@ export interface UseTimelineRowWindowDeps {
77
77
  * wrote `scrollTop` into a spacer and mounted nothing.
78
78
  */
79
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>;
80
92
  /** False renders every row (a short list, or a surface without a scroller). */
81
93
  enabled?: boolean;
82
94
  }
83
95
 
84
- 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 {
85
104
  // Heights of rows that have been on screen at least once, by id — so a row
86
105
  // keeps its height across being unmounted, which is what keeps the scrollbar
87
106
  // steady while the reader moves through a long session.
@@ -103,6 +122,17 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
103
122
  * the stream stopped following after the jump.
104
123
  */
105
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
+ });
106
136
 
107
137
  const layout = useMemo(
108
138
  () => layoutTimelineRows(ids, measuredRef.current),
@@ -202,7 +232,12 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
202
232
  // growth itself. A reader who was at the bottom before a row was measured
203
233
  // taller must stay at the bottom — measured against the DOM they were
204
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.
205
239
  const tail = tailPinRef.current
240
+ || Boolean(jumpActiveRef?.current)
206
241
  || layout.total - scrollTop - (viewport || el.clientHeight) <= TAIL_ANCHOR_PX;
207
242
  const offset = anchorId ? el.scrollTop - layout.offsets[current.start] : 0;
208
243
 
@@ -224,8 +259,9 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
224
259
  // every frame, so a correction here would be written back over it and the
225
260
  // two would trade the viewport (measured before this guard existed: the
226
261
  // reveal and the restore alternated `0` and its target for the whole
227
- // animation). The measurement is still adopted; only the position waits.
228
- if (!revealingRef.current) {
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) {
229
265
  setScrollTop(target);
230
266
  writeScrollTop(el, target);
231
267
  }
@@ -256,13 +292,17 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
256
292
  useLayoutEffect(() => {
257
293
  const el = element;
258
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;
259
299
  // The tail pin outlives a commit: the rows above it are estimates until
260
300
  // they mount, so every measurement can move the bottom by its own error.
261
301
  // The bottom edge is the anchor. `writeScrollTop`, because the container
262
302
  // carries `scroll-smooth`: a bare `scrollTop` assignment animates, and a
263
303
  // correction that animates is a correction that arrives late.
264
304
  writeScrollTop(el, Math.max(0, el.scrollHeight - el.clientHeight));
265
- }, [layout, element]);
305
+ }, [layout, element, jumpActiveRef]);
266
306
 
267
307
  const revealRow = useMemo(
268
308
  () => createRevealRow({ scrollRef, idsRef, layoutRef, viewportRef, tailPinRef, revealingRef, generationRef: revealGenerationRef }),
@@ -78,8 +78,10 @@ export interface ScrollProbe {
78
78
  StubResizeObserver: typeof StubResizeObserver;
79
79
  /** Preact's test-utils `act`, loaded after the DOM globals exist. */
80
80
  act: typeof PreactAct;
81
- /** Drain the deferred frames the hook scheduled. */
82
- flushFrames(): Promise<void>;
81
+ /** Drain the deferred frames the hook scheduled. `rounds` runs the queue
82
+ * again for callbacks those frames scheduled themselves (a per-frame watch),
83
+ * which is the only way a multi-frame loop advances without a real clock. */
84
+ flushFrames(rounds?: number): Promise<void>;
83
85
  message(id: string): ChatMessageData;
84
86
  mountProbe(sessionId: string, messages: ChatMessageData[]): Promise<ProbeHandle>;
85
87
  updateProbe(probe: ProbeHandle, sessionId: string, messages: ChatMessageData[]): Promise<void>;
@@ -158,7 +160,11 @@ export async function setupScrollProbe(): Promise<ScrollProbe> {
158
160
  enabled: true,
159
161
  });
160
162
  props.holder.current = scroll;
161
- return h('div', { ref: scroll.scrollRef, onScroll: scroll.handleScroll },
163
+ // `scrollNodeRef`, not `scrollRef`: the product uses it, and it is what
164
+ // publishes the scroller as state for the subscriptions (the reader-input
165
+ // listeners, the row window). A probe on the bare ref subscribes to
166
+ // nothing, which is a state the product cannot be in.
167
+ return h('div', { ref: scroll.scrollNodeRef, onScroll: scroll.handleScroll },
162
168
  h('div', { ref: scroll.contentRef }));
163
169
  }
164
170
 
@@ -173,6 +179,11 @@ export async function setupScrollProbe(): Promise<ScrollProbe> {
173
179
  await act(async () => { render(h(Probe, { sessionId, messages, holder }), node); });
174
180
  const el = holder.current!.scrollRef.current!;
175
181
  installScroller(el);
182
+ // A browser runs the frames a mount scheduled; the fake platform does not,
183
+ // so drain them here. Without this the open jump's landing watch is still
184
+ // armed when the test's first assertion runs, which is a state the product
185
+ // never stays in.
186
+ await flushFrames(8);
176
187
  return { holder, node, el };
177
188
  }
178
189
 
@@ -181,6 +192,7 @@ export async function setupScrollProbe(): Promise<ScrollProbe> {
181
192
  await act(async () => {
182
193
  render(h(Probe, { sessionId, messages, holder: probe.holder }), probe.node);
183
194
  });
195
+ await flushFrames(8);
184
196
  }
185
197
 
186
198
  async function unmountProbe(probe: ProbeHandle) {
@@ -196,14 +208,15 @@ export async function setupScrollProbe(): Promise<ScrollProbe> {
196
208
  * that fires an observer has to let the frame it scheduled run before the
197
209
  * geometry it asserts on has been applied.
198
210
  */
199
- async function flushFrames() {
200
- for (let i = 0; i < pendingFrames.length; i++) {
201
- const callback = pendingFrames[i];
202
- pendingFrames[i] = null;
203
- if (!callback) continue;
204
- await act(async () => { callback(); });
211
+ async function flushFrames(rounds = 1) {
212
+ for (let round = 0; round < rounds; round++) {
213
+ const scheduled = pendingFrames.splice(0, pendingFrames.length);
214
+ if (scheduled.length === 0) return;
215
+ for (const callback of scheduled) {
216
+ if (!callback) continue;
217
+ await act(async () => { callback(); });
218
+ }
205
219
  }
206
- pendingFrames.length = 0;
207
220
  }
208
221
 
209
222
  function teardown() {
@@ -81,7 +81,9 @@ describe('timeline scroll', () => {
81
81
  expect(scroll().jumpCountRef.current).toBe(1);
82
82
  expect(scroll().jumpActiveRef.current).toBe(true);
83
83
 
84
- // The user reads back. A stream chunk must not yank the viewport down...
84
+ // The user reads back (a wheel, then the viewport moves up). A stream chunk
85
+ // must not yank it down...
86
+ await p.act(() => { probe.el.dispatchEvent(new Event('wheel')); });
85
87
  probe.el.scrollTop = 100;
86
88
  expect(scroll().followRef.current).toBe(false);
87
89
  p.scrolled.length = 0;
@@ -97,20 +99,75 @@ describe('timeline scroll', () => {
97
99
  await p.unmountProbe(probe);
98
100
  });
99
101
 
100
- test('the jump guard releases so history paging is not blocked for good', async () => {
102
+ test('the jump guard releases when the landing SETTLES, not on a clock', async () => {
101
103
  p.scrolled.length = 0;
102
104
  p.geometry.top = 0;
103
105
  p.geometry.height = 5000;
104
106
  const probe = await p.mountProbe('a', [p.message('a1')]);
105
107
  const scroll = () => probe.holder.current!;
106
108
 
109
+ // A long session on a slow device is still animating seconds later. A guard
110
+ // released by a timer here is a guard released mid-flight: the paging
111
+ // trigger it was holding off then fires at the top of history, and the
112
+ // window it pages is one the jump must outrun.
107
113
  fakeTimers.useFakeTimers();
114
+ await p.act(() => { scroll().jumpToBottom('smooth'); });
115
+ expect(scroll().jumpActiveRef.current).toBe(true);
116
+ await p.act(() => { fakeTimers.advanceTimersByTime(10_000); });
117
+ expect(scroll().jumpActiveRef.current).toBe(true);
118
+ fakeTimers.useRealTimers();
119
+
120
+ // Landed: the guard lets go, so history paging is not blocked for good.
121
+ await p.act(() => { probe.el.scrollTo({ top: p.geometry.height, behavior: 'instant' }); });
122
+ await p.flushFrames(6);
123
+ expect(scroll().jumpActiveRef.current).toBe(false);
124
+ await p.unmountProbe(probe);
125
+ });
126
+
127
+ test('a jump that lands short re-aims instead of leaving the button up', async () => {
128
+ p.scrolled.length = 0;
129
+ p.geometry.top = 0;
130
+ p.geometry.height = 5000;
131
+ const probe = await p.mountProbe('a', [p.message('a1')]);
132
+ const scroll = () => probe.holder.current!;
133
+
134
+ // A smooth scroll that never moves: the browser dropped it because the rows
135
+ // it was scrolling through were replaced by the mounted window. This is the
136
+ // reported "the button does nothing until I scroll the rest myself".
137
+ p.scrolled.length = 0;
138
+ await p.act(() => { scroll().jumpToBottom('smooth'); });
139
+ expect(p.scrolled.length).toBe(1);
140
+ expect(probe.el.scrollTop).toBe(0);
141
+
142
+ await p.flushFrames(8);
143
+ // The watch re-aimed on its own rather than giving up.
144
+ expect(p.scrolled.length).toBeGreaterThan(1);
145
+ expect(p.scrolled.at(-1)?.top).toBe(p.geometry.height);
146
+ await p.unmountProbe(probe);
147
+ });
148
+
149
+ test('a layout clamp may not cancel a jump in flight; real input still may', async () => {
150
+ p.scrolled.length = 0;
151
+ p.geometry.top = 0;
152
+ p.geometry.height = 5000;
153
+ const probe = await p.mountProbe('a', [p.message('a1')]);
154
+ const scroll = () => probe.holder.current!;
155
+
108
156
  await p.act(() => { scroll().jumpToBottom('instant'); });
109
157
  expect(scroll().jumpActiveRef.current).toBe(true);
110
158
 
111
- await p.act(() => { fakeTimers.advanceTimersByTime(1000); });
159
+ // A measurement replaced an estimate with a taller height and the browser
160
+ // clamped `scrollTop` UP. Nobody touched the scroller: the jump stands.
161
+ probe.el.scrollTop = 300;
162
+ expect(scroll().followRef.current).toBe(true);
163
+ expect(scroll().jumpActiveRef.current).toBe(true);
164
+
165
+ // The reader themselves: a wheel, then the viewport moves up. The jump must
166
+ // stand down rather than keep pulling the tail under them.
167
+ await p.act(() => { probe.el.dispatchEvent(new Event('wheel')); });
168
+ probe.el.scrollTop = 100;
169
+ expect(scroll().followRef.current).toBe(false);
112
170
  expect(scroll().jumpActiveRef.current).toBe(false);
113
- fakeTimers.useRealTimers();
114
171
  await p.unmountProbe(probe);
115
172
  });
116
173
 
@@ -21,14 +21,25 @@
21
21
  * button, re-engages it. Programmatic jumps (`scrollTo`) never flip the mode.
22
22
  *
23
23
  * `jumpToBottom` is the unconditional bypass (`follow` is re-engaged, geometry
24
- * is re-baselined, and the paging trigger stands down for a moment) — the
25
- * button's jump, the open-session jump, and the send jump all go through it.
26
- * `follow` lives across session switches, so an open jump that honoured it was
27
- * simply refused for a session opened after the user had scrolled up.
24
+ * is re-baselined, and the paging trigger stands down until the landing
25
+ * settles) — the button's jump, the open-session jump, and the send jump all
26
+ * go through it. `follow` lives across session switches, so an open jump that
27
+ * honoured it was simply refused for a session opened after the user had
28
+ * scrolled up.
29
+ *
30
+ * A jump OWNS the viewport until it has actually landed, the same way
31
+ * `revealRow` owns it while it flies. The timeline mounts a window of its rows
32
+ * and ESTIMATES the rest, so `scrollHeight` changes while a jump mounts the
33
+ * rows it passes over — the target it was issued against is stale before the
34
+ * animation ends. The jump watch therefore re-reads the geometry every frame
35
+ * and re-aims until the viewport has SAT at the tail; the content observer and
36
+ * the row window stand down meanwhile, so no measurement drags the landing
37
+ * back. See `createJumpLanding` for what each state means.
28
38
  */
29
39
 
30
40
  import type { RefObject } from 'preact/compat';
31
41
  import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
42
+ import { createJumpLanding, type JumpLanding } from '@/client/hooks/chat/timeline/jump-landing';
32
43
 
33
44
  /** Distance from the tail, in pixels, that still counts as "at the bottom". */
34
45
  const FOLLOW_BOTTOM_THRESHOLD_PX = 100;
@@ -47,12 +58,11 @@ const FOLLOW_BOTTOM_THRESHOLD_PX = 100;
47
58
  */
48
59
  const COMPACT_TRIGGER_PX = FOLLOW_BOTTOM_THRESHOLD_PX + 64;
49
60
 
50
- /** How long a bottom jump counts as settling. The scroll handler reads "the
51
- * viewport is at the top, fetch older history" from geometry, and a jump that
52
- * STARTS at the top (the button, on a session scrolled back to its head)
53
- * passes through those first pixels — so the paging trigger stands down for
54
- * the jump's duration instead of paging a window the jump must then outrun. */
55
- const JUMP_SETTLE_MS = 1000;
61
+ /** How long after a wheel/touch/pointer/key event an upward scroll still
62
+ * counts as the READER's. Only consulted while a jump is landing: a layout
63
+ * clamp moves `scrollTop` up with nobody behind it, and treating that as the
64
+ * reader taking the viewport back is what cancelled a jump mid-flight. */
65
+ const READER_INPUT_WINDOW_MS = 600;
56
66
 
57
67
  export interface ChatTimelineScrollOptions {
58
68
  /** Called when the viewport reaches the top (history paging trigger).
@@ -97,8 +107,10 @@ export interface ChatTimelineScrollResult {
97
107
  * over the jump (reproduced: the jump stopped ~26k px short of the tail and
98
108
  * only the next click reached it, once no window was left to page in). */
99
109
  jumpCountRef: RefObject<number>;
100
- /** True while a bottom jump is settling ({@link JUMP_SETTLE_MS}); history
101
- * paging stands down meanwhile. */
110
+ /** True while a bottom jump is landing: the jump owns the viewport, so
111
+ * history paging stands down and neither the content observer nor the row
112
+ * window writes a position under it. Released once the viewport has SAT at
113
+ * the tail (see `createJumpLanding`), never on a fixed timer. */
102
114
  jumpActiveRef: RefObject<boolean>;
103
115
  handleScroll: () => void;
104
116
  scrollToBottom: (behavior?: ScrollBehavior) => void;
@@ -110,10 +122,6 @@ export interface ChatTimelineScrollResult {
110
122
  /** Distance from the top that counts as "reached the history boundary". */
111
123
  const SCROLL_TOP_TRIGGER_PX = 40;
112
124
 
113
- /** Pending timeout handle. Named here rather than re-derived per ref because
114
- * the DOM and Bun/Node typings disagree on what `setTimeout` returns. */
115
- type TimeoutHandle = ReturnType<typeof setTimeout>;
116
-
117
125
  export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}): ChatTimelineScrollResult {
118
126
  const onScrollTopRef = useRef<(() => void) | undefined>(options.onScrollTop);
119
127
  onScrollTopRef.current = options.onScrollTop ?? onScrollTopRef.current;
@@ -144,7 +152,14 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
144
152
  // Bottom-jump bookkeeping; see ChatTimelineScrollResult for each ref.
145
153
  const jumpCountRef = useRef(0);
146
154
  const jumpActiveRef = useRef(false);
147
- const jumpTimerRef = useRef<TimeoutHandle>();
155
+ // The landing watch: owns the viewport until the jump has landed.
156
+ const landingRef = useRef<JumpLanding | null>(null);
157
+ // Last time the READER touched the scroller (wheel, touch, pointer, key).
158
+ // `scrollTop` moving up is not enough to tell them from a layout clamp.
159
+ // `-Infinity`, not `0`: the window is compared against `performance.now()`,
160
+ // which starts near zero, so a zero sentinel would read as input on the first
161
+ // moments of a page load.
162
+ const readerInputAtRef = useRef(Number.NEGATIVE_INFINITY);
148
163
 
149
164
  const contentRef = useCallback((node: HTMLDivElement | null) => {
150
165
  setContentNode(node);
@@ -183,10 +198,17 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
183
198
  // mid-animation as content outgrows the animation. Re-engage whenever
184
199
  // the viewport is back near the tail, whichever way it got there.
185
200
  if (el.scrollTop < lastScrollTopRef.current - 1) {
186
- followRef.current = false;
187
- // The user took the viewport back: a jump still settling must not keep
188
- // re-pinning the tail under them.
189
- jumpActiveRef.current = false;
201
+ // An upward move is not automatically the reader's: the row window
202
+ // replacing estimates with measured heights CLAMPS `scrollTop` up, and
203
+ // while a jump is landing that clamp used to cancel the jump outright —
204
+ // the animation stopped mid-flight, the button stayed up, and only the
205
+ // next click (or scrolling the rest of the way by hand) reached the
206
+ // tail. While the guard is up, only real input takes the viewport back.
207
+ const reader = performance.now() - readerInputAtRef.current < READER_INPUT_WINDOW_MS;
208
+ if (!jumpActiveRef.current || reader) {
209
+ followRef.current = false;
210
+ jumpActiveRef.current = false;
211
+ }
190
212
  }
191
213
  if (el.scrollHeight - el.scrollTop - el.clientHeight < FOLLOW_BOTTOM_THRESHOLD_PX) followRef.current = true;
192
214
  lastScrollTopRef.current = el.scrollTop;
@@ -197,6 +219,14 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
197
219
  syncFollowBottom();
198
220
  }, [syncFollowBottom]);
199
221
 
222
+ /** The landing watch, created on first use. Lazily, because the open-session
223
+ * jump runs from a LAYOUT effect — before this hook's own passive effects —
224
+ * and a watch created there must not be replaced by a second one later. */
225
+ const landing = useCallback((): JumpLanding => {
226
+ landingRef.current ??= createJumpLanding({ scrollRef, jumpActiveRef, pinToBottom });
227
+ return landingRef.current;
228
+ }, [pinToBottom]);
229
+
200
230
  const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
201
231
  // Follow-gated: a stream chunk in read mode (user scrolled away) must not
202
232
  // yank the viewport down. jumpToBottom is the explicit bypass.
@@ -209,10 +239,12 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
209
239
  followRef.current = true;
210
240
  jumpActiveRef.current = true;
211
241
  jumpCountRef.current += 1;
212
- clearTimeout(jumpTimerRef.current);
213
- jumpTimerRef.current = setTimeout(() => { jumpActiveRef.current = false; }, JUMP_SETTLE_MS);
242
+ // The click that starts a jump is not a scroll input: the reader has not
243
+ // taken the viewport back, so a clamp right after this must not cancel it.
244
+ readerInputAtRef.current = Number.NEGATIVE_INFINITY;
245
+ landing().start();
214
246
  pinToBottom(behavior);
215
- }, [pinToBottom]);
247
+ }, [landing, pinToBottom]);
216
248
 
217
249
  // Geometry, not events: content that grows without the user scrolling
218
250
  // (history prepending, an accordion expanding, an image decoding, a late
@@ -255,7 +287,10 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
255
287
  if (frame !== null) return;
256
288
  frame = requestAnimationFrame(() => {
257
289
  frame = null;
258
- if (followRef.current) pinToBottom('instant');
290
+ // A jump in flight owns the position: its watch re-aims at the tail
291
+ // itself, and a pin from here would replace a smooth landing with an
292
+ // instant snap on every measurement along the way.
293
+ if (followRef.current && !jumpActiveRef.current) pinToBottom('instant');
259
294
  syncFollowBottom();
260
295
  });
261
296
  });
@@ -267,8 +302,24 @@ export function useChatTimelineScroll(options: ChatTimelineScrollOptions = {}):
267
302
  };
268
303
  }, [contentNode, scrollNode, pinToBottom, syncFollowBottom]);
269
304
 
305
+ // What counts as the reader having taken the viewport back, for
306
+ // `handleScroll`'s upward-scroll test. Wired on the scroller NODE (state, not
307
+ // the ref — the surface is swapped in a commit late), because a wheel, a
308
+ // finger or a key only ever arrives there.
309
+ useEffect(() => {
310
+ if (!scrollNode) return;
311
+ const note = () => {
312
+ readerInputAtRef.current = performance.now();
313
+ };
314
+ const types = ['wheel', 'touchstart', 'touchmove', 'pointerdown', 'keydown'] as const;
315
+ for (const type of types) scrollNode.addEventListener(type, note, { passive: true });
316
+ return () => {
317
+ for (const type of types) scrollNode.removeEventListener(type, note);
318
+ };
319
+ }, [scrollNode]);
320
+
270
321
  useEffect(() => () => {
271
- clearTimeout(jumpTimerRef.current);
322
+ landingRef.current?.stop();
272
323
  }, []);
273
324
 
274
325
  return {
@@ -24,7 +24,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } fr
24
24
  import { Window } from 'happy-dom';
25
25
  import type { h as PreactH, render as PreactRender } from 'preact';
26
26
  import type { act as PreactAct } from 'preact/test-utils';
27
- import type { OpenTabScope, useMissingFiles as UseMissingFilesHook } from '@/client/hooks/workspace/missing-files';
27
+ import type { OpenTabScope, ProbeableTab, useMissingFiles as UseMissingFilesHook } from '@/client/hooks/workspace/missing-files';
28
28
 
29
29
  let useMissingFiles: typeof UseMissingFilesHook;
30
30
  let openTabScopeKey: (tab: OpenTabScope) => string;
@@ -66,8 +66,8 @@ async function settle() {
66
66
  }
67
67
  }
68
68
 
69
- async function mount(tabs: OpenTabScope[], refreshKey = 0) {
70
- const Probe = ({ tabs: current, refreshKey: key }: { tabs: OpenTabScope[]; refreshKey: number }) => {
69
+ async function mount(tabs: ProbeableTab[], refreshKey = 0) {
70
+ const Probe = ({ tabs: current, refreshKey: key }: { tabs: ProbeableTab[]; refreshKey: number }) => {
71
71
  mounted = useMissingFiles(current, key);
72
72
  return null;
73
73
  };
@@ -168,6 +168,23 @@ describe('useMissingFiles', () => {
168
168
  expect([...(mounted ?? [])]).toEqual([1]);
169
169
  });
170
170
 
171
+ test('a tab with no server-backed file is never probed', async () => {
172
+ // Measured on a phone: opening an attachment chip, a launched document or a
173
+ // file in a nested repo struck it through as deleted, because the caller
174
+ // filtered these itself and the phone's caller forgot. The rule now lives in
175
+ // `isProbeableTab`, so this asserts the SKIP for every such tab.
176
+ await mount([
177
+ { id: 'chip', path: 'notes.md', content: '# inline' },
178
+ { id: 'handle', path: 'launched.md', handleId: 'handle-1' },
179
+ { id: 'device', path: 'report.md', deviceFile: true },
180
+ { id: 'diff', path: 'src/a.ts', isDiff: true },
181
+ { id: 'plain', path: 'src/a.ts' },
182
+ ]);
183
+
184
+ expect(probes.map((p) => p.path)).toEqual(['src/a.ts']);
185
+ expect([...(mounted ?? [])]).toEqual(['plain']);
186
+ });
187
+
171
188
  test('the scope key keeps two trees apart', () => {
172
189
  expect(openTabScopeKey({ id: 1, path: 'a.ts', root: '/ws', repo: '.' })).not.toBe(
173
190
  openTabScopeKey({ id: 1, path: 'a.ts', root: '/ws', repo: 'projects/b' }),
@@ -36,6 +36,38 @@ export interface OpenTabScope {
36
36
  repo?: string;
37
37
  }
38
38
 
39
+ /**
40
+ * An open tab as a layout holds it: the scope above, plus the facts that decide
41
+ * whether a probe can say anything true about the file behind it.
42
+ */
43
+ export interface ProbeableTab extends OpenTabScope {
44
+ /** Inline bytes — an attachment chip is a name AND its content, not a file on disk. */
45
+ content?: string;
46
+ /** A launched/dropped file's live handle: no server path exists to `stat`. */
47
+ handleId?: string;
48
+ /** The bytes came from the DEVICE, so there is no path the server can reach. */
49
+ deviceFile?: boolean;
50
+ /** A diff tab's path names a CHANGE, not a document. */
51
+ isDiff?: boolean;
52
+ }
53
+
54
+ /**
55
+ * Whether a probe about this tab means anything.
56
+ *
57
+ * The answer lives HERE, once, because the two layouts that ask it — the desktop
58
+ * tab strip and the phone's full-screen editor — disagreed: the desktop skipped
59
+ * a tab carrying inline `content` and the phone did not, so every attachment
60
+ * chip and every device/handle file opened on a phone was struck through as
61
+ * deleted while its buffer was on screen and perfectly fine. A predicate stated
62
+ * twice is how that happens; neither caller filters on its own any more.
63
+ */
64
+ export function isProbeableTab(tab: ProbeableTab): boolean {
65
+ if (!tab.path) return false;
66
+ if (tab.content !== undefined) return false;
67
+ if (tab.handleId || tab.deviceFile) return false;
68
+ return !tab.isDiff;
69
+ }
70
+
39
71
  /** The scope key a probe's verdict is stored under. Exported for its test. */
40
72
  export function openTabScopeKey(tab: OpenTabScope): string {
41
73
  return `${tab.root ?? ''}\u0000${tab.repo ?? '.'}\u0000${tab.path ?? ''}`;
@@ -66,11 +98,13 @@ async function probeExists(tab: OpenTabScope): Promise<boolean> {
66
98
  * The tab ids whose file is gone.
67
99
  *
68
100
  * `refreshKey` is the workspace's own "something was written" counter, so a
69
- * delete issued from any panel reaches here without a poll. The CALLER decides
70
- * which tabs are plain files — a diff tab and an attachment chip have no file
71
- * behind their `path`, and probing one would strike it through on sight.
101
+ * delete issued from any panel reaches here without a poll. Which tabs can be
102
+ * probed at all is decided HERE (`isProbeableTab`), not at each call site: a
103
+ * diff tab and an attachment chip have no file behind their `path`, and probing
104
+ * one would strike it through on sight — a rule the two layouts used to apply
105
+ * differently, so the phone struck through files the desktop left alone.
72
106
  */
73
- export function useMissingFiles(tabs: readonly OpenTabScope[], refreshKey: number): Set<number | string> {
107
+ export function useMissingFiles(tabs: readonly ProbeableTab[], refreshKey: number): Set<number | string> {
74
108
  const [missing, setMissing] = useState<Set<number | string>>(() => new Set());
75
109
  // Bumped by a focus or a visibility change: the effect below owns the probe,
76
110
  // and re-running it is the whole repair for an external deletion.
@@ -88,9 +122,9 @@ export function useMissingFiles(tabs: readonly OpenTabScope[], refreshKey: numbe
88
122
  useEffect(() => {
89
123
  let cancelled = false;
90
124
  void (async () => {
91
- const probes = new Map<string, OpenTabScope>();
125
+ const probes = new Map<string, ProbeableTab>();
92
126
  for (const tab of tabsRef.current) {
93
- if (tab.path) probes.set(openTabScopeKey(tab), tab);
127
+ if (isProbeableTab(tab)) probes.set(openTabScopeKey(tab), tab);
94
128
  }
95
129
  const results = await Promise.all(
96
130
  [...probes.entries()].map(async ([key, tab]) => ({ key, exists: await probeExists(tab) })),
@@ -102,7 +136,7 @@ export function useMissingFiles(tabs: readonly OpenTabScope[], refreshKey: numbe
102
136
 
103
137
  const next = new Set<number | string>();
104
138
  for (const tab of tabsRef.current) {
105
- if (tab.path && gone.has(openTabScopeKey(tab))) next.add(tab.id);
139
+ if (isProbeableTab(tab) && gone.has(openTabScopeKey(tab))) next.add(tab.id);
106
140
  }
107
141
  // A fresh Set only when the verdict moved: the tab strip is cheap, but a
108
142
  // new identity on every probe would re-render it for nothing.
@@ -404,11 +404,22 @@
404
404
  padding-inline: 1rem;
405
405
  padding-top: 0.875rem;
406
406
  }
407
+ /* STRETCHED, the frosted card covers the transcript instead of sitting under
408
+ * it, so 58% paper stops being a surface and becomes a veil: message text
409
+ * reads through the draft at 42% and the two layers merge (measured: the
410
+ * expanded desktop card overlapped timeline rows at 58% with `blur(16px)`).
411
+ * The stretch exists to write a long prompt against that transcript, so the
412
+ * card must win the overlap — 92% paper keeps the tint and the blurred edge
413
+ * while leaving the text underneath 8% of its contrast. */
414
+ [data-composer-style="glass"][data-composer-expanded="true"] {
415
+ background-color: color-mix(in srgb, var(--theme-paper) 92%, transparent);
416
+ }
407
417
  /* A browser without `backdrop-filter` gets an opaque card rather than a
408
418
  * half-transparent one with nothing behind the blur: a 58% paper card over the
409
419
  * canvas is legible, a 58% card over the transcript is not. */
410
420
  @supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
411
- [data-composer-style="glass"] {
421
+ [data-composer-style="glass"],
422
+ [data-composer-style="glass"][data-composer-expanded="true"] {
412
423
  background-color: var(--theme-paper);
413
424
  }
414
425
  }
@@ -74,6 +74,17 @@ export async function initSchema(db: DbClient): Promise<void> {
74
74
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
75
75
  );
76
76
 
77
+ -- The sidebar's subagent badge, saved per file version so a restart does
78
+ -- not re-derive it by streaming every transcript (see
79
+ -- lib/omp/session/subagent-presence-store). Derived data: deleting the
80
+ -- table only costs one cold pass.
81
+ CREATE TABLE IF NOT EXISTS session_subagent_presence (
82
+ session_path TEXT PRIMARY KEY,
83
+ version TEXT NOT NULL,
84
+ has_subagents INTEGER NOT NULL,
85
+ updated_at INTEGER NOT NULL DEFAULT 0
86
+ );
87
+
77
88
  CREATE TABLE IF NOT EXISTS queued_messages (
78
89
  id TEXT PRIMARY KEY,
79
90
  session_id TEXT NOT NULL,
@@ -13,7 +13,13 @@
13
13
  */
14
14
 
15
15
  import { afterEach, describe, expect, test } from 'bun:test';
16
- import { maintainMemory, snapshot, stopMemoryMaintenance } from '@/server/lib/lifecycle/memory';
16
+ import {
17
+ footprintMBFromOutput,
18
+ footprintMBFromSmapsRollup,
19
+ maintainMemory,
20
+ snapshot,
21
+ stopMemoryMaintenance,
22
+ } from '@/server/lib/lifecycle/memory';
17
23
 
18
24
  const originalCeiling = Bun.env.KABMO_MEMORY_CEILING_MB;
19
25
 
@@ -57,6 +63,40 @@ describe('snapshot', () => {
57
63
  );
58
64
  expect(Math.abs(snapshot().rssMB - Math.round(psKb / 1024))).toBeLessThanOrEqual(2);
59
65
  });
66
+
67
+ test('reports a physical footprint, because RSS is not the memory in use', () => {
68
+ // On macOS a Bun process that has read and dropped a transcript keeps
69
+ // freed pages resident: measured on a live server, RSS 752 MB against a
70
+ // 70.6 MB physical footprint and a 24 MB JS heap. The sweep reacts to the
71
+ // footprint, so it has to be there.
72
+ const snap = snapshot();
73
+ expect(snap.footprintMB).not.toBeNull();
74
+ expect(snap.footprintMB ?? 0).toBeGreaterThan(0);
75
+ // A footprint larger than the resident set would mean the parser read the
76
+ // wrong field; compressed pages can push it close, never past it by much.
77
+ expect(snap.footprintMB ?? 0).toBeLessThanOrEqual(snap.rssMB * 1.25 + 16);
78
+ });
79
+ });
80
+
81
+ describe('footprint parsing', () => {
82
+ test('reads the macOS `footprint -p` headline', () => {
83
+ expect(footprintMBFromOutput('bun [98166]: 64-bit Footprint: 122 MB (16384 bytes per page)')).toBe(122);
84
+ });
85
+
86
+ test('honours the unit the tool prints', () => {
87
+ expect(footprintMBFromOutput(' Footprint: 512 KB (4096 bytes per page)')).toBe(1);
88
+ expect(footprintMBFromOutput(' Footprint: 1.5 GB (16384 bytes per page)')).toBe(1536);
89
+ });
90
+
91
+ test('an unreadable report is null rather than a guess', () => {
92
+ expect(footprintMBFromOutput('')).toBeNull();
93
+ expect(footprintMBFromOutput('some other report')).toBeNull();
94
+ });
95
+
96
+ test('reads Pss from Linux smaps_rollup', () => {
97
+ expect(footprintMBFromSmapsRollup('Rss: 40960 kB\nPss: 12345 kB\nPss_Anon: 1 kB\n')).toBe(12);
98
+ expect(footprintMBFromSmapsRollup('Rss: 40960 kB\n')).toBeNull();
99
+ });
60
100
  });
61
101
 
62
102
  describe('maintainMemory', () => {