@kabmo-labs/kabmo 0.10.1 → 0.11.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 (70) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +391 -391
  3. package/dist/client/static/js/{index-135sdc46.js → index-amss8pge.js} +660 -659
  4. package/dist/client/static/js/index-bq6qeayr.css +1 -0
  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/client/hooks/chat/timeline/index.ts +1 -0
  31. package/src/client/hooks/chat/timeline/send-execute.test.ts +14 -207
  32. package/src/client/hooks/chat/timeline/send-refusal.test.ts +72 -0
  33. package/src/client/hooks/chat/timeline/send-steer.test.ts +1 -0
  34. package/src/client/hooks/chat/timeline/send.test-util.ts +245 -0
  35. package/src/client/hooks/chat/timeline/send.test.ts +1 -0
  36. package/src/client/hooks/chat/timeline/send.ts +10 -0
  37. package/src/server/lib/fs/git-actions-worktree.ts +25 -2
  38. package/src/server/lib/fs/git-actions.ts +3 -3
  39. package/src/server/lib/fs/git-status-read.test.ts +20 -0
  40. package/src/server/lib/fs/git-status-read.ts +43 -2
  41. package/src/server/lib/omp/rpc/constants.ts +15 -1
  42. package/src/server/lib/omp/rpc/manager.ts +1 -1
  43. package/src/server/lib/omp/rpc/prewarm-pool.ts +166 -0
  44. package/src/server/lib/omp/rpc/session-registry.ts +80 -164
  45. package/src/server/lib/omp/session/messages.test.ts +21 -0
  46. package/src/server/lib/omp/session/resumable-model.recovery.test.ts +194 -0
  47. package/src/server/lib/omp/session/resumable-model.server.test.ts +90 -0
  48. package/src/server/lib/omp/session/resumable-model.server.ts +181 -0
  49. package/src/server/lib/omp/session/standby.server.ts +1 -1
  50. package/src/server/routes/agent/command.ts +7 -1
  51. package/src/server/routes/agent/prewarm.ts +1 -1
  52. package/src/server/routes/fs/git-action.test.ts +4 -0
  53. package/src/server/routes/fs/git-init-action.test.ts +125 -0
  54. package/src/shared/lib/chat/notice-row.test.ts +25 -0
  55. package/src/shared/lib/chat/notice-row.ts +22 -1
  56. package/src/shared/lib/chat/omp/approval-gate.test.ts +99 -0
  57. package/src/shared/lib/chat/omp/approval-gate.ts +129 -0
  58. package/src/shared/lib/omp/config/schema.test.ts +12 -0
  59. package/src/shared/lib/omp/session/job-progress.test.ts +76 -0
  60. package/src/shared/lib/omp/session/job-progress.ts +84 -0
  61. package/src/shared/lib/omp/session/mapper.ts +3 -6
  62. package/src/shared/lib/omp/session/messages-map.test.ts +15 -6
  63. package/src/shared/lib/omp/session/messages-map.ts +19 -1
  64. package/src/shared/lib/omp/session/proc.test.ts +23 -0
  65. package/src/shared/lib/omp/session/proc.ts +17 -0
  66. package/src/shared/lib/omp/session/wait.test.ts +22 -0
  67. package/src/shared/lib/omp/session/wait.ts +14 -0
  68. package/src/test-support/fake-omp-restore.ts +153 -0
  69. package/src/test-support/file-explorer.test-util.ts +1 -1
  70. package/dist/client/static/js/index-snd9wk6w.css +0 -1
@@ -37,6 +37,7 @@ import {
37
37
  } from '@/shared/lib/omp/session/proc';
38
38
  import { FallbackOutput } from '@/client/components/workspace/chat-timeline/tool-renderers/shared/FallbackOutput';
39
39
  import { ToolPanelHeader } from '@/client/components/workspace/chat-timeline/tool-renderers/shared/ToolPanelHeader';
40
+ import { jobProgressLine } from '@/shared/lib/omp/session/job-progress';
40
41
 
41
42
  /** Tone → class list. A toned chip is text-only; the ink palette has no room
42
43
  * for a filled pill in a dense row. */
