ompchamber 3.3.3 → 3.4.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 (55) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +275 -268
  3. package/dist/client/static/js/{index-8ejde0b7.js → index-h05z90mw.js} +581 -581
  4. package/package.json +1 -1
  5. package/src/client/components/settings/categories/AppearanceSettings.tsx +1 -1
  6. package/src/client/components/settings/categories/ChatSettings.tsx +1 -1
  7. package/src/client/components/workspace/btw-panel/AskCard.tsx +6 -1
  8. package/src/client/components/workspace/btw-panel/Messages.tsx +1 -1
  9. package/src/client/components/workspace/btw-panel/TopicMenu.tsx +1 -1
  10. package/src/client/components/workspace/btw-panel/index.tsx +20 -27
  11. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +29 -18
  12. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +9 -39
  13. package/src/client/components/workspace/chat-timeline/chat-input/props.ts +62 -0
  14. package/src/client/hooks/chat/btw/index.ts +7 -73
  15. package/src/client/hooks/chat/btw/intercept.test.ts +80 -0
  16. package/src/client/hooks/chat/btw/intercept.ts +5 -2
  17. package/src/client/hooks/chat/btw/mode.ts +16 -76
  18. package/src/client/hooks/chat/timeline/actions.ts +22 -30
  19. package/src/client/hooks/chat/timeline/queue-actions.ts +88 -0
  20. package/src/client/hooks/chat/timeline/send.ts +8 -1
  21. package/src/client/hooks/chat/timeline/tui-only-guard.ts +58 -0
  22. package/src/server/lib/btw/child.server.test.ts +68 -0
  23. package/src/server/lib/btw/child.server.ts +17 -16
  24. package/src/server/lib/btw/frames.test.ts +3 -3
  25. package/src/server/lib/btw/frames.ts +1 -1
  26. package/src/server/lib/btw/lifecycle.server.test.ts +139 -0
  27. package/src/server/lib/btw/lifecycle.server.ts +41 -31
  28. package/src/server/lib/btw/prompt.ts +7 -11
  29. package/src/server/lib/btw/registry.server.ts +1 -9
  30. package/src/server/lib/btw/reply.ts +54 -0
  31. package/src/server/lib/btw/runtime.server.test.ts +128 -0
  32. package/src/server/lib/btw/runtime.server.ts +77 -86
  33. package/src/server/lib/btw/schema.server.test.ts +84 -0
  34. package/src/server/lib/btw/schema.server.ts +8 -0
  35. package/src/server/lib/btw/service.server.ts +47 -78
  36. package/src/server/lib/btw/store.server.ts +9 -20
  37. package/src/server/lib/omp/rpc/constants.ts +10 -0
  38. package/src/server/lib/omp/rpc/session-commands.ts +45 -0
  39. package/src/server/lib/omp/session/merge-stored-notices.test.ts +81 -0
  40. package/src/server/lib/omp/session/merge-stored.ts +70 -1
  41. package/src/server/lib/omp/session/messages.ts +27 -2
  42. package/src/server/routes/agent/command.ts +9 -1
  43. package/src/server/routes/btw/topics.ts +2 -59
  44. package/src/shared/lib/chat/btw/client.ts +0 -30
  45. package/src/shared/lib/chat/composer/tui-only.test.ts +90 -0
  46. package/src/shared/lib/chat/composer/tui-only.ts +138 -0
  47. package/src/shared/lib/chat/notice-text.ts +33 -0
  48. package/src/shared/lib/chat/omp/agent-events.ts +18 -37
  49. package/src/shared/lib/chat/omp/available-commands-cache.test.ts +66 -0
  50. package/src/shared/lib/chat/omp/command-output-ansi.test.ts +84 -0
  51. package/src/shared/lib/chat/omp/fold-deps.ts +48 -0
  52. package/src/shared/lib/chat/timeline/command-output.ts +65 -0
  53. package/src/shared/lib/chat/timeline/omp-callbacks.ts +4 -17
  54. package/src/shared/lib/omp/session/messages-map.ts +6 -1
  55. package/src/shared/types/btw.ts +13 -34
