@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
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A thinking block's open state belongs to the conversation, not to the mounted
8
+ * component instance.
9
+ *
10
+ * The defect this pins: the accordion kept its openness in a local
11
+ * `useState`, and `MessageList` mounts a WINDOW of rows. Expanding a thought
12
+ * grows its row, the next measurement moves the viewport, the row leaves the
13
+ * window and comes back with a fresh `useState(false)` — so the block snapped
14
+ * shut, and whether it did depended on how much content sat below it ("sometimes
15
+ * it works"). Measured in the browser on a real session: one click removed and
16
+ * re-added every row at the window's edge.
17
+ *
18
+ * Mounted against happy-dom and driven through the rendered button, because the
19
+ * claim is about what a click on the real control does across a remount.
20
+ */
21
+
22
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
23
+ import { Window } from 'happy-dom';
24
+ import { h, render } from 'preact';
25
+ import { act } from 'preact/test-utils';
26
+ import { ThinkingSection } from '@/client/components/workspace/chat-timeline/ThinkingSection';
27
+ import { SessionStateProvider } from '@/client/components/common/session-state-provider';
28
+ import { forgetSession } from '@/shared/lib/workspace/session-state/store';
29
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
30
+
31
+ const SESSION = 'spec-thinking-open';
32
+ /** The runner's own fetch, so a leaked stub cannot be mistaken for it. */
33
+ const nativeFetch = Bun.fetch;
34
+
35
+ let container: HTMLElement;
36
+
37
+ const THOUGHT = { thought: 'Read the summary module, then patch the header row.', duration: '1.2s' };
38
+
39
+ beforeAll(() => installDomGlobals(new Window({ url: 'http://localhost' })));
40
+ afterAll(() => restoreDomGlobals());
41
+
42
+ beforeEach(() => {
43
+ container = document.createElement('div');
44
+ document.body.appendChild(container);
45
+ (globalThis as unknown as Record<string, unknown>).fetch = async () =>
46
+ new Response(JSON.stringify({ sessionId: SESSION, state: {} }), {
47
+ status: 200,
48
+ headers: { 'content-type': 'application/json' },
49
+ });
50
+ });
51
+
52
+ afterEach(() => {
53
+ render(null, container);
54
+ container.remove();
55
+ forgetSession(SESSION);
56
+ (globalThis as unknown as Record<string, unknown>).fetch = nativeFetch;
57
+ });
58
+
59
+ async function mount(messageId: string, thinking: typeof THOUGHT & { isGenerating?: boolean } = THOUGHT): Promise<void> {
60
+ await act(async () => {
61
+ render(
62
+ h(SessionStateProvider, {
63
+ sessionId: SESSION,
64
+ children: h(ThinkingSection, { thinking, messageId }),
65
+ }) as never,
66
+ container,
67
+ );
68
+ });
69
+ for (let i = 0; i < 4; i += 1) await act(async () => {});
70
+ }
71
+
72
+ function toggle(): HTMLButtonElement {
73
+ const button = container.querySelector<HTMLButtonElement>('button[aria-expanded]');
74
+ if (!button) throw new Error('no thinking toggle');
75
+ return button;
76
+ }
77
+
78
+ async function click(): Promise<void> {
79
+ await act(async () => { toggle().click(); });
80
+ }
81
+
82
+ describe('thinking open state', () => {
83
+ test('a block starts closed and a click opens it', async () => {
84
+ await mount('m1');
85
+ expect(toggle().getAttribute('aria-expanded')).toBe('false');
86
+ await click();
87
+ expect(toggle().getAttribute('aria-expanded')).toBe('true');
88
+ });
89
+
90
+ test('the choice survives the row being unmounted and remounted', async () => {
91
+ await mount('m1');
92
+ await click();
93
+ // What the timeline's row window does when the expanded row grows and the
94
+ // reader moves: the row leaves the DOM and comes back.
95
+ render(null, container);
96
+ await mount('m1');
97
+ expect(toggle().getAttribute('aria-expanded')).toBe('true');
98
+ });
99
+
100
+ test('each row remembers its own choice', async () => {
101
+ await mount('m1');
102
+ await click();
103
+ render(null, container);
104
+ await mount('m2');
105
+ expect(toggle().getAttribute('aria-expanded')).toBe('false');
106
+ });
107
+
108
+ test('a generating run opens itself, and closing it during the run sticks', async () => {
109
+ await mount('m1', { ...THOUGHT, isGenerating: true });
110
+ expect(toggle().getAttribute('aria-expanded')).toBe('true');
111
+
112
+ // The reader closes it mid-run. The run is still generating, so a default
113
+ // re-applied on the next frame would re-open it under their cursor.
114
+ await click();
115
+ expect(toggle().getAttribute('aria-expanded')).toBe('false');
116
+ });
117
+ });
@@ -23,7 +23,7 @@
23
23
  * a tool card with a title of "Thinking".
24
24
  */
25
25
 
26
- import { useEffect, useRef, useState } from 'preact/hooks';
26
+ import { useEffect, useRef } from 'preact/hooks';
27
27
  import { BrainCircuit, ChevronDown, Sparkles } from 'lucide-preact';
28
28
  import type { ThinkingData } from '@/shared/types';
29
29
  import { MarkdownRenderer } from '@/client/components/common/MarkdownRenderer';
@@ -31,9 +31,16 @@ import { CopyButton } from '@/client/components/common/CopyButton';
31
31
  import { transcriptGutter } from '@/shared/lib/chat/timeline/gutter';
32
32
  import { blockChrome, traceInset } from '@/shared/lib/chat/timeline/block-chrome';
33
33
  import { useToolRenderMode } from '@/client/hooks/chat/timeline/tool-render-mode';
34
+ import { useThinkingOpenState } from '@/client/hooks/chat/timeline/thinking-open';
34
35
 
35
36
  interface ThinkingSectionProps {
36
37
  thinking: ThinkingData | string;
38
+ /**
39
+ * The row this block belongs to, and the key its open state is stored under.
40
+ * Optional: a block mounted outside a timeline still toggles, it just cannot
41
+ * remember the choice across the row being unmounted (see `thinking-open`).
42
+ */
43
+ messageId?: string;
37
44
  defaultExpanded?: boolean;
38
45
  showSeparator?: boolean;
39
46
  /** Phone layout: the section's frame is the timeline gutter itself. */
@@ -42,6 +49,7 @@ interface ThinkingSectionProps {
42
49
 
43
50
  export function ThinkingSection({
44
51
  thinking,
52
+ messageId,
45
53
  defaultExpanded = false,
46
54
  showSeparator = false,
47
55
  isMobile = false,
@@ -51,13 +59,9 @@ export function ThinkingSection({
51
59
  const framed = mode === 'card';
52
60
 
53
61
  const isGenerating = typeof thinking === 'object' ? Boolean(thinking.isGenerating) : false;
54
- const [isOpen, setIsOpen] = useState(defaultExpanded || isGenerating);
62
+ const { isOpen, toggle: toggleOpen } = useThinkingOpenState(messageId, defaultExpanded, isGenerating);
55
63
  const thoughtBodyRef = useRef<HTMLDivElement>(null);
56
64
 
57
- useEffect(() => {
58
- if (isGenerating) setIsOpen(true);
59
- }, [isGenerating]);
60
-
61
65
  const thoughtText = typeof thinking === 'string' ? thinking : thinking.thought || '';
62
66
  const noticeMatch = thoughtText.match(/<system-notice[^>]*>([\s\S]*?)<\/system-notice>/);
63
67
  const noticeText = noticeMatch?.[1]?.trim() ?? '';
@@ -73,10 +77,7 @@ export function ThinkingSection({
73
77
  if (el) el.scrollTop = el.scrollHeight;
74
78
  }, [isOpen, cleanThought, isGenerating]);
75
79
 
76
- const toggleOpen = () => setIsOpen(prev => !prev);
77
-
78
80
  if (!cleanThought) return null;
79
-
80
81
  const iconTone = framed ? 'bg-ink/5 text-ink/70' : 'text-ink/40';
81
82
 
82
83
  return (
@@ -23,12 +23,18 @@ import { h, render } from 'preact';
23
23
  import { act } from 'preact/test-utils';
24
24
  import { ThinkingSection } from '@/client/components/workspace/chat-timeline/ThinkingSection';
25
25
  import { SystemNotice } from '@/client/components/workspace/chat-timeline/SystemNotice';
26
+ import { SessionStateProvider } from '@/client/components/common/session-state-provider';
26
27
  import { primeKabmoSettings } from '@/shared/lib/settings/client';
27
28
  import { applyToolRenderMode } from '@/client/hooks/chat/timeline/tool-render-mode';
28
29
  import { blockChrome } from '@/shared/lib/chat/timeline/block-chrome';
30
+ import { forgetSession } from '@/shared/lib/workspace/session-state/store';
29
31
  import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
30
32
 
31
33
  let container: HTMLElement;
34
+ /** The runner's own fetch, so a leaked stub cannot be mistaken for it. */
35
+ const nativeFetch = Bun.fetch;
36
+ /** A pending id: the provider loads it like any other and nothing is stored. */
37
+ const SESSION = 'spec-block-chrome';
32
38
 
33
39
  beforeAll(() => installDomGlobals(new Window({ url: 'http://localhost' })));
34
40
  afterAll(() => restoreDomGlobals());
@@ -40,11 +46,20 @@ beforeEach(() => {
40
46
  // completed (`Cannot call beforeEach() after the test run has completed`).
41
47
  container = document.createElement('div');
42
48
  document.body.appendChild(container);
49
+ // The blocks remember their openness per session, so the provider they are
50
+ // mounted under asks for this session's blob.
51
+ (globalThis as unknown as Record<string, unknown>).fetch = async () =>
52
+ new Response(JSON.stringify({ sessionId: SESSION, state: {} }), {
53
+ status: 200,
54
+ headers: { 'content-type': 'application/json' },
55
+ });
43
56
  });
44
57
 
45
58
  afterEach(() => {
46
59
  render(null, container);
47
60
  container.remove();
61
+ forgetSession(SESSION);
62
+ (globalThis as unknown as Record<string, unknown>).fetch = nativeFetch;
48
63
  });
49
64
 
50
65
  /** A thought long enough that the block renders (an empty one renders nothing). */
@@ -59,9 +74,14 @@ async function paint(style: string, node: preact.ComponentChildren): Promise<HTM
59
74
  // paint would assert against the previous style.
60
75
  render(null, container);
61
76
  primeKabmoSettings({ kabmo_settings: { toolRenderStyle: style } });
77
+ // The blocks remember their openness per session (`useToolOpenState`,
78
+ // `useThinkingOpenState`), so they are mounted the way the timeline mounts
79
+ // them: inside the provider.
62
80
  await act(async () => {
63
- render(node as never, container);
81
+ render(h(SessionStateProvider, { sessionId: SESSION, children: node }) as never, container);
64
82
  });
83
+ // The provider's blob load settles across a tick.
84
+ for (let i = 0; i < 4; i += 1) await act(async () => {});
65
85
  return container;
66
86
  }
67
87
 
@@ -36,10 +36,24 @@ export function SvgPreview({ content, name }: SvgPreviewProps) {
36
36
  {/* A checkerboard would be wrong here: an SVG is normally opaque or
37
37
  intended to sit on a surface, and the panel's paper is that surface.
38
38
  The SVG scales to the container via the CSS below rather than a
39
- measured size, so no layout pass is needed. */}
39
+ measured size, so no layout pass is needed.
40
+
41
+ `w-full` on the wrapper is load-bearing, not cosmetic. A flex item is
42
+ shrink-to-fit, and an SVG that carries only a `viewBox` — no `width`
43
+ or `height` attributes, which is how most icon SVGs ship — defaults to
44
+ `width:100%` of its containing block. With no definite width above it,
45
+ that resolves against itself and the picture collapses to a 0x0 box:
46
+ the markup is in the DOM and nothing is drawn. The wrapper takes the
47
+ row's width, and the SVG then fills it, keeping its aspect ratio and
48
+ capped by `max-h`.
49
+
50
+ `mx-auto` pays for that width: an SVG that DOES declare its own size
51
+ is narrower than the wrapper, and the row's `justify-center` no longer
52
+ reaches it through a full-width child. It is a no-op for the filling
53
+ case above. */}
40
54
  <div className="flex min-h-full items-center justify-center p-6">
41
55
  <div
42
- className="svg-preview max-w-full [&>svg]:h-auto [&>svg]:max-h-[80vh] [&>svg]:w-auto [&>svg]:max-w-full"
56
+ className="svg-preview w-full max-w-full [&>svg]:mx-auto [&>svg]:block [&>svg]:h-auto [&>svg]:max-h-[80vh] [&>svg]:w-auto [&>svg]:max-w-full"
43
57
  role="img"
44
58
  aria-label={name}
45
59
  dangerouslySetInnerHTML={{ __html: safeSvg }}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `revealRow` — scroll a row into the middle of the viewport, mounting it if the
8
+ * window does not cover it yet.
9
+ *
10
+ * Split out of `row-window.ts` so that hook stays under the repo's per-file
11
+ * ceiling; the loop is a self-contained piece with its own timing rules, and it
12
+ * talks to the hook only through refs (which is what lets it keep correcting for
13
+ * seconds without a re-render).
14
+ *
15
+ * The landing is never a single write. The rows a jump just mounted are
16
+ * measured on later commits — a tool card's output arrives through a deferred
17
+ * highlight, an image decodes, an accordion opens — and every measurement above
18
+ * the target moves it. Measured here, a fixed short window left a jump to the
19
+ * newest turn 300 px short of the tail: outside `scroll.ts`'s 100 px follow
20
+ * threshold, so the stream silently stopped following after the jump.
21
+ */
22
+
23
+ import type { RowLayout } from '@/shared/lib/chat/timeline/row-window';
24
+ import { rowIndex, rowScrollOffset } from '@/shared/lib/chat/timeline/row-window';
25
+
26
+ /** How long a reveal keeps correcting after it first moves the viewport. */
27
+ const REVEAL_SETTLE_MS = 3000;
28
+
29
+ /** Consecutive still frames that end a reveal early — the layout has settled. */
30
+ const REVEAL_STILL_FRAMES = 10;
31
+
32
+ /** How long a reveal waits for a row the pager is still bringing in. */
33
+ const REVEAL_DEADLINE_MS = 3000;
34
+
35
+ /**
36
+ * Write a scroll position that is meant to LAND, not to animate.
37
+ *
38
+ * The timeline container carries Tailwind's `scroll-smooth`, and CSS
39
+ * `scroll-behavior` applies to a `scrollTop` ASSIGNMENT too (CSSOM-View:
40
+ * the setter scrolls with `behavior: auto`, which resolves to the element's
41
+ * computed `scroll-behavior`). So `el.scrollTop = target` started a smooth
42
+ * animation, the reveal's correction loop re-targeted it every frame, and the
43
+ * jump was left mid-flight wherever the loop stopped — measured on a
44
+ * 240-message session: the trace walked 9 804 → 6 504 px and stayed there.
45
+ * `behavior: 'instant'` is the one value CSS cannot override.
46
+ */
47
+ export function writeScrollTop(el: HTMLElement, top: number): void {
48
+ if (Math.abs(el.scrollTop - top) <= 1) return;
49
+ el.scrollTo({ top, behavior: 'instant' });
50
+ }
51
+
52
+ export interface RevealRowDeps {
53
+ /** The timeline's scroll container, read at call time (it is swapped in late). */
54
+ scrollRef: { current: HTMLDivElement | null };
55
+ idsRef: { current: readonly string[] };
56
+ layoutRef: { current: RowLayout };
57
+ viewportRef: { current: number };
58
+ /** Set when the landing is the newest turn; the tail is an anchor of its own. */
59
+ tailPinRef: { current: boolean };
60
+ /** True while a reveal owns the viewport, so a measurement stands down. */
61
+ revealingRef: { current: boolean };
62
+ /** Bumped per reveal: a superseded one stops writing. */
63
+ generationRef: { current: number };
64
+ }
65
+
66
+ /**
67
+ * Build the reveal function. Every dep is a ref, so the returned function is
68
+ * stable for the life of the hook and never re-creates the loop mid-flight.
69
+ */
70
+ export function createRevealRow(deps: RevealRowDeps): (id: string) => Promise<void> {
71
+ return (id: string): Promise<void> => {
72
+ const el = deps.scrollRef.current;
73
+ if (!el) return Promise.resolve();
74
+ const deadline = Date.now() + REVEAL_DEADLINE_MS;
75
+ const settleBy = Date.now() + REVEAL_SETTLE_MS;
76
+ // Supersedes an earlier reveal: two rail clicks in a row must land on the
77
+ // SECOND turn, not race each other to the first one's position.
78
+ const generation = (deps.generationRef.current += 1);
79
+ deps.revealingRef.current = true;
80
+ const { promise, resolve } = Promise.withResolvers<void>();
81
+ let stillFrames = 0;
82
+ let lastTop = -1;
83
+ const finish = (): void => {
84
+ // Only the reveal that still owns the generation clears the flag: a
85
+ // superseded one must not hand the viewport to a correction while its
86
+ // successor is still flying.
87
+ if (generation === deps.generationRef.current) deps.revealingRef.current = false;
88
+ resolve();
89
+ };
90
+ const step = (): void => {
91
+ if (generation !== deps.generationRef.current) {
92
+ finish();
93
+ return;
94
+ }
95
+ const rows = deps.idsRef.current;
96
+ const index = rowIndex(rows, id);
97
+ if (index < 0) {
98
+ // The pager may still be bringing the row in; keep asking until the
99
+ // deadline rather than scrolling to a row that does not exist yet.
100
+ if (Date.now() < deadline) requestAnimationFrame(step);
101
+ else finish();
102
+ return;
103
+ }
104
+ const current = deps.layoutRef.current;
105
+ const view = el.clientHeight || deps.viewportRef.current;
106
+ // The newest turn is the TAIL, not the centre of the last row: that is
107
+ // what the reader means by jumping there, and it is what lets follow mode
108
+ // re-engage (the scroll handler's threshold is 100 px).
109
+ deps.tailPinRef.current = index === rows.length - 1;
110
+ writeScrollTop(
111
+ el,
112
+ deps.tailPinRef.current
113
+ ? Math.max(0, el.scrollHeight - view)
114
+ : rowScrollOffset(current, index, view),
115
+ );
116
+ // A row that was just mounted is measured on a later commit; the
117
+ // corrections land on the MEASURED position rather than the estimate the
118
+ // first write used.
119
+ stillFrames = Math.abs(el.scrollTop - lastTop) <= 1 ? stillFrames + 1 : 0;
120
+ lastTop = el.scrollTop;
121
+ if (stillFrames >= REVEAL_STILL_FRAMES || Date.now() >= settleBy) {
122
+ finish();
123
+ return;
124
+ }
125
+ requestAnimationFrame(step);
126
+ };
127
+ requestAnimationFrame(step);
128
+ return promise;
129
+ };
130
+ }
@@ -208,4 +208,39 @@ describe('useTimelineRowWindow', () => {
208
208
 
209
209
  expect(scroller.scrollTop).toBe(soloTop);
210
210
  });
211
+
212
+ test('a row growing above the viewport keeps the mounted window and the reader', async () => {
213
+ // An expanded thinking block grows the row it sits in. The correction has
214
+ // to land in the SAME commit as the measurement: a deferred restore runs
215
+ // with the pre-measurement layout, so the next commit has no anchor left,
216
+ // the window re-derives from a stale `scrollTop`, and the rows at its edge
217
+ // unmount — measured in the browser as three rows removed and re-added per
218
+ // expand, which throws away every block's local state (an expanded thought
219
+ // snapping shut).
220
+ const scroller = installScroller(20_000);
221
+ const heights = new Map<string, number>();
222
+ for (let i = 0; i < ROWS; i += 1) {
223
+ const node = document.createElement('div');
224
+ node.dataset.rowId = `r-${i}`;
225
+ node.getBoundingClientRect = () => ({ height: heights.get(node.dataset.rowId!) ?? ROW_HEIGHT }) as DOMRect;
226
+ scroller.appendChild(node);
227
+ }
228
+ await mount(scroller);
229
+ await act(async () => {});
230
+ const opened = rowWindow!.start;
231
+ const before = scroller.scrollTop;
232
+ expect(opened).toBeGreaterThan(0);
233
+
234
+ heights.set('r-50', ROW_HEIGHT + 1_000);
235
+ // What the timeline does on the click: a re-render, then the measure
236
+ // effect adopts the grown row.
237
+ await act(async () => { render(h(Probe, { node: scroller }), container); });
238
+ drainFrames();
239
+ await act(async () => {});
240
+
241
+ expect(rowWindow!.start).toBe(opened);
242
+ // The row the reader was on kept its place: the 1 000 px that appeared
243
+ // above it moved the offset by exactly that much.
244
+ expect(scroller.scrollTop).toBe(before + 1_000);
245
+ });
211
246
  });