@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
@@ -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
  }
@@ -14,6 +14,7 @@ import { pathExists } from '@/server/lib/omp/core/paths';
14
14
  import { kabmoExtensionArgs } from '@/server/lib/omp/extensions/locator';
15
15
  import { ensureTitleModelOverlay, titleModelOverlayPath } from '@/server/lib/omp/session/title-model-overlay.server';
16
16
  import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
17
+ import type { SelectedModel } from '@/shared/types/models';
17
18
 
18
19
  export interface AgentEvent {
19
20
  type: string;
@@ -279,7 +280,11 @@ export async function resolveSpawnCwd(recordedCwd?: string | null): Promise<stri
279
280
  * reaches omp's title generation: the child watches that path, so
280
281
  * `rename-with-ai` rewrites the `tiny` role for the duration of one request.
281
282
  * See `session/title-model-overlay.server.ts`. */
282
- export function buildSessionSpawnArgs(sessionFile: string, approvalMode?: ApprovalMode): string[] {
283
+ export function buildSessionSpawnArgs(
284
+ sessionFile: string,
285
+ approvalMode?: ApprovalMode,
286
+ resumeModel?: SelectedModel,
287
+ ): string[] {
283
288
  const args: string[] = [];
284
289
  ensureTitleModelOverlay();
285
290
  args.push('--config', titleModelOverlayPath());
@@ -289,6 +294,15 @@ export function buildSessionSpawnArgs(sessionFile: string, approvalMode?: Approv
289
294
  // resume/fork prompts.
290
295
  args.push('--resume', sessionFile);
291
296
  }
297
+ // The model the session is RESTORED with. omp restores the model its
298
+ // transcript's last `model_change` names, and it does NOT fall back when
299
+ // that model is no longer in the registry: the child exits(1) with
300
+ // "Could not restore model <provider>/<id>" and every command to the
301
+ // session fails with it. `--model` names a model that DOES resolve, so a
302
+ // session whose recorded model is gone still starts.
303
+ if (resumeModel?.provider && resumeModel.modelId) {
304
+ args.push('--model', `${resumeModel.provider}/${resumeModel.modelId}`);
305
+ }
292
306
  if (approvalMode) {
293
307
  // Spawn-time only: omp exposes no RPC command to change the tool-approval
294
308
  // mode, so the flag is the sole lever. It works with or without --resume.
@@ -346,5 +346,5 @@ export class AgentSessionWrapper {
346
346
  }
347
347
  }
348
348
 
349
- export { getRpcSession, startRpcSession, prewarmRpcSession, startNewRpcSession } from '@/server/lib/omp/rpc/session-registry';
349
+ export { getRpcSession, startRpcSession, startNewRpcSession } from '@/server/lib/omp/rpc/session-registry';
350
350
  export { getSpawnApprovalMode, getSpawnModeEnv, reconcileSpawnApprovalMode } from '@/server/lib/omp/rpc/spawn-provenance';
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The prewarm pool: one idle "new session" spawned ahead of the first prompt
8
+ * so adopting it on send skips the multi-second omp boot.
9
+ *
10
+ * Split out of `session-registry.ts` so that file stays under the repo's
11
+ * per-file size ceiling: the pool is a concern of its own (a cache with its
12
+ * own lifecycle), and the registry is the map of LIVE sessions.
13
+ *
14
+ * Keyed per cwd (the spawn's project directory) with its approval mode and
15
+ * mode selection; consumed exactly once by `startNewRpcSession`.
16
+ */
17
+
18
+ import { RpcProcess } from '@/server/lib/omp/rpc/process';
19
+ import { buildSessionSpawnArgs } from '@/server/lib/omp/rpc/constants';
20
+ import { AgentSessionWrapper } from '@/server/lib/omp/rpc/manager';
21
+ import { recordSpawnProvenance } from '@/server/lib/omp/rpc/spawn-provenance';
22
+ import { DEFAULT_APPROVAL_MODE, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
23
+
24
+ interface PrewarmedEntry {
25
+ cwd: string;
26
+ approvalMode: ApprovalMode;
27
+ /** Mode selection the entry was spawned with; a mismatch makes it unusable. */
28
+ modeEnv?: Record<string, string>;
29
+ /** Resolves when the wrapper is ready, or rejects when the spawn failed or
30
+ * the entry was torn down before being claimed. */
31
+ ready: Promise<AgentSessionWrapper>;
32
+ claimed: boolean;
33
+ }
34
+
35
+ declare global {
36
+ // eslint-disable-next-line no-var
37
+ var __ompPrewarmed: Map<string, PrewarmedEntry> | undefined;
38
+ }
39
+
40
+ export function getPrewarmed(): Map<string, PrewarmedEntry> {
41
+ if (!globalThis.__ompPrewarmed) globalThis.__ompPrewarmed = new Map();
42
+ return globalThis.__ompPrewarmed;
43
+ }
44
+
45
+ /** Spawn (at most one) idle omp process for `cwd` so the next new-session
46
+ * send starts instantly. Fire-and-forget; a failed spawn just clears itself.
47
+ * Safe to call repeatedly — an existing live or in-flight entry wins. */
48
+ export function prewarmRpcSession(cwd: string, approvalMode?: ApprovalMode, modeEnv?: Record<string, string>): void {
49
+ const pool = getPrewarmed();
50
+ const existing = pool.get(cwd);
51
+ if (existing) return;
52
+ const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
53
+ // A pending chat has no mode selection yet, so its prewarmed process is
54
+ // spawned with none — the first send races it and any real selection kills
55
+ // the entry (see `startNewRpcSession`).
56
+ const holder: { wrapper?: AgentSessionWrapper } = {};
57
+ const proc = new RpcProcess({
58
+ cwd,
59
+ extraArgs: buildSessionSpawnArgs('', mode),
60
+ env: modeEnv,
61
+ onExit: ({ stderrTail }) => holder.wrapper?.handleProcessExit(stderrTail),
62
+ });
63
+ const wrapper = new AgentSessionWrapper(proc, cwd);
64
+ recordSpawnProvenance(wrapper, mode, modeEnv);
65
+ holder.wrapper = wrapper;
66
+ wrapper.start();
67
+ const ready = wrapper
68
+ .waitUntilReady()
69
+ .then(() => {
70
+ // A dead wrapper (idle-kill, crash, exit) must not be handed out.
71
+ if (!wrapper.isAlive()) throw new Error('prewarmed process exited');
72
+ return wrapper;
73
+ })
74
+ .catch((error) => {
75
+ void wrapper.destroyAndWait();
76
+ const entry = pool.get(cwd);
77
+ if (entry?.ready === ready) pool.delete(cwd);
78
+ throw error;
79
+ });
80
+ pool.set(cwd, { cwd, approvalMode: mode, modeEnv, ready, claimed: false });
81
+ }
82
+
83
+ /**
84
+ * Recycle every UNCLAIMED prewarmed process.
85
+ *
86
+ * A prewarmed child is a full session host that has no session yet, spawned
87
+ * from whatever binary was current when the user opened a pending chat. After
88
+ * `omp update` it is a stale build waiting to be adopted by the next send, so
89
+ * the recycle happens here rather than being left to the idle timer.
90
+ *
91
+ * Safe because there is nothing to lose: an unclaimed entry owns no session and
92
+ * no turn. An entry a send is already adopting is left alone — the claim is a
93
+ * synchronous check-and-set (`startNewRpcSession`), so an entry is either taken
94
+ * before this pass reads it or taken after this pass removed it, never both.
95
+ * A wrapper still booting is destroyed through `destroyAndWait`, which is also
96
+ * the error path the prewarm itself would have taken.
97
+ */
98
+ export async function restartPrewarmedSessions(): Promise<number> {
99
+ const pool = getPrewarmed();
100
+ if (pool.size === 0) return 0;
101
+ const doomed: PrewarmedEntry[] = [];
102
+ for (const [cwd, entry] of pool) {
103
+ if (entry.claimed) continue;
104
+ entry.claimed = true;
105
+ pool.delete(cwd);
106
+ doomed.push(entry);
107
+ }
108
+ await Promise.all(doomed.map(async (entry) => {
109
+ try {
110
+ const wrapper = await entry.ready;
111
+ await wrapper.destroyAndWait();
112
+ } catch {
113
+ // A spawn that failed already tore its own wrapper down; nothing to do.
114
+ }
115
+ }));
116
+ return doomed.length;
117
+ }
118
+
119
+ /**
120
+ * Take the prewarmed process for `cwd` when it can serve the request.
121
+ *
122
+ * Returns the wrapper, or null when there is none to take: no entry, an entry
123
+ * whose approval mode or mode selection differs from the request's, or an
124
+ * entry that died before it was claimed. The mismatching entry is destroyed —
125
+ * it cannot serve this request — and the caller spawns cold.
126
+ */
127
+ export async function claimPrewarmedSession(
128
+ cwd: string,
129
+ approvalMode: ApprovalMode,
130
+ modeEnv?: Record<string, string>,
131
+ ): Promise<AgentSessionWrapper | null> {
132
+ const pool = getPrewarmed();
133
+ const entry = pool.get(cwd);
134
+ if (!entry) return null;
135
+
136
+ // A prewarmed entry was spawned with the environment current at prewarm
137
+ // time, so a MODE selection that differs from its own can no longer be served
138
+ // by it — the extension reads the mode env once, at session start. Treated
139
+ // exactly like a mode mismatch: claim and kill, then spawn cold.
140
+ const entryModes = entry.modeEnv?.KABMO_MODES ?? entry.modeEnv?.CHAMBER_MODES ?? '';
141
+ const wantedModes = modeEnv?.KABMO_MODES ?? modeEnv?.CHAMBER_MODES ?? '';
142
+ const usable = !entry.claimed && entry.approvalMode === approvalMode && entryModes === wantedModes;
143
+
144
+ if (usable) {
145
+ entry.claimed = true;
146
+ pool.delete(cwd);
147
+ try {
148
+ const candidate = await entry.ready;
149
+ // Died between readiness and claim (idle kill, crash) → cold spawn.
150
+ if (candidate.isAlive()) return candidate;
151
+ await candidate.destroyAndWait();
152
+ } catch {
153
+ // fall through to a cold spawn
154
+ }
155
+ return null;
156
+ }
157
+
158
+ if (entry.claimed) return null;
159
+ // Wrong approval mode, or a different session-mode selection: the prewarmed
160
+ // process cannot serve this request. Kill it and spawn cold —
161
+ // reconcileSpawnApprovalMode would refuse (no session file).
162
+ entry.claimed = true;
163
+ pool.delete(cwd);
164
+ void entry.ready.then((w) => w.destroyAndWait()).catch(() => {});
165
+ return null;
166
+ }
@@ -20,7 +20,10 @@ import { localRuns } from '@/server/lib/omp/session/local-runs.server';
20
20
  import { recordSpawnProvenance } from '@/server/lib/omp/rpc/spawn-provenance';
21
21
  import { registerSpawnedSession } from '@/server/lib/omp/rpc/session-registration';
22
22
  import { resolveSessionOwnership, SessionOwnedElsewhereError } from '@/server/lib/omp/session/ownership.server';
23
+ import { claimPrewarmedSession } from '@/server/lib/omp/rpc/prewarm-pool';
24
+ import { isUnrestorableModelFailure, resolveResumableModel } from '@/server/lib/omp/session/resumable-model.server';
23
25
  import { DEFAULT_APPROVAL_MODE, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
26
+ import type { SelectedModel } from '@/shared/types/models';
24
27
 
25
28
  export { getSpawnApprovalMode, getSpawnModeEnv, reconcileSpawnApprovalMode } from '@/server/lib/omp/rpc/spawn-provenance';
26
29
 
@@ -111,6 +114,7 @@ export async function startRpcSession(
111
114
  recordedCwd?: string | null,
112
115
  approvalMode?: ApprovalMode,
113
116
  modeEnv?: Record<string, string>,
117
+ resumeModel?: SelectedModel,
114
118
  ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {
115
119
  const registry = getRegistry();
116
120
  const locks = getLocks();
@@ -137,156 +141,95 @@ export async function startRpcSession(
137
141
  const inflight = locks.get(sessionId);
138
142
  if (inflight) return inflight;
139
143
 
140
- const starting = (async () => {
141
- const holder: { wrapper?: AgentSessionWrapper } = {};
142
- const proc = new RpcProcess({
143
- cwd,
144
- extraArgs: buildSessionSpawnArgs(sessionFile, approvalMode),
145
- env: modeEnv,
146
- onExit: ({ stderrTail }) => holder.wrapper?.handleProcessExit(stderrTail),
147
- });
148
- const created = new AgentSessionWrapper(proc, cwd, recordedCwd);
149
- recordSpawnProvenance(created, approvalMode, modeEnv);
150
- holder.wrapper = created;
151
- created.start();
152
- try {
153
- await created.waitUntilReady();
154
- } catch (error) {
155
- await created.destroyAndWait();
156
- throw error;
157
- }
158
-
159
- const realSessionId = created.sessionId;
160
- registerSpawnedSession(registry, created, sessionId, realSessionId);
161
- // A session's cwd may sit outside every registered workspace, and omp
162
- // resolves project skills from it all the same — so the discovery watcher
163
- // has to learn this directory. AWAITED, not fired and forgotten: the
164
- // reconcile attaches its watchers asynchronously, and a caller that wrote a
165
- // skill the moment the spawn returned would land it in the gap before the
166
- // watch existed (measured: the write was missed on a fast follow-up and
167
- // picked up once the attach had settled).
168
- await syncDiscoveryRootsWatch();
169
- // A `session:<id>` topic subscribed before this spawn had no child to bind
170
- // to, so it published nothing and its subscribers hold a `running:false`
171
- // snapshot. The child exists now: tell the realtime layer to re-snapshot
172
- // that topic for whoever is watching.
173
- emitRealtimeSignal('session-attached', realSessionId);
174
- // A forked resume answers a NEW id, and the client is still subscribed (and
175
- // still posting) under the id it asked for. Publishing only the real id
176
- // leaves that subscriber attached to a topic whose `getRpcSession` now
177
- // resolves — through the alias `registerSpawnedSession` installs — while
178
- // nothing ever told it to re-snapshot, so a reload-less tab would keep the
179
- // pre-spawn snapshot.
180
- if (sessionId !== realSessionId) emitRealtimeSignal('session-attached', sessionId);
181
- return { session: created, realSessionId };
182
- })().finally(() => locks.delete(sessionId));
144
+ const starting = spawnOnce(sessionId, sessionFile, cwd, recordedCwd, approvalMode, modeEnv)
145
+ .catch(async (error) => {
146
+ // omp restores the model the session's transcript records, and it does
147
+ // NOT fall back when that model is gone: the child exits(1) with
148
+ // "Could not restore model <provider>/<id>" and EVERY command to the
149
+ // session fails with it. Measured on omp 18.13.1 — a session whose last
150
+ // model_change named a provider that is no longer in the registry could
151
+ // not receive a prompt at all.
152
+ //
153
+ // The recovery respawns it with a model omp CAN resolve. The command
154
+ // that triggered this spawn then runs against the new child, so the
155
+ // user's own `set_model` still lands on it.
156
+ //
157
+ // The first attempt is deliberately left UNCHANGED (no `--model`): a
158
+ // caller's pick can itself be stale — the picker's list is a 60 s
159
+ // snapshot — and naming it up front made a healthy session unopenable
160
+ // ("Model <x> not found"). It is only a CANDIDATE here, and one that has
161
+ // to survive the resolvability check.
162
+ if (!isUnrestorableModelFailure(error)) throw error;
163
+ const replacement = await resolveResumableModel(resumeModel);
164
+ if (!replacement) throw error;
165
+ return spawnOnce(sessionId, sessionFile, cwd, recordedCwd, approvalMode, modeEnv, replacement);
166
+ })
167
+ .finally(() => locks.delete(sessionId));
183
168
 
184
169
  locks.set(sessionId, starting);
185
170
  return starting;
186
171
  }
187
172
 
188
- // ============================================================================
189
- // Prewarm pool: one idle "new session" spawned ahead of the first prompt so
190
- // adopting it on send skips the multi-second omp boot. Keyed per cwd (the
191
- // spawn's project directory) with its approval mode; consumed exactly once by
192
- // startNewRpcSession.
193
- // ============================================================================
194
-
195
- interface PrewarmedEntry {
196
- cwd: string;
197
- approvalMode: ApprovalMode;
198
- /** Mode selection the entry was spawned with; a mismatch makes it unusable. */
199
- modeEnv?: Record<string, string>;
200
- /** Resolves when the wrapper is ready, or rejects when the spawn failed or
201
- * the entry was torn down before being claimed. */
202
- ready: Promise<AgentSessionWrapper>;
203
- claimed: boolean;
204
- }
205
-
206
- declare global {
207
- // eslint-disable-next-line no-var
208
- var __ompPrewarmed: Map<string, PrewarmedEntry> | undefined;
209
- }
210
-
211
- function getPrewarmed(): Map<string, PrewarmedEntry> {
212
- if (!globalThis.__ompPrewarmed) globalThis.__ompPrewarmed = new Map();
213
- return globalThis.__ompPrewarmed;
214
- }
215
-
216
- /** Spawn (at most one) idle omp process for `cwd` so the next new-session
217
- * send starts instantly. Fire-and-forget; a failed spawn just clears itself.
218
- * Safe to call repeatedly — an existing live or in-flight entry wins. */
219
- export function prewarmRpcSession(cwd: string, approvalMode?: ApprovalMode, modeEnv?: Record<string, string>): void {
220
- const pool = getPrewarmed();
221
- const existing = pool.get(cwd);
222
- if (existing) return;
223
- const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
224
- // A pending chat has no mode selection yet, so its prewarmed process is
225
- // spawned with none — the first send races it and any real selection kills
226
- // the entry (see `startNewRpcSession`).
173
+ /** One spawn attempt: build the child, wait for it to be ready, register it. */
174
+ async function spawnOnce(
175
+ sessionId: string,
176
+ sessionFile: string,
177
+ cwd: string,
178
+ recordedCwd: string | null | undefined,
179
+ approvalMode: ApprovalMode | undefined,
180
+ modeEnv: Record<string, string> | undefined,
181
+ resumeModel?: SelectedModel | undefined,
182
+ ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {
183
+ const registry = getRegistry();
227
184
  const holder: { wrapper?: AgentSessionWrapper } = {};
228
185
  const proc = new RpcProcess({
229
186
  cwd,
230
- extraArgs: buildSessionSpawnArgs('', mode),
187
+ extraArgs: buildSessionSpawnArgs(sessionFile, approvalMode, resumeModel),
231
188
  env: modeEnv,
232
189
  onExit: ({ stderrTail }) => holder.wrapper?.handleProcessExit(stderrTail),
233
190
  });
234
- const wrapper = new AgentSessionWrapper(proc, cwd);
235
- recordSpawnProvenance(wrapper, mode, modeEnv);
236
- holder.wrapper = wrapper;
237
- wrapper.start();
238
- const ready = wrapper
239
- .waitUntilReady()
240
- .then(() => {
241
- // A dead wrapper (idle-kill, crash, exit) must not be handed out.
242
- if (!wrapper.isAlive()) throw new Error('prewarmed process exited');
243
- return wrapper;
244
- })
245
- .catch((error) => {
246
- void wrapper.destroyAndWait();
247
- const entry = pool.get(cwd);
248
- if (entry?.ready === ready) pool.delete(cwd);
249
- throw error;
250
- });
251
- pool.set(cwd, { cwd, approvalMode: mode, modeEnv, ready, claimed: false });
252
- }
253
-
254
- /**
255
- * Recycle every UNCLAIMED prewarmed process.
256
- *
257
- * A prewarmed child is a full session host that has no session yet, spawned
258
- * from whatever binary was current when the user opened a pending chat. After
259
- * `omp update` it is a stale build waiting to be adopted by the next send, so
260
- * the recycle happens here rather than being left to the idle timer.
261
- *
262
- * Safe because there is nothing to lose: an unclaimed entry owns no session and
263
- * no turn. An entry a send is already adopting is left alone — the claim is a
264
- * synchronous check-and-set (`startNewRpcSession`), so an entry is either taken
265
- * before this pass reads it or taken after this pass removed it, never both.
266
- * A wrapper still booting is destroyed through `destroyAndWait`, which is also
267
- * the error path the prewarm itself would have taken.
268
- */
269
- export async function restartPrewarmedSessions(): Promise<number> {
270
- const pool = getPrewarmed();
271
- if (pool.size === 0) return 0;
272
- const doomed: PrewarmedEntry[] = [];
273
- for (const [cwd, entry] of pool) {
274
- if (entry.claimed) continue;
275
- entry.claimed = true;
276
- pool.delete(cwd);
277
- doomed.push(entry);
191
+ const created = new AgentSessionWrapper(proc, cwd, recordedCwd);
192
+ recordSpawnProvenance(created, approvalMode, modeEnv);
193
+ holder.wrapper = created;
194
+ created.start();
195
+ try {
196
+ await created.waitUntilReady();
197
+ } catch (error) {
198
+ await created.destroyAndWait();
199
+ throw error;
278
200
  }
279
- await Promise.all(doomed.map(async (entry) => {
280
- try {
281
- const wrapper = await entry.ready;
282
- await wrapper.destroyAndWait();
283
- } catch {
284
- // A spawn that failed already tore its own wrapper down; nothing to do.
285
- }
286
- }));
287
- return doomed.length;
201
+
202
+ const realSessionId = created.sessionId;
203
+ registerSpawnedSession(registry, created, sessionId, realSessionId);
204
+ // A session's cwd may sit outside every registered workspace, and omp
205
+ // resolves project skills from it all the same — so the discovery watcher
206
+ // has to learn this directory. AWAITED, not fired and forgotten: the
207
+ // reconcile attaches its watchers asynchronously, and a caller that wrote a
208
+ // skill the moment the spawn returned would land it in the gap before the
209
+ // watch existed (measured: the write was missed on a fast follow-up and
210
+ // picked up once the attach had settled).
211
+ await syncDiscoveryRootsWatch();
212
+ // A `session:<id>` topic subscribed before this spawn had no child to bind
213
+ // to, so it published nothing and its subscribers hold a `running:false`
214
+ // snapshot. The child exists now: tell the realtime layer to re-snapshot
215
+ // that topic for whoever is watching.
216
+ emitRealtimeSignal('session-attached', realSessionId);
217
+ // A forked resume answers a NEW id, and the client is still subscribed (and
218
+ // still posting) under the id it asked for. Publishing only the real id
219
+ // leaves that subscriber attached to a topic whose `getRpcSession` now
220
+ // resolves — through the alias `registerSpawnedSession` installs — while
221
+ // nothing ever told it to re-snapshot, so a reload-less tab would keep the
222
+ // pre-spawn snapshot.
223
+ if (sessionId !== realSessionId) emitRealtimeSignal('session-attached', sessionId);
224
+ return { session: created, realSessionId };
288
225
  }
289
226
 
227
+ // ============================================================================
228
+ // The prewarm pool (one idle "new session" spawned ahead of the first prompt)
229
+ // lives in `prewarm-pool.ts`: it is a cache with its own lifecycle, not part
230
+ // of the live-session map below.
231
+ // ============================================================================
232
+
290
233
  /** Consume the prewarmed process for `cwd` when its approval mode matches, or
291
234
  * spawn a fresh session. The returned wrapper is already registered under its
292
235
  * real session id, mirroring startRpcSession's bookkeeping. */
@@ -295,35 +238,8 @@ export async function startNewRpcSession(
295
238
  approvalMode?: ApprovalMode,
296
239
  modeEnv?: Record<string, string>,
297
240
  ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {
298
- const pool = getPrewarmed();
299
- const entry = pool.get(cwd);
300
241
  const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
301
- let wrapper: AgentSessionWrapper | undefined;
302
- // A prewarmed entry was spawned with the environment current at prewarm
303
- // time, so a MODE selection that differs from its own can no longer be served
304
- // by it — the extension reads the mode env once, at session start. Treated
305
- // exactly like a mode mismatch: claim and kill, then spawn cold.
306
- const entryModes = entry?.modeEnv?.KABMO_MODES ?? entry?.modeEnv?.CHAMBER_MODES ?? '';
307
- const wantedModes = modeEnv?.KABMO_MODES ?? modeEnv?.CHAMBER_MODES ?? '';
308
- if (entry && !entry.claimed && entry.approvalMode === mode && entryModes === wantedModes) {
309
- entry.claimed = true;
310
- pool.delete(cwd);
311
- try {
312
- const candidate = await entry.ready;
313
- // Died between readiness and claim (idle kill, crash) → cold spawn.
314
- if (candidate.isAlive()) wrapper = candidate;
315
- else await candidate.destroyAndWait();
316
- } catch {
317
- wrapper = undefined; // fall through to a cold spawn
318
- }
319
- } else if (entry && !entry.claimed) {
320
- // Wrong approval mode, or a different session-mode selection: the prewarmed
321
- // process cannot serve this request. Kill it and spawn cold —
322
- // reconcileSpawnApprovalMode would refuse (no session file).
323
- entry.claimed = true;
324
- pool.delete(cwd);
325
- void entry.ready.then((w) => w.destroyAndWait()).catch(() => {});
326
- }
242
+ const wrapper = await claimPrewarmedSession(cwd, mode, modeEnv);
327
243
 
328
244
  if (!wrapper) {
329
245
  return startRpcSession(`__new__${Bun.randomUUIDv7()}`, '', cwd, undefined, mode, modeEnv);
@@ -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
+ });