@kabmo-labs/kabmo 0.23.0 → 0.24.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 (151) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +679 -679
  3. package/dist/client/static/js/{index-ph0q59rs.js → index-jcr5twtp.js} +769 -767
  4. package/dist/client/static/js/index-z3w7n85q.css +1 -0
  5. package/package.json +1 -1
  6. package/src/client/components/common/Modal.tsx +2 -6
  7. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
  8. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
  9. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +23 -7
  10. package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
  11. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +27 -11
  12. package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
  13. package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
  14. package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
  15. package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
  16. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
  17. package/src/client/components/workspace/chat-timeline/index.tsx +2 -1
  18. package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
  19. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
  20. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
  21. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
  22. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
  23. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
  24. package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
  25. package/src/client/components/workspace/file-explorer/index.tsx +9 -3
  26. package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
  27. package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
  28. package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
  29. package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
  30. package/src/client/data/settings/omp-schema.json +4 -4
  31. package/src/client/hooks/chat/timeline/actions.ts +2 -2
  32. package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
  33. package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
  34. package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
  35. package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
  36. package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
  37. package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
  38. package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
  39. package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
  40. package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
  41. package/src/client/hooks/chat/timeline/send-execute.test.ts +17 -0
  42. package/src/client/hooks/chat/timeline/send-props.ts +5 -3
  43. package/src/client/hooks/chat/timeline/send-steer.test.ts +1 -3
  44. package/src/client/hooks/chat/timeline/send.test-util.ts +1 -1
  45. package/src/client/hooks/chat/timeline/send.test.ts +1 -3
  46. package/src/client/hooks/chat/timeline/send.ts +8 -3
  47. package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
  48. package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
  49. package/src/client/hooks/chat/timeline/session-load.ts +6 -14
  50. package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
  51. package/src/client/hooks/models/harness-catalog.ts +114 -0
  52. package/src/client/hooks/models/provider-writes.test.ts +81 -0
  53. package/src/client/hooks/models/provider-writes.ts +10 -3
  54. package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
  55. package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
  56. package/src/client/hooks/models/use-harnesses.test.ts +2 -1
  57. package/src/client/hooks/models/use-harnesses.ts +48 -114
  58. package/src/client/tailwind.css +9 -1
  59. package/src/server/lib/harness/acp/activation.test.ts +81 -0
  60. package/src/server/lib/harness/acp/activation.ts +72 -0
  61. package/src/server/lib/harness/acp/frames.test.ts +50 -1
  62. package/src/server/lib/harness/acp/frames.ts +17 -5
  63. package/src/server/lib/harness/acp/mapper.ts +6 -4
  64. package/src/server/lib/harness/acp/session-config.test.ts +73 -0
  65. package/src/server/lib/harness/acp/session-config.ts +87 -6
  66. package/src/server/lib/harness/acp/session-handshake.ts +9 -2
  67. package/src/server/lib/harness/acp/session-idle.ts +51 -0
  68. package/src/server/lib/harness/acp/session-notifications.ts +19 -3
  69. package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
  70. package/src/server/lib/harness/acp/session-options.ts +33 -0
  71. package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
  72. package/src/server/lib/harness/acp/session.test-util.ts +31 -2
  73. package/src/server/lib/harness/acp/session.test.ts +65 -3
  74. package/src/server/lib/harness/acp/session.ts +20 -20
  75. package/src/server/lib/harness/acp/turn.ts +31 -7
  76. package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
  77. package/src/server/lib/harness/auto-probe.server.ts +178 -0
  78. package/src/server/lib/harness/config.server.test.ts +1 -1
  79. package/src/server/lib/harness/config.server.ts +1 -1
  80. package/src/server/lib/harness/launch-table.ts +195 -0
  81. package/src/server/lib/harness/launch.test.ts +37 -0
  82. package/src/server/lib/harness/launch.ts +13 -115
  83. package/src/server/lib/harness/provider-entry.ts +32 -0
  84. package/src/server/lib/harness/provider-file.server.ts +3 -0
  85. package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
  86. package/src/server/lib/harness/provider-sources.server.ts +26 -2
  87. package/src/server/lib/harness/provider-write.server.ts +21 -32
  88. package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
  89. package/src/server/lib/harness/provider-zcode.server.ts +324 -0
  90. package/src/server/lib/harness/update-state.server.ts +15 -20
  91. package/src/server/lib/lifecycle/after-listen.ts +7 -0
  92. package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
  93. package/src/server/lib/models/registry-refresh.server.ts +98 -0
  94. package/src/server/lib/omp/rpc/child-config.ts +5 -4
  95. package/src/server/lib/omp/rpc/constants.test.ts +2 -1
  96. package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
  97. package/src/server/lib/omp/session/delete-flow.server.ts +15 -8
  98. package/src/server/lib/omp/session/delete.server.ts +12 -0
  99. package/src/server/routes/chat/rewind.test.ts +147 -0
  100. package/src/server/routes/chat/rewind.ts +29 -7
  101. package/src/server/routes/chat/session.test.ts +165 -10
  102. package/src/server/routes/chat/session.ts +60 -7
  103. package/src/server/routes/harness/import-action.ts +18 -4
  104. package/src/server/routes/harness/root.ts +8 -49
  105. package/src/server/routes/harness/toggle.test.ts +20 -0
  106. package/src/server/routes/harness/update.ts +49 -7
  107. package/src/server/routes/harness/versions.ts +5 -1
  108. package/src/server/routes/sessions/delete-acp.test.ts +227 -0
  109. package/src/server/routes/settings/model-override.ts +5 -2
  110. package/src/server/routes/settings/provider-entry.ts +2 -2
  111. package/src/server/routes/settings/provider-model.ts +2 -2
  112. package/src/server/routes/settings/provider-models.ts +2 -2
  113. package/src/server/routes/settings/provider-refresh.ts +6 -4
  114. package/src/server/routes/settings/providers.ts +3 -1
  115. package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
  116. package/src/shared/lib/chat/ask-form/fields.ts +76 -0
  117. package/src/shared/lib/chat/ask-form/index.ts +323 -0
  118. package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
  119. package/src/shared/lib/chat/ask-form/types.ts +43 -0
  120. package/src/shared/lib/chat/ask-form.test.ts +137 -0
  121. package/src/shared/lib/chat/ask-questions.test.ts +65 -1
  122. package/src/shared/lib/chat/ask-questions.ts +51 -145
  123. package/src/shared/lib/chat/ask-results.ts +198 -0
  124. package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
  125. package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
  126. package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
  127. package/src/shared/lib/harness/catalog.test.ts +1 -1
  128. package/src/shared/lib/harness/config-fields.test.ts +4 -0
  129. package/src/shared/lib/harness/config-fields.ts +19 -4
  130. package/src/shared/lib/harness/dialects.test.ts +8 -0
  131. package/src/shared/lib/harness/dialects.ts +12 -0
  132. package/src/shared/lib/harness/provider-facts.test.ts +32 -8
  133. package/src/shared/lib/harness/provider-facts.ts +46 -11
  134. package/src/shared/lib/harness/providers.ts +9 -0
  135. package/src/shared/lib/harness/rewind.ts +24 -0
  136. package/src/shared/lib/harness/update-plan.test.ts +51 -1
  137. package/src/shared/lib/harness/update-plan.ts +47 -7
  138. package/src/shared/lib/harness/updates.test.ts +22 -0
  139. package/src/shared/lib/harness/updates.ts +24 -1
  140. package/src/shared/lib/models/client.ts +10 -1
  141. package/src/shared/lib/omp/dialog-methods.ts +4 -3
  142. package/src/shared/lib/theme/css.ts +2 -0
  143. package/src/shared/lib/theme/ink-scale.ts +21 -1
  144. package/src/shared/lib/theme/theme.test.ts +25 -9
  145. package/src/shared/lib/ui/safe-area.test.ts +28 -0
  146. package/src/shared/lib/ui/safe-area.ts +42 -0
  147. package/src/shared/types/harness.ts +30 -4
  148. package/src/test-support/file-explorer-render.test-util.ts +37 -0
  149. package/src/test-support/file-explorer.test-util.ts +20 -18
  150. package/src/test-support/harness-table.test-util.ts +6 -3
  151. package/dist/client/static/js/index-jhmg4w91.css +0 -1
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A registry write is only visible to the readers that re-open the file, so the
8
+ * refresh has an ORDER: recycle the pooled omp children, forget the probes that
9
+ * measured the old file, re-probe when asked, and invalidate Kabmo's caches LAST
10
+ * — invalidating first would let the `models` topic resolve from the pre-write
11
+ * pool and cache that answer for another minute.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+
16
+ import {
17
+ refreshModelRegistryAfterWrite,
18
+ type RegistryRefreshDeps,
19
+ } from '@/server/lib/models/registry-refresh.server';
20
+
21
+ /** Record every side effect in the order it happened. */
22
+ function recorder(sharing: string[] = ['omp-acp']) {
23
+ const steps: string[] = [];
24
+ const deps: RegistryRefreshDeps = {
25
+ restartUtilities: async () => { steps.push('restart'); },
26
+ registryPath: async () => '/home/me/.omp/models.yml',
27
+ sharing: (path) => {
28
+ steps.push(`sharing:${path}`);
29
+ return sharing as never;
30
+ },
31
+ forget: async (id) => { steps.push(`forget:${id}`); },
32
+ reprobe: async (ids, cwd) => { steps.push(`reprobe:${ids.join(',')}:${cwd}`); },
33
+ invalidate: () => { steps.push('invalidate'); },
34
+ };
35
+ return { steps, deps };
36
+ }
37
+
38
+ describe('refreshModelRegistryAfterWrite', () => {
39
+ test('recycles the pool, forgets the probes, and invalidates LAST', async () => {
40
+ const { steps, deps } = recorder();
41
+
42
+ const sharing = await refreshModelRegistryAfterWrite({}, deps);
43
+
44
+ expect(sharing).toEqual(['omp-acp'] as never);
45
+ expect(steps).toEqual([
46
+ 'restart',
47
+ 'sharing:/home/me/.omp/models.yml',
48
+ 'forget:omp-acp',
49
+ 'invalidate',
50
+ ]);
51
+ });
52
+
53
+ test('a re-probe runs on the shared harnesses, with the caller scope, before the caches drop', async () => {
54
+ const { steps, deps } = recorder(['omp-rpc', 'omp-acp']);
55
+
56
+ await refreshModelRegistryAfterWrite({ path: '/w/models.yml', reprobe: true, cwd: '/w' }, deps);
57
+
58
+ expect(steps).toEqual([
59
+ 'restart',
60
+ 'sharing:/w/models.yml',
61
+ 'forget:omp-rpc',
62
+ 'forget:omp-acp',
63
+ 'reprobe:omp-rpc,omp-acp:/w',
64
+ 'invalidate',
65
+ ]);
66
+ });
67
+
68
+ test('a write that cannot change a probe still recycles and invalidates', async () => {
69
+ const { steps, deps } = recorder();
70
+
71
+ const sharing = await refreshModelRegistryAfterWrite({ probes: false }, deps);
72
+
73
+ expect(sharing).toEqual([]);
74
+ expect(steps).toEqual(['restart', 'invalidate']);
75
+ });
76
+
77
+ test('the restart lands before any cache is dropped, even when it throws', async () => {
78
+ const { steps, deps } = recorder();
79
+ deps.restartUtilities = async () => {
80
+ steps.push('restart');
81
+ throw new Error('omp is missing');
82
+ };
83
+
84
+ await expect(refreshModelRegistryAfterWrite({}, deps)).rejects.toThrow('omp is missing');
85
+ expect(steps).toEqual(['restart']);
86
+ });
87
+ });
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Refresh every reader of a registry file AFTER a write to it.
8
+ *
9
+ * A `models.yml` write is invisible to the pooled `omp` utility child: the child
10
+ * loads the file when it is SPAWNED, and `get_available_models` only awaits an
11
+ * in-flight background refresh — it does not compare the file's mtime. So
12
+ * dropping Kabmo's cache alone left `/api/models` re-reading the OLD registry
13
+ * from that child, which is why adding a provider only showed up after omp was
14
+ * restarted. Recycling the pool makes the next read start from the current file.
15
+ *
16
+ * The harness probes have the same problem from the other side: an ACP transport
17
+ * reads the same file at spawn, so a probe recorded before the write describes a
18
+ * registry that no longer exists. Those records are dropped, and the launchable
19
+ * transports are re-probed when `reprobe` is set, so a picker that reads the
20
+ * cache sees the new provider without an extra "check status" round.
21
+ *
22
+ * The caches are dropped LAST: the `models` topic resolver reads through
23
+ * `loadModelsWithCache`, and publishing before the pool was recycled would cache
24
+ * the pre-write answer for another 60s.
25
+ */
26
+
27
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
28
+ import { restartUtilityProcesses } from '@/server/lib/omp/rpc/utility';
29
+ import { getModelsConfigPath } from '@/server/lib/omp/config/models-config';
30
+ import { forgetProbe } from '@/server/lib/harness/probe-cache.server';
31
+ import { runAutoProbe } from '@/server/lib/harness/auto-probe.server';
32
+ import { harnessesSharingRegistry } from '@/server/lib/harness/provider-sources.server';
33
+ import { invalidateModelsCaches } from '@/shared/lib/models/server-cache';
34
+
35
+ export interface RegistryWriteRefreshOptions {
36
+ /**
37
+ * The registry file that was written. Defaults to the omp `models.yml` path,
38
+ * which is what every settings route writes.
39
+ */
40
+ path?: string;
41
+ /** Workspace scope for a re-probe; defaults to the server's cwd. */
42
+ cwd?: string;
43
+ /**
44
+ * Drop stored probes for the harnesses that read this file. Set false for a
45
+ * write that cannot change what an agent lists (a per-model override), where
46
+ * dropping the answer would only hide a still-valid model list.
47
+ */
48
+ probes?: boolean;
49
+ /** Re-probe the launchable harnesses after dropping their records. */
50
+ reprobe?: boolean;
51
+ }
52
+
53
+ /** The side effects the refresh drives, injected so a test can watch the ORDER. */
54
+ export interface RegistryRefreshDeps {
55
+ restartUtilities: () => Promise<unknown>;
56
+ registryPath: () => Promise<string>;
57
+ sharing: (path: string) => HarnessId[];
58
+ forget: (id: HarnessId) => Promise<void>;
59
+ reprobe: (ids: readonly HarnessId[], cwd: string) => Promise<unknown>;
60
+ invalidate: () => void;
61
+ }
62
+
63
+ const defaults: RegistryRefreshDeps = {
64
+ restartUtilities: restartUtilityProcesses,
65
+ registryPath: getModelsConfigPath,
66
+ sharing: harnessesSharingRegistry,
67
+ forget: forgetProbe,
68
+ reprobe: (ids, cwd) => runAutoProbe({ ids, cwd }),
69
+ invalidate: invalidateModelsCaches,
70
+ };
71
+
72
+ /**
73
+ * Recycle the pooled omp readers, forget the probes that measured the old file,
74
+ * and republish the model catalog once the fresh state is in place.
75
+ *
76
+ * Returns the harness ids that read the written file, so a caller can tell the
77
+ * browser which tabs need their own probe.
78
+ */
79
+ export async function refreshModelRegistryAfterWrite(
80
+ options: RegistryWriteRefreshOptions = {},
81
+ deps: RegistryRefreshDeps = defaults,
82
+ ): Promise<HarnessId[]> {
83
+ await deps.restartUtilities();
84
+
85
+ const sharing = options.probes === false
86
+ ? []
87
+ : deps.sharing(options.path ?? (await deps.registryPath()));
88
+
89
+ if (options.probes !== false) {
90
+ for (const id of sharing) await deps.forget(id);
91
+ if (options.reprobe) {
92
+ await deps.reprobe(sharing, options.cwd ?? process.cwd());
93
+ }
94
+ }
95
+
96
+ deps.invalidate();
97
+ return sharing;
98
+ }
@@ -39,10 +39,11 @@ export async function configureChild(proc: RpcProcess): Promise<void> {
39
39
  // Full accumulated `message_update` frames (see the module doc): the streaming
40
40
  // tool call's name/id live on the seed block, which delta mode drops.
41
41
  await proc.sendCommand({ type: 'set_event_filter', events: null, messageUpdates: 'full' }).catch(() => {});
42
- // Grouped `ask` dialogs: every question of one `ask` tool call in a SINGLE
42
+ // Grouped `ask` dialogs: every question of one ask in a SINGLE
43
43
  // `extension_ui_request` (`method:"ask"`, with `multi`/`recommended`), answered
44
- // by one `answers` response. Without this omp loops one `select` per question,
45
- // which is what the ask card's per-question bookkeeping exists to reassemble.
46
- // Verified on 18.8.3: two questions (one `multi`) arrived in one request.
44
+ // by one `answers` response. omp 18.18.3 no longer routes its OWN `ask` tool
45
+ // through this (the tool takes an HTML form now and the RPC host walks its
46
+ // fields one dialog at a time), but extensions and the ratchet still use the
47
+ // grouped dialog, and an older child still takes this path for the tool.
47
48
  await proc.sendCommand({ type: 'set_ask_dialog', enabled: true }).catch(() => {});
48
49
  }