@@ -0,0 +1,139 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The side turn's frame fold.
8
+ *
9
+ * These pin the three behaviours that are invisible until a reload: a completed
10
+ * message is stored as COMPLETE (its thinking stops pulsing, its usage is the
11
+ * real one), a tool call the model emitted anyway is not rendered as a card for
12
+ * a tool that never ran, and the stored summary is bounded the way omp bounds
13
+ * its own side replies.
14
+ */
15
+
16
+ import { describe, expect, test } from 'bun:test';
17
+ import { boundSideReply } from '@/server/lib/btw/reply';
18
+ import { trackTurnMessage, type BtwLifecycleHost } from '@/server/lib/btw/lifecycle.server';
19
+ import type { ChatMessageData } from '@/shared/types';
20
+
21
+ function makeHost(): { host: BtwLifecycleHost; frames: string[] } {
22
+ const frames: string[] = [];
23
+ const host = {
24
+ topicId: 'topic',
25
+ sessionId: 'session',
26
+ sink: { publish: (frame: { type: string }) => frames.push(frame.type), stateChanged: () => {} },
27
+ running: true,
28
+ proc: null,
29
+ idleTimer: null,
30
+ abortTimer: null,
31
+ lastIdleReset: 0,
32
+ turnIndex: 0,
33
+ settling: false,
34
+ messages: [] as ChatMessageData[],
35
+ activity: '',
36
+ disposing: null,
37
+ start: async () => ({} as never),
38
+ teardownChild: async () => {},
39
+ } as unknown as BtwLifecycleHost;
40
+ return { host, frames };
41
+ }
42
+
43
+ const ASSISTANT_WITH_TOOL_CALL = {
44
+ type: 'message_end',
45
+ message: {
46
+ id: 'm1',
47
+ role: 'assistant',
48
+ timestamp: 1,
49
+ content: [
50
+ { type: 'thinking', thinking: 'weighing it up' },
51
+ { type: 'text', text: 'the answer' },
52
+ { type: 'toolCall', id: 'call_1', name: 'read', input: { path: 'x' } },
53
+ ],
54
+ usage: { input: 10, output: 4, totalTokens: 14 },
55
+ },
56
+ };
57
+
58
+ describe('trackTurnMessage', () => {
59
+ test('a completed message is stored as complete, with its usage', () => {
60
+ const { host } = makeHost();
61
+ trackTurnMessage(host, ASSISTANT_WITH_TOOL_CALL as never, false);
62
+
63
+ const [row] = host.messages;
64
+ expect(row?.content).toBe('the answer');
65
+ expect(typeof row?.thinking === 'object' ? row.thinking.isGenerating : undefined).toBe(false);
66
+ expect(row?.usage?.totalTokens).toBe(14);
67
+ });
68
+
69
+ test('a streaming segment still marks its thinking as generating', () => {
70
+ const { host } = makeHost();
71
+ trackTurnMessage(host, {
72
+ type: 'message_update',
73
+ message: { id: 'm1', role: 'assistant', timestamp: 1, content: [{ type: 'thinking', thinking: 'still going' }] },
74
+ } as never);
75
+
76
+ const thinking = host.messages[0]?.thinking;
77
+ expect(typeof thinking === 'object' ? thinking.isGenerating : undefined).toBe(true);
78
+ });
79
+
80
+ test('a tool call the model emitted anyway is not rendered', () => {
81
+ const { host } = makeHost();
82
+ trackTurnMessage(host, ASSISTANT_WITH_TOOL_CALL as never, false);
83
+
84
+ expect(host.messages[0]?.toolCalls ?? []).toHaveLength(0);
85
+ });
86
+
87
+ test('a toolResult frame never becomes a row', () => {
88
+ const { host, frames } = makeHost();
89
+ trackTurnMessage(host, {
90
+ type: 'message_end',
91
+ message: { id: 'r1', role: 'toolResult', toolCallId: 'call_1', content: [{ type: 'text', text: 'file body' }] },
92
+ } as never, false);
93
+
94
+ expect(host.messages).toHaveLength(0);
95
+ expect(frames).toHaveLength(0);
96
+ });
97
+
98
+ test('a same-id frame replaces the streaming row in place', () => {
99
+ const { host } = makeHost();
100
+ trackTurnMessage(host, { type: 'message_update', message: { id: 'm1', role: 'assistant', timestamp: 1, content: [{ type: 'text', text: 'half' }] } } as never);
101
+ trackTurnMessage(host, { type: 'message_end', message: { id: 'm1', role: 'assistant', timestamp: 1, content: [{ type: 'text', text: 'the answer' }] } } as never, false);
102
+
103
+ expect(host.messages).toHaveLength(1);
104
+ expect(host.messages[0]?.content).toBe('the answer');
105
+ });
106
+ });
107
+
108
+ describe('boundSideReply', () => {
109
+ test('a long run of identical lines collapses with a count', () => {
110
+ const reply = ['same', 'same', 'same', 'same', 'same'].join('\n');
111
+ expect(boundSideReply(reply)).toBe('same\n[…5×]');
112
+ });
113
+
114
+ test('a run at the limit is left alone', () => {
115
+ const reply = ['same', 'same', 'same'].join('\n');
116
+ expect(boundSideReply(reply)).toBe(reply);
117
+ });
118
+
119
+ test('an oversized reply is capped and marked', () => {
120
+ // Comfortably past the 4 KiB cap: 500 lines averaging ~11 bytes.
121
+ const reply = Array.from({ length: 500 }, (_, index) => `line number ${index}`).join('\n');
122
+ const bounded = boundSideReply(reply);
123
+ expect(bounded.endsWith('\n[…truncated]')).toBe(true);
124
+ expect(Buffer.byteLength(bounded, 'utf8')).toBeLessThanOrEqual(4096);
125
+ });
126
+
127
+ test('the cap does not split a surrogate pair', () => {
128
+ // 4-byte characters only: a byte-slice would leave a lone surrogate, which
129
+ // JSON round-trips as U+FFFD.
130
+ const reply = '😀'.repeat(1500);
131
+ const bounded = boundSideReply(reply);
132
+ expect(bounded).not.toContain('\uFFFD');
133
+ expect(bounded.endsWith('\n[…truncated]')).toBe(true);
134
+ });
135
+
136
+ test('a short reply is untouched', () => {
137
+ expect(boundSideReply('just an answer')).toBe('just an answer');
138
+ });
139
+ });
@@ -16,14 +16,13 @@
16
16
 
