@kabmo-labs/kabmo 0.10.1 → 0.11.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 (52) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +306 -306
  3. package/dist/client/static/js/index-bq6qeayr.css +1 -0
  4. package/dist/client/static/js/{index-135sdc46.js → index-nqvfpgm2.js} +649 -648
  5. package/package.json +1 -1
  6. package/src/client/components/common/code-surface/theme.ts +11 -5
  7. package/src/client/components/workspace/chat-timeline/chat-input/access-levels.ts +11 -2
  8. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/ApprovalBody.tsx +65 -0
  9. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/Header.tsx +21 -2
  10. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/SelectBody.tsx +35 -19
  11. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/approval-gate.test.tsx +145 -0
  12. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/index.tsx +32 -104
  13. package/src/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/shortcuts.tsx +166 -0
  14. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +30 -0
  15. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +33 -27
  16. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +51 -0
  17. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +6 -0
  18. package/src/client/components/workspace/diff-panel/folding.test.ts +252 -0
  19. package/src/client/components/workspace/diff-panel/folding.ts +134 -0
  20. package/src/client/components/workspace/diff-panel/merge.ts +5 -0
  21. package/src/client/components/workspace/git-panel/InitRepository.tsx +49 -0
  22. package/src/client/components/workspace/git-panel/commit-modal.test.ts +193 -0
  23. package/src/client/components/workspace/git-panel/index.test.ts +3 -125
  24. package/src/client/components/workspace/git-panel/index.tsx +7 -1
  25. package/src/client/components/workspace/git-panel/init-state.test.ts +145 -0
  26. package/src/client/data/samples/virtual-devices-session.ts +8 -2
  27. package/src/client/data/settings/omp-schema.json +25 -3
  28. package/src/client/hooks/chat/timeline/ask-frames.test.ts +33 -0
  29. package/src/client/hooks/chat/timeline/ask-frames.ts +9 -1
  30. package/src/server/lib/fs/git-actions-worktree.ts +25 -2
  31. package/src/server/lib/fs/git-actions.ts +3 -3
  32. package/src/server/lib/fs/git-status-read.test.ts +20 -0
  33. package/src/server/lib/fs/git-status-read.ts +43 -2
  34. package/src/server/lib/omp/session/messages.test.ts +21 -0
  35. package/src/server/routes/fs/git-action.test.ts +4 -0
  36. package/src/server/routes/fs/git-init-action.test.ts +125 -0
  37. package/src/shared/lib/chat/notice-row.test.ts +25 -0
  38. package/src/shared/lib/chat/notice-row.ts +22 -1
  39. package/src/shared/lib/chat/omp/approval-gate.test.ts +99 -0
  40. package/src/shared/lib/chat/omp/approval-gate.ts +129 -0
  41. package/src/shared/lib/omp/config/schema.test.ts +12 -0
  42. package/src/shared/lib/omp/session/job-progress.test.ts +76 -0
  43. package/src/shared/lib/omp/session/job-progress.ts +84 -0
  44. package/src/shared/lib/omp/session/mapper.ts +3 -6
  45. package/src/shared/lib/omp/session/messages-map.test.ts +15 -6
  46. package/src/shared/lib/omp/session/messages-map.ts +19 -1
  47. package/src/shared/lib/omp/session/proc.test.ts +23 -0
  48. package/src/shared/lib/omp/session/proc.ts +17 -0
  49. package/src/shared/lib/omp/session/wait.test.ts +22 -0
  50. package/src/shared/lib/omp/session/wait.ts +14 -0
  51. package/src/test-support/file-explorer.test-util.ts +1 -1
  52. package/dist/client/static/js/index-snd9wk6w.css +0 -1
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Folding and brace detection for the diff bodies.
8
+ *
9
+ * A diff is a READER: the change is what matters and the surrounding block is
10
+ * what gets in the way of comparing it. So the three mechanisms the editor
11
+ * ships are registered here too —
12
+ *
13
+ * - `bracketMatching()` + `bracketGuide`: the pair highlight and the vertical
14
+ * rule from a brace to its match. This is the open/close DETECTION. With no
15
+ * parser installed the pairing is TEXTUAL, the same trade the editor makes
16
+ * (`code-surface/bracket-guide.ts`), so a brace inside a string can pair with
17
+ * one in another string.
18
+ * - Folding, answered by `foldService` because there is no syntax tree. The
19
+ * diff's own rule is a BRACE rule followed by the editor's indentation rule:
20
+ * a line that opens `{` / `[` / `(` and whose match closes on a LATER line
21
+ * folds down to the line before that closer. The brace rule is first because
22
+ * it is the exact boundary a reader comparing two sides expects — the closing
23
+ * brace stays visible and nothing after it is hidden — while indentation is
24
+ * what still folds a block the brackets cannot describe (YAML, Python, a
25
+ * wrapped expression).
26
+ * - `foldGutter()`: the marker AND the fold state field. Not `codeFolding()` —
27
+ * a `foldEffect` dispatched into a state that has no `foldState` field is
28
+ * discarded with no error (measured in `fold-stack.test.ts`).
29
+ *
30
+ * The chords are `@codemirror/language`'s own `foldKeymap`, so ⌥⌘[ / ⌥⌘] mean
31
+ * the same thing in a diff as in the editor.
32
+ */
33
+
34
+ import type { EditorState, Extension, Line } from '@codemirror/state';
35
+ import { bracketMatching, foldGutter, foldKeymap, foldService } from '@codemirror/language';
36
+ import { keymap } from '@codemirror/view';
37
+
38
+ import { bracketGuide } from '@/client/components/common/code-surface/bracket-guide';
39
+ import { indentFoldService, MAX_FOLD_LINES } from '@/client/components/common/code-surface/fold';
40
+
41
+ /** The brackets a line may open, and what closes each. */
42
+ const CLOSERS = { '{': '}', '[': ']', '(': ')' } as const;
43
+
44
+ type Opener = keyof typeof CLOSERS;
45
+
46
+ function isOpener(char: string | undefined): char is Opener {
47
+ return char === '{' || char === '[' || char === '(';
48
+ }
49
+
50
+ /**
51
+ * The line holding `column`'s matching closer, or null.
52
+ *
53
+ * A depth counter for the OPENING character's own type only: mixing types in
54
+ * one counter would let an unbalanced `(` swallow a `}`. Quoted strings and
55
+ * comments are not skipped — the scan is textual, like `bracketMatching()`'s —
56
+ * which is the stated trade rather than an oversight.
57
+ *
58
+ * The scan is capped at `MAX_FOLD_LINES` and REFUSES past it instead of
59
+ * returning a range that ends somewhere the reader never chose; the cap is the
60
+ * same cost bound `indentFoldRange` documents (a generated one-block file would
61
+ * otherwise be walked on every gutter line the reader scrolls past).
62
+ */
63
+ function closerLineOf(state: EditorState, openerLine: Line, column: number, opener: Opener): Line | null {
64
+ const closer = CLOSERS[opener];
65
+ const lastLineNumber = Math.min(state.doc.lines, openerLine.number + MAX_FOLD_LINES);
66
+ let depth = 0;
67
+
68
+ for (let number = openerLine.number; number <= lastLineNumber; number++) {
69
+ const text = state.doc.line(number).text;
70
+ for (let index = number === openerLine.number ? column : 0; index < text.length; index++) {
71
+ const char = text[index];
72
+ if (char === opener) depth += 1;
73
+ else if (char === closer) {
74
+ depth -= 1;
75
+ if (depth === 0) return state.doc.line(number);
76
+ }
77
+ }
78
+ }
79
+ return null;
80
+ }
81
+
82
+ /**
83
+ * The foldable range for the BRACE opened on the line at `lineStart`, or null.
84
+ *
85
+ * Shaped exactly like CM6's `foldService` callback so it can be registered as
86
+ * one; exported separately because the rule is what the tests pin.
87
+ *
88
+ * The first opener that spans lines wins, which is the OUTERMOST one — the
89
+ * block a reader is looking at. A closer on the very next line is skipped: the
90
+ * range would hide nothing, and the next opener (or the indentation rule) is
91
+ * the honest answer.
92
+ */
93
+ export function braceFoldRange(
94
+ state: EditorState,
95
+ lineStart: number,
96
+ lineEnd: number,
97
+ ): { from: number; to: number } | null {
98
+ const line = state.doc.lineAt(lineStart);
99
+ if (!line.text.trim()) return null;
100
+
101
+ for (let column = 0; column < line.text.length; column++) {
102
+ const char = line.text[column];
103
+ if (!isOpener(char)) continue;
104
+ const closerLine = closerLineOf(state, line, column, char);
105
+ // Nothing between the opener's line and the closer's: not a fold.
106
+ if (!closerLine || closerLine.number <= line.number + 1) continue;
107
+ // Ends at the last line INSIDE the pair, so the closing brace stays on
108
+ // screen — the boundary a diff reader is comparing against.
109
+ return { from: lineEnd, to: state.doc.line(closerLine.number - 1).to };
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /** The brace rule as a fold service. */
115
+ export const braceFoldService = foldService.of((state, lineStart, lineEnd) =>
116
+ braceFoldRange(state, lineStart, lineEnd),
117
+ );
118
+
119
+ /**
120
+ * Everything both diff shapes register.
121
+ *
122
+ * `braceFoldService` is listed BEFORE `indentFoldService` on purpose: the fold
123
+ * facet hands the question to each provider in order and the FIRST answer wins
124
+ * (`foldable()` in `@codemirror/language`), so the exact brace boundary is
125
+ * preferred and indentation is the fallback.
126
+ */
127
+ export const diffFoldingExtensions: Extension[] = [
128
+ bracketMatching(),
129
+ bracketGuide,
130
+ braceFoldService,
131
+ indentFoldService,
132
+ foldGutter(),
133
+ keymap.of(foldKeymap),
134
+ ];
@@ -33,6 +33,7 @@ import { Chunk, MergeView, diff, unifiedMergeView } from '@codemirror/merge';
33
33
 
34
34
  import { shikiHighlight, type ShikiThemeNames } from '@/client/components/common/code-surface/shiki';
35
35
  import { surfaceTheme } from '@/client/components/common/code-surface/theme';
36
+ import { diffFoldingExtensions } from '@/client/components/workspace/diff-panel/folding';
36
37
 
37
38
  /** What the toolbar shows; `diff` collapses the unchanged stretches. */
38
39
  export type CollapseMode = 'diff' | 'full';
@@ -140,6 +141,10 @@ function baseExtensions(options: DiffViewOptions, wrap: Compartment): Extension[
140
141
  return [
141
142
  ...READ_ONLY,
142
143
  lineNumbers(),
144
+ // Folding (a brace rule then the editor's indentation rule), the fold
145
+ // gutter that supplies the fold STATE field, and bracket pairing + guide.
146
+ // A read-only viewer still folds — that is the whole point of it here.
147
+ ...diffFoldingExtensions,
143
148
  shikiHighlight(options.language, options.themes),
144
149
  surfaceTheme(),
145
150
  diffTheme(),
@@ -0,0 +1,49 @@
1
+ import { GitBranch } from 'lucide-preact';
2
+
3
+ interface GitInitRepositoryProps {
4
+ /** The repo-relative path the panel is scoped to (`.` for the workspace root). */
5
+ repo: string;
6
+ isBusy: boolean;
7
+ onInit: () => void;
8
+ }
9
+
10
+ /**
11
+ * The Source Control panel's state for a folder that is not a repository.
12
+ *
13
+ * The panel used to render its full chrome here — branch toolbar, commit box,
14
+ * "No changes found." — over a directory where every one of those controls
15
+ * answers `fatal: not a git repository`, so the panel looked functional and did
16
+ * nothing. `readGitStatus` now reports `isRepo: false` for that case, and this
17
+ * is what the panel draws instead: the one action that turns the folder into
18
+ * something the rest of the panel can act on.
19
+ *
20
+ * The button is labelled by `aria-label`, not by its visible text: the wording
21
+ * ("Initialize repository") and the title (`git init` in this folder) name the
22
+ * same command, and an accessible name that follows the label would change with
23
+ * copy edits.
24
+ */
25
+ export function GitInitRepository({ repo, isBusy, onInit }: GitInitRepositoryProps) {
26
+ const where = repo === '.' ? 'this folder' : repo;
27
+ return (
28
+ <div className="flex-1 flex flex-col items-center justify-center gap-3 px-6 text-center">
29
+ <GitBranch size={26} className="text-ink/25" aria-hidden />
30
+ <div className="font-mono space-y-1">
31
+ <p className="text-xs text-ink/70">Not a Git repository</p>
32
+ <p className="text-[11px] leading-4 text-ink/40">
33
+ Initialize one in {where} to track changes, commit and manage branches.
34
+ </p>
35
+ </div>
36
+ <button
37
+ type="button"
38
+ onClick={onInit}
39
+ disabled={isBusy}
40
+ aria-label="Initialize Git repository"
41
+ title={`git init in ${where}`}
42
+ className="flex items-center justify-center gap-1.5 px-3 py-1.5 rounded bg-ink text-canvas hover:bg-ink/90 transition-colors cursor-pointer text-xs font-medium disabled:opacity-40 disabled:cursor-not-allowed"
43
+ >
44
+ <GitBranch size={12} aria-hidden />
45
+ Initialize repository
46
+ </button>
47
+ </div>
48
+ );
49
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The commit modal opens because the user ASKED for it — never because the
8
+ * panel re-rendered.
9
+ *
10
+ * `actionFetcher.data` is sticky (it holds the last response for the life of
11
+ * the mount) while the effect that turns a history payload into the modal also
12
+ * depends on `loadRepo`, whose identity changes whenever `rootPath` does. So
13
+ * switching to a session in another workspace re-ran that effect against the
14
+ * PREVIOUS history payload and reopened a modal the user had already dismissed
15
+ * (reported as "clicking a session item opens the commit modal").
16
+ *
17
+ * Split from `index.test.ts` when both files reached the repo's line ceiling;
18
+ * each owns its own harness.
19
+ */
20
+
21
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
22
+ import { Window } from 'happy-dom';
23
+ import { h, render } from 'preact';
24
+ import { act } from 'preact/test-utils';
25
+ import { GitPanel } from '@/client/components/workspace/git-panel';
26
+ import { SessionStateProvider } from '@/client/components/common/session-state-provider/index';
27
+ import { resetRealtimeClient } from '@/shared/lib/realtime/client';
28
+ import { gitTopic, reposTopic } from '@/shared/lib/realtime/protocol';
29
+ import { startRealtimeTestServer, type RealtimeTestServer } from '@/test-support/realtime-server';
30
+ import { installDomGlobals, pristineWebSocket, restoreDomGlobals } from '@/test-support/pristine-globals';
31
+ import type { TopicResolver } from '@/server/lib/realtime/hub.server';
32
+
33
+ const ROOT = '/ws';
34
+ const SESSION = 'new-git-panel-modal';
35
+ const TOPIC = gitTopic(`${ROOT}\u0000.`);
36
+
37
+ /** The runner's own fetch, reached through `Bun` so a leaked stub cannot be mistaken for it. */
38
+ const nativeFetch = Bun.fetch;
39
+
40
+ let container: HTMLElement;
41
+ let server: RealtimeTestServer;
42
+
43
+ /** A payload the panel renders as `count` changed files — a repository. */
44
+ function statusOf(count: number): unknown {
45
+ return {
46
+ changes: Array.from({ length: count }, (_, i) => ({
47
+ status: '??',
48
+ file: `file-${i}.txt`,
49
+ staged: false,
50
+ additions: 1,
51
+ deletions: 0,
52
+ })),
53
+ branch: 'main',
54
+ branches: ['main'],
55
+ remoteBranches: [],
56
+ isRepo: true,
57
+ };
58
+ }
59
+
60
+ beforeAll(() => {
61
+ installDomGlobals(new Window({ url: 'http://localhost' }));
62
+ });
63
+
64
+ afterEach(() => {
65
+ if (container) {
66
+ render(null, container);
67
+ container.remove();
68
+ }
69
+ resetRealtimeClient();
70
+ server?.stop();
71
+ });
72
+
73
+ afterAll(() => {
74
+ (globalThis as unknown as Record<string, unknown>).fetch = nativeFetch;
75
+ restoreDomGlobals();
76
+ });
77
+
78
+ /**
79
+ * happy-dom ships none of the three globals the modal's measurement layer
80
+ * needs (`useLayoutEffect`'s rAF, its own `ResizeObserver`, the paging
81
+ * `IntersectionObserver`). Stubbed rather than asserted on: the modal's
82
+ * geometry is not what this test is about.
83
+ */
84
+ const OBSERVER_STUBS = ['ResizeObserver', 'IntersectionObserver'] as const;
85
+ const stubs: Partial<Record<(typeof OBSERVER_STUBS)[number], unknown>> = {};
86
+
87
+ beforeAll(() => {
88
+ const target = globalThis as unknown as Record<string, unknown>;
89
+ for (const key of OBSERVER_STUBS) stubs[key] = target[key];
90
+ target.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
91
+ target.IntersectionObserver = class { observe() {} unobserve() {} disconnect() {} };
92
+ // No-op rather than a timer: the geometry pass is not what this asserts, and
93
+ // a real delay would make the case's duration depend on the machine.
94
+ target.requestAnimationFrame = () => 0;
95
+ target.cancelAnimationFrame = () => {};
96
+ });
97
+
98
+ afterAll(() => {
99
+ const target = globalThis as unknown as Record<string, unknown>;
100
+ for (const key of OBSERVER_STUBS) {
101
+ if (stubs[key] === undefined) delete target[key];
102
+ else target[key] = stubs[key];
103
+ }
104
+ delete target.requestAnimationFrame;
105
+ delete target.cancelAnimationFrame;
106
+ });
107
+
108
+ /** Mount with an HTTP POST that answers a history page. */
109
+ async function mountHistory(): Promise<{ rerender: (props: { rootPath: string; enabled: boolean }) => Promise<void> }> {
110
+ server = await startRealtimeTestServer(new Map<string, TopicResolver>([
111
+ [TOPIC, async () => statusOf(1)],
112
+ [reposTopic(ROOT), async () => ({ repos: ['.'], reposPending: false })],
113
+ ]));
114
+ const win = new Window({ url: `http://127.0.0.1:${server.port}` });
115
+ installDomGlobals(win);
116
+ const target = globalThis as unknown as Record<string, unknown>;
117
+ target.WebSocket = pristineWebSocket;
118
+ target.fetch = async (input: unknown, init?: RequestInit) => {
119
+ const url = String(input);
120
+ const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
121
+ if (url.includes('/state')) return json({ sessionId: SESSION, state: {} });
122
+ if (url.includes('reposOnly')) return json({ repos: ['.'], reposPending: false });
123
+ if (init?.method === 'POST') {
124
+ return json({ success: true, type: 'history', data: [{ hash: 'abc1234', message: 'first', author: 'a', time: 'now' }], hasMore: false, total: 1 });
125
+ }
126
+ return json(statusOf(0));
127
+ };
128
+ container = document.createElement('div');
129
+ document.body.appendChild(container);
130
+ const rerender = async (props: { rootPath: string; enabled: boolean }) => {
131
+ await act(async () => {
132
+ render(h(SessionStateProvider, { sessionId: SESSION, children: h(GitPanel, props) }), container);
133
+ });
134
+ for (let i = 0; i < 20; i += 1) await act(async () => {});
135
+ };
136
+ await rerender({ rootPath: ROOT, enabled: true });
137
+ await server.waitForTopic(TOPIC, (value) => value !== null);
138
+ for (let i = 0; i < 20; i += 1) await act(async () => {});
139
+ return { rerender };
140
+ }
141
+
142
+ const settle = async (rounds = 20) => { for (let i = 0; i < rounds; i += 1) await act(async () => {}); };
143
+
144
+ describe('GitPanel commit modal', () => {
145
+ test('a dismissed modal stays dismissed when the workspace root moves', async () => {
146
+ const { rerender } = await mountHistory();
147
+
148
+ const historyButton = container.querySelector('button[title="Commit History"]') as HTMLButtonElement | null;
149
+ expect(historyButton).toBeTruthy();
150
+ await act(async () => { historyButton?.click(); });
151
+ await settle();
152
+ expect(container.querySelector('[role="dialog"]')).toBeTruthy();
153
+
154
+ const close = container.querySelector('button[title="Close modal"]') as HTMLButtonElement | null;
155
+ expect(close).toBeTruthy();
156
+ await act(async () => { close?.click(); });
157
+ await settle(5);
158
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
159
+
160
+ await rerender({ rootPath: '/ws-other', enabled: true });
161
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
162
+ });
163
+
164
+ /**
165
+ * The same guard covers the ACTIVITY-BAR case: `enabled` is what the layout
166
+ * flips when another right-panel view is selected, and `loadRepo` depends on
167
+ * it too — so a panel-button click re-ran the effect exactly as a workspace
168
+ * switch did. Reported as the modal appearing "when clicking a panel button".
169
+ */
170
+ test('a dismissed modal stays dismissed when the panel is toggled off and on', async () => {
171
+ const { rerender } = await mountHistory();
172
+
173
+ const historyButton = container.querySelector('button[title="Commit History"]') as HTMLButtonElement | null;
174
+ expect(historyButton).toBeTruthy();
175
+ await act(async () => { historyButton?.click(); });
176
+ await settle();
177
+ expect(container.querySelector('[role="dialog"]')).toBeTruthy();
178
+
179
+ const close = container.querySelector('button[title="Close modal"]') as HTMLButtonElement | null;
180
+ expect(close).toBeTruthy();
181
+ await act(async () => { close?.click(); });
182
+ await settle(5);
183
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
184
+
185
+ // Selecting another view in the activity bar: the layout sets `enabled` false.
186
+ await rerender({ rootPath: ROOT, enabled: false });
187
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
188
+
189
+ // And back to Source Control.
190
+ await rerender({ rootPath: ROOT, enabled: true });
191
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
192
+ });
193
+ });
@@ -54,6 +54,7 @@ function statusOf(count: number, syncCount?: { ahead: number; behind: number }):
54
54
  branch: 'main',
55
55
  branches: ['main'],
56
56
  remoteBranches: [],
57
+ isRepo: true,
57
58
  ...(syncCount ? { syncCount } : {}),
58
59
  };
59
60
  }
@@ -219,129 +220,6 @@ describe('GitPanel sync badge', () => {
219
220
  });
220
221
 
221
222
  /**
222
- * The commit modal opens because the user ASKED for it — never because the
223
- * panel re-rendered.
224
- *
225
- * `actionFetcher.data` is sticky (it holds the last response for the life of
226
- * the mount) while the effect that turns a history payload into the modal also
227
- * depends on `loadRepo`, whose identity changes whenever `rootPath` does. So
228
- * switching to a session in another workspace re-ran that effect against the
229
- * PREVIOUS history payload and reopened a modal the user had already dismissed
230
- * (reported as "clicking a session item opens the commit modal").
223
+ * The commit modal's own cases live in `commit-modal.test.ts`: the two files
224
+ * together exceeded the repo's line ceiling, and each mounts its own harness.
231
225
  */
232
- describe('GitPanel commit modal', () => {
233
- /**
234
- * happy-dom ships none of the three globals the modal's measurement layer
235
- * needs (`useLayoutEffect`'s rAF, its own `ResizeObserver`, the paging
236
- * `IntersectionObserver`). Stubbed rather than asserted on: the modal's
237
- * geometry is not what this test is about.
238
- */
239
- const OBSERVER_STUBS = ['ResizeObserver', 'IntersectionObserver'] as const;
240
- const stubs: Partial<Record<(typeof OBSERVER_STUBS)[number], unknown>> = {};
241
-
242
- beforeAll(() => {
243
- const target = globalThis as unknown as Record<string, unknown>;
244
- for (const key of OBSERVER_STUBS) stubs[key] = target[key];
245
- target.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
246
- target.IntersectionObserver = class { observe() {} unobserve() {} disconnect() {} };
247
- // No-op rather than a timer: the geometry pass is not what this asserts, and
248
- // a real delay would make the case's duration depend on the machine.
249
- target.requestAnimationFrame = () => 0;
250
- target.cancelAnimationFrame = () => {};
251
- });
252
-
253
- afterAll(() => {
254
- const target = globalThis as unknown as Record<string, unknown>;
255
- for (const key of OBSERVER_STUBS) {
256
- if (stubs[key] === undefined) delete target[key];
257
- else target[key] = stubs[key];
258
- }
259
- delete target.requestAnimationFrame;
260
- delete target.cancelAnimationFrame;
261
- });
262
-
263
- /** Mount with an HTTP POST that answers a history page. */
264
- async function mountHistory(): Promise<{ rerender: (props: { rootPath: string; enabled: boolean }) => Promise<void> }> {
265
- server = await startRealtimeTestServer(new Map<string, TopicResolver>([
266
- [TOPIC, async () => statusOf(1)],
267
- [reposTopic(ROOT), async () => ({ repos: ['.'], reposPending: false })],
268
- ]));
269
- const win = new Window({ url: `http://127.0.0.1:${server.port}` });
270
- installDomGlobals(win);
271
- const target = globalThis as unknown as Record<string, unknown>;
272
- target.WebSocket = pristineWebSocket;
273
- target.fetch = async (input: unknown, init?: RequestInit) => {
274
- const url = String(input);
275
- const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
276
- if (url.includes('/state')) return json({ sessionId: SESSION, state: {} });
277
- if (url.includes('reposOnly')) return json({ repos: ['.'], reposPending: false });
278
- if (init?.method === 'POST') {
279
- return json({ success: true, type: 'history', data: [{ hash: 'abc1234', message: 'first', author: 'a', time: 'now' }], hasMore: false, total: 1 });
280
- }
281
- return json(statusOf(0));
282
- };
283
- container = document.createElement('div');
284
- document.body.appendChild(container);
285
- const rerender = async (props: { rootPath: string; enabled: boolean }) => {
286
- await act(async () => {
287
- render(h(SessionStateProvider, { sessionId: SESSION, children: h(GitPanel, props) }), container);
288
- });
289
- for (let i = 0; i < 20; i += 1) await act(async () => {});
290
- };
291
- await rerender({ rootPath: ROOT, enabled: true });
292
- await server.waitForTopic(TOPIC, (value) => value !== null);
293
- for (let i = 0; i < 20; i += 1) await act(async () => {});
294
- return { rerender };
295
- }
296
-
297
- const settle = async (rounds = 20) => { for (let i = 0; i < rounds; i += 1) await act(async () => {}); };
298
-
299
- test('a dismissed modal stays dismissed when the workspace root moves', async () => {
300
- const { rerender } = await mountHistory();
301
-
302
- const historyButton = container.querySelector('button[title="Commit History"]') as HTMLButtonElement | null;
303
- expect(historyButton).toBeTruthy();
304
- await act(async () => { historyButton?.click(); });
305
- await settle();
306
- expect(container.querySelector('[role="dialog"]')).toBeTruthy();
307
-
308
- const close = container.querySelector('button[title="Close modal"]') as HTMLButtonElement | null;
309
- expect(close).toBeTruthy();
310
- await act(async () => { close?.click(); });
311
- await settle(5);
312
- expect(container.querySelector('[role="dialog"]')).toBeNull();
313
-
314
- await rerender({ rootPath: '/ws-other', enabled: true });
315
- expect(container.querySelector('[role="dialog"]')).toBeNull();
316
- });
317
-
318
- /**
319
- * The same guard covers the ACTIVITY-BAR case: `enabled` is what the layout
320
- * flips when another right-panel view is selected, and `loadRepo` depends on
321
- * it too — so a panel-button click re-ran the effect exactly as a workspace
322
- * switch did. Reported as the modal appearing "when clicking a panel button".
323
- */
324
- test('a dismissed modal stays dismissed when the panel is toggled off and on', async () => {
325
- const { rerender } = await mountHistory();
326
-
327
- const historyButton = container.querySelector('button[title="Commit History"]') as HTMLButtonElement | null;
328
- expect(historyButton).toBeTruthy();
329
- await act(async () => { historyButton?.click(); });
330
- await settle();
331
- expect(container.querySelector('[role="dialog"]')).toBeTruthy();
332
-
333
- const close = container.querySelector('button[title="Close modal"]') as HTMLButtonElement | null;
334
- expect(close).toBeTruthy();
335
- await act(async () => { close?.click(); });
336
- await settle(5);
337
- expect(container.querySelector('[role="dialog"]')).toBeNull();
338
-
339
- // Selecting another view in the activity bar: the layout sets `enabled` false.
340
- await rerender({ rootPath: ROOT, enabled: false });
341
- expect(container.querySelector('[role="dialog"]')).toBeNull();
342
-
343
- // And back to Source Control.
344
- await rerender({ rootPath: ROOT, enabled: true });
345
- expect(container.querySelector('[role="dialog"]')).toBeNull();
346
- });
347
- });
@@ -8,6 +8,7 @@ import { GitRepoHeader } from '@/client/components/workspace/git-panel/RepoHeade
8
8
  import { GitChangesList } from '@/client/components/workspace/git-panel/ChangesList';
9
9
  import { GitPanelModals } from '@/client/components/workspace/git-panel/PanelModals';
10
10
  import { GitStashSection } from '@/client/components/workspace/git-panel/StashSection';
11
+ import { GitInitRepository } from '@/client/components/workspace/git-panel/InitRepository';
11
12
  import { ToastStack } from '@/client/components/common/ToastStack';
12
13
  import { useToasts } from '@/client/hooks/ui/toasts';
13
14
  import { useSessionState } from '@/client/hooks/workspace/session-state';
@@ -264,7 +265,11 @@ export function GitPanel({ className = '', enabled = true, rootPath, refreshKey
264
265
  }}
265
266
  onRefreshRepos={refreshRepos}
266
267
  />
267
-
268
+ {/* A folder with no repository has no working tree to show, and the picker
269
+ above can still point at a nested one: everything below acts on a repo. */}
270
+ {data?.isRepo === false ? (
271
+ <GitInitRepository repo={activeRepo} isBusy={isBusy} onInit={() => executeAction('init')} />
272
+ ) : (<>
268
273
  {/* Branch & View Mode Toolbar */}
269
274
  <GitBranchToolbar
270
275
  branchRef={branchRef}
@@ -337,6 +342,7 @@ export function GitPanel({ className = '', enabled = true, rootPath, refreshKey
337
342
  isBusy={isBusy}
338
343
  onAction={(actionType, extra) => handleAction(actionType, undefined, extra)}
339
344
  />
345
+ </>)}
340
346
  </div>
341
347
  );
342
348
  }