Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โ™ป๏ธ refactor(heterogeneous-agent): prune lowest-value 5% of tests (#20484)

AmAzing-9dce198e54a2
diff --git a/.agents/skills/heterogeneous-agent/references/debug-workflow.md b/.agents/skills/heterogeneous-agent/references/debug-workflow.md
index bd0791fc218..953f1b52c2f 100644
--- a/.agents/skills/heterogeneous-agent/references/debug-workflow.md
+++ b/.agents/skills/heterogeneous-agent/references/debug-workflow.md
@@ -160,7 +160,6 @@ If the repo already contains useful references, inspect these first:
If you only need boundary semantics or tool persistence behavior, prefer existing adapter tests under:
- `packages/heterogeneous-agents/src/adapters/claudeCode.test.ts`
-- `packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts`
## 3. Compare Raw And Adapted Events
diff --git a/apps/desktop/src/main/controllers/__tests__/HeteroSessionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeteroSessionCtr.test.ts
index 77926879082..9fffae769ac 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeteroSessionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeteroSessionCtr.test.ts
@@ -262,16 +262,6 @@ describe('HeteroSessionCtr', () => {
expect(isUnderRoot(file, root, path.win32)).toBe(true);
});
- it('accepts a transcript under the root on POSIX separators', () => {
- expect(
- isUnderRoot(
- '/home/me/.claude/projects/proj/a.jsonl',
- '/home/me/.claude/projects',
- path.posix,
- ),
- ).toBe(true);
- });
-
it('rejects paths outside the root, including sibling prefixes', () => {
expect(isUnderRoot('/etc/passwd', '/home/me/.claude/projects', path.posix)).toBe(false);
// a sibling dir that merely shares the root as a string prefix
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 510b5987d7e..2bfb38a2642 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1651,21 +1651,6 @@ describe('HeterogeneousAgentCtr', () => {
});
});
- it.each([
- '-flag-looking-prompt',
- '--help please',
- '- dash at start',
- '-p -- mixed',
- 'normal prompt with -dash- inside',
- ])('accepts dash-containing prompt without leaking to argv: %s', async (prompt) => {
- const { cliArgs, writes } = await runSendPrompt(prompt);
-
- expect(cliArgs).not.toContain(prompt);
- expect(writes).toHaveLength(1);
- const msg = JSON.parse(writes[0].trimEnd());
- expect(msg.message.content.at(-1).text).toBe(prompt);
- });
-
it('falls back to the user Desktop when no cwd is supplied', async () => {
const { options } = await runSendPrompt('hello');
@@ -3137,83 +3122,6 @@ describe('HeterogeneousAgentCtr', () => {
expect(spawnCalls).toHaveLength(0);
});
- it('fails fast when Claude Code CLI is unavailable instead of attempting spawn', async () => {
- const detect = vi.fn().mockResolvedValue({ available: false });
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- binaryManager: { detect },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'claude-code',
- command: 'claude',
- });
-
- await expect(
- ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
- ).rejects.toThrow('Claude Code CLI was not found');
-
- expect(detect).toHaveBeenCalledWith('claude');
- expect(spawnCalls).toHaveLength(0);
- });
-
- it('fails fast with CodeBuddy install guidance when CodeBuddy is unavailable', async () => {
- const detect = vi.fn().mockResolvedValue({ available: false });
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- binaryManager: { detect },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codebuddy',
- command: 'codebuddy',
- });
-
- await expect(
- ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
- ).rejects.toThrow('CodeBuddy CLI was not found');
-
- expect(detect).toHaveBeenCalledWith('codebuddy');
- expect(spawnCalls).toHaveLength(0);
- });
-
- it('fails fast with AMP-specific install guidance when AMP is unavailable', async () => {
- const detect = vi.fn().mockResolvedValue({ available: false });
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- binaryManager: { detect },
- } as any);
- const { sessionId } = await ctr.startSession({ agentType: 'amp', command: 'amp' });
-
- await expect(
- ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
- ).rejects.toThrow('Amp CLI was not found');
-
- expect(detect).toHaveBeenCalledWith('amp');
- expect(spawnCalls).toHaveLength(0);
- });
-
- it('fails fast with OpenCode install guidance when OpenCode is unavailable', async () => {
- const detect = vi.fn().mockResolvedValue({ available: false });
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- binaryManager: { detect },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'opencode',
- command: 'opencode',
- });
-
- await expect(
- ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
- ).rejects.toThrow('OpenCode CLI was not found');
-
- expect(detect).toHaveBeenCalledWith('opencode');
- expect(spawnCalls).toHaveLength(0);
- });
-
it('fails fast when a customized Claude command is unavailable instead of checking the default detector', async () => {
execFileMock.mockImplementation(
(
@@ -5310,80 +5218,6 @@ describe('HeterogeneousAgentCtr', () => {
expect(runtimeEnd).toBeUndefined();
});
- it('delivers late final Codex stdout chunks BEFORE heteroAgentSessionComplete', async () => {
- const threadStarted = `${JSON.stringify({ thread_id: 't1', type: 'thread.started' })}\n`;
- const turnStarted = `${JSON.stringify({ type: 'turn.started' })}\n`;
- const finalMessage = `${JSON.stringify({
- item: {
- id: 'item_103',
- text: 'Final report after late stdout.',
- type: 'agent_message',
- },
- type: 'item.completed',
- })}\n`;
- const turnCompleted = `${JSON.stringify({
- type: 'turn.completed',
- usage: { input_tokens: 10, output_tokens: 5 },
- })}\n`;
-
- const proc = new EventEmitter() as any;
- const stdout = new PassThrough();
- const stderr = new PassThrough();
- proc.stdout = stdout;
- proc.stderr = stderr;
- proc.stdin = {
- end: vi.fn(),
- write: vi.fn((_chunk: any, cb?: () => void) => {
- cb?.();
- return true;
- }),
- };
- proc.kill = vi.fn();
- proc.killed = false;
- proc.__start = () => {
- setImmediate(() => {
- stdout.write(threadStarted);
- stdout.write(turnStarted);
- stderr.end();
- proc.emit('exit', 0);
- setImmediate(() => {
- stdout.write(finalMessage);
- stdout.write(turnCompleted);
- stdout.end();
- });
- });
- };
- nextFakeProc = proc;
-
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({ agentType: 'codex', command: 'codex' });
- const sendStartedAt = Date.now();
- await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
- const sendDurationMs = Date.now() - sendStartedAt;
-
- const completeIdx = broadcasts.findIndex((b) => b.channel === 'heteroAgentSessionComplete');
- const finalChunkIdx = broadcasts.findIndex(
- (b) =>
- b.channel === 'heteroAgentEvent' &&
- (b.data as any)?.event?.type === 'stream_chunk' &&
- (b.data as any)?.event?.data?.content === 'Final report after late stdout.',
- );
- const runtimeEndIdx = broadcasts.findIndex(
- (b) =>
- b.channel === 'heteroAgentEvent' && (b.data as any)?.event?.type === 'agent_runtime_end',
- );
-
- expect(completeIdx).toBeGreaterThan(-1);
- expect(finalChunkIdx).toBeGreaterThan(-1);
- expect(runtimeEndIdx).toBeGreaterThan(-1);
- expect(finalChunkIdx).toBeLessThan(completeIdx);
- expect(runtimeEndIdx).toBeLessThan(completeIdx);
- expect(sendDurationMs).toBeGreaterThanOrEqual(900);
- });
-
it('serializes AskUserQuestion bridge events behind already-queued stdout tool events', async () => {
const initLine = `${JSON.stringify({
model: 'claude-sonnet-4-6',
@@ -5640,28 +5474,6 @@ describe('HeterogeneousAgentCtr', () => {
processExitSpy.mockRestore();
});
- it('SIGINT handler unlinks pending intervention temp configs (Ctrl-C path)', async () => {
- const electron = (await import('electron')) as any;
- electron.app.on.mockClear();
- const processOnSpy = vi.spyOn(process, 'on').mockImplementation(() => process);
- const processExitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
-
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const file = await seedPendingIntervention(ctr, 'opSigint');
-
- ctr.afterAppReady();
- const sigint = captureRegisteredHandler(processOnSpy, 'SIGINT');
- sigint();
-
- await expect(access(file)).rejects.toThrow();
-
- processOnSpy.mockRestore();
- processExitSpy.mockRestore();
- });
-
it('cleanup is idempotent โ€” already-deleted files do not throw', async () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
index 83153b4e856..4a6d871b41a 100644
--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
@@ -238,6 +238,3 @@ export const cliAgentBinaries: BinarySpec[] = [
qwenCodeBinary,
aiderBinary,
];
-
-export const listHeterogeneousCliBinaryTypes = (): LocalHeterogeneousAgentType[] =>
- Object.keys(heterogeneousCliAgentBinaries) as LocalHeterogeneousAgentType[];
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
index 0ef65d04a25..0c3e111de8d 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
@@ -5,8 +5,8 @@ import { claudeCodeDriver } from './drivers/claudeCode';
import { codeBuddyDriver } from './drivers/codeBuddy';
import { codexDriver } from './drivers/codex';
import { cursorDriver } from './drivers/cursor';
-import { droidDriver } from './drivers/droid';
import { devinDriver } from './drivers/devin';
+import { droidDriver } from './drivers/droid';
import { grokBuildDriver } from './drivers/grokBuild';
import { kimiCodeDriver } from './drivers/kimiCode';
import { opencodeDriver } from './drivers/opencode';
@@ -40,6 +40,3 @@ export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAge
return driver;
};
-
-export const listHeterogeneousAgentDriverTypes = (): LocalHeterogeneousAgentType[] =>
- Object.keys(heterogeneousAgentDrivers) as LocalHeterogeneousAgentType[];
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.ts
deleted file mode 100644
index 7c92e6aa256..00000000000
--- a/apps/desktop/src/main/modules/heterogeneousAgent/registryConsistency.test.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { HETEROGENEOUS_AGENT_CONFIGS, listLocalAgentTypes } from '@lobechat/heterogeneous-agents';
-import { describe, expect, it } from 'vitest';
-
-import { listHeterogeneousCliBinaryTypes } from '../binaries/cliAgentBinaries';
-import { listHeterogeneousAgentDriverTypes } from '.';
-
-describe('heterogeneous agent registry consistency', () => {
- it('keeps every executable registry aligned with the descriptor catalog', () => {
- const descriptorTypes = HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted();
-
- expect(listLocalAgentTypes().toSorted()).toEqual(descriptorTypes);
- expect(listHeterogeneousAgentDriverTypes().toSorted()).toEqual(descriptorTypes);
- expect(listHeterogeneousCliBinaryTypes().toSorted()).toEqual(descriptorTypes);
- });
-});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts
deleted file mode 100644
index 6e1e923c79c..00000000000
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-/**
- * End-to-end integration test for ClaudeCodeAdapter.
- *
- * Simulates a realistic Claude Code CLI stream-json session with multiple steps:
- * init โ†’ thinking โ†’ text โ†’ tool_use โ†’ tool_result โ†’ new step โ†’ text โ†’ result
- *
- * Verifies the complete event pipeline that the executor would consume.
- */
-import { describe, expect, it } from 'vitest';
-
-import { ClaudeCodeAdapter } from './claudeCode';
-
-/**
- * Simulate a realistic multi-step Claude Code session.
- *
- * Scenario: CC reads a file, then writes a fix in a second LLM turn.
- */
-const simulatedStream = [
- // 1. System init
- {
- model: 'claude-sonnet-4-6',
- session_id: 'sess_abc123',
- subtype: 'init',
- tools: ['Read', 'Write', 'Bash'],
- type: 'system',
- },
- // 2. First assistant turn โ€” thinking + tool_use (Read)
- {
- message: {
- content: [
- { thinking: 'Let me read the file first to understand the issue.', type: 'thinking' },
- ],
- id: 'msg_01',
- model: 'claude-sonnet-4-6',
- role: 'assistant',
- usage: { input_tokens: 500, output_tokens: 100 },
- },
- type: 'assistant',
- },
- {
- message: {
- content: [
- { id: 'toolu_read_1', input: { file_path: '/src/app.ts' }, name: 'Read', type: 'tool_use' },
- ],
- id: 'msg_01',
- model: 'claude-sonnet-4-6',
- role: 'assistant',
- usage: { input_tokens: 500, output_tokens: 150 },
- },
- type: 'assistant',
- },
- // 3. Tool result (user event)
- {
- message: {
- content: [
- {
- content: 'export function add(a: number, b: number) {\n return a - b; // BUG\n}',
- tool_use_id: 'toolu_read_1',
- type: 'tool_result',
- },
- ],
- role: 'user',
- },
- type: 'user',
- },
- // 4. Second assistant turn โ€” NEW message.id = new step
- {
- message: {
- content: [
- { thinking: 'Found the bug: subtract instead of add. Let me fix it.', type: 'thinking' },
- ],
- id: 'msg_02',
- model: 'claude-sonnet-4-6',
- role: 'assistant',
- usage: { input_tokens: 800, output_tokens: 80 },
- },
- type: 'assistant',
- },
- {
- message: {
- content: [
- {
- id: 'toolu_write_1',
- input: {
- content: 'export function add(a: number, b: number) {\n return a + b;\n}',
- file_path: '/src/app.ts',
- },
- name: 'Write',
- type: 'tool_use',
- },
- ],
- id: 'msg_02',
- model: 'claude-sonnet-4-6',
- role: 'assistant',
- usage: { input_tokens: 800, output_tokens: 200 },
- },
- type: 'assistant',
- },
- // 5. Write tool result
- {
- message: {
- content: [
- {
- content: 'File written successfully.',
- tool_use_id: 'toolu_write_1',
- type: 'tool_result',
- },
- ],
- role: 'user',
- },
- type: 'user',
- },
- // 6. Third assistant turn โ€” final text response, NEW message.id
- {
- message: {
- content: [
- {
- text: 'I fixed the bug in `/src/app.ts`. The `add` function was subtracting instead of adding.',
- type: 'text',
- },
- ],
- id: 'msg_03',
- model: 'claude-sonnet-4-6',
- role: 'assistant',
- usage: { input_tokens: 1000, output_tokens: 30 },
- },
- type: 'assistant',
- },
- // 7. Final result
- {
- is_error: false,
- result: 'I fixed the bug in `/src/app.ts`.',
- type: 'result',
- },
-];
-
-describe('ClaudeCodeAdapter E2E', () => {
- it('produces correct event sequence for a multi-step session', () => {
- const adapter = new ClaudeCodeAdapter();
- const allEvents = simulatedStream.flatMap((line) => adapter.adapt(line));
-
- // Extract event types for sequence verification
- const types = allEvents.map((e) => e.type);
-
- // 1. Should start with stream_start (from init)
- expect(types[0]).toBe('stream_start');
-
- // 2. Should have content chunks (thinking, tool_use, text)
- const textChunks = allEvents.filter(
- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'text',
- );
- expect(textChunks.length).toBeGreaterThanOrEqual(1);
-
- const reasoningChunks = allEvents.filter(
- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'reasoning',
- );
- expect(reasoningChunks.length).toBe(2); // Two thinking blocks
-
- const toolChunks = allEvents.filter(
- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
- );
- expect(toolChunks.length).toBe(2); // Read + Write
-
- // 3. Tool lifecycle: tool_start โ†’ tool_result โ†’ tool_end for each tool
- const toolStarts = allEvents.filter((e) => e.type === 'tool_start');
- const toolResults = allEvents.filter((e) => e.type === 'tool_result');
- const toolEnds = allEvents.filter((e) => e.type === 'tool_end');
-
- expect(toolStarts.length).toBe(2);
- expect(toolResults.length).toBe(2);
- expect(toolEnds.length).toBe(2);
-
- // Verify tool call IDs match
- expect(toolResults[0].data.toolCallId).toBe('toolu_read_1');
- expect(toolResults[1].data.toolCallId).toBe('toolu_write_1');
-
- // 4. Should have step boundaries (stream_end + stream_start with newStep)
- // First assistant after init does NOT trigger newStep, only subsequent message.id changes do
- const newStepStarts = allEvents.filter(
- (e) => e.type === 'stream_start' && e.data?.newStep === true,
- );
- // 2 boundaries: msg_01 โ†’ msg_02, msg_02 โ†’ msg_03
- expect(newStepStarts.length).toBe(2);
-
- // 5. This fixture has no `stream_event` records โ€” i.e. BATCH mode, like the
- // `lh hetero exec` device / sandbox path. There is no `message_delta` to
- // own per-turn usage, so the adapter emits turn_metadata from each
- // `assistant` event that carries `message.usage` (authoritative in batch
- // mode, not a stale echo). The fixture has 5 such assistant events.
- // In partial mode this path is suppressed โ€” see claudeCode.test.ts.
- const metaEvents = allEvents.filter(
- (e) => e.type === 'step_complete' && e.data?.phase === 'turn_metadata',
- );
- expect(metaEvents.length).toBe(5);
- // All carry the canonical model + provider.
- expect(metaEvents.every((e) => e.data.model === 'claude-sonnet-4-6')).toBe(true);
- expect(metaEvents.every((e) => e.data.provider === 'claude-code')).toBe(true);
- // Final turn's authoritative usage (msg_03: input 1000 + output 30).
- expect(metaEvents.at(-1)!.data.usage.totalTokens).toBe(1030);
-
- const resultUsage = allEvents.filter(
- (e) => e.type === 'step_complete' && e.data?.phase === 'result_usage',
- );
- // No `result.usage` in this fixture, so none emitted either.
- expect(resultUsage.length).toBe(0);
-
- // 6. Should end with visible_output_end + agent_runtime_end (from result)
- const lastTwo = types.slice(-2);
- expect(lastTwo).toEqual(['visible_output_end', 'agent_runtime_end']);
-
- // 7. Session ID should be captured
- expect(adapter.sessionId).toBe('sess_abc123');
- });
-
- it('correctly extracts tool result content', () => {
- const adapter = new ClaudeCodeAdapter();
- const allEvents = simulatedStream.flatMap((line) => adapter.adapt(line));
-
- const toolResults = allEvents.filter((e) => e.type === 'tool_result');
-
- // First tool result: file content from Read
- expect(toolResults[0].data.content).toContain('return a - b');
- expect(toolResults[0].data.isError).toBe(false);
-
- // Second tool result: write confirmation
- expect(toolResults[1].data.content).toBe('File written successfully.');
- expect(toolResults[1].data.isError).toBe(false);
- });
-
- it('tracks step boundaries via stepIndex', () => {
- const adapter = new ClaudeCodeAdapter();
- const allEvents = simulatedStream.flatMap((line) => adapter.adapt(line));
-
- // Collect unique stepIndex values
- const stepIndices = [...new Set(allEvents.map((e) => e.stepIndex))];
- // Should have at least 3 steps (init step + msg_01 step + msg_02 step + msg_03 step)
- expect(stepIndices.length).toBeGreaterThanOrEqual(3);
-
- // stepIndex should be monotonically non-decreasing
- for (let i = 1; i < allEvents.length; i++) {
- expect(allEvents[i].stepIndex).toBeGreaterThanOrEqual(allEvents[i - 1].stepIndex);
- }
- });
-
- it('handles error result correctly in multi-step session', () => {
- const adapter = new ClaudeCodeAdapter();
-
- // Init + one assistant turn + error result
- adapter.adapt(simulatedStream[0]); // init
- adapter.adapt(simulatedStream[1]); // thinking
-
- const events = adapter.adapt({
- is_error: true,
- result: 'Permission denied: cannot write to /etc/hosts',
- type: 'result',
- });
-
- const error = events.find((e) => e.type === 'error');
- expect(error).toBeDefined();
- expect(error!.data.message).toBe('Permission denied: cannot write to /etc/hosts');
-
- // Should also have stream_end before error
- expect(events[0].type).toBe('stream_end');
- });
-
- it('no pending tools after full session', () => {
- const adapter = new ClaudeCodeAdapter();
- simulatedStream.forEach((line) => adapter.adapt(line));
-
- // flush should return empty โ€” all tools were resolved via tool_result
- const flushEvents = adapter.flush();
- expect(flushEvents).toHaveLength(0);
- });
-});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 2c23d4e3d3e..82239f2c484 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -433,54 +433,6 @@ describe('ClaudeCodeAdapter', () => {
expect(events[2].data).toMatchObject({ code: 'overloaded', message: rawError });
});
- it('replays a real session that streamed a turn then overloaded โ†’ overloaded + clears echo', () => {
- // Faithful transport-layer replay of a captured CC session shape: init โ†’
- // a streamed assistant turn โ†’ the exact upstream throttle the user hit
- // (api_error_status 429 + the "not your usage limit" wording, alongside a
- // generic rate_limit_event with no reset window). This is how the
- // overloaded guide is driven without waiting on a real upstream outage.
- const adapter = new ClaudeCodeAdapter();
- const rawError =
- 'API Error: Server is temporarily limiting requests (not your usage limit) ยท Rate limited';
-
- adapter.adapt({
- model: 'claude-opus-4-8',
- session_id: 'sess_replay',
- subtype: 'init',
- type: 'system',
- });
- // A turn that already streamed content before the throttle landed.
- adapter.adapt({
- message: {
- content: [{ text: 'Let me read loadEvidence and the runner', type: 'text' }],
- id: 'msg_replay',
- role: 'assistant',
- },
- type: 'assistant',
- });
- adapter.adapt({
- rate_limit_info: { isUsingOverage: false, status: 'rejected' },
- type: 'rate_limit_event',
- });
-
- const events = adapter.adapt({
- api_error_status: 429,
- is_error: true,
- result: rawError,
- type: 'result',
- });
-
- const errorEvent = events.find((e) => e.type === 'error');
- expect(errorEvent?.data).toMatchObject({
- agentType: 'claude-code',
- // The UI keys auto-retry on this exact code; clearEchoedContent wipes
- // the half-streamed turn so the guide stands in for the whole bubble.
- clearEchoedContent: true,
- code: 'overloaded',
- message: rawError,
- });
- });
-
it('classifies a user quota limit from rateLimitType alone (no resetsAt)', () => {
const adapter = new ClaudeCodeAdapter();
const rawError = 'API Error: 429 ยท Rate limited';
@@ -1439,30 +1391,6 @@ describe('ClaudeCodeAdapter', () => {
expect(result!.data.content).toBe('[Image: image]');
expect(result!.data.pluginState.images).toEqual([{ data: 'AAAA', mediaType: 'image' }]);
});
-
- it('does not set pluginState.images for a text-only tool_result', () => {
- const adapter = new ClaudeCodeAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 'r1', input: { file_path: 'x.ts' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
-
- const events = adapter.adapt({
- message: {
- content: [{ content: 'plain text', tool_use_id: 'r1', type: 'tool_result' }],
- role: 'user',
- },
- type: 'user',
- });
-
- const result = events.find((e) => e.type === 'tool_result');
- expect(result!.data.content).toBe('plain text');
- expect(result!.data.pluginState).toBeUndefined();
- });
});
describe('TodoWrite pluginState synthesis', () => {
@@ -2013,46 +1941,6 @@ describe('ClaudeCodeAdapter', () => {
// Subagent task tools are out-of-scope for the main todo plan UI.
expect(result!.data.pluginState).toBeUndefined();
});
-
- it('mixed TodoWrite + Task* flows are independent (TodoWrite path still wins on its own call)', () => {
- const adapter = new ClaudeCodeAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
-
- // First, a TaskCreate snapshot.
- driveTaskCreate(
- adapter,
- { description: 'A', subject: 'A' },
- 'tu_create_1',
- 'Task #1 created successfully: A',
- 'msg_1',
- );
-
- // Then a TodoWrite from a legacy / resumed session โ€” should produce
- // its own pluginState from its own input, NOT the Task accumulator.
- adapter.adapt({
- message: {
- id: 'msg_2',
- content: [
- {
- id: 'tu_todo',
- input: { todos: [{ activeForm: 'Doing X', content: 'X', status: 'completed' }] },
- name: 'TodoWrite',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
- const todoEvents = adapter.adapt({
- message: {
- content: [{ content: 'ok', tool_use_id: 'tu_todo', type: 'tool_result' }],
- role: 'user',
- },
- type: 'user',
- });
- const todoState = todoEvents.find((e) => e.type === 'tool_result')!.data.pluginState;
- expect(todoState.todos.items).toEqual([{ status: 'completed', text: 'X' }]);
- });
});
describe('multi-step execution (message.id boundary)', () => {
@@ -2456,14 +2344,6 @@ describe('ClaudeCodeAdapter', () => {
expect(events[0].data.result).toMatchObject({ success: false });
});
- it('returns empty array when no pending tools', () => {
- const adapter = new ClaudeCodeAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
-
- const events = adapter.flush();
- expect(events).toHaveLength(0);
- });
-
it('clears pending tools after flush', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
@@ -2618,7 +2498,7 @@ describe('ClaudeCodeAdapter', () => {
expect(starts[0].data.toolCalling.id).toBe('t2');
});
- it('starts a fresh accumulator when message.id advances (new LLM turn)', () => {
+ it('dedupes when CC echoes a tool_use block with the same id', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
@@ -2630,22 +2510,24 @@ describe('ClaudeCodeAdapter', () => {
type: 'assistant',
});
- const events = adapter.adapt({
+ // Same tool_use id re-sent โ€” cumulative list must not duplicate it,
+ // and tool_start must not fire again.
+ const e2 = adapter.adapt({
message: {
- id: 'msg_2',
- content: [{ id: 't2', input: {}, name: 'Bash', type: 'tool_use' }],
+ id: 'msg_1',
+ content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
},
type: 'assistant',
});
- const chunk = events.find(
+ const chunk = e2.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
);
- // Different message.id โ€” the new assistant's tools[] must NOT contain t1
- expect(chunk!.data.toolsCalling.map((t: any) => t.id)).toEqual(['t2']);
+ expect(chunk!.data.toolsCalling.map((t: any) => t.id)).toEqual(['t1']);
+ expect(e2.filter((e) => e.type === 'tool_start')).toHaveLength(0);
});
- it('dedupes when CC echoes a tool_use block with the same id', () => {
+ it('starts a fresh accumulator when message.id advances (new LLM turn)', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
@@ -2657,21 +2539,19 @@ describe('ClaudeCodeAdapter', () => {
type: 'assistant',
});
- // Same tool_use id re-sent โ€” cumulative list must not duplicate it,
- // and tool_start must not fire again.
- const e2 = adapter.adapt({
+ const events = adapter.adapt({
message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
+ id: 'msg_2',
+ content: [{ id: 't2', input: {}, name: 'Bash', type: 'tool_use' }],
},
type: 'assistant',
});
- const chunk = e2.find(
+ const chunk = events.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
);
- expect(chunk!.data.toolsCalling.map((t: any) => t.id)).toEqual(['t1']);
- expect(e2.filter((e) => e.type === 'tool_start')).toHaveLength(0);
+ // Different message.id โ€” the new assistant's tools[] must NOT contain t1
+ expect(chunk!.data.toolsCalling.map((t: any) => t.id)).toEqual(['t2']);
});
});
@@ -3365,43 +3245,6 @@ describe('ClaudeCodeAdapter', () => {
});
});
- it('extracts spawnMetadata from the `Agent` spawn-tool variant too (not just Task)', () => {
- // Real CC traces emit `Agent` for general-purpose subagents, not just
- // `Task` โ€” the adapter should cache input for ANY main-agent tool and
- // build spawnMetadata off whichever spawn-tool variant was used.
- const adapter = new ClaudeCodeAdapter();
- adapter.adapt(init);
- adapter.adapt(
- mainAssistant('msg_main', {
- id: 'toolu_agent',
- input: {
- description: 'lookup the pwd',
- prompt: 'run pwd and report it back',
- subagent_type: 'general-purpose',
- },
- name: 'Agent',
- type: 'tool_use',
- }),
- );
-
- const first = adapter.adapt(
- subAgent('msg_sub_1', 'toolu_agent', {
- id: 'toolu_child',
- input: {},
- name: 'Bash',
- type: 'tool_use',
- }),
- );
- const firstChunk = first.find(
- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
- );
- expect(firstChunk!.data.subagent.spawnMetadata).toEqual({
- description: 'lookup the pwd',
- prompt: 'run pwd and report it back',
- subagentType: 'general-purpose',
- });
- });
-
it('does NOT stamp subagent context on non-subagent (main-agent) tool_uses', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt(init);
@@ -3787,38 +3630,6 @@ describe('ClaudeCodeAdapter', () => {
).toBeUndefined();
});
- it('does NOT tag turns that follow a user/tool_result event', () => {
- const adapter = new ClaudeCodeAdapter();
- init(adapter);
-
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],
- id: 'msg_01',
- },
- type: 'assistant',
- });
- adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
- adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
- adapter.adapt(ccMessageStart('msg_02')); // confirmation (no signal)
-
- // LLM emits Bash mid-task โ†’ Bash's tool_result arrives โ†’ next turn
- // is a natural follow-up to Bash, NOT a Monitor callback.
- adapter.adapt({
- message: {
- content: [{ id: 'toolu_bash', input: {}, name: 'Bash', type: 'tool_use' }],
- id: 'msg_03',
- },
- type: 'assistant',
- });
- adapter.adapt(ccUser('toolu_bash', 'bash ok'));
-
- const ev = adapter.adapt(ccMessageStart('msg_04'));
- expect(
- ev.find((e) => e.type === 'stream_start' && e.data?.newStep)!.data.externalSignal,
- ).toBeUndefined();
- });
-
it('does NOT trigger from subagent inner user events', () => {
const adapter = new ClaudeCodeAdapter();
init(adapter);
diff --git a/packages/heterogeneous-agents/src/adapters/codeBuddy.test.ts b/packages/heterogeneous-agents/src/adapters/codeBuddy.test.ts
index 40d6dc09aa5..90fb169061f 100644
--- a/packages/heterogeneous-agents/src/adapters/codeBuddy.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/codeBuddy.test.ts
@@ -27,66 +27,6 @@ describe('CodeBuddyAdapter', () => {
expect(adapter.sessionId).toBe('cb-session-1');
});
- it('keeps CodeBuddy identity on tool and usage events', () => {
- const adapter = new CodeBuddyAdapter();
- adapter.adapt({ session_id: 'cb-session-1', subtype: 'init', type: 'system' });
-
- const events = adapter.adapt({
- message: {
- content: [{ id: 'tool-1', input: { command: 'pwd' }, name: 'Bash', type: 'tool_use' }],
- id: 'message-1',
- model: 'gpt-5.4',
- usage: { input_tokens: 4, output_tokens: 2 },
- },
- type: 'assistant',
- });
-
- const tool = events.find((event) => event.type === 'stream_chunk');
- const usage = events.find((event) => event.type === 'step_complete');
- expect(tool?.data.toolsCalling[0]).toMatchObject({ identifier: 'codebuddy' });
- expect(usage?.data).toMatchObject({ model: 'gpt-5.4', provider: 'codebuddy' });
- });
-
- it('maps text, reasoning, tool results, and a successful terminal result', () => {
- const adapter = new CodeBuddyAdapter();
- adapter.adapt({ session_id: 'cb-session-1', subtype: 'init', type: 'system' });
-
- const assistantEvents = adapter.adapt({
- message: {
- content: [
- { thinking: 'checking', type: 'thinking' },
- { text: 'Running pwd', type: 'text' },
- { id: 'tool-1', input: { command: 'pwd' }, name: 'Bash', type: 'tool_use' },
- ],
- id: 'message-1',
- model: 'gpt-5.4',
- },
- type: 'assistant',
- });
- expect(assistantEvents).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ data: expect.objectContaining({ reasoning: 'checking' }) }),
- expect.objectContaining({ data: expect.objectContaining({ content: 'Running pwd' }) }),
- ]),
- );
-
- const toolEvents = adapter.adapt({
- message: {
- content: [{ content: '/workspace', tool_use_id: 'tool-1', type: 'tool_result' }],
- },
- type: 'user',
- });
- expect(toolEvents.map((event) => event.type)).toEqual(['tool_result', 'tool_end']);
- expect(toolEvents[0].data).toMatchObject({ content: '/workspace', toolCallId: 'tool-1' });
-
- const resultEvents = adapter.adapt({ is_error: false, result: 'done', type: 'result' });
- expect(resultEvents.map((event) => event.type)).toEqual([
- 'stream_end',
- 'visible_output_end',
- 'agent_runtime_end',
- ]);
- });
-
it('keeps partial reasoning and text snapshots with different item ids in one turn', () => {
const adapter = new CodeBuddyAdapter();
const events = [
diff --git a/packages/heterogeneous-agents/src/adapters/qoder.test.ts b/packages/heterogeneous-agents/src/adapters/qoder.test.ts
index b624f497913..2c75a430b54 100644
--- a/packages/heterogeneous-agents/src/adapters/qoder.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/qoder.test.ts
@@ -45,37 +45,6 @@ describe('QoderAdapter', () => {
).toEqual(['stream_end', 'visible_output_end', 'agent_runtime_end']);
});
- it('maps partial text and thinking deltas', () => {
- const adapter = new QoderAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- event: { message: { id: 'msg-1', model: 'qoder-default' }, type: 'message_start' },
- type: 'stream_event',
- });
-
- const text = adapter.adapt({
- event: {
- delta: { text: 'Hel', type: 'text_delta' },
- index: 0,
- type: 'content_block_delta',
- },
- type: 'stream_event',
- });
- const thinking = adapter.adapt({
- event: {
- delta: { thinking: 'reasoning', type: 'thinking_delta' },
- index: 0,
- type: 'content_block_delta',
- },
- type: 'stream_event',
- });
-
- expect(text[0]).toMatchObject({ data: { chunkType: 'text', content: 'Hel' } });
- expect(thinking[0]).toMatchObject({
- data: { chunkType: 'reasoning', reasoning: 'reasoning' },
- });
- });
-
it('normalizes tool calls, results, and parent lineage to Qoder', () => {
const adapter = new QoderAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
@@ -119,159 +88,6 @@ describe('QoderAdapter', () => {
});
});
- it('preserves synthesized todo state from Qoder Task tools', () => {
- const adapter = new QoderAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- content: [
- {
- id: 'task-create-1',
- input: {
- activeForm: 'Adding Qoder todo support',
- description: 'Keep the synthesized task state for the UI.',
- subject: 'Add Qoder todo support',
- },
- name: 'TaskCreate',
- type: 'tool_use',
- },
- ],
- id: 'msg-task-create',
- },
- type: 'assistant',
- });
-
- const events = adapter.adapt({
- message: {
- content: [
- {
- content: 'Task #1 created successfully: Add Qoder todo support',
- tool_use_id: 'task-create-1',
- type: 'tool_result',
- },
- ],
- role: 'user',
- },
- type: 'user',
- });
- const pluginState = {
- todos: {
- items: [{ id: '1', status: 'todo', text: 'Add Qoder todo support' }],
- updatedAt: expect.any(String),
- },
- };
- expect(events.find((event) => event.type === 'tool_result')?.data.pluginState).toEqual(
- pluginState,
- );
- expect(events.find((event) => event.type === 'tool_end')?.data.result.state).toEqual(
- pluginState,
- );
-
- adapter.adapt({
- message: {
- content: [
- {
- id: 'task-update-1',
- input: { status: 'completed', taskId: '1' },
- name: 'TaskUpdate',
- type: 'tool_use',
- },
- ],
- id: 'msg-task-update',
- },
- type: 'assistant',
- });
- const updatedEvents = adapter.adapt({
- message: {
- content: [
- {
- content: 'Updated task #1 status',
- tool_use_id: 'task-update-1',
- type: 'tool_result',
- },
- ],
- role: 'user',
- },
- type: 'user',
- });
- const updatedPluginState = {
- todos: {
- items: [{ id: '1', status: 'completed', text: 'Add Qoder todo support' }],
- updatedAt: expect.any(String),
- },
- };
- expect(updatedEvents.find((event) => event.type === 'tool_result')?.data.pluginState).toEqual(
- updatedPluginState,
- );
- expect(updatedEvents.find((event) => event.type === 'tool_end')?.data.result.state).toEqual(
- updatedPluginState,
- );
- });
-
- it('preserves Qoder WebSearch structured sources on tool_result and tool_end', () => {
- const adapter = new QoderAdapter();
- adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- content: [
- {
- id: 'web-search-1',
- input: { query: 'TradingView copper futures symbol ticker' },
- name: 'WebSearch',
- type: 'tool_use',
- },
- ],
- id: 'msg-search',
- },
- type: 'assistant',
- });
-
- const events = adapter.adapt({
- message: {
- content: [
- {
- content: 'Web search results for query: "TradingView copper futures symbol ticker"',
- tool_use_id: 'web-search-1',
- type: 'tool_result',
- },
- ],
- role: 'user',
- },
- tool_use_result: {
- durationSeconds: 2.938580792,
- query: 'TradingView copper futures symbol ticker',
- results: [
- {
- hostname: 'www.tradingview.com',
- link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',
- snippet: 'The current price of Copper Futures is 6.7190 USD',
- title: 'HG1! Charts and Quotes - Futures',
- },
- ],
- },
- type: 'user',
- });
-
- const result = events.find((event) => event.type === 'tool_result');
- const end = events.find((event) => event.type === 'tool_end');
- expect(result?.data.pluginState).toEqual({
- durationSeconds: 2.938580792,
- query: 'TradingView copper futures symbol ticker',
- results: [
- {
- hostname: 'www.tradingview.com',
- link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',
- snippet: 'The current price of Copper Futures is 6.7190 USD',
- title: 'HG1! Charts and Quotes - Futures',
- },
- ],
- });
- expect(end?.data).toMatchObject({
- payload: { toolCalling: { identifier: 'qoder' } },
- result: { state: result?.data.pluginState, success: true },
- });
- });
-
it('emits one structured Qoder auth error even though Qoder exits successfully', () => {
const adapter = new QoderAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
diff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts
index f969be0cb4a..de302e09333 100644
--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts
+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts
@@ -172,16 +172,6 @@ describe('AskUserBridge', () => {
expect(onProgress).toHaveBeenCalledTimes(3);
drain.stop();
});
-
- it('skips onProgress entirely when not provided', async () => {
- const bridge = new AskUserBridge('op-1');
- const drain = drainEvents(bridge);
- // No onProgress โ€” just verify timeout still works without it.
- const pending = bridge.pending({ arguments: {} }, { timeoutMs: 50 });
- vi.advanceTimersByTime(60);
- await expect(pending).resolves.toMatchObject({ cancelled: true });
- drain.stop();
- });
});
describe('response event mirror', () => {
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 35985735b40..5267e412ba6 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -381,14 +381,6 @@ describe('main agent reducer', () => {
expect(ofKind(r.intents, 'createAssistant')[0]).toMatchObject({ parentId: 'SIG' });
});
- it('falls back to the current assistant only before any tool exists', () => {
- const { steps } = run([textEvent('hi'), newStepEvent()]); // no tool ever seen
- expect(ofKind(steps[1], 'createAssistant')[0]).toMatchObject({
- messageId: 'msg_1',
- parentId: 'A0',
- });
- });
-
it('resolves a main tool_result via the global tool map', () => {
const { steps } = run([
toolsEvent([tool('t1')]),
diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts
index f4d9b764d23..fc4cc5416b5 100644
--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts
+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts
@@ -10,25 +10,6 @@ describe('buildHeteroExecStdinPayload', () => {
expect(JSON.parse(payload)).toBe('hello');
});
- it('builds a content-block array with systemContext first', () => {
- const payload = buildHeteroExecStdinPayload({ prompt: 'hello', systemContext: 'ctx' });
- expect(JSON.parse(payload)).toEqual([
- { text: 'ctx', type: 'text' },
- { text: 'hello', type: 'text' },
- ]);
- });
-
- it('appends image blocks after the prompt', () => {
- const payload = buildHeteroExecStdinPayload({
- imageList: [{ id: 'file-1', url: 'https://x/a.png' }],
- prompt: 'look at this',
- });
- expect(JSON.parse(payload)).toEqual([
- { text: 'look at this', type: 'text' },
- { source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },
- ]);
- });
-
it('orders systemContext, prompt, then images', () => {
const payload = buildHeteroExecStdinPayload({
imageList: [{ id: 'file-1', url: 'https://x/a.png' }, { url: 'https://x/b.jpg' }],
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
index 7a550aa2797..a13760ac468 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
@@ -106,18 +106,6 @@ describe('fetchClaudeCodeQuota', () => {
expect(result.status).toBe('ok');
});
- it('ignores disabled routing flags and falls through to the credential lookup', async () => {
- setPlatform('linux');
- vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
- vi.mocked(fetch).mockResolvedValue(okUsageResponse({ five_hour: { utilization: 10 } }));
-
- const result = await fetchClaudeCodeQuota({
- env: { CLAUDE_CODE_USE_BEDROCK: '0', CLAUDE_CODE_USE_VERTEX: 'false' },
- });
-
- expect(result.status).toBe('ok');
- });
-
it('reports missing credentials when neither keychain nor files hold a login', async () => {
setPlatform('darwin');
diff --git a/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts
index 03a9a3e65fe..a68c8b6f1c5 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/kimiCodeQuota.test.ts
@@ -305,17 +305,6 @@ describe('fetchKimiCodeQuota', () => {
expect(result.error).toContain('ECONNREFUSED');
});
- it('surfaces a usage API 500 as an error', async () => {
- vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
- vi.mocked(fetch).mockResolvedValue({ ok: false, status: 500 } as Response);
-
- const result = await fetchKimiCodeQuota();
-
- expect(result).toMatchObject({ status: 'error' });
- expect(result.reason).toBeUndefined();
- expect(result.error).toContain('500');
- });
-
it('surfaces a usage API 401 as an error, not a credential state', async () => {
vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
vi.mocked(fetch).mockResolvedValue({ ok: false, status: 401 } as Response);
diff --git a/packages/heterogeneous-agents/src/quota/kimiCode.test.ts b/packages/heterogeneous-agents/src/quota/kimiCode.test.ts
index e05943db5a8..5cee3c8919d 100644
--- a/packages/heterogeneous-agents/src/quota/kimiCode.test.ts
+++ b/packages/heterogeneous-agents/src/quota/kimiCode.test.ts
@@ -18,18 +18,6 @@ describe('Kimi Code persisted quota projection', () => {
expect(projectWindows(readings)[2].windowSeconds).toBe(43_200 * 60);
});
- it('maps each window to its limit type with an explicit window length', () => {
- const readings = kimiCodeQuotaReadings(windows, now);
-
- expect(readings.map((reading) => [reading.limitType, reading.windowMinutes])).toEqual([
- ['session', 300],
- ['weekly_all', 10_080],
- ['month_total', 43_200],
- ['month_code', 43_200],
- ]);
- expect(readings.every((reading) => reading.scopeKey === '')).toBe(true);
- });
-
it('omits windows the provider did not report', () => {
const readings = kimiCodeQuotaReadings(
{ monthly: null, monthlyCode: null, session: windows.session, weekly: null },
diff --git a/packages/heterogeneous-agents/src/quota/quota.test.ts b/packages/heterogeneous-agents/src/quota/quota.test.ts
index 8713f7b658e..ddd7cfb90ba 100644
--- a/packages/heterogeneous-agents/src/quota/quota.test.ts
+++ b/packages/heterogeneous-agents/src/quota/quota.test.ts
@@ -41,14 +41,6 @@ describe('computeTurnCostUsd', () => {
expect(cost).toBeCloseTo(0.3, 6);
});
- it('captures the Fable-vs-Opus price ratio that proved the unit', () => {
- // same token shape, Fable is 2x Opus โ†’ cost is 2x
- const usage = { input: 500_000, output: 200_000 };
- const opus = computeTurnCostUsd(usage, { input: 5, output: 25 });
- const fable = computeTurnCostUsd(usage, { input: 10, output: 50 });
- expect(fable / opus).toBeCloseTo(2, 6);
- });
-
it('totalTokens sums all classes', () => {
expect(totalTokens({ cacheRead: 3, input: 1, output: 2 })).toBe(6);
});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts
index 80538c31a05..5e5be0f09c8 100644
--- a/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts
+++ b/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts
@@ -139,13 +139,6 @@ describe('PiRpcClient', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
- it('captures the raw handshake before the ready client is returned', async () => {
- const raw: Buffer[] = [];
- const { client } = await createReadyClient({ onRawStdout: (chunk) => raw.push(chunk) });
- expect(JSON.parse(Buffer.concat(raw).toString()).command).toBe('get_state');
- await client.close();
- });
-
it('bounds abort even when ordinary command timeouts are disabled', async () => {
const { client } = await createReadyClient({ requestTimeoutMs: false });
vi.useFakeTimers();
@@ -321,16 +314,6 @@ describe('PiRpcClient', () => {
await client.close();
});
- it('rejects commands when the process dies before responding', async () => {
- const { child, client, stdout } = await createReadyClient();
- const request = client.command({ type: 'get_messages' });
- stdout.end();
- child.emit('close', 1, null);
- await expect(request).rejects.toThrow(PiRpcConnectionError);
- await expect(request).rejects.toThrow(/exited unexpectedly/);
- await client.close();
- });
-
it('hard-fails the handshake when get_state never answers', async () => {
const { child } = createProcess();
spawnMock.mockReturnValue(child);
@@ -347,20 +330,4 @@ describe('PiRpcClient', () => {
await expect(started).rejects.toThrow(PiRpcConnectionError);
await expect(started).rejects.toThrow(/handshake/);
});
-
- it('gracefully closes via stdin EOF and escalates only when exit stalls', async () => {
- Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' });
- const { child, client } = await createReadyClient({ closeGraceMs: 50 });
- vi.spyOn(process, 'kill').mockImplementation(() => {
- setTimeout(() => child.emit('close', null, 'SIGTERM'), 1);
- return true;
- });
- // Override the simulated clean-exit so the process lingers.
- child.stdin.end = vi.fn(() => {
- /* no exit */
- });
- await client.close();
- // SIGTERM escalation attempted after the grace window.
- expect(process.kill).toHaveBeenCalledWith(-child.pid, 'SIGTERM');
- });
});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts
index b46ad17043a..2392d3ba308 100644
--- a/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts
+++ b/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts
@@ -510,55 +510,4 @@ describe('PiRpcSession', () => {
);
await session.close();
});
-
- it('keeps the process alive across runs when autoCloseOnSettle is false', async () => {
- const { session } = createSession({ autoCloseOnSettle: false });
- mocks.start.mockResolvedValue(undefined);
- mocks.command.mockImplementation((command: { type: string }) => {
- if (command.type === 'get_state') {
- return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
- }
- return Promise.resolve({ success: true, type: 'response', command: command.type });
- });
- mocks.close.mockResolvedValue(undefined);
-
- // Turn 1 settles without closing the process.
- const first = session.run({ text: 'first' });
- await vi.waitFor(() => expect(session.isRunning).toBe(true));
- await emit(session, { type: 'agent_settled' });
- await expect(first).resolves.toEqual({ aborted: false });
- expect(session.isRunning).toBe(false);
- expect(mocks.close).not.toHaveBeenCalled();
-
- // Turn 2 reuses the same session/process.
- const second = session.run({ text: 'second' });
- await vi.waitFor(() => expect(session.isRunning).toBe(true));
- await emit(session, { type: 'agent_settled' });
- await expect(second).resolves.toEqual({ aborted: false });
- expect(session.isRunning).toBe(false);
- expect(mocks.close).not.toHaveBeenCalled();
-
- // The host owns close() in pooled mode.
- await session.close();
- expect(mocks.close).toHaveBeenCalled();
- });
-
- it('forwards extension UI requests to the host', async () => {
- const handler = vi.fn().mockReturnValue(undefined);
- const { session } = createSession({ onExtensionUiRequest: handler });
- mocks.start.mockResolvedValue(undefined);
- mocks.command.mockImplementation((command: { type: string }) => {
- if (command.type === 'get_state')
- return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
- return Promise.resolve({ success: true, type: 'response', command: command.type });
- });
- mocks.close.mockResolvedValue(undefined);
-
- const runPromise = session.run({ text: 'hello' });
- // Extension UI requests are intercepted by the RPC client (covered in
- // piRpcClient.test.ts) and never surface as agent events.
- await emit(session, { type: 'agent_settled' });
- await runPromise;
- expect(handler).not.toHaveBeenCalled();
- });
});
diff --git a/packages/heterogeneous-agents/src/scan/scanHost.test.ts b/packages/heterogeneous-agents/src/scan/scanHost.test.ts
index 7b669b3cfb9..49b11fdf3aa 100644
--- a/packages/heterogeneous-agents/src/scan/scanHost.test.ts
+++ b/packages/heterogeneous-agents/src/scan/scanHost.test.ts
@@ -109,22 +109,6 @@ describe('platform command scanning', () => {
});
});
- it('falls back to the official OpenClaw managed install path', async () => {
- detectValidatedCommandCandidatesMock.mockResolvedValue({
- available: true,
- path: path.join(os.homedir(), '.openclaw', 'bin', 'openclaw'),
- version: '2026.1.29',
- });
-
- await expect(resolveRemotePlatformCommand('openclaw')).resolves.toMatchObject({
- available: true,
- version: '2026.1.29',
- });
- expect(detectValidatedCommandCandidatesMock.mock.calls[0]![0]).toContain(
- path.join(os.homedir(), '.openclaw', 'bin', 'openclaw'),
- );
- });
-
it('falls back to the official Hermes user-local install path', async () => {
detectValidatedCommandCandidatesMock.mockResolvedValue({
available: true,
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 510c3c9b3e3..5136d8d9c25 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -164,16 +164,6 @@ describe('AgentStreamPipeline', () => {
expect(pipeline.sessionId).toBe('cc-99');
});
- it('auto-wires the Codex file-change tracker for codex agents only', async () => {
- // claude-code โ†’ no codex tracker, file_change payloads pass through untouched
- const claude = new AgentStreamPipeline({ agentType: 'claude-code', operationId: 'op-1' });
- expect((claude as any).codexTracker).toBeUndefined();
-
- // codex โ†’ tracker is instantiated automatically; consumers stay agent-agnostic
- const codex = new AgentStreamPipeline({ agentType: 'codex', operationId: 'op-1' });
- expect((codex as any).codexTracker).toBeDefined();
- });
-
it('emits an initial Codex model metadata event before stdout-derived events', async () => {
const pipeline = new AgentStreamPipeline({
agentType: 'codex',
@@ -250,18 +240,6 @@ describe('AgentStreamPipeline', () => {
expect(events.length).toBeGreaterThan(0);
});
- it('flushes adapter-buffered events on stream end', async () => {
- const pipeline = new AgentStreamPipeline({
- agentType: 'claude-code',
- operationId: 'op-1',
- });
-
- await pipeline.push(init());
- const flushed = await pipeline.flush();
-
- expect(Array.isArray(flushed)).toBe(true);
- });
-
describe('collectPostRunUsage', () => {
it('no-ops for adapters without a post-run usage hook', async () => {
const pipeline = new AgentStreamPipeline({
diff --git a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts
index 6c9b0bc398f..fff73734ea7 100644
--- a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts
@@ -6,7 +6,6 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { AskUserBridge } from '../askUser/AskUserBridge';
-import { DEFAULT_ASK_USER_TIMEOUT_MS } from '../askUser/constants';
import { AcpRpcResponseError } from './acpStdioClient';
import {
buildCursorAcpArgs,
@@ -299,21 +298,6 @@ describe('CursorAcpSession', () => {
}
});
- it('preserves the structured RPC error when a legacy Cursor session cannot be loaded', async () => {
- const fake = createAcpProcess({
- loadError: { code: -32_602, message: 'Session "legacy-session" not found' },
- });
- spawnMock.mockReturnValue(fake.child);
- vi.spyOn(process, 'kill').mockImplementation(() => true);
-
- const run = new CursorAcpSession(
- createSessionOptions({ resumeSessionId: 'legacy-session' }),
- ).run();
-
- await expect(run).rejects.toSatisfy(isCursorAcpSessionNotFoundError);
- expect(fake.requests.some(({ method }) => method === 'session/prompt')).toBe(false);
- });
-
it('returns an explicit cancellation instead of fabricating a skipped answer without a UI', async () => {
const fake = createAcpProcess({ askQuestion: true });
spawnMock.mockReturnValue(fake.child);
@@ -326,45 +310,6 @@ describe('CursorAcpSession', () => {
});
});
- it('keeps streaming session updates while AskUserBridge is waiting', async () => {
- const fake = createAcpProcess({ askQuestion: true });
- spawnMock.mockReturnValue(fake.child);
- vi.spyOn(process, 'kill').mockImplementation(() => true);
- const bridge = createCursorBridge();
- const options = createSessionOptions({ askUserBridge: bridge });
- const events: AgentStreamEvent[] = [];
- options.onEvents = (batch) => {
- events.push(...batch);
- };
- const eventIterator = bridge.events()[Symbol.asyncIterator]();
- const run = new CursorAcpSession(options).run();
-
- await eventIterator.next();
- fake.send({
- method: 'session/update',
- params: {
- sessionId: 'cursor-session-1',
- update: {
- content: { text: ' still streaming', type: 'text' },
- sessionUpdate: 'agent_message_chunk',
- },
- },
- });
- await vi.waitFor(() =>
- expect(events).toContainEqual(
- expect.objectContaining({
- data: { chunkType: 'text', content: ' still streaming' },
- type: 'stream_chunk',
- }),
- ),
- );
-
- bridge.resolve('cursor-question-1', {
- result: { 'How broad should the fix be?': 'Full' },
- });
- await run;
- });
-
it('blocks cursor/ask_question until the bridge returns selected option labels', async () => {
const fake = createAcpProcess({ askQuestion: true });
spawnMock.mockReturnValue(fake.child);
@@ -682,28 +627,4 @@ describe('CursorAcpSession', () => {
});
}
});
-
- it('cancels plan approval when the intervention times out', async () => {
- vi.useFakeTimers();
- const fake = createAcpProcess({
- serverRequest: {
- id: 'plan-request-1',
- method: 'cursor/create_plan',
- params: { plan: 'Do the work.', todos: [], toolCallId: 'plan-1' },
- },
- });
- spawnMock.mockReturnValue(fake.child);
- vi.spyOn(process, 'kill').mockImplementation(() => true);
- const bridge = createCursorBridge();
- const eventIterator = bridge.events()[Symbol.asyncIterator]();
- const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();
-
- await eventIterator.next();
- await vi.advanceTimersByTimeAsync(DEFAULT_ASK_USER_TIMEOUT_MS);
- await run;
-
- expect(fake.requests.find(({ id }) => id === 'plan-request-1')?.result).toEqual({
- outcome: { outcome: 'cancelled' },
- });
- });
});
diff --git a/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts
index fe0631321b7..6ed3ae19b45 100644
--- a/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts
@@ -267,10 +267,6 @@ describe('Devin ACP helpers', () => {
expect(buildDevinAcpArgs(['--model', 'sonnet'])).toEqual(['acp', '--model', 'sonnet']);
});
- it('does not inject a default permission mode', () => {
- expect(buildDevinAcpArgs(['--model', 'sonnet'])).toEqual(['acp', '--model', 'sonnet']);
- });
-
it('moves a permission mode already in extra args before the acp subcommand', () => {
expect(buildDevinAcpArgs(['--permission-mode', 'dangerous', '--model', 'sonnet'])).toEqual([
'--permission-mode',
diff --git a/packages/heterogeneous-agents/src/spawn/droidAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/droidAcpSession.test.ts
index 7f674364244..7ad43986289 100644
--- a/packages/heterogeneous-agents/src/spawn/droidAcpSession.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/droidAcpSession.test.ts
@@ -538,34 +538,4 @@ describe('DroidAcpSession', () => {
}),
);
});
-
- it('cancels an active prompt through the standard ACP notification', async () => {
- let promptRequestId: number | string | undefined;
- const fake = createAcpProcess({
- onMessage: (message, { send }) => {
- if (message.method === 'session/prompt') {
- promptRequestId = message.id;
- return true;
- }
- if (message.method === 'session/cancel') {
- send({ id: promptRequestId, result: { stopReason: 'cancelled' } });
- return true;
- }
- },
- });
- spawnMock.mockReturnValue(fake.child);
- vi.spyOn(process, 'kill').mockImplementation(() => true);
- const session = new DroidAcpSession(createSessionOptions());
- const run = session.run();
- await vi.waitFor(() => expect(promptRequestId).toBeDefined());
-
- session.interrupt();
- await run;
-
- expect(fake.requests).toContainEqual({
- jsonrpc: '2.0',
- method: 'session/cancel',
- params: { sessionId: 'droid-session-1' },
- });
- });
});
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
index b7766f51df2..e455948855c 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
@@ -1269,36 +1269,6 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);
expect(resolved.command).toBe('/Users/x/.local/bin/amp');
});
- it('defines opencode as the default OpenCode command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND.opencode).toBe('opencode');
- });
-
- it('defines agent as the default Cursor command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND.cursor).toBe('agent');
- });
-
- it('defines grok as the default Grok Build command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND['grok-build']).toBe('grok');
- });
-
- it('defines pi as the default Pi command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND.pi).toBe('pi');
- });
-
- it('defines qodercli as the default Qoder command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND.qoder).toBe('qodercli');
- });
-
- it('defines traecli as the default TRAE command', async () => {
- const { DEFAULT_HETERO_COMMAND } = await importModule();
- expect(DEFAULT_HETERO_COMMAND.trae).toBe('traecli');
- });
-
it('resolves the default bare command to the validated absolute path', async () => {
callExecFile('/usr/local/bin/codex\n');
callExecFile('codex-cli 0.142.5');
@@ -1437,29 +1407,6 @@ describe('login-shell PATH probe', () => {
).toHaveLength(0);
});
- it('re-reads the PATH after an explicit invalidation', async () => {
- // Rescan has to see a PATH an installer edited while the app was running.
- const module = await importModule();
- module.invalidateLoginShellPathCache();
-
- queueMissThenShell('/opt/tools/bin:/usr/bin');
- callExecFileError(new Error('still not found'));
- await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');
-
- module.invalidateLoginShellPathCache();
- execFileMock.mockReset();
- rejectUnqueuedExecFile();
- queueMissThenShell('/opt/tools/bin:/new/place:/usr/bin');
- callExecFileError(new Error('still not found'));
- await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');
-
- expect(
- execFileMock.mock.calls.filter(
- ([file, args]) => file === '/bin/zsh' && Array.isArray(args) && args[0] === '-ilc',
- ),
- ).toHaveLength(1);
- });
-
it('reports a timed-out probe as its own failure, not as a missing CLI', async () => {
// The bug this replaces: a busy machine blew the probe's budget and the
// user was told to install a CLI that was present and had just run.
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
index d2d369bbea5..041fd779fb7 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -477,28 +477,6 @@ describe('spawnAgent', () => {
processKill.mockRestore();
});
- it('preserves SIGKILL when force-stopping a Grok ACP run', async () => {
- const fake = createGrokAcpProc({ promptAutoComplete: false });
- nextFakeProc = fake.proc;
- const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true);
-
- const { spawnAgent } = await import('./spawnAgent');
- const handle = await spawnAgent({
- agentType: 'grok-build',
- operationId: 'op-grok-force-stop',
- prompt: 'keep running',
- });
- await vi.waitFor(() => {
- expect(fake.requests.some(({ method }) => method === 'session/prompt')).toBe(true);
- });
-
- handle.kill('SIGKILL');
-
- expect(processKill).toHaveBeenCalledWith(-54_321, 'SIGKILL');
- await expect(handle.exit).resolves.toEqual({ code: null, signal: 'SIGKILL' });
- processKill.mockRestore();
- });
-
it('preserves SIGINT when the transport fails during graceful cancellation', async () => {
const fake = createGrokAcpProc({ promptAutoComplete: false });
nextFakeProc = fake.proc;
@@ -1420,14 +1398,6 @@ describe('spawnAgent', () => {
expect(args).toContain('x');
});
- it('rejects with an error on unknown agent type', async () => {
- nextFakeProc = createFakeProc().proc;
- const { spawnAgent } = await import('./spawnAgent');
- await expect(
- spawnAgent({ agentType: 'kimi-cli', operationId: 'op-1', prompt: 'hi' }),
- ).rejects.toThrow('Unknown local heterogeneous agent type: "kimi-cli"');
- });
-
it('events iterator drains all pipeline events including the trailing flush', async () => {
const fake = createFakeProc({ stdoutChunks: [ccInit, ccText] });
nextFakeProc = fake.proc;
diff --git a/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts
index 1713f9348dc..b4d90952e05 100644
--- a/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts
@@ -101,30 +101,6 @@ describe('buildClaudeCodeTranscript', () => {
expect(asst.message.content).toEqual([{ type: 'text', text: 'visible answer' }]);
});
- it('trims a trailing unanswered tool_use (would 400 the next turn)', () => {
- const jsonl = buildClaudeCodeTranscript(
- [
- userMsg('go'),
- assistantMsg('running', [
- {
- apiName: 'Bash',
- arguments: '{}',
- id: 'toolu_dangling',
- identifier: 'claude-code',
- type: 'default',
- },
- ]),
- ],
- { cwd: CWD, sessionId: SESSION_ID },
- );
- // the assistant tool_use has no matching tool_result โ†’ trimmed away,
- // leaving just the user turn (still a valid, resumable transcript)
- const recs = parseLines(jsonl);
- expect(recs).toHaveLength(1);
- expect(recs[0].type).toBe('user');
- expect(jsonl).not.toContain('toolu_dangling');
- });
-
it('keeps a resolved tool_use but trims a later dangling one', () => {
const jsonl = buildClaudeCodeTranscript(
[
@@ -171,9 +147,7 @@ describe('encodeClaudeProjectDir', () => {
expect(encodeClaudeProjectDir('/private/tmp/cc-resurrect-lab')).toBe(
'-private-tmp-cc-resurrect-lab',
);
- });
-
- it('collapses dots and underscores to dashes too', () => {
+ // Dots and underscores collapse to dashes too.
expect(encodeClaudeProjectDir('/a/b.c_d')).toBe('-a-b-c-d');
});
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts
index dc54256e41c..72d572b474e 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts
@@ -105,13 +105,6 @@ describe('resolveHeteroResume', () => {
});
});
- it('handles undefined metadata', () => {
- expect(resolveNative(undefined, '/Users/me/projA')).toEqual({
- cwdChanged: false,
- resumeSessionId: undefined,
- });
- });
-
it('does not flag cwd change when there is no saved sessionId', () => {
// cwd field lingering without a sessionId shouldn't trigger the toast;
// there's nothing to skip resuming.
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 6987a959b7e..632d5a58d33 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -9,9 +9,6 @@
* - Content/reasoning/model/usage final writes
* - Sync snapshot + reset to prevent cross-step content contamination
*/
-import fs from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
import type * as LobeChatConst from '@lobechat/const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
@@ -1082,23 +1079,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(lastToolUpdate[1].tools[0].result_msg_id).toBe(createdToolId);
});
- it('should deduplicate tool calls (idempotent)', async () => {
- await runWithEvents([
- ccInit(),
- // Same tool_use id sent twice (CC can echo tool blocks)
- ccToolUse('msg_01', 'toolu_1', 'Bash', { command: 'ls' }),
- ccAssistant('msg_01', [
- { id: 'toolu_1', input: { command: 'ls' }, name: 'Bash', type: 'tool_use' },
- ]),
- ccToolResult('toolu_1', 'output'),
- ccResult(),
- ]);
-
- // Should only create ONE tool message despite two tool_use events with same id
- const toolCreates = mockCreateMessage.mock.calls.filter(([p]: any) => p.role === 'tool');
- expect(toolCreates.length).toBe(1);
- });
-
it('batches main message writes before tool_end reconciliation', async () => {
await runWithEvents([
ccInit(),
@@ -1302,28 +1282,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// lands in DB with provider set from the start (no later backfill needed).
expect(step2Assistant![0].provider).toBe('claude-code');
});
-
- it('should fall back to assistant parentId when step has no tools', async () => {
- const ids: string[] = [];
- mockCreateMessage.mockImplementation(async (params: any) => {
- const id = `${params.role}-${ids.length}`;
- ids.push(id);
- return { id };
- });
-
- await runWithEvents([
- ccInit(),
- // Step 1: just text, no tools
- ccText('msg_01', 'Let me think...'),
- // Step 2: more text (new message.id, no tools in step 1)
- ccText('msg_02', 'Here is the answer.'),
- ccResult(),
- ]);
-
- // Step 2 assistant should have parentId = initial assistant (no tools to chain through)
- const step2 = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'assistant');
- expect(step2?.[0].parentId).toBe('ast-initial');
- });
});
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1539,67 +1497,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(finalWrite![1].provider).toBe('claude-code');
});
- it('persists the Grok prompt-result model with per-turn rather than aggregate usage', async () => {
- await runWithEvents(
- [
- {
- jsonrpc: '2.0',
- method: 'session/update',
- params: {
- sessionId: 'grok-session',
- update: {
- content: { text: 'Grok answer', type: 'text' },
- sessionUpdate: 'agent_message_chunk',
- },
- },
- },
- {
- jsonrpc: '2.0',
- method: 'x.ai/session_notification',
- params: {
- _meta: { eventId: 'grok-response-completed' },
- sessionId: 'grok-session',
- update: {
- sessionUpdate: 'response_completed',
- stop_reason: 'end_turn',
- usage: { input_tokens: 10, output_tokens: 5 },
- },
- },
- },
- {
- id: 5,
- jsonrpc: '2.0',
- result: {
- _meta: {
- modelId: 'grok-build',
- usage: { inputTokens: 12, outputTokens: 4 },
- },
- stopReason: 'end_turn',
- },
- },
- ],
- {
- params: {
- heterogeneousProvider: { command: 'grok', type: 'grok-build' },
- },
- },
- );
-
- const modelWrite = mockUpdateMessage.mock.calls.find(
- ([id, value]: any) => id === 'ast-initial' && value.model === 'grok-build' && value.usage,
- );
- expect(modelWrite).toBeDefined();
- expect(modelWrite![1]).toMatchObject({
- model: 'grok-build',
- provider: 'grok-build',
- usage: {
- totalInputTokens: 10,
- totalOutputTokens: 5,
- totalTokens: 15,
- },
- });
- });
-
// The run's first assistant already exists in `dbMessagesMap` before the
// executor starts, so the gateway handler's stream_start seed-insert (its
// only model/provider โ†’ store path) is skipped for it. The executor must
@@ -2414,59 +2311,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(systemContext).toContain('const answer = 42;');
});
- it('should pass Claude Code model and thinking effort as spawn args', async () => {
- const store = createMockStore();
- const get = vi.fn(() => store);
-
- await executeHeterogeneousAgent(get, {
- ...defaultParams,
- heterogeneousProvider: {
- args: ['--verbose'],
- command: 'claude',
- effort: 'high',
- model: 'opus',
- type: 'claude-code' as const,
- },
- });
-
- expect(mockStartSession).toHaveBeenCalledWith(
- expect.objectContaining({
- args: ['--verbose', '--model', 'opus', '--effort', 'high'],
- agentType: 'claude-code',
- }),
- );
- });
-
- it('should pass Codex model and thinking effort as spawn args', async () => {
- const store = createMockStore();
- const get = vi.fn(() => store);
-
- await executeHeterogeneousAgent(get, {
- ...defaultParams,
- heterogeneousProvider: {
- args: ['--ask-for-approval', 'never'],
- command: 'codex',
- effort: 'xhigh',
- model: 'gpt-5.5',
- type: 'codex' as const,
- },
- });
-
- expect(mockStartSession).toHaveBeenCalledWith(
- expect.objectContaining({
- agentType: 'codex',
- args: [
- '--ask-for-approval',
- 'never',
- '--model',
- 'gpt-5.5',
- '-c',
- 'model_reasoning_effort="xhigh"',
- ],
- }),
- );
- });
-
it('should pass the selected TRAE model through ACP instead of native args', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
@@ -2589,27 +2433,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
});
- it('should preserve Claude Code defaults when model and effort are not selected', async () => {
- const store = createMockStore();
- const get = vi.fn(() => store);
-
- await executeHeterogeneousAgent(get, {
- ...defaultParams,
- heterogeneousProvider: {
- args: ['--verbose'],
- command: 'claude',
- type: 'claude-code' as const,
- },
- });
-
- expect(mockStartSession).toHaveBeenCalledWith(
- expect.objectContaining({
- args: ['--verbose'],
- agentType: 'claude-code',
- }),
- );
- });
-
it('should clear stale resume metadata and retry once without resume for recoverable Codex errors', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
@@ -3145,44 +2968,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
releaseUpdate();
});
-
- it('replays a failed write-behind assistant create without blocking live step state', async () => {
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- mockCreateMessage.mockImplementation(async (p: any) => {
- if (p.role === 'assistant') throw new Error('transient create failure');
- return { id: p.id ?? `tool-${Date.now()}` };
- });
-
- try {
- await runWithEvents([
- ccInit(),
- // Turn 1 on the seed assistant (ast-initial): text + tool + result.
- ccText('msg_01', 'turn one'),
- ccToolUse('msg_01', 't1', 'Bash', { command: 'ls' }),
- ccToolResult('t1', 'ok'),
- // Turn 2 (new message.id โ†’ step boundary): the new-assistant create
- // is now write-behind, so live state advances immediately and a
- // failed durable create is replayed after terminal flush.
- ccToolUse('msg_02', 't2', 'Read', { file_path: '/a' }),
- ccToolResult('t2', 'data'),
- ccResult(),
- ]);
-
- const assistantCreateAttempts = mockCreateMessage.mock.calls.filter(
- ([p]: any) => p.role === 'assistant',
- );
- expect(assistantCreateAttempts.length).toBeGreaterThanOrEqual(2);
-
- const attemptedAssistantId = assistantCreateAttempts[0][0].id;
- const t2Create = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 't2',
- );
- expect(t2Create).toBeDefined();
- expect(t2Create![0].parentId).toBe(attemptedAssistantId);
- } finally {
- consoleError.mockRestore();
- }
- });
});
describe('Desktop IPC session lifecycle', () => {
@@ -3519,97 +3304,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
).toBe(true);
});
- it('should switch to a new assistant before persisting the next turn tool', async () => {
- const idCounter = { assistant: 0, tool: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool += 1;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
-
- if (params.role === 'assistant') {
- idCounter.assistant += 1;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- }
-
- return { id: `created-${params.role}-${idCounter.assistant + idCounter.tool}` };
- });
-
- const toolsUpdates: Array<{ assistantId: string; toolIds: string[] }> = [];
- mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
- if (val.tools) {
- toolsUpdates.push({
- assistantId: id,
- toolIds: val.tools.map((tool: any) => tool.id),
- });
- }
- });
-
- await runWithEvents(
- [
- codexThreadStarted(),
- codexTurnStarted(),
- codexAgentMessage('item_0', 'Running the first command.'),
- codexCommandStarted('item_1', '/bin/zsh -lc pwd'),
- codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),
- codexTurnCompleted({ input_tokens: 10, output_tokens: 3 }),
- codexTurnStarted(),
- codexAgentMessage('item_2', 'Running the second command.'),
- codexCommandStarted('item_3', "/bin/zsh -lc 'git status --short'"),
- codexCommandCompleted('item_3', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),
- codexTurnCompleted({ input_tokens: 12, output_tokens: 4 }),
- ],
- {
- params: {
- heterogeneousProvider: { command: 'codex', type: 'codex' as const },
- },
- },
- );
-
- // The second turn opens exactly one new assistant (pre-allocated id).
- const newAstId = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'assistant',
- )![0].id;
-
- // The second-turn assistant chains off the spine (turn 1's assistant,
- // here the initial one), NOT turn 1's last tool.
- const secondTurnAssistantCreate = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'assistant',
- );
- expect(secondTurnAssistantCreate?.[0]).toMatchObject({
- parentId: 'ast-initial',
- role: 'assistant',
- });
-
- const firstToolCreate = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'tool' && params.tool_call_id === 'item_1',
- );
- expect(firstToolCreate?.[0]).toMatchObject({
- parentId: 'ast-initial',
- role: 'tool',
- tool_call_id: 'item_1',
- });
-
- const secondToolCreate = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'tool' && params.tool_call_id === 'item_3',
- );
- expect(secondToolCreate?.[0]).toMatchObject({
- parentId: newAstId,
- role: 'tool',
- tool_call_id: 'item_3',
- });
-
- const firstTurnToolWrites = toolsUpdates.filter(
- (update) => update.assistantId === 'ast-initial' && update.toolIds.includes('item_1'),
- );
- expect(firstTurnToolWrites.length).toBeGreaterThanOrEqual(1);
-
- const secondTurnToolWrites = toolsUpdates.filter(
- (update) => update.assistantId === newAstId && update.toolIds.includes('item_3'),
- );
- expect(secondTurnToolWrites.length).toBeGreaterThanOrEqual(1);
- });
-
it('does not leave a usage-only empty assistant when a final turn emits no agent_message', async () => {
// Repro for the cloud "usage-only empty shell" symptom (e.g. topic
// tpc_96sSE0Eb0DHw tail: assistant(tool call) -> tool result ->
@@ -3691,337 +3385,69 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(emptyShells).toEqual([]);
});
- it('REPLAY real trace: item_43 final agent_message text must persist (not be dropped)', async () => {
- // Replays the actual recorded Codex stdout for topic tpc_96sSE0Eb0DHw
- // (heteroSessionId 019f3c84-โ€ฆ-d4059626cb19). In production, the final
- // agent_message item_43 ("็ป“ๆžœๆ˜ฏ๏ผš่ฟ™ไธๆ˜ฏ Codex rawโ€ฆ") was emitted by Codex
- // and turn.completed carried usage (output_tokens=16372) that DID land on
- // the shell assistant โ€” but item_43's text never reached the DB. This
- // replay checks whether the client executor reproduces that text loss.
- const tracePath = path.join(
- os.homedir(),
- 'Library/Application Support/LobeHub/lobehub-storage/heteroAgent/tracing/codex',
- '20260707-202328-11c75f72-2a74-4545-b39f-bf3e089c2d01',
- 'stdout.jsonl',
- );
- if (!fs.existsSync(tracePath)) {
- console.log('SKIP replay โ€” trace not present:', tracePath);
- return;
- }
-
- const raw = fs.readFileSync(tracePath, 'utf8');
- const events = raw
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => line.length > 0)
- .map((line) => {
- try {
- return JSON.parse(line);
- } catch {
- return null;
- }
- })
- .filter((v): v is Record<string, any> => v !== null);
-
+ it('replays the final Codex assistant content flush when the first terminal write reports success=false', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const dbMessages = new Map<string, any>([
+ ['ast-initial', { content: '', id: 'ast-initial', role: 'assistant' }],
+ ]);
const idCounter = { assistant: 0, tool: 0 };
+ const finalText = '็ป“ๆžœๆ˜ฏ๏ผšraw ๅ’Œ adapter ้ƒฝๆœ‰ๆœ€ๅŽไธ€ๆกๆถˆๆฏ๏ผŒ็ผบ็š„ๆ˜ฏ terminal content flushใ€‚';
+ const failedFinalContentWrite = new Set<string>();
+ const contentAttempts: string[] = [];
+
mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool += 1;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- if (params.role === 'assistant') {
- idCounter.assistant += 1;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- }
- return { id: `created-${params.role}` };
+ const id =
+ params.id ??
+ (params.role === 'assistant'
+ ? `ast-new-${++idCounter.assistant}`
+ : `tool-${++idCounter.tool}`);
+ dbMessages.set(id, { ...params, content: params.content ?? '', id });
+ return { id };
});
- const contentByAssistant = new Map<string, string>();
mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
if (typeof val.content === 'string') {
- contentByAssistant.set(id, val.content);
+ contentAttempts.push(id);
+ if (val.content === finalText && !failedFinalContentWrite.has(id)) {
+ failedFinalContentWrite.add(id);
+ return { success: false };
+ }
}
- });
- await runWithEvents(events, {
- params: { heterogeneousProvider: { command: 'codex', type: 'codex' as const } },
+ const previous = dbMessages.get(id) ?? { content: '', id };
+ dbMessages.set(id, {
+ ...previous,
+ ...val,
+ metadata: {
+ ...previous.metadata,
+ ...val.metadata,
+ },
+ });
+ return { success: true };
});
- const assistantCreates = mockCreateMessage.mock.calls.filter(
- ([params]: any) => params.role === 'assistant',
- );
-
- // item_43's final answer text MUST land on SOME assistant.
- const allContent = [...contentByAssistant.values()].join('\n');
- const hasItem43 = allContent.includes('็ป“ๆžœ');
- const lastAssistantId = assistantCreates.at(-1)?.[0].id;
- const lastAssistantContent = lastAssistantId
- ? contentByAssistant.get(lastAssistantId)
- : undefined;
-
- console.log('REPLAY assistants=', assistantCreates.length, '| hasItem43Text=', hasItem43);
-
- console.log(
- 'REPLAY last assistant=',
- lastAssistantId,
- '| contentLen=',
- lastAssistantContent?.length ?? 0,
- );
+ try {
+ await runWithEvents(
+ [
+ codexThreadStarted(),
+ codexTurnStarted(),
+ codexAgentMessage('item_0', 'ๆˆ‘ๅ…ˆ่ท‘ไธ€ไธชๅ‘ฝไปคใ€‚'),
+ codexCommandStarted('item_1', '/bin/zsh -lc pwd'),
+ codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),
+ codexAgentMessage('item_2', finalText),
+ codexTurnCompleted({ cached_input_tokens: 4, input_tokens: 10, output_tokens: 3 }),
+ ],
+ {
+ params: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ },
+ },
+ );
- expect(hasItem43).toBe(true);
- });
-
- it('should forward cumulative tools_calling chunks for multiple Codex tools in one step', async () => {
- await runWithEvents(
- [
- codexThreadStarted(),
- codexTurnStarted(),
- codexAgentMessage('item_0', 'Running the first checks.'),
- codexCommandStarted('item_1', '/bin/zsh -lc pwd'),
- codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),
- codexCommandStarted('item_2', "/bin/zsh -lc 'git status --short'"),
- codexCommandCompleted('item_2', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),
- codexAgentMessage('item_3', 'Now I will inspect the commit details.'),
- codexCommandStarted('item_4', "/bin/zsh -lc 'git show --stat --summary HEAD'"),
- codexCommandCompleted(
- 'item_4',
- "/bin/zsh -lc 'git show --stat --summary HEAD'",
- ' src/file.ts | 1 +\n',
- ),
- codexTurnCompleted({ input_tokens: 10, output_tokens: 3 }),
- ],
- {
- params: {
- heterogeneousProvider: { command: 'codex', type: 'codex' as const },
- },
- },
- );
-
- const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results[0]?.value as ReturnType<
- typeof vi.fn
- >;
- expect(handlerSpy).toBeDefined();
-
- const toolsCallingChunks = handlerSpy.mock.calls
- .map((call) => call[0])
- .filter(
- (event: any) =>
- event?.type === 'stream_chunk' && event.data?.chunkType === 'tools_calling',
- );
-
- expect(toolsCallingChunks).toHaveLength(3);
- expect(toolsCallingChunks[0]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([
- 'item_1',
- ]);
- expect(toolsCallingChunks[1]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([
- 'item_1',
- 'item_2',
- ]);
- expect(toolsCallingChunks[2]?.data.toolsCalling.map((tool: any) => tool.id)).toEqual([
- 'item_4',
- ]);
- });
-
- it('should cut new assistants for later agent_message items in the same Codex turn', async () => {
- const idCounter = { assistant: 0, tool: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool += 1;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
-
- if (params.role === 'assistant') {
- idCounter.assistant += 1;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- }
-
- return { id: `created-${params.role}-${idCounter.assistant + idCounter.tool}` };
- });
-
- const toolsUpdates: Array<{ assistantId: string; toolIds: string[] }> = [];
- const contentUpdates: Array<{ assistantId: string; content: string }> = [];
- mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
- if (val.tools) {
- toolsUpdates.push({
- assistantId: id,
- toolIds: val.tools.map((tool: any) => tool.id),
- });
- }
- if (typeof val.content === 'string') {
- contentUpdates.push({ assistantId: id, content: val.content });
- }
- });
-
- await runWithEvents(
- [
- codexThreadStarted(),
- codexTurnStarted(),
- codexAgentMessage(
- 'item_0',
- 'Running the five read-only checks from the repo root exactly as requested.',
- ),
- codexCommandStarted('item_1', '/bin/zsh -lc pwd'),
- codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),
- codexCommandStarted('item_2', "/bin/zsh -lc 'git status --short'"),
- codexCommandCompleted('item_2', "/bin/zsh -lc 'git status --short'", ' M src/file.ts\n'),
- codexCommandStarted('item_3', "/bin/zsh -lc 'rg --files src | head -n 5'"),
- codexCommandCompleted(
- 'item_3',
- "/bin/zsh -lc 'rg --files src | head -n 5'",
- 'src/store/session/store.ts\n',
- ),
- codexAgentMessage(
- 'item_4',
- 'The workspace is dirty in a few files, but I am only collecting read-only outputs.',
- ),
- codexCommandStarted(
- 'item_5',
- `/bin/zsh -lc 'rg -n "heterogeneousAgent" src apps packages | head -n 10'`,
- ),
- codexCommandCompleted(
- 'item_5',
- `/bin/zsh -lc 'rg -n "heterogeneousAgent" src apps packages | head -n 10'`,
- 'apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts:18:import ...\n',
- ),
- codexCommandStarted(
- 'item_6',
- `/bin/zsh -lc 'rg -n "tool_call_id|tool_calls" src packages | head -n 10'`,
- ),
- codexCommandCompleted(
- 'item_6',
- `/bin/zsh -lc 'rg -n "tool_call_id|tool_calls" src packages | head -n 10'`,
- 'packages/agent-runtime/src/agents/GeneralChatAgent.ts:34:...\n',
- ),
- codexAgentMessage(
- 'item_7',
- 'Confirmed the repo root and the requested ripgrep checks returned matches.',
- ),
- codexTurnCompleted({
- cached_input_tokens: 92672,
- input_tokens: 107744,
- output_tokens: 996,
- }),
- ],
- {
- params: {
- heterogeneousProvider: { command: 'codex', type: 'codex' as const },
- },
- },
- );
-
- const assistantCreates = mockCreateMessage.mock.calls.filter(
- ([params]: any) => params.role === 'assistant',
- );
- expect(assistantCreates).toHaveLength(2);
- const newAst1 = assistantCreates[0]![0].id;
- const newAst2 = assistantCreates[1]![0].id;
- // The cut assistants chain along the spine (each off the previous
- // non-tool main message), NOT off the preceding turn's last tool.
- expect(assistantCreates[0]?.[0]).toMatchObject({
- parentId: 'ast-initial',
- role: 'assistant',
- });
- expect(assistantCreates[1]?.[0]).toMatchObject({
- parentId: newAst1,
- role: 'assistant',
- });
-
- const firstStepToolWrites = toolsUpdates.filter(
- (update) =>
- update.assistantId === 'ast-initial' &&
- update.toolIds.includes('item_1') &&
- update.toolIds.includes('item_2') &&
- update.toolIds.includes('item_3'),
- );
- expect(firstStepToolWrites.length).toBeGreaterThanOrEqual(1);
-
- const secondStepToolWrites = toolsUpdates.filter(
- (update) =>
- update.assistantId === newAst1 &&
- update.toolIds.includes('item_5') &&
- update.toolIds.includes('item_6'),
- );
- expect(secondStepToolWrites.length).toBeGreaterThanOrEqual(1);
-
- const thirdStepToolWrites = toolsUpdates.filter(
- (update) => update.assistantId === newAst2 && update.toolIds.length > 0,
- );
- expect(thirdStepToolWrites).toHaveLength(0);
-
- expect(
- contentUpdates.findLast((update) => update.assistantId === 'ast-initial')?.content,
- ).toContain('Running the five read-only checks');
- expect(
- contentUpdates.findLast((update) => update.assistantId === newAst1)?.content,
- ).toContain('The workspace is dirty in a few files');
- expect(
- contentUpdates.findLast((update) => update.assistantId === newAst2)?.content,
- ).toContain('Confirmed the repo root');
- });
-
- it('replays the final Codex assistant content flush when the first terminal write reports success=false', async () => {
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- const dbMessages = new Map<string, any>([
- ['ast-initial', { content: '', id: 'ast-initial', role: 'assistant' }],
- ]);
- const idCounter = { assistant: 0, tool: 0 };
- const finalText = '็ป“ๆžœๆ˜ฏ๏ผšraw ๅ’Œ adapter ้ƒฝๆœ‰ๆœ€ๅŽไธ€ๆกๆถˆๆฏ๏ผŒ็ผบ็š„ๆ˜ฏ terminal content flushใ€‚';
- const failedFinalContentWrite = new Set<string>();
- const contentAttempts: string[] = [];
-
- mockCreateMessage.mockImplementation(async (params: any) => {
- const id =
- params.id ??
- (params.role === 'assistant'
- ? `ast-new-${++idCounter.assistant}`
- : `tool-${++idCounter.tool}`);
- dbMessages.set(id, { ...params, content: params.content ?? '', id });
- return { id };
- });
-
- mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
- if (typeof val.content === 'string') {
- contentAttempts.push(id);
- if (val.content === finalText && !failedFinalContentWrite.has(id)) {
- failedFinalContentWrite.add(id);
- return { success: false };
- }
- }
-
- const previous = dbMessages.get(id) ?? { content: '', id };
- dbMessages.set(id, {
- ...previous,
- ...val,
- metadata: {
- ...previous.metadata,
- ...val.metadata,
- },
- });
- return { success: true };
- });
-
- try {
- await runWithEvents(
- [
- codexThreadStarted(),
- codexTurnStarted(),
- codexAgentMessage('item_0', 'ๆˆ‘ๅ…ˆ่ท‘ไธ€ไธชๅ‘ฝไปคใ€‚'),
- codexCommandStarted('item_1', '/bin/zsh -lc pwd'),
- codexCommandCompleted('item_1', '/bin/zsh -lc pwd', '/repo\n'),
- codexAgentMessage('item_2', finalText),
- codexTurnCompleted({ cached_input_tokens: 4, input_tokens: 10, output_tokens: 3 }),
- ],
- {
- params: {
- heterogeneousProvider: { command: 'codex', type: 'codex' as const },
- },
- },
- );
-
- const finalAssistantId = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'assistant',
- )![0].id;
- const finalRow = dbMessages.get(finalAssistantId);
+ const finalAssistantId = mockCreateMessage.mock.calls.find(
+ ([params]: any) => params.role === 'assistant',
+ )![0].id;
+ const finalRow = dbMessages.get(finalAssistantId);
expect(contentAttempts.filter((id) => id === finalAssistantId)).toHaveLength(2);
expect(finalRow.content).toBe(finalText);
@@ -4155,70 +3581,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
* The orphan happens when assistant2.tools[] does NOT contain
* the git_diff entry, making the tool message appear orphaned in the UI.
*/
- it('should register tools on the correct assistant in multi-turn tool execution', async () => {
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- });
-
- // Track ALL updateMessage calls to inspect tools[] writes
- const toolsUpdates: Array<{ assistantId: string; tools: any[] }> = [];
- mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
- if (val.tools) {
- toolsUpdates.push({ assistantId: id, tools: val.tools });
- }
- });
-
- await runWithEvents([
- ccInit(),
- // Turn 1: text + Bash (git log) โ€” same message.id
- ccAssistant('msg_01', [
- { text: 'ๆฒกๆœ‰ๆœชๆไบค็š„ไฟฎๆ”น๏ผŒ็œ‹็œ‹ๅทฒๆไบคไฝ†ๆœชๆŽจ้€็š„ๅ˜ๆ›ด๏ผš', type: 'text' },
- ]),
- ccToolUse('msg_01', 'toolu_gitlog', 'Bash', { command: 'git log canary..HEAD --oneline' }),
- ccToolResult('toolu_gitlog', 'abc123 feat: something\ndef456 fix: another'),
- // Turn 2: Bash (git diff) โ€” NEW message.id โ†’ step boundary
- ccToolUse('msg_02', 'toolu_gitdiff', 'Bash', { command: 'git diff --stat' }),
- ccToolResult('toolu_gitdiff', ' file1.ts | 10 +\n file2.ts | 5 -'),
- // Turn 3: text summary โ€” NEW message.id โ†’ step boundary
- ccText('msg_03', 'ๅฝ“ๅ‰ๅˆ†ๆ”ฏๆœ‰2ไธชๆœชๆŽจ้€็š„ๆไบค๏ผŒไฟฎๆ”นไบ†2ไธชๆ–‡ไปถใ€‚'),
- ccResult(),
- ]);
-
- // โ”€โ”€ Verify: Turn 1 tool registered on ast-initial โ”€โ”€
- const gitlogToolUpdates = toolsUpdates.filter(
- (u) => u.assistantId === 'ast-initial' && u.tools.some((t: any) => t.id === 'toolu_gitlog'),
- );
- expect(gitlogToolUpdates.length).toBeGreaterThanOrEqual(1);
-
- // Turn 2's assistant is the first newly-created assistant (pre-allocated id).
- const step2AstId = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'assistant')![0]
- .id;
-
- // โ”€โ”€ Verify: Turn 2 tool registered on the step-2 assistant โ”€โ”€
- // This is the critical assertion โ€” if this fails, the tool becomes orphaned
- const gitdiffToolUpdates = toolsUpdates.filter(
- (u) => u.assistantId === step2AstId && u.tools.some((t: any) => t.id === 'toolu_gitdiff'),
- );
- expect(gitdiffToolUpdates.length).toBeGreaterThanOrEqual(1);
-
- // โ”€โ”€ Verify: tool messages have correct parentId โ”€โ”€
- const gitlogToolCreate = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_gitlog',
- );
- expect(gitlogToolCreate![0].parentId).toBe('ast-initial');
-
- const gitdiffToolCreate = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_gitdiff',
- );
- expect(gitdiffToolCreate![0].parentId).toBe(step2AstId);
- });
-
it('should register tools on correct assistant when turn has ONLY tool_use (no text)', async () => {
// Edge case: turn 2 has only a tool_use, no text. The step transition creates
// a new assistant, then the tool_use must be registered on it (not the old one).
@@ -4439,273 +3801,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
- // Data-driven regression from real trace (regression.json)
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
- describe('data-driven regression (133 events)', () => {
- it('should have no orphan tools when replaying real CC trace', async () => {
- // Load real trace data
- const fs = await import('node:fs');
- const tracePath = path.join(process.cwd(), 'regression.json');
-
- let traceData: any[];
- try {
- traceData = JSON.parse(fs.readFileSync(tracePath, 'utf8'));
- } catch {
- // Skip if file doesn't exist (CI)
- console.log('regression.json not found, skipping data-driven test');
- return;
- }
-
- // Track all createMessage and updateMessage calls
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-${idCounter.assistant}` };
- });
-
- // Collect tools[] writes per assistant
- const toolsRegistry = new Map<string, Set<string>>();
- mockUpdateMessage.mockImplementation(async (id: string, val: any) => {
- if (val.tools && Array.isArray(val.tools)) {
- if (!toolsRegistry.has(id)) toolsRegistry.set(id, new Set());
- const set = toolsRegistry.get(id)!;
- for (const t of val.tools) {
- if (t.id) set.add(t.id);
- }
- }
- });
-
- // Collect tool messages: { tool_call_id โ†’ parentId (assistant) }
- const toolMessages = new Map<string, string>();
- const origCreate = mockCreateMessage.getMockImplementation()!;
- mockCreateMessage.mockImplementation(async (params: any) => {
- const result = await origCreate(params);
- if (params.role === 'tool' && params.tool_call_id) {
- toolMessages.set(params.tool_call_id, params.parentId);
- }
- return result;
- });
-
- // Extract raw lines from trace
- const rawLines = traceData.map((entry: any) => entry.rawLine);
-
- await runWithEvents(rawLines);
-
- // โ”€โ”€ Check for orphans โ”€โ”€
- // An orphan is a tool message whose tool_call_id doesn't appear in ANY
- // assistant's tools[] registry
- const allRegisteredToolIds = new Set<string>();
- for (const toolIds of toolsRegistry.values()) {
- for (const id of toolIds) allRegisteredToolIds.add(id);
- }
-
- const orphans: string[] = [];
- for (const [toolCallId, parentId] of toolMessages) {
- if (!allRegisteredToolIds.has(toolCallId)) {
- orphans.push(`tool_call_id=${toolCallId} parentId=${parentId}`);
- }
- }
-
- if (orphans.length > 0) {
- console.error('Orphan tools found:', orphans);
- }
- expect(orphans).toEqual([]);
-
- // โ”€โ”€ Sanity checks โ”€โ”€
- // Should have created many tool messages (trace has ~60 tool calls)
- expect(toolMessages.size).toBeGreaterThan(20);
- // Should have many assistants
- expect(idCounter.assistant).toBeGreaterThan(10);
- });
- });
-
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
- // reproduction: Skill โ†’ ToolSearch โ†’ MCP tool
- //
- // Mirrors the exact trace from the user-reported screenshot where
- // ToolSearch loads deferred MCP schemas before the MCP tool is called.
- // Verifies tool_result content is persisted for ALL three tools so the
- // UI stops showing "loading" after each tool completes.
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
- describe('Skill โ†’ ToolSearch โ†’ MCP repro', () => {
- it('persists tool_result content for Skill, ToolSearch, and the deferred MCP tool', async () => {
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- });
-
- const schemaPayload =
- '<functions><function>{"description":"Get a Linear issue","name":"mcp__linear-server__get_issue","parameters":{}}</function></functions>';
-
- await runWithEvents([
- ccInit(),
- // Turn 1: Skill invocation
- ccToolUse('msg_01', 'toolu_skill', 'Skill', { skill: 'linear' }),
- ccToolResult('toolu_skill', 'Launching skill: linear'),
- // Turn 2: ToolSearch with select: prefix (deferred schema fetch)
- ccToolUse('msg_02', 'toolu_search', 'ToolSearch', {
- query: 'select:mcp__linear-server__get_issue,mcp__linear-server__save_issue',
- max_results: 3,
- }),
- ccToolResult('toolu_search', schemaPayload),
- // Turn 3: the deferred MCP tool now callable
- ccToolUse('msg_03', 'toolu_get_issue', 'mcp__linear-server__get_issue', {
- id: '',
- }),
- ccToolResult('toolu_get_issue', '{"title":"resume error on topic switch"}'),
- ccText('msg_04', 'done'),
- ccResult(),
- ]);
-
- const toolIdOf = (callId: string) =>
- mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === callId,
- )![0].id;
- const astCreates = mockCreateMessage.mock.calls.filter(([p]: any) => p.role === 'assistant');
- const step2AstId = astCreates[0]![0].id;
- const step3AstId = astCreates[1]![0].id;
-
- // All three tool messages should have their content persisted.
- const skillResult = mockUpdateToolMessage.mock.calls.find(
- ([id]: any) => id === toolIdOf('toolu_skill'),
- );
- const searchResult = mockUpdateToolMessage.mock.calls.find(
- ([id]: any) => id === toolIdOf('toolu_search'),
- );
- const getIssueResult = mockUpdateToolMessage.mock.calls.find(
- ([id]: any) => id === toolIdOf('toolu_get_issue'),
- );
-
- expect(skillResult).toBeDefined();
- expect(skillResult![1]).toMatchObject({ content: 'Launching skill: linear' });
-
- expect(searchResult).toBeDefined();
- expect(searchResult![1]).toMatchObject({ content: schemaPayload });
- expect(searchResult![1].pluginError).toBeUndefined();
-
- expect(getIssueResult).toBeDefined();
- expect(getIssueResult![1]).toMatchObject({
- content: '{"title":"resume error on topic switch"}',
- });
-
- // tools[] registry on each step should contain the right tool id so the
- // UI can match tool messages to their assistant (no orphan warnings).
- const skillRegister = mockUpdateMessage.mock.calls.find(
- ([id, val]: any) =>
- id === 'ast-initial' && val.tools?.some((t: any) => t.id === 'toolu_skill'),
- );
- expect(skillRegister).toBeDefined();
-
- const searchRegister = mockUpdateMessage.mock.calls.find(
- ([id, val]: any) =>
- id === step2AstId && val.tools?.some((t: any) => t.id === 'toolu_search'),
- );
- expect(searchRegister).toBeDefined();
-
- const getIssueRegister = mockUpdateMessage.mock.calls.find(
- ([id, val]: any) =>
- id === step3AstId && val.tools?.some((t: any) => t.id === 'toolu_get_issue'),
- );
- expect(getIssueRegister).toBeDefined();
- });
- });
-
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
- // Full multi-step E2E
- // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-
- describe('full multi-step E2E', () => {
- it('should produce correct DB write sequence for Read โ†’ Write โ†’ text flow', async () => {
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- });
-
- await runWithEvents([
- ccInit(),
- // Turn 1: Read tool
- ccAssistant('msg_01', [{ thinking: 'Need to read the file', type: 'thinking' }]),
- ccToolUse('msg_01', 'toolu_read', 'Read', { file_path: '/src/app.ts' }),
- ccToolResult('toolu_read', 'export default function App() {}'),
- // Turn 2: Write tool (new message.id)
- ccToolUse('msg_02', 'toolu_write', 'Write', { file_path: '/src/app.ts', content: 'fixed' }),
- ccToolResult('toolu_write', 'File written'),
- // Turn 3: final summary (new message.id)
- ccText('msg_03', 'Fixed the bug in app.ts.'),
- ccResult(),
- ]);
-
- // --- Verify DB write sequence ---
-
- // 1. Tool message created for Read (parentId = initial assistant)
- const readToolCreate = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_read',
- );
- expect(readToolCreate![0].parentId).toBe('ast-initial');
- expect(readToolCreate![0].plugin.apiName).toBe('Read');
- const readToolId = readToolCreate![0].id;
-
- // 2. Read tool result written (to the pre-allocated Read tool message id)
- expect(mockUpdateToolMessage).toHaveBeenCalledWith(
- readToolId,
- expect.objectContaining({ content: 'export default function App() {}' }),
- expect.any(Object),
- );
-
- // 3. Step 2 assistant created chained off the spine (the initial
- // assistant), with the Read tool inline under step 1.
- const step2Create = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'assistant' && p.parentId === 'ast-initial',
- );
- expect(step2Create).toBeDefined();
-
- // 4. Write tool message created (parentId = step 2 assistant)
- const writeToolCreate = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_write',
- );
- expect(writeToolCreate).toBeDefined();
- expect(writeToolCreate![0].parentId).toBe(step2Create![0].id);
- const writeToolId = writeToolCreate![0].id;
-
- // 5. Write tool result written
- expect(mockUpdateToolMessage).toHaveBeenCalledWith(
- writeToolId,
- expect.objectContaining({ content: 'File written' }),
- expect.any(Object),
- );
-
- // 6. Step 3 assistant created chained off the spine (step 2 assistant),
- // with the Write tool inline under step 2.
- const step3Create = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'assistant' && p.parentId === step2Create![0].id,
- );
- expect(step3Create).toBeDefined();
-
- // 7. Final content written to the last assistant message
- const finalContentWrite = mockUpdateMessage.mock.calls.find(
- ([, val]: any) => val.content === 'Fixed the bug in app.ts.',
- );
- expect(finalContentWrite).toBeDefined();
- });
- });
-
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// CC subagent thread-container model ()
//
@@ -6013,95 +5108,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
* non-tool main message: the conversation chains user โ†’ asst โ†’ asst with
* tools inline, and the reactive callbacks render as plain spine assistants.
*/
- it('basic flow: each reactive step chains along the spine', async () => {
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- });
-
- await runWithEvents([
- ccInit(),
- // Step 0: Monitor starts a long-running task
- ccMessageStart('msg_01'),
- ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', {
- shell: 'until curl localhost/health; do sleep 5; done',
- }),
- ccMessageDelta({ input_tokens: 100, output_tokens: 20 }),
- ccToolResult('toolu_mon_0', 'Monitor started, task abc'),
- // Step 1 (new msg id): CC reacts to Monitor stdout with Bash + new Monitor
- ccMessageStart('msg_02'),
- ccToolUse('msg_02', 'toolu_bash_1', 'Bash', { command: 'echo ok' }),
- ccToolUse('msg_02', 'toolu_mon_1', 'Monitor', { shell: 'tail -f log' }),
- ccMessageDelta({ input_tokens: 150, output_tokens: 30 }),
- ccToolResult('toolu_bash_1', 'ok'),
- ccToolResult('toolu_mon_1', 'Monitor started, task def'),
- // Step 2 (new msg id)
- ccMessageStart('msg_03'),
- ccToolUse('msg_03', 'toolu_bash_2', 'Bash', { command: 'date' }),
- ccMessageDelta({ input_tokens: 200, output_tokens: 40 }),
- ccToolResult('toolu_bash_2', 'Mon Apr 21'),
- ccResult(),
- ]);
-
- const assistantCreates = mockCreateMessage.mock.calls.filter(
- ([p]: any) => p.role === 'assistant',
- );
- // Two new assistants (step 1 + step 2); step 0 uses ast-initial
- expect(assistantCreates.length).toBe(2);
-
- // Step 1 parent = the spine (initial assistant); its tools are inline.
- expect(assistantCreates[0][0].parentId).toBe('ast-initial');
- // Step 2 parent = the spine advanced to step 1's assistant.
- expect(assistantCreates[1][0].parentId).toBe(assistantCreates[0][0].id);
- });
-
/**
* regression: a toolless step in the middle keeps the spine linear.
* The next step chains off the toolless assistant (the most recent
* non-tool main message), so no message is orphaned.
*/
- it('toolless middle step: spine stays linear through the toolless step', async () => {
- const idCounter = { tool: 0, assistant: 0 };
- mockCreateMessage.mockImplementation(async (params: any) => {
- if (params.role === 'tool') {
- idCounter.tool++;
- return { id: params.id ?? `tool-${idCounter.tool}` };
- }
- idCounter.assistant++;
- return { id: params.id ?? `ast-new-${idCounter.assistant}` };
- });
-
- await runWithEvents([
- ccInit(),
- // Step 0: Monitor
- ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: 'watch -n1 date' }),
- ccToolResult('toolu_mon_0', 'Monitor started'),
- // Step 1 (new msg id): TEXT ONLY โ€” no tool_use
- ccText('msg_02', 'Looks like it started. I will wait for output.'),
- // Step 2 (new msg id): Monitor emits a line, CC reacts with Bash
- ccToolUse('msg_03', 'toolu_bash_2', 'Bash', { command: 'echo reacting' }),
- ccToolResult('toolu_bash_2', 'reacting'),
- ccResult(),
- ]);
-
- const assistantCreates = mockCreateMessage.mock.calls.filter(
- ([p]: any) => p.role === 'assistant',
- );
- expect(assistantCreates.length).toBe(2);
-
- // Step 1 (toolless) parent = the spine (initial assistant).
- expect(assistantCreates[0][0].parentId).toBe('ast-initial');
-
- // Step 2 parent = step 1's assistant: the spine advances on the toolless
- // step too, so the chain stays linear (no skip-back to a tool needed).
- expect(assistantCreates[1][0].parentId).toBe(assistantCreates[0][0].id);
- });
-
/**
* follow-up: N consecutive toolless steps (Monitor pushing
* stdout line by line, each line triggering a new LLM call that only