@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,145 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * A folder that is not a repository gets ONE control instead of the panel's
8
+ * chrome.
9
+ *
10
+ * The status read reports `isRepo: false` for it (it used to fold git's refusal
11
+ * into an empty change list on branch `main`), and the panel drew its branch
12
+ * toolbar, commit box and "No changes found." over a directory where every one of
13
+ * them fails with `fatal: not a git repository` — the reported "the git panel has
14
+ * no function here, only the dropdown works".
15
+ *
16
+ * Split from `index.test.ts`: the two files together exceeded the repo's line
17
+ * ceiling, and each mounts its own harness.
18
+ */
19
+
20
+ import { afterAll, afterEach, beforeAll, 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
+ import { GitPanel } from '@/client/components/workspace/git-panel';
25
+ import { SessionStateProvider } from '@/client/components/common/session-state-provider/index';
26
+ import { resetRealtimeClient } from '@/shared/lib/realtime/client';
27
+ import { gitTopic, reposTopic } from '@/shared/lib/realtime/protocol';
28
+ import { startRealtimeTestServer, type RealtimeTestServer } from '@/test-support/realtime-server';
29
+ import { installDomGlobals, pristineWebSocket, restoreDomGlobals } from '@/test-support/pristine-globals';
30
+ import type { TopicResolver } from '@/server/lib/realtime/hub.server';
31
+
32
+ const ROOT = '/ws';
33
+ const SESSION = 'new-git-panel-init';
34
+ const TOPIC = gitTopic(`${ROOT}\u0000.`);
35
+
36
+ /** The runner's own fetch, reached through `Bun` so a leaked stub cannot be mistaken for it. */
37
+ const nativeFetch = Bun.fetch;
38
+
39
+ let container: HTMLElement;
40
+ let server: RealtimeTestServer;
41
+ /** Every action the panel posted, as its form fields — reset per mount. */
42
+ let actionRequests: Array<Record<string, unknown>> = [];
43
+
44
+ /**
45
+ * A folder outside every repository, as `readGitStatus` reports it: an EMPTY
46
+ * change list carrying git's own refusal. The `isRepo` flag is what the panel
47
+ * reads — the empty list and `main` are the same fields a clean repository has.
48
+ */
49
+ const NOT_A_REPO = {
50
+ changes: [],
51
+ branch: 'main',
52
+ branches: [],
53
+ remoteBranches: [],
54
+ isRepo: false,
55
+ error: 'fatal: not a git repository (or any of the parent directories): .git',
56
+ };
57
+
58
+ beforeAll(() => {
59
+ installDomGlobals(new Window({ url: 'http://localhost' }));
60
+ });
61
+
62
+ afterEach(() => {
63
+ if (container) {
64
+ render(null, container);
65
+ container.remove();
66
+ }
67
+ resetRealtimeClient();
68
+ server?.stop();
69
+ });
70
+
71
+ afterAll(() => {
72
+ (globalThis as unknown as Record<string, unknown>).fetch = nativeFetch;
73
+ restoreDomGlobals();
74
+ });
75
+
76
+ /** Mount the panel over a server that answers the not-a-repository payload. */
77
+ async function mount(): Promise<void> {
78
+ actionRequests = [];
79
+ server = await startRealtimeTestServer(new Map<string, TopicResolver>([
80
+ [TOPIC, async () => NOT_A_REPO],
81
+ [reposTopic(ROOT), async () => ({ repos: ['.'], reposPending: false })],
82
+ ]));
83
+ const win = new Window({ url: `http://127.0.0.1:${server.port}` });
84
+ installDomGlobals(win);
85
+ const target = globalThis as unknown as Record<string, unknown>;
86
+ target.WebSocket = pristineWebSocket;
87
+ target.fetch = async (input: unknown, init?: RequestInit) => {
88
+ const url = String(input);
89
+ const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
90
+ if (url.includes('/state')) return json({ sessionId: SESSION, state: {} });
91
+ if (url.includes('reposOnly')) return json({ repos: ['.'], reposPending: false });
92
+ if (init?.method === 'POST') {
93
+ // Duck-typed, not `instanceof FormData`: the body is built by the panel in
94
+ // the happy-dom realm, so an identity check would miss it.
95
+ const body = init.body as { forEach?: (fn: (value: unknown, key: string) => void) => void } | null;
96
+ const fields: Record<string, unknown> = {};
97
+ body?.forEach?.((value, key) => { fields[key] = value; });
98
+ actionRequests.push(fields);
99
+ return json({ success: true });
100
+ }
101
+ // The panel's own HTTP read answers the same state: both paths agree.
102
+ return json(NOT_A_REPO);
103
+ };
104
+
105
+ container = document.createElement('div');
106
+ document.body.appendChild(container);
107
+ await act(async () => {
108
+ render(
109
+ h(SessionStateProvider, {
110
+ sessionId: SESSION,
111
+ children: h(GitPanel, { rootPath: ROOT, enabled: true }),
112
+ }),
113
+ container,
114
+ );
115
+ });
116
+ await server.waitForTopic(TOPIC, (value) => value !== null);
117
+ for (let i = 0; i < 20; i += 1) await act(async () => {});
118
+ }
119
+
120
+ describe('GitPanel without a repository', () => {
121
+ test('offers Initialize instead of the toolbar, commit box and change list', async () => {
122
+ await mount();
123
+
124
+ expect(container.textContent).toContain('Not a Git repository');
125
+ expect(container.querySelector('button[aria-label="Initialize Git repository"]')).toBeTruthy();
126
+ // The chrome that cannot act on this folder is GONE, not merely empty.
127
+ expect(container.textContent).not.toContain('No changes found.');
128
+ expect(container.querySelector('textarea')).toBeNull();
129
+ expect(container.querySelector('button[aria-label="Sync with upstream"]')).toBeNull();
130
+ });
131
+
132
+ test('the button posts the init action for the scoped folder', async () => {
133
+ await mount();
134
+
135
+ const button = container.querySelector('button[aria-label="Initialize Git repository"]') as HTMLButtonElement | null;
136
+ if (!button) throw new Error('no initialize control rendered');
137
+ await act(async () => { button.click(); });
138
+ for (let i = 0; i < 20; i += 1) await act(async () => {});
139
+
140
+ expect(actionRequests).toHaveLength(1);
141
+ expect(actionRequests[0]?.actionType).toBe('init');
142
+ expect(actionRequests[0]?.repo).toBe('.');
143
+ expect(actionRequests[0]?.root).toBe(ROOT);
144
+ });
145
+ });
@@ -229,11 +229,17 @@ app/hooks/useSync.ts
229
229
  label: 'Deep Typecheck & Regression Suite',
230
230
  durationMs: 1820,
231
231
  resolvedModel: 'claude-3-5-sonnet',
232
- status: 'completed',
232
+ status: 'running',
233
+ completionPercent: 55,
234
+ requests: 90,
235
+ cost: 18.4,
236
+ contextTokens: 163_840,
237
+ contextWindow: 1_048_576,
238
+ stage: 'implementing',
233
239
  },