17
17
  import type { RpcProcess, RpcFrame } from '@/server/lib/omp/rpc/process';
18
18
  import { GET_STATE_TIMEOUT_MS, IDLE_DESTROY_MS, PROMPT_ACK_TIMEOUT_MS } from '@/server/lib/omp/rpc/constants';
19
- import type { PendingUiDialogs } from '@/server/lib/omp/rpc/pending-ui-dialogs';
20
19
  import { buildBtwPrompt } from '@/server/lib/btw/prompt';
20
+ import { boundSideReply } from '@/server/lib/btw/reply';
21
21
  import { appendBtwTurn, settleRunningBtwTurns, updateBtwTurn } from '@/server/lib/btw/store.server';
22
22
  import type { BtwRuntimeSink } from '@/server/lib/btw/runtime.server';
23
23
  import { toChatMessage } from '@/shared/lib/omp/session/mapper';
24
24
  import { describeAssistantPhase, describeToolActivity } from '@/shared/lib/chat/timeline/tool-verbs';
25
25
  import { isNoticeRow } from '@/shared/lib/chat/notice-row';
26
- import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
27
26
  import type { AgentImage, BtwTurnStatus, ChatMessageData } from '@/shared/types';
28
27
 
29
28
  /** Longest an aborted turn may stay unsettled before its child is reclaimed. */
