@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
@@ -0,0 +1,194 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * A session whose RECORDED model cannot be restored still starts.
8
+ *
9
+ * `omp --resume <file>` restores the model the session's last `model_change`
10
+ * entry names, and it does NOT fall back when that model is gone: the child
11
+ * exits(1) with `error: Could not restore model <provider>/<id>`, so every
12
+ * command to that session fails with it — the `set_model` a model change
13
+ * posts, the `get_state` warmup, and the `prompt` alike.
14
+ *
15
+ * Measured on omp 18.13.1 against a real session file: the user-visible shape
16
+ * was "I changed the model, then sent a prompt to the previous session, and
17
+ * the prompt never arrived". `--model <a model omp can resolve>` makes the
18
+ * resume start (verified against the real binary), which is the lever the
19
+ * recovery uses.
20
+ *
21
+ * This drives the REAL spawn path (`startRpcSession` → `RpcProcess` → the
22
+ * scripted child), so the retry, the `--model` argument and the registration
23
+ * bookkeeping are the shipped code — not a stub of it.
24
+ */
25
+
26
+ import { afterEach, beforeEach, expect, test } from 'bun:test';
27
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
28
+ import { tmpdir } from 'node:os';
29
+ import { join } from 'node:path';
30
+ import { describePosix } from '@/test-support/platform';
31
+
32
+ import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
33
+ import { stopDiscoveryRootsWatch } from '@/server/lib/omp/config/roots-watch.server';
34
+ import { getRpcSession, startRpcSession } from '@/server/lib/omp/rpc/session-registry';
35
+ import { invalidateResolvableModels } from '@/server/lib/omp/session/resumable-model.server';
36
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
37
+
38
+ let root: string;
39
+ let agentDir: string;
40
+ let saved: Record<string, string | undefined>;
41
+
42
+ const ENV_KEYS = [
43
+ 'KABMO_OMP_BIN',
44
+ 'PI_CODING_AGENT_DIR',
45
+ 'KABMO_DB_PATH',
46
+ 'SYNC_WORKSPACE',
47
+ 'FAKE_OMP_RESTORE_FAILS',
48
+ 'FAKE_OMP_RESTORE_MODELS',
49
+ 'FAKE_OMP_RESTORE_LOG',
50
+ ] as const;
51
+
52
+ /** The argv of every child the scripted omp started, in spawn order. */
53
+ function spawnedArgs(): string[][] {
54
+ const path = Bun.env.FAKE_OMP_RESTORE_LOG;
55
+ if (!path || !existsSync(path)) return [];
56
+ return readFileSync(path, 'utf8')
57
+ .trim()
58
+ .split('\n')
59
+ .filter(Boolean)
60
+ .map((line) => JSON.parse(line) as string[]);
61
+ }
62
+
63
+ beforeEach(async () => {
64
+ root = mkdtempSync(join(tmpdir(), 'omp-restore-test-'));
65
+ saved = Object.fromEntries(ENV_KEYS.map((key) => [key, Bun.env[key]]));
66
+ await isolateDb();
67
+ agentDir = join(root, 'agent');
68
+ Bun.env.KABMO_OMP_BIN = join(import.meta.dir, '../../../../test-support/fake-omp-restore.ts');
69
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
70
+ Bun.env.SYNC_WORKSPACE = 'false';
71
+ Bun.env.FAKE_OMP_RESTORE_FAILS = '1';
72
+ Bun.env.FAKE_OMP_RESTORE_MODELS = 'kenari/deepseek-v4-flash,kenari/deepseek-v4-pro';
73
+ Bun.env.FAKE_OMP_RESTORE_LOG = join(root, 'spawns.jsonl');
74
+ invalidateOmpCliCache();
75
+ invalidateResolvableModels();
76
+ delete globalThis.__ompSessions;
77
+ delete globalThis.__ompStartLocks;
78
+ // The registry's fallback candidate: config.yml's `modelRoles.default`.
79
+ mkdirSync(agentDir, { recursive: true });
80
+ writeFileSync(
81
+ join(agentDir, 'config.yml'),
82
+ 'modelRoles:\n default: kenari/deepseek-v4-flash\n',
83
+ );
84
+ });
85
+
86
+ afterEach(async () => {
87
+ stopDiscoveryRootsWatch();
88
+ delete globalThis.__ompSessions;
89
+ delete globalThis.__ompStartLocks;
90
+ invalidateOmpCliCache();
91
+ invalidateResolvableModels();
92
+ await releaseDb();
93
+ for (const key of ENV_KEYS) {
94
+ const value = saved[key];
95
+ if (value === undefined) delete Bun.env[key];
96
+ else Bun.env[key] = value;
97
+ }
98
+ rmSync(root, { recursive: true, force: true });
99
+ });
100
+
101
+ // The scripted omp is spawned from a `#!/usr/bin/env bun` file; Windows can
102
+ // start a real executable, not a shebang file, so `uv_spawn` answers EFTYPE.
103
+ describePosix('a session whose recorded model cannot be restored', () => {
104
+ test('is respawned with a resolvable --model and comes up', async () => {
105
+ const cwd = join(root, 'ws');
106
+ const sessionsDir = join(root, 'agent', 'sessions', 'ws');
107
+ mkdirSync(cwd, { recursive: true });
108
+ mkdirSync(sessionsDir, { recursive: true });
109
+ const sessionFile = join(sessionsDir, 's.jsonl');
110
+ writeFileSync(sessionFile, '');
111
+
112
+ const { session } = await startRpcSession('restore-test-session', sessionFile, cwd);
113
+
114
+ // The session is USABLE: the wrapper is alive and registered, which is what
115
+ // the prompt path needs.
116
+ expect(session.isAlive()).toBe(true);
117
+ expect(getRpcSession('restore-test-session')).toBe(session);
118
+
119
+ // Two spawns: the bare resume (which died with omp's own restore error),
120
+ // then the recovered one carrying the model that resolves.
121
+ const attempts = spawnedArgs();
122
+ expect(attempts.length).toBe(2);
123
+ expect(attempts[0]).not.toContain('--model');
124
+ expect(attempts[1]).toContain('--model');
125
+ expect(attempts[1][attempts[1].indexOf('--model') + 1]).toBe('kenari/deepseek-v4-flash');
126
+
127
+ session.destroy();
128
+ }, 30_000);
129
+
130
+ test('the new child runs on the model it was resumed with', async () => {
131
+ const cwd = join(root, 'ws');
132
+ const sessionsDir = join(root, 'agent', 'sessions', 'ws');
133
+ mkdirSync(cwd, { recursive: true });
134
+ mkdirSync(sessionsDir, { recursive: true });
135
+ const sessionFile = join(sessionsDir, 's.jsonl');
136
+ writeFileSync(sessionFile, '');
137
+
138
+ const { session } = await startRpcSession('restore-test-model', sessionFile, cwd);
139
+ const state = await session.send({ type: 'get_state' }) as { model?: { provider?: string; id?: string } };
140
+
141
+ expect(state.model?.provider).toBe('kenari');
142
+ expect(state.model?.id).toBe('deepseek-v4-flash');
143
+ session.destroy();
144
+ }, 30_000);
145
+
146
+ test('the caller\'s own pick is the first recovery candidate', async () => {
147
+ const cwd = join(root, 'ws');
148
+ const sessionsDir = join(root, 'agent', 'sessions', 'ws');
149
+ mkdirSync(cwd, { recursive: true });
150
+ mkdirSync(sessionsDir, { recursive: true });
151
+ const sessionFile = join(sessionsDir, 's.jsonl');
152
+ writeFileSync(sessionFile, '');
153
+
154
+ // A `set_model` posts the operator's own pick, so the session resumes on
155
+ // what they chose — but only through the recovery: the first attempt names
156
+ // no model, because a stale pick must not make a healthy session
157
+ // unopenable (omp answers `Model <x> not found` for one).
158
+ const { session } = await startRpcSession(
159
+ 'restore-test-explicit',
160
+ sessionFile,
161
+ cwd,
162
+ undefined,
163
+ undefined,
164
+ undefined,
165
+ { provider: 'kenari', modelId: 'deepseek-v4-pro' },
166
+ );
167
+
168
+ const attempts = spawnedArgs();
169
+ expect(attempts.length).toBe(2);
170
+ expect(attempts[0]).not.toContain('--model');
171
+ expect(attempts[1][attempts[1].indexOf('--model') + 1]).toBe('kenari/deepseek-v4-pro');
172
+ session.destroy();
173
+ }, 30_000);
174
+
175
+ test('an unrecoverable resume still reports the failure', async () => {
176
+ // No model omp can resolve: the catalog is empty and no default is set.
177
+ Bun.env.FAKE_OMP_RESTORE_MODELS = '';
178
+ writeFileSync(join(agentDir, 'config.yml'), '{}\n');
179
+ invalidateResolvableModels();
180
+
181
+ const cwd = join(root, 'ws');
182
+ const sessionsDir = join(root, 'agent', 'sessions', 'ws');
183
+ mkdirSync(cwd, { recursive: true });
184
+ mkdirSync(sessionsDir, { recursive: true });
185
+ const sessionFile = join(sessionsDir, 's.jsonl');
186
+ writeFileSync(sessionFile, '');
187
+
188
+ // The failure is NOT swallowed: the caller sees omp's own sentence, which
189
+ // names the model that could not be restored.
190
+ const failure = await startRpcSession('restore-test-honest', sessionFile, cwd).catch((error: unknown) => error);
191
+ expect(failure).toBeInstanceOf(Error);
192
+ expect((failure as Error).message).toContain('Could not restore model');
193
+ }, 30_000);
194
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The recovery for a session whose RECORDED model no longer exists.
8
+ *
9
+ * `omp --resume <file>` restores the model the session's last `model_change`
10
+ * entry names, and it does NOT fall back when that model is gone: the child
11
+ * exits(1) with "Could not restore model <provider>/<id>", and EVERY command
12
+ * to that session fails with it — the `set_model` a model change posts, the
13
+ * `get_state` warmup, and the `prompt` alike.
14
+ *
15
+ * Measured on omp 18.13.1: a session whose last `model_change` named a
16
+ * provider that is not in the registry (`deepseek/deepseek-flash`) could not
17
+ * receive a prompt at all, and the user-visible shape was "I changed the
18
+ * model, then sent a prompt to the previous session, and the prompt never
19
+ * arrived".
20
+ *
21
+ * These cases pin the two halves of the recovery:
22
+ * - the FAILURE is recognised from omp's own message, and nothing else is;
23
+ * - the RESPAWN carries `--model <a model omp can resolve>`, which is what
24
+ * makes the resume succeed (verified against the real omp binary).
25
+ */
26
+
27
+ import { describe, expect, test } from 'bun:test';
28
+
29
+ import { isUnrestorableModelFailure } from '@/server/lib/omp/session/resumable-model.server';
30
+ import { buildSessionSpawnArgs } from '@/server/lib/omp/rpc/constants';
31
+
32
+ describe('the unrestorable-model failure', () => {
33
+ // omp's own wording, as it appears in the child's stderr tail.
34
+ const restoreFailure = 'omp exited (code 1, signal none): error: Could not restore model deepseek/deepseek-flash\n';
35
+
36
+ test('is recognised from omp\'s own sentence', () => {
37
+ expect(isUnrestorableModelFailure(new Error(restoreFailure))).toBe(true);
38
+ });
39
+
40
+ test('is recognised from a bare message too', () => {
41
+ expect(isUnrestorableModelFailure(new Error('Could not restore model kenari/gone'))).toBe(true);
42
+ });
43
+
44
+ test('another spawn failure is NOT this one', () => {
45
+ // A wrong cwd, a missing binary, a crash: each needs its own report, and
46
+ // respawning with a different model would hide the real cause.
47
+ expect(isUnrestorableModelFailure(new Error('omp exited (code 1): spawn ENOENT'))).toBe(false);
48
+ expect(isUnrestorableModelFailure(new Error('omp binary not found'))).toBe(false);
49
+ expect(isUnrestorableModelFailure(new Error('omp exited (code 137, signal SIGKILL)'))).toBe(false);
50
+ });
51
+
52
+ test('a non-Error throw is judged by its text', () => {
53
+ expect(isUnrestorableModelFailure('Could not restore model a/b')).toBe(true);
54
+ expect(isUnrestorableModelFailure(undefined)).toBe(false);
55
+ });
56
+ });
57
+
58
+ describe('the resume model on the spawn', () => {
59
+ test('is named so omp restores a model that resolves', () => {
60
+ const args = buildSessionSpawnArgs('/tmp/session.jsonl', 'always-ask', {
61
+ provider: 'kenari',
62
+ modelId: 'deepseek-v4-flash',
63
+ });
64
+ expect(args).toContain('--model');
65
+ expect(args[args.indexOf('--model') + 1]).toBe('kenari/deepseek-v4-flash');
66
+ });
67
+
68
+ test('is omitted when there is no replacement', () => {
69
+ // A healthy session is spawned exactly as before: omp restores the
70
+ // transcript's own model, and no catalog is read for it.
71
+ expect(buildSessionSpawnArgs('/tmp/session.jsonl', 'always-ask')).not.toContain('--model');
72
+ });
73
+
74
+ test('a half-specified model is not passed on', () => {
75
+ const args = buildSessionSpawnArgs('/tmp/session.jsonl', 'always-ask', {
76
+ provider: 'kenari',
77
+ modelId: '',
78
+ });
79
+ expect(args).not.toContain('--model');
80
+ });
81
+
82
+ test('the resume file and the approval mode are untouched', () => {
83
+ const args = buildSessionSpawnArgs('/tmp/session.jsonl', 'yolo', {
84
+ provider: 'kenari',
85
+ modelId: 'deepseek-v4-flash',
86
+ });
87
+ expect(args[args.indexOf('--resume') + 1]).toBe('/tmp/session.jsonl');
88
+ expect(args[args.indexOf('--approval-mode') + 1]).toBe('yolo');
89
+ });
90
+ });
@@ -0,0 +1,181 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Recovering a session whose RECORDED model no longer exists.
8
+ *
9
+ * ## The failure
10
+ *
11
+ * `omp --resume <file>` restores the model the session's last `model_change`
12
+ * entry names. When that model is no longer in the registry — a provider the
13
+ * user disconnected, a model removed from `models.yml`, a provider added to
14
+ * `disabledProviders` — omp does NOT fall back: the child exits(1) with
15
+ * `error: Could not restore model <provider>/<id>`.
16
+ *
17
+ * Measured on this machine (omp 18.13.1): a session whose last `model_change`
18
+ * was `deepseek/deepseek-flash` (a provider that is not in the registry at all)
19
+ * made every later command to that session fail with that error — the `set_model`
20
+ * a model change posts, the `get_state` warmup, and the `prompt` alike. The
21
+ * user-visible shape is "I changed the model, then sent a prompt to the
22
+ * previous session, and the prompt never arrived": the send never reached a
23
+ * model because the child could not even start.
24
+ *
25
+ * ## The recovery
26
+ *
27
+ * The session is RESPAWNED with `--model <a model omp can resolve>`. The
28
+ * command that triggered the spawn then runs against the new child, so the
29
+ * user's own `set_model` still lands and the pick they made is what the
30
+ * session ends up running.
31
+ *
32
+ * The respawn happens ONLY when the child died for this reason: a healthy
33
+ * session is spawned exactly as before, and no catalog is read (the listing
34
+ * costs ~1.3 s).
35
+ *
36
+ * ## Why the CLI listing is the oracle
37
+ *
38
+ * The set of models omp can actually resolve is its OWN listing
39
+ * (`omp models --json --kind all`), not the chat picker: the picker filters
40
+ * `disabledProviders` and per-model hides out, so a model the picker once
41
+ * offered can be absent from it while omp still resolves it, and a model the
42
+ * picker never offered (a `kind` other than `chat`) can still be what the
43
+ * transcript names. The listing is the union of everything omp can run, which
44
+ * is exactly the question "can this session's model be restored?".
45
+ */
46
+
47
+ import { getDb } from '@/server/db.server';
48
+ import { readSettingsJson } from '@/server/lib/db/settings-store';
49
+ import { childEnv } from '@/server/lib/fs/child-env';
50
+ import { resolveOmpBin } from '@/server/lib/omp/core/cli';
51
+ import { readModelRoles } from '@/server/lib/omp/config/roles';
52
+ import type { SelectedModel } from '@/shared/types/models';
53
+
54
+ /** How long the CLI listing stays usable. */
55
+ const CATALOG_TTL_MS = 60_000;
56
+ const CATALOG_TIMEOUT_MS = 30_000;
57
+
58
+ /** The app_settings row the model dropdown writes on every pick. */
59
+ const SELECTED_MODEL_KEY = 'omp_selected_model';
60
+
61
+ declare global {
62
+ // eslint-disable-next-line no-var
63
+ var __kabmoResolvableModels: { at: number; selectors: Set<string> } | undefined;
64
+ }
65
+
66
+ /** `provider/id` → the selector omp's own listing reports. */
67
+ function selectorOf(model: SelectedModel): string {
68
+ return `${model.provider}/${model.modelId}`;
69
+ }
70
+
71
+ /**
72
+ * Every model omp can resolve, as `provider/id` selectors.
73
+ *
74
+ * `null` when the listing could not be read — the caller then has no basis for
75
+ * a replacement and the spawn failure is reported as it is.
76
+ */
77
+ async function readResolvableSelectors(): Promise<Set<string> | null> {
78
+ const cached = globalThis.__kabmoResolvableModels;
79
+ if (cached && cached.at + CATALOG_TTL_MS > Date.now()) return cached.selectors;
80
+
81
+ const bin = resolveOmpBin();
82
+ if (!bin) return null;
83
+ try {
84
+ const proc = Bun.spawn({
85
+ env: childEnv(),
86
+ cmd: [bin, 'models', '--json', '--kind', 'all'],
87
+ stdout: 'pipe',
88
+ stderr: 'ignore',
89
+ timeout: CATALOG_TIMEOUT_MS,
90
+ maxBuffer: 32 * 1024 * 1024,
91
+ windowsHide: true,
92
+ });
93
+ const stdout = await new Response(proc.stdout).text();
94
+ if ((await proc.exited) !== 0) return null;
95
+ const parsed = JSON.parse(stdout) as { models?: unknown };
96
+ if (!Array.isArray(parsed.models)) return null;
97
+ const selectors = new Set<string>();
98
+ for (const entry of parsed.models) {
99
+ if (typeof entry !== 'object' || entry === null) continue;
100
+ const row = entry as { provider?: unknown; id?: unknown };
101
+ if (typeof row.provider !== 'string' || typeof row.id !== 'string') continue;
102
+ selectors.add(`${row.provider}/${row.id}`);
103
+ }
104
+ globalThis.__kabmoResolvableModels = { at: Date.now(), selectors };
105
+ return selectors;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /** Drop the cached listing (a provider or model changed under us). */
112
+ export function invalidateResolvableModels(): void {
113
+ globalThis.__kabmoResolvableModels = undefined;
114
+ }
115
+
116
+ /**
117
+ * True when a child died because omp could not restore the session's model.
118
+ *
119
+ * The message is omp's own (`error: Could not restore model <provider>/<id>`),
120
+ * carried in the process's stderr tail by the exit error.
121
+ */
122
+ export function isUnrestorableModelFailure(error: unknown): boolean {
123
+ const message = error instanceof Error ? error.message : String(error);
124
+ return /Could not restore model\s+\S+/.test(message);
125
+ }
126
+
127
+ /** The model the model dropdown last recorded, as a `provider`/`modelId` pair. */
128
+ async function readPersistedPick(): Promise<SelectedModel | null> {
129
+ try {
130
+ const db = await getDb();
131
+ const stored = await readSettingsJson<unknown>(db, SELECTED_MODEL_KEY, null);
132
+ if (typeof stored !== 'object' || stored === null) return null;
133
+ const row = stored as { provider?: unknown; modelId?: unknown; id?: unknown };
134
+ const provider = typeof row.provider === 'string' ? row.provider : '';
135
+ const modelId = typeof row.modelId === 'string'
136
+ ? row.modelId
137
+ : typeof row.id === 'string' ? row.id : '';
138
+ if (!provider || !modelId) return null;
139
+ return { provider, modelId };
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+
145
+ /** The registry's default model (`config.yml`'s `modelRoles.default`). */
146
+ async function readRegistryDefault(): Promise<SelectedModel | null> {
147
+ try {
148
+ const { roles } = await readModelRoles();
149
+ const selector = roles.default;
150
+ if (!selector) return null;
151
+ const slash = selector.indexOf('/');
152
+ if (slash <= 0 || slash === selector.length - 1) return null;
153
+ return { provider: selector.slice(0, slash), modelId: selector.slice(slash + 1) };
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * A model omp can resolve, to RESUME a session with.
161
+ *
162
+ * The order is the caller's own candidate first (the model the command being
163
+ * dispatched asks for — the operator's pick in the composer), then the model
164
+ * the dropdown last recorded, then the registry's default. The session's
165
+ * RECORDED model is deliberately not a candidate: it is the one that could not
166
+ * be restored, and offering it again would repeat the same failure.
167
+ */
168
+ export async function resolveResumableModel(
169
+ preferred?: SelectedModel | null,
170
+ ): Promise<SelectedModel | null> {
171
+ const selectors = await readResolvableSelectors();
172
+ // The listing could not be read: there is no basis for a replacement, and a
173
+ // guess would swap the session's model for an arbitrary one.
174
+ if (!selectors) return null;
175
+
176
+ for (const candidate of [preferred ?? null, await readPersistedPick(), await readRegistryDefault()]) {
177
+ if (!candidate) continue;
178
+ if (selectors.has(selectorOf(candidate))) return candidate;
179
+ }
180
+ return null;
181
+ }
@@ -34,7 +34,7 @@
34
34
  * see `standby.server.test.ts`.
35
35
  */
36
36
 
37
- import { restartPrewarmedSessions } from '@/server/lib/omp/rpc/session-registry';
37
+ import { restartPrewarmedSessions } from '@/server/lib/omp/rpc/prewarm-pool';
38
38
  import { restartUtilityProcesses } from '@/server/lib/omp/rpc/utility';
39
39
  import { invalidateSkillCache } from '@/server/lib/omp/config/skills';
40
40
  import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
@@ -127,7 +127,13 @@ export async function sendCommand({ params, request }: ActionFunctionArgs) {
127
127
  // Kabmo restart, a second instance, or a CLI-driven session all agree.
128
128
  const persisted = body.modes !== undefined ? parseModeSelection(body as Record<string, unknown>) : await loadPersistedModes(filePath);
129
129
  const modeEnv = kabmoModeEnv({ plan: persisted.plan, goal: persisted.goal });
130
- const { session } = await startRpcSession(sessionId, filePath, cwd, recordedCwd, spawnMode, modeEnv);
130
+ // The model this command ASKS for is the best candidate to RESUME with: a
131
+ // `set_model` carries the operator's own pick, and a session whose
132
+ // recorded model no longer exists needs a replacement that resolves.
133
+ const asked = body.type === 'set_model' && typeof body.provider === 'string' && typeof body.modelId === 'string'
134
+ ? { provider: body.provider, modelId: body.modelId }
135
+ : undefined;
136
+ const { session } = await startRpcSession(sessionId, filePath, cwd, recordedCwd, spawnMode, modeEnv, asked);
131
137
  const result = await session.send(forwarded);
132
138
  // Same Resume nudge as the live path: a resumed goal must not sit idle
133
139
  // waiting for the operator's next message.
@@ -1,6 +1,6 @@
1
1
  import { json } from '@/server/lib/remix-compat';
2
2
  import type { ActionFunctionArgs } from '@/server/lib/remix-compat';
3
- import { prewarmRpcSession } from '@/server/lib/omp/rpc/manager';
3
+ import { prewarmRpcSession } from '@/server/lib/omp/rpc/prewarm-pool';
4
4
  import { isApprovalMode } from '@/shared/lib/omp/config/access-mode';
5
5
  import { loadPersistedAccessMode } from '@/shared/lib/omp/config/access-mode.server';
6
6
  import { rpcErrorResponse } from '@/server/lib/omp/rpc/errors';
@@ -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.' });