234
240
  ],
235
241
  },
236
- output: 'All 2 background jobs completed successfully with 0 vulnerabilities detected.',
242
+ output: 'Wait limit reached; 1 of 2 background jobs still running — read proc:// for status.',
237
243
  },
238
244
  ...internalUrlCalls,
239
245
  {
@@ -1,5 +1,5 @@
1
1
  {
2
- "source": "@oh-my-pi/pi-coding-agent 10 tabs / 559 settings",
2
+ "source": "@oh-my-pi/pi-coding-agent 10 tabs / 563 settings",
3
3
  "tabs": [
4
4
  {
5
5
  "id": "appearance",
@@ -1524,7 +1524,7 @@
1524
1524
  "tab": "interaction",
1525
1525
  "group": "Power",
1526
1526
  "label": "Sleep Prevention",
1527
- "description": "Prevent the system sleeping during active sessions. Each level is cumulative — it adds the flags of all lower levels.",
1527
+ "description": "Prevent the system sleeping while the agent is running a turn; an idle session, including one waiting on background jobs, does not hold it. Each level is cumulative — it adds the flags of all lower levels.",
1528
1528
  "options": [
1529
1529
  {
1530
1530
  "value": "off",
@@ -1534,7 +1534,7 @@
1534
1534
  {
1535
1535
  "value": "idle",
1536
1536
  "label": "Prevent Idle Sleep",
1537
- "description": "Keep the system awake while a session is open (macOS `caffeinate -i`)"
1537
+ "description": "Keep the system awake while the agent is running a turn (macOS `caffeinate -i`)"
1538
1538
  },
1539
1539
  {
1540
1540
  "value": "display",
@@ -5887,6 +5887,18 @@
5887
5887
  ]
5888
5888
  }
5889
5889
  },
5890
+ "tools.restrictedFolders": {
5891
+ "type": "array",
5892
+ "default": [],
5893
+ "ui": {
5894
+ "tab": "interaction",
5895
+ "group": "Approvals",
5896
+ "label": "Restricted Folders",
5897
+ "editor": "json",
5898
+ "description": "Folders where every read, write, edit, search, or command needs an explicit approval, whatever the approval mode or a remembered grant. The folder and everything under it is restricted; commands are matched by the directory they run in. A JSON list of paths, e.g. [\"~/secrets\"].",
5899
+ "condition": "restrictedFoldersNotProject"
5900
+ }
5901
+ },
5890
5902
  "todo.enabled": {
5891
5903
  "type": "boolean",
5892
5904
  "default": true,
@@ -6510,6 +6522,16 @@
6510
6522
  "description": "Enable async bash commands and background task execution"
6511
6523
  }
6512
6524
  },
6525
+ "async.printWake": {
6526
+ "type": "boolean",
6527
+ "default": false,
6528
+ "ui": {
6529
+ "tab": "tools",
6530
+ "group": "Execution",
6531
+ "label": "Wake Print Mode on Job Results",
6532
+ "description": "In print mode (-p, --mode json), keep running after the last prompt while this run's background jobs are active, and start another turn in the same session with each job's result; exits once no job or result is pending. Off: print mode exits after its prompts and cancels running jobs"
6533
+ }
6534
+ },
6513
6535
  "async.widgets": {
6514
6536
  "type": "boolean",
6515
6537
  "default": true,
@@ -47,6 +47,15 @@ function selectFrame(id: string, title: string): ExtensionUiDialogRequest {
47
47
  return { type: 'extension_ui_request', id, method: 'select', title, options: ['A (Recommended)', 'B', 'Other (type your own)'] };
48
48
  }
49
49
 
50
+ /**
51
+ * omp's TOOL-APPROVAL gate, exactly as it arrives over RPC: a `select` whose
52
+ * title is omp's whole prompt and whose choices are "Approve" / "Deny"
53
+ * (measured against 18.13.1).
54
+ */
55
+ function approvalGateFrame(id: string, title: string): ExtensionUiDialogRequest {
56
+ return { type: 'extension_ui_request', id, method: 'select', title, options: ['Approve', 'Deny'] };
57
+ }
58
+
50
59
  function confirmFrame(id: string, title: string): ExtensionUiDialogRequest {
51
60
  return { type: 'extension_ui_request', id, method: 'confirm', title };
52
61
  }
@@ -148,4 +157,28 @@ describe('splitAskFrames', () => {
148
157
  expect(split.framesByTool.size).toBe(0);
149
158
  expect(split.modalRequest).toBe(frame);
150
159
  });
160
+
161
+ test('an approval gate is not claimed by an open question\'s card', () => {
162
+ // The gate arrives over RPC as a `select` whose title is omp's approval
163
+ // prompt (measured against 18.13.1) — the same method as a question's own
164
+ // dialog, and its title names no question, so the "last ask spoke"
165
+ // fallback used to hand it to that ask's card. There it rendered as
166
+ // "Approve"/"Deny" offered as the ANSWERS to "Which language?", and the
167
+ // answer was posted to the ask instead of the call being approved.
168
+ const question = selectFrame('f1', 'Which language?');
169
+ const gate = approvalGateFrame('g1', 'Allow tool: read\nReason: Restricted folder: /tmp/secret\nPath: /tmp/secret/creds.txt');
170
+ const split = splitAskFrames(askHistory(['Which language?']), [question, gate], true);
171
+
172
+ const held = split.framesByTool.get('call_ask')?.[0]?.map((frame) => frame.id) ?? [];
173
+ expect(held).toEqual(['f1']);
174
+ expect(split.modalRequest).toBe(gate);
175
+ });
176
+
177
+ test('an approval gate beside no question at all keeps the modal', () => {
178
+ const gate = approvalGateFrame('g1', 'Allow tool: bash\nCommand: ls -la /tmp');
179
+ const split = splitAskFrames([], [gate], true);
180
+
181
+ expect(split.framesByTool.size).toBe(0);
182
+ expect(split.modalRequest).toBe(gate);
183
+ });
151
184
  });
@@ -43,6 +43,7 @@ import { createContext, useContext } from 'preact/compat';
43
43
  import type { ChatMessageData } from '@/shared/types';
44
44
  import type { ExtensionUiDialogRequest } from '@/shared/types/omp/agent';
45
45
  import { groupAskFrames, isAskSettled, isAskToolCall, normalizeAskText, parseAskQuestions, parseAskResult, type AskQuestion } from '@/shared/lib/chat/ask-questions';
46
+ import { isApprovalGateFrame } from '@/shared/lib/chat/omp/approval-gate';
46
47
  import type { ExtensionDialogResponse } from '@/client/components/workspace/chat-timeline/tool-renderers/extension-dialog/Lazy';
47
48
 
48
49
  export interface AskFramesSplit {
@@ -181,7 +182,14 @@ export function splitAskFrames(
181
182
  // The dialog omp opens after "Other (type your own)" names the question in
182
183
  // its title only loosely; it continues whichever ask spoke last. An
183
184
  // approval gate is never part of an ask, so it keeps its own modal.
184
- if (!owner && request.method !== 'confirm') owner = lastOwner;
185
+ //
186
+ // The gate arrives as a `select` over RPC (see `isApprovalGateFrame`), and
187
+ // its title names no question — so the walk above cannot place it, and the
188
+ // "last ask spoke" fallback used to hand it to that ask's card, where
189
+ // "Approve"/"Deny" rendered as the ANSWERS to an unrelated question and
190
+ // the answer went to the wrong tool call. A gate is excluded from the
191
+ // fallback exactly like a `confirm`, and reaches the modal instead.
192
+ if (!owner && request.method !== 'confirm' && !isApprovalGateFrame(request)) owner = lastOwner;
185
193
  if (!owner) continue;
186
194
  claimed.add(request);
187
195
  lastOwner = owner;
@@ -5,8 +5,9 @@
5
5
 
6
6
  /**
7
7
  * The working-tree and history half of the Source Control panel's actions: the
8
- * index, the commit, checkout, branch creation, and the two read actions that
9
- * travel through the POST path (a page of commits, one file's patch).
8
+ * repository init, the index, the commit, checkout, branch creation, and the two
9
+ * read actions that travel through the POST path (a page of commits, one file's
10
+ * patch).
10
11
  *
11
12
  * The branch/remote/conflict/stash half is `git-actions-branch.ts`; both are
12
13
  * merged into one dispatch table by `git-actions.ts`. Split for the repo's
@@ -24,6 +25,7 @@
24
25
 
25
26
  import { invalidateRemoteRefs } from '@/server/lib/fs/git-sync';
26
27
  import { readGitState } from '@/server/lib/fs/git-state';
28
+ import { runGit } from '@/server/lib/fs/git-run';
27
29
  import { revertAll, revertPath } from '@/server/lib/fs/git-revert';
28
30
  import {
29
31
  cherryPick,
@@ -76,6 +78,27 @@ async function checkoutRef(targetDir: string, ref: string): Promise<void> {
76
78
 
77
79
  /** The working-tree and history actions. */
78
80
  export const GIT_WORKTREE_ACTIONS: Record<string, GitActionHandler> = {
81
+ /**
82
+ * Create the repository, for a folder that has none.
83
+ *
84
+ * The Source Control panel offers this INSTEAD of its toolbar, commit box and
85
+ * change list when the status read answers `isRepo: false` (see
86
+ * `git-status-read.ts`), so it is the one action reachable on a tree where
87
+ * every other action would fail with "not a git repository".
88
+ *
89
+ * The guard is the probe, not the panel's render state: `git init` on an
90
+ * existing repository is a silent "Reinitialized existing Git repository", so a
91
+ * stale client would be told it created something it did not. `rev-parse
92
+ * --git-dir` is also what catches the folder-inside-another-repo case, where
93
+ * git answers with the ENCLOSING repository and `init` would nest a second one
94
+ * inside it.
95
+ */
96
+ async init({ targetDir }) {
97
+ const existing = await runGit(['rev-parse', '--git-dir'], { cwd: targetDir });
98
+ if (existing.exitCode === 0) throw new Error('Already a Git repository.');
99
+ await expectOk(['init'], targetDir);
100
+ },
101
+
79
102
  async commit({ formData, targetDir }) {
80
103
  const message = (formData.get('message') as string) ?? '';
81
104
  const amend = formData.get('amend') === '1';
@@ -13,9 +13,9 @@
13
13
  * shape — root/repo resolution, the 400 envelope, the realtime signal — and
14
14
  * adding an action is a row rather than another `else if`.
15
15
  *
16
- * - `git-actions-worktree.ts` — the index, the commit, checkout, branch
17
- * creation, history/graph, and the commit-row actions (cherry-pick, revert,
18
- * reset, rebase).
16
+ * - `git-actions-worktree.ts` — repository init, the index, the commit,
17
+ * checkout, branch creation, history/graph, and the commit-row actions
18
+ * (cherry-pick, revert, reset, rebase).
19
19
  * - `git-actions-branch.ts` — merge, the conflict trio, fetch/push/pull/sync,
20
20
  * branch rename/delete, the stash.
21
21
  */
@@ -103,6 +103,26 @@ describe('readGitStatus', () => {
103
103
  expect(files).toContain('plain.sh');
104
104
  expect(files).toContain('with space.sh');
105
105
  expect(files).toContain('untracked.sh');
106
+ expect(status.isRepo).toBe(true);
107
+ });
108
+
109
+ /**
110
+ * The panel decides between its normal chrome and the init state from this
111
+ * flag, so the not-a-repository answer must be POSITIVE: it used to be an empty
112
+ * change list on branch `main`, which reads exactly like a clean tree (the
113
+ * Source Control panel said "No changes found." and every control it drew
114
+ * failed with git's own refusal).
115
+ */
116
+ test('a folder outside every repository answers isRepo false, with git’s reason', async () => {
117
+ const plain = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-no-repo-'));
118
+ try {
119
+ const status = await readGitStatus(plain);
120
+ expect(status.isRepo).toBe(false);
121
+ expect(status.error ?? '').toMatch(/not a git repository/i);
122
+ expect(status.changes).toEqual([]);
123
+ } finally {
124
+ removeDir(plain);
125
+ }
106
126
  });
107
127
 
108
128
  // The bug this dialect exists to prevent: porcelain's default form escapes
@@ -28,6 +28,18 @@ export interface GitStatusPayload {
28
28
  branch: string;
29
29
  branches: string[];
30
30
  remoteBranches: string[];
31
+ /**
32
+ * Whether `targetDir` is a working tree at all.
33
+ *
34
+ * A directory outside every repository makes each `git` read below exit 128
35
+ * with "fatal: not a git repository", and folding that into the empty-change
36
+ * answer made it indistinguishable from a clean tree: the Source Control panel
37
+ * drew its branch toolbar, commit box and "No changes found." over a folder
38
+ * with no repository to act on. The panel now renders an init state from this
39
+ * flag, so the two answers cannot be confused — a repository with nothing to
40
+ * commit is `isRepo: true` and an empty change list.
41
+ */
42
+ isRepo: boolean;
31
43
  syncCount?: { ahead: number; behind: number };
32
44
  /**
33
45
  * Whether an operation is in progress (merge/rebase/cherry-pick/revert/stash
@@ -86,7 +98,28 @@ export async function readGitStatus(targetDir: string, options: GitStatusOptions
86
98
  // listed, and so a path holding a space, a quote or a non-ASCII byte
87
99
  // arrives VERBATIM. The non-`-z` form quotes those and octal-escapes the
88
100
  // non-ASCII ones, which no decode reverses — see `parsePorcelainZ`.
89
- const statusOut = (await runShell('git status --porcelain=v1 -z -uall', { cwd: targetDir, maxBuffer: 4 * 1024 * 1024, env: GIT_ENV })).stdout;
101
+ const statusResult = await runShell('git status --porcelain=v1 -z -uall', { cwd: targetDir, maxBuffer: 4 * 1024 * 1024, env: GIT_ENV });
102
+ const statusOut = statusResult.stdout;
103
+ // "Is this a working tree at all" is answered by the read everything below
104
+ // already depends on: `git status` is what fails, and it carries git's own
105
+ // reason. A DIFFERENT failure (git missing, a locked index, a permission
106
+ // problem) is deliberately NOT read as "not a repository" — the panel offers
107
+ // `init` on that answer, and offering it for a repository git merely could
108
+ // not read would create a second one nested inside it.
109
+ if (statusResult.exitCode !== 0 && /not a git repository/i.test(statusResult.stderr)) {
110
+ // Both probes started above are already in flight; settling them keeps a
111
+ // rejection from escaping as an unhandled one on the way out.
112
+ await Promise.allSettled([remoteRefresh, stateRead]);
113
+ return {
114
+ changes: [],
115
+ branch: 'main',
116
+ branches: [],
117
+ remoteBranches: [],
118
+ isRepo: false,
119
+ state: { operation: null, conflicts: [], detached: false },
120
+ error: statusResult.stderr.trim() || 'Not a git repository',
121
+ };
122
+ }
90
123
 
91
124
  let branch = 'main';
92
125
  // Seeded empty, not `['main']`: the seed used to be pushed as a real local
@@ -157,10 +190,13 @@ export async function readGitStatus(targetDir: string, options: GitStatusOptions
157
190
  branch: branch || 'main',
158
191
  branches: localBranches,
159
192
  remoteBranches,
193
+ // The `git status` probe above exited 0, which is what a working tree is.
194
+ isRepo: true,
160
195
  syncCount,
161
196
  state,
162
197
  };
163
198
  } catch (error) {
199
+ const message = error instanceof Error ? error.message : 'Git error';
164
200
  return {
165
201
  changes: [],
166
202
  branch: 'main',
@@ -168,7 +204,12 @@ export async function readGitStatus(targetDir: string, options: GitStatusOptions
168
204
  remoteBranches: [],
169
205
  syncCount: { ahead: 0, behind: 0 },
170
206
  state: { operation: null, conflicts: [], detached: false },
171
- error: error instanceof Error ? error.message : 'Git error',
207
+ // A thrown read is not evidence of a MISSING repository — git may simply
208
+ // be unreadable here — and the panel would answer a missing one with an
209
+ // `init` button that recreates it nested inside the real one. Only git's
210
+ // own "not a git repository" earns that answer.
211
+ isRepo: !/not a git repository/i.test(message),
212
+ error: message,
172
213
  };
173
214
  }
174
215
  }
@@ -180,3 +180,24 @@ describe('loadSessionMessages reminder classification', () => {
180
180
  expect(message.notice).toBe('<system-reminder>2 items open</system-reminder>');
181
181
  });
182
182
  });
183
+
184
+ describe('loadSessionMessages developer turns', () => {
185
+ test('a developer-role nudge renders as a notice card, never assistant prose', async () => {
186
+ const nudge = 'Tool call failed: your previous response tried to invoke a tool, but the tool-call markup was malformed, so it arrived as plain text, no tool was executed, and the broken markup was removed from your response.\n\nA tool call must be one complete envelope:\n\n```\n<|DSML|tool_calls>\n<|DSML|invoke name="TOOL_NAME">\n```';
187
+ const file = await writeSession([
188
+ {
189
+ type: 'message',
190
+ id: 'd1',
191
+ timestamp: at(1),
192
+ message: { role: 'developer', attribution: 'agent', content: [{ type: 'text', text: nudge }] },
193
+ },
194
+ ]);
195
+
196
+ const [message] = await loadSessionMessages(file);
197
+
198
+ expect(message.role).toBe('ai');
199
+ expect(message.content).toBe('');
200
+ expect(message.notice).toBe(nudge);
201
+ expect(isNoticeRow(message)).toBe(true);
202
+ });
203
+ });
@@ -332,3 +332,7 @@ describe('create_branch_at (the commit row\'s "create branch here")', () => {
332
332
  expect(git(repo, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe('main');
333
333
  });
334
334
  });
335
+
336
+ /* `init` has its own file (`git-init-action.test.ts`): its fixtures are a
337
+ directory that is NOT a repository, and the two files together exceeded the
338
+ repo's line ceiling. */
@@ -0,0 +1,125 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The `init` action — the one action reachable on a folder with no repository,
8
+ * and the reason `readGitStatus` reports `isRepo` at all.
9
+ *
10
+ * Split from `git-action.test.ts`: the two files together exceeded the repo's
11
+ * line ceiling, and this one needs fixtures the others do not (a directory that
12
+ * is not a repository at all).
13
+ *
14
+ * The guard matters as much as the verb: `git init` on an existing repository
15
+ * prints "Reinitialized existing Git repository" and exits 0, so a stale client
16
+ * (the button survives until the next status read lands) would be told it created
17
+ * something it did not — and inside another repository's subtree it would create
18
+ * a second, nested one.
19
+ */
20
+
21
+ import { afterAll, describe, expect, test } from 'bun:test';
22
+ import fs from 'node:fs';
23
+ import os from 'node:os';
24
+ import path from 'node:path';
25
+ import { action } from '@/server/routes/fs/git';
26
+ import { GIT_ACTIONS } from '@/server/lib/fs/git-actions';
27
+ import { removeDir } from '@/test-support/remove-dir';
28
+
29
+ /**
30
+ * Scratch fixtures under a directory this file owns, inside the app root — the
31
+ * route's allow-list (`resolveRoot` accepts the app root, a path beneath it, or a
32
+ * registered workspace) substitutes the app root for anything else, which would
33
+ * run git against the Kabmo repository itself.
34
+ */
35
+ const FIXTURE_ROOT = path.join(process.cwd(), 'tmp-test-git-init');
36
+ const scratch: string[] = [];
37
+
38
+ function git(cwd: string, ...args: string[]): void {
39
+ const result = Bun.spawnSync({ cmd: ['git', ...args], cwd });
40
+ if (result.exitCode !== 0) {
41
+ throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`);
42
+ }
43
+ }
44
+
45
+ /** A fresh directory under the fixture root (a repository only if `makeRepo` says so). */
46
+ function makeDir(): string {
47
+ fs.mkdirSync(FIXTURE_ROOT, { recursive: true });
48
+ const base = fs.mkdtempSync(path.join(FIXTURE_ROOT, 'work-'));
49
+ scratch.push(base);
50
+ const dir = path.join(base, 'work');
51
+ fs.mkdirSync(dir);
52
+ return dir;
53
+ }
54
+
55
+ /** A fresh repository with one commit. */
56
+ function makeRepo(): string {
57
+ const dir = makeDir();
58
+ git(dir, 'init', '-q', '-b', 'main');
59
+ git(dir, 'config', 'user.email', 'test@example.invalid');
60
+ git(dir, 'config', 'user.name', 'Test');
61
+ fs.writeFileSync(path.join(dir, 'base.txt'), 'base\n');
62
+ git(dir, 'add', '-A');
63
+ git(dir, 'commit', '-q', '-m', 'base');
64
+ return dir;
65
+ }
66
+
67
+ /** POST one action through the route, reading its operands from the form body. */
68
+ async function post(fields: Record<string, string>): Promise<{ status: number; body: { success?: boolean; error?: string } }> {
69
+ if (!(fields.root ?? '').startsWith(FIXTURE_ROOT + path.sep)) {
70
+ throw new Error(`refusing to run a git action outside the fixture root: ${fields.root}`);
71
+ }
72
+ const form = new FormData();
73
+ for (const [key, value] of Object.entries(fields)) form.set(key, value);
74
+ const response = await action({
75
+ request: new Request('http://localhost/api/fs/git', { method: 'POST', body: form }),
76
+ } as never);
77
+ return { status: response.status, body: (await response.json()) as { success?: boolean; error?: string } };
78
+ }
79
+
80
+ afterAll(() => {
81
+ for (const dir of scratch) removeDir(dir);
82
+ removeDir(FIXTURE_ROOT);
83
+ });
84
+
85
+ describe('init', () => {
86
+ test('creates a repository in a folder that has none', async () => {
87
+ // OUTSIDE the app root on purpose: every fixture under it sits inside the
88
+ // Kabmo checkout's own repository — which is the case the last test refuses.
89
+ // So the happy path drives the registered handler directly, in a directory
90
+ // git genuinely knows nothing about.
91
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-init-'));
92
+ try {
93
+ await GIT_ACTIONS.init({ formData: new FormData(), targetDir: dir });
94
+ expect(fs.existsSync(path.join(dir, '.git'))).toBe(true);
95
+ expect(Bun.spawnSync({ cmd: ['git', 'rev-parse', '--git-dir'], cwd: dir }).exitCode).toBe(0);
96
+ } finally {
97
+ removeDir(dir);
98
+ }
99
+ });
100
+
101
+ test('refuses a folder that already is a repository', async () => {
102
+ const repo = makeRepo();
103
+
104
+ const res = await post({ actionType: 'init', repo: '.', root: repo });
105
+
106
+ expect(res.status).toBe(400);
107
+ expect(res.body.error).toContain('Already a Git repository');
108
+ });
109
+
110
+ /**
111
+ * The nested case, only reachable THROUGH the route: a folder inside another
112
+ * repository resolves that enclosing one, so `init` would create a second
113
+ * repository inside the first. The panel never offers the button there
114
+ * (`git status` succeeds, so the read reports `isRepo: true`), but the guard is
115
+ * the server's, not the panel's render state.
116
+ */
117
+ test('refuses a folder inside another repository rather than nesting one', async () => {
118
+ const dir = makeDir();
119
+
120
+ const res = await post({ actionType: 'init', repo: '.', root: dir });
121
+
122
+ expect(res.status).toBe(400);
123
+ expect(fs.existsSync(path.join(dir, '.git'))).toBe(false);
124
+ });
125
+ });
@@ -6,6 +6,7 @@
6
6
  import { describe, expect, test } from 'bun:test';
7
7
 
8
8
  import {
9
+ developerTurnNotice,
9
10
  isNoticeRow,
10
11
  messageAnswerText,
11
12
  noticeIsAssistantText,
@@ -72,6 +73,30 @@ describe('reminderPartIndex', () => {
72
73
  });
73
74
  });
74
75
 
76
+ describe('developerTurnNotice', () => {
77
+ test('is undefined for a non-harness role', () => {
78
+ expect(developerTurnNotice('assistant', ['answer text'])).toBeUndefined();
79
+ expect(developerTurnNotice('user', ['prompt'])).toBeUndefined();
80
+ expect(developerTurnNotice(undefined, ['x'])).toBeUndefined();
81
+ });
82
+
83
+ test('keeps the plain text of a developer nudge, tags stripped', () => {
84
+ const nudge = 'Tool call failed: your previous response tried to invoke a tool.\n\n```\n<|DSML|tool_calls>\n```';
85
+ expect(developerTurnNotice('developer', [nudge])).toBe(nudge);
86
+ });
87
+
88
+ test('keeps the envelope of a wrapped developer turn (the tag is identity)', () => {
89
+ const wrapped = '<system-reminder rule="ts-no-any">\nNo any.\n</system-reminder>';
90
+ expect(developerTurnNotice('developer', [wrapped])).toBe(wrapped);
91
+ });
92
+
93
+ test('applies to the system role too and returns undefined for empty text', () => {
94
+ expect(developerTurnNotice('system', ['sys rule'])).toBe('sys rule');
95
+ expect(developerTurnNotice('developer', [' '])).toBeUndefined();
96
+ expect(developerTurnNotice('system', [])).toBeUndefined();
97
+ });
98
+ });
99
+
75
100
  describe('notice row classification', () => {
76
101
  test('a bare notice row is a notice card', () => {
77
102
  const notice = row({ notice: 'Late LSP diagnostics arrived after the edit returned.' });