@kabmo-labs/kabmo 0.26.0 → 0.27.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 (71) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +164 -164
  3. package/dist/client/static/js/index-32rpkj6b.css +1 -0
  4. package/dist/client/static/js/{index-95b3n20k.js → index-e3qh2yps.js} +668 -668
  5. package/package.json +1 -1
  6. package/src/client/components/common/Toast.test.tsx +28 -2
  7. package/src/client/components/common/Toast.tsx +21 -9
  8. package/src/client/components/layout/desktop-layout/LeftColumn.tsx +2 -1
  9. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +2 -1
  10. package/src/client/components/layout/session-sidebar/SessionList.tsx +2 -1
  11. package/src/client/components/layout/session-sidebar/about-modal/UpdateSection.tsx +3 -2
  12. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +2 -1
  13. package/src/client/components/layout/session-sidebar/modern/RevealRow.tsx +56 -0
  14. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +10 -28
  15. package/src/client/components/layout/session-sidebar/modern/reveal-row.test.tsx +104 -0
  16. package/src/client/components/layout/session-sidebar/scheduler-modal/index.tsx +2 -1
  17. package/src/client/components/layout/session-sidebar/variant-props.ts +2 -1
  18. package/src/client/components/mobile/SessionSidebar.tsx +2 -1
  19. package/src/client/components/mobile/mobile-session-sidebar/ClassicDrawer.tsx +2 -1
  20. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +2 -1
  21. package/src/client/components/mobile/mobile-session-sidebar/List.tsx +2 -1
  22. package/src/client/components/settings/Modal.tsx +1 -1
  23. package/src/client/components/settings/categories/project-settings/WorktreeSettings.tsx +2 -1
  24. package/src/client/components/settings/categories/usage-settings/LimitsSection.tsx +39 -19
  25. package/src/client/components/settings/categories/usage-settings/ProviderDetail.tsx +1 -0
  26. package/src/client/components/settings/categories/usage-settings/limit-groups.test.ts +94 -0
  27. package/src/client/components/settings/categories/usage-settings/limit-groups.ts +118 -0
  28. package/src/client/components/settings/categories/usage-settings/limits-section.test.tsx +118 -0
  29. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +58 -54
  30. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +11 -1
  31. package/src/client/components/workspace/chat-timeline/PendingTranscript.tsx +130 -0
  32. package/src/client/components/workspace/chat-timeline/fork-preview.test.tsx +141 -0
  33. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  34. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +2 -1
  35. package/src/client/components/workspace/chat-timeline/target-picker/WorktreePicker.tsx +5 -4
  36. package/src/client/components/workspace/git-panel/index.tsx +2 -2
  37. package/src/client/components/workspace/terminal-panel/RealtimeTerminalView.tsx +8 -5
  38. package/src/client/components/workspace/terminal-panel/index.tsx +3 -0
  39. package/src/client/hooks/chat/omp/session-list.tsx +5 -0
  40. package/src/client/hooks/chat/omp/sidebar-reload.test.ts +85 -0
  41. package/src/client/hooks/chat/omp/sidebar-reload.ts +30 -0
  42. package/src/client/hooks/chat/timeline/fork-preview.test.ts +148 -0
  43. package/src/client/hooks/chat/timeline/fork-preview.ts +104 -0
  44. package/src/client/hooks/chat/timeline/fork-send.test.ts +139 -0
  45. package/src/client/hooks/chat/timeline/pending-branch.ts +9 -0
  46. package/src/client/hooks/chat/timeline/pending-dispatch.ts +49 -0
  47. package/src/client/hooks/chat/timeline/stop-with-queue.ts +1 -1
  48. package/src/client/hooks/chat/waiting/cancel.ts +2 -1
  49. package/src/client/hooks/chat/waiting/dispatch.ts +5 -4
  50. package/src/client/hooks/chat/waiting/held.ts +2 -1
  51. package/src/client/hooks/settings/providers/actions.ts +3 -2
  52. package/src/client/hooks/settings/providers/messages.ts +9 -7
  53. package/src/client/hooks/settings/providers/model-actions.ts +2 -1
  54. package/src/client/hooks/ui/editor-error-toast.ts +2 -1
  55. package/src/client/hooks/workspace/batch-archive.test.ts +2 -2
  56. package/src/client/hooks/workspace/batch-archive.ts +4 -2
  57. package/src/client/hooks/workspace/git-action-outcome.ts +4 -3
  58. package/src/client/hooks/workspace/navbar-session-actions.ts +2 -1
  59. package/src/client/hooks/workspace/session-actions.test.ts +2 -1
  60. package/src/client/hooks/workspace/session-actions.ts +2 -1
  61. package/src/client/hooks/workspace/terminal/connection.test.ts +63 -0
  62. package/src/client/hooks/workspace/terminal/connection.ts +47 -0
  63. package/src/client/hooks/workspace/terminal/index.ts +35 -4
  64. package/src/client/hooks/workspace/workspace-folder-actions.ts +2 -1
  65. package/src/server/lib/usage/report.server.ts +57 -0
  66. package/src/shared/lib/chat/timeline/fork-preview.test.ts +62 -0
  67. package/src/shared/lib/chat/timeline/fork-preview.ts +36 -0
  68. package/src/shared/lib/ui/toast-duration.test.ts +25 -1
  69. package/src/shared/lib/ui/toast-duration.ts +22 -4
  70. package/src/shared/lib/workspace/session-state/store.ts +4 -0
  71. package/dist/client/static/js/index-p2yw9ywf.css +0 -1