@@ -92,35 +93,40 @@ function JobRow({ job }: { job: ProcJob }) {
92
93
  const tone = jobTone(job.status);
93
94
  const running = job.status === 'running';
94
95
  const duration = typeof job.durationMs === 'number' ? formatProcDuration(job.durationMs) : undefined;
96
+ // This row has no percent chip, so the line carries the estimate itself.
97
+ const progress = jobProgressLine(job, { includePercent: true });
95
98
  return (
96
- <div className="flex items-center gap-2 px-3 py-1.5 text-[11.5px]">
97
- {running ? (
98
- <Loader2 size={11} className="shrink-0 animate-spin text-ink/50" />
99
- ) : job.status === 'failed' ? (
100
- <CircleSlash size={11} className="shrink-0 text-error" />
101
- ) : job.status === 'cancelled' ? (
102
- <CircleSlash size={11} className="shrink-0 text-warning" />
103
- ) : (
104
- <CheckCircle2 size={11} className="shrink-0 text-success" />
105
- )}
106
- {job.id && <span className="shrink-0 font-mono text-[10px] font-semibold text-ink/80">{job.id}</span>}
107
- {job.type && (
108
- <span className="shrink-0 rounded bg-ink/5 px-1 py-0.2 font-mono text-[8.5px] uppercase tracking-wider text-ink/45">
109
- {job.type}
110
- </span>
111
- )}
112
- <span className="min-w-0 flex-1 truncate text-ink/85" title={job.label}>
113
- {job.label ?? job.resultText ?? job.errorText ?? ''}
114
- </span>
115
- {job.resolvedModel && (
116
- <span className="hidden max-w-[120px] truncate font-mono text-[9px] text-ink/40 sm:inline-block">
117
- {job.resolvedModel}
99
+ <div className="space-y-0.5 px-3 py-1.5">
100
+ <div className="flex items-center gap-2 text-[11.5px]">
101
+ {running ? (
102
+ <Loader2 size={11} className="shrink-0 animate-spin text-ink/50" />
103
+ ) : job.status === 'failed' ? (
104
+ <CircleSlash size={11} className="shrink-0 text-error" />
105
+ ) : job.status === 'cancelled' ? (
106
+ <CircleSlash size={11} className="shrink-0 text-warning" />
107
+ ) : (
108
+ <CheckCircle2 size={11} className="shrink-0 text-success" />
109
+ )}
110
+ {job.id && <span className="shrink-0 font-mono text-[10px] font-semibold text-ink/80">{job.id}</span>}
111
+ {job.type && (
112
+ <span className="shrink-0 rounded bg-ink/5 px-1 py-0.2 font-mono text-[8.5px] uppercase tracking-wider text-ink/45">
113
+ {job.type}
114
+ </span>
115
+ )}
116
+ <span className="min-w-0 flex-1 truncate text-ink/85" title={job.label}>
117
+ {job.label ?? job.resultText ?? job.errorText ?? ''}
118
118
  </span>
119
- )}
120
- {duration && <span className="shrink-0 font-mono text-[9px] text-ink/40">{duration}</span>}
121
- {job.status && (
122
- <span className={`shrink-0 font-mono text-[9px] font-semibold ${TONE_CLASSES[tone]}`}>{job.status}</span>
123
- )}
119
+ {job.resolvedModel && (
120
+ <span className="hidden max-w-[120px] truncate font-mono text-[9px] text-ink/40 sm:inline-block">
121
+ {job.resolvedModel}
122
+ </span>
123
+ )}
124
+ {duration && <span className="shrink-0 font-mono text-[9px] text-ink/40">{duration}</span>}
125
+ {job.status && (
126
+ <span className={`shrink-0 font-mono text-[9px] font-semibold ${TONE_CLASSES[tone]}`}>{job.status}</span>
127
+ )}
128
+ </div>
129
+ {progress && <div className="truncate font-mono text-[9px] text-ink/40">{progress}</div>}
124
130
  </div>
125
131
  );
126
132
  }
@@ -140,6 +140,57 @@ describe('Wait panel — a blocking call', () => {
140
140
  });
141
141
  });
142
142
 