@@ -119,7 +119,8 @@ describe('command classification sets', () => {
119
119
  test('image-bearing commands and answerable UI methods', () => {
120
120
  expect([...IMAGE_BEARING_COMMANDS].sort()).toEqual(['abort_and_prompt', 'follow_up', 'prompt', 'steer']);
121
121
  // `ask` is the grouped dialog `configureChild` opts into with
122
- // `set_ask_dialog`: omp parks the tool call on it exactly as it does on a
122
+ // `set_ask_dialog` (extensions and the ratchet; omp's own tool moved to an
123
+ // HTML form in 18.18.3): the agent parks on it exactly as it does on a
123
124
  // `select`, so a list without it leaves the frame unremembered and the
124
125
  // question unanswerable after a reload.
125
126
  expect(Object.keys(ANSWERABLE_UI_METHODS).sort()).toEqual(['ask', 'confirm', 'editor', 'input', 'select']);
@@ -32,6 +32,7 @@ import { describePosix } from '@/test-support/platform';
32
32
  import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
33
33
  import { stopDiscoveryRootsWatch } from '@/server/lib/omp/config/roots-watch.server';
34
34
  import { getRpcSession, startRpcSession } from '@/server/lib/omp/rpc/session-registry';
35
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
35
36
 
36
37
  /** One line per spawned child, written by the scripted omp. */
37
38
  interface ForkRecord {
@@ -53,12 +54,19 @@ const ENV_KEYS = [
53
54
  'FAKE_OMP_FORK_LOG',
54
55
  ] as const;
55
56
 
56
- beforeEach(() => {
57
+ beforeEach(async () => {
57
58
  root = mkdtempSync(join(tmpdir(), 'omp-fork-test-'));
58
59
  saved = Object.fromEntries(ENV_KEYS.map((key) => [key, Bun.env[key]]));
60
+ // The registry's spawn path persists `harness_sessions` rows. Assigning
61
+ // `KABMO_DB_PATH` here is NOT isolation: the handle is a process-wide
62
+ // singleton, so a sibling suite that already opened the developer's real
63
+ // `~/.kabmo/db.sqlite` makes the assignment inert and every spawn below
64
+ // writes a row there (measured: 141 `omp-fork-test-*` rows in a live
65
+ // install). `isolateDb` closes that handle before it points the path at a
66
+ // fresh temp file.
67
+ await isolateDb();
59
68
  Bun.env.KABMO_OMP_BIN = join(import.meta.dir, '../../../../test-support/fake-omp-fork.ts');
60
69
  Bun.env.PI_CODING_AGENT_DIR = join(root, 'agent');
61
- Bun.env.KABMO_DB_PATH = join(root, 'db.sqlite');
62
70
  Bun.env.SYNC_WORKSPACE = 'false';
63
71
  Bun.env.FAKE_OMP_FORK_ON_RESUME = '1';
64
72
  Bun.env.FAKE_OMP_FORK_LOG = join(root, 'forks.jsonl');
@@ -66,10 +74,13 @@ beforeEach(() => {
66
74
  delete globalThis.__ompStartLocks;
67
75
  });
68
76
 
69
- afterEach(() => {
77
+ afterEach(async () => {
70
78
  stopDiscoveryRootsWatch();
71
79
  delete globalThis.__ompSessions;
72
80
  delete globalThis.__ompStartLocks;
81
+ // Close and drop the temp handle BEFORE restoring `KABMO_DB_PATH`: leaving it
82
+ // in the process-wide slot sends the next suite's writes to this deleted file.
83
+ await releaseDb();
73
84
  for (const key of ENV_KEYS) {
74
85
  const value = saved[key];
75
86
  if (value === undefined) delete Bun.env[key];
@@ -10,18 +10,24 @@
10
10
  * The ORDER is the contract and it is enforced here, not by the callers:
11
11
  * 1. refuse a pending `new-…` chat and an id that is not one path segment —
12
12
  * both name something other than the session they appear to;
13
- * 2. refuse a session whose omp child is mid-turn (a run, a live subagent, or
14
- * a dialog the agent is blocked on) — the delete would kill work the user
15
- * can still see, and omp would flush the file back on shutdown anyway;
16
- * 3. destroy the child and AWAIT its exit — omp writes session state on
17
- * shutdown and would otherwise recreate the transcript just removed;
13
+ * 2. refuse a session whose child is mid-turn (a run, a live subagent, or a
14
+ * dialog the agent is blocked on) — the delete would kill work the user can
15
+ * still see, and omp would flush the file back on shutdown anyway. ANY
16
+ * harness: an ACP chat is live in the same registry and is just as much in
17
+ * the middle of something;
18
+ * 3. destroy the child and AWAIT its exit;
18
19
  * 4. purge side questions, then the transcript, artifacts and Kabmo rows.
19
20
  *
21
+ * Step 2/3 read `getLiveSession`, not the omp-only view: an ACP session has no
22
+ * `AgentSessionWrapper`, so the old `getRpcSession` lookup answered "nothing is
23
+ * live" for every non-omp chat — the delete then removed its rows while the
24
+ * agent process kept the conversation aliased in the registry.
25
+ *
20
26
  * A batch that re-implemented any of this would drift from the single delete,
21
27
  * and the drift would be silent: the route answers per-id verdicts either way.
22
28
  */
23
29
 
24
- import { getRpcSession } from '@/server/lib/omp/rpc/session-registry';
30
+ import { getLiveSession } from '@/server/lib/omp/rpc/session-registry';
25
31
  import { purgeSessionData } from '@/server/lib/omp/session/delete.server';
26
32
  import { purgeBtwForSession } from '@/server/lib/btw/purge.server';
27
33
  import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
@@ -61,8 +67,9 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
61
67
 
62
68
  try {
63
69
  // A live child is the only other writer of the transcript. Busy means a
64
- // turn, a live subagent, or a dialog omp is parked on.
65
- const live = getRpcSession(sessionId);
70
+ // turn, a live subagent, or a dialog the agent is parked on — omp's child
71
+ // and an ACP agent's alike.
72
+ const live = getLiveSession(sessionId);
66
73
  if (live?.isAlive()) {
67
74
  if (live.isBusy()) {
68
75
  return {
@@ -18,6 +18,10 @@
18
18
  * - its sibling artifacts directory, which holds the subagent transcripts;
19
19
  * - the `archived_sessions`, `session_ui_state`, `session_stream_state`,
20
20
  * `queued_messages` and `chat_sessions` rows for that id;
21
+ * - the `harness_sessions`, `harness_goal_state` and `harness_usage_state`
22
+ * rows, which are the WHOLE record of a chat that ran on an ACP agent (its
23
+ * transcript is written by nobody Kabmo can read) and its resume id, goal
24
+ * and token usage besides;
21
25
  * - in mock mode the demo `sessions` row and its `files` tree.
22
26
  *
23
27
  * The caller owns the process: a live omp child MUST be destroyed before this
@@ -62,6 +66,14 @@ const SESSION_ROW_DELETES: readonly (readonly [string, string])[] = [
62
66
  ['queued_messages', 'session_id'],
63
67
  ['chat_sessions', 'session_id'],
64
68
  ['files', 'session_id'],
69
+ // An ACP chat has no transcript for the scan to lose: `harness_sessions` IS
70
+ // its row, so leaving it behind both refused the delete as "not found" (nothing
71
+ // else matched) and, for `omp-acp` whose JSONL did exist, re-listed the chat
72
+ // from the record the moment the file was gone. The goal and usage rows are
73
+ // keyed to the same id and would otherwise outlive the chat they describe.
74
+ ['harness_sessions', 'session_id'],
75
+ ['harness_goal_state', 'session_id'],
76
+ ['harness_usage_state', 'session_id'],
65
77
  ];
66
78
 
67
79
  async function purgeKabmoRows(db: DbClient, sessionId: string): Promise<number> {
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The in-place rewind endpoint, driven against a real session file.
8
+ *
9
+ * Two rules are pinned here, both of which the ACP transport made visible:
10
+ *
11
+ * - the live child is torn down BEFORE the file is touched. `omp-acp` writes
12
+ * the same JSONL and flushes it on shutdown, so a rewind that rewrote the
13
+ * file first raced the child and could be overwritten by its final flush;
14
+ * - a harness whose agent keeps its own transcript is refused BEFORE its child
15
+ * is destroyed. `claude` has no omp file to truncate, so the old shape would
16
+ * have killed a working chat and then answered 404.
17
+ */
18
+
19
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
20
+ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
21
+ import { tmpdir } from 'node:os';
22
+ import { join } from 'node:path';
23
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
24
+ import { removeDir } from '@/test-support/remove-dir';
25
+ import { registerAcpSession } from '@/server/lib/harness/register.server';
26
+ import { claimHarness } from '@/server/lib/harness/registry';
27
+ import { clearSessionFileCaches } from '@/server/lib/omp/session/files';
28
+ import { action } from '@/server/routes/chat/rewind';
29
+ import type { HarnessSession } from '@/server/lib/harness/session';
30
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
31
+
32
+ const SESSION_ID = '01a1b49f-0000-7000-8000-000000000001';
33
+
34
+ const FIXTURE = [
35
+ JSON.stringify({ type: 'session', id: SESSION_ID, cwd: '/tmp/project' }),
36
+ JSON.stringify({ type: 'message', id: 'u1', timestamp: 1_000, message: { role: 'user', content: 'first ask' } }),
37
+ JSON.stringify({ type: 'message', id: 'a1', timestamp: 2_000, message: { role: 'assistant', content: 'answer' } }),
38
+ '',
39
+ ].join('\n');
40
+
41
+ let root = '';
42
+ let filePath = '';
43
+ let previousAgentDir: string | undefined;
44
+
45
+ /** Register a fake ACP session the route's `getLiveSession` lookup will find. */
46
+ function registerLive(id: string, harness: HarnessId, onDestroy?: () => void): () => void {
47
+ let release: (() => void) | null = null;
48
+ const session = {
49
+ sessionId: id,
50
+ harness,
51
+ sessionFile: '',
52
+ cwd: '/tmp/project',
53
+ isStreaming: false,
54
+ isPromptRunning: false,
55
+ runModel: null,
56
+ isAlive: () => true,
57
+ isRunning: () => false,
58
+ isBusy: () => false,
59
+ send: async () => ({}),
60
+ getPendingUiDialogs: () => [],
61
+ resolvePendingUiDialog: () => {},
62
+ onEvent: () => () => {},
63
+ emit: () => {},
64
+ destroy: () => {},
65
+ destroyAndWait: async () => {
66
+ onDestroy?.();
67
+ release?.();
68
+ },
69
+ onDestroy: (callback: () => void) => {
70
+ release = callback;
71
+ },
72
+ } as unknown as HarnessSession;
73
+ registerAcpSession(session, id);
74
+ claimHarness(session, harness);
75
+ return () => release?.();
76
+ }
77
+
78
+ function rewind(entryId = 'u1'): Promise<Response> {
79
+ return action({
80
+ params: { sessionId: SESSION_ID },
81
+ request: new Request(`http://localhost/api/chat/${SESSION_ID}/rewind`, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({ entryId }),
85
+ }),
86
+ } as never) as Promise<Response>;
87
+ }
88
+
89
+ beforeEach(async () => {
90
+ previousAgentDir = Bun.env.PI_CODING_AGENT_DIR;
91
+ root = mkdtempSync(join(tmpdir(), 'kabmo-rewind-'));
92
+ Bun.env.PI_CODING_AGENT_DIR = root;
93
+ const project = join(root, 'sessions', 'project');
94
+ mkdirSync(project, { recursive: true });
95
+ filePath = join(project, `${SESSION_ID}.jsonl`);
96
+ writeFileSync(filePath, FIXTURE);
97
+ clearSessionFileCaches();
98
+ await isolateDb();
99
+ });
100
+
101
+ afterEach(async () => {
102
+ await releaseDb();
103
+ clearSessionFileCaches();
104
+ if (previousAgentDir === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
105
+ else Bun.env.PI_CODING_AGENT_DIR = previousAgentDir;
106
+ if (root) removeDir(root);
107
+ root = '';
108
+ });
109
+
110
+ describe('POST /api/chat/:id/rewind', () => {
111
+ test('an omp-acp chat is torn down BEFORE its shared JSONL is rewritten', async () => {
112
+ const atTeardown: string[] = [];
113
+ const release = registerLive(SESSION_ID, 'omp-acp', () => atTeardown.push(readFileSync(filePath, 'utf8')));
114
+ try {
115
+ const response = await rewind();
116
+ expect(response.status).toBe(200);
117
+ // The child still had the abandoned turn when it was destroyed — proof the
118
+ // teardown ran first, not after the rewrite.
119
+ expect(atTeardown).toHaveLength(1);
120
+ expect(atTeardown[0]).toContain('"id":"a1"');
121
+
122
+ const next = readFileSync(filePath, 'utf8');
123
+ expect(next).not.toContain('"id":"u1"');
124
+ expect(next).not.toContain('"id":"a1"');
125
+ expect(next).toContain('"type":"session"');
126
+ } finally {
127
+ release();
128
+ }
129
+ });
130
+
131
+ test('another ACP agent is refused without destroying its live child', async () => {
132
+ let destroyed = 0;
133
+ const release = registerLive(SESSION_ID, 'claude', () => { destroyed += 1; });
134
+ try {
135
+ const response = await rewind();
136
+ expect(response.status).toBe(400);
137
+ const body = (await response.json()) as { code?: string; error?: string };
138
+ expect(body.code).toBe('harness_not_rewindable');
139
+ expect(body.error).toContain('claude');
140
+ expect(destroyed).toBe(0);
141
+ // Its file — when it has one Kabmo can find — is untouched.
142
+ expect(readFileSync(filePath, 'utf8')).toContain('"id":"u1"');
143
+ } finally {
144
+ release();
145
+ }
146
+ });
147
+ });
@@ -2,10 +2,11 @@ import { json } from '@/server/lib/remix-compat';
2
2
  import type { ActionFunctionArgs } from '@/server/lib/remix-compat';
3
3
  import { getDb } from '@/server/db.server';
4
4
  import { resolveSessionFileOr404 } from '@/server/lib/omp/session/locator';
5
- import { getRpcSession } from '@/server/lib/omp/rpc/session-registry';
5
+ import { getLiveSession, harnessOfSession } from '@/server/lib/omp/rpc/session-registry';
6
6
  import { clearSessionFileCaches } from '@/server/lib/omp/session/files';
7
7
  import { pruneStoredAfterCut, survivingUserTexts, truncateSessionBody } from '@/server/lib/omp/session/rewind-file';
8
8
  import { userTurnsRelate } from '@/shared/lib/chat/timeline/turns';
9
+ import { harnessSupportsRewind } from '@/shared/lib/harness/rewind';
9
10
 
10
11
  /**
11
12
  * In-place rewind (undo) for an omp session: truncate the session JSONL back
@@ -16,9 +17,18 @@ import { userTurnsRelate } from '@/shared/lib/chat/timeline/turns';
16
17
  * file in place for equivalent operations (`rewriteEntries`), and its JSONL
17
18
  * readers walk entries in order, so a prefix-preserving truncation is faithful.
18
19
  *
20
+ * Both omp transports reach this endpoint. `omp-acp` writes the SAME JSONL as
21
+ * `omp-rpc`, so a chat that ran over ACP is rewound the same way — the ACP
22
+ * child is torn down first, because it holds the old context in memory and is
23
+ * the only other writer of the file; the next prompt resumes the truncated
24
+ * transcript over RPC (`resumeRecordedHarnessSession` deliberately excludes
25
+ * `omp-acp`, whose `session/load` forks). Every other ACP agent stores its own
26
+ * history and offers no truncation, so it is refused in words instead of
27
+ * truncating a file it does not read.
28
+ *
19
29
  * Safety contract:
20
- * - the live omp process for this session is destroyed first (it flushes all
21
- * pending state on shutdown and is the only other writer of this file);
30
+ * - the live child for this session is destroyed first (it flushes pending
31
+ * state on shutdown and is the only other writer of this file);
22
32
  * - the original file is kept as `<name>.bak-<timestamp>` (omp's session
23
33
  * listing ignores names containing `.bak`, so it never becomes a phantom
24
34
  * session).
@@ -54,10 +64,22 @@ export async function action({ params, request }: ActionFunctionArgs) {
54
64
  if ('response' in resolved) return resolved.response;
55
65
  const { filePath } = resolved;
56
66
 
57
- // Tear down the live process first: it flushes pending writes on shutdown
58
- // and must not race the rewrite. Best-effort — the session may already be
59
- // gone or mid-restart.
60
- const live = getRpcSession(sessionId);
67
+ // Tear down the live child FIRST, whichever transport runs it: it flushes
68
+ // pending writes on shutdown, it is the only other writer of the file, and
69
+ // the file's CONTENT is read below. Best-effort: the session may already be
70
+ // gone or mid-restart. A harness whose agent keeps its own transcript is
71
+ // refused BEFORE its child is touched — truncating a file it does not read
72
+ // would kill a working chat to no effect.
73
+ const live = getLiveSession(sessionId);
74
+ if (live && !harnessSupportsRewind(harnessOfSession(live))) {
75
+ return json(
76
+ {
77
+ error: `${harnessOfSession(live)} cannot rewind this chat: its agent keeps its own transcript and offers no truncation.`,
78
+ code: 'harness_not_rewindable',
79
+ },
80
+ { status: 400 },
81
+ );
82
+ }
61
83
  if (live?.isAlive()) {
62
84
  await live.destroyAndWait();
63
85
  }