@@ -33,8 +32,6 @@ const ABORT_GRACE_MS = 10_000;
33
32
  export interface BtwLifecycleHost {
34
33
  readonly topicId: string;
35
34
  readonly sink: BtwRuntimeSink;
36
- /** Ask/approval dialogs the child is blocked on. */
37
- readonly dialogs: PendingUiDialogs;
38
35
  /** A question is in flight in this topic. */
39
36
  readonly running: boolean;
40
37
  proc: RpcProcess | null;
@@ -49,8 +46,6 @@ export interface BtwLifecycleHost {
49
46
  /** Last activity phrase published, so repeats are not re-published. */
50
47
  activity: string;
51
48
  disposing: Promise<void> | null;
52
- /** Approval mode the live child was spawned with. */
53
- spawnedApprovalMode: ApprovalMode | undefined;
54
49
  /** Spawn (or reuse) the child. */
55
50
  start(): Promise<RpcProcess>;
56
51
  /** Drop the child and everything scoped to it. */
@@ -71,7 +66,7 @@ export async function askSideQuestion(host: BtwLifecycleHost, question: string,
71
66
  PROMPT_ACK_TIMEOUT_MS,
72
67
  );
73
68
  } catch (error) {
74
- await settleSideTurn(host, 'failed');
69
+ await settleSideTurn(host, 'error');
75
70
  host.sink.publish({
76
71
  type: 'btw_error',
77
72
  topicId: host.topicId,
@@ -106,6 +101,29 @@ export async function abortSideTurn(host: BtwLifecycleHost): Promise<void> {
106
101
  host.abortTimer = timer;
107
102
  }
108
103
 
104
+ /**
105
+ * Drop `toolCall` content blocks from a message.
106
+ *
107
+ * omp's own side turn filters them out of its final message
108
+ * (`agent-session.ts`: `content.filter(block => block.type !== 'toolCall')`)
109
+ * because the call was never executed. A model that emits one anyway — a
110
+ * hallucinated call against the tool catalog omp keeps attached for the prompt
111
+ * cache — must not surface here as a card for a tool that never ran.
112
+ */
113
+ function withoutToolCalls(record: Record<string, unknown>): Record<string, unknown> {
114
+ const content = record.content;
115
+ if (!Array.isArray(content)) return record;
116
+ const kept = content.filter((block) => !isToolCallBlock(block));
117
+ if (kept.length === content.length) return record;
118
+ return { ...record, content: kept };
119
+ }
120
+
121
+ /** Whether a content block is a tool call — the block shape omp's own filter reads. */
122
+ function isToolCallBlock(block: unknown): boolean {
123
+ if (!block || typeof block !== 'object' || !('type' in block)) return false;
124
+ return block.type === 'toolCall';
125
+ }
126
+
109
127
  /**
110
128
  * The turn's conversation as it accumulates, in the chat's own shape.
111
129
  *
@@ -113,17 +131,24 @@ export async function abortSideTurn(host: BtwLifecycleHost): Promise<void> {
113
131
  * accumulated content and its own message id — so a same-id frame replaces the
114
132
  * entry in place and a new id appends. That is exactly the upsert the chat
115
133
  * timeline's `onMessageUpdate` performs, and keeping it identical is what makes
116
- * a side answer render through the chat's own `MessageList`: a tool the side
117
- * child runs shows up here the same way it would in the chat.
134
+ * a side answer render through the chat's own `MessageList`.
135
+ *
136
+ * `streaming` is the chat stream's own distinction, and it matters in two
137
+ * places: a COMPLETED message is the authoritative copy (it carries the turn's
138
+ * real usage where the deltas report zeros), and its thinking is no longer
139
+ * generating — mapping it as a streaming row left every reloaded turn with an
140
+ * open, pulsing accordion.
118
141
  */
119
- export function trackTurnMessage(host: BtwLifecycleHost, frame: RpcFrame): void {
142
+ export function trackTurnMessage(host: BtwLifecycleHost, frame: RpcFrame, streaming = true): void {
120
143
  const raw = frame.message;
121
144
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
122
145
  const record = raw as Record<string, unknown>;
146
+ // A side turn executes no tool (see `child.server.ts`), so omp emits no
147
+ // `toolResult` for it. Dropping the role keeps a stray one from becoming a row.
123
148
  if (record.role === 'toolResult') return;
124
149
  const turnIndex = host.turnIndex;
125
150
  if (turnIndex === null) return;
126
- const converted = toChatMessage(record);
151
+ const converted = toChatMessage(withoutToolCalls(record), streaming);
127
152
  if (!converted) return;
128
153
  const existing = host.messages.findIndex((message) => message.id === converted.id);
129
154
  host.messages =
@@ -168,12 +193,9 @@ export async function settleSideTurn(host: BtwLifecycleHost, status: BtwTurnStat
168
193
  host.turnIndex = null;
169
194
  // `||`, not `??`: a turn that only ran tools has no prose, and the caller
170
195
  // passes an empty string rather than undefined — the summary must then fall
171
- // through to whatever the conversation does carry.
172
- const text = answer || answerText(host.messages, '');
173
- // A settled turn has no dialogs left to answer; a stale modal would sit over
174
- // an idle panel with nothing behind it.
175
- const hadDialogs = host.dialogs.list().length > 0;
176
- host.dialogs.clear();
196
+ // through to whatever the conversation does carry. Bounded the way omp bounds
197
+ // its own side replies (see `reply.ts`).
198
+ const text = boundSideReply(answer || answerText(host.messages, ''));
177
199
  host.settling = true;
178
200
  try {
179
201
  await updateBtwTurn(host.topicId, turnIndex, { answer: text, status, messages: host.messages });
@@ -181,7 +203,6 @@ export async function settleSideTurn(host: BtwLifecycleHost, status: BtwTurnStat
181
203
  host.settling = false;
182
204
  host.messages = [];
183
205
  host.sink.stateChanged();
184
- if (hadDialogs) host.sink.stateChanged();
185
206
  }
186
207
  }
187
208
 
@@ -189,13 +210,7 @@ export async function settleSideTurn(host: BtwLifecycleHost, status: BtwTurnStat
189
210
  export function handleSideChildExit(host: BtwLifecycleHost, stderrTail: string): void {
190
211
  const wasRunning = host.running;
191
212
  host.proc = null;
192
- host.spawnedApprovalMode = undefined;
193
- const hadDialogs = host.dialogs.list().length > 0;
194
- host.dialogs.clear();
195
- if (!wasRunning) {
196
- if (hadDialogs) host.sink.stateChanged();
197
- return;
198
- }
213
+ if (!wasRunning) return;
199
214
  void settleRunningBtwTurns(host.topicId, 'interrupted').then(() => {
200
215
  host.turnIndex = null;
201
216
  host.messages = [];
@@ -209,7 +224,7 @@ export function handleSideChildExit(host: BtwLifecycleHost, stderrTail: string):
209
224
  });
210
225
  }
211
226
 
212
- /** Clear the timers and the process, and drop the dialogs that belonged to it. */
227
+ /** Clear the timers and drop the child. */
213
228
  export async function teardownSideChild(host: BtwLifecycleHost): Promise<void> {
214
229
  // Type-required guards: the fields are `Timeout | null`, `clearTimeout` takes
215
230
  // `Timeout | undefined`.
@@ -217,15 +232,10 @@ export async function teardownSideChild(host: BtwLifecycleHost): Promise<void> {
217
232
  if (host.abortTimer) clearTimeout(host.abortTimer);
218
233
  host.idleTimer = null;
219
234
  host.abortTimer = null;
220
- const hadDialogs = host.dialogs.list().length > 0;
221
- host.dialogs.clear();
222
- host.spawnedApprovalMode = undefined;
223
235
  const proc = host.proc;
224
236
  host.proc = null;
225
237
  if (proc) await proc.dispose().catch(() => {});
226
238
  host.disposing = null;
227
- // A modal whose process is gone must not stay on screen.
228
- if (hadDialogs) host.sink.stateChanged();
229
239
  }
230
240
 
231
241
  async function disposeIfUnsettled(host: BtwLifecycleHost): Promise<void> {
@@ -6,17 +6,12 @@
6
6
  /**
7
7
  * The side-question prompt.
8
8
  *
9
- * Derived from omp's own `/btw` template
10
- * (`packages/coding-agent/src/prompts/system/btw-user.md`), with one
11
- * deliberate divergence: the TUI's `/btw` runs the side child with
12
- * `--no-tools` and its prompt says "NEVER use tools". The chamber's panel
13
- * exposes a real access-control dropdown, which only means something when the
14
- * child HAS a tool surface — so the tool prohibition is dropped and the
15
- * approval mode governs what the side child may actually do.
16
- *
17
- * What is kept is the shape that makes a side question a side question: it
18
- * answers briefly and directly, and it never opens a follow-up dialogue of its
19
- * own — follow-ups are explicit user turns.
9
+ * Byte-for-byte omp's own `/btw` template
10
+ * (`packages/coding-agent/src/prompts/system/btw-user.md`), including
11
+ * "NEVER use tools": the side child runs with `--no-tools`, so a tool call is
12
+ * impossible and the prompt must not invite one. Keeping the template identical
13
+ * means a side question reads the same in both clients and a model tuned against
14
+ * one behaves the same in the other.
20
15
  *
21
16
  * The parent session's history is NOT part of this text: the side session
22
17
  * resumes the parent's transcript, so the context arrives as real provider
@@ -28,6 +23,7 @@ export function buildBtwPrompt(question: string): string {
28
23
  '<btw>',
29
24
  'Ephemeral side question for current interactive session.',
30
25
  'Answer briefly, directly; use conversation context already provided.',
26
+ 'NEVER use tools.',
31
27
  'NEVER ask follow-up questions.',
32
28
  'Question:',
33
29
  question,
@@ -20,7 +20,7 @@
20
20
 
21
21
  import { listBtwTopics, settleRunningBtwTurns } from '@/server/lib/btw/store.server';
22
22
  import { BtwRuntime, type BtwRuntimeContext } from '@/server/lib/btw/runtime.server';
23
- import type { BtwFrame, BtwState, BtwTopic, ExtensionUiDialogRequest } from '@/shared/types';
23
+ import type { BtwFrame, BtwState, BtwTopic } from '@/shared/types';
24
24
 
25
25
  interface BtwRegistryHost {
26
26
  runtimes: Map<string, BtwRuntime>;
@@ -132,14 +132,6 @@ export async function btwStateFor(sessionId: string): Promise<BtwState> {
132
132
  topics: repaired,
133
133
  runningTopicId: repaired.find((topic) => topic.turns.some((turn) => turn.status === 'running'))?.id ?? null,
134
134
  live: liveRuntime?.liveTurn() ?? null,
135
- // Dialogs live on the runtime, not in SQLite: they belong to the child
136
- // process that raised them, and a child that is gone has none.
137
- dialogs: runtimes.flatMap((runtime) =>
138
- runtime.dialogs
139
- .list()
140
- .filter((request) => typeof request.id === 'string')
141
- .map((request) => ({ topicId: runtime.topicId, request: request as unknown as ExtensionUiDialogRequest })),
142
- ),
143
135
  };
144
136
  }
145
137
 
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The side reply's stored summary, bounded the way omp bounds its own.
8
+ *
9
+ * omp runs every ephemeral side reply through `dedupeEphemeralReply`
10
+ * (`session/messages.ts`): a run of more than three identical lines collapses to
11
+ * one line plus `[…N×]`, and the whole reply is capped at 4 KiB with a
12
+ * `[…truncated]` suffix. The cap exists because a degenerate model can emit
13
+ * thousands of identical lines, and this summary is what the panel's history
14
+ * labels and a promotion's title are built from.
15
+ *
16
+ * Only the turn's `answer` summary goes through here. The rendered conversation
17
+ * (`messages`) is stored whole — truncating that would hide content the panel is
18
+ * there to show.
19
+ */
20
+
21
+ /** Longest stored summary, matching omp's `EPHEMERAL_REPLY_MAX_BYTES`. */
22
+ const MAX_REPLY_BYTES = 4096;
23
+
24
+ /** Runs longer than this collapse to one line plus a count. */
25
+ const MAX_REPEATED_LINES = 3;
26
+
27
+ export function boundSideReply(text: string): string {
28
+ if (!text) return text;
29
+ const lines = text.split('\n');
30
+ const collapsed: string[] = [];
31
+ let index = 0;
32
+ while (index < lines.length) {
33
+ let next = index + 1;
34
+ while (next < lines.length && lines[next] === lines[index]) next += 1;
35
+ const runLength = next - index;
36
+ if (runLength > MAX_REPEATED_LINES) {
37
+ collapsed.push(lines[index], `[…${runLength}×]`);
38
+ } else {
39
+ for (let repeat = 0; repeat < runLength; repeat += 1) collapsed.push(lines[index]);
40
+ }
41
+ index = next;
42
+ }
43
+ let result = collapsed.join('\n');
44
+ if (Buffer.byteLength(result, 'utf8') <= MAX_REPLY_BYTES) return result;
45
+ const suffix = '\n[…truncated]';
46
+ const budget = MAX_REPLY_BYTES - Buffer.byteLength(suffix, 'utf8');
47
+ // Cut by code point: slicing at an arbitrary byte would leave half a surrogate
48
+ // pair, which JSON-serializes as U+FFFD and never round-trips.
49
+ while (result.length > 0 && Buffer.byteLength(result, 'utf8') > budget) {
50
+ const last = result.charCodeAt(result.length - 1);
51
+ result = result.slice(0, last >= 0xdc00 && last <= 0xdfff ? -2 : -1);
52
+ }
53
+ return result + suffix;
54
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * `BtwRuntime.retarget` — the path that makes a side question follow the chat's
8
+ * model and thinking selector.
9
+ *
10
+ * A live child keeps the model it was SPAWNED with, so a chat that switched
11
+ * model between two side questions would otherwise be answered by the stale one.
12
+ * omp's side turn reads `request.session.model` per run; this is the equivalent,
13
+ * and it has to be a no-op when the values already match or every question would
14
+ * spend two RPC round-trips re-sending what the child already runs.
15
+ *
16
+ * The child is a real `RpcProcess` here (no omp binary is spawned): only the
17
+ * command surface is replaced, so the assertions are on the actual commands the
18
+ * runtime would put on the wire.
19
+ */
20
+
21
+ import { describe, expect, test } from 'bun:test';
22
+ import { BtwRuntime } from '@/server/lib/btw/runtime.server';
23
+ import type { RpcProcess } from '@/server/lib/omp/rpc/process';
24
+ import type { BtwFrame } from '@/shared/types';
25
+
26
+ interface SentCommand {
27
+ type: string;
28
+ [key: string]: unknown;
29
+ }
30
+
31
+ /** A runtime whose child is alive and records every command sent to it. */
32
+ function makeRuntime(options: { alive: boolean }): { runtime: BtwRuntime; sent: SentCommand[]; setState: (state: unknown) => void } {
33
+ const sent: SentCommand[] = [];
34
+ let state: unknown = { model: { provider: 'kenari', id: 'deepseek-v4' }, thinkingLevel: 'high' };
35
+ const proc = {
36
+ get isAlive() {
37
+ return options.alive;
38
+ },
39
+ async sendCommand(command: SentCommand) {
40
+ sent.push(command);
41
+ return command.type === 'get_state' ? state : {};
42
+ },
43
+ sendFrame: () => {},
44
+ onFrame: () => () => {},
45
+ dispose: async () => {},
46
+ };
47
+ const runtime = new BtwRuntime(
48
+ {
49
+ topicId: 'topic',
50
+ sessionId: 'session',
51
+ parentSessionFile: '/tmp/parent.jsonl',
52
+ cwd: '/tmp',
53
+ model: { provider: 'kenari', id: 'deepseek-v4' },
54
+ thinkingLevel: 'high',
55
+ },
56
+ { publish: (_frame: BtwFrame) => {}, stateChanged: () => {} },
57
+ );
58
+ // `proc` is the private field the runtime reads; the cast is the seam that
59
+ // keeps this a unit test instead of a spawned-child integration test.
60
+ (runtime as unknown as { proc: unknown }).proc = proc;
61
+ return {
62
+ runtime,
63
+ sent,
64
+ setState: (next) => {
65
+ state = next;
66
+ },
67
+ };
68
+ }
69
+
70
+ describe('BtwRuntime.start', () => {
71
+ test('reuses the live child instead of spawning a second one', async () => {
72
+ const { runtime } = makeRuntime({ alive: true });
73
+ // The seam this suite installs, read back as the type `start` returns.
74
+ const proc = (runtime as unknown as { proc: RpcProcess }).proc;
75
+
76
+ // A live child is returned as-is; `spawnChild` is never reached (it would
77
+ // throw here, since no omp binary is configured for this unit test).
78
+ expect(await runtime.start()).toBe(proc);
79
+ });
80
+ });
81
+
82
+ describe('BtwRuntime.retarget', () => {
83
+ test('re-sends both values when the chat moved on', async () => {
84
+ const { runtime, sent } = makeRuntime({ alive: true });
85
+ // Seed what the child currently reports (as `captureModel` would).
86
+ await runtime.retarget({ provider: 'kenari', id: 'deepseek-v4' }, 'high');
87
+ sent.length = 0;
88
+
89
+ await runtime.retarget({ provider: 'anthropic', id: 'claude-sonnet-5' }, 'low');
90
+
91
+ expect(sent.map((command) => command.type)).toEqual(['set_model', 'set_thinking_level']);
92
+ expect(sent[0]).toMatchObject({ provider: 'anthropic', modelId: 'claude-sonnet-5' });
93
+ expect(sent[1]).toMatchObject({ level: 'low' });
94
+ });
95
+
96
+ test('sends nothing when the child already runs them', async () => {
97
+ const { runtime, sent } = makeRuntime({ alive: true });
98
+ await runtime.retarget({ provider: 'kenari', id: 'deepseek-v4' }, 'high');
99
+ sent.length = 0;
100
+
101
+ await runtime.retarget({ provider: 'kenari', id: 'deepseek-v4' }, 'high');
102
+
103
+ expect(sent).toHaveLength(0);
104
+ });
105
+
106
+ test('records the values for the next spawn when no child is alive', async () => {
107
+ const { runtime, sent } = makeRuntime({ alive: false });
108
+
109
+ await runtime.retarget({ provider: 'anthropic', id: 'claude-sonnet-5' }, 'auto');
110
+
111
+ expect(sent).toHaveLength(0);
112
+ // The spawn reads these; nothing was sent to a dead process.
113
+ expect((runtime as unknown as { context: { model?: unknown; thinkingLevel?: string } }).context.model)
114
+ .toEqual({ provider: 'anthropic', id: 'claude-sonnet-5' });
115
+ expect((runtime as unknown as { context: { thinkingLevel?: string } }).context.thinkingLevel).toBe('auto');
116
+ });
117
+
118
+ test('carries `auto` through to the child rather than dropping it', async () => {
119
+ const { runtime, sent } = makeRuntime({ alive: true });
120
+ await runtime.retarget(undefined, 'high');
121
+ sent.length = 0;
122
+
123
+ await runtime.retarget(undefined, 'auto');
124
+
125
+ expect(sent.map((command) => command.type)).toEqual(['set_thinking_level']);
126
+ expect(sent[0]).toMatchObject({ level: 'auto' });
127
+ });
128
+ });