143
+ describe('Wait panel — running-task telemetry', () => {
144
+ // omp 18.13.0 lifts a task's `requests`, `cost`, context fill and `stage`
145
+ // into the job snapshot, which is what makes omp's own row read
146
+ // `90 req · $18.40 · ctx 160K/1M · stage: implementing`. The card has to draw
147
+ // them, or the telemetry reaches the wire and goes nowhere.
148
+ const TELEMETRY: Partial<ToolCallData> & Pick<ToolCallData, 'type'> = {
149
+ type: 'wait',
150
+ name: 'wait',
151
+ status: 'running',
152
+ output: '',
153
+ details: {
154
+ op: 'wait',
155
+ jobs: [{
156
+ id: 'bg_3', type: 'task', status: 'running', label: 'refactor', durationMs: 18_446_000,
157
+ completionPercent: 55, requests: 90, cost: 18.4,
158
+ contextTokens: 163_840, contextWindow: 1_048_576, stage: 'implementing',
159
+ }],
160
+ },
161
+ };
162
+
163
+ test('draws the telemetry line under the row', async () => {
164
+ const el = await mount(TELEMETRY);
165
+ const text = el.textContent ?? '';
166
+ expect(text).toContain('90 req');
167
+ expect(text).toContain('$18.40');
168
+ expect(text).toContain('ctx 163.8K/1.0M');
169
+ expect(text).toContain('stage: implementing');
170
+ });
171
+
172
+ test('the percent stays on the row and out of the telemetry line', async () => {
173
+ // The row already shows `55%` as its own chip, so the line must not repeat
174
+ // it — twice would read as a second estimate.
175
+ const el = await mount(TELEMETRY);
176
+ const line = [...el.querySelectorAll('.font-mono')].map((node) => node.textContent ?? '').find((t) => t.includes('req'));
177
+ expect(line?.includes('~55%')).toBe(false);
178
+ });
179
+
180
+ test('a settled job draws no telemetry, so a stored snapshot never looks live', async () => {
181
+ const el = await mount({
182
+ ...TELEMETRY,
183
+ status: 'success',
184
+ durationMs: 18_446_000,
185
+ details: {
186
+ op: 'wait',
187
+ jobs: [{ ...TELEMETRY.details!.jobs[0], status: 'completed', exitCode: 0 }],
188
+ },
189
+ });
190
+ expect(el.textContent ?? '').not.toContain('req');
191
+ });
192
+ });
193
+
143
194
  describe('Wait panel — the 30-minute cap', () => {
144
195
  test('states the ceiling and the remaining budget while blocking', async () => {
145
196
  // omp caps one `wait` at 30 minutes and takes no argument to raise it, so
@@ -49,6 +49,7 @@ import {
49
49
  } from '@/shared/lib/omp/session/wait';
50
50
  import { FallbackOutput } from '@/client/components/workspace/chat-timeline/tool-renderers/shared/FallbackOutput';
51
51
  import { ToolPanelHeader } from '@/client/components/workspace/chat-timeline/tool-renderers/shared/ToolPanelHeader';
52
+ import { jobProgressLine } from '@/shared/lib/omp/session/job-progress';
52
53
 
53
54
  const TONE_CLASSES = {
54
55
  ok: 'text-success',
@@ -132,6 +133,8 @@ function JobRow({ job }: { job: WaitJob }) {
132
133
  const running = job.status === 'running';
133
134
  const label = job.label ?? job.resultText ?? job.errorText ?? job.id ?? '';
134
135
  const percent = running ? job.completionPercent : undefined;
136
+ // The percent is already a chip in this row, so the progress line leaves it out.
137
+ const progress = jobProgressLine(job);
135
138
  return (
136
139
  <div className="space-y-1 px-3 py-2">
137
140
  <div className="flex items-center gap-2 text-[11.5px]">
@@ -173,6 +176,9 @@ function JobRow({ job }: { job: WaitJob }) {
173
176
  {running && percent !== undefined && (
174
177
  <ProgressTrack percent={percent} active />
175
178
  )}
179
+ {progress && (
180
+ <div className="truncate font-mono text-[9px] text-ink/40">{progress}</div>
181
+ )}
176
182
  {job.resolvedModel && (
177
183
  <div className="truncate font-mono text-[9px] text-ink/40">{job.resolvedModel}</div>
178
184
  )}
@@ -0,0 +1,252 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Folding and brace detection in the DIFF bodies.
8
+ *
9
+ * Two layers, because each can be wrong on its own:
10
+ *
11
+ * - The RULE (`braceFoldRange`) is pure, and every way it fails is a boundary:
12
+ * an opener that does not really close, a pair that hides nothing, a cap that
13
+ * would cut a block at a line the reader never chose.
14
+ * - The MOUNTED STACK is what proves the feature exists at all. `foldGutter()`
15
+ * without a `foldService` draws a gutter and offers no marker; a `foldEffect`
16
+ * dispatched into a state with no `foldState` field is discarded with no
17
+ * error; and `bracketMatching()` is a `ViewPlugin`, so nothing at the state
18
+ * level can see it. Both diff shapes are mounted for that reason — the split
19
+ * view has TWO states, and each one needs its own field and service.
20
+ */
21
+
22
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
23
+ import { Window } from 'happy-dom';
24
+ import { EditorState } from '@codemirror/state';
25
+ import { EditorView } from '@codemirror/view';
26
+ import { foldEffect, foldState, foldable } from '@codemirror/language';
27
+
28
+ import { braceFoldRange, diffFoldingExtensions } from '@/client/components/workspace/diff-panel/folding';
29
+ import { mountSplitDiff, mountUnifiedDiff } from '@/client/components/workspace/diff-panel/merge';
30
+ import { MAX_FOLD_LINES } from '@/client/components/common/code-surface/fold';
31
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
32
+
33
+ const EXTRA_GLOBALS = ['MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame'] as const;
34
+ const native: Partial<Record<(typeof EXTRA_GLOBALS)[number], unknown>> = {};
35
+
36
+ let host: HTMLElement;
37
+
38
+ beforeAll(() => {
39
+ const win = new Window({ url: 'http://localhost' });
40
+ installDomGlobals(win);
41
+ const target = globalThis as unknown as Record<string, unknown>;
42
+ for (const key of EXTRA_GLOBALS) {
43
+ native[key] = target[key];
44
+ target[key] = (win as unknown as Record<string, unknown>)[key];
45
+ }
46
+ host = document.body.appendChild(document.createElement('div'));
47
+ });
48
+
49
+ afterAll(() => {
50
+ const target = globalThis as unknown as Record<string, unknown>;
51
+ for (const key of EXTRA_GLOBALS) {
52
+ if (native[key] === undefined) delete target[key];
53
+ else target[key] = native[key];
54
+ }
55
+ restoreDomGlobals();
56
+ });
57
+
58
+ function stateOf(doc: string): EditorState {
59
+ return EditorState.create({ doc, extensions: diffFoldingExtensions });
60
+ }
61
+
62
+ /** The fold for line `number` (1-based), as `[startLine, endLine]` or null. */
63
+ function foldAt(state: EditorState, number: number): [number, number] | null {
64
+ const line = state.doc.line(number);
65
+ const range = foldable(state, line.from, line.to);
66
+ if (!range) return null;
67
+ return [state.doc.lineAt(range.from).number, state.doc.lineAt(range.to).number];
68
+ }
69
+
70
+ function diffOptions(original: string, next: string) {
71
+ return {
72
+ original,
73
+ next,
74
+ language: 'typescript',
75
+ wordWrap: false,
76
+ collapse: 'full' as const,
77
+ scrollTestId: 'diff-fold-test',
78
+ onScroller: () => {},
79
+ };
80
+ }
81
+
82
+ /** The view inside the FIRST editor of a mounted host. */
83
+ function viewIn(element: Element): EditorView {
84
+ const editor = EditorView.findFromDOM(element as HTMLElement);
85
+ if (!editor) throw new Error('no EditorView inside the mounted host');
86
+ return editor;
87
+ }
88
+
89
+ function foldMarkers(element: Element): string[] {
90
+ // `foldGutter` draws an `initialSpacer` marker that reserves the gutter's
91
+ // width — a real `.cm-gutterElement` with `visibility: hidden`. Only the
92
+ // visible ones are markers the reader can click.
93
+ return Array.from(element.querySelectorAll('.cm-foldGutter .cm-gutterElement span'))
94
+ .filter((node) => !(node.parentElement?.getAttribute('style') ?? '').includes('hidden'))
95
+ .map((node) => node.textContent ?? '');
96
+ }
97
+
98
+ describe('braceFoldRange', () => {
99
+ test('a brace block folds down to the line before its closing brace', () => {
100
+ const state = stateOf('function f() {\n a();\n b();\n}\nafter();\n');
101
+ expect(foldAt(state, 1)).toEqual([1, 3]);
102
+ });
103
+
104
+ test('the fold starts after the opener LINE, so the opener stays visible', () => {
105
+ const state = stateOf('function f() {\n a();\n}\n');
106
+ const line = state.doc.line(1);
107
+ const range = braceFoldRange(state, line.from, line.to);
108
+ expect(range?.from).toBe(line.to);
109
+ });
110
+
111
+ test('a pair that closes on the NEXT line hides nothing and does not fold', () => {
112
+ const state = stateOf('call(\n a);\nother();\n');
113
+ // The `(` closes on line 2, so the range would hide nothing at all.
114
+ expect(braceFoldRange(state, 0, state.doc.line(1).to)).toBeNull();
115
+ });
116
+
117
+ test('an opener with no closer is refused by the brace rule, not folded to the end', () => {
118
+ const state = stateOf('function f() {\n a();\n');
119
+ // The brace rule itself must answer null; `foldAt` would still fold the
120
+ // body by INDENTATION, which is the fallback doing its job.
121
+ expect(braceFoldRange(state, 0, state.doc.line(1).to)).toBeNull();
122
+ });
123
+
124
+ test('a same-line pair is skipped in favour of the outer block', () => {
125
+ const state = stateOf('function f(a, b) {\n call(a);\n}\n');
126
+ // `(` closes on line 1, so the `{` is the pair that spans lines.
127
+ expect(foldAt(state, 1)).toEqual([1, 2]);
128
+ });
129
+
130
+ test('a nested block folds to its OWN closer', () => {
131
+ const state = stateOf('if (a) {\n if (b) {\n c();\n }\n d();\n}\n');
132
+ expect(foldAt(state, 1)).toEqual([1, 5]);
133
+ expect(foldAt(state, 2)).toEqual([2, 3]);
134
+ });
135
+
136
+ test('a bracket list folds the same way a brace block does', () => {
137
+ const state = stateOf('const x = [\n 1,\n 2,\n];\nnext();\n');
138
+ expect(foldAt(state, 1)).toEqual([1, 3]);
139
+ });
140
+
141
+ test('a one-line block does not fold', () => {
142
+ const state = stateOf('if (a) { b(); }\nnext();\n');
143
+ expect(foldAt(state, 1)).toBeNull();
144
+ });
145
+
146
+ test('mismatched bracket types do not swallow each other', () => {
147
+ // A `(` counter that also counted `}` would pair this `{` with the `)`.
148
+ const state = stateOf('call(a, {\n b: 1,\n});\nnext();\n');
149
+ expect(foldAt(state, 1)).toEqual([1, 2]);
150
+ });
151
+
152
+ test('a block past the cap is REFUSED rather than truncated', () => {
153
+ const state = stateOf('function f() {\n' + ' x();\n'.repeat(MAX_FOLD_LINES + 10) + '}\n');
154
+ expect(foldAt(state, 1)).toBeNull();
155
+ });
156
+
157
+ test('a block inside the cap still folds', () => {
158
+ const state = stateOf('function f() {\n' + ' x();\n'.repeat(50) + '}\n');
159
+ expect(foldAt(state, 1)).toEqual([1, 51]);
160
+ });
161
+
162
+ test('the indentation rule still answers where no bracket spans lines', () => {
163
+ const state = stateOf('key:\n a: 1\n b: 2\nnext: 1\n');
164
+ // No brace on line 1: this fold is `indentFoldService`'s.
165
+ expect(foldAt(state, 1)).toEqual([1, 3]);
166
+ expect(braceFoldRange(state, 0, state.doc.line(1).to)).toBeNull();
167
+ });
168
+ });
169
+
170
+ describe('the mounted diff stack', () => {
171
+ test('a unified diff installs the fold state and offers a marker', () => {
172
+ const element = host.appendChild(document.createElement('div'));
173
+ const handle = mountUnifiedDiff(element, diffOptions('const a = 1;\n', 'function g() {\n a();\n}\n'));
174
+ try {
175
+ const view = viewIn(element);
176
+ expect(view.state.field(foldState, false)).toBeDefined();
177
+ expect(foldMarkers(element)).toHaveLength(1);
178
+ } finally {
179
+ handle.destroy();
180
+ element.remove();
181
+ }
182
+ });
183
+
184
+ test('a folded block in a unified diff draws the placeholder', () => {
185
+ const element = host.appendChild(document.createElement('div'));
186
+ const handle = mountUnifiedDiff(element, diffOptions('const a = 1;\n', 'function g() {\n a();\n b();\n}\n'));
187
+ try {
188
+ const view = viewIn(element);
189
+ expect(view.state.doc.lines).toBe(5);
190
+ const before = view.contentDOM.querySelectorAll('.cm-line').length;
191
+ view.dispatch({
192
+ effects: foldEffect.of({ from: view.state.doc.line(1).to, to: view.state.doc.line(3).to }),
193
+ });
194
+ expect(view.contentDOM.querySelector('.cm-foldPlaceholder')).not.toBeNull();
195
+ expect(view.contentDOM.querySelectorAll('.cm-line').length).toBeLessThan(before);
196
+ } finally {
197
+ handle.destroy();
198
+ element.remove();
199
+ }
200
+ });
201
+
202
+ test('a unified diff paints both ends of the caret’s brace pair', () => {
203
+ const element = host.appendChild(document.createElement('div'));
204
+ const doc = 'function g() {\n a();\n}\n';
205
+ const handle = mountUnifiedDiff(element, diffOptions('const a = 1;\n', doc));
206
+ try {
207
+ const view = viewIn(element);
208
+ view.dispatch({ selection: { anchor: doc.indexOf('{') + 1 } });
209
+ const painted = Array.from(
210
+ view.contentDOM.querySelectorAll('.cm-matchingBracket'),
211
+ ).map((node) => node.textContent);
212
+ expect(painted).toEqual(['{', '}']);
213
+ } finally {
214
+ handle.destroy();
215
+ element.remove();
216
+ }
217
+ });
218
+
219
+ test('the guide draws the rows between the caret’s brace and its pair', () => {
220
+ const element = host.appendChild(document.createElement('div'));
221
+ const doc = 'function g() {\n a();\n b();\n}\n';
222
+ const handle = mountUnifiedDiff(element, diffOptions('const a = 1;\n', doc));
223
+ try {
224
+ const view = viewIn(element);
225
+ view.dispatch({ selection: { anchor: doc.indexOf('{') + 1 } });
226
+ // The two body rows; the opener and the closer keep their own lines.
227
+ expect(view.contentDOM.querySelectorAll('.cm-line.cm-bracket-guide')).toHaveLength(2);
228
+ } finally {
229
+ handle.destroy();
230
+ element.remove();
231
+ }
232
+ });
233
+
234
+ test('BOTH halves of a split diff fold independently', () => {
235
+ const element = host.appendChild(document.createElement('div'));
236
+ const handle = mountSplitDiff(element, diffOptions('before();\n', 'function g() {\n a();\n}\n'));
237
+ try {
238
+ const editors = Array.from(element.querySelectorAll('.cm-editor'));
239
+ expect(editors).toHaveLength(2);
240
+ for (const editor of editors) {
241
+ const view = viewIn(editor);
242
+ expect(view.state.field(foldState, false)).toBeDefined();
243
+ }
244
+ // Only the new side has a brace block, so only it offers a marker.
245
+ expect(foldMarkers(editors[0] as Element)).toHaveLength(0);
246
+ expect(foldMarkers(editors[1] as Element)).toHaveLength(1);
247
+ } finally {
248
+ handle.destroy();
249
+ element.remove();
250
+ }
251
+ });
252
+ });
@@ -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
+ }