π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π§ͺ test: simplify agent runtime and context tests (#22199)
Inneic59bc8908b03
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 05fb530bb31..f5b8e972d49 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -12,7 +12,7 @@ import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';-import { registerHeteroCommand, SUPPORTED_AGENT_TYPES } from './hetero';+import { registerHeteroCommand } from './hetero';const {mockCreateCodexAgentHandle,@@ -290,12 +290,6 @@ describe('hetero exec command', () => {},);- it('supports every local descriptor type plus the bundled DeepSeek Harness runtime', () => {- expect([...SUPPORTED_AGENT_TYPES].toSorted()).toEqual(- [...HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type), 'deepseek-harness'].toSorted(),- );- });-it('rejects unsupported agent types via process.exit(2)', async () => {await runCmd(['hetero', 'exec', '--type', 'kimi-cli', '--prompt', 'hi']);expect(exitSpy).toHaveBeenCalledWith(2);diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex 9f2c9b7f572..68bcc2df530 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -302,19 +302,6 @@ describe('GatewayStreamNotifier', () => {expect(order).toEqual(['stream_chunk', 'stream_end', 'step_start']);});-- it('still returns inner result even if gateway fails', async () => {- mockFetch.mockRejectedValueOnce(new Error('network error'));-- const result = await notifier.publishStreamEvent('op-1', {- data: {},- stepIndex: 0,- type: 'step_start' as const,- });-- expect(result).toBe('publishStreamEvent-result');- expect(inner.calls.publishStreamEvent).toHaveLength(1);- });});describe('publishStreamChunk', () => {diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.tsindex ae19e8ee438..8d2cef14d00 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts@@ -51,14 +51,6 @@ describe('ServerOperationStore', () => {expect(topicMock.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main', 'unread');});- it('clears the mark when this operation owns it', async () => {- topicMock.findById.mockResolvedValue(markedWith('op-main'));-- await createStore('op-main').clearRunningMark();-- expect(topicMock.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main', 'unread');- });-// The bug this adapter caused: `finish` calls clearRunningMark BEFORE it// publishes `execution_complete`, and the client only learns the run ended// from that event β so the client's own settle always arrived to a mark thisdiff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.tsindex a368d3a96be..954746ff0ad 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts@@ -119,13 +119,6 @@ describe('formatErrorForState', () => {expect((formatErrorForState(error).body as { stack?: string }).stack).toBeUndefined();});-- it('falls back to AgentRuntimeError for unknown thrown values', () => {- const result = formatErrorForState('plain string failure');-- expect(result.type).toBe(AgentRuntimeErrorType.AgentRuntimeError);- expect(result.message).toBe('plain string failure');- });});describe('ERROR_CODE_SPECS enrichment', () => {diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex 960279d9ce7..ebe082a42dd 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -509,17 +509,6 @@ describe('AI Agent Router Integration Tests', () => {);});- it('should handle autoStart=true by default', async () => {- const caller = aiAgentRouter.createCaller(createTestContext());-- const result = await caller.execAgent({- agentId: testAgentId,- prompt: 'Hello',- });-- expect(result.autoStarted).toBe(true);- });-it('should include threadId in appContext when provided', async () => {const { AgentRuntimeService } = await import('@/server/services/agentRuntime');const mockCreateOperation = vi.fn().mockResolvedValue({diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.tsindex b49c0970dad..85900618f06 100644--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts@@ -130,7 +130,6 @@ describe('aiChatRouter', () => {expect.objectContaining({content: expect.any(String),model: 'gpt-4o',- parentId: 'm-user',role: 'assistant',sessionId: 's1',topicId: 't1',@@ -391,7 +390,6 @@ describe('aiChatRouter', () => {expect(mockCreateMessage).toHaveBeenNthCalledWith(2,expect.objectContaining({- parentId: 'm-user',role: 'assistant',sessionId: 's1',threadId: 'thread-123',@@ -500,7 +498,6 @@ describe('aiChatRouter', () => {expect(mockCreateMessage).toHaveBeenNthCalledWith(4,expect.objectContaining({- parentId: 'm-user',role: 'assistant',sessionId: 's1',threadId: 'thread-123',@@ -563,7 +560,6 @@ describe('aiChatRouter', () => {expect(mockCreateMessage).toHaveBeenNthCalledWith(2,expect.objectContaining({- parentId: 'm-user',role: 'assistant',sessionId: 's1',threadId: 'thread-new',@@ -785,7 +781,6 @@ describe('aiChatRouter', () => {expect.objectContaining({agentId: 'supervisor-agent',groupId: 'group-123',- parentId: 'm-user',role: 'assistant',sessionId: 's1',topicId: 't1',diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientGroupAgentTaskThread.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientGroupAgentTaskThread.integration.test.tsindex 3211f5bf8fd..c0674edb2ed 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientGroupAgentTaskThread.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientGroupAgentTaskThread.integration.test.ts@@ -206,55 +206,6 @@ describe('createClientGroupAgentTaskThread Integration', () => {expect(userMsgInThread?.threadId).toBe(result.threadId);});- it('should NOT filter by agentId (messages from any agent in thread are included)', async () => {- const caller = aiAgentRouter.createCaller(createTestContext());-- const result = await caller.createClientGroupAgentTaskThread({- groupId: testGroupId,- instruction: 'Execute the task',- parentMessageId,- subAgentId: workerAgentId,- topicId: testTopicId,- });-- // Create a message in the thread with a DIFFERENT agentId (simulating supervisor adding to thread)- await serverDB.insert(messages).values({- userId,- role: 'assistant',- content: 'Response from supervisor in thread',- topicId: testTopicId,- agentId: supervisorAgentId, // Different from subAgentId!- groupId: testGroupId,- threadId: result.threadId,- });-- // Query thread messages again via API- const result2 = await caller.createClientGroupAgentTaskThread({- groupId: testGroupId,- instruction: 'Another task',- parentMessageId,- subAgentId: workerAgentId,- topicId: testTopicId,- });-- // The key test: messages in a thread from different agents should all be queryable- // This verifies the API doesn't filter by agentId- const [supervisorMsgInThread] = await serverDB- .select()- .from(messages)- .where(eq(messages.threadId, result.threadId));-- // If we directly query the database, we should find messages with different agentIds- const threadMsgs = await serverDB- .select()- .from(messages)- .where(eq(messages.threadId, result.threadId));-- const agentIds = [...new Set(threadMsgs.map((m) => m.agentId))];- // Thread should be able to contain messages from multiple agents- expect(agentIds.length).toBeGreaterThanOrEqual(1);- });-it('should include ancestor messages in thread context', async () => {// Create a chain of messages with different agentIdsconst [userMsg] = (await serverDBdiff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.task.integration.test.tsindex 61734afe841..56951ce4500 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts@@ -344,12 +344,6 @@ describe('Agent Task Integration', () => {expect(createResult.success).toBe(false);expect(createResult.error).toBe('Agent execution failed');expect(createResult.threadId).toBe(threadId);-- // Verify Thread status- const [thread] = await serverDB.select().from(threads).where(eq(threads.id, threadId));-- expect(thread.status).toBe(ThreadStatus.Failed);- expect(thread.metadata?.error).toBe('Agent execution failed');});it('should handle task failure during execution', async () => {diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.tsindex f4160537479..abbd874ec49 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts@@ -391,11 +391,6 @@ describe('Multi-Round Tool Execution', () => {// The chain detector combines consecutive assistant+tool rounds into a single assistantGroupexpect(finalState.messages.length).toBeGreaterThan(0);- // After state.messages stores parse-processed UIChatMessage[]- // Tool messages are wrapped in virtual 'assistantGroup' nodes by conversation-flow parse()- // The chain detector combines consecutive assistant+tool rounds into a single assistantGroup- expect(finalState.messages.length).toBeGreaterThan(0);-// parse() combines the multi-round assistant+tool chain into one assistantGroupconst assistantGroupMessages = finalState.messages.filter((m: { role: string }) => m.role === 'assistantGroup',diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.tsindex 3cf5ba1ba08..ea0f9bfba10 100644--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts@@ -4,9 +4,7 @@ import { describe, expect, it } from 'vitest';import { aiAgentRouter } from '.';/**- * Pins the router's public surface: every procedure path, its kind, and its- * middleware chain length (which encodes the procedure builder and its input- * parsers). Splitting the router across files must keep all three.+ * Pins the router's public procedure paths and query/mutation kinds.*/describe('aiAgentRouter procedures', () => {const procedures = (aiAgentRouter as any)._def.procedures as Record<string, any>;@@ -15,51 +13,50 @@ describe('aiAgentRouter procedures', () => {expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));});- it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ it.each(expected())('%s is a %s', (name, type) => {expect(procedures[name]._def.type).toBe(type);- expect(procedures[name]._def.middlewares).toHaveLength(middlewares);});});-function expected(): Array<[name: string, type: 'mutation' | 'query', middlewares: number]> {+function expected(): Array<[name: string, type: 'mutation' | 'query']> {return [- ['beginServerDefaultHeterogeneousOperation', 'mutation', 11],- ['cancelServerDefaultHeterogeneousOperation', 'mutation', 11],- ['createClientGroupAgentTaskThread', 'mutation', 13],- ['createClientTaskThread', 'mutation', 13],- ['describeServerDefaultHeterogeneousModel', 'mutation', 11],- ['execAgent', 'mutation', 13],- ['execAgents', 'mutation', 13],- ['execGroupAgent', 'mutation', 13],- ['execSubAgentTask', 'mutation', 13],- ['finishServerDefaultHeterogeneousOperation', 'mutation', 11],- ['getAgentInterventionReview', 'mutation', 11],- ['getAgentInterventionReviewBySource', 'mutation', 11],- ['getHeteroInterventionReview', 'mutation', 11],- ['getOperationStatus', 'query', 12],- ['getOperationStreamHistory', 'query', 11],- ['getPendingInterventions', 'query', 12],- ['getServerDefaultHeterogeneousCapability', 'query', 10],- ['getSubAgentTaskStatus', 'query', 12],- ['heteroFinish', 'mutation', 8],- ['heteroIngest', 'mutation', 8],- ['interruptTask', 'mutation', 13],- ['issueGatewayUserToken', 'query', 11],- ['listClientLlmWaits', 'query', 12],- ['processHumanIntervention', 'mutation', 13],- ['refreshGatewayToken', 'query', 12],- ['refreshHeteroOperationToken', 'mutation', 8],- ['releaseSubAgentLlmRelay', 'mutation', 13],- ['resolveAgentIntervention', 'mutation', 13],- ['resolveAgentInterventionBySource', 'mutation', 13],- ['resolveHeteroIntervention', 'mutation', 13],- ['resumeClientLlmWait', 'mutation', 13],- ['scheduleAgentRun', 'mutation', 13],- ['setQueuedMessages', 'mutation', 13],- ['startExecution', 'mutation', 13],- ['stopPendingApproval', 'mutation', 13],- ['submitHeteroIntervention', 'mutation', 13],- ['updateClientTaskThreadStatus', 'mutation', 13],- ['waitInterventionResponse', 'query', 8],+ ['beginServerDefaultHeterogeneousOperation', 'mutation'],+ ['cancelServerDefaultHeterogeneousOperation', 'mutation'],+ ['createClientGroupAgentTaskThread', 'mutation'],+ ['createClientTaskThread', 'mutation'],+ ['describeServerDefaultHeterogeneousModel', 'mutation'],+ ['execAgent', 'mutation'],+ ['execAgents', 'mutation'],+ ['execGroupAgent', 'mutation'],+ ['execSubAgentTask', 'mutation'],+ ['finishServerDefaultHeterogeneousOperation', 'mutation'],+ ['getAgentInterventionReview', 'mutation'],+ ['getAgentInterventionReviewBySource', 'mutation'],+ ['getHeteroInterventionReview', 'mutation'],+ ['getOperationStatus', 'query'],+ ['getOperationStreamHistory', 'query'],+ ['getPendingInterventions', 'query'],+ ['getServerDefaultHeterogeneousCapability', 'query'],+ ['getSubAgentTaskStatus', 'query'],+ ['heteroFinish', 'mutation'],+ ['heteroIngest', 'mutation'],+ ['interruptTask', 'mutation'],+ ['issueGatewayUserToken', 'query'],+ ['listClientLlmWaits', 'query'],+ ['processHumanIntervention', 'mutation'],+ ['refreshGatewayToken', 'query'],+ ['refreshHeteroOperationToken', 'mutation'],+ ['releaseSubAgentLlmRelay', 'mutation'],+ ['resolveAgentIntervention', 'mutation'],+ ['resolveAgentInterventionBySource', 'mutation'],+ ['resolveHeteroIntervention', 'mutation'],+ ['resumeClientLlmWait', 'mutation'],+ ['scheduleAgentRun', 'mutation'],+ ['setQueuedMessages', 'mutation'],+ ['startExecution', 'mutation'],+ ['stopPendingApproval', 'mutation'],+ ['submitHeteroIntervention', 'mutation'],+ ['updateClientTaskThreadStatus', 'mutation'],+ ['waitInterventionResponse', 'query'],];}diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.tsindex da779256c78..536b66c0238 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.basics.test.ts@@ -90,18 +90,6 @@ describe('isSuccessLikeCompletionReason', () => {});describe('CompletionLifecycle.extractErrorMessage', () => {- it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {- const lifecycle = buildLifecycle();- const error = {- _responseBody: { provider: 'lobehub' },- error: { message: 'Budget exceeded' },- errorType: 'InsufficientBudgetForModel',- provider: 'lobehub',- };-- expect(lifecycle.extractErrorMessage(error)).toBe('Budget exceeded');- });-it('extracts message from ChatCompletionErrorPayload (InvalidProviderAPIKey)', () => {const lifecycle = buildLifecycle();const error = {diff --git a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.tsindex e9e603c31c4..8349ee443dd 100644--- a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts@@ -299,7 +299,7 @@ describe('StaleOperationReaper', () => {expect(queue.scheduleMessage).not.toHaveBeenCalled();expect(finalizeAbandonedMock).not.toHaveBeenCalled();- expect(result).toMatchObject({ alive: 1, redriven: 0 });+ expect(result).toMatchObject({ abandoned: 0, alive: 1, redriven: 0 });});it('abandons once the redrive budget is spent', async () => {@@ -320,22 +320,6 @@ describe('StaleOperationReaper', () => {expect(result).toMatchObject({ abandoned: 1 });});- it('refuses to abandon a run that heartbeated after the candidate was selected', async () => {- // `listStaleRunning` selected this row, then the worker resumed while the- // sweep was doing its Redis reads. Abandoning is irreversible and- // user-visible, so it must re-check the lease atomically rather than- // trust the stale select.- const queue = buildQueue();- claimStaleRedriveMock.mockResolvedValue(null);- settleStaleRunningMock.mockResolvedValue(false);-- const result = await buildReaper([candidate()], runningState(), queue).sweep();-- expect(finalizeAbandonedMock).not.toHaveBeenCalled();- expect(queue.scheduleMessage).not.toHaveBeenCalled();- expect(result).toMatchObject({ abandoned: 0, alive: 1 });- });-it('gives the attempt back when the redrive fails to publish', async () => {// The budget bounds LLM spend; a delivery that never went out spent// nothing. Without the release, a brief queue outage walks a healthydiff --git a/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.tsindex 9359fe7881e..ce44bf27b06 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts@@ -220,39 +220,6 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {}),]);});-- it('should NOT have hook config when no hooks are configured', async () => {- const operationId = 'hook-none-1';-- await service.createOperation({- agentConfig: { model: 'gpt-4o', provider: 'openai' },- appContext: { agentId: 'test-agent' },- autoStart: false,- initialContext: makeContext(operationId),- initialMessages: [{ content: 'Hello', role: 'user' }],- modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },- operationId,- toolSet: { manifestMap: {}, tools: [] },- userId,- });-- const state = await stateManager.loadAgentState(operationId);- expect(state?.host?.hooks).toBeUndefined();- });-- it('should not throw when webhook fetch fails', async () => {- const operationId = 'hook-fail-1';- const webhookUrl = 'https://example.com/failing-webhook';-- // Make fetch throw- fetchSpy.mockRejectedValueOnce(new Error('Network error'));-- await createOperationWithHook(operationId, webhookUrl, { runId: 'run-1' });-- // Verify the hook is stored -- the hook dispatch catches errors internally- const state = await stateManager.loadAgentState(operationId);- expect(state?.host?.hooks?.[0]?.webhook?.url).toBe(webhookUrl);- });});describe('hook payload structure', () => {diff --git a/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeSync.test.tsindex 703d5c57721..14fdef26493 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts@@ -164,13 +164,6 @@ describe('AgentRuntimeService.executeSync', () => {});});- describe('getCoordinator', () => {- it('should return the coordinator instance', () => {- const coordinator = service.getCoordinator();- expect(coordinator).toBeDefined();- });- });-describe('InMemoryAgentStateManager', () => {it('should save and load state correctly', async () => {const operationId = 'state-test-1';diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.tsindex 170284c985f..2a16028742f 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { HookDispatcher } from '../HookDispatcher';import { matchesHook } from '../matcher';+import * as serverHooks from '../serverHooks';import type { AgentHook, AgentHookEvent } from '../types';const { fetchMock, queueMode } = vi.hoisted(() => ({ fetchMock: vi.fn(), queueMode: vi.fn() }));@@ -40,6 +41,19 @@ describe('hook registration and restoration', () => {afterEach(() => {vi.restoreAllMocks();});+ it.each([false, true])(+ 'finishes without sending a notification when no hooks exist in queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ vi.spyOn(serverHooks, 'getServerHooks').mockReturnValue([]);++ await expect(+ new HookDispatcher().dispatch('op', 'onComplete', event),+ ).resolves.toBeUndefined();++ expect(fetchMock).not.toHaveBeenCalled();+ },+ );it.each([false, true])('sends webhook-only hooks in queue=%s', async (queue) => {queueMode.mockReturnValue(queue);const dispatcher = new HookDispatcher();diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.tsindex 88697e523d2..bc7502b4cc8 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts@@ -1,5 +1,4 @@import type { ComposerUserMessageMetadata, ContextSelection } from '@lobechat/types';-import { COMPOSER_USER_MESSAGE_METADATA_KEYS } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -334,9 +333,6 @@ describe('AiAgentService.execAgent - hetero runs keep the composer-authored useruserMessage: { editorData, metadata: everyComposerField },});- expect(Object.keys(everyComposerField).sort()).toEqual(- [...COMPOSER_USER_MESSAGE_METADATA_KEYS].sort(),- );expect(userMessageCreate()?.editorData).toEqual(editorData);expect(userMessageCreate()?.metadata).toMatchObject(everyComposerField);});diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.test.tsindex ed382ffc732..803ab05d224 100644--- a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts@@ -5,24 +5,9 @@ import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';import { builtinTools } from '@lobechat/builtin-tools';import { describe, expect, it } from 'vitest';-import {- buildAllowedBuiltinTools,- DEVICE_TOOL_IDENTIFIERS,- isDeviceToolIdentifier,-} from './deviceToolRegistry';+import { buildAllowedBuiltinTools, isDeviceToolIdentifier } from './deviceToolRegistry';describe('deviceToolRegistry', () => {- it('pins the device tool set to local-system, AUV, remote-device, and browser', () => {- expect([...DEVICE_TOOL_IDENTIFIERS].sort()).toEqual(- [- LocalSystemManifest.identifier,- RemoteDeviceManifest.identifier,- BrowserManifest.identifier,- AuvManifest.identifier,- ].sort(),- );- });-it('isDeviceToolIdentifier recognises the device tools', () => {expect(isDeviceToolIdentifier(LocalSystemManifest.identifier)).toBe(true);expect(isDeviceToolIdentifier(RemoteDeviceManifest.identifier)).toBe(true);diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.tsindex 0b36e8adc3f..3214989a9f0 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts@@ -33,7 +33,6 @@ describe('heteroOperationCapabilities', () => {});it('keeps acceptance evidence out of a run with no Task', () => {- expect(heteroOperationCapabilities('fix the build')).not.toContain('acceptance:evidence');expect(heteroOperationCapabilities('fix the build', {})).not.toContain('acceptance:evidence');});});diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 166e1ede188..fc20be90455 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -1072,14 +1072,10 @@ describe('HeterogeneousAgentService', () => {});// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- // End-to-end DATA-FLOW reproduction of the runtime path: seed the run's hooks- // the way execAgent does (real hookDispatcher.register β getSerializedHooks β- // persist onto runningOperation via a shared in-memory topic store with REAL- // shallow-merge semantics), then run the REAL heteroFinish against the SAME- // store. This exercises the cross-process round-trip the isolated unit tests- // hand-wave, and lets us reproduce the production "stuck task_topics" symptom- // by injecting the suspected lost-update race on topic.metadata.- describe('heteroFinish β seedβreadβdeliver round-trip + lost-update repro', () => {+ // Serialize hooks into the topic mirror, then finish after dropping the+ // in-memory registration. The topic store is a fake; this covers hook+ // serialization and dispatch, not ingest or database concurrency.+ describe('heteroFinish β serialized topic hook round-trip', () => {const originalToken = process.env.QSTASH_TOKEN;const originalAppUrl = process.env.APP_URL;const TOPIC = 'topic-int';@@ -1096,9 +1092,7 @@ describe('HeterogeneousAgentService', () => {},};- // Shared topic store whose updateMetadata mirrors TopicModel.updateMetadata.- // `mergeBase` lets a test force the historical stale-snapshot race, while- // settleRunningOperation models the operation-owned terminal CAS.+ // Fake topic store for seeding and settling this run's serialized hooks.const makeStore = () => {let meta: Record<string, any> = {};const topicModel = {@@ -1148,14 +1142,14 @@ describe('HeterogeneousAgentService', () => {threadId: operation.threadId,};}),- updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>, mergeBase?: any) => {- meta = { ...(mergeBase ?? meta), ...patch };+ updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>) => {+ meta = { ...meta, ...patch };}),} as any;return { get: () => meta, topicModel };};- // Reproduce execAgent's seed step exactly.+ // Use the real hook serializer to seed the topic mirror.const seed = (store: ReturnType<typeof makeStore>, operationId: string) => {hookDispatcher.register(operationId, [taskHook]);const serializedHooks = hookDispatcher.getSerializedHooks(operationId);@@ -1189,12 +1183,11 @@ describe('HeterogeneousAgentService', () => {else process.env.APP_URL = originalAppUrl;});- it('happy path: a fresh-read heteroIngest write preserves hooks β heteroFinish delivers', async () => {+ it('dispatches serialized topic hooks after the in-memory registration is gone', async () => {const store = makeStore();await seed(store, 'op-int');- // A normal mid-run ingest write reads the CURRENT snapshot, so the- // shallow-merge keeps runningOperation intact.+ // An unrelated metadata update preserves the seeded hooks in this fake.await store.topicModel.updateMetadata(TOPIC, {heteroCurrentMsgId: { msgId: 'm1', operationId: 'op-int' },});@@ -1218,39 +1211,5 @@ describe('HeterogeneousAgentService', () => {'/api/workflows/task/on-topic-complete',);});-- it('REPRO: a stale-read ingest write clobbers runningOperation.hooks β heteroFinish delivers nothing (the stuck-task symptom)', async () => {- const store = makeStore();- // Snapshot BEFORE the seed commits β what a racing reader would have seen.- const preSeedSnapshot = { ...store.get() };- await seed(store, 'op-int');- expect(store.get().runningOperation?.hooks).toHaveLength(1);-- // A concurrent heteroIngest whose read-modify-write started from the- // pre-seed snapshot (replica lag / interleave): merging its patch over the- // STALE base drops runningOperation entirely β a classic lost update.- await store.topicModel.updateMetadata(- TOPIC,- { heteroCurrentMsgId: { msgId: 'm1', operationId: 'op-int' } },- preSeedSnapshot,- );- expect(store.get().runningOperation).toBeUndefined();-- // Model the process boundary: heteroFinish's in-memory dispatcher is empty,- // so the clobbered runningOperation is its ONLY source of the hook.- hookDispatcher.unregister('op-int');-- await makeService(store).heteroFinish({- agentType: 'claude-code',- operationId: 'op-int',- result: 'success',- topicId: TOPIC,- });-- // Exactly the production failure: the run finished, but the terminal hook- // had nothing to deliver, so onTopicComplete never fires and the task- // topic is stranded at `running`.- expect(mockPublishJSON).not.toHaveBeenCalled();- });});});diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 8cc403034a6..b575f882eff 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -2842,69 +2842,6 @@ describe('GeneralChatAgent', () => {]);});- it('should await async dynamic intervention resolvers', async () => {- const agent = new GeneralChatAgent({- agentConfig: { maxSteps: 100 },- dynamicInterventionAudits: {- pathScopeAudit: async (toolArgs, metadata) => {- const workingDirectory = metadata?.workingDirectory as string | undefined;- if (!workingDirectory) return false;-- const path = toolArgs.path as string;- return !path.startsWith(workingDirectory);- },- },- operationId: 'test-session',- modelRuntimeConfig: mockModelRuntimeConfig,- });-- const toolCall: ChatToolPayload = {- id: 'call-1',- identifier: 'local-system',- apiName: 'readLocalFile',- arguments: '{"path":"/etc/passwd"}',- type: 'builtin',- };-- const state = createMockState({- plan: { workingDirectory: '/workspace' },- toolManifestMap: {- 'local-system': {- identifier: 'local-system',- api: [- {- name: 'readLocalFile',- humanIntervention: {- dynamic: {- default: 'never',- policy: 'required',- type: 'pathScopeAudit',- },- },- },- ],- },- },- });-- const context = createMockContext('llm_result', {- hasToolsCalling: true,- toolsCalling: [toolCall],- parentMessageId: 'msg-1',- });-- const result = await agent.runner(context, state);-- expect(result).toEqual([- {- type: 'request_human_approve',- parentMessageId: 'msg-1',- pendingToolsCalling: [toolCall],- reason: 'human_intervention_required',- },- ]);- });-it('should check intervention at API level when configured', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.tsindex 26d3e4cfe6f..2aacc4ca5ff 100644--- a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts@@ -146,10 +146,6 @@ const parseGraph = (graph: unknown) => AgentGraphSchema.safeParse(graph);describe('GraphAgent', () => {describe('schema', () => {- it('should accept the goal-loop fixture', () => {- expect(parseGraph(loadGoalLoopGraph()).success).toBe(true);- });-it('should require exactly one root edge', () => {const graph = loadGoalLoopGraph();const result = parseGraph({@@ -787,30 +783,6 @@ describe('GraphAgent', () => {});describe('e2e', () => {- it('should keep the goal-loop fixture aligned with the graph schema', () => {- const graph = loadGoalLoopGraph();-- expect(graph.terminal).toBe('verify');- expect(graph.nodes).toMatchObject({- plan: { allowedToolApiNames: ['read', 'search'], type: 'agent' },- verify: { type: 'llm' },- work: { type: 'agent' },- });- expect(graph.edges).toEqual(- expect.arrayContaining([- expect.objectContaining({- from: AGENT_GRAPH_ROOT_NODE_ID,- to: 'plan',- }),- expect.objectContaining({- from: 'verify',- maxTraversals: 3,- to: 'work',- }),- ]),- );- });-it('should execute the /goal plan-work-verify loop with mocked llm outputs', async () => {const agent = new GraphAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.tsindex 051c7ec36cc..6a94d9dea78 100644--- a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts+++ b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts@@ -113,10 +113,4 @@ describe('createSecurityBlacklistAudit', () => {await expect(config.resolver({ command: 'rm -rf /' })).resolves.toBe(false);});});-- describe('SECURITY_BLACKLIST_AUDIT_TYPE', () => {- it('should be securityBlacklist', () => {- expect(SECURITY_BLACKLIST_AUDIT_TYPE).toBe('securityBlacklist');- });- });});diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.tsindex 476d4b6564a..23ef2fea351 100644--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts@@ -66,19 +66,6 @@ function createTestContext(describe('AgentRuntime', () => {describe('Constructor and Executor Priority', () => {- it('should use built-in executors by default', () => {- const agent = new MockAgent();- const runtime = new AgentRuntime(agent);-- // @ts-expect-error - accessing private property for testing- const executors = runtime.executors;-- expect(executors).toHaveProperty('call_llm');- expect(executors).toHaveProperty('call_tool');- expect(executors).toHaveProperty('finish');- expect(executors).toHaveProperty('request_human_approve');- });-it('should allow config executors to override built-in ones', () => {const agent = new MockAgent();const customFinish = vi.fn();diff --git a/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts b/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.tsindex 240d68b1485..1b83feb8e5c 100644--- a/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts+++ b/packages/agent-runtime/src/utils/emptyArgumentsCalls.test.ts@@ -2,12 +2,7 @@ import type { ChatToolPayload } from '@lobechat/types';import { describe, expect, it } from 'vitest';import type { AgentState } from '../types';-import {- EMPTY_ARGS_TOOL_CONTENT,- EMPTY_ARGS_TOOL_REASON,- partitionEmptyArgumentsCalls,- toolExpectsNoArguments,-} from './emptyArgumentsCalls';+import { partitionEmptyArgumentsCalls, toolExpectsNoArguments } from './emptyArgumentsCalls';const makeState = (manifestMap: Record<string, unknown> = {}): AgentState =>({ toolManifestMap: manifestMap }) as unknown as AgentState;@@ -185,10 +180,3 @@ describe('partitionEmptyArgumentsCalls', () => {expect(result.emptyArgsCalls).toEqual([unknown]);});});--describe('rejection feedback constants', () => {- it('keeps the actionable single-call escape hint in the blocked content', () => {- expect(EMPTY_ARGS_TOOL_CONTENT).toContain('Call the tool again one call at a time');- expect(EMPTY_ARGS_TOOL_REASON).toBe('tool_arguments_empty');- });-});diff --git a/packages/const/src/heterogeneousAgent.test.ts b/packages/const/src/heterogeneousAgent.test.tsindex 3d4c162d277..22e97108705 100644--- a/packages/const/src/heterogeneousAgent.test.ts+++ b/packages/const/src/heterogeneousAgent.test.ts@@ -10,13 +10,11 @@ describe('isHeterogeneousAgentModelId', () => {it.each(['kimi-code', 'qoder'] as const)('includes %s so its bare model routes as a heterogeneous agent',(model) => {- expect(HETEROGENEOUS_AGENT_MODEL_IDS).toContain(model);expect(isHeterogeneousAgentModelId(model)).toBe(true);},);it('includes cursor so bare model: "cursor" routes as a heterogeneous agent', () => {- expect(HETEROGENEOUS_AGENT_MODEL_IDS).toContain('cursor');expect(isHeterogeneousAgentModelId('cursor')).toBe(true);});diff --git a/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts b/packages/context-engine/src/base/__tests__/BaseProcessor.test.tsindex 65c17b6e4c4..d07361c7713 100644--- a/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts+++ b/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts@@ -73,18 +73,6 @@ describe('BaseProcessor', () => {},});- describe('constructor', () => {- it('should initialize with options', () => {- const processor = new TestProcessor({ debug: true });- expect(processor.name).toBe('TestProcessor');- });-- it('should initialize without options', () => {- const processor = new TestProcessor();- expect(processor.name).toBe('TestProcessor');- });- });-describe('process', () => {it('should process valid context', async () => {const processor = new TestProcessor();diff --git a/packages/context-engine/src/base/__tests__/BaseProvider.test.ts b/packages/context-engine/src/base/__tests__/BaseProvider.test.tsindex eeb2cd5eff3..1abb03c0769 100644--- a/packages/context-engine/src/base/__tests__/BaseProvider.test.ts+++ b/packages/context-engine/src/base/__tests__/BaseProvider.test.ts@@ -94,18 +94,6 @@ describe('BaseProvider', () => {},});- describe('constructor', () => {- it('should initialize with options', () => {- const provider = new TestProvider({ debug: true });- expect(provider.name).toBe('TestProvider');- });-- it('should initialize without options', () => {- const provider = new TestProvider();- expect(provider.name).toBe('TestProvider');- });- });-describe('buildContext', () => {it('should return null by default', async () => {const provider = new TestProvider();diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.tsindex 8816340f755..185666ed1ae 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts@@ -271,21 +271,6 @@ describe('ToolResolver', () => {expect(result.enabledToolIds).toEqual(['web-search']);});- it('should keep manifests for step-activated tools even if not in original enabledToolIds', () => {- const opSet = makeOperationToolSet([mockSearchManifest]);- const delta: StepToolDelta = {- activatedTools: [- { id: 'local-system', manifest: mockLocalSystemManifest, source: 'device' },- ],- };-- const result = resolver.resolve(opSet, delta);-- // local-system was step-activated, so it should be in both enabledToolIds and manifestMap- expect(result.enabledToolIds).toContain('local-system');- expect(result.manifestMap['local-system']).toBeDefined();- });-it('should preserve deactivated manifests only in wildcard deactivation', () => {// When forceFinish deactivates all tools, manifests are kept for ToolNameResolverconst opSet = makeOperationToolSet([mockSearchManifest]);diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.tsindex 45f6b275b86..11a8e845672 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts@@ -1225,9 +1225,7 @@ describe('ToolsEngine', () => {excludeDefaultToolIds: manualModeExcludeToolIds,});- // Web browsing and sandbox should remain available even in manual mode- expect(result.enabledToolIds).toContain('lobe-web-browsing');- expect(result.enabledToolIds).toContain('lobe-cloud-sandbox');+ // Only the three execution tools should remain available in manual mode.expect(result.enabledToolIds).toHaveLength(3); // skills + web-browsing + cloud-sandbox});diff --git a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.tsindex a9ea0601c15..7aba7821664 100644--- a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts@@ -18,18 +18,6 @@ describe('MessageCleanupProcessor', () => {},});- describe('constructor', () => {- it('should initialize with default options', () => {- const processor = new MessageCleanupProcessor();- expect(processor.name).toBe('MessageCleanupProcessor');- });-- it('should initialize with custom options', () => {- const processor = new MessageCleanupProcessor({ debug: true });- expect(processor.name).toBe('MessageCleanupProcessor');- });- });-describe('process', () => {it('should clean system messages', async () => {const processor = new MessageCleanupProcessor();diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.tsindex cf870598e0a..4b17ff72898 100644--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.ts+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest';import type { PipelineContext } from '../../types';-import { HYDRATED_TOOL_RESULTS, PlaceholderVariablesProcessor } from '../PlaceholderVariables';+import { PlaceholderVariablesProcessor } from '../PlaceholderVariables';/*** Regression for the prompt-cache break caused by rewriting tool results.@@ -173,13 +173,4 @@ describe('PlaceholderVariablesProcessor β tool result passthrough', () => {// Not in the supplied allowlist β the default no longer applies.expect(result.messages[1].content).toBe('topic {{topic_id}}');});-- it('covers the activation surface ActivationResultTrimProcessor recognises', () => {- // Both processors must agree on which tool results are platform-authored- // documents; a skill activated but not injected keeps its tool result as the- // only channel for a SKILL.md body that references {{agent_id}}.- expect(HYDRATED_TOOL_RESULTS['lobe-activator']).toContain('activateTools');- expect(HYDRATED_TOOL_RESULTS['lobe-activator']).toContain('activateSkill');- expect(HYDRATED_TOOL_RESULTS['lobe-skills']).toContain('activateSkill');- });});diff --git a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.tsindex 31d2be6994a..ffe504ed048 100644--- a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts+++ b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts@@ -652,13 +652,6 @@ describe('StaleToolResultTrimProcessor', () => {describe('cacheEconomicsForProvider', () => {it('returns provider-specific policies and falls back to Anthropic', () => {- expect(cacheEconomicsForProvider('anthropic')).toEqual({- readPrice: 0.1,- ttlMs: 300_000,- writePrice: 1.25,- });- expect(cacheEconomicsForProvider('deepseek').ttlMs).toBe(3_600_000);- expect(cacheEconomicsForProvider('openai').writePrice).toBe(1);expect(cacheEconomicsForProvider('some-new-provider')).toEqual(cacheEconomicsForProvider('anthropic'),);diff --git a/packages/context-engine/src/processors/__tests__/ToolCall.test.ts b/packages/context-engine/src/processors/__tests__/ToolCall.test.tsindex dfe5940ab8d..695c3175f15 100644--- a/packages/context-engine/src/processors/__tests__/ToolCall.test.ts+++ b/packages/context-engine/src/processors/__tests__/ToolCall.test.ts@@ -24,18 +24,6 @@ describe('ToolCallProcessor', () => {provider: 'openai',};- describe('constructor', () => {- it('should initialize with config', () => {- const processor = new ToolCallProcessor(defaultConfig);- expect(processor.name).toBe('ToolCallProcessor');- });-- it('should initialize with custom options', () => {- const processor = new ToolCallProcessor(defaultConfig, { debug: true });- expect(processor.name).toBe('ToolCallProcessor');- });- });-describe('process - assistant messages', () => {it('should convert tools to tool_calls format', async () => {const processor = new ToolCallProcessor(defaultConfig);diff --git a/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.tsindex 86644edb071..b326ff75876 100644--- a/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts@@ -173,29 +173,6 @@ describe('GroupContextInjector', () => {});});- describe('Identity Rules Section', () => {- it('should always include identity rules', async () => {- const injector = new GroupContextInjector({- enabled: true,- // Minimal config- });-- const input: any[] = [- { role: 'system', content: 'Base prompt.' },- { role: 'user', content: 'Hello' },- ];-- const context = createContext(input);- const result = await injector.process(context);-- // Check injected message content- const injectedContent = result.messages[1].content;-- // Even with minimal config, identity rules should be present- expect(injectedContent).toMatchSnapshot();- });- });-describe('Edge Cases', () => {it('should handle empty members array', async () => {const injector = new GroupContextInjector({diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snapindex 461a142806d..46c1dfe8b6c 100644--- a/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap@@ -13,27 +13,6 @@ Empty group description<group_participants>The following agents are available in this group:-</group_participants>--<identity_rules>-- NEVER expose or display agent IDs to users - always refer to agents by their names-</identity_rules>-</group_context>"-`;--exports[`GroupContextInjector > Identity Rules Section > should always include identity rules 1`] = `-"<group_context>-You are "", acting as a in the multi-agent group "".-Your internal agent ID is (for system use only, never expose to users).--<group_description>The following describes the purpose and goals of this agent group:---</group_description>--<group_participants>The following agents are available in this group:--</group_participants><identity_rules>diff --git a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/index.test.tsindex cb7b186caa6..8d75ee76fd2 100644--- a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts+++ b/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts@@ -730,9 +730,6 @@ describe('countContextTokens', () => {expect(r.bySource.toolCalls).toBeGreaterThan(0);// tool.id ships as the flattened tool message's tool_call_idexpect(r.bySource.toolCallId).toBeGreaterThan(0);- expect(r.bySource.content).toBeGreaterThan(150);- expect(r.bySource.toolCalls).toBeGreaterThan(0);- expect(r.bySource.toolCallId).toBeGreaterThan(0);});it('counts nested assistantGroup members', () => {diff --git a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.tsindex 6fbe6dec68f..b768ffab116 100644--- a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts+++ b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts@@ -3,11 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { z } from 'zod';import { AskUserBridge } from '../askUser/AskUserBridge';-import {- ASK_USER_MCP_SERVER_NAME,- ASK_USER_TOOL_FULL_NAME,- ASK_USER_TOOL_NAME,-} from '../askUser/constants';+import { ASK_USER_TOOL_NAME } from '../askUser/constants';import { LobeBuiltinMcpServer } from './LobeBuiltinMcpServer';let server: LobeBuiltinMcpServer;@@ -130,9 +126,6 @@ describe('LobeBuiltinMcpServer', () => {const list = await client.listTools();expect(list.tools).toHaveLength(1);expect(list.tools[0].name).toBe(ASK_USER_TOOL_NAME);- expect(ASK_USER_TOOL_FULL_NAME).toBe(- `mcp__${ASK_USER_MCP_SERVER_NAME}__${ASK_USER_TOOL_NAME}`,- );} finally {await client.close();}diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsindex b80d4b0b6ba..c532f94d535 100644--- a/packages/heterogeneous-agents/src/config.test.ts+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -4,48 +4,14 @@ import {buildHeterogeneousAgentAuthRequiredError,buildHeterogeneousAgentCliNotFoundError,getHeterogeneousAgentConfig,- HETEROGENEOUS_AGENT_CONFIGS,isHeterogeneousAgentAuthRequired,isRemoteHeterogeneousType,resolveHeterogeneousAgentCommand,} from './config';-import { getHeterogeneousTypeLabel, HETEROGENEOUS_TYPE_LABELS } from './labels';+import { getHeterogeneousTypeLabel } from './labels';describe('heterogeneous agent config', () => {- it('defines create config for all registered agent types', () => {- expect(HETEROGENEOUS_AGENT_CONFIGS.map((config) => config.type)).toEqual([- 'amp',- 'claude-code',- 'codebuddy',- 'codex',- 'copilot',- 'cursor',- 'droid',- 'devin',- 'grok-build',- 'kimi-code',- 'opencode',- 'pi',- 'qoder',- 'trae',- ]);- });-- it('resolves descriptor metadata by type', () => {- expect(getHeterogeneousAgentConfig('claude-code')).toMatchObject({- defaultCommand: 'claude',- install: {- docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',- },- kind: 'local-cli',- title: 'Claude Code',- type: 'claude-code',- });- expect(getHeterogeneousAgentConfig('codex')).toMatchObject({- defaultCommand: 'codex',- title: 'Codex',- type: 'codex',- });+ it('resolves Copilot descriptor metadata by type', () => {expect(getHeterogeneousAgentConfig('copilot')).toMatchObject({auth: { signInCommand: 'copilot login' },defaultCommand: 'copilot',@@ -59,83 +25,11 @@ describe('heterogeneous agent config', () => {title: 'GitHub Copilot',type: 'copilot',});- expect(getHeterogeneousAgentConfig('codebuddy')).toMatchObject({- defaultCommand: 'codebuddy',- title: 'CodeBuddy',- type: 'codebuddy',- });- expect(getHeterogeneousAgentConfig('cursor')).toMatchObject({- defaultCommand: 'agent',- install: { commands: ['curl https://cursor.com/install -fsS | bash'] },- title: 'Cursor',- type: 'cursor',- });- expect(getHeterogeneousAgentConfig('droid')).toMatchObject({- auth: { signInCommand: 'droid' },- defaultCommand: 'droid',- install: {- commands: [- 'curl -fsSL https://app.factory.ai/cli | sh',- 'irm https://app.factory.ai/cli/windows | iex',- ],- },- title: 'Factory Droid',- type: 'droid',- });- expect(getHeterogeneousAgentConfig('amp')).toMatchObject({- defaultCommand: 'amp',- title: 'Amp',- type: 'amp',- });- expect(getHeterogeneousAgentConfig('devin')).toMatchObject({- auth: { signInCommand: 'devin auth login' },- defaultCommand: 'devin',- install: {- commands: expect.arrayContaining(['irm https://static.devin.ai/cli/setup.ps1 | iex']),- },- title: 'Devin',- type: 'devin',- });- expect(getHeterogeneousAgentConfig('grok-build')).toMatchObject({- auth: { signInCommand: 'grok login' },- defaultCommand: 'grok',- title: 'Grok Build',- type: 'grok-build',- });- expect(getHeterogeneousAgentConfig('kimi-code')).toMatchObject({- defaultCommand: 'kimi',- title: 'Kimi Code',- type: 'kimi-code',- });- expect(getHeterogeneousAgentConfig('opencode')).toMatchObject({- defaultCommand: 'opencode',- title: 'OpenCode',- type: 'opencode',- });- expect(getHeterogeneousAgentConfig('pi')).toMatchObject({- defaultCommand: 'pi',- title: 'Pi',- type: 'pi',- });- expect(getHeterogeneousAgentConfig('qoder')).toMatchObject({- auth: { docsUrl: 'https://docs.qoder.com/cli/auth.md' },- defaultCommand: 'qodercli',- title: 'Qoder',- type: 'qoder',- });- expect(getHeterogeneousAgentConfig('trae')).toMatchObject({- defaultCommand: 'traecli',- install: {- commands: [],- docsUrl: 'https://docs.volcengine.com/docs/86677/2387326?lang=zh',- },- title: 'TRAE CLI',- type: 'trae',- });});it('resolves commands from descriptors and fails loudly for unknown types', () => {expect(resolveHeterogeneousAgentCommand('claude-code')).toBe('claude');+ expect(resolveHeterogeneousAgentCommand('copilot')).toBe('copilot');expect(resolveHeterogeneousAgentCommand('claude-code', ' claude-beta ')).toBe('claude-beta');expect(() => resolveHeterogeneousAgentCommand('unknown-agent')).toThrow('Unknown local heterogeneous agent type: "unknown-agent"',@@ -190,29 +84,9 @@ describe('heterogeneous agent config', () => {});});- it('derives display labels from the shared config source', () => {- expect(HETEROGENEOUS_TYPE_LABELS).toEqual({- 'amp': 'Amp',- 'claude-code': 'Claude Code',- 'codebuddy': 'CodeBuddy',- 'codex': 'Codex',- 'copilot': 'GitHub Copilot',- 'cursor': 'Cursor',- 'droid': 'Factory Droid',- 'devin': 'Devin',- 'grok-build': 'Grok Build',- 'hermes': 'Hermes',- 'kimi-code': 'Kimi Code',- 'openclaw': 'OpenClaw',- 'opencode': 'OpenCode',- 'pi': 'Pi',- 'qoder': 'Qoder',- 'trae': 'TRAE CLI',- });- });-it('resolves display labels with safe fallbacks', () => {expect(getHeterogeneousTypeLabel('codebuddy')).toBe('CodeBuddy');+ expect(getHeterogeneousTypeLabel('copilot')).toBe('GitHub Copilot');expect(getHeterogeneousTypeLabel('hermes')).toBe('Hermes');expect(getHeterogeneousTypeLabel('future-runtime')).toBe('future-runtime');expect(getHeterogeneousTypeLabel('toString')).toBe('toString');diff --git a/packages/heterogeneous-agents/src/errors/specs.test.ts b/packages/heterogeneous-agents/src/errors/specs.test.tsindex 86b8c0911ad..c5133e93de0 100644--- a/packages/heterogeneous-agents/src/errors/specs.test.ts+++ b/packages/heterogeneous-agents/src/errors/specs.test.ts@@ -30,35 +30,12 @@ describe('hetero error taxonomy', () => {expect(new Set(ids).size).toBe(ids.length);});- it('only emits guide codes the client can actually render', () => {- const renderable = new Set([- 'auth_required',- 'cli_not_found',- 'overloaded',- 'rate_limit',- 'working_directory_not_found',- ]);- for (const spec of specs) {- if (spec.guideCode) expect(renderable).toContain(spec.guideCode);- }- });-it('never marks a user-attributed outcome as an operational failure', () => {for (const spec of specs) {if (spec.attribution === 'user') expect(spec.countAsFailure).toBe(false);}});- it('only treats transient kinds as retryable', () => {- const retryable = specs.filter((spec) => spec.retryable).map((spec) => spec.kind);- expect(retryable.toSorted()).toEqual(['network_drop', 'server_overloaded', 'server_throttle']);- });-- it('exposes exactly one fallback bucket', () => {- const fallbacks = specs.filter((spec) => spec.isFallback).map((spec) => spec.kind);- expect(fallbacks).toEqual(['agent_failed']);- });-it('formats and resolves stable ids', () => {expect(formatHeteroErrorId('usage_limit')).toBe('H2001');expect(formatHeteroErrorId('agent_failed')).toBe('H9002');diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.tsindex b277aa1fb56..e7c78c64754 100644--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts@@ -80,9 +80,3 @@ describe.runIf(runnable)('spawnDshAcpSession β live harness', () => {expect(await readFile(path.join(cwd, 'proof.txt'), 'utf8')).toContain('dsh-e2e-proof');}, 240_000);});--describe.skipIf(runnable)('spawnDshAcpSession β live harness (not runnable here)', () => {- it('needs DEEPSEEK_API_KEY and the dsh CLI', () => {- expect(runnable).toBe(false);- });-});diff --git a/packages/mecha/src/modelParams/resolveModelParams.test.ts b/packages/mecha/src/modelParams/resolveModelParams.test.tsindex 07a5de22b53..c3d95c6ced7 100644--- a/packages/mecha/src/modelParams/resolveModelParams.test.ts+++ b/packages/mecha/src/modelParams/resolveModelParams.test.ts@@ -426,14 +426,6 @@ describe('frozen model facts', () => {expect(frozenCard?.deploymentName).toBe('prod-endpoint');// The bundled card is preserved apart from the alias.expect(frozenCard).toMatchObject({ displayName: 'DeepSeek V4 Pro', id: 'deepseek-v4-pro' });- // And the transport's lookup answers from the snapshot as stored.- expect(- facts.cards.find(- (card) =>- card.providerId === 'deepseek' &&- (card.id === 'deepseek-v4-pro' || card.deploymentName === 'deepseek-v4-pro'),- )?.deploymentName,- ).toBe('prod-endpoint');});it('freezes a minimal deployment card for a custom model the bank has no card for', async () => {diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex 6ba787cdf05..e19181c12da 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -1031,14 +1031,6 @@ describe('resolveAgencyConfig', () => {expect(resolveAgencyConfig(undefined, undefined)).toBeUndefined();});- it('an override with only executionTarget leaves the shared boundDeviceId in place', () => {- const shared = { boundDeviceId: 'ws-device', executionTarget: 'device' as const };- expect(resolveAgencyConfig(shared, { executionTarget: 'sandbox' })).toEqual({- boundDeviceId: 'ws-device',- executionTarget: 'sandbox',- });- });-it('an override that unsets executionTarget by setting it to a defined value replaces the shared', () => {// Merge semantics: `undefined` in the override is treated as "not overriding".// Only *defined* values in the override win. Test both branches.diff --git a/packages/types/src/agent/agentIntervention.test.ts b/packages/types/src/agent/agentIntervention.test.tsindex bb7645eb52a..66f07057817 100644--- a/packages/types/src/agent/agentIntervention.test.ts+++ b/packages/types/src/agent/agentIntervention.test.ts@@ -1,18 +1,13 @@-import { describe, expect, expectTypeOf, it } from 'vitest';+import { describe, expectTypeOf, it } from 'vitest';import type {+ AGENT_INTERVENTION_CUSTOM_EXECUTION_STATES,AgentInterventionCustomExecutionResult,AgentInterventionCustomExecutionState,} from './agentIntervention';-import { AGENT_INTERVENTION_CUSTOM_EXECUTION_STATES } from './agentIntervention';describe('agent intervention custom execution types', () => {it('keeps the execution state union aligned with its runtime literals', () => {- expect(AGENT_INTERVENTION_CUSTOM_EXECUTION_STATES).toEqual([- 'pending',- 'executing',- 'completed',- ]);expectTypeOf<(typeof AGENT_INTERVENTION_CUSTOM_EXECUTION_STATES)[number]>().toEqualTypeOf<AgentInterventionCustomExecutionState>();diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.tsindex 9217aca4f13..bfdf16c69a4 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.test.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts@@ -4,7 +4,6 @@ import type { HeterogeneousProviderConfig } from './agencyConfig';import { buildHeteroSpawnArgs } from './agencyConfig';import {applyHeteroSelection,- CODEX_SERVER_DEFAULT_CUSTOM_MODELS,getHeteroSelectorCapability,HETEROGENEOUS_AGENT_DEFAULT_SELECTION,isCodexServerDefaultCustomModel,@@ -32,16 +31,7 @@ describe('selector availability', () => {expect(isHeteroSelectorAvailable(undefined)).toBe(false);});- it('exposes the dimensions each provider actually supports', () => {- expect(getHeteroSelectorCapability('amp')?.mode?.levels).toEqual([- 'low',- 'medium',- 'high',- 'ultra',- ]);- expect(getHeteroSelectorCapability('amp')?.model).toBeUndefined();- expect(getHeteroSelectorCapability('claude-code')?.speed).toBeUndefined();- expect(getHeteroSelectorCapability('codex')?.speed).toBeDefined();+ it('exposes the Copilot catalog and reasoning levels', () => {expect(getHeteroSelectorCapability('copilot')?.model?.source).toBe('catalog');expect(getHeteroSelectorCapability('copilot')?.effort?.levels()).toEqual(['low',@@ -50,31 +40,9 @@ describe('selector availability', () => {'xhigh','max',]);- expect(getHeteroSelectorCapability('cursor')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('droid')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('devin')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('grok-build')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('kimi-code')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('grok-build')?.effort?.levels('grok-4.6')).toEqual([- 'low',- 'medium',- 'high',- 'xhigh',- ]);- expect(getHeteroSelectorCapability('opencode')?.effort).toBeUndefined();- expect(getHeteroSelectorCapability('qoder')?.effort).toBeDefined();- expect(getHeteroSelectorCapability('codex')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('codebuddy')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('qoder')?.model?.source).toBe('catalog');- expect(getHeteroSelectorCapability('trae')?.model?.source).toBe('catalog');});- it('keeps non-OpenAI Codex relay support on an explicit allowlist', () => {- expect(CODEX_SERVER_DEFAULT_CUSTOM_MODELS).toEqual([- 'deepseek-v4-flash',- 'deepseek-v4-pro',- 'glm-5.2',- ]);+ it('recognizes supported non-OpenAI Codex relay models', () => {expect(isCodexServerDefaultCustomModel('deepseek-v4-pro')).toBe(true);expect(isCodexServerDefaultCustomModel('kimi-k2.6')).toBe(false);});diff --git a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.tsindex 6ef7835a807..d362f3a6f05 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts+++ b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts@@ -93,28 +93,11 @@ describe('dimensions per provider', () => {});});- it('labels Claude aliases without claiming a fixed model version', () => {- const options = viewOf({ type: 'claude-code' }).dimensions[0].options;- expect(options.slice(1)).toEqual([- { label: 'Fable', value: 'fable' },- { label: 'Opus', value: 'opus' },- { label: 'Sonnet', value: 'sonnet' },- { label: 'Haiku', value: 'haiku' },- ]);- });-it('offers Amp mode without inventing a model dimension', () => {const dimensions = viewOf({ type: 'amp' }).dimensions;expect(dimensions.map((dimension) => dimension.key)).toEqual(['mode']);expect(dimensions[0].label).toBe('heteroAgent.modelSelector.mode.label');- expect(dimensions[0].options.map((option) => option.value)).toEqual([- 'default',- 'low',- 'medium',- 'high',- 'ultra',- ]);});it('keeps reasoning and speed beside the catalog for a fast-capable codex model', () => {@@ -132,6 +115,28 @@ describe('dimensions per provider', () => {expect(dimensionKeys({ model: 'opus', type: 'claude-code' })).toEqual(['model', 'reasoning']);});+ it('keeps a Grok Build reasoning pick available and reflects it in the menu', () => {+ const provider: HeterogeneousProviderConfig = { model: 'grok-4.6', type: 'grok-build' };+ const updated = { ...provider, ...applyHeteroSelection(provider, { effort: 'xhigh' }) };+ const reasoning = viewOf(updated).dimensions.find((dimension) => dimension.key === 'reasoning');++ expect(reasoning).toMatchObject({+ current: 'xhigh',+ valueLabel: 'heteroAgent.modelSelector.reasoning.xhigh',+ });+ expect(reasoning?.options.map((option) => option.value)).toEqual([+ 'default',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ ]);+ expect(reasoning?.options).toContainEqual({+ label: 'heteroAgent.modelSelector.reasoning.xhigh',+ value: 'xhigh',+ });+ });+it('loads the CodeBuddy model dimension from its CLI catalog and keeps reasoning in the menu', () => {const view = viewOf({ effort: 'high', model: 'gpt-5.4', type: 'codebuddy' });diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.tsindex 884ab5389f6..48fa6ef1679 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts+++ b/src/features/ChatInput/ControlBar/HeteroModel/useModelCatalogView.test.ts@@ -32,11 +32,6 @@ describe('Model catalog view', () => {expect(result.current.selectedIsStale).toBe(false);});- it('renders the last successful catalog supplied by the shared cache', () => {- const { result } = renderHook(() => useModelCatalogView({ ...defaults, data: loaded }));- expect(result.current.rows).toEqual(loaded.models);- });-it('keeps off-catalog saved models pickable and marks them as stale only after discovery', () => {const { result, rerender } = renderHook(({ data }) => useModelCatalogView({ ...defaults, currentModel: 'custom-model', data }),diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.tsindex aabef0ee56e..baa0bbd618b 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts@@ -288,10 +288,7 @@ describe('resolveQuotaAccountSpawnPlan', () => {expect(selectAccountForAgent).not.toHaveBeenCalled();});- it('degrades to no routing when the agent is unbound or the service fails', async () => {- selectAccountForAgent.mockResolvedValueOnce(null);- expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });-+ it('degrades to no routing when the service fails', async () => {selectAccountForAgent.mockRejectedValueOnce(new Error('offline'));expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });});