@kabmo-labs/kabmo 0.14.0 → 0.14.1

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 (30) 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-bnrrw242.css +1 -0
  4. package/dist/client/static/js/{index-nfsg1jpt.js → index-w6jx0h0p.js} +602 -602
  5. package/marketplace/plugins/command-runner/package.json +2 -2
  6. package/marketplace/plugins/command-runner/src/server/ring.test.ts +41 -0
  7. package/marketplace/plugins/command-runner/src/server/run-types.ts +6 -0
  8. package/marketplace/plugins/command-runner/src/server/runner-harness.ts +69 -0
  9. package/marketplace/plugins/command-runner/src/server/runner-path.test.ts +127 -0
  10. package/marketplace/plugins/command-runner/src/server/runner.test.ts +2 -72
  11. package/marketplace/plugins/command-runner/src/server/runner.ts +31 -3
  12. package/package.json +2 -2
  13. package/src/client/components/common/session-row/index.tsx +11 -1
  14. package/src/client/components/common/session-row/session-row.test.tsx +10 -0
  15. package/src/client/components/layout/session-sidebar/modern/Skeleton.tsx +5 -4
  16. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +11 -2
  17. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +111 -0
  18. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +1 -0
  19. package/src/client/components/workspace/chat-timeline/ThinkingSection.test.tsx +117 -0
  20. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +10 -9
  21. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +21 -1
  22. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +16 -2
  23. package/src/client/hooks/chat/timeline/row-window-reveal.ts +130 -0
  24. package/src/client/hooks/chat/timeline/row-window.test.ts +35 -0
  25. package/src/client/hooks/chat/timeline/row-window.ts +59 -133
  26. package/src/client/hooks/chat/timeline/thinking-open.ts +67 -0
  27. package/src/shared/lib/chat/timeline/trace-groups.test.ts +12 -0
  28. package/src/shared/lib/chat/timeline/trace-groups.ts +29 -2
  29. package/src/shared/lib/workspace/session-state/store.ts +5 -0
  30. package/dist/client/static/js/index-tsgy3gd1.css +0 -1
@@ -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;
@@ -126,12 +92,6 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
126
92
  const [viewport, setViewport] = useState(0);
127
93
  // The scroll container. STATE, not the ref: see `scrollNode` in the deps.
128
94
  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
95
  /**
136
96
  * The viewport belongs to the BOTTOM until the reader scrolls away.
137
97
  *
@@ -157,6 +117,12 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
157
117
  viewportRef.current = viewport;
158
118
  // Bumped per reveal so a superseded one stops writing.
159
119
  const revealGenerationRef = useRef(0);
120
+ /**
121
+ * A reveal is flying: it re-writes its target every frame until it settles,
122
+ * so a measurement must not correct the position underneath it (the two
123
+ * would trade the viewport). See `adopt`.
124
+ */
125
+ const revealingRef = useRef(false);
160
126
 
161
127
  const range = useMemo(
162
128
  () => (enabled ? timelineWindow(layout, scrollTop, viewport) : { start: 0, end: ids.length, padTop: 0, padBottom: 0 }),
@@ -220,26 +186,48 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
220
186
  return changed;
221
187
  };
222
188
  const adopt = (): void => {
189
+ // Which row the reader is looking at, under the geometry they are still
190
+ // seeing: `el.scrollTop` has not moved yet (a browser does not adjust it
191
+ // when content above grows), so the OLD layout is the right one to read
192
+ // the anchor from.
223
193
  const current = timelineWindow(layout, el.scrollTop, el.clientHeight, 0);
224
194
  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
- };
195
+ // A reader parked at the tail follows the TAIL, not the row that happened
196
+ // to be at the top of the viewport: the rows below it are estimates until
197
+ // they mount, so a row anchor would leave the viewport short of the
198
+ // bottom — measured at 775 px on an opened session, which is past the
199
+ // 100 px threshold that decides whether the stream keeps following.
200
+ // Measured against the PREVIOUS layout, not the DOM: this effect runs
201
+ // after the content already grew, so the DOM's own distance is the
202
+ // growth itself. A reader who was at the bottom before a row was measured
203
+ // taller must stay at the bottom — measured against the DOM they were
204
+ // left 2 080 px short, i.e. outside follow mode.
205
+ const tail = tailPinRef.current
206
+ || layout.total - scrollTop - (viewport || el.clientHeight) <= TAIL_ANCHOR_PX;
207
+ const offset = anchorId ? el.scrollTop - layout.offsets[current.start] : 0;
208
+
209
+ // The correction is written HERE, against the new layout, not deferred to
210
+ // an effect that runs after this commit. Deferring it is what made an
211
+ // expanded thinking block snap shut: the restore effect for the SAME
212
+ // commit still holds the pre-measurement layout, so it consumed the
213
+ // anchor and wrote the reader's old offset; the next commit then had no
214
+ // anchor left, `scrollTop` was still stale, and the mounted WINDOW moved
215
+ // one row — unmounting and remounting the rows at its edge (measured in
216
+ // the browser: three rows removed and re-added per expand), which throws
217
+ // away every block's local state.
218
+ const next = layoutTimelineRows(ids, measuredRef.current);
219
+ const target = tail || !anchorId
220
+ ? Math.max(0, el.scrollHeight - el.clientHeight)
221
+ : next.offsets[rowIndex(ids, anchorId)] + offset;
222
+ tailPinRef.current = tail;
223
+ // A reveal OWNS the viewport until it settles: it re-writes its target
224
+ // every frame, so a correction here would be written back over it and the
225
+ // two would trade the viewport (measured before this guard existed: the
226
+ // 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) {
229
+ setScrollTop(target);
230
+ writeScrollTop(el, target);
243
231
  }
244
232
  setVersion((value) => value + 1);
245
233
  };
@@ -266,80 +254,18 @@ export function useTimelineRowWindow({ ids, scrollRef, scrollNode, enabled = tru
266
254
 
267
255
  // Restore the reading position after the layout moved under it.
268
256
  useLayoutEffect(() => {
269
- const anchor = anchorRef.current;
270
- if (!anchor) return;
271
- anchorRef.current = null;
272
257
  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]);
258
+ if (!el || !tailPinRef.current) return;
259
+ // The tail pin outlives a commit: the rows above it are estimates until
260
+ // they mount, so every measurement can move the bottom by its own error.
261
+ // The bottom edge is the anchor. `writeScrollTop`, because the container
262
+ // carries `scroll-smooth`: a bare `scrollTop` assignment animates, and a
263
+ // correction that animates is a correction that arrives late.
264
+ writeScrollTop(el, Math.max(0, el.scrollHeight - el.clientHeight));
265
+ }, [layout, element]);
292
266
 
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
- },
267
+ const revealRow = useMemo(
268
+ () => createRevealRow({ scrollRef, idsRef, layoutRef, viewportRef, tailPinRef, revealingRef, generationRef: revealGenerationRef }),
343
269
  [scrollRef],
344
270
  );
345
271
 
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Whether a thinking block is open, remembered per session and per message.
8
+ *
9
+ * The accordion kept this in a plain `useState`, and that was survivable while
10
+ * every row stayed mounted for the life of the session. It is not survivable
11
+ * now: `MessageList` mounts a WINDOW of rows (`useTimelineRowWindow`), so a
12
+ * block is unmounted whenever the window moves past it — which an expand does
13
+ * by itself, because the row it opens grows and the reader parked at the tail
14
+ * follows the new bottom. Measured in the browser on a real session: the click
15
+ * opened the body, the next measurement moved the viewport, the row unmounted
16
+ * and remounted with a fresh `useState(false)`, and the block was closed again
17
+ * — "sometimes it works" being exactly the case where enough content sat below
18
+ * the row to keep it mounted.
19
+ *
20
+ * The tool cards already answer this by persisting their openness per session
21
+ * (`useToolOpenState`), so this is the same rule for the same reason, not a
22
+ * second convention: a block's open state belongs to the conversation.
23
+ *
24
+ * Only a choice the reader MADE is stored. A generating run opens by default,
25
+ * and writing that default per block would put a row in the session blob for
26
+ * every thought the model produced.
27
+ */
28
+
29
+ import { useEffect, useState } from 'preact/hooks';
30
+ import { useSessionState } from '@/client/hooks/workspace/session-state';
31
+
32
+ /** Session slot holding `{ [messageId]: open }` for the blocks the reader toggled. */
33
+ export const THINKING_OPEN_STATE_KEY = 'chat.thinkingOpen';
34
+
35
+ export interface ThinkingOpenState {
36
+ isOpen: boolean;
37
+ toggle: () => void;
38
+ }
39
+
40
+ /**
41
+ * `messageId` is optional so a block mounted outside a session (a spec, a
42
+ * preview) still toggles — it just cannot remember the choice.
43
+ */
44
+ export function useThinkingOpenState(
45
+ messageId: string | undefined,
46
+ defaultOpen: boolean,
47
+ isGenerating: boolean,
48
+ ): ThinkingOpenState {
49
+ const [stored, setStored] = useSessionState<Record<string, boolean>>(THINKING_OPEN_STATE_KEY, {});
50
+ const [local, setLocal] = useState(defaultOpen || isGenerating);
51
+ const choice = messageId ? stored[messageId] : undefined;
52
+
53
+ // A run that starts streaming opens itself, as it always has. This is the
54
+ // local half on purpose: the stored half is the reader's own choice, and it
55
+ // must not be overwritten by a default.
56
+ useEffect(() => {
57
+ if (isGenerating) setLocal(true);
58
+ }, [isGenerating]);
59
+
60
+ const isOpen = choice ?? local;
61
+ const toggle = (): void => {
62
+ const next = !isOpen;
63
+ setLocal(next);
64
+ if (messageId) setStored((prev) => ({ ...prev, [messageId]: next }));
65
+ };
66
+ return { isOpen, toggle };
67
+ }
@@ -80,6 +80,18 @@ describe('trace grouping', () => {
80
80
  expect(groups[0].trace).toBe(true);
81
81
  });
82
82
 
83
+ test('a truncated run keeps the key of its first row, so a window shift cannot remount it', () => {
84
+ // The timeline mounts a WINDOW of rows, so the run is routinely rendered
85
+ // from the middle. Keying the group by `rows[0]` renamed it every time a
86
+ // measurement moved `start` by one row, and a renamed key remounts the
87
+ // whole run — which threw away the thinking accordion's own open state
88
+ // (measured: one expand removed and re-added all 14 rows of the run).
89
+ const whole = groupTraceRows(TURN, 1, 4);
90
+ const shifted = groupTraceRows(TURN, 2, 4);
91
+ expect(whole[0].key).toBe('a1');
92
+ expect(shifted[0].key).toBe(whole[0].key);
93
+ });
94
+
83
95
  test('hasTraceContent reads each shape omp writes', () => {
84
96
  expect(hasTraceContent({ id: 'x', role: 'ai', content: '', notice: 'n' } as unknown as ChatMessageData)).toBe(true);
85
97
  expect(hasTraceContent({ id: 'x', role: 'ai', content: '', thinking: { thought: 't' } } as unknown as ChatMessageData)).toBe(true);
@@ -22,7 +22,20 @@ import type { ChatMessageData } from '@/shared/types/chat';
22
22
  import { isNoticeRow } from '@/shared/lib/chat/notice-row';
23
23
 
24
24
  export interface TraceGroup {
25
- /** React key: the first row's id. */
25
+ /**
26
+ * Render key: the id of the row that STARTS the run — which is the window's
27
+ * first row only when the window happens to begin at the run's first row.
28
+ *
29
+ * It used to be `rows[0]` unconditionally, and that is what made a block
30
+ * inside a run collapse the moment it was expanded. The timeline mounts a
31
+ * WINDOW of rows, so every measurement that moved the window's `start` by one
32
+ * row renamed the group; a renamed `key` remounts the whole run, and a
33
+ * remount throws away every block's local state — the thinking accordion's
34
+ * own `useState` included, which is why expanding a thought snapped shut
35
+ * again (measured in the browser: one click removed and re-added all 14 rows
36
+ * of the run). A key derived from the run's first row is the same string for
37
+ * every window that covers part of that run.
38
+ */
26
39
  key: string;
27
40
  /** Indices into the caller's `messages` array, in order. */
28
41
  rows: number[];
@@ -40,12 +53,26 @@ export function hasTraceContent(msg: ChatMessageData): boolean {
40
53
  return Boolean((msg.toolCalls?.length ?? 0) || (msg.actions?.length ?? 0) || (msg.actions2?.length ?? 0));
41
54
  }
42
55
 
56
+ /**
57
+ * The absolute index where the run containing `index` begins: the first row
58
+ * after the previous user row. Walks back past the window's own `start`,
59
+ * because the key must not depend on where the window happens to begin.
60
+ */
61
+ function runStartIndex(messages: ChatMessageData[], index: number): number {
62
+ let cursor = index;
63
+ while (cursor > 0 && messages[cursor - 1].role !== 'user') cursor -= 1;
64
+ return cursor;
65
+ }
66
+
43
67
  /**
44
68
  * Group `messages[start, end)` into render units.
45
69
  *
46
70
  * A user row is its own unit; every other row joins the run above it. The
47
71
  * group's `trace` is the OR of its rows' trace content, so a run whose steps sit
48
72
  * on one row and whose answer sits on the next still draws one line across both.
73
+ *
74
+ * A truncated run keeps the key of its FIRST row, outside the window included —
75
+ * see `TraceGroup.key`.
49
76
  */
50
77
  export function groupTraceRows(messages: ChatMessageData[], start = 0, end = messages.length): TraceGroup[] {
51
78
  const groups: TraceGroup[] = [];
@@ -62,7 +89,7 @@ export function groupTraceRows(messages: ChatMessageData[], start = 0, end = mes
62
89
  open.trace = open.trace || hasTraceContent(msg);
63
90
  continue;
64
91
  }
65
- groups.push({ key: msg.id, rows: [idx], trace: hasTraceContent(msg) });
92
+ groups.push({ key: messages[runStartIndex(messages, idx)].id, rows: [idx], trace: hasTraceContent(msg) });
66
93
  }
67
94
  return groups;
68
95
  }
@@ -66,6 +66,11 @@
66
66
  * from another conversation is never restored
67
67
  * - chat.draft string
68
68
  * - chat.draftAttachments attachment metadata array
69
+ * - chat.toolOpen Record<toolId, boolean> — the tool cards the
70
+ * reader opened or closed (see `useToolOpenState`)
71
+ * - chat.thinkingOpen Record<messageId, boolean> — the same for the
72
+ * thinking accordions (`useThinkingOpenState`), so a
73
+ * block stays open when the row window unmounts it
69
74
  *
70
75
  * The module is three files, because one had passed the per-file ceiling: this
71
76
  * one owns the PUBLIC API (read, write, load, migrate) and what a write means;