@@ -0,0 +1,130 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The pending chat's rows: the optimistic turn (`messages`) under the history a
8
+ * FORK inherits (`preview`), in source order.
9
+ *
10
+ * Split from `EmptyWorkspacePrompt` for the per-file ceiling; that file keeps
11
+ * the frame (target row, scroller, dock, composer) and this one owns what is
12
+ * drawn inside the scroller, so the two run-footer rules — one for rows this
13
+ * page mounted, none for the source's own rows — stay in one place.
14
+ */
15
+
16
+ import { Fragment } from 'preact';
17
+ import { useMemo } from 'preact/hooks';
18
+ import type { Attachment, ChatMessageData } from '@/shared/types';
19
+ import { ChatMessageItem } from '@/client/components/workspace/chat-timeline/MessageItem';
20
+ import { RunFooter } from '@/client/components/workspace/chat-timeline/RunFooter';
21
+ import { resolveRunFooters, streamingRowIndex } from '@/shared/lib/chat/timeline/run-footer';
22
+ import type { ForkPreview } from '@/client/hooks/chat/timeline/fork-preview';
23
+
24
+ export interface PendingTranscriptProps {
25
+ /** Rows this chat mounted itself (the optimistic turn). */
26
+ messages: ChatMessageData[];
27
+ /** The branch's inherited history; present only for a pending fork. */
28
+ preview?: ForkPreview | null;
29
+ isGenerating: boolean;
30
+ isMobile: boolean;
31
+ provider?: string;
32
+ providerNames?: Record<string, string>;
33
+ modelName?: string;
34
+ modelNames?: Record<string, string>;
35
+ sessionThinkingLevel?: string | null;
36
+ harness?: string;
37
+ onUndo?: (id: string, content?: string) => void;
38
+ onRetry?: (id: string) => void;
39
+ onNewChat?: (content: string, attachments?: Attachment[]) => void;
40
+ }
41
+
42
+ export function PendingTranscript({
43
+ messages,
44
+ preview = null,
45
+ isGenerating,
46
+ isMobile,
47
+ provider,
48
+ providerNames,
49
+ modelName,
50
+ modelNames,
51
+ sessionThinkingLevel,
52
+ harness,
53
+ onUndo,
54
+ onRetry,
55
+ onNewChat,
56
+ }: PendingTranscriptProps) {
57
+ const previewMessages = preview?.messages ?? [];
58
+ const { streamingIdx, footers } = useMemo(
59
+ () => ({
60
+ streamingIdx: streamingRowIndex(messages),
61
+ footers: resolveRunFooters(messages, isGenerating),
62
+ }),
63
+ [messages, isGenerating],
64
+ );
65
+
66
+ return (
67
+ <div className="chat-column">
68
+ {/* The branch's own history, read-only: these rows belong to the SOURCE
69
+ session, so their Undo / Fork / New-chat actions would act on this
70
+ pending chat and do nothing. No run footer either — the model stamp on
71
+ screen must be the source's, and the fork has not run. */}
72
+ {previewMessages.map((msg, idx) => {
73
+ const prev = previewMessages[idx - 1];
74
+ const isAiFragment = msg.role !== 'user' && prev && prev.role !== 'user';
75
+ return (
76
+ <ChatMessageItem
77
+ key={msg.id}
78
+ msg={msg}
79
+ userActions={false}
80
+ isPrevAssistant={Boolean(prev && prev.role !== 'user')}
81
+ isMobile={isMobile}
82
+ className={isAiFragment ? 'mt-1' : 'mt-8'}
83
+ />
84
+ );
85
+ })}
86
+ {preview?.loading && previewMessages.length === 0 && (
87
+ <div className="mt-8 text-xs text-ink/40">Loading the source transcript…</div>
88
+ )}
89
+ {preview?.error && (
90
+ <div className="mt-8 text-xs text-[var(--theme-error)]">
91
+ Could not read the source transcript: {preview.error}
92
+ </div>
93
+ )}
94
+ {messages.map((msg, idx) => {
95
+ const prev = messages[idx - 1];
96
+ const isLoading = isGenerating && idx === streamingIdx && msg.role === 'ai';
97
+ const isAiFragment = msg.role !== 'user' && prev && prev.role !== 'user';
98
+ const footer = footers[idx];
99
+ return (
100
+ <Fragment key={msg.id}>
101
+ <ChatMessageItem
102
+ msg={msg}
103
+ isStreaming={isLoading}
104
+ onUndo={onUndo}
105
+ onNewChat={onNewChat}
106
+ isMobile={isMobile}
107
+ className={isAiFragment ? 'mt-1' : 'mt-8'}
108
+ />
109
+ {footer && (
110
+ <RunFooter
111
+ msg={footer.msg}
112
+ provider={provider}
113
+ providerNames={providerNames}
114
+ modelName={modelName}
115
+ modelNames={modelNames}
116
+ thinkingLevel={sessionThinkingLevel ?? undefined}
117
+ {...(harness ? { harness } : {})}
118
+ durationMs={footer.durationMs}
119
+ answerText={footer.answerText}
120
+ retryTargetId={footer.runUserId}
121
+ onRetry={onRetry}
122
+ onNewChat={onNewChat}
123
+ />
124
+ )}
125
+ </Fragment>
126
+ );
127
+ })}
128
+ </div>
129
+ );
130
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The fork composer draws the history it is about to continue.
8
+ *
9
+ * A fork opens as an empty `new-…` chat, so the pending composer was the whole
10
+ * screen: the operator chose the branch's first turn with none of the source
11
+ * transcript in sight, and after moving "Fork from" the previous source's rows
12
+ * were all there was. Asserted from the mounted surface:
13
+ *
14
+ * - the preview rows render above the composer;
15
+ * - the "Fork from" picker stays reachable WHILE those rows are drawn (the
16
+ * docked branch used to drop the target row), and choosing another session
17
+ * reports it, which is what swaps the transcript.
18
+ */
19
+
20
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
21
+ import { Window } from 'happy-dom';
22
+ import { h, render } from 'preact';
23
+ import { act } from 'preact/test-utils';
24
+
25
+ import { EmptyWorkspacePrompt } from '@/client/components/workspace/chat-timeline/EmptyWorkspacePrompt';
26
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
27
+ import { silenceRealtime, restoreRealtime } from '@/test-support/silent-socket';
28
+ import type { ChatMessageData, WorkspaceFolderData } from '@/shared/types';
29
+
30
+ let container: HTMLElement;
31
+ /** The runner's own fetch: a stub left installed poisons every later suite. */
32
+ const originalFetch = Bun.fetch;
33
+
34
+ beforeAll(() => {
35
+ installDomGlobals(new Window({ url: 'http://localhost' }));
36
+ (globalThis as unknown as Record<string, unknown>).getComputedStyle = window.getComputedStyle.bind(window);
37
+ });
38
+ afterAll(() => restoreDomGlobals());
39
+
40
+ beforeEach(() => {
41
+ silenceRealtime();
42
+ // Only the composer's catalog reads are answered; nothing here asserts them.
43
+ globalThis.fetch = (async () => Response.json({})) as unknown as typeof fetch;
44
+ container = document.createElement('div');
45
+ document.body.appendChild(container);
46
+ });
47
+
48
+ afterEach(() => {
49
+ globalThis.fetch = originalFetch;
50
+ render(null, container);
51
+ container.remove();
52
+ restoreRealtime();
53
+ });
54
+
55
+ const SOURCE_ROWS: ChatMessageData[] = [
56
+ { id: 'u1', role: 'user', content: 'source question' },
57
+ { id: 'a1', role: 'ai', content: 'source answer' },
58
+ ];
59
+
60
+ const FOLDERS = [{
61
+ id: 1,
62
+ name: 'kabmo',
63
+ isExpanded: true,
64
+ sessions: [
65
+ { id: 'sess-a', title: 'Branch A', folder_id: 1, is_archived: 0 },
66
+ { id: 'sess-b', title: 'Branch B', folder_id: 1, is_archived: 0 },
67
+ ],
68
+ hasMore: false,
69
+ totalSessions: 2,
70
+ }] as unknown as WorkspaceFolderData[];
71
+
72
+ function mount(props: Record<string, unknown>) {
73
+ act(() => {
74
+ render(h(EmptyWorkspacePrompt, {
75
+ folders: FOLDERS,
76
+ selectedFolderId: 1,
77
+ setSelectedFolderId: () => {},
78
+ inputValue: '',
79
+ setInputValue: () => {},
80
+ onSend: () => {},
81
+ isGenerating: false,
82
+ accessMode: 'always-ask',
83
+ onAccessModeChange: () => {},
84
+ composerModelRef: { current: null },
85
+ deferredComposerPickRef: { current: null },
86
+ parentSessionId: 'sess-a',
87
+ onParentSessionChange: () => {},
88
+ branchLabel: 'Fork from',
89
+ branchAllowNone: false,
90
+ branchPreview: { messages: SOURCE_ROWS, loading: false, error: null },
91
+ ...props,
92
+ } as never), container);
93
+ });
94
+ return container;
95
+ }
96
+
97
+ async function settle(): Promise<void> {
98
+ // The mocked catalog reads resolve through microtasks; drain them instead of
99
+ // waiting on a wall clock.
100
+ await act(async () => {
101
+ for (let tick = 0; tick < 8; tick += 1) await Promise.resolve();
102
+ });
103
+ }
104
+
105
+ describe('fork preview in the pending composer', () => {
106
+ test('the source transcript renders above an otherwise empty chat', async () => {
107
+ const el = mount({});
108
+ await settle();
109
+ expect(el.textContent).toContain('source question');
110
+ // The assistant row is rendered through the answer renderer, which
111
+ // capitalizes the first letter; what matters is the row is there.
112
+ expect(el.textContent).toMatch(/source answer/i);
113
+ });
114
+
115
+ test('preview rows belong to the source: no chat-owning actions on them', async () => {
116
+ const el = mount({});
117
+ await settle();
118
+ expect(el.querySelector('[aria-label="Fork this session from this message"]')).toBeNull();
119
+ expect(el.querySelector('[aria-label="Undo this message"]')).toBeNull();
120
+ });
121
+
122
+ test('"Fork from" stays reachable while the preview is docked, and reports a new source', async () => {
123
+ const picked: string[] = [];
124
+ const el = mount({ onParentSessionChange: (id: string | null) => picked.push(String(id)) });
125
+ await settle();
126
+
127
+ const trigger = el.querySelector('[data-testid="parent-session-picker"]');
128
+ expect(trigger, 'the fork picker disappeared once the preview docked').not.toBeNull();
129
+ act(() => {
130
+ (trigger as HTMLElement).dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
131
+ });
132
+ await settle();
133
+
134
+ const other = el.querySelector('[data-testid="parent-candidate"][data-session-id="sess-b"]');
135
+ expect(other, 'the other source is not offered').not.toBeNull();
136
+ act(() => {
137
+ (other as HTMLElement).dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
138
+ });
139
+ expect(picked).toEqual(['sess-b']);
140
+ });
141
+ });
@@ -14,6 +14,7 @@ import { useSessionTitle } from '@/client/hooks/chat/timeline/session-title';
14
14
  import { useSubagentView } from '@/client/hooks/chat/timeline/subagent-view';
15
15
  import { useUndoConfirmation } from '@/client/hooks/chat/timeline/undo-confirmation';
16
16
  import { usePendingBranch } from '@/client/hooks/chat/timeline/pending-branch';
17
+ import { useForkPreview } from '@/client/hooks/chat/timeline/fork-preview';
17
18
  import { useForkSession } from '@/client/hooks/chat/timeline/use-fork-session';
18
19
  import { useStopWithQueuedPrompts } from '@/client/hooks/chat/timeline/stop-with-queue';
19
20
  import { useModelNames } from '@/client/hooks/models/use-model-names';
@@ -152,6 +153,9 @@ export function ChatTimeline({ className = '', appSettings = {}, onSessionTitle,
152
153
  const sessionDataModel = typeof sessionData?.model === 'object' ? sessionData.model : null;
153
154
  const branch = usePendingBranch({ sessionId, folders, selectedFolderId, setSelectedFolderId, urlParentId: searchParams.get('parentSessionId'), urlForkFrom: searchParams.get('forkFrom'), urlForkAt: searchParams.get('forkAt'), setSearchParams, harnessPicker: activeHarness.picker, pendingHarnessRef });
154
155
  const fork = useForkSession(sessionId, folders, selectedFolderId);
156
+ // A fork's source transcript, drawn above the pending composer and reloaded
157
+ // when "Fork from" moves to another session.
158
+ const forkPreview = useForkPreview(branch.forkSourceSessionId, branch.forkAnchorEntryId);
155
159
 
156
160
  // The chat-level "a run is in flight" flag is computed in `useChatTimeline`
157
161
  // (it owns the queue-vs-send decision that depends on it) and consumed here
@@ -207,7 +211,8 @@ export function ChatTimeline({ className = '', appSettings = {}, onSessionTitle,
207
211
  spawnTarget={spawnTarget}
208
212
  onSpawnTargetChange={setSpawnTarget}
209
213
  {...branch.viewProps}
210
- onWorktreeReport={(message) => pushToast(message, 'success', { duration: 6000 })}
214
+ {...(branch.forkSourceSessionId ? { branchPreview: forkPreview } : {})}
215
+ onWorktreeReport={(message, tone) => pushToast(message, tone ?? 'success', { duration: 6000 })}
211
216
  {...branch.composerProps}
212
217
  />
213
218
  );
@@ -22,6 +22,7 @@ import {
22
22
  } from '@/client/components/workspace/chat-timeline/chat-input/WaitingDependencyPicker';
23
23
  import type { SpawnTarget } from '@/client/hooks/chat/timeline/spawn-target';
24
24
  import type { WorkspaceFolderData } from '@/shared/types';
25
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
25
26
 
26
27
  export interface DraftTargetRowProps {
27
28
  folders: WorkspaceFolderData[];
@@ -30,7 +31,7 @@ export interface DraftTargetRowProps {
30
31
  spawnTarget?: SpawnTarget | null;
31
32
  onSpawnTargetChange?: (next: SpawnTarget | null) => void;
32
33
  /** Reports a worktree the composer created or failed to create. */
33
- onWorktreeReport?: (message: string) => void;
34
+ onWorktreeReport?: (message: string, tone?: ToastTone) => void;
34
35
  /** The session this chat runs under, or null for a top-level chat. */
35
36
  parentSessionId?: string | null;
36
37
  onParentSessionChange?: (sessionId: string | null) => void;
@@ -32,6 +32,7 @@ import type { SpawnTarget } from '@/client/hooks/chat/timeline/spawn-target';
32
32
  import type { WorktreeInfo } from '@/shared/lib/workspace/worktree/types';
33
33
  import { lastPathSegment } from '@/shared/lib/fs/paths';
34
34
  import type { WorkspaceFolderData } from '@/shared/types';
35
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
35
36
 
36
37
  export interface WorktreePickerProps {
37
38
  folders: WorkspaceFolderData[];
@@ -39,7 +40,7 @@ export interface WorktreePickerProps {
39
40
  target: SpawnTarget | null;
40
41
  setTarget: (next: SpawnTarget | null) => void;
41
42
  /** Reports a completed create, or the refusal that stopped one. */
42
- onReport?: (message: string) => void;
43
+ onReport?: (message: string, tone?: ToastTone) => void;
43
44
  }
44
45
 
45
46
  /** The worktree row the pick names, or null for the project root. */
@@ -131,9 +132,9 @@ export function WorktreePicker({ folders, selectedFolderId, target, setTarget, o
131
132
  // is `wt/groovy-yak` (measured in the browser, and for the whole time the
132
133
  // menu stays closed, which is when the label matters).
133
134
  await refresh();
134
- onReport?.(`Worktree ${created.branch || lastPathSegment(created.path)} created`);
135
+ onReport?.(`Worktree ${created.branch || lastPathSegment(created.path)} created`, 'success');
135
136
  } catch (failure) {
136
- onReport?.(failure instanceof Error ? failure.message : String(failure));
137
+ onReport?.(failure instanceof Error ? failure.message : String(failure), 'error');
137
138
  } finally {
138
139
  setCreating(false);
139
140
  }
@@ -277,7 +278,7 @@ export function WorktreePicker({ folders, selectedFolderId, target, setTarget, o
277
278
  // this control holds has never seen, so the trigger would fall back to
278
279
  // the folder name until the menu was opened again.
279
280
  void refresh();
280
- onReport?.(`Worktree ${created.branch} created`);
281
+ onReport?.(`Worktree ${created.branch} created`, 'success');
281
282
  }}
282
283
  />
283
284
  </div>
@@ -88,8 +88,8 @@ export function GitPanel({ className = '', enabled = true, rootPath, refreshKey
88
88
  fetcher: actionFetcher,
89
89
  onPage: setViewingOutput,
90
90
  onReload: loadRepo,
91
- onSuccess: (message) => pushToast(message, 'success'),
92
- onError: (message) => pushToast(message),
91
+ onSuccess: (message, tone) => pushToast(message, tone),
92
+ onError: (message) => pushToast(message, 'error'),
93
93
  });
94
94
 
95
95
  useOnClickOutside(optionsRef, () => setShowOptions(false));
@@ -156,12 +156,15 @@ export const RealtimeTerminalView = forwardRef<RealtimeTerminalHandle, RealtimeT
156
156
  };
157
157
  }, []);
158
158
 
159
- // No background and no padding: the terminal is not a surface of its own,
160
- // and the panel's paper shows through the strip the fit addon leaves for
161
- // its in-canvas scrollbar. `p-1.5` also made the grid narrower than the
162
- // panel, which read as a terminal that was not full width.
159
+ // The gutter lives on this WRAPPER, never on the measured container:
160
+ // `safeFit` gates on `container.clientWidth/clientHeight`, and `clientWidth`
161
+ // includes padding — padding on the container itself would size the canvas
162
+ // wider than the box it is drawn in. Here the grid is measured against the
163
+ // content box, so it is narrower by exactly the padding, which is the point.
164
+ // No background: the terminal is not a surface of its own, and the panel's
165
+ // paper shows through the strip the fit addon leaves for its scrollbar.
163
166
  return (
164
- <div className="relative flex-1 w-full h-full overflow-hidden">
167
+ <div className="relative flex-1 w-full h-full overflow-hidden p-2">
165
168
  <div
166
169
  ref={containerRef}
167
170
  data-terminal-root=""
@@ -72,6 +72,9 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
72
72
  restart,
73
73
  reattach,
74
74
  } = useTerminal({
75
+ // "Open" is this panel being selected with its column shown; the view is
76
+ // mounted even when hidden, so mounting alone must never start a shell.
77
+ visible: active && enabled,
75
78
  root: enabled ? rootPath : undefined,
76
79
  repo: activeRepo,
77
80
  theme: isDark ? 'dark' : 'light',
@@ -28,6 +28,7 @@ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'p
28
28
  import { createContext } from 'preact/compat';
29
29
  import type { ReactNode } from 'preact/compat';
30
30
  import { useRealtimeTopic } from '@/client/hooks/ui/realtime';
31
+ import { useSidebarFullReload } from '@/client/hooks/chat/omp/sidebar-reload';
31
32
  import { useInputRequiredAlert } from '@/client/hooks/ui/input-required-alert';
32
33
  import { useRunOutcomeAlert } from '@/client/hooks/ui/run-outcome-alert';
33
34
 
@@ -186,6 +187,10 @@ export function SidebarDataProvider({ children, initialFolders = [] }: { childre
186
187
  realtimeClient.refresh(TOPIC_SIDEBAR_ACTIVITY);
187
188
  }, []);
188
189
 
190
+ // The list's own beat, so a row moved by another Kabmo instance, a CLI run or
191
+ // omp writing its session file late converges without a page reload.
192
+ useSidebarFullReload(refresh);
193
+
189
194
  // The spinner follows a user's click only: it is raised here and lowered when
190
195
  // the next structure snapshot arrives (the status snapshot may land first, and
191
196
  // the list is what the user is looking at).
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The full-reload beat: it fires on the interval, and stops when the mount
8
+ * goes away. A live timer after unmount is what keeps a list re-reading from a
9
+ * component nobody is looking at.
10
+ */
11
+
12
+ import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'bun:test';
13
+ import { Window } from 'happy-dom';
14
+ import { h, render } from 'preact';
15
+ import { act } from 'preact/test-utils';
16
+
17
+ import { SIDEBAR_FULL_RELOAD_MS, useSidebarFullReload } from '@/client/hooks/chat/omp/sidebar-reload';
18
+
19
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'Node', 'Element', 'HTMLElement', 'Event'] as const;
20
+ const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
21
+ let container: HTMLElement;
22
+
23
+ beforeAll(() => {
24
+ const win = new Window({ url: 'http://localhost' });
25
+ const target = globalThis as unknown as Record<string, unknown>;
26
+ for (const key of DOM_GLOBALS) {
27
+ nativeGlobals[key] = target[key];
28
+ target[key] = (win as unknown as Record<string, unknown>)[key];
29
+ }
30
+ container = document.createElement('div');
31
+ document.body.appendChild(container);
32
+ });
33
+
34
+ afterAll(() => {
35
+ const target = globalThis as unknown as Record<string, unknown>;
36
+ for (const key of DOM_GLOBALS) {
37
+ if (nativeGlobals[key] === undefined) delete target[key];
38
+ else target[key] = nativeGlobals[key];
39
+ }
40
+ container.remove();
41
+ });
42
+
43
+ afterEach(() => {
44
+ vi.useRealTimers();
45
+ });
46
+
47
+ function mount(refresh: () => void): void {
48
+ function Probe() {
49
+ useSidebarFullReload(refresh);
50
+ return null;
51
+ }
52
+ act(() => {
53
+ render(h(Probe, null), container);
54
+ });
55
+ }
56
+
57
+ describe('useSidebarFullReload', () => {
58
+ test('refreshes once per interval, not before it', () => {
59
+ vi.useFakeTimers();
60
+ const refresh = vi.fn();
61
+ mount(refresh);
62
+
63
+ vi.advanceTimersByTime(SIDEBAR_FULL_RELOAD_MS - 1);
64
+ expect(refresh).not.toHaveBeenCalled();
65
+
66
+ vi.advanceTimersByTime(1);
67
+ expect(refresh).toHaveBeenCalledTimes(1);
68
+
69
+ vi.advanceTimersByTime(SIDEBAR_FULL_RELOAD_MS * 2);
70
+ expect(refresh).toHaveBeenCalledTimes(3);
71
+ });
72
+
73
+ test('stops the beat when the mount goes away', () => {
74
+ vi.useFakeTimers();
75
+ const refresh = vi.fn();
76
+ mount(refresh);
77
+
78
+ act(() => {
79
+ render(null, container);
80
+ });
81
+ vi.advanceTimersByTime(SIDEBAR_FULL_RELOAD_MS * 3);
82
+
83
+ expect(refresh).not.toHaveBeenCalled();
84
+ });
85
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The sidebar's full-reload beat: one request for every topic per interval.
8
+ *
9
+ * omp's own writes cover most of the list, but something outside this tab —
10
+ * another Kabmo instance, a CLI-driven run, omp writing a session file late —
11
+ * can move a row with no push reaching this client. The watcher narrows that
12
+ * window; it does not close it. This beat re-reads structure, status and
13
+ * activity so the list converges on its own instead of waiting for a reload.
14
+ *
15
+ * The transport coalesces a request that arrives while a snapshot is in
16
+ * flight, so a slow scan cannot queue snapshots behind each other.
17
+ */
18
+
19
+ import { useEffect } from 'preact/hooks';
20
+
21
+ /** How often the sidebar re-reads the whole list, in milliseconds. */
22
+ export const SIDEBAR_FULL_RELOAD_MS = 15_000;
23
+
24
+ /** Re-read every sidebar topic on a fixed beat while the mount is alive. */
25
+ export function useSidebarFullReload(refresh: () => void): void {
26
+ useEffect(() => {
27
+ const timer = setInterval(refresh, SIDEBAR_FULL_RELOAD_MS);
28
+ return () => clearInterval(timer);
29
+ }, [refresh]);
30
+ }