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.

♻️ test: consolidate test simplification across modules (#22337)

Inneia5df92814145
diff --git a/.github/scripts/bundle-size-gate.test.cjs b/.github/scripts/bundle-size-gate.test.cjs
index c6c093e7b29..6d1ce64d15f 100644
--- a/.github/scripts/bundle-size-gate.test.cjs
+++ b/.github/scripts/bundle-size-gate.test.cjs
@@ -118,7 +118,7 @@ const runCheck = ({ baselineGraphCount, baselineJsTotal, currentGraphCount, curr
};
};
-test('Vite JS output file count over the baseline percentage limit fails the gate', () => {
+test('a JS file-count breach reports the diagnostic and failing heading', () => {
const result = runCheck({
baselineGraphCount: 10,
baselineJsTotal: 100,
@@ -127,6 +127,7 @@ test('Vite JS output file count over the baseline percentage limit fails the gat
});
assert.equal(result.status, 1);
assert.match(result.stderr, /Vite JS output file count increases by more than 5%/);
+ assert.ok(result.report.startsWith('### ❌ Web dist — exceeds the gate on 1 of 2 entries'));
});
test('a passing gate states the entry count and the largest delta in the heading', () => {
@@ -165,18 +166,6 @@ test('buildHeadline formats bytes only, but still counts a file-count breach', (
);
});
-test('a failing gate states how many entries are over it in the heading', () => {
- const result = runCheck({
- baselineGraphCount: 10,
- baselineJsTotal: 100,
- currentGraphCount: 10,
- currentJsTotal: 106,
- });
-
- assert.equal(result.status, 1);
- assert.ok(result.report.startsWith('### ❌ Web dist — exceeds the gate on 1 of 2 entries'));
-});
-
test('buildHeadline stays empty when nothing was comparable', () => {
assert.equal(buildHeadline([]), '');
assert.equal(
diff --git a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
index fffaca8a3a9..bd42c0003b2 100644
--- a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
@@ -8,6 +8,52 @@ import type { App } from '@/core/App';
import AuthCtr from '../AuthCtr';
import RemoteServerConfigCtr from '../RemoteServerConfigCtr';
+const createCloudAuthConfig = (): DataSyncConfig => ({
+ active: false,
+ storageMode: 'cloud',
+});
+
+const createTokenResponse = () => ({
+ status: 200,
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ access_token: 'new-access-token',
+ refresh_token: 'new-refresh-token',
+ expires_in: 3600,
+ }),
+ text: () => Promise.resolve('mock response'),
+ clone: () => ({
+ json: () =>
+ Promise.resolve({
+ access_token: 'new-access-token',
+ refresh_token: 'new-refresh-token',
+ expires_in: 3600,
+ }),
+ }),
+});
+
+const createAuthCodeResponse = () => ({
+ status: 200,
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ success: true,
+ data: {
+ payload: {
+ code: 'mock-auth-code',
+ state: 'mock-random-2', // Second randomBytes call is for state
+ },
+ },
+ }),
+ text: () => Promise.resolve('mock response'),
+});
+
+const createMissingAuthResponse = () => ({
+ status: 404,
+ ok: false,
+});
+
const { ipcMainHandleMock } = vi.hoisted(() => ({
ipcMainHandleMock: vi.fn(),
}));
@@ -142,15 +188,9 @@ describe('AuthCtr', () => {
describe('Basic functionality', () => {
describe('requestAuthorization', () => {
it('should generate PKCE parameters and open authorization URL', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
const result = await authCtr.requestAuthorization(config);
@@ -171,15 +211,9 @@ describe('AuthCtr', () => {
});
it('should start polling after authorization request', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
const result = await authCtr.requestAuthorization(config);
expect(result.success).toBe(true);
@@ -206,10 +240,7 @@ describe('AuthCtr', () => {
remoteServerUrl: 'https://my-custom-server.com',
};
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
await authCtr.requestAuthorization(config);
@@ -220,10 +251,7 @@ describe('AuthCtr', () => {
});
it('should handle authorization request error gracefully', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
vi.mocked(shell.openExternal).mockRejectedValue(new Error('Failed to open browser'));
@@ -236,15 +264,9 @@ describe('AuthCtr', () => {
describe('polling mechanism', () => {
it('should poll every 3 seconds', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
await authCtr.requestAuthorization(config);
@@ -266,10 +288,7 @@ describe('AuthCtr', () => {
});
it('should stop polling when credentials are received', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
let pollCount = 0;
mockFetch.mockImplementation((url: string) => {
@@ -279,51 +298,16 @@ describe('AuthCtr', () => {
if (urlObj.pathname.includes('/oidc/handoff')) {
pollCount++;
if (pollCount >= 3) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- success: true,
- data: {
- payload: {
- code: 'mock-auth-code',
- state: 'mock-random-2', // Second randomBytes call is for state
- },
- },
- }),
- text: () => Promise.resolve('mock response'),
- });
+ return Promise.resolve(createAuthCodeResponse());
}
}
// Token exchange endpoint
if (urlObj.pathname.includes('/oidc/token')) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- text: () => Promise.resolve('mock response'),
- clone: () => ({
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- }),
- });
+ return Promise.resolve(createTokenResponse());
}
- return Promise.resolve({
- status: 404,
- ok: false,
- });
+ return Promise.resolve(createMissingAuthResponse());
});
await authCtr.requestAuthorization(config);
@@ -339,52 +323,17 @@ describe('AuthCtr', () => {
});
it('should broadcast authorizationSuccessful when credentials are exchanged', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
mockFetch.mockImplementation((url: string) => {
const urlObj = new URL(url);
if (urlObj.pathname.includes('/oidc/handoff')) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- success: true,
- data: {
- payload: {
- code: 'mock-auth-code',
- state: 'mock-random-2', // Second randomBytes call is for state
- },
- },
- }),
- text: () => Promise.resolve('mock response'),
- });
+ return Promise.resolve(createAuthCodeResponse());
}
if (urlObj.pathname.includes('/oidc/token')) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- text: () => Promise.resolve('mock response'),
- clone: () => ({
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- }),
- });
+ return Promise.resolve(createTokenResponse());
}
return Promise.resolve({ status: 404, ok: false });
@@ -441,10 +390,7 @@ describe('AuthCtr', () => {
});
it('should validate state parameter and reject mismatched state', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
mockFetch.mockImplementation((url: string) => {
const urlObj = new URL(url);
@@ -483,52 +429,17 @@ describe('AuthCtr', () => {
describe('token refresh', () => {
it('should start auto-refresh after successful authorization', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
mockFetch.mockImplementation((url: string) => {
const urlObj = new URL(url);
if (urlObj.pathname.includes('/oidc/handoff')) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- success: true,
- data: {
- payload: {
- code: 'mock-auth-code',
- state: 'mock-random-2', // Second randomBytes call is for state
- },
- },
- }),
- text: () => Promise.resolve('mock response'),
- });
+ return Promise.resolve(createAuthCodeResponse());
}
if (urlObj.pathname.includes('/oidc/token')) {
- return Promise.resolve({
- status: 200,
- ok: true,
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- text: () => Promise.resolve('mock response'),
- clone: () => ({
- json: () =>
- Promise.resolve({
- access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
- expires_in: 3600,
- }),
- }),
- });
+ return Promise.resolve(createTokenResponse());
}
return Promise.resolve({ status: 404, ok: false });
@@ -556,16 +467,10 @@ describe('AuthCtr', () => {
describe('Scenario: Authorization Timeout and Retry', () => {
it('Step 1: User requests authorization but does not complete it within 5 minutes', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
// Mock: User never completes authorization, so polling always returns 404
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
// User clicks "Connect to Cloud" button
await authCtr.requestAuthorization(config);
@@ -588,15 +493,9 @@ describe('AuthCtr', () => {
});
it('Step 2: User clicks retry button after previous attempt', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
- mockFetch.mockResolvedValue({
- status: 404,
- ok: false,
- });
+ mockFetch.mockResolvedValue(createMissingAuthResponse());
// First attempt
await authCtr.requestAuthorization(config);
@@ -618,10 +517,7 @@ describe('AuthCtr', () => {
});
it('Step 3: Retry generates new state parameter (not reusing old state)', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
const capturedStates: string[] = [];
@@ -656,10 +552,7 @@ describe('AuthCtr', () => {
});
it('Step 4: User completes authorization on retry successfully', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
// First attempt - incomplete
mockFetch.mockResolvedValue({ status: 404, ok: false });
@@ -731,10 +624,7 @@ describe('AuthCtr', () => {
});
it('Edge case: Rapid retry clicks should not create multiple polling intervals', async () => {
- const config: DataSyncConfig = {
- active: false,
- storageMode: 'cloud',
- };
+ const config: DataSyncConfig = createCloudAuthConfig();
mockFetch.mockResolvedValue({ status: 404, ok: false });
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 9cead45f87b..a50a8b80684 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -22,6 +22,36 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as heteroCliProcessModule from '../../utils/heteroCliProcess';
import HeterogeneousAgentCtr, { redactPromptArgs } from '../HeterogeneousAgentImpl';
+const createAgentAppOptions = (appStoragePath: string) => ({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+});
+
+const createMockWindows = (send: ReturnType<typeof vi.fn>) => [
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+];
+
+const createCodexAppServerOptions = (): Parameters<HeterogeneousAgentCtr['startSession']>[0] => ({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+});
+
+const createProviderBinding = (): NonNullable<
+ Parameters<HeterogeneousAgentCtr['startSession']>[0]['providerBinding']
+> => ({
+ apiConfig: { model: 'gpt-test', providerId: 'openai' },
+ kind: 'provider',
+});
+
+const createCodexOptions = (): Parameters<HeterogeneousAgentCtr['startSession']>[0] => ({
+ agentType: 'codex',
+ command: 'codex',
+});
+
/**
* A fresh CLI session's serialized prompt leads with the `lh` introduction (Claude
* Code loads it as a skill instead); a resumed one (`startSession({ resumeSessionId })`) does not.
@@ -838,14 +868,8 @@ describe('HeterogeneousAgentCtr', () => {
proc.exitCode = null;
proc.signalCode = null;
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexOptions());
const prompt = ctr.sendPrompt({
operationId: 'op-cancel-wait',
prompt: 'sleep 60',
@@ -891,14 +915,12 @@ describe('HeterogeneousAgentCtr', () => {
proc.pid = 4242;
proc.signalCode = null;
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as unknown as ConstructorParameters<typeof HeterogeneousAgentCtr>[0]);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const ctr = new HeterogeneousAgentCtr(
+ createAgentAppOptions(appStoragePath) as unknown as ConstructorParameters<
+ typeof HeterogeneousAgentCtr
+ >[0],
+ );
+ const { sessionId } = await ctr.startSession(createCodexOptions());
const spawnCount = spawnCalls.length;
const prompt = ctr.sendPrompt({
operationId: 'op-cancel-timeout',
@@ -1088,10 +1110,7 @@ describe('HeterogeneousAgentCtr', () => {
updatedAt: Date.now(),
weekly: null,
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const params = { command: '/custom/bin/codex', env: { CODEX_HOME: '/tmp/codex-home' } };
await ctr.getCodexQuota(params);
@@ -1134,10 +1153,7 @@ describe('HeterogeneousAgentCtr', () => {
};
fetchCodexQuotaMock.mockResolvedValueOnce(initialQuota).mockResolvedValueOnce(refreshedQuota);
consumeCodexRateLimitResetCreditMock.mockResolvedValue('reset');
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const source = {
command: '/custom/bin/codex',
env: { CODEX_HOME: '/tmp/codex-home' },
@@ -1200,10 +1216,7 @@ describe('HeterogeneousAgentCtr', () => {
)
.mockResolvedValueOnce(refreshedQuota);
consumeCodexRateLimitResetCreditMock.mockResolvedValue('reset');
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const source = {
command: '/custom/bin/codex',
env: { CODEX_HOME: '/tmp/codex-home' },
@@ -1241,10 +1254,7 @@ describe('HeterogeneousAgentCtr', () => {
weekly: null,
} satisfies KimiCodeQuotaSnapshot;
fetchKimiCodeQuotaMock.mockResolvedValue(quota);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const params = {
env: { KIMI_CODE_HOME: '/tmp/kimi-code-home' },
kimiCodeHomePath: '/tmp/kimi-code-home',
@@ -1270,10 +1280,7 @@ describe('HeterogeneousAgentCtr', () => {
weekly: null,
} satisfies KimiCodeQuotaSnapshot;
fetchKimiCodeQuotaMock.mockResolvedValue(quota);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const params = { env: { KIMI_CODE_HOME: '/tmp/kimi-code-home' } };
await ctr.getKimiCodeQuota(params);
@@ -1291,10 +1298,7 @@ describe('HeterogeneousAgentCtr', () => {
it('drives the installed dsh CLI acp profile and broadcasts unified stream events', async () => {
const send = vi.fn();
mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
args: ['--config', '/custom/dsh.json'],
@@ -1345,10 +1349,7 @@ describe('HeterogeneousAgentCtr', () => {
it('does not re-send the session introduction when resuming a dsh session', async () => {
mockGetAllWindows.mockReturnValue([]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -1384,10 +1385,7 @@ describe('HeterogeneousAgentCtr', () => {
};
},
}));
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -1405,10 +1403,7 @@ describe('HeterogeneousAgentCtr', () => {
const send = vi.fn();
mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
dshDetectMock.mockResolvedValueOnce({ available: false, error: 'not found' });
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -1430,10 +1425,7 @@ describe('HeterogeneousAgentCtr', () => {
path: '/Users/me/.local/bin/dsh',
version: '0.0.1',
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -1449,10 +1441,7 @@ describe('HeterogeneousAgentCtr', () => {
it('does not launch the runtime when Stop lands before it starts', async () => {
const send = vi.fn();
mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -1633,16 +1622,8 @@ describe('HeterogeneousAgentCtr', () => {
it('uses Claude SDK streaming lab instead of spawning claude -p', async () => {
process.env.LOBE_CLAUDE_CODE_SDK = '1';
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
args: ['--model', 'claude-sonnet-4-6', '--effort', 'medium'],
@@ -1693,10 +1674,7 @@ describe('HeterogeneousAgentCtr', () => {
vi.setSystemTime(new Date(start.getTime() + 5000));
});
nextFakeProc = createFakeProc().proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
command: 'claude',
@@ -1725,10 +1703,7 @@ describe('HeterogeneousAgentCtr', () => {
// orphan that keeps writing the transcript a replay would read, and a
// PID-less ledger entry looks safe to recover next to it.
process.env.LOBE_CLAUDE_CODE_SDK = '1';
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
command: 'claude',
@@ -1760,10 +1735,7 @@ describe('HeterogeneousAgentCtr', () => {
it('does not start the Claude SDK when server-default execution is cancelled during preparation', async () => {
process.env.LOBE_CLAUDE_CODE_SDK = '1';
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'claude-code',
command: 'claude',
@@ -1950,16 +1922,8 @@ describe('HeterogeneousAgentCtr', () => {
it('routes Cursor through ACP and persists its native session id', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'cursor',
args: ['--model', 'composer-1.5'],
@@ -2003,12 +1967,7 @@ describe('HeterogeneousAgentCtr', () => {
it('forwards Cursor questions through the existing intervention bridge and returns the answer', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
let receivedAnswer: unknown;
cursorAcpSessionRunMock.mockImplementation(async (options) => {
receivedAnswer = await options.askUserBridge.pending({
@@ -2025,10 +1984,7 @@ describe('HeterogeneousAgentCtr', () => {
toolCallId: 'cursor-question-1',
});
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'cursor', command: 'agent' });
const run = ctr.sendPrompt({ operationId: 'op-cursor-question', prompt: 'work', sessionId });
@@ -2056,12 +2012,7 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies an exact Cursor ACP session/load not-found error for resume fallback', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
const missingSessionError = new AcpRpcResponseError('session/load', {
code: -32_602,
message: 'Session "legacy-cursor-session" not found',
@@ -2070,10 +2021,7 @@ describe('HeterogeneousAgentCtr', () => {
await options.onStderr('Cursor ACP diagnostic\n');
throw missingSessionError;
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'cursor',
command: 'agent',
@@ -2118,10 +2066,7 @@ describe('HeterogeneousAgentCtr', () => {
resolveRun = resolve;
}),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'cursor', command: 'agent' });
const run = ctr.sendPrompt({ operationId: 'op-cursor', prompt: 'work', sessionId });
await vi.waitFor(() => expect(cursorAcpSessionConstructMock).toHaveBeenCalledOnce());
@@ -2142,16 +2087,8 @@ describe('HeterogeneousAgentCtr', () => {
it('routes Devin through ACP and persists its native session and model', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'devin',
args: ['--model', 'claude-sonnet-4-6-thinking'],
@@ -2197,12 +2134,7 @@ describe('HeterogeneousAgentCtr', () => {
it('forwards Devin permission choices through the intervention bridge', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
let receivedAnswer: unknown;
devinAcpSessionRunMock.mockImplementation(async (options) => {
receivedAnswer = await options.askUserBridge.pending({
@@ -2219,10 +2151,7 @@ describe('HeterogeneousAgentCtr', () => {
toolCallId: 'devin-permission-1',
});
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'devin', command: 'devin' });
const run = ctr.sendPrompt({ operationId: 'op-devin-question', prompt: 'work', sessionId });
@@ -2254,12 +2183,7 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies a missing resumed Devin ACP session', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
const missingSessionError = new AcpRpcResponseError('session/load', {
code: -32_016,
data: {
@@ -2269,10 +2193,7 @@ describe('HeterogeneousAgentCtr', () => {
message: 'Session not found',
});
devinAcpSessionRunMock.mockRejectedValue(missingSessionError);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'devin',
command: 'devin',
@@ -2307,10 +2228,7 @@ describe('HeterogeneousAgentCtr', () => {
resolveRun = resolve;
}),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'devin', command: 'devin' });
const run = ctr.sendPrompt({ operationId: 'op-devin', prompt: 'work', sessionId });
await vi.waitFor(() => expect(devinAcpSessionConstructMock).toHaveBeenCalledOnce());
@@ -2331,16 +2249,8 @@ describe('HeterogeneousAgentCtr', () => {
it('uses the ACP runtime, persists the native session id, and broadcasts its lifecycle', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'grok-build',
args: ['--model', 'grok-build'],
@@ -2392,10 +2302,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('launches provider-bound Grok with a managed secret-free profile', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'grok-build',
args: ['--model', 'stale-model', '--effort', 'high'],
@@ -2405,10 +2312,7 @@ describe('HeterogeneousAgentCtr', () => {
GROK_CONFIG: 'untrusted',
XAI_API_KEY: 'stale-key',
},
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
const originalLegacyApiKey = process.env.GROK_CODE_XAI_API_KEY;
@@ -2464,10 +2368,7 @@ describe('HeterogeneousAgentCtr', () => {
resolveRun = resolve;
}),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'grok-build',
command: 'grok',
@@ -2484,19 +2385,11 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies ACP authentication failures for the existing sign-in guide', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
grokAcpSessionRunMock.mockRejectedValue(
new Error('Authentication required. Run `grok login`, then retry.'),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'grok-build',
command: 'grok',
@@ -2517,12 +2410,7 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies a missing resumed ACP session after broadcasting its terminal error', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
const missingSessionError = new AcpRpcResponseError('session/load', {
code: -32_603,
data: { code: 'FS_NOT_FOUND', detail: '/sessions/missing-grok-session' },
@@ -2547,10 +2435,7 @@ describe('HeterogeneousAgentCtr', () => {
]);
throw missingSessionError;
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'grok-build',
command: 'grok',
@@ -2594,10 +2479,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('does not classify a non-load ACP filesystem error as a stale resume session', () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const promptError = new AcpRpcResponseError('session/prompt', {
code: -32_603,
data: { code: 'FS_NOT_FOUND', detail: '/workspace/missing-file' },
@@ -2685,10 +2567,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('keeps the env-only binding across fresh and resumed runs without persisting the key', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const providerBinding = {
apiConfig: { model: 'upstream-model', providerId: 'custom-openai' },
kind: 'provider' as const,
@@ -2868,10 +2747,7 @@ describe('HeterogeneousAgentCtr', () => {
relayInvocation,
success: true,
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType,
command: agentType,
@@ -2915,10 +2791,7 @@ describe('HeterogeneousAgentCtr', () => {
model: 'kimi-k3',
nativeResponses: false,
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -2952,10 +2825,7 @@ describe('HeterogeneousAgentCtr', () => {
it('still launches server-default Codex when the model card cannot be read', async () => {
nextFakeProc = createFakeProc().proc;
describeServerDefaultModelMock.mockRejectedValueOnce(new Error('offline'));
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -2977,10 +2847,7 @@ describe('HeterogeneousAgentCtr', () => {
it('injects a Kimi operation token into its Anthropic credential env', async () => {
nextFakeProc = createFakeProc().proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'kimi-code',
command: 'kimi',
@@ -3023,10 +2890,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('injects a Pi operation token into its Responses credential env', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'pi',
command: 'pi',
@@ -3082,10 +2946,7 @@ describe('HeterogeneousAgentCtr', () => {
}),
);
nextFakeProc = createFakeProc().proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -3122,10 +2983,7 @@ describe('HeterogeneousAgentCtr', () => {
it('does not launch server-default Codex when cancelled during spawn preparation', async () => {
nextFakeProc = createFakeProc().proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -3172,10 +3030,7 @@ describe('HeterogeneousAgentCtr', () => {
storeManager: { get: vi.fn() },
binaryManager: { detect },
} as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const { sessionId } = await ctr.startSession(createCodexOptions());
await expect(
ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
@@ -3195,19 +3050,13 @@ describe('HeterogeneousAgentCtr', () => {
settings: { sdkType: 'openai', supportResponsesApi: true },
},
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
await expect(
ctr.startSession({
agentType: 'codex',
command: 'codex',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
}),
).rejects.toThrow('Model "openai/gpt-test" is disabled or unavailable.');
});
@@ -3222,10 +3071,7 @@ describe('HeterogeneousAgentCtr', () => {
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
const runsDir = path.join(appStoragePath, 'heteroAgent', 'runs');
expect(await readdir(runsDir)).toEqual([sessionId]);
@@ -3239,10 +3085,7 @@ describe('HeterogeneousAgentCtr', () => {
it('forces provider-bound Codex through exec without persisting or logging its secret', async () => {
const { cliArgs, options, sessionId } = await runSendPrompt('provider-bound prompt', {
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
useCodexAppServer: true,
});
@@ -3273,17 +3116,11 @@ describe('HeterogeneousAgentCtr', () => {
throw new Error('spawn failed');
},
};
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
await expect(
@@ -3295,25 +3132,16 @@ describe('HeterogeneousAgentCtr', () => {
});
it('resumes a provider-bound session only when the resolved binding key matches', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const first = await ctr.startSession({
agentType: 'codex',
command: 'codex',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
const legacy = await ctr.startSession({
agentType: 'codex',
command: 'codex',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
resumeSessionId: 'thread-without-binding-key',
});
const rejected = await ctr.startSession({
@@ -3359,10 +3187,7 @@ describe('HeterogeneousAgentCtr', () => {
storeManager: { get: vi.fn() },
binaryManager: { detect },
} as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const { sessionId } = await ctr.startSession(createCodexOptions());
await expect(
ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
@@ -3450,10 +3275,7 @@ describe('HeterogeneousAgentCtr', () => {
storeManager: { get: vi.fn() },
binaryManager: { detect },
} as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const { sessionId } = await ctr.startSession(createCodexOptions());
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
expect(spawnCalls[0].command).toBe(resolvedPath);
@@ -3538,16 +3360,8 @@ describe('HeterogeneousAgentCtr', () => {
it('uses Codex app-server lab instead of spawning codex exec', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
args: ['--model', 'gpt-5.5-codex'],
@@ -3588,15 +3402,8 @@ describe('HeterogeneousAgentCtr', () => {
});
it('reuses one native thread session across multiple turns', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexAppServerOptions());
await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId });
await ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId });
@@ -3610,20 +3417,9 @@ describe('HeterogeneousAgentCtr', () => {
});
it('does not switch to exec when the shared native client is incompatible', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const first = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
- const second = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const first = await ctr.startSession(createCodexAppServerOptions());
+ const second = await ctr.startSession(createCodexAppServerOptions());
await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
codexAppServerCanReuse.value = false;
@@ -3638,15 +3434,8 @@ describe('HeterogeneousAgentCtr', () => {
it('replaces an incompatible shared client after its last thread session closes', async () => {
codexAppServerShouldFailAfterThread.value = true;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const first = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const first = await ctr.startSession(createCodexAppServerOptions());
await expect(
ctr.sendPrompt({ operationId: 'op-1', prompt: 'fail', sessionId: first.sessionId }),
).rejects.toThrow('Codex app-server disconnected');
@@ -3654,11 +3443,7 @@ describe('HeterogeneousAgentCtr', () => {
codexAppServerShouldFailAfterThread.value = false;
codexAppServerCanReuse.value = false;
- const second = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const second = await ctr.startSession(createCodexAppServerOptions());
await ctr.sendPrompt({ operationId: 'op-2', prompt: 'retry', sessionId: second.sessionId });
expect(codexAppServerClientCloseMock).toHaveBeenCalledOnce();
@@ -3672,10 +3457,7 @@ describe('HeterogeneousAgentCtr', () => {
])('keeps unsupported Codex $label arguments on exec', async ({ args }) => {
const { proc } = createFakeProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
args,
@@ -3692,10 +3474,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('does not replay an existing thread through exec when its arguments are unsupported', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
args: ['--profile', 'work'],
@@ -3715,24 +3494,12 @@ describe('HeterogeneousAgentCtr', () => {
it('falls back to codex exec when the native handshake is incompatible', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
const { proc } = createFakeProc();
nextFakeProc = proc;
codexAppServerShouldFallback.value = true;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexAppServerOptions());
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'fallback safely', sessionId });
@@ -3760,15 +3527,8 @@ describe('HeterogeneousAgentCtr', () => {
it('does not fall back to exec after the native thread is established', async () => {
codexAppServerShouldFailAfterThread.value = true;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexAppServerOptions());
await expect(
ctr.sendPrompt({ operationId: 'op-test', prompt: 'do not replay', sessionId }),
@@ -3784,15 +3544,8 @@ describe('HeterogeneousAgentCtr', () => {
});
it('clears a closed native thread session after a genuine interrupt failure', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexAppServerOptions());
await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId });
codexAppServerInterruptMock.mockRejectedValueOnce(new Error('Interrupt rejected'));
@@ -3805,10 +3558,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('resumes existing Codex threads through native app-server', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -3827,10 +3577,7 @@ describe('HeterogeneousAgentCtr', () => {
it('does not replay an existing Codex thread through exec when thread/resume fails', async () => {
codexAppServerShouldFailResume.value = true;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'codex',
command: 'codex',
@@ -3925,14 +3672,8 @@ describe('HeterogeneousAgentCtr', () => {
];
const { proc } = createFakeProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexOptions());
await expect(
ctr.sendPrompt({
@@ -3962,14 +3703,8 @@ describe('HeterogeneousAgentCtr', () => {
],
});
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const { sessionId } = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- });
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
+ const { sessionId } = await ctr.startSession(createCodexOptions());
await expect(
ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
@@ -4141,10 +3876,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('classifies stale Codex resume stderr as a structured resume error', () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const payload = (ctr as any).getSessionErrorPayload(
'No conversation found for thread thread_stale_123',
@@ -4171,10 +3903,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('classifies CLI authentication failures as auth-required errors', () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const payload = (ctr as any).getSessionErrorPayload(
'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}',
@@ -4199,10 +3928,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('classifies missing credentials for Pi as an auth-required error', () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const payload = (ctr as any).getSessionErrorPayload(
'No API key found for provider anthropic',
@@ -4228,16 +3954,8 @@ describe('HeterogeneousAgentCtr', () => {
describe('sendPrompt (droid)', () => {
it('routes Factory Droid through ACP and persists the native session id', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'droid',
args: ['--tag', 'lobe'],
@@ -4278,12 +3996,7 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies a missing Droid ACP session for resume fallback', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
const missingSessionError = new AcpRpcResponseError('session/load', {
code: -32_603,
data: { details: 'Session missing-droid-session not found' },
@@ -4293,10 +4006,7 @@ describe('HeterogeneousAgentCtr', () => {
await options.onStderr('Droid ACP diagnostic\n');
throw missingSessionError;
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'droid',
command: 'droid',
@@ -4334,16 +4044,8 @@ describe('HeterogeneousAgentCtr', () => {
describe('sendPrompt (trae)', () => {
it('routes TRAE through ACP and persists the native session id', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'trae',
args: ['--feature=test'],
@@ -4383,10 +4085,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('launches a provider-bound TRAE session with invocation-local config and existing auth', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'trae',
args: ['--model', 'stale-model', '--profile', 'personal', '--permission-mode', 'auto'],
@@ -4397,10 +4096,7 @@ describe('HeterogeneousAgentCtr', () => {
TRAE_HOME: '/user/trae',
},
initialModel: 'stale-native-model',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
await ctr.sendPrompt({ operationId: 'op-trae-provider', prompt: 'hello', sessionId });
@@ -4442,10 +4138,7 @@ describe('HeterogeneousAgentCtr', () => {
});
it('uses invocation-local TRAE config and existing auth for server-default runs', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'trae',
command: 'traecli',
@@ -4521,10 +4214,7 @@ describe('HeterogeneousAgentCtr', () => {
const providerSession = await ctr.startSession({
agentType: 'trae',
command: 'traecli',
- providerBinding: {
- apiConfig: { model: 'gpt-test', providerId: 'openai' },
- kind: 'provider',
- },
+ providerBinding: createProviderBinding(),
});
await expect(
@@ -4553,20 +4243,12 @@ describe('HeterogeneousAgentCtr', () => {
it('classifies authentication diagnostics emitted only on ACP stderr', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
traeAcpSessionRunMock.mockImplementation(async (options) => {
await options.onStderr('Please sign in through TRAE Enterprise\n');
throw new Error('TRAE ACP exited unexpectedly (code 1, signal null)');
});
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'trae',
command: 'traecli',
@@ -4590,16 +4272,8 @@ describe('HeterogeneousAgentCtr', () => {
describe('sendPrompt (pi rpc)', () => {
it('routes pi prompts through the RPC transport with resume args and captures the native session id', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'pi',
args: ['--provider', 'anthropic'],
@@ -4627,12 +4301,7 @@ describe('HeterogeneousAgentCtr', () => {
it('waits for RPC cancellation instead of killing the process tree', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
let resolveRun: ((result: { aborted: boolean }) => void) | undefined;
piRpcSessionRunMock.mockImplementation(
() =>
@@ -4640,10 +4309,7 @@ describe('HeterogeneousAgentCtr', () => {
resolveRun = resolve;
}),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'pi',
command: 'pi',
@@ -4678,10 +4344,7 @@ describe('HeterogeneousAgentCtr', () => {
piRpcSessionRunMock.mockReturnValue(
new Promise<{ aborted: boolean }>((resolve) => (finishRun = resolve)),
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
const run = ctr.sendPrompt({ operationId: 'op-pi', prompt: 'work', sessionId });
await vi.waitFor(() => expect(piRpcSessionRunMock).toHaveBeenCalled());
@@ -4696,16 +4359,8 @@ describe('HeterogeneousAgentCtr', () => {
it('reuses the pooled process across turns of the same conversation', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
// Turn 1: no native id yet → spawn a fresh process.
const env = { LOBEHUB_AGENT_ID: 'agent-pi', LOBEHUB_TOPIC_ID: 'topic-pi' };
@@ -4757,16 +4412,8 @@ describe('HeterogeneousAgentCtr', () => {
'spawns fresh when runtime options change between turns: $secondOptions',
async ({ firstOptions, secondOptions }) => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
// Turn 1 with one runtime configuration.
const first = await ctr.startSession({
@@ -4797,17 +4444,9 @@ describe('HeterogeneousAgentCtr', () => {
it('reaps an idle pooled pi process after the grace window', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
process.env.LOBE_PI_RPC_IDLE_TIMEOUT_MS = '60';
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
await ctr.sendPrompt({ operationId: 'op-idle', prompt: 'x', sessionId });
@@ -4818,17 +4457,9 @@ describe('HeterogeneousAgentCtr', () => {
it('surfaces pi RPC failures as session errors without a json fallback', async () => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
piRpcSessionRunMock.mockRejectedValue(new Error('pi RPC exited unexpectedly (code 1)'));
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'pi',
command: 'pi',
@@ -4905,16 +4536,8 @@ describe('HeterogeneousAgentCtr', () => {
'does not start $label when cancelled during transport preparation',
async ({ agentType, command, constructMock, runMock, useCodexAppServer }) => {
const send = vi.fn();
- mockGetAllWindows.mockReturnValue([
- {
- isDestroyed: () => false,
- webContents: { send },
- },
- ]);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ mockGetAllWindows.mockReturnValue(createMockWindows(send));
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType,
command,
@@ -4980,10 +4603,7 @@ describe('HeterogeneousAgentCtr', () => {
it('uses the self-contained embedded CLI instead of a global lh from PATH', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec(params);
@@ -5036,10 +4656,7 @@ describe('HeterogeneousAgentCtr', () => {
try {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec({ ...params, agentId, assistantMessageId: undefined });
proc.emit('spawn');
@@ -5061,10 +4678,7 @@ describe('HeterogeneousAgentCtr', () => {
it('forwards the topic workspace as LOBEHUB_WORKSPACE_ID for ingest', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec({ ...params, workspaceId: 'ws-lobehub' });
proc.emit('spawn');
@@ -5078,10 +4692,7 @@ describe('HeterogeneousAgentCtr', () => {
it('encodes primary and resume fallback contexts for the embedded CLI', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec({
...params,
@@ -5112,10 +4723,7 @@ describe('HeterogeneousAgentCtr', () => {
it('rejects the gateway request when the embedded CLI cannot spawn', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec(params);
proc.emit('error', new Error('spawn EACCES'));
@@ -5129,10 +4737,7 @@ describe('HeterogeneousAgentCtr', () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
mockMissingDir(missingCwd);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec({ ...params, cwd: missingCwd });
@@ -5152,10 +4757,7 @@ describe('HeterogeneousAgentCtr', () => {
vi.mocked(existsSync).mockImplementation(
(candidate) => candidate !== '/fake/cli/dist/index.js',
);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
await expect(ctr.spawnLhHeteroExec(params)).resolves.toEqual({
reason: `Embedded CLI not found at ${path.normalize('/fake/cli/dist/index.js')}`,
@@ -5170,10 +4772,7 @@ describe('HeterogeneousAgentCtr', () => {
throw new Error('write EPIPE');
});
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec(params);
expect(() => proc.emit('spawn')).not.toThrow();
@@ -5184,10 +4783,7 @@ describe('HeterogeneousAgentCtr', () => {
it('handles a late stdin EPIPE after acceptance without an uncaught stream error', async () => {
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const ack = ctr.spawnLhHeteroExec(params);
proc.emit('spawn');
@@ -5220,10 +4816,7 @@ describe('HeterogeneousAgentCtr', () => {
});
const proc = createGatewayCliProc();
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
try {
const ack = ctr.spawnLhHeteroExec(params);
@@ -5335,10 +4928,7 @@ describe('HeterogeneousAgentCtr', () => {
{ type: 'turn.completed' },
].map((record) => JSON.stringify(record) + '\n'),
}).proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const upload = vi.fn(async () => {
if (mode === 'failed') throw new Error('Upload rejected');
return { fileId: 'file-dog', url: 'https://cdn/dog.png' };
@@ -5422,10 +5012,7 @@ describe('HeterogeneousAgentCtr', () => {
};
nextFakeProc = proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'codex', command: 'codex' });
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
@@ -5460,10 +5047,7 @@ describe('HeterogeneousAgentCtr', () => {
})}\n`;
nextFakeProc = createFakeProc({ stdoutLines: [initLine, assistantLine] }).proc;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'amp', command: 'amp' });
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId });
@@ -5537,10 +5121,7 @@ describe('HeterogeneousAgentCtr', () => {
proc.kill = vi.fn();
proc.killed = false;
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
proc.__start = () => {
setImmediate(() => {
@@ -5633,10 +5214,7 @@ describe('HeterogeneousAgentCtr', () => {
electron.app.on.mockClear();
electron.app.quit.mockClear();
vi.spyOn(process, 'on').mockImplementation(() => process);
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
const session = (ctr as any).sessions.get(sessionId);
let finishActive!: () => void;
@@ -5677,10 +5255,7 @@ describe('HeterogeneousAgentCtr', () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
electron.app.quit.mockClear();
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({
agentType: 'deepseek-harness',
command: '',
@@ -5711,10 +5286,7 @@ describe('HeterogeneousAgentCtr', () => {
it('before-quit closes a running TRAE ACP session', async () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const { sessionId } = await ctr.startSession({ agentType: 'trae', command: 'traecli' });
const session = (ctr as any).sessions.get(sessionId);
session.traeAcpSession = { close: traeAcpSessionCloseMock };
@@ -5732,10 +5304,7 @@ describe('HeterogeneousAgentCtr', () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const fileA = await seedPendingIntervention(ctr, 'opA');
const fileB = await seedPendingIntervention(ctr, 'opB');
@@ -5762,10 +5331,7 @@ describe('HeterogeneousAgentCtr', () => {
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 ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const file = await seedPendingIntervention(ctr, 'opSigterm');
ctr.afterAppReady();
@@ -5782,10 +5348,7 @@ describe('HeterogeneousAgentCtr', () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
+ const ctr = new HeterogeneousAgentCtr(createAgentAppOptions(appStoragePath) as any);
const file = await seedPendingIntervention(ctr, 'opIdempotent');
// Pre-delete the file out from under the controller — simulates a
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index f9e33a5f8cf..e0d7a95928d 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -7,6 +7,21 @@ import { type App } from '@/core/App';
import LocalFileCtr from '../LocalFileCtr';
+const createFileStats = (isDirectory: boolean, size: number) => ({
+ isDirectory: () => isDirectory,
+ birthtime: new Date('2024-01-01'),
+ mtime: new Date('2024-01-15'),
+ atime: new Date('2024-01-20'),
+ size,
+});
+
+const createEditFileInput = () => ({
+ file_path: '/test/file.txt',
+ old_string: 'Hello',
+ new_string: 'Hi',
+ replace_all: false,
+});
+
const { getProjectFileIndexMock, ipcMainHandleMock, fetchMock } = vi.hoisted(() => ({
getProjectFileIndexMock: vi.fn(),
ipcMainHandleMock: vi.fn(),
@@ -1165,12 +1180,7 @@ describe('LocalFileCtr', () => {
it('should replace a unique occurrence successfully', async () => {
const disk = useDisk({ '/test/file.txt': 'Hello world\nGreetings again\nGoodbye world' });
- const result = await localFileCtr.handleEditFile({
- file_path: '/test/file.txt',
- old_string: 'Hello',
- new_string: 'Hi',
- replace_all: false,
- });
+ const result = await localFileCtr.handleEditFile(createEditFileInput());
expect(result.success).toBe(true);
expect(result.replacements).toBe(1);
@@ -1187,12 +1197,7 @@ describe('LocalFileCtr', () => {
const originalContent = 'Hello world\nHello again\nGoodbye world';
vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
- const result = await localFileCtr.handleEditFile({
- file_path: '/test/file.txt',
- old_string: 'Hello',
- new_string: 'Hi',
- replace_all: false,
- });
+ const result = await localFileCtr.handleEditFile(createEditFileInput());
expect(result.success).toBe(false);
expect(result.replacements).toBe(0);
@@ -1256,12 +1261,7 @@ describe('LocalFileCtr', () => {
it('should handle file read error', async () => {
vi.mocked(mockFsPromises.readFile).mockRejectedValue(new Error('Permission denied'));
- const result = await localFileCtr.handleEditFile({
- file_path: '/test/file.txt',
- old_string: 'Hello',
- new_string: 'Hi',
- replace_all: false,
- });
+ const result = await localFileCtr.handleEditFile(createEditFileInput());
expect(result.success).toBe(false);
expect(result.error).toBe('Permission denied');
@@ -1273,12 +1273,7 @@ describe('LocalFileCtr', () => {
vi.mocked(mockFsPromises.readFile).mockResolvedValue(originalContent);
vi.mocked(mockFsPromises.writeFile).mockRejectedValue(new Error('Disk full'));
- const result = await localFileCtr.handleEditFile({
- file_path: '/test/file.txt',
- old_string: 'Hello',
- new_string: 'Hi',
- replace_all: false,
- });
+ const result = await localFileCtr.handleEditFile(createEditFileInput());
expect(result.success).toBe(false);
expect(result.error).toBe('Disk full');
@@ -1307,13 +1302,7 @@ describe('LocalFileCtr', () => {
vi.mocked(mockFsPromises.stat).mockImplementation(async (filePath) => {
const name = (filePath as string).split('/').pop();
if (name === 'folder1') {
- return {
- isDirectory: () => true,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 4096,
- } as any;
+ return createFileStats(true, 4096) as any;
}
return {
isDirectory: () => false,
@@ -1341,13 +1330,7 @@ describe('LocalFileCtr', () => {
vi.mocked(mockFsPromises.stat).mockImplementation(async (filePath) => {
const name = (filePath as string).split('/').pop();
if (name === 'folder1') {
- return {
- isDirectory: () => true,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 4096,
- } as any;
+ return createFileStats(true, 4096) as any;
}
return {
isDirectory: () => false,
@@ -1393,13 +1376,7 @@ describe('LocalFileCtr', () => {
it('should sort by name ascending when specified', async () => {
vi.mocked(mockFsPromises.readdir).mockResolvedValue(['zebra.txt', 'alpha.txt', 'apple.txt']);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(false, 1024) as any);
const result = await localFileCtr.listLocalFiles({
path: '/test',
@@ -1469,13 +1446,7 @@ describe('LocalFileCtr', () => {
'file4.txt',
'file5.txt',
]);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(false, 1024) as any);
const result = await localFileCtr.listLocalFiles({
path: '/test',
@@ -1490,13 +1461,7 @@ describe('LocalFileCtr', () => {
// Create 150 files
const files = Array.from({ length: 150 }, (_, i) => `file${i}.txt`);
vi.mocked(mockFsPromises.readdir).mockResolvedValue(files);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(false, 1024) as any);
const result = await localFileCtr.listLocalFiles({ path: '/test' });
@@ -1568,13 +1533,7 @@ describe('LocalFileCtr', () => {
it('should sort by name descending when specified', async () => {
vi.mocked(mockFsPromises.readdir).mockResolvedValue(['alpha.txt', 'zebra.txt', 'middle.txt']);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(false, 1024) as any);
const result = await localFileCtr.listLocalFiles({
path: '/test',
@@ -1692,13 +1651,7 @@ describe('LocalFileCtr', () => {
it('should handle limit larger than file count', async () => {
vi.mocked(mockFsPromises.readdir).mockResolvedValue(['file1.txt', 'file2.txt']);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(false, 1024) as any);
const result = await localFileCtr.listLocalFiles({
path: '/test',
@@ -1754,13 +1707,7 @@ describe('LocalFileCtr', () => {
if ((filePath as string).includes('bad.txt')) {
throw new Error('Cannot stat file');
}
- return {
- isDirectory: () => false,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 1024,
- } as any;
+ return createFileStats(false, 1024) as any;
});
const result = await localFileCtr.listLocalFiles({ path: '/test' });
@@ -1773,13 +1720,7 @@ describe('LocalFileCtr', () => {
it('should handle directory type correctly', async () => {
vi.mocked(mockFsPromises.readdir).mockResolvedValue(['my_folder']);
- vi.mocked(mockFsPromises.stat).mockResolvedValue({
- isDirectory: () => true,
- birthtime: new Date('2024-01-01'),
- mtime: new Date('2024-01-15'),
- atime: new Date('2024-01-20'),
- size: 4096,
- } as any);
+ vi.mocked(mockFsPromises.stat).mockResolvedValue(createFileStats(true, 4096) as any);
const result = await localFileCtr.listLocalFiles({ path: '/test' });
diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts
index 5eb93ec3ce4..35d4f441cd5 100644
--- a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts
@@ -6,6 +6,16 @@ import type { App } from '@/core/App';
import McpCtr from '../McpCtr';
+const createStdioToolInput = (
+ toolName: string,
+ env: Record<string, string> | undefined,
+): Parameters<McpCtr['runStdioMcpTool']>[0] => ({
+ args: '',
+ env,
+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
+ toolName,
+});
+
const { mcpClientMocks } = vi.hoisted(() => ({
mcpClientMocks: vi.fn(),
}));
@@ -189,18 +199,8 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const instance = makeClientInstance('first');
mcpClientMocks.mockReturnValue(instance);
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'open_database',
- } as any);
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any);
// Exactly ONE MCPClient was constructed for both calls: the stdio
// process is NOT respawned per call, so server-side state survives.
@@ -217,12 +217,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const second = makeClientInstance('b');
mcpClientMocks.mockReturnValueOnce(first).mockReturnValueOnce(second);
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'open_database',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
await ctr.runStdioMcpTool({
args: '',
env: { IDB_PATH: '/other' },
@@ -243,12 +238,9 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const fresh = makeClientInstance('fresh');
mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);
- const result = await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any);
+ const result = await ctr.runStdioMcpTool(
+ createStdioToolInput('execute_python', undefined) as any,
+ );
// The stale session was evicted + disconnected, the retry succeeded.
expect(stale.disconnect).toHaveBeenCalledTimes(1);
@@ -256,12 +248,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
expect(result.success).toBe(true);
// Next call reuses the replacement session (pool stays warm).
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any);
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
});
@@ -277,12 +264,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
});
await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
).rejects.toThrow('Session not found');
});
@@ -294,12 +276,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValue(pooled);
await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
).rejects.toThrow('no open database instance');
// App-level failure: no eviction, no disconnect, no second invocation.
@@ -385,12 +362,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValue(pooled);
await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'delete_record',
- } as any),
+ ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined) as any),
).rejects.toThrow('tool execution failed');
// Exactly one invocation, no eviction, no disconnect.
@@ -416,12 +388,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
return instance;
});
- const params = {
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'open_database',
- } as any;
+ const params = createStdioToolInput('open_database', undefined) as any;
const first = ctr.runStdioMcpTool(params);
// Let the first call reach its pending initialize() before the second.
@@ -455,12 +422,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
.mockReturnValue(replacement);
await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
).rejects.toThrow('Session not found');
// Both the stale session and the proven-dead replacement were evicted.
@@ -481,12 +443,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
.mockReturnValueOnce(replacement) // single-flight creates ONE replacement
.mockReturnValue(replacement);
- const params = {
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'execute_python',
- } as any;
+ const params = createStdioToolInput('execute_python', undefined) as any;
// Two concurrent calls share the stale session; both fail stale and both
// enter the retry path.
@@ -599,18 +556,8 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const b = makeClientInstance('b');
mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any);
- await ctr.runStdioMcpTool({
- args: '',
- env: { TOKEN: 'x' },
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }) as any);
await (ctr as any).disposeAllPooledClients();
@@ -639,12 +586,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}),
);
- const params = {
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any;
+ const params = createStdioToolInput('t', undefined) as any;
const manifestPromise = ctr.getStdioMcpServerManifest(params);
await vi.waitFor(() => {
@@ -691,12 +633,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}),
);
- const params = {
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any;
+ const params = createStdioToolInput('t', undefined) as any;
const callPromise = ctr.runStdioMcpTool(params);
await vi.advanceTimersByTimeAsync(31 * 60 * 1000);
@@ -744,12 +681,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValueOnce(dead).mockReturnValue(replacement);
await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'delete_record',
- } as any),
+ ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined) as any),
).rejects.toThrow('Connection closed');
// Dead session evicted + disconnected; the failure was still surfaced
@@ -760,12 +692,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
expect(mcpClientMocks).toHaveBeenCalledTimes(1);
// The next call builds a FRESH session instead of reusing the corpse.
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 'open_database',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
expect(replacement.callTool).toHaveBeenCalledTimes(1);
});
@@ -780,14 +707,9 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
);
mcpClientMocks.mockReturnValue(pooled);
- await expect(
- ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any),
- ).rejects.toThrow('Connection closed by tool sandbox');
+ await expect(ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any)).rejects.toThrow(
+ 'Connection closed by tool sandbox',
+ );
expect(pooled.disconnect).not.toHaveBeenCalled();
expect(mcpClientMocks).toHaveBeenCalledTimes(1);
@@ -817,12 +739,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}),
);
- const longParams = {
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any;
+ const longParams = createStdioToolInput('t', undefined) as any;
const callPromise = ctr.runStdioMcpTool(longParams);
await vi.advanceTimersByTimeAsync(40 * 60 * 1000);
await callPromise;
@@ -855,18 +772,8 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
});
mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);
- await ctr.runStdioMcpTool({
- args: '',
- env: undefined,
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any);
- await ctr.runStdioMcpTool({
- args: '',
- env: { TOKEN: 'x' },
- params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
- toolName: 't',
- } as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }) as any);
// The disposal promise resolves only after BOTH teardowns settle, and
// both were initiated up front (b's disconnect is called before a's
diff --git a/apps/desktop/src/main/controllers/__tests__/NetworkProxyCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NetworkProxyCtr.test.ts
index 84ead147125..fcd0f210ad3 100644
--- a/apps/desktop/src/main/controllers/__tests__/NetworkProxyCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/NetworkProxyCtr.test.ts
@@ -40,6 +40,21 @@ const mockApp = {
storeManager: mockStoreManager,
} as unknown as App;
+const createValidProxySettings = (): NetworkProxySettings => ({
+ enableProxy: true,
+ proxyType: 'http',
+ proxyServer: 'proxy.example.com',
+ proxyPort: '8080',
+ proxyRequireAuth: false,
+ proxyBypass: 'localhost,127.0.0.1,::1',
+});
+
+const createSuccessfulResponse = () => ({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+});
+
describe('NetworkProxyCtr', () => {
let networkProxyCtr: NetworkProxyCtr;
@@ -70,22 +85,11 @@ describe('NetworkProxyCtr', () => {
vi.mocked(mockUndici.setGlobalDispatcher).mockReturnValue(undefined);
// Set default return value for fetch mock
- vi.mocked(mockUndici.fetch).mockResolvedValue({
- ok: true,
- status: 200,
- statusText: 'OK',
- });
+ vi.mocked(mockUndici.fetch).mockResolvedValue(createSuccessfulResponse());
});
describe('ProxyConfigValidator', () => {
- const validConfig: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const validConfig: NetworkProxySettings = createValidProxySettings();
it('should validate enabled proxy config with all required fields', () => {
// Indirectly test validation logic by testing public methods
@@ -142,14 +146,7 @@ describe('NetworkProxyCtr', () => {
describe('getDesktopSettings', () => {
it('should return stored proxy settings', async () => {
- const expectedSettings: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const expectedSettings: NetworkProxySettings = createValidProxySettings();
mockStoreManager.get.mockReturnValue(expectedSettings);
@@ -178,14 +175,7 @@ describe('NetworkProxyCtr', () => {
});
describe('setProxySettings', () => {
- const validConfig: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const validConfig: NetworkProxySettings = createValidProxySettings();
it('should save valid proxy settings', async () => {
mockStoreManager.get.mockReturnValue({
@@ -225,11 +215,7 @@ describe('NetworkProxyCtr', () => {
describe('testProxyConnection', () => {
it('should return success for successful connection', async () => {
- const mockResponse = {
- ok: true,
- status: 200,
- statusText: 'OK',
- };
+ const mockResponse = createSuccessfulResponse();
vi.mocked(mockUndici.fetch).mockResolvedValueOnce(mockResponse);
@@ -259,21 +245,10 @@ describe('NetworkProxyCtr', () => {
});
describe('testProxyConfig', () => {
- const validConfig: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const validConfig: NetworkProxySettings = createValidProxySettings();
it('should return success for valid config and successful connection', async () => {
- const mockResponse = {
- ok: true,
- status: 200,
- statusText: 'OK',
- };
+ const mockResponse = createSuccessfulResponse();
vi.mocked(mockUndici.fetch).mockResolvedValueOnce(mockResponse);
@@ -301,11 +276,7 @@ describe('NetworkProxyCtr', () => {
enableProxy: false,
};
- const mockResponse = {
- ok: true,
- status: 200,
- statusText: 'OK',
- };
+ const mockResponse = createSuccessfulResponse();
vi.mocked(mockUndici.fetch).mockResolvedValueOnce(mockResponse);
@@ -326,14 +297,7 @@ describe('NetworkProxyCtr', () => {
describe('beforeAppReady', () => {
it('should apply stored proxy settings on app ready', async () => {
- const storedConfig: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const storedConfig: NetworkProxySettings = createValidProxySettings();
mockStoreManager.get.mockReturnValue(storedConfig);
@@ -373,14 +337,7 @@ describe('NetworkProxyCtr', () => {
describe('ProxyUrlBuilder', () => {
it('should build URL without authentication', () => {
- const config: NetworkProxySettings = {
- enableProxy: true,
- proxyType: 'http',
- proxyServer: 'proxy.example.com',
- proxyPort: '8080',
- proxyRequireAuth: false,
- proxyBypass: 'localhost,127.0.0.1,::1',
- };
+ const config: NetworkProxySettings = createValidProxySettings();
// Indirectly test URL building by testing proxy settings
expect(() => networkProxyCtr.setProxySettings(config)).not.toThrow();
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index bb24531c82d..0621631a7f9 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -1,4 +1,5 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, writeSync } from 'node:fs';
+import type * as fsPromises from 'node:fs/promises';
import { homedir, tmpdir } from 'node:os';
import { delimiter, dirname, join, relative } from 'node:path';
@@ -10,6 +11,19 @@ import type { App } from '@/core/App';
import CliCtr from '../CliCtr';
import ShellCommandCtr from '../ShellCommandCtr';
+const createAvailableSandboxCapability = () => ({
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+});
+
+const createUnprovisionedSandboxCapability = () => ({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'Sandbox user is not provisioned',
+});
+
const { ipcMainHandleMock } = vi.hoisted(() => ({
ipcMainHandleMock: vi.fn(),
}));
@@ -29,7 +43,7 @@ vi.mock('node:child_process', () => ({
// The shared runner checks cwd exists before spawning; `spawn` is mocked, so
// treat the fixture cwd (`/repo`) as a real directory.
vi.mock('node:fs/promises', async (importOriginal) => ({
- ...(await importOriginal<typeof import('node:fs/promises')>()),
+ ...(await importOriginal<typeof fsPromises>()),
stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),
}));
@@ -306,11 +320,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
// Default to a host with a one-click setup (Windows); the cases that care
// about the other platforms override it.
mockCanInstallSandbox.mockReturnValue(true);
- mockProbeSandboxCapability.mockResolvedValue({
- available: true,
- backend: 'srt',
- networkIsolation: true,
- });
+ mockProbeSandboxCapability.mockResolvedValue(createAvailableSandboxCapability());
mockCreateSandboxLaunchPlan.mockResolvedValue({
args: ['-c', 'echo test'],
capability: { available: true, backend: 'srt', networkIsolation: true },
@@ -497,12 +507,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
// Installing the desktop app is supposed to be enough: the row goes
// from unavailable to usable without the user touching a terminal.
mockCanInstallSandbox.mockReturnValue(true);
- mockProbeSandboxCapability.mockResolvedValue({
- available: false,
- backend: 'none',
- networkIsolation: false,
- reason: 'Sandbox user is not provisioned',
- });
+ mockProbeSandboxCapability.mockResolvedValue(createUnprovisionedSandboxCapability());
expect(await ctr.getSandboxCapability()).toEqual({
available: false,
canInstall: true,
@@ -510,11 +515,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
});
mockInstallDeviceSandbox.mockResolvedValue({ status: 'installed' });
- mockProbeSandboxCapability.mockResolvedValue({
- available: true,
- backend: 'srt',
- networkIsolation: true,
- });
+ mockProbeSandboxCapability.mockResolvedValue(createAvailableSandboxCapability());
const result = await ctr.installSandbox();
@@ -531,11 +532,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
expect((await ctr.getSandboxCapability()).available).toBe(false);
mockInstallDeviceSandbox.mockResolvedValue({ status: 'installed' });
- mockProbeSandboxCapability.mockResolvedValue({
- available: true,
- backend: 'srt',
- networkIsolation: true,
- });
+ mockProbeSandboxCapability.mockResolvedValue(createAvailableSandboxCapability());
expect((await ctr.installSandbox()).capability.available).toBe(true);
});
@@ -543,12 +540,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
it('reports a dismissed elevation prompt as cancelled, not a failure', async () => {
mockCanInstallSandbox.mockReturnValue(true);
mockInstallDeviceSandbox.mockResolvedValue({ status: 'cancelled' });
- mockProbeSandboxCapability.mockResolvedValue({
- available: false,
- backend: 'none',
- networkIsolation: false,
- reason: 'Sandbox user is not provisioned',
- });
+ mockProbeSandboxCapability.mockResolvedValue(createUnprovisionedSandboxCapability());
const result = await ctr.installSandbox();
@@ -560,12 +552,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
it('surfaces an install failure without leaving the capability stale', async () => {
mockCanInstallSandbox.mockReturnValue(true);
mockInstallDeviceSandbox.mockRejectedValue(new Error('WFP filter install failed'));
- mockProbeSandboxCapability.mockResolvedValue({
- available: false,
- backend: 'none',
- networkIsolation: false,
- reason: 'Sandbox user is not provisioned',
- });
+ mockProbeSandboxCapability.mockResolvedValue(createUnprovisionedSandboxCapability());
const result = await ctr.installSandbox();
@@ -596,11 +583,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
it('does not offer setup on a host that already has a sandbox', async () => {
mockCanInstallSandbox.mockReturnValue(true);
- mockProbeSandboxCapability.mockResolvedValue({
- available: true,
- backend: 'srt',
- networkIsolation: true,
- });
+ mockProbeSandboxCapability.mockResolvedValue(createAvailableSandboxCapability());
expect((await ctr.getSandboxCapability()).canInstall).toBe(false);
});
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
index d8fd7b5c5ae..1f8bc51ca01 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
@@ -285,12 +285,6 @@ describe('ProtocolManager', () => {
});
});
- describe('getScheme', () => {
- it('should return the protocol scheme', () => {
- expect(manager.getScheme()).toBe('lobehub');
- });
- });
-
describe('isRegistered', () => {
it('should return true when registered', () => {
mockApp.isDefaultProtocolClient.mockReturnValue(true);
diff --git a/apps/desktop/src/main/utils/__tests__/logger.test.ts b/apps/desktop/src/main/utils/__tests__/logger.test.ts
index 83f9ccde4d0..2cb2f55c066 100644
--- a/apps/desktop/src/main/utils/__tests__/logger.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/logger.test.ts
@@ -6,6 +6,15 @@ import { getDesktopEnv } from '@/env';
import { createLogger } from '../logger';
+const createLoggerEnv = (nodeEnv: 'development' | 'production' | undefined) => ({
+ NODE_ENV: nodeEnv,
+ DEBUG_VERBOSE: false,
+ DESKTOP_RENDERER_STATIC: false,
+ UPDATE_CHANNEL: undefined,
+ MCP_TOOL_TIMEOUT: 60000,
+ OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
+});
+
// This suite exercises the real logger, so opt out of the global stub in
// `__mocks__/setup.ts`.
vi.unmock('@/utils/logger');
@@ -46,27 +55,13 @@ describe('logger', () => {
beforeEach(() => {
vi.mocked(debug).mockReturnValue(mockDebugLogger as any);
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: undefined,
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv(undefined));
vi.clearAllMocks();
});
afterEach(() => {
// Reset to default state
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: undefined,
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv(undefined));
});
describe('createLogger', () => {
@@ -111,14 +106,7 @@ describe('logger', () => {
describe('logger.error', () => {
it('should use electronLog.error in production', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'production',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('production'));
const logger = createLogger('test:error');
logger.error('error message', { error: 'details' });
@@ -129,14 +117,7 @@ describe('logger', () => {
});
it('should use console.error in development', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'development',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('development'));
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const logger = createLogger('test:error');
logger.error('error message', { error: 'details' });
@@ -153,14 +134,7 @@ describe('logger', () => {
// the production log file. `app.isPackaged` is what must gate persistence.
it('should persist error/info/warn in a packaged build with no NODE_ENV', () => {
mockApp.isPackaged = true;
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: undefined,
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv(undefined));
const logger = createLogger('test:packaged');
logger.error('error message');
@@ -190,14 +164,7 @@ describe('logger', () => {
describe('logger.info', () => {
it('should use electronLog.info with namespace in production', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'production',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('production'));
const logger = createLogger('test:info');
logger.info('info message', { data: 'value' });
@@ -208,14 +175,7 @@ describe('logger', () => {
});
it('should use debug logger in development', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'development',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('development'));
const logger = createLogger('test:info');
logger.info('info message', { data: 'value' });
@@ -266,14 +226,7 @@ describe('logger', () => {
describe('logger.warn', () => {
it('should use electronLog.warn in production', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'production',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('production'));
const logger = createLogger('test:warn');
logger.warn('warn message', { warning: 'details' });
@@ -284,14 +237,7 @@ describe('logger', () => {
});
it('should not use electronLog.warn in development', () => {
- mockGetDesktopEnv.mockReturnValue({
- NODE_ENV: 'development',
- DEBUG_VERBOSE: false,
- DESKTOP_RENDERER_STATIC: false,
- UPDATE_CHANNEL: undefined,
- MCP_TOOL_TIMEOUT: 60000,
- OFFICIAL_CLOUD_SERVER: 'https://lobechat.com',
- });
+ mockGetDesktopEnv.mockReturnValue(createLoggerEnv('development'));
const logger = createLogger('test:warn');
logger.warn('warn message');
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.feature b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.feature
deleted file mode 100644
index d5c52082577..00000000000
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.feature
+++ /dev/null
@@ -1,94 +0,0 @@
-Feature: Agent 运行时协调器
- 作为一个使用 Agent 运行时系统的开发者
- 我想要协调智能体状态管理和事件流
- 以便我能够正确跟踪智能体生命周期并处理事件
-
- Background:
- Given 智能体运行时系统已经启动
- And 协调器已经初始化完成
-
- Scenario: 创建新的智能体会话
- When 我创建一个新的智能体会话 "chat-session-001"
- And 会话配置为:
- | 字段 | 值 |
- | 用户ID | user-12345 |
- | 模型配置 | GPT-4 温度0.7 |
- | 智能体类型 | 对话助理 |
- Then 会话应该成功创建
- And 系统应该发布会话初始化事件
- And 事件应该包含会话的基本信息
-
- Scenario: 智能体执行任务并完成
- Given 智能体会话 "chat-session-001" 已经创建
- And 智能体当前状态为 "运行中"
- When 智能体完成所有任务
- And 会话状态更新为 "已完成"
- Then 系统应该保存最终状态
- And 应该发布会话结束事件
- And 事件应该包含执行结果和统计信息
-
- Scenario: 智能体正在执行任务
- Given 智能体会话 "chat-session-001" 已经创建
- And 智能体当前状态为 "空闲"
- When 智能体开始执行任务
- And 会话状态更新为 "运行中"
- Then 系统应该保存当前状态
- But 不应该发布会话结束事件
-
- Scenario: 完成单个执行步骤
- Given 智能体会话 "chat-session-001" 正在运行
- When 智能体完成第5个执行步骤
- And 该步骤标记为最终步骤
- Then 系统应该保存步骤结果
- And 应该发布会话结束事件
- And 事件应该包含完整的执行历史
-
- Scenario: 完成中间执行步骤
- Given 智能体会话 "chat-session-001" 正在运行
- When 智能体完成第3个执行步骤
- And 该步骤不是最终步骤
- Then 系统应该保存步骤结果
- But 不应该发布会话结束事件
-
- Scenario: 查询智能体执行状态
- Given 智能体会话 "chat-session-001" 存在
- When 我查询会话的当前状态
- Then 应该返回最新的状态信息
- And 信息应该包含当前步骤数和执行状态
-
- Scenario: 查询会话元数据
- Given 智能体会话 "chat-session-001" 存在
- When 我查询会话的元数据
- Then 应该返回会话的配置信息
- And 信息应该包含用户ID、模型配置和创建时间
-
- Scenario: 查询执行历史
- Given 智能体会话 "chat-session-001" 已经执行了多个步骤
- When 我查询最近10步的执行历史
- Then 应该返回包含10个步骤的历史记录
- And 每个记录应该包含步骤索引、执行时间和状态
-
- Scenario: 清理会话资源
- Given 智能体会话 "chat-session-001" 已经完成
- When 我删除该会话
- Then 会话的所有数据应该被清理
- And 相关的事件流数据也应该被清理
-
- Scenario: 断开系统连接
- Given 协调器正在运行中
- When 我关闭协调器
- Then 所有的数据库连接应该被正确关闭
- And 所有的资源应该被释放
-
- Scenario: 获取系统统计信息
- Given 系统中存在多个智能体会话
- When 我查询系统统计信息
- Then 应该返回活跃会话数量
- And 应该返回已完成会话数量
- And 应该返回出错会话数量
-
- Scenario: 清理过期会话
- Given 系统中存在一些长时间未活跃的会话
- When 我执行过期会话清理
- Then 超过保留期限的会话应该被删除
- And 应该返回清理的会话数量
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 89959d10692..8b14d52b575 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2,6 +2,7 @@ import { type AgentState } from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { type AgentGroupConfig, ToolNameResolver } from '@lobechat/context-engine';
import { consumeStreamUntilDone, ModelEmptyError } from '@lobechat/model-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
import type * as ModelBank from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -337,6 +338,36 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
type: 'compress_context' as const,
});
+ const createSearchToolCall = () => ({
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'web-search',
+ type: 'default' as const,
+ });
+
+ const createCrawlToolCall = () => ({
+ apiName: 'crawl',
+ arguments: '{}',
+ id: 'tool-call-2',
+ identifier: 'web-browsing',
+ type: 'default' as const,
+ });
+
+ const createCallLlmInstruction = () => ({
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ type: 'call_llm' as const,
+ });
+
+ const createBatchToolInstruction = (toolsCalling: ChatToolPayload[]) => ({
+ payload: { parentMessageId: 'assistant-msg-123', toolsCalling },
+ type: 'call_tools_batch' as const,
+ });
+
describe('call_llm executor', () => {
const createMockState = (overrides?: Partial<AgentState>): AgentState => ({
cost: createMockCost(),
@@ -605,17 +636,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- await executors.call_llm!(
- {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- },
- state,
- );
+ await executors.call_llm!(createCallLlmInstruction(), state);
expect(
mockChat.mock.calls[0][0].tools.map((tool: { function: { name: string } }) => {
@@ -938,14 +959,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
const result = await executors.call_llm!(instruction, state);
const assistant = result.newState.messages.at(-1) as any;
@@ -1177,14 +1191,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
const result = await executors.call_llm!(instruction, state);
const assistant = result.newState.messages.at(-1) as any;
@@ -2114,14 +2121,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
];
const state = createMockState({ tools: tools as any });
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2141,14 +2141,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
];
const state = createMockState({ tools: stateTools as any });
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2170,14 +2163,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
] as any,
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2508,14 +2494,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2591,14 +2570,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2915,14 +2887,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
forceFinish: true,
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -2950,14 +2915,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
world: { agent: { plugins: [], systemRole: 'test' }, eval: evalContext as any },
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -3020,14 +2978,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -3041,14 +2992,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({ world: { agent: { plugins: [], systemRole: 'test' } } });
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -3101,14 +3045,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- provider: 'openai',
- },
- type: 'call_llm' as const,
- };
+ const instruction = createCallLlmInstruction();
await executors.call_llm!(instruction, state);
@@ -3383,13 +3320,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolCalling: {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
+ toolCalling: createSearchToolCall(),
},
type: 'call_tool' as const,
};
@@ -3561,13 +3492,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolCalling: {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
+ toolCalling: createSearchToolCall(),
},
type: 'call_tool' as const,
};
@@ -3592,13 +3517,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'deleted-parent',
- toolCalling: {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
+ toolCalling: createSearchToolCall(),
},
type: 'call_tool' as const,
};
@@ -3809,13 +3728,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
payload: {
parentMessageId: 'pending-tool-msg-1',
skipCreateToolMessage: true,
- toolCalling: {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
+ toolCalling: createSearchToolCall(),
},
type: 'call_tool' as const,
};
@@ -4130,28 +4043,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{"query": "test1"}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{"url": "https://example.com"}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'search',
+ arguments: '{"query": "test1"}',
+ id: 'tool-call-1',
+ identifier: 'web-search',
+ type: 'default' as const,
},
- type: 'call_tools_batch' as const,
- };
+ {
+ apiName: 'crawl',
+ arguments: '{"url": "https://example.com"}',
+ id: 'tool-call-2',
+ identifier: 'web-browsing',
+ type: 'default' as const,
+ },
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -4213,28 +4120,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'createTask',
- arguments: '{"name":"A"}',
- id: 'tool-call-1',
- identifier: 'lobe-task',
- type: 'default' as const,
- },
- {
- apiName: 'updateTask',
- arguments: '{"name":"B"}',
- id: 'tool-call-2',
- identifier: 'lobe-task',
- type: 'default' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'createTask',
+ arguments: '{"name":"A"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-task',
+ type: 'default' as const,
},
- type: 'call_tools_batch' as const,
- };
+ {
+ apiName: 'updateTask',
+ arguments: '{"name":"B"}',
+ id: 'tool-call-2',
+ identifier: 'lobe-task',
+ type: 'default' as const,
+ },
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -4301,28 +4202,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-retry-batch',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-stop-batch',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-retry-batch',
+ identifier: 'web-search',
+ type: 'default' as const,
},
- type: 'call_tools_batch' as const,
- };
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-stop-batch',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ ]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4339,21 +4234,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState({ messages: [{ content: 'old', role: 'user' }] });
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([createSearchToolCall()]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4375,21 +4256,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([createSearchToolCall()]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4414,28 +4281,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([
+ createSearchToolCall(),
+ createCrawlToolCall(),
+ ]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4461,15 +4310,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'original-parent-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'call_tools_batch' as const,
};
@@ -4495,15 +4336,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'deleted-parent',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'call_tools_batch' as const,
};
@@ -4529,28 +4362,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([
+ createSearchToolCall(),
+ createCrawlToolCall(),
+ ]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4576,28 +4391,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([
+ createSearchToolCall(),
+ createCrawlToolCall(),
+ ]);
await expect(executors.call_tools_batch!(instruction, state)).rejects.toThrow(
'Database error',
@@ -4608,28 +4405,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([
+ createSearchToolCall(),
+ createCrawlToolCall(),
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -4653,28 +4432,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([
+ createSearchToolCall(),
+ createCrawlToolCall(),
+ ]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4703,21 +4464,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([createSearchToolCall()]);
await executors.call_tools_batch!(instruction, state);
@@ -4771,15 +4518,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'msg-2',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'call_tools_batch' as const,
};
@@ -4846,21 +4585,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([createSearchToolCall()]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4899,28 +4624,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{"query": "test"}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{"url": "https://example.com"}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'search',
+ arguments: '{"query": "test"}',
+ id: 'tool-call-1',
+ identifier: 'web-search',
+ type: 'default' as const,
},
- type: 'call_tools_batch' as const,
- };
+ {
+ apiName: 'crawl',
+ arguments: '{"url": "https://example.com"}',
+ id: 'tool-call-2',
+ identifier: 'web-browsing',
+ type: 'default' as const,
+ },
+ ]);
const result = await executors.call_tools_batch!(instruction, state);
@@ -4965,28 +4684,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState();
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{"query": "test"}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{"url": "https://example.com"}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'search',
+ arguments: '{"query": "test"}',
+ id: 'tool-call-1',
+ identifier: 'web-search',
+ type: 'default' as const,
},
- type: 'call_tools_batch' as const,
- };
+ {
+ apiName: 'crawl',
+ arguments: '{"url": "https://example.com"}',
+ id: 'tool-call-2',
+ identifier: 'web-browsing',
+ type: 'default' as const,
+ },
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -5021,21 +4734,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
- },
- type: 'call_tools_batch' as const,
- };
+ const instruction = createBatchToolInstruction([createSearchToolCall()]);
await executors.call_tools_batch!(instruction, state);
@@ -5058,21 +4757,15 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'createDocument',
- arguments: '{"title":"Test","content":"Hello"}',
- id: 'tool-call-1',
- identifier: 'lobe-agent-documents',
- type: 'builtin' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'createDocument',
+ arguments: '{"title":"Test","content":"Hello"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-agent-documents',
+ type: 'builtin' as const,
},
- type: 'call_tools_batch' as const,
- };
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -5099,21 +4792,15 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'generateImage',
- arguments: '{"prompt":"A lighthouse"}',
- id: 'tool-call-1',
- identifier: 'lobe-image-generation',
- type: 'builtin' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'generateImage',
+ arguments: '{"prompt":"A lighthouse"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-image-generation',
+ type: 'builtin' as const,
},
- type: 'call_tools_batch' as const,
- };
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -5136,21 +4823,15 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
});
- const instruction = {
- payload: {
- parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'createDocument',
- arguments: '{"title":"Test","content":"Hello"}',
- id: 'tool-call-1',
- identifier: 'lobe-agent-documents',
- type: 'builtin' as const,
- },
- ],
+ const instruction = createBatchToolInstruction([
+ {
+ apiName: 'createDocument',
+ arguments: '{"title":"Test","content":"Hello"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-agent-documents',
+ type: 'builtin' as const,
},
- type: 'call_tools_batch' as const,
- };
+ ]);
await executors.call_tools_batch!(instruction, state);
@@ -5321,15 +5002,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'resolve_aborted_tools' as const,
};
@@ -5346,15 +5019,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'resolve_aborted_tools' as const,
};
@@ -5377,15 +5042,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall()],
},
type: 'resolve_aborted_tools' as const,
};
@@ -5423,22 +5080,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall(), createCrawlToolCall()],
},
type: 'resolve_aborted_tools' as const,
};
@@ -5474,22 +5116,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const instruction = {
payload: {
parentMessageId: 'assistant-msg-123',
- toolsCalling: [
- {
- apiName: 'search',
- arguments: '{}',
- id: 'tool-call-1',
- identifier: 'web-search',
- type: 'default' as const,
- },
- {
- apiName: 'crawl',
- arguments: '{}',
- id: 'tool-call-2',
- identifier: 'web-browsing',
- type: 'default' as const,
- },
- ],
+ toolsCalling: [createSearchToolCall(), createCrawlToolCall()],
},
type: 'resolve_aborted_tools' as const,
};
@@ -6094,6 +5721,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
describe('hooks integration', () => {
+ const createMockDispatcher = () => ({
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),
+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
+ evaluateToolCall: vi.fn().mockResolvedValue({
+ status: 'allow',
+ }),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ });
+
const createToolState = (overrides?: Partial<AgentState>): AgentState => ({
cost: createMockCost(),
createdAt: new Date().toISOString(),
@@ -6197,15 +5834,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it.each([false, true])(
'keeps runtime owner identity in shared-session tool hooks (throws: %s)',
async (throws) => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
if (throws)
mockToolExecutionService.executeTool.mockRejectedValue(new Error('Tool failed'));
const state = createToolState({
@@ -6250,15 +5879,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
it('should preserve native identity and structured results across tool notifications', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const toolResult = {
content: 'device output',
deviceExecutionTime: 17,
@@ -6338,15 +5959,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should report structured blocked results as unsuccessful notifications, not exceptions', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const toolResult = {
content: 'Tool unavailable in this scope',
executionTime: 0,
@@ -6379,15 +5992,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should correlate repeated tool names in a batch by native call ids', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const tool = createToolInstruction().payload.toolCalling;
await createRuntimeExecutors({ ...ctx, hookDispatcher: mockDispatcher as any })
.call_tools_batch!(
@@ -6422,15 +6027,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should retain client routing and structured client results in notifications', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const result = {
content: 'client result',
executionTime: 11,
@@ -6469,15 +6066,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should dispatch beforeToolCall and afterToolCall hooks', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const ctxWithHooks = { ...ctx, hookDispatcher: mockDispatcher as any };
const executors = createRuntimeExecutors(ctxWithHooks);
@@ -6548,15 +6137,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
// time it lands, `executeStep` has emitted the terminal hooks and the
// operation is unregistered, so a local consumer drops it silently and a
// webhook consumer would see `afterToolCall` after `onComplete`.
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const controller = new AbortController();
mockToolExecutionService.executeTool.mockImplementationOnce(async () => {
@@ -6668,15 +6249,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should dispatch onToolCallError when tool throws', async () => {
mockToolExecutionService.executeTool.mockRejectedValue(new Error('Connection refused'));
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const ctxWithHooks = { ...ctx, hookDispatcher: mockDispatcher as any };
const executors = createRuntimeExecutors(ctxWithHooks);
@@ -6699,15 +6272,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should derive callIndex from state.usage.tools.byTool', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const ctxWithHooks = { ...ctx, hookDispatcher: mockDispatcher as any };
const executors = createRuntimeExecutors(ctxWithHooks);
@@ -6753,15 +6318,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
describe('compress_context hooks', () => {
it('should dispatch beforeCompact and afterCompact hooks', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const ctxWithHooks = {
...ctx,
@@ -6836,15 +6393,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
it('should dispatch beforeHumanIntervention hook', async () => {
- const mockDispatcher = {
- dispatch: vi.fn().mockResolvedValue(undefined),
- hasAfterToolCallControl: vi.fn().mockReturnValue(false),
- evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),
- evaluateToolCall: vi.fn().mockResolvedValue({
- status: 'allow',
- }),
- dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
- };
+ const mockDispatcher = createMockDispatcher();
const ctxWithHooks = { ...ctx, hookDispatcher: mockDispatcher as any };
const executors = createRuntimeExecutors(ctxWithHooks);
diff --git a/apps/server/src/modules/ModelRuntime/index.test.ts b/apps/server/src/modules/ModelRuntime/index.test.ts
index f63f2ba60da..cbe64f4f70f 100644
--- a/apps/server/src/modules/ModelRuntime/index.test.ts
+++ b/apps/server/src/modules/ModelRuntime/index.test.ts
@@ -747,11 +747,12 @@ describe('initModelRuntimeWithUserPayload method', () => {
expect(runtime['_runtime']).toBeInstanceOf(LobeMoonshotAI);
});
- it('Qwen AI provider: with apikey', async () => {
+ it('Qwen AI provider: with apikey and default endpoint', async () => {
const jwtPayload: ClientSecretPayload = { apiKey: 'user-qwen-key' };
const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Qwen, jwtPayload);
expect(runtime).toBeInstanceOf(ModelRuntime);
expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
+ expect(runtime['_runtime'].baseURL).toBe('https://dashscope.aliyuncs.com/compatible-mode/v1');
});
it('Vertex AI provider: with service account json', async () => {
@@ -1025,16 +1026,6 @@ describe('initModelRuntimeWithUserPayload method', () => {
expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
});
- it('Qwen AI provider: without endpoint', async () => {
- const jwtPayload: ClientSecretPayload = { apiKey: 'user-qwen-key' };
- const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Qwen, jwtPayload);
-
- // 假设 LobeQwenAI 是 Qwen 提供者的实现类
- expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
- // endpoint 不存在,应返回 DEFAULT_BASE_URL
- expect(runtime['_runtime'].baseURL).toBe('https://dashscope.aliyuncs.com/compatible-mode/v1');
- });
-
it('Bedrock AI provider: without apikey', async () => {
const jwtPayload = {};
const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
diff --git a/apps/server/src/router-hono/acceptance-review/__tests__/extension.test.ts b/apps/server/src/router-hono/acceptance-review/__tests__/extension.test.ts
index 8ae88c57f97..31c15a7931e 100644
--- a/apps/server/src/router-hono/acceptance-review/__tests__/extension.test.ts
+++ b/apps/server/src/router-hono/acceptance-review/__tests__/extension.test.ts
@@ -156,7 +156,6 @@ describe('extension endpoints', () => {
title: 'Pricing page',
workspaceId,
});
- expect(body.acceptances.map((a: { id: string }) => a.id)).not.toContain(site.acceptanceId);
});
it('falls back to the most recent round that has a preview', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index e49cbfe5ae0..bbbe66d1ad0 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -761,7 +761,7 @@ describe('agentRouter', () => {
expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
});
- it('rejects promotion of another member agent even for a workspace owner', async () => {
+ it('rejects promotion when resource permission denies access to another member agent', async () => {
agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
slug: null,
userId: 'other-member',
@@ -778,24 +778,6 @@ describe('agentRouter', () => {
expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
});
- it('rejects promotion of another member agent for a plain member', async () => {
- agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
- slug: null,
- userId: 'other-member',
- visibility: 'private',
- });
- vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
- new TRPCError({ code: 'FORBIDDEN' }),
- );
-
- const caller = agentRouter.createCaller(wsCtx());
-
- await expect(
- caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' }),
- ).rejects.toMatchObject({ code: 'FORBIDDEN' });
- expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
- });
-
it('does not run the public-task guard on promotion', async () => {
agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
slug: null,
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index 4f51158450a..3227aa7f1bc 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -9,6 +9,33 @@ import { AsyncTaskStatus } from '@/types/asyncTask';
import { FileSource } from '@/types/files';
import { TransferErrorCode } from '@/types/transferError';
+const uploadInput = () => ({
+ hash: 'test-hash',
+ fileType: 'text',
+ name: 'test.txt',
+ size: 100,
+ url: 'files/test.txt',
+ metadata: {},
+});
+
+const plainTextUploadInput = () => ({
+ fileType: 'text/plain',
+ hash: 'test-hash',
+ metadata: {},
+ name: 'test.txt',
+ size: 100,
+ url: 'files/test.txt',
+});
+
+const movedFileInput = () => ({
+ hash: 'test-hash',
+ fileType: 'text',
+ metadata: { path: 'new/path.txt' },
+ name: 'test.txt',
+ size: 100,
+ url: 'new/path.txt',
+});
+
const buildMockFileAccessUrl = ({ id }: { id: string }) => `https://lobehub.com/f/${id}`;
const routerMocks = vi.hoisted(() => {
@@ -504,14 +531,7 @@ describe('fileRouter', () => {
mockFileModelCheckHash.mockResolvedValue({ isExist: false });
mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
- const result = await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- metadata: {},
- });
+ const result = await caller.createFile(uploadInput());
expect(result).toEqual({
id: 'new-file-id',
@@ -633,14 +653,7 @@ describe('fileRouter', () => {
.mockRejectedValueOnce(new Error('NoSuchKey'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(function () {});
- await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- metadata: { path: 'new/path.txt' },
- name: 'test.txt',
- size: 100,
- url: 'new/path.txt',
- });
+ await caller.createFile(movedFileInput());
expect(mockFileModelUpdateGlobalFile).toHaveBeenCalledWith(
'test-hash',
@@ -670,14 +683,7 @@ describe('fileRouter', () => {
contentType: 'text/plain',
});
- await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- metadata: { path: 'new/path.txt' },
- name: 'test.txt',
- size: 100,
- url: 'new/path.txt',
- });
+ await caller.createFile(movedFileInput());
expect(mockFileModelUpdateGlobalFile).not.toHaveBeenCalled();
expect(mockFileModelCreate).toHaveBeenCalledWith(
@@ -691,14 +697,7 @@ describe('fileRouter', () => {
mockFileModelCheckHash.mockResolvedValue({ isExist: false });
mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
- await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- metadata: {},
- });
+ await caller.createFile(uploadInput());
expect(routerMocks.serverDB.transaction).toHaveBeenCalledTimes(1);
expect(routerMocks.businessFileUploadCheck).toHaveBeenCalledWith(
@@ -732,14 +731,7 @@ describe('fileRouter', () => {
status: 'settled',
});
- await caller.createFile({
- fileType: 'text/plain',
- hash: 'test-hash',
- metadata: {},
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- });
+ await caller.createFile(plainTextUploadInput());
expect(routerMocks.businessFileUploadCheck).not.toHaveBeenCalled();
expect(mockFileUploadFindLatestForUpdate).toHaveBeenCalledWith(
@@ -765,16 +757,10 @@ describe('fileRouter', () => {
mockFileUploadTouchActive.mockResolvedValue(upload);
mockFileServiceGetFileMetadata.mockResolvedValue({ contentLength: 101 });
- await expect(
- caller.createFile({
- fileType: 'text/plain',
- hash: 'test-hash',
- metadata: {},
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- }),
- ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'Uploaded file size mismatch' });
+ await expect(caller.createFile(plainTextUploadInput())).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Uploaded file size mismatch',
+ });
expect(mockFileUploadReleaseBestEffort).toHaveBeenCalledWith('files/test.txt');
expect(mockFileModelCreate).not.toHaveBeenCalled();
@@ -821,16 +807,7 @@ describe('fileRouter', () => {
url: 'files/test.txt',
});
- await expect(
- caller.createFile({
- fileType: 'text/plain',
- hash: 'test-hash',
- metadata: {},
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- }),
- ).resolves.toEqual({
+ await expect(caller.createFile(plainTextUploadInput())).resolves.toEqual({
id: 'settled-file-id',
url: 'https://lobehub.com/f/settled-file-id',
});
@@ -844,14 +821,7 @@ describe('fileRouter', () => {
mockFileModelCheckHash.mockResolvedValue({ isExist: false });
mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
- await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- metadata: {},
- });
+ await caller.createFile(uploadInput());
expect(routerMocks.businessFileUploadCheck).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1017,14 +987,7 @@ describe('fileRouter', () => {
contentType: 'text/plain',
});
- await caller.createFile({
- hash: 'test-hash',
- fileType: 'text',
- name: 'test.txt',
- size: 100,
- url: 'files/test.txt',
- metadata: {},
- });
+ await caller.createFile(uploadInput());
// Verify create was called with input size since contentLength < 1
expect(mockFileModelCreate).toHaveBeenCalledWith(
diff --git a/apps/server/src/routers/lambda/__tests__/generationBatch.test.ts b/apps/server/src/routers/lambda/__tests__/generationBatch.test.ts
index 2e8665d6f54..deb134a1a27 100644
--- a/apps/server/src/routers/lambda/__tests__/generationBatch.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/generationBatch.test.ts
@@ -15,6 +15,25 @@ vi.mock('@/server/services/generation/latency', () => ({
`${provider}\0${model}`,
}));
+const createDeletedBatch = (id: string, prompt = 'Test prompt'): GenerationBatchItem => ({
+ id,
+ userId: 'test-user',
+ workspaceId: null,
+ generationTopicId: 'topic-1',
+ provider: 'test-provider',
+ model: 'test-model',
+ prompt,
+ width: 1024,
+ height: 1024,
+ ratio: null,
+ config: null,
+ accessedAt: new Date(),
+ deletedAt: null,
+ isDeleted: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+});
+
describe('generationBatchRouter', () => {
const mockCtx = {
userId: 'test-user',
@@ -61,24 +80,7 @@ describe('generationBatchRouter', () => {
it('should delete generation batch without thumbnails', async () => {
const mockBatchId = 'batch-123';
- const mockDeletedBatch: GenerationBatchItem = {
- id: mockBatchId,
- userId: 'test-user',
- workspaceId: null,
- generationTopicId: 'topic-1',
- provider: 'test-provider',
- model: 'test-model',
- prompt: 'Test prompt',
- width: 1024,
- height: 1024,
- ratio: null,
- config: null,
- accessedAt: new Date(),
- deletedAt: null,
- isDeleted: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
+ const mockDeletedBatch: GenerationBatchItem = createDeletedBatch(mockBatchId);
const mockDelete = vi.fn().mockResolvedValue({
deletedBatch: mockDeletedBatch,
@@ -110,24 +112,7 @@ describe('generationBatchRouter', () => {
it('should delete generation batch with thumbnails', async () => {
const mockBatchId = 'batch-123';
const mockThumbnailUrls = ['thumb1.jpg', 'thumb2.jpg', 'thumb3.jpg'];
- const mockDeletedBatch: GenerationBatchItem = {
- id: mockBatchId,
- userId: 'test-user',
- workspaceId: null,
- generationTopicId: 'topic-1',
- provider: 'test-provider',
- model: 'test-model',
- prompt: 'Test prompt',
- width: 1024,
- height: 1024,
- ratio: null,
- config: null,
- accessedAt: new Date(),
- deletedAt: null,
- isDeleted: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
+ const mockDeletedBatch: GenerationBatchItem = createDeletedBatch(mockBatchId);
const mockDelete = vi.fn().mockResolvedValue({
deletedBatch: mockDeletedBatch,
@@ -159,24 +144,7 @@ describe('generationBatchRouter', () => {
it('should still return deleted batch when thumbnail deletion fails', async () => {
const mockBatchId = 'batch-123';
const mockThumbnailUrls = ['thumb1.jpg', 'thumb2.jpg'];
- const mockDeletedBatch: GenerationBatchItem = {
- id: mockBatchId,
- userId: 'test-user',
- workspaceId: null,
- generationTopicId: 'topic-1',
- provider: 'test-provider',
- model: 'test-model',
- prompt: 'Test prompt',
- width: 1024,
- height: 1024,
- ratio: null,
- config: null,
- accessedAt: new Date(),
- deletedAt: null,
- isDeleted: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
+ const mockDeletedBatch: GenerationBatchItem = createDeletedBatch(mockBatchId);
const mockDelete = vi.fn().mockResolvedValue({
deletedBatch: mockDeletedBatch,
@@ -243,24 +211,10 @@ describe('generationBatchRouter', () => {
const mockBatchId = 'batch-with-many-thumbnails';
// Simulate a batch with many thumbnails
const mockThumbnailUrls = Array.from({ length: 50 }, (_, i) => `thumb${i + 1}.jpg`);
- const mockDeletedBatch: GenerationBatchItem = {
- id: mockBatchId,
- userId: 'test-user',
- workspaceId: null,
- generationTopicId: 'topic-1',
- provider: 'test-provider',
- model: 'test-model',
- prompt: 'Batch with many generations',
- width: 1024,
- height: 1024,
- ratio: null,
- config: null,
- accessedAt: new Date(),
- deletedAt: null,
- isDeleted: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
+ const mockDeletedBatch: GenerationBatchItem = createDeletedBatch(
+ mockBatchId,
+ 'Batch with many generations',
+ );
const mockDelete = vi.fn().mockResolvedValue({
deletedBatch: mockDeletedBatch,
@@ -325,24 +279,7 @@ describe('generationBatchRouter', () => {
it('should handle partial thumbnail deletion failure gracefully', async () => {
const mockBatchId = 'batch-123';
const mockThumbnailUrls = ['thumb1.jpg', 'thumb2.jpg', 'thumb3.jpg'];
- const mockDeletedBatch: GenerationBatchItem = {
- id: mockBatchId,
- userId: 'test-user',
- workspaceId: null,
- generationTopicId: 'topic-1',
- provider: 'test-provider',
- model: 'test-model',
- prompt: 'Test prompt',
- width: 1024,
- height: 1024,
- ratio: null,
- config: null,
- accessedAt: new Date(),
- deletedAt: null,
- isDeleted: null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
+ const mockDeletedBatch: GenerationBatchItem = createDeletedBatch(mockBatchId);
const mockDelete = vi.fn().mockResolvedValue({
deletedBatch: mockDeletedBatch,
diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
index 8395ef81d50..e4f48c105fb 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
@@ -755,14 +755,11 @@ describe('Agent Eval Router Integration Tests', () => {
expect(deleted).toBeUndefined();
});
- it('should return error when test case not found', async () => {
+ it('does not reject when a test case is missing', async () => {
const caller = agentEvalRouter.createCaller(createTestContext(userId));
+ // PGlite may omit rowCount, so only non-rejection is verified here.
await caller.deleteTestCase({ id: 'non-existent' });
-
- // In PGlite, rowCount may be undefined, so we can't reliably detect non-existent deletes
- // This test just verifies no error is thrown
- expect(true).toBe(true);
});
});
});
@@ -1110,14 +1107,11 @@ describe('Agent Eval Router Integration Tests', () => {
await cleanupTestUser(serverDB, user2Id);
});
- it('should return error when run not found', async () => {
+ it('does not reject when a run is missing', async () => {
const caller = agentEvalRouter.createCaller(createTestContext(userId));
+ // PGlite may omit rowCount, so only non-rejection is verified here.
await caller.deleteRun({ id: 'non-existent' });
-
- // In PGlite, rowCount may be undefined, so we can't reliably detect non-existent deletes
- // This test just verifies no error is thrown
- expect(true).toBe(true);
});
});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
index 4712ea44fe2..b83bfbfea6b 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
@@ -18,6 +18,32 @@ import {
createTestUser,
} from './setup';
+const taskInput = (
+ agentId: string,
+): Parameters<ReturnType<typeof taskRouter.createCaller>['create']>[0] => ({
+ assigneeAgentId: agentId,
+ instruction: 'Test',
+});
+
+const chapterInput = (
+ agentId: string,
+ instruction: string,
+ parentTaskId: string,
+): Parameters<ReturnType<typeof taskRouter.createCaller>['create']>[0] => ({
+ assigneeAgentId: agentId,
+ instruction,
+ parentTaskId,
+});
+
+const workspaceRoster = (
+ userId: string,
+ workspaceId: string,
+ memberId: string,
+): Array<{ role: 'owner' | 'member'; userId: string; workspaceId: string }> => [
+ { role: 'owner', userId, workspaceId },
+ { role: 'member', userId: memberId, workspaceId },
+];
+
// Mock getServerDB
let testDB: LobeChatDatabase;
vi.mock('@/database/core/db-adaptor', () => ({
@@ -302,10 +328,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const wsAgentId = 'agt_assignee_coexist_ws';
await serverDB
.insert(agents)
@@ -789,10 +814,7 @@ describe('Task Router Integration', () => {
describe('run idempotency', () => {
it('resolves a task identifier to its row when starting a run', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await caller.run({ id: task.data.identifier });
@@ -801,10 +823,7 @@ describe('Task Router Integration', () => {
});
it('should reject run when a topic is already running', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
// First run succeeds
await caller.run({ id: task.data.id });
@@ -814,10 +833,7 @@ describe('Task Router Integration', () => {
});
it('should reject continue on already running topic', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await caller.run({ id: task.data.id });
@@ -864,10 +880,7 @@ describe('Task Router Integration', () => {
it('should rollback task status to paused on run failure', async () => {
mockExecAgent.mockRejectedValueOnce(new Error('LLM failed'));
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await expect(caller.run({ id: task.data.id })).rejects.toThrow();
@@ -892,10 +905,7 @@ describe('Task Router Integration', () => {
topicId: testTopicId,
});
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await expect(caller.run({ id: task.data.id })).rejects.toThrow();
@@ -930,10 +940,7 @@ describe('Task Router Integration', () => {
describe('cancelTopic', () => {
it('should cancel a running topic and pause task', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await caller.run({ id: task.data.id });
@@ -946,10 +953,7 @@ describe('Task Router Integration', () => {
});
it('should reject cancel on non-running topic', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
await caller.run({ id: task.data.id });
await caller.cancelTopic({ topicId: 'tpc_test' });
@@ -1223,10 +1227,7 @@ describe('Task Router Integration', () => {
describe('heartbeat timeout detection', () => {
it('should auto-detect timeout on detail and pause task', async () => {
- const task = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Test',
- });
+ const task = await caller.create(taskInput(testAgentId));
// Start running with very short timeout
await caller.update({
@@ -1251,21 +1252,9 @@ describe('Task Router Integration', () => {
describe('subtask layers + batch run', () => {
it('previewSubtaskLayers groups subtasks by dependency level', async () => {
const parent = await caller.create({ instruction: 'Book' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
- const ch2 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 2',
- parentTaskId: parent.data.id,
- });
- const ch3 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 3',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
+ const ch2 = await caller.create(chapterInput(testAgentId, 'Chapter 2', parent.data.id));
+ const ch3 = await caller.create(chapterInput(testAgentId, 'Chapter 3', parent.data.id));
// ch3 depends on ch1 and ch2
await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch3.data.id });
await caller.addDependency({ dependsOnId: ch2.data.id, taskId: ch3.data.id });
@@ -1298,21 +1287,9 @@ describe('Task Router Integration', () => {
it('runReadySubtasks kicks off the first layer only', async () => {
const parent = await caller.create({ instruction: 'Book' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
- const ch2 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 2',
- parentTaskId: parent.data.id,
- });
- const ch3 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 3',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
+ const ch2 = await caller.create(chapterInput(testAgentId, 'Chapter 2', parent.data.id));
+ const ch3 = await caller.create(chapterInput(testAgentId, 'Chapter 3', parent.data.id));
await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch3.data.id });
await caller.addDependency({ dependsOnId: ch2.data.id, taskId: ch3.data.id });
@@ -1337,16 +1314,8 @@ describe('Task Router Integration', () => {
it('previewSubtaskLayers holds back dependents of in-flight subtasks (does not free them)', async () => {
const parent = await caller.create({ instruction: 'Inflight blocker' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
- const ch2 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 2',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
+ const ch2 = await caller.create(chapterInput(testAgentId, 'Chapter 2', parent.data.id));
await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });
// Kick ch1 off — now in `running` state
@@ -1362,16 +1331,8 @@ describe('Task Router Integration', () => {
it('runReadySubtasks does not start a subtask whose blocker is still running', async () => {
const parent = await caller.create({ instruction: 'Inflight runReady' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
- const ch2 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 2',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
+ const ch2 = await caller.create(chapterInput(testAgentId, 'Chapter 2', parent.data.id));
await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });
await caller.run({ id: ch1.data.id });
@@ -1392,11 +1353,7 @@ describe('Task Router Integration', () => {
instruction: 'External blocker',
});
const parent = await caller.create({ instruction: 'Cross-scope' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
// ch1 depends on a task that is NOT a descendant of parent
await caller.addDependency({ dependsOnId: externalBlocker.data.id, taskId: ch1.data.id });
@@ -1415,16 +1372,8 @@ describe('Task Router Integration', () => {
it('updateStatus(completed) triggers cascade kickoff for unlocked downstream', async () => {
const parent = await caller.create({ instruction: 'Cascade' });
- const ch1 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 1',
- parentTaskId: parent.data.id,
- });
- const ch2 = await caller.create({
- assigneeAgentId: testAgentId,
- instruction: 'Chapter 2',
- parentTaskId: parent.data.id,
- });
+ const ch1 = await caller.create(chapterInput(testAgentId, 'Chapter 1', parent.data.id));
+ const ch2 = await caller.create(chapterInput(testAgentId, 'Chapter 2', parent.data.id));
await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });
// Kick off layer 1 (just ch1)
@@ -1534,10 +1483,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const wsCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
const wsOtherCaller = taskRouter.createCaller({
...createTestContext(otherUserId),
@@ -1578,10 +1526,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const wsCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
const wsOtherCaller = taskRouter.createCaller({
...createTestContext(otherUserId),
@@ -1656,10 +1603,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const wsCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
// Create without assignee, then assign another member → notifies once.
@@ -1881,10 +1827,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const ownerCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
const memberCaller = taskRouter.createCaller({
...createTestContext(otherUserId!),
@@ -1942,10 +1887,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const ownerCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
const memberCaller = taskRouter.createCaller({
...createTestContext(otherUserId!),
@@ -1983,10 +1927,9 @@ describe('Task Router Integration', () => {
primaryOwnerId: userId,
slug: workspaceId,
});
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId, workspaceId },
- { role: 'member', userId: otherUserId!, workspaceId },
- ]);
+ await serverDB
+ .insert(workspaceMembers)
+ .values(workspaceRoster(userId, workspaceId, otherUserId!));
const wsCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });
// Creating a private task assigned to another member is rejected.
diff --git a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
index 11127f6758c..4c28c3d973f 100644
--- a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
@@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { knowledgeBaseRouter } from '@/server/routers/lambda/knowledgeBase';
import { TransferErrorCode } from '@/types/transferError';
+const publicMemberKnowledgeBase = () => ({
+ id: 'kb-1',
+ userId: 'another-member',
+ visibility: 'public',
+ workspaceId: 'workspace-active',
+});
+
const routerMocks = vi.hoisted(() => ({
assertContentsNotInRestrictedKnowledgeBase: vi.fn(),
assertKnowledgeBaseBrowsable: vi.fn(),
@@ -123,12 +130,7 @@ describe('knowledgeBaseRouter', () => {
describe('updateKnowledgeBase', () => {
it("lets a member update another member's visible shared library", async () => {
- mockKnowledgeBaseModelFindById.mockResolvedValue({
- id: 'kb-1',
- userId: 'another-member',
- visibility: 'public',
- workspaceId: 'workspace-active',
- });
+ mockKnowledgeBaseModelFindById.mockResolvedValue(publicMemberKnowledgeBase());
await caller.updateKnowledgeBase({ id: 'kb-1', value: { name: 'Updated library' } });
@@ -146,12 +148,7 @@ describe('knowledgeBaseRouter', () => {
// so a member with collaborative `edit` access could reassign the row, move
// it to another workspace, or take it private through the rename endpoint.
it('drops identity and scope fields from the update payload', async () => {
- mockKnowledgeBaseModelFindById.mockResolvedValue({
- id: 'kb-1',
- userId: 'another-member',
- visibility: 'public',
- workspaceId: 'workspace-active',
- });
+ mockKnowledgeBaseModelFindById.mockResolvedValue(publicMemberKnowledgeBase());
await caller.updateKnowledgeBase({
id: 'kb-1',
@@ -255,12 +252,7 @@ describe('knowledgeBaseRouter', () => {
describe('removeKnowledgeBase', () => {
it("lets a member delete another creator's visible library", async () => {
- mockKnowledgeBaseModelFindById.mockResolvedValue({
- id: 'kb-1',
- userId: 'another-member',
- visibility: 'public',
- workspaceId: 'workspace-active',
- });
+ mockKnowledgeBaseModelFindById.mockResolvedValue(publicMemberKnowledgeBase());
await caller.removeKnowledgeBase({ id: 'kb-1' });
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.ts
index 6b5020fa6d4..a7ea24ba1e4 100644
--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts
@@ -29,6 +29,30 @@ import {
import { linearRouter } from '../linear';
+const syncRuleInput = (
+ connectionId: string,
+ projectId: string,
+ stateType: NonNullable<
+ Parameters<ReturnType<typeof linearRouter.createCaller>['createSyncRule']>[0]['stateTypes']
+ >[number],
+): Parameters<ReturnType<typeof linearRouter.createCaller>['createSyncRule']>[0] => ({
+ connectionId,
+ projectId,
+ stateTypes: [stateType],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+});
+
+const unauthorizedResponse = () => ({
+ result: {
+ error: {
+ code: -32_001,
+ data: { code: 'UNAUTHORIZED', httpStatus: 401 },
+ message: 'Invalid JWT token',
+ },
+ },
+});
+
const serverDB = await getTestDB();
const userId = 'linear-router-user';
const otherUserId = 'linear-router-user-2';
@@ -351,13 +375,9 @@ describe('linearRouter', () => {
const connection = await connect({ userId });
mocks.getToken.mockResolvedValue('token');
mocks.runSync.mockResolvedValue({ ok: true });
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['unstarted'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'unstarted'),
+ );
const { id } = await caller({ userId }).startRuleSync({ ruleId: rule.id });
return { id, rule };
};
@@ -665,15 +685,7 @@ describe('linearRouter', () => {
mocks.syncByFilter.mockResolvedValue(round(100, true, '100'));
const { id } = await startRule();
mocks.runSync.mockRejectedValue(
- new TRPCClientError('Invalid JWT token', {
- result: {
- error: {
- code: -32_001,
- data: { code: 'UNAUTHORIZED', httpStatus: 401 },
- message: 'Invalid JWT token',
- },
- },
- } as any),
+ new TRPCClientError('Invalid JWT token', unauthorizedResponse() as any),
);
await routerService().run(id);
@@ -763,13 +775,9 @@ describe('linearRouter', () => {
const connection = await connect({ userId });
mocks.getToken.mockResolvedValue('token');
mocks.runSync.mockResolvedValue({ ok: true });
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['unstarted'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'unstarted'),
+ );
const [first, second] = await Promise.all([
caller({ userId }).startRuleSync({ ruleId: rule.id }),
@@ -783,26 +791,14 @@ describe('linearRouter', () => {
describe('when the async router rejects the hand-off', () => {
// What the async router answers when it turns down the internal token.
const rejected = () =>
- new TRPCClientError('Invalid JWT token', {
- result: {
- error: {
- code: -32_001,
- data: { code: 'UNAUTHORIZED', httpStatus: 401 },
- message: 'Invalid JWT token',
- },
- },
- } as any);
+ new TRPCClientError('Invalid JWT token', unauthorizedResponse() as any);
const startRule = async () => {
const connection = await connect({ userId });
mocks.getToken.mockResolvedValue('token');
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['unstarted'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'unstarted'),
+ );
return caller({ userId }).startRuleSync({ ruleId: rule.id });
};
@@ -907,13 +903,9 @@ describe('linearRouter', () => {
mocks.runSync.mockResolvedValue({ ok: true });
let finish: ((result: typeof syncResult) => void) | undefined;
mocks.syncByFilter.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['unstarted'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'unstarted'),
+ );
const { id } = await caller({ userId }).startRuleSync({ ruleId: rule.id });
const running = new LinearSyncJobService(serverDB, userId).run(id);
const settle = async (done: () => Promise<boolean> | boolean) => {
@@ -947,13 +939,9 @@ describe('linearRouter', () => {
it("hides another user's personal rules", async () => {
const connection = await connect({ userId: otherUserId });
- const rule = await caller({ userId: otherUserId }).createSyncRule({
- connectionId: connection.id,
- projectId: otherProjectId,
- stateTypes: ['backlog'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId: otherUserId }).createSyncRule(
+ syncRuleInput(connection.id, otherProjectId, 'backlog'),
+ );
await expect(
caller({ userId }).listSyncRules({ projectId: otherProjectId }),
@@ -970,13 +958,7 @@ describe('linearRouter', () => {
const connection = await connect({ userId });
await expect(
- caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId: otherProjectId,
- stateTypes: ['backlog'],
- teamId: 'team-1',
- teamName: 'Engineering',
- }),
+ caller({ userId }).createSyncRule(syncRuleInput(connection.id, otherProjectId, 'backlog')),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
await expect(
caller({ userId }).startImport({
@@ -1041,13 +1023,9 @@ describe('linearRouter', () => {
targetProjectId: projectId,
});
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['backlog'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'backlog'),
+ );
const run = await caller({ userId }).startRuleSync({ ruleId: rule.id, syncComments: true });
await new LinearSyncJobService(serverDB, userId).run(run.id);
expect(mocks.syncByFilter).toHaveBeenCalledWith(
@@ -1097,13 +1075,9 @@ describe('linearRouter', () => {
await serverDB
.insert(projects)
.values({ id: 'linear-router-project-3', identifier: 'LRR', name: 'Other', userId });
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['backlog'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'backlog'),
+ );
expect(
await caller({ userId }).listSyncRules({ projectId: 'linear-router-project-3' }),
@@ -1118,13 +1092,9 @@ describe('linearRouter', () => {
it('keeps a rule removable after its connection is disconnected, and asks to reconnect on run', async () => {
const connection = await connect({ userId });
- const rule = await caller({ userId }).createSyncRule({
- connectionId: connection.id,
- projectId,
- stateTypes: ['backlog'],
- teamId: 'team-1',
- teamName: 'Engineering',
- });
+ const rule = await caller({ userId }).createSyncRule(
+ syncRuleInput(connection.id, projectId, 'backlog'),
+ );
await LinearConnectionModel.revoke(serverDB, connection.id);
const { LinearReconnectRequiredError } = await import('@/server/services/linear/token');
mocks.getToken.mockRejectedValue(new LinearReconnectRequiredError());
diff --git a/apps/server/src/routers/lambda/__tests__/pushToken.test.ts b/apps/server/src/routers/lambda/__tests__/pushToken.test.ts
index 1c0e9bef0c9..70302d16e92 100644
--- a/apps/server/src/routers/lambda/__tests__/pushToken.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/pushToken.test.ts
@@ -286,20 +286,6 @@ describe('pushTokenRouter', () => {
expect(mockUnregisterLiveActivities).not.toHaveBeenCalled();
});
- it('should prefer expoToken precision over the legacy userId fallback', async () => {
- // If both are available, always take Path A — the (expoToken, deviceId)
- // pair is more precise and doesn't risk deleting a wrong row.
- const caller = createCaller();
-
- await caller.unregister({
- deviceId: 'device-1',
- expoToken: 'ExponentPushToken[abc]',
- });
-
- expect(mockDeleteByExpoTokenAndDevice).toHaveBeenCalled();
- expect(mockUnregister).not.toHaveBeenCalled();
- });
-
it('should reject empty deviceId', async () => {
const caller = createCaller();
await expect(caller.unregister({ deviceId: '' })).rejects.toThrow();
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index 40edf4e70df..25f9dc5cfd2 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -41,6 +41,17 @@ describe('HookDispatcher', () => {
...overrides,
});
+ const makeToolCallContext = (): Parameters<HookDispatcher['dispatchBeforeToolCall']>[1] => ({
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
+ apiName: 'search',
+ args: {},
+ callIndex: 1,
+ identifier: 'twitter',
+ stepIndex: 0,
+ });
+
beforeEach(() => {
dispatcher = new HookDispatcher();
vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(false);
@@ -554,16 +565,7 @@ describe('HookDispatcher', () => {
describe('dispatchBeforeToolCall', () => {
it('should return null when no beforeToolCall hooks registered', async () => {
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toBeNull();
});
@@ -606,16 +608,7 @@ describe('HookDispatcher', () => {
},
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toBeNull();
});
@@ -659,16 +652,7 @@ describe('HookDispatcher', () => {
},
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toBeNull();
});
@@ -684,16 +668,7 @@ describe('HookDispatcher', () => {
]);
await expect(
- dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- }),
+ dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext()),
).resolves.toEqual({ isMocked: true, result });
});
});
@@ -831,16 +806,7 @@ describe('HookDispatcher', () => {
},
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toEqual({
isMocked: true,
@@ -862,16 +828,7 @@ describe('HookDispatcher', () => {
},
{ handler: secondHandler, id: 'must-not-run', type: 'beforeToolCall' },
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toEqual({
isMocked: true,
result: { content: '{"first":true}', success: true },
@@ -892,16 +849,7 @@ describe('HookDispatcher', () => {
},
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(observeHandler).toHaveBeenCalled();
expect(result).toEqual({
@@ -924,16 +872,7 @@ describe('HookDispatcher', () => {
]);
// dispatchBeforeToolCall only runs in local mode
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(result).toBeNull();
});
@@ -955,16 +894,7 @@ describe('HookDispatcher', () => {
]);
// beforeToolCall should not trigger afterStep or onComplete
- await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(afterStepHandler).not.toHaveBeenCalled();
expect(onCompleteHandler).not.toHaveBeenCalled();
@@ -990,16 +920,7 @@ describe('HookDispatcher', () => {
{ handler: mockHandler, id: 'recovering', type: 'beforeToolCall' },
]);
- const result = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, makeToolCallContext());
expect(mockHandler).toHaveBeenCalled();
expect(result).toEqual({
@@ -1101,16 +1022,10 @@ describe('HookDispatcher', () => {
]);
// Local mode: mock works
- const localResult = await dispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const localResult = await dispatcher.dispatchBeforeToolCall(
+ operationId,
+ makeToolCallContext(),
+ );
expect(localResult).toEqual({
isMocked: true,
result: { content: '{"mocked":true}', success: true },
@@ -1121,16 +1036,10 @@ describe('HookDispatcher', () => {
// executes the step, this.hooks would be empty, so mock cannot fire.
// This is by design — mock is local-only.
const otherDispatcher = new HookDispatcher();
- const remoteResult = await otherDispatcher.dispatchBeforeToolCall(operationId, {
- assistantMessageId: 'assistant-1',
- executor: 'server',
- toolCallId: 'native-call-1',
- apiName: 'search',
- args: {},
- callIndex: 1,
- identifier: 'twitter',
- stepIndex: 0,
- });
+ const remoteResult = await otherDispatcher.dispatchBeforeToolCall(
+ operationId,
+ makeToolCallContext(),
+ );
expect(remoteResult).toBeNull(); // No hooks registered → no mock
});
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
index 7aca4234743..32bb307d407 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
@@ -2,7 +2,6 @@
import { describe, expect, it, vi } from 'vitest';
import { AgentSignalProcedureInspector, createProcedurePolicyOptions } from '../../../procedure';
-import { createRuntimeProcessorContext } from '../../../runtime/context';
import type { AgentSignalPolicyStateStore } from '../../../store/types';
import type {
ActionUserMemoryHandle,
@@ -13,18 +12,9 @@ import type {
} from '../../types';
import { createAnalyzeIntentPolicy } from '..';
import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';
+import { createFeedbackTestContext } from './testUtils';
-const context = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
-});
+const context = createFeedbackTestContext();
const createStore = (): AgentSignalPolicyStateStore => {
const state = new Map<string, Record<string, string>>();
@@ -54,10 +44,7 @@ type DomainSignalInput<TTarget extends SupportedTask4DomainTarget> = {
skillActionIntent?: 'consolidate' | 'create' | 'maintain' | 'noop' | 'refine';
skillIntentConfidence?: number;
skillIntentExplicitness?:
- | 'explicit_action'
- | 'implicit_strong_learning'
- | 'non_skill_preference'
- | 'weak_positive';
+ 'explicit_action' | 'implicit_strong_learning' | 'non_skill_preference' | 'weak_positive';
skillIntentReason?: string;
skillRoute?: 'accumulate' | 'direct_decision' | 'non_skill';
signalId: string;
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
index 1c18ddba094..b41fd3da505 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
@@ -1,21 +1,11 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
-import { createRuntimeProcessorContext } from '../../../runtime/context';
import type { SignalFeedbackSatisfaction } from '../../types';
import { createFeedbackDomainJudgeSignalHandler } from '../feedbackDomain';
+import { createFeedbackTestContext } from './testUtils';
-const context = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
-});
+const context = createFeedbackTestContext();
const createSatisfactionSignal = (input: {
message: string;
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
index f7ac9032b50..b6c7050c9e8 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
@@ -8,6 +8,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { createRuntimeProcessorContext } from '../../../runtime/context';
import { createFeedbackSatisfactionJudgeProcessor } from '../feedbackSatisfaction';
+import { createFeedbackTestContext } from './testUtils';
vi.mock('@/server/modules/ModelRuntime', () => ({
initModelRuntimeFromDB: vi.fn(),
@@ -113,17 +114,7 @@ describe('feedbackSatisfactionJudge', () => {
result: 'satisfied',
});
- const ctx = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
- });
+ const ctx = createFeedbackTestContext();
const processor = createFeedbackSatisfactionJudgeProcessor({
db: {} as LobeChatDatabase,
@@ -205,17 +196,7 @@ describe('feedbackSatisfactionJudge', () => {
result: 'satisfied',
}),
};
- const ctx = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
- });
+ const ctx = createFeedbackTestContext();
const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
const result = await processor.handle(
createUserMessageSource(
@@ -259,17 +240,7 @@ describe('feedbackSatisfactionJudge', () => {
result: 'not_satisfied',
}),
};
- const ctx = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
- });
+ const ctx = createFeedbackTestContext();
const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
const result = await processor.handle(
createUserMessageSource(
@@ -314,17 +285,7 @@ describe('feedbackSatisfactionJudge', () => {
result: 'not_satisfied',
}),
};
- const ctx = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
- });
+ const ctx = createFeedbackTestContext();
const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
const result = await processor.handle(
createUserMessageSource(
@@ -363,17 +324,7 @@ describe('feedbackSatisfactionJudge', () => {
result: 'satisfied',
}),
};
- const ctx = createRuntimeProcessorContext({
- backend: {
- async getGuardState() {
- return {};
- },
- async touchGuardState() {
- return {};
- },
- },
- scopeKey: 'topic:thread_1',
- });
+ const ctx = createFeedbackTestContext();
const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
const result = await processor.handle(
createUserMessageSource(
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/testUtils.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/testUtils.ts
new file mode 100644
index 00000000000..45687e636ac
--- /dev/null
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/testUtils.ts
@@ -0,0 +1,14 @@
+import { createRuntimeProcessorContext } from '../../../runtime/context';
+
+export const createFeedbackTestContext = () =>
+ createRuntimeProcessorContext({
+ backend: {
+ async getGuardState() {
+ return {};
+ },
+ async touchGuardState() {
+ return {};
+ },
+ },
+ scopeKey: 'topic:thread_1',
+ });
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts
index cc7235aa50e..903ed8408b3 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/review.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { ReviewTools } from '../review';
-import { createToolSet, ToolSetFacade } from '../shared';
+import { ToolSetFacade } from '../shared';
const createToolSetFacade = () =>
new ToolSetFacade({
@@ -59,12 +59,4 @@ describe('ReviewTools', () => {
expect(recordSelfReviewIdea).toHaveBeenCalledOnce();
});
-
- /**
- * @example
- * expect(createToolSet).toBeTypeOf('function');
- */
- it('exports the shared factory used by concrete review tools', () => {
- expect(createToolSet).toBeTypeOf('function');
- });
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 8eb38466dec..a319bac5f9b 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -226,6 +226,26 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
platform: 'darwin' as const,
};
+ const createAgentConfig = (agencyConfig: Record<string, unknown>) => ({
+ agencyConfig,
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ });
+
+ const createOwnerBotContext = () => ({
+ applicationId: 'app-1',
+ isOwner: true,
+ platform: 'discord',
+ platformThreadId: 'discord:guild-1:channel-1',
+ senderExternalUserId: 'owner-id',
+ });
+
// Override the agent's agencyConfig and rebuild the service. Auto-activation
// is now exclusive to `executionTarget: 'auto'` — the default (`local`) never
// grabs a device — so the auto-activation specs opt in explicitly.
@@ -233,17 +253,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig,
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi.fn().mockResolvedValue(createAgentConfig(agencyConfig)),
} as any;
});
service = new AiAgentService(mockDb, userId);
@@ -257,13 +267,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -279,13 +283,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -301,13 +299,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -324,13 +316,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -426,17 +412,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig,
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi.fn().mockResolvedValue(createAgentConfig(agencyConfig)),
} as any;
});
service = new AiAgentService(mockDb, userId);
@@ -486,17 +462,9 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig: { boundDeviceId: 'device-001' },
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi
+ .fn()
+ .mockResolvedValue(createAgentConfig({ boundDeviceId: 'device-001' })),
} as any;
});
@@ -519,17 +487,9 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig: { boundDeviceId: 'device-001' },
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi
+ .fn()
+ .mockResolvedValue(createAgentConfig({ boundDeviceId: 'device-001' })),
} as any;
});
@@ -636,17 +596,9 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig: { boundDeviceId: 'device-002' },
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi
+ .fn()
+ .mockResolvedValue(createAgentConfig({ boundDeviceId: 'device-002' })),
} as any;
});
@@ -934,13 +886,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -1028,13 +974,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -1052,17 +992,9 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const { AgentService } = await import('@/server/services/agent');
vi.mocked(AgentService).mockImplementation(function () {
return {
- getAgentConfig: vi.fn().mockResolvedValue({
- agencyConfig: { boundDeviceId: 'device-001' },
- chatConfig: {},
- files: [],
- id: 'agent-1',
- knowledgeBases: [],
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helpful assistant',
- }),
+ getAgentConfig: vi
+ .fn()
+ .mockResolvedValue(createAgentConfig({ boundDeviceId: 'device-001' })),
} as any;
});
@@ -1100,13 +1032,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
@@ -1120,13 +1046,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
await service.execAgent({
agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- isOwner: true,
- platform: 'discord',
- platformThreadId: 'discord:guild-1:channel-1',
- senderExternalUserId: 'owner-id',
- } as any,
+ botContext: createOwnerBotContext() as any,
prompt: 'List my files',
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
index 8fda05979b2..e0abda83d19 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
@@ -241,6 +241,15 @@ const toolsEngineConfigArg = () =>
const skillById = (identifier: string) =>
operationSkillSetArg()?.skills.find((s) => s.identifier === identifier);
+const createAgentConfig = (plugins: string[]) => ({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins,
+ provider: 'openai',
+ systemRole: 'You are a helper',
+});
+
describe('AiAgentService.execAgent - pinned skill content injection', () => {
let service: AiAgentService;
@@ -297,15 +306,8 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('injects a pinned DB skill body into the operation skill set, leaving auto skills content-less', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- // db-skill-pinned is pinned; db-skill-auto is absent from plugins → auto.
- plugins: ['db-skill-pinned'],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ // db-skill-pinned is pinned; db-skill-auto is absent from plugins → auto.
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -316,14 +318,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('fetches bodies only for the pinned subset to keep the op-param payload bounded', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: ['db-skill-pinned'],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-pinned']));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -342,14 +337,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
title: null,
},
]);
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: ['agent-skills:foo'],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(['agent-skills:foo']));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -359,14 +347,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('does not attach content when no skill is pinned', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -376,14 +357,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('enables the goal tool for a direct server /goal prompt', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
await service.execAgent({ agentId: 'agent-1', prompt: '/goal ship it' } as any);
@@ -419,15 +393,8 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('does not eager-inject an auto skill whose identifier collides with a turn-scoped tool id', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- // Nothing pinned — db-skill-auto is in auto mode.
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ // Nothing pinned — db-skill-auto is in auto mode.
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
// db-skill-auto lands in the expanded operation tool list (`agentPlugins`)
// via a turn-scoped @-mention pick, but it is NOT pinned on the agent.
@@ -444,14 +411,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('lists the user skill library to every run, content-less until a run names a skill', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -467,14 +427,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('injects a user skill the run names in its plugins, as a goal batch unit does', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
await service.execAgent({
additionalPluginIds: ['lobe-task', 'user-skills:goal-plan-x'],
@@ -487,14 +440,7 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
});
it('appends the resource tree to a pinned skill body, mirroring activateSkill', async () => {
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- plugins: ['db-skill-with-resources'],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig(['db-skill-with-resources']));
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
@@ -535,15 +481,8 @@ describe('AiAgentService.execAgent - selected skill content injection', () => {
mockGetAgentSkills.mockResolvedValue([]);
mockListUserSkillCatalog.mockResolvedValue([]);
mockLoadUserSkills.mockResolvedValue([]);
- mockGetAgentConfig.mockResolvedValue({
- chatConfig: {},
- id: 'agent-1',
- model: 'gpt-4',
- // Nothing pinned — db-skill-auto is an auto-mode skill.
- plugins: [],
- provider: 'openai',
- systemRole: 'You are a helper',
- });
+ // Nothing pinned — db-skill-auto is an auto-mode skill.
+ mockGetAgentConfig.mockResolvedValue(createAgentConfig([]));
service = new AiAgentService({} as any, 'test-user-id');
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts
index 0d725d5678b..3658cb30fe7 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.supersedeRunningOperation.test.ts
@@ -195,6 +195,13 @@ vi.mock('model-bank', async (importOriginal) => {
};
});
+const createInteractiveParams = (prompt = 'please hurry') => ({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ interactiveStart: true,
+ prompt,
+});
+
const topicWithMarker = (operationId: string) => ({
id: 'topic-1',
metadata: { runningOperation: { assistantMessageId: 'asst-old', operationId } },
@@ -289,12 +296,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
});
it('interrupts the live marker holder when the client sent no replacement', async () => {
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(interruptTask).toHaveBeenCalledTimes(1);
expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });
@@ -320,12 +322,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
userId: 'test-user-id',
});
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });
});
@@ -342,12 +339,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
userId: 'test-user-id',
});
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });
expect(mockMergeMetadata).toHaveBeenCalledWith(
@@ -366,12 +358,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
},
});
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(interruptTask).not.toHaveBeenCalled();
});
@@ -388,14 +375,9 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
userId: 'teammate-id',
});
- await expect(
- service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'keep going',
- }),
- ).rejects.toBeInstanceOf(ForeignLiveRunError);
+ await expect(service.execAgent(createInteractiveParams('keep going'))).rejects.toBeInstanceOf(
+ ForeignLiveRunError,
+ );
expect(interruptTask).not.toHaveBeenCalled();
expect(mockMessageCreate).not.toHaveBeenCalled();
@@ -435,12 +417,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
userId: 'teammate-id',
});
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'keep going',
- });
+ await service.execAgent(createInteractiveParams('keep going'));
expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });
});
@@ -486,12 +463,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
])('leaves %s alone', async (_, operation) => {
mockFindOperationById.mockResolvedValue({ id: 'op-live', ...operation });
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(interruptTask).not.toHaveBeenCalled();
});
@@ -530,12 +502,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
mockIsOperationInterrupted.mockResolvedValue(true);
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(mockMergeMetadata).toHaveBeenCalledWith(expect.any(String), {
supersede: expect.objectContaining({ kind: 'already_stopping' }),
@@ -552,12 +519,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
vi.spyOn(console, 'warn').mockImplementation(() => {});
mockMergeMetadata.mockRejectedValue(new Error('db down'));
- const result = await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ const result = await service.execAgent(createInteractiveParams());
expect(result.success).toBe(true);
error.mockRestore();
@@ -567,12 +529,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
mockIsOperationInterrupted.mockRejectedValue(new Error('redis down'));
- const result = await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ const result = await service.execAgent(createInteractiveParams());
expect(result.success).toBe(true);
expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-live', topicId: 'topic-1' });
@@ -586,12 +543,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
interruptTask.mockResolvedValue({ success: false });
- const result = await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ const result = await service.execAgent(createInteractiveParams());
expect(result.success).toBe(true);
expect(warn).toHaveBeenCalledWith('[execAgent] supersede of %s was not confirmed', 'op-live', {
@@ -603,12 +555,7 @@ describe('AiAgentService.execAgent - supersede running foreground operation', ()
it('records nothing when no run was superseded', async () => {
mockFindOperationById.mockResolvedValue({ id: 'op-live', status: 'done', trigger: 'chat' });
- await service.execAgent({
- agentId: 'agent-1',
- appContext: { topicId: 'topic-1' },
- interactiveStart: true,
- prompt: 'please hurry',
- });
+ await service.execAgent(createInteractiveParams());
expect(mockMergeMetadata).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index c023263c40f..da4dcc134a6 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -1,3 +1,4 @@
+import type { ExecAgentResult, ExecSubAgentParams } from '@lobechat/types';
import { ThreadStatus, ThreadType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -139,6 +140,44 @@ vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({
createStreamEventManager: () => mockStreamManager,
}));
+const createSuccessfulExecAgentResult = (): ExecAgentResult => ({
+ agentId: 'agent-1',
+ assistantMessageId: 'assistant-msg-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'Agent operation created successfully',
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ topicId: 'topic-1',
+ userMessageId: 'user-msg-1',
+});
+
+const createFailedExecAgentResult = (error: string): ExecAgentResult => ({
+ agentId: 'agent-1',
+ assistantMessageId: 'assistant-msg-1',
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ error,
+ message: 'Agent operation failed to start',
+ operationId: 'op-123',
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId: 'topic-1',
+ userMessageId: 'user-msg-1',
+});
+
+const createSubAgentParams = (): ExecSubAgentParams => ({
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: 'topic-1',
+});
+
describe('AiAgentService.execSubAgent', () => {
let service: AiAgentService;
const mockDb = {} as any;
@@ -166,28 +205,9 @@ describe('AiAgentService.execSubAgent', () => {
describe('successful isolated execution', () => {
it('should create Thread with correct parameters', async () => {
// Mock execAgent to return success
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(createSuccessfulExecAgentResult());
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
expect(mockThreadModel.create).toHaveBeenCalledWith({
agentId: 'agent-1',
@@ -199,28 +219,9 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should update Thread status to processing with startedAt', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(createSuccessfulExecAgentResult());
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {
metadata: { startedAt: expect.any(String) },
@@ -229,28 +230,11 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should call execAgent with threadId in appContext and stepCallbacks', async () => {
- const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue(createSuccessfulExecAgentResult());
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
expect(execAgentSpy).toHaveBeenCalledWith({
agentId: 'agent-1',
@@ -275,20 +259,9 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should run deferred lobe-agent children through execVirtualSubAgent', async () => {
- const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue(createSuccessfulExecAgentResult());
await service.execVirtualSubAgent({
agentId: 'agent-1',
@@ -337,28 +310,9 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should store operationId and startedAt in Thread metadata', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(createSuccessfulExecAgentResult());
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
// Second update call should be storing operationId and startedAt in metadata
expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {
@@ -367,28 +321,9 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should return correct result on success', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(createSuccessfulExecAgentResult());
- const result = await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ const result = await service.execSubAgent(createSubAgentParams());
expect(result).toEqual({
assistantMessageId: 'assistant-msg-1',
@@ -402,28 +337,11 @@ describe('AiAgentService.execSubAgent', () => {
describe('execAgent failure handling', () => {
it('should update Thread status to failed when execAgent fails', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'Agent execution failed',
- message: 'Agent operation failed to start',
- operationId: 'op-123',
- status: 'error',
- success: false,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(
+ createFailedExecAgentResult('Agent execution failed'),
+ );
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
// Should update Thread status to failed with metadata
expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {
@@ -439,28 +357,11 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should store error info with duration in Thread metadata when execAgent fails', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'QStash service unavailable',
- message: 'Agent operation failed to start',
- operationId: 'op-123',
- status: 'error',
- success: false,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(
+ createFailedExecAgentResult('QStash service unavailable'),
+ );
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
// Last update call should contain error info, completedAt, startedAt, and duration
const lastUpdateCall = mockThreadModel.update.mock.calls.find(
@@ -477,28 +378,11 @@ describe('AiAgentService.execSubAgent', () => {
});
it('should return result with error info when execAgent fails', async () => {
- vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'Agent execution failed',
- message: 'Agent operation failed to start',
- operationId: 'op-123',
- status: 'error',
- success: false,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ vi.spyOn(service, 'execAgent').mockResolvedValue(
+ createFailedExecAgentResult('Agent execution failed'),
+ );
- const result = await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ const result = await service.execSubAgent(createSubAgentParams());
expect(result).toEqual({
assistantMessageId: 'assistant-msg-1',
@@ -514,56 +398,27 @@ describe('AiAgentService.execSubAgent', () => {
it('should throw error when Thread creation fails', async () => {
mockThreadModel.create.mockResolvedValue(null);
- await expect(
- service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow('Failed to create thread for agent execution');
+ await expect(service.execSubAgent(createSubAgentParams())).rejects.toThrow(
+ 'Failed to create thread for agent execution',
+ );
});
it('should throw error when Thread creation throws', async () => {
mockThreadModel.create.mockRejectedValue(new Error('Database connection failed'));
- await expect(
- service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow('Database connection failed');
+ await expect(service.execSubAgent(createSubAgentParams())).rejects.toThrow(
+ 'Database connection failed',
+ );
});
});
describe('source message summary update', () => {
it('should pass sourceMessageId (parentMessageId) to callbacks for summary update', async () => {
- const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue({
- agentId: 'agent-1',
- assistantMessageId: 'assistant-msg-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'Agent operation created successfully',
- messageId: 'queue-msg-1',
- operationId: 'op-123',
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- topicId: 'topic-1',
- userMessageId: 'user-msg-1',
- });
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue(createSuccessfulExecAgentResult());
- await service.execSubAgent({
- agentId: 'agent-1',
- groupId: 'group-1',
- instruction: 'Test instruction',
- parentMessageId: 'parent-msg-1',
- topicId: 'topic-1',
- });
+ await service.execSubAgent(createSubAgentParams());
// Verify that hooks were passed with onComplete
expect(execAgentSpy).toHaveBeenCalledWith(
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.test.ts
index 2ca2e3914d0..7c4417576b5 100644
--- a/apps/server/src/services/bot/AgentBridgeService/index.test.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.test.ts
@@ -683,21 +683,6 @@ describe('AgentBridgeService', () => {
expect(thread.startTyping).toHaveBeenCalled();
expect(progressMessageIdFromHooks()).toBeUndefined();
});
-
- it('keeps the ack when processingMessage is on', async () => {
- mockGetPlatform.mockReturnValue({ id: 'qq', name: 'QQ', supportsMessageEdit: false });
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const thread = createThread();
-
- await service.handleMention(thread, createMessage(), {
- agentId: 'agent-1',
- botContext: { platform: 'qq', platformThreadId: 'qq:c2c:user-1' } as any,
- botSettings: { processingMessage: true },
- client: createClient(),
- });
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- });
});
describe('activeThreads cleanup on side-effect failure', () => {
diff --git a/apps/server/src/services/comfyui/__tests__/core/errorHandling.test.ts b/apps/server/src/services/comfyui/__tests__/core/errorHandling.test.ts
index 3840d98b609..24d294cb1a2 100644
--- a/apps/server/src/services/comfyui/__tests__/core/errorHandling.test.ts
+++ b/apps/server/src/services/comfyui/__tests__/core/errorHandling.test.ts
@@ -70,16 +70,6 @@ describe('Error Handling - SDK Integration', () => {
});
describe('Parameter Validation Errors', () => {
- it('should validate required parameters', async () => {
- const missingParams = {
- model: 'flux-dev',
- params: { prompt: '' }, // 缺少必要参数,但至少包含必需的prompt
- };
-
- // 应该验证并报错
- await expect(imageService.createImage(missingParams)).rejects.toThrow();
- });
-
it('should handle parameter boundary violations gracefully', async () => {
const invalidParams = {
model: 'flux-dev',
diff --git a/apps/server/src/services/comfyui/__tests__/integration/serviceIntegration.test.ts b/apps/server/src/services/comfyui/__tests__/integration/serviceIntegration.test.ts
index b8db4c20746..87400c5e02e 100644
--- a/apps/server/src/services/comfyui/__tests__/integration/serviceIntegration.test.ts
+++ b/apps/server/src/services/comfyui/__tests__/integration/serviceIntegration.test.ts
@@ -152,9 +152,6 @@ describe('Service Integration - Module Level', () => {
} catch (error) {
// 预期在 mock 环境中可能有错误
}
-
- // 验证基本功能正常
- expect(true).toBe(true);
});
});
});
diff --git a/apps/server/src/services/comfyui/__tests__/utils/componentInfo.test.ts b/apps/server/src/services/comfyui/__tests__/utils/componentInfo.test.ts
index 46cab4e468b..f92b64f2a5f 100644
--- a/apps/server/src/services/comfyui/__tests__/utils/componentInfo.test.ts
+++ b/apps/server/src/services/comfyui/__tests__/utils/componentInfo.test.ts
@@ -283,18 +283,6 @@ describe('componentInfo.ts', () => {
expect(() => isSystemComponent('any-file.safetensors')).not.toThrow();
});
- it('should handle corrupted COMPONENT_NODE_MAPPINGS gracefully', () => {
- // Test with a component that exists in SYSTEM_COMPONENTS but has invalid type
- const result = getComponentInfo('invalid-component.bin');
- expect(result).toBeUndefined();
- });
-
- it('should handle missing properties in config', () => {
- // Test with a component that has invalid type in our mock
- const result = getComponentInfo('invalid-component.bin');
- expect(result).toBeUndefined();
- });
-
it('should handle very long filenames', () => {
const longFilename = 'a'.repeat(1000) + '.safetensors';
expect(() => {
diff --git a/apps/server/src/services/conversationWake/__tests__/config.test.ts b/apps/server/src/services/conversationWake/__tests__/config.test.ts
index 35bc6ac83ff..885c6c9e3f1 100644
--- a/apps/server/src/services/conversationWake/__tests__/config.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/config.test.ts
@@ -678,15 +678,4 @@ describe('an operator override of the modes', () => {
expect(flattened).not.toHaveProperty('botWake');
expect(parseBotWakeSettings(flattened).ruleMode).toBe('enforce');
});
-
- it('is not read from the flat keys an earlier form saved', () => {
- const parsed = parseBotWakeSettings({
- botWakeClassifierMode: 'off',
- botWakeDisabled: false,
- botWakeMode: 'shadow',
- });
-
- expect(parsed.ruleMode).toBe('enforce');
- expect(parsed.rules.classifier.mode).toBe('enforce');
- });
});
diff --git a/apps/server/src/services/conversationWake/__tests__/policies.test.ts b/apps/server/src/services/conversationWake/__tests__/policies.test.ts
index db286827a0c..ffc737275d5 100644
--- a/apps/server/src/services/conversationWake/__tests__/policies.test.ts
+++ b/apps/server/src/services/conversationWake/__tests__/policies.test.ts
@@ -125,12 +125,6 @@ describe('internal rules policy', () => {
expect([result.verdict, result.reason]).toEqual(expected);
});
-
- it('never allows', () => {
- for (const { signal: overrides } of cases) {
- expect(evaluate(policy, signal(overrides)).verdict).not.toBe('allow');
- }
- });
});
describe('internal rules policy: naming the bot', () => {
diff --git a/apps/server/src/services/dashboard/__tests__/index.test.ts b/apps/server/src/services/dashboard/__tests__/index.test.ts
index c9b22fe83f8..146084ff64b 100644
--- a/apps/server/src/services/dashboard/__tests__/index.test.ts
+++ b/apps/server/src/services/dashboard/__tests__/index.test.ts
@@ -20,18 +20,15 @@ describe('normalizeItemLayout', () => {
it('keeps the whole item inside the last column', () => {
// a wide item near the right edge is pulled left so it ends on the grid
- expect(normalizeItemLayout({ h: 1, w: 20, x: 80, y: 0 })).toMatchObject({ w: 20, x: 76 });
+ const wide = normalizeItemLayout({ h: 1, w: 20, x: 80, y: 0 });
+ expect(wide).toMatchObject({ w: 20, x: 76 });
// a one-cell item cannot start past the final column
- expect(normalizeItemLayout({ h: 1, w: 1, x: 96, y: 0 })).toMatchObject({ w: 1, x: 95 });
+ const single = normalizeItemLayout({ h: 1, w: 1, x: 96, y: 0 });
+ expect(single).toMatchObject({ w: 1, x: 95 });
// the clamp uses the normalized width, not the raw one
expect(normalizeItemLayout({ h: 1, w: 0, x: 96, y: 0 })).toMatchObject({ w: 1, x: 95 });
expect(normalizeItemLayout({ h: 1, w: 999, x: 60, y: 0 })).toMatchObject({ w: 48, x: 48 });
- for (const layout of [
- { h: 1, w: 20, x: 80, y: 0 },
- { h: 1, w: 1, x: 96, y: 0 },
- { h: 1, w: 48, x: 1000, y: 0 },
- ]) {
- const { w, x } = normalizeItemLayout(layout);
+ for (const { w, x } of [wide, single, normalizeItemLayout({ h: 1, w: 48, x: 1000, y: 0 })]) {
expect(x + w).toBeLessThanOrEqual(DASHBOARD_GRID.maxColumns);
}
});
diff --git a/apps/server/src/services/deviceGateway/index.projectFiles.test.ts b/apps/server/src/services/deviceGateway/index.projectFiles.test.ts
index 59a5d05557a..3b3613c4da2 100644
--- a/apps/server/src/services/deviceGateway/index.projectFiles.test.ts
+++ b/apps/server/src/services/deviceGateway/index.projectFiles.test.ts
@@ -4,6 +4,31 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DeviceGateway } from '.';
import { mockClient, mockEnv, resetGatewayMocks } from './testUtils';
+const createWorkspaceInput = () => ({
+ deviceId: 'dev-1',
+ scope: '/proj',
+ userId: 'user-1',
+});
+
+const createReadProjectFileInput = () => ({
+ deviceId: 'dev-1',
+ path: '/proj/App.tsx',
+ userId: 'user-1',
+ workingDirectory: '/proj',
+});
+
+const createProjectSkillItem = () => ({
+ description: 'spa',
+ fileCount: 3,
+ files: ['SKILL.md'],
+ name: 'spa-routes',
+ path: '/proj/.agents/skills/spa-routes/SKILL.md',
+ previewRoot: '/proj',
+ scope: 'project',
+ skillDir: '/proj/.agents/skills/spa-routes',
+ source: '.agents/skills',
+});
+
vi.mock('@/server/services/redis/client', () =>
import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),
);
@@ -31,11 +56,7 @@ describe('DeviceGateway', () => {
it('should return undefined when not configured', async () => {
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toBeUndefined();
expect(mockClient.invokeRpc).not.toHaveBeenCalled();
});
@@ -47,17 +68,7 @@ describe('DeviceGateway', () => {
instructions: [{ content: '# Rules', source: 'AGENTS.md' }],
// Device returns rich ProjectSkillItems; only prompt metadata survives.
skills: [
- {
- description: 'spa',
- fileCount: 3,
- files: ['SKILL.md'],
- name: 'spa-routes',
- path: '/proj/.agents/skills/spa-routes/SKILL.md',
- previewRoot: '/proj',
- scope: 'project',
- skillDir: '/proj/.agents/skills/spa-routes',
- source: '.agents/skills',
- },
+ createProjectSkillItem(),
{
description: 'device',
fileCount: 2,
@@ -75,11 +86,7 @@ describe('DeviceGateway', () => {
});
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toEqual({
instructions: [{ content: '# Rules', source: 'AGENTS.md' }],
@@ -109,11 +116,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ data: {}, success: true });
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toEqual({ instructions: [], skills: [] });
});
@@ -123,11 +126,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -137,11 +136,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ success: true });
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -151,11 +146,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));
const proxy = new DeviceGateway();
- const result = await proxy.initWorkspace({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.initWorkspace(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -190,11 +181,7 @@ describe('DeviceGateway', () => {
it('should return undefined when not configured', async () => {
const proxy = new DeviceGateway();
- const result = await proxy.listProjectSkills({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.listProjectSkills(createWorkspaceInput());
expect(result).toBeUndefined();
expect(mockClient.invokeRpc).not.toHaveBeenCalled();
});
@@ -203,29 +190,13 @@ describe('DeviceGateway', () => {
configure();
const data = {
root: '/proj',
- skills: [
- {
- description: 'spa',
- fileCount: 3,
- files: ['SKILL.md'],
- name: 'spa-routes',
- path: '/proj/.agents/skills/spa-routes/SKILL.md',
- previewRoot: '/proj',
- scope: 'project',
- skillDir: '/proj/.agents/skills/spa-routes',
- source: '.agents/skills',
- },
- ],
+ skills: [createProjectSkillItem()],
source: '.agents/skills',
};
mockClient.invokeRpc.mockResolvedValue({ data, success: true });
const proxy = new DeviceGateway();
- const result = await proxy.listProjectSkills({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.listProjectSkills(createWorkspaceInput());
expect(result).toEqual(data);
expect(mockClient.invokeRpc).toHaveBeenCalledWith(
@@ -239,11 +210,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });
const proxy = new DeviceGateway();
- const result = await proxy.listProjectSkills({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.listProjectSkills(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -253,11 +220,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ success: true });
const proxy = new DeviceGateway();
- const result = await proxy.listProjectSkills({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.listProjectSkills(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -267,11 +230,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));
const proxy = new DeviceGateway();
- const result = await proxy.listProjectSkills({
- deviceId: 'dev-1',
- scope: '/proj',
- userId: 'user-1',
- });
+ const result = await proxy.listProjectSkills(createWorkspaceInput());
expect(result).toBeUndefined();
});
@@ -306,12 +265,7 @@ describe('DeviceGateway', () => {
it('returns an error result when not configured', async () => {
const proxy = new DeviceGateway();
- const result = await proxy.getLocalFilePreview({
- deviceId: 'dev-1',
- path: '/proj/App.tsx',
- userId: 'user-1',
- workingDirectory: '/proj',
- });
+ const result = await proxy.getLocalFilePreview(createReadProjectFileInput());
expect(result).toEqual({ error: 'Device gateway not configured', success: false });
expect(mockClient.invokeRpc).not.toHaveBeenCalled();
@@ -330,12 +284,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ data, success: true });
const proxy = new DeviceGateway();
- const result = await proxy.getLocalFilePreview({
- deviceId: 'dev-1',
- path: '/proj/App.tsx',
- userId: 'user-1',
- workingDirectory: '/proj',
- });
+ const result = await proxy.getLocalFilePreview(createReadProjectFileInput());
expect(result).toEqual(data);
expect(mockClient.invokeRpc).toHaveBeenCalledWith(
@@ -382,12 +331,7 @@ describe('DeviceGateway', () => {
mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });
const proxy = new DeviceGateway();
- const result = await proxy.getLocalFilePreview({
- deviceId: 'dev-1',
- path: '/proj/App.tsx',
- userId: 'user-1',
- workingDirectory: '/proj',
- });
+ const result = await proxy.getLocalFilePreview(createReadProjectFileInput());
expect(result).toEqual({ error: 'offline', success: false });
});
diff --git a/apps/server/src/services/discover/index.test.ts b/apps/server/src/services/discover/index.test.ts
index 26cb9be5013..730e2ae526b 100644
--- a/apps/server/src/services/discover/index.test.ts
+++ b/apps/server/src/services/discover/index.test.ts
@@ -649,8 +649,6 @@ describe('DiscoverService', () => {
it('should filter by search query', async () => {
const result = await service.getProviderList({ q: 'openai' });
-
- expect(result.items.length).toBeGreaterThan(0);
expect(result.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -772,11 +770,6 @@ describe('DiscoverService', () => {
}),
]),
);
- });
-
- it('should not include categories that only have hidden models', async () => {
- const result = await service.getModelCategories();
-
expect(result.some((item) => item.category === 'lobehub')).toBe(false);
});
});
diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.ts
index 180ee684949..9955ff0b064 100644
--- a/apps/server/src/services/file/__tests__/index.test.ts
+++ b/apps/server/src/services/file/__tests__/index.test.ts
@@ -450,7 +450,7 @@ describe('FileService', () => {
);
});
- it('should write metadata compatible with UI upload path', async () => {
+ it('records upload metadata and a nonempty content hash', async () => {
const content = Buffer.from('test content');
await service.uploadFromBuffer(content, 'text/plain', 'files/test-user/abc/test.txt');
@@ -467,6 +467,10 @@ describe('FileService', () => {
expect.any(Boolean),
expect.anything(),
);
+
+ expect(mockFileModel.checkHash).toHaveBeenCalled();
+ const createdRecord = mockFileModel.create.mock.calls[0][0];
+ expect(createdRecord.fileHash.length).toBeGreaterThan(0);
});
it('preserves private visibility and page-editor source for rehosted images', async () => {
@@ -513,16 +517,6 @@ describe('FileService', () => {
);
expect(mockFileModel.create).toHaveBeenCalledWith(expect.anything(), false, tx);
});
-
- it('should compute hash for deduplication', async () => {
- const content = Buffer.from('test content');
-
- await service.uploadFromBuffer(content, 'text/plain', 'files/test-user/abc/test.txt');
-
- expect(mockFileModel.checkHash).toHaveBeenCalled();
- const createdRecord = mockFileModel.create.mock.calls[0][0];
- expect(createdRecord.fileHash.length).toBeGreaterThan(0);
- });
});
describe('createFileRecord', () => {
diff --git a/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts b/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts
index fbd20dcf09d..76cd75442a5 100644
--- a/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts
+++ b/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts
@@ -152,19 +152,6 @@ describe('GatewayManager', () => {
);
});
- it('should skip already running bots', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { key: 'value' },
- },
- ]);
-
- await manager.start();
-
- expect(manager.isRunning).toBe(true);
- });
-
it('should handle sync errors gracefully', async () => {
mockFindEnabledByPlatform.mockRejectedValue(new Error('DB connection failed'));
diff --git a/apps/server/src/services/gateway/index.desiredForHost.test.ts b/apps/server/src/services/gateway/index.desiredForHost.test.ts
index a63bf5df06e..ba7d9e65339 100644
--- a/apps/server/src/services/gateway/index.desiredForHost.test.ts
+++ b/apps/server/src/services/gateway/index.desiredForHost.test.ts
@@ -12,6 +12,13 @@ import {
resetGatewayServiceMocks,
} from './testUtils';
+const createWechatLink = () => ({
+ applicationId: 'wx-app',
+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
+ tenantId: 't1',
+ userId: 'u1',
+});
+
vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));
vi.mock('./MessageGatewayClient', () =>
import('./testUtils').then((m) => m.messageGatewayClientModule()),
@@ -183,12 +190,7 @@ describe('GatewayService', () => {
mockFindEnabledByPlatform.mockResolvedValue([]);
mockResolveConnectionMode.mockReturnValue('polling');
mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
+ createWechatLink(),
{ applicationId: 'wx-app', credentials: {}, tenantId: 't2', userId: 'u2' },
]);
@@ -222,14 +224,7 @@ describe('GatewayService', () => {
});
mockResolveConnectionMode.mockReturnValue('polling');
mockFindEnabledByPlatform.mockResolvedValue([]);
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });
const result = await service.listDesiredConnectionsForHost('node');
@@ -245,14 +240,7 @@ describe('GatewayService', () => {
mockNodeGateway.platforms = [];
mockNodeGatewayClient.isConfigured = true;
mockResolveConnectionMode.mockReturnValue('polling');
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
const result = await service.listDesiredConnectionsForHost('node');
@@ -269,14 +257,7 @@ describe('GatewayService', () => {
mockNodeGatewayClient.isConfigured = true;
mockResolveConnectionMode.mockReturnValue('polling');
mockFindEnabledByPlatform.mockResolvedValue([]);
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
// The default host still holds it — mid-migration.
mockGatewayClient.getRegisteredIds.mockResolvedValue({
ids: ['messenger:wechat:t1:user-u1'],
@@ -301,14 +282,7 @@ describe('GatewayService', () => {
mockNodeGatewayClient.isConfigured = true;
mockResolveConnectionMode.mockReturnValue('polling');
mockFindEnabledByPlatform.mockResolvedValue([]);
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
// Stats answered, registered-ids did not: a live host we can only half see.
mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registry unavailable'));
@@ -326,14 +300,7 @@ describe('GatewayService', () => {
mockNodeGatewayClient.isConfigured = true;
mockResolveConnectionMode.mockReturnValue('polling');
mockFindEnabledByPlatform.mockResolvedValue([]);
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });
const result = await service.listDesiredConnectionsForHost('node');
@@ -353,14 +320,7 @@ describe('GatewayService', () => {
mockNodeGatewayClient.isConfigured = true;
mockResolveConnectionMode.mockReturnValue('polling');
mockFindEnabledByPlatform.mockResolvedValue([]);
- mockFindAllLinksByPlatform.mockResolvedValue([
- {
- applicationId: 'wx-app',
- credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },
- tenantId: 't1',
- userId: 'u1',
- },
- ]);
+ mockFindAllLinksByPlatform.mockResolvedValue([createWechatLink()]);
mockGatewayClient.getStats.mockRejectedValue(new Error('admin down'));
mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('admin down'));
diff --git a/apps/server/src/services/gateway/index.dualHost.test.ts b/apps/server/src/services/gateway/index.dualHost.test.ts
index bee9048c6f7..84f831f54df 100644
--- a/apps/server/src/services/gateway/index.dualHost.test.ts
+++ b/apps/server/src/services/gateway/index.dualHost.test.ts
@@ -15,6 +15,27 @@ import {
resetGatewayServiceMocks,
} from './testUtils';
+const createWechatProvider = () => ({
+ applicationId: 'wechat-app',
+ credentials: { botToken: 'token' },
+ id: 'wechat-provider',
+ settings: {},
+ userId: 'u1',
+});
+
+const createConnectedWechatStats = (connectionId: string) => ({
+ byPlatform: { wechat: 1 },
+ connections: [
+ {
+ connectionId,
+ platform: 'wechat',
+ state: { status: 'connected' },
+ userId: 'u1',
+ },
+ ],
+ total: 1,
+});
+
vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));
vi.mock('./MessageGatewayClient', () =>
import('./testUtils').then((m) => m.messageGatewayClientModule()),
@@ -66,17 +87,7 @@ describe('GatewayService', () => {
it('moves a bot provider to the node host: stale-disconnects on default, connects on node', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider()] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
// Provider row is enabled+polling, but routed to node — the TOCTOU
@@ -218,17 +229,7 @@ describe('GatewayService', () => {
it('defers a cross-host move while the destination host has no usable snapshot', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider()] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockFindByIds.mockResolvedValue([
@@ -316,17 +317,7 @@ describe('GatewayService', () => {
// drain the source second, and never revisit the destination.
mockNodeGateway.platforms = [];
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider()] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockFindByIds.mockResolvedValue([
@@ -429,18 +420,7 @@ describe('GatewayService', () => {
/** The default host is holding the WeChat poller; routing says it moves. */
const defaultHostHoldsIt = () => {
- mockGatewayClient.getStats.mockResolvedValue({
- byPlatform: { wechat: 1 },
- connections: [
- {
- connectionId: CONNECTION_ID,
- platform: 'wechat',
- state: { status: 'connected' },
- userId: 'u1',
- },
- ],
- total: 1,
- });
+ mockGatewayClient.getStats.mockResolvedValue(createConnectedWechatStats(CONNECTION_ID));
mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });
};
@@ -480,18 +460,7 @@ describe('GatewayService', () => {
mockNodeGateway.platforms = [];
mockGatewayClient.getCapabilities.mockResolvedValue(null);
// The node host is the one still holding it — this is the rollback.
- mockNodeGatewayClient.getStats.mockResolvedValue({
- byPlatform: { wechat: 1 },
- connections: [
- {
- connectionId: CONNECTION_ID,
- platform: 'wechat',
- state: { status: 'connected' },
- userId: 'u1',
- },
- ],
- total: 1,
- });
+ mockNodeGatewayClient.getStats.mockResolvedValue(createConnectedWechatStats(CONNECTION_ID));
mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });
mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
diff --git a/apps/server/src/services/gateway/index.reconcile.test.ts b/apps/server/src/services/gateway/index.reconcile.test.ts
index 9bc9fb77fc0..01607f5402d 100644
--- a/apps/server/src/services/gateway/index.reconcile.test.ts
+++ b/apps/server/src/services/gateway/index.reconcile.test.ts
@@ -12,6 +12,13 @@ import {
resetGatewayServiceMocks,
} from './testUtils';
+const createConnectedDiscordConnection = () => ({
+ connectionId: 'prov-1',
+ platform: 'discord',
+ state: { status: 'connected' },
+ userId: 'u1',
+});
+
vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));
vi.mock('./MessageGatewayClient', () =>
import('./testUtils').then((m) => m.messageGatewayClientModule()),
@@ -71,12 +78,7 @@ describe('GatewayService', () => {
mockGatewayClient.getStats.mockResolvedValue({
byPlatform: {},
connections: [
- {
- connectionId: 'prov-1',
- platform: 'discord',
- state: { status: 'connected' },
- userId: 'u1',
- },
+ createConnectedDiscordConnection(),
{
connectionId: 'stale-1',
platform: 'wechat',
@@ -317,14 +319,7 @@ describe('GatewayService', () => {
);
mockGatewayClient.getStats.mockResolvedValue({
byPlatform: {},
- connections: [
- {
- connectionId: 'prov-1',
- platform: 'discord',
- state: { status: 'connected' },
- userId: 'u1',
- },
- ],
+ connections: [createConnectedDiscordConnection()],
total: 1,
});
@@ -361,14 +356,7 @@ describe('GatewayService', () => {
);
mockGatewayClient.getStats.mockResolvedValue({
byPlatform: {},
- connections: [
- {
- connectionId: 'prov-1',
- platform: 'discord',
- state: { status: 'connected' },
- userId: 'u1',
- },
- ],
+ connections: [createConnectedDiscordConnection()],
total: 1,
});
diff --git a/apps/server/src/services/gateway/index.sync.test.ts b/apps/server/src/services/gateway/index.sync.test.ts
index 6a7c939d68c..aff28c86eb0 100644
--- a/apps/server/src/services/gateway/index.sync.test.ts
+++ b/apps/server/src/services/gateway/index.sync.test.ts
@@ -39,6 +39,22 @@ vi.mock('@/server/services/messenger/platforms', () =>
);
vi.mock('../bot/platforms', () => import('./testUtils').then((m) => m.botPlatformsModule()));
+const createGatewayProvider = () => ({
+ applicationId: 'app-1',
+ credentials: { token: 'x' },
+ id: 'prov-1',
+ settings: {},
+ userId: 'u1',
+});
+
+const createWechatProvider = (userId: string) => ({
+ applicationId: 'wechat-app',
+ credentials: { botToken: 'token' },
+ id: 'wechat-provider',
+ settings: {},
+ userId,
+});
+
describe('GatewayService', () => {
let service: GatewayService;
@@ -59,15 +75,7 @@ describe('GatewayService', () => {
});
it('skips webhook-mode providers', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
+ mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);
mockResolveConnectionMode.mockReturnValue('webhook');
await service.ensureRunning();
@@ -80,15 +88,7 @@ describe('GatewayService', () => {
// stranded DO (alarm chain lost) looks exactly like this and sleeps
// forever unless woken. The wake is an `ensure` connect, never a status
// probe: parked connections answer 409 and keep their park.
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
+ mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });
mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });
@@ -104,17 +104,7 @@ describe('GatewayService', () => {
it('connects disconnected providers', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'discord'
- ? [
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'discord' ? [createGatewayProvider()] : [],
);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });
@@ -139,17 +129,7 @@ describe('GatewayService', () => {
// `dormant`; it must be mapped through the shared helper so it is not
// collapsed to `starting` (the DO sends no correcting callback).
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'discord'
- ? [
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'discord' ? [createGatewayProvider()] : [],
);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.connect.mockResolvedValue({ status: 'dormant' });
@@ -166,17 +146,7 @@ describe('GatewayService', () => {
it('disconnects paid-only WeChat providers when the owner is on a free plan', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'free-user',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider('free-user')] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
@@ -209,17 +179,7 @@ describe('GatewayService', () => {
'disconnects a paid-gated provider when the registry snapshot is $snapshot',
async ({ statsUnavailable }) => {
mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'free-user',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider('free-user')] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
@@ -239,15 +199,7 @@ describe('GatewayService', () => {
);
it('sets connected status for sync connect result', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
+ mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.connect.mockResolvedValue({ status: 'connected' });
@@ -259,15 +211,7 @@ describe('GatewayService', () => {
});
it('defers desired providers when the gateway snapshot is unavailable', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
+ mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));
mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered-ids unavailable'));
@@ -279,15 +223,7 @@ describe('GatewayService', () => {
});
it('handles connect failure gracefully', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
+ mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);
mockResolveConnectionMode.mockReturnValue('websocket');
mockGatewayClient.connect.mockRejectedValue(new Error('timeout'));
@@ -298,17 +234,7 @@ describe('GatewayService', () => {
it('keeps the connection when the feature gate check itself throws', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'u1',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider('u1')] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockRejectedValue(new Error('subscription service down'));
@@ -327,17 +253,7 @@ describe('GatewayService', () => {
it('does not repeatedly disconnect a gated provider absent from the gateway snapshot', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
- platform === 'wechat'
- ? [
- {
- applicationId: 'wechat-app',
- credentials: { botToken: 'token' },
- id: 'wechat-provider',
- settings: {},
- userId: 'free-user',
- },
- ]
- : [],
+ platform === 'wechat' ? [createWechatProvider('free-user')] : [],
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
diff --git a/apps/server/src/services/generation/index.test.ts b/apps/server/src/services/generation/index.test.ts
index d26acaefa21..3f51113264d 100644
--- a/apps/server/src/services/generation/index.test.ts
+++ b/apps/server/src/services/generation/index.test.ts
@@ -345,17 +345,6 @@ describe('GenerationService', () => {
});
describe('edge cases', () => {
- it('should handle base64 data URI correctly', async () => {
- const base64Data =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAGAWqGfKwAAAABJRU5ErkJggg==';
- const dataUri = `data:image/png;base64,${base64Data}`;
-
- const result = await fetchImageFromUrl(dataUri);
-
- expect(result.mimeType).toBe('image/png');
- expect(result.buffer).toBeInstanceOf(Buffer);
- });
-
it('should throw error for invalid data URI format', async () => {
const invalidDataUri = 'data:image/png:invalid-format';
@@ -394,21 +383,6 @@ describe('GenerationService', () => {
expect(result.buffer).toBeInstanceOf(Buffer);
});
});
-
- describe('return type validation', () => {
- it('should return object with correct structure', async () => {
- const base64Data =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAGAWqGfKwAAAABJRU5ErkJggg==';
- const dataUri = `data:image/png;base64,${base64Data}`;
-
- const result = await fetchImageFromUrl(dataUri);
-
- expect(result).toHaveProperty('buffer');
- expect(result).toHaveProperty('mimeType');
- expect(typeof result.mimeType).toBe('string');
- expect(result.buffer).toBeInstanceOf(Buffer);
- });
- });
});
describe('transformImageForGeneration', () => {
@@ -847,37 +821,6 @@ describe('GenerationService', () => {
expect(mockFileService.uploadMedia).toHaveBeenCalledTimes(1);
});
-
- it('should validate file naming format with correct patterns', async () => {
- mockFileService.uploadMedia
- .mockResolvedValueOnce({
- key: 'generations/images/test-uuid_600x800_20240101123000_raw.png',
- })
- .mockResolvedValueOnce({
- key: 'generations/images/test-uuid_300x400_20240101123000_thumb.png',
- });
-
- await service.uploadImageForGeneration(mockImage, mockThumbnail);
-
- // Verify file name patterns match exact format: {uuid}_{width}x{height}_{timestamp}_{type}.{ext}
- const imageCall = mockFileService.uploadMedia.mock.calls[0];
- const thumbnailCall = mockFileService.uploadMedia.mock.calls[1];
-
- expect(imageCall[0]).toMatch(
- /^generations\/images\/test-uuid_600x800_20240101123000_raw\.png$/,
- );
- expect(thumbnailCall[0]).toMatch(
- /^generations\/images\/test-uuid_300x400_20240101123000_thumb\.png$/,
- );
-
- // Verify dimensions are correctly embedded in filename
- expect(imageCall[0]).toContain('600x800'); // Original dimensions
- expect(thumbnailCall[0]).toContain('300x400'); // Thumbnail dimensions
-
- // Verify file type suffixes
- expect(imageCall[0]).toContain('_raw.');
- expect(thumbnailCall[0]).toContain('_thumb.');
- });
});
describe('createCoverFromUrl', () => {
diff --git a/apps/server/src/services/generation/videoBackgroundPolling.test.ts b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
index 876a133d63c..dc5c37c2d08 100644
--- a/apps/server/src/services/generation/videoBackgroundPolling.test.ts
+++ b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
@@ -49,6 +49,28 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
initModelRuntimeFromDB: vi.fn(),
}));
+const createSuccessfulPollResult = () => ({
+ status: 'success',
+ videoUrl: 'https://example.com/video.mp4',
+});
+
+const createFailedPollResult = () => ({
+ status: 'failed',
+ error: 'Model API error',
+});
+
+const createProcessedVideoResult = () => ({
+ coverKey: 'cover-key',
+ duration: 10,
+ fileHash: 'hash',
+ fileSize: 1024,
+ height: 1080,
+ mimeType: 'video/mp4',
+ thumbnailKey: 'thumb-key',
+ videoKey: 'video-key',
+ width: 1920,
+});
+
describe('videoBackgroundPolling', () => {
const mockAsyncTaskModel = {
update: vi.fn(),
@@ -209,10 +231,7 @@ describe('videoBackgroundPolling', () => {
vi.mocked(resolveBusinessModelMapping)
.mockResolvedValueOnce({ resolvedModelId: 'bytedance/seedance-2.5' } as any)
.mockResolvedValueOnce({ resolvedModelId: 'bytedance/seedance-2.5' } as any);
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
mockVideoService.processVideoForGeneration.mockResolvedValue({
coverKey: 'cover-key',
duration: 4.04,
@@ -242,10 +261,7 @@ describe('videoBackgroundPolling', () => {
vi.mocked(resolveBusinessModelMapping).mockResolvedValueOnce({
resolvedModelId: 'mapped-model',
} as any);
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'failed',
- error: 'Model API error',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createFailedPollResult());
const route = { apiType: 'google', channelId: 'channel-1', routerId: 'router-1' };
await processBackgroundVideoPolling(mockDb, { ...mockParams, route });
@@ -258,10 +274,7 @@ describe('videoBackgroundPolling', () => {
});
it('should keep spend origin and workspace context on completion', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
const spendOrigin = { trigger: 'agent-share' };
await processBackgroundVideoPolling(mockDb, {
@@ -282,10 +295,7 @@ describe('videoBackgroundPolling', () => {
});
it('should keep spend origin on the failure refund', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'failed',
- error: 'Model API error',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createFailedPollResult());
await processBackgroundVideoPolling(mockDb, {
...mockParams,
@@ -301,10 +311,7 @@ describe('videoBackgroundPolling', () => {
});
it('should skip a polling result already claimed by a webhook', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
vi.mocked(AsyncTaskModel.claimVideoCompletion).mockResolvedValueOnce(false);
await processBackgroundVideoPolling(mockDb, mockParams);
@@ -319,17 +326,7 @@ describe('videoBackgroundPolling', () => {
status: 'success',
videoUrl: 'data:video/mp4;base64,inline-video',
});
- mockVideoService.processVideoForGeneration.mockResolvedValue({
- coverKey: 'cover-key',
- duration: 10,
- fileHash: 'hash',
- fileSize: 1024,
- height: 1080,
- mimeType: 'video/mp4',
- thumbnailKey: 'thumb-key',
- videoKey: 'video-key',
- width: 1920,
- });
+ mockVideoService.processVideoForGeneration.mockResolvedValue(createProcessedVideoResult());
await processBackgroundVideoPolling(mockDb, mockParams);
@@ -347,22 +344,9 @@ describe('videoBackgroundPolling', () => {
mockModelRuntime.handlePollVideoStatus
.mockResolvedValueOnce({ status: 'processing' })
.mockResolvedValueOnce({ status: 'processing' })
- .mockResolvedValueOnce({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ .mockResolvedValueOnce(createSuccessfulPollResult());
- mockVideoService.processVideoForGeneration.mockResolvedValue({
- coverKey: 'cover-key',
- duration: 10,
- fileHash: 'hash',
- fileSize: 1024,
- height: 1080,
- mimeType: 'video/mp4',
- thumbnailKey: 'thumb-key',
- videoKey: 'video-key',
- width: 1920,
- });
+ mockVideoService.processVideoForGeneration.mockResolvedValue(createProcessedVideoResult());
const pollPromise = processBackgroundVideoPolling(mockDb, mockParams);
@@ -376,10 +360,7 @@ describe('videoBackgroundPolling', () => {
describe('processBackgroundVideoPolling - error handling', () => {
it('should handle polling failure with error message', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'failed',
- error: 'Model API error',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createFailedPollResult());
await processBackgroundVideoPolling(mockDb, mockParams);
@@ -405,10 +386,7 @@ describe('videoBackgroundPolling', () => {
});
it('should handle video processing error', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
mockVideoService.processVideoForGeneration.mockRejectedValue(
new Error('Video processing failed'),
@@ -423,22 +401,9 @@ describe('videoBackgroundPolling', () => {
});
it('should handle asset creation error', async () => {
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
- mockVideoService.processVideoForGeneration.mockResolvedValue({
- coverKey: 'cover-key',
- duration: 10,
- fileHash: 'hash',
- fileSize: 1024,
- height: 1080,
- mimeType: 'video/mp4',
- thumbnailKey: 'thumb-key',
- videoKey: 'video-key',
- width: 1920,
- });
+ mockVideoService.processVideoForGeneration.mockResolvedValue(createProcessedVideoResult());
mockGenerationModel.createAssetAndFile.mockRejectedValue(new Error('DB error'));
@@ -456,22 +421,9 @@ describe('videoBackgroundPolling', () => {
mockModelRuntime.handlePollVideoStatus
.mockRejectedValueOnce(new Error('Network error'))
.mockResolvedValueOnce({ status: 'processing' })
- .mockResolvedValueOnce({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ .mockResolvedValueOnce(createSuccessfulPollResult());
- mockVideoService.processVideoForGeneration.mockResolvedValue({
- coverKey: 'cover-key',
- duration: 10,
- fileHash: 'hash',
- fileSize: 1024,
- height: 1080,
- mimeType: 'video/mp4',
- thumbnailKey: 'thumb-key',
- videoKey: 'video-key',
- width: 1920,
- });
+ mockVideoService.processVideoForGeneration.mockResolvedValue(createProcessedVideoResult());
mockGenerationModel.createAssetAndFile.mockResolvedValue(undefined);
@@ -492,22 +444,9 @@ describe('videoBackgroundPolling', () => {
const startTime = new Date('2024-01-01T00:00:00Z');
const endTime = new Date('2024-01-01T00:05:00Z');
- mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
- status: 'success',
- videoUrl: 'https://example.com/video.mp4',
- });
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue(createSuccessfulPollResult());
- mockVideoService.processVideoForGeneration.mockResolvedValue({
- coverKey: 'cover-key',
- duration: 10,
- fileHash: 'hash',
- fileSize: 1024,
- height: 1080,
- mimeType: 'video/mp4',
- thumbnailKey: 'thumb-key',
- videoKey: 'video-key',
- width: 1920,
- });
+ mockVideoService.processVideoForGeneration.mockResolvedValue(createProcessedVideoResult());
mockGenerationModel.createAssetAndFile.mockResolvedValue(undefined);
diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts
index 2ff7d4c4b2f..4c679fb2015 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts
@@ -14,7 +14,7 @@ import { TaskRunnerService } from '../../../taskRunner';
import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';
import { VERIFICATION_FAILED_ERROR } from '../../decideNextMove';
import { uncoveredAxisValues } from '../../spec';
-import { registerGoalServiceTestCleanup } from '../../testUtils';
+import { createBatchDecomposition, registerGoalServiceTestCleanup } from '../../testUtils';
import { GoalService } from '../index';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -316,21 +316,9 @@ describe('GoalService', () => {
});
it('routes a batch unit out of verification retries through the batch gate', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
const service = new GoalService(serverDB, userId);
const graph = await service.create({
@@ -368,21 +356,9 @@ describe('GoalService', () => {
// A sleeping laptop is not the recipe's fault. Routed to the batch gate first,
// one device the probe could not reach paused the whole rollout and asked the
// owner to revise or fork the recipe.
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const runSpy = vi
.spyOn(TaskRunnerService.prototype, 'runTask')
.mockRejectedValueOnce(new Error('DEVICE_NOT_FOUND'))
@@ -408,21 +384,9 @@ describe('GoalService', () => {
});
it('stops the running Tasks of the members a restart retires', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
index 443ff6c49dc..9134fc6e0c3 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
@@ -14,7 +14,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { TaskRunnerService } from '../../../taskRunner';
import { UserSkillService } from '../../../userSkill';
import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';
-import { registerGoalServiceTestCleanup } from '../../testUtils';
+import { createBatchDecomposition, registerGoalServiceTestCleanup } from '../../testUtils';
import { GoalService } from '../index';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -24,21 +24,9 @@ registerGoalServiceTestCleanup(serverDB, userId);
describe('GoalService', () => {
it('re-opens the broken unit as a new task when the canary loop restarts', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -151,21 +139,9 @@ describe('GoalService', () => {
});
it('falls back to copying the revised plan when the skill revision does not land', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -199,21 +175,9 @@ describe('GoalService', () => {
});
it('mounts what a break taught on the agent that runs the units, even in a project', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
await serverDB.insert(agents).values([{ id: 'agt_batch', slug: 'agt-batch', userId }]);
await serverDB.insert(projects).values({
coordinatorAgentId: 'agt_batch',
@@ -252,21 +216,9 @@ describe('GoalService', () => {
});
it('learns into one shared domain per agent, through the executor fallback', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
await serverDB.insert(agents).values([
{ id: 'agt_goal_main', slug: 'agt-goal-main', userId },
{ id: 'agt_gone_exec', slug: 'agt-gone-exec', userId },
@@ -325,21 +277,9 @@ describe('GoalService', () => {
});
it('creates one batch domain when two goals on an agent learn at the same time', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
await serverDB.insert(agents).values([{ id: 'agt_shared', slug: 'agt-shared', userId }]);
const service = new GoalService(serverDB, userId);
const graphModel = new GoalGraphModel(serverDB, userId);
@@ -376,21 +316,9 @@ describe('GoalService', () => {
});
it('moves a batch from before plan skills into one at its next revision', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
diff --git a/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts b/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts
index 03f2f7f390a..392d7a1e246 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts
@@ -21,6 +21,27 @@ import { TaskRecoveryCoordinator } from '../../taskRecoveryCoordinator';
import { registerGoalServiceTestCleanup } from '../../testUtils';
import { GoalService } from '../index';
+const deliveredTopic = (taskId: string, userId: string): typeof taskTopics.$inferInsert => ({
+ handoff: { summary: 'Delivered', title: 'Delivered title' },
+ operationId: 'op-delivered',
+ seq: 1,
+ status: 'completed',
+ taskId,
+ userId,
+});
+
+const sharedBacklog = (userId: string): typeof documents.$inferInsert => ({
+ content: 'Shared backlog body',
+ fileType: 'markdown',
+ filename: 'Shared backlog',
+ source: 'notebook',
+ sourceType: 'api',
+ title: 'Shared backlog',
+ totalCharCount: 19,
+ totalLineCount: 1,
+ userId,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'goal-service-test-user';
@@ -412,14 +433,7 @@ describe('GoalService', () => {
const workModel = new WorkModel(serverDB, userId);
const graph = await service.create({ tasks: ['Deliver me'], title: 'Harvest deliverables' });
const created = await service.tick(graph.goal.id);
- await serverDB.insert(taskTopics).values({
- handoff: { summary: 'Delivered', title: 'Delivered title' },
- operationId: 'op-delivered',
- seq: 1,
- status: 'completed',
- taskId: created.taskId!,
- userId,
- });
+ await serverDB.insert(taskTopics).values(deliveredTopic(created.taskId!, userId));
await workModel.registerExternal({
changeType: 'created',
identifier: 'ENG-7',
@@ -448,14 +462,7 @@ describe('GoalService', () => {
const workModel = new WorkModel(serverDB, userId);
const graph = await service.create({ tasks: ['Deliver me'], title: 'Idempotent harvest' });
const created = await service.tick(graph.goal.id);
- await serverDB.insert(taskTopics).values({
- handoff: { summary: 'Delivered', title: 'Delivered title' },
- operationId: 'op-delivered',
- seq: 1,
- status: 'completed',
- taskId: created.taskId!,
- userId,
- });
+ await serverDB.insert(taskTopics).values(deliveredTopic(created.taskId!, userId));
await workModel.registerExternal({
changeType: 'created',
resourceId: 'lobehub/lobehub#8',
@@ -498,20 +505,7 @@ describe('GoalService', () => {
title: 'Revisions are not deliveries',
});
const created = await service.tick(graph.goal.id);
- const [backlog] = await serverDB
- .insert(documents)
- .values({
- content: 'Shared backlog body',
- fileType: 'markdown',
- filename: 'Shared backlog',
- source: 'notebook',
- sourceType: 'api',
- title: 'Shared backlog',
- totalCharCount: 19,
- totalLineCount: 1,
- userId,
- })
- .returning();
+ const [backlog] = await serverDB.insert(documents).values(sharedBacklog(userId)).returning();
// Written by an earlier task's run; this task only appends to it.
await workModel.registerDocument({
changeType: 'created',
@@ -520,14 +514,7 @@ describe('GoalService', () => {
toolIdentifier: 'lobehub-notebook',
toolName: 'createDocument',
});
- await serverDB.insert(taskTopics).values({
- handoff: { summary: 'Delivered', title: 'Delivered title' },
- operationId: 'op-delivered',
- seq: 1,
- status: 'completed',
- taskId: created.taskId!,
- userId,
- });
+ await serverDB.insert(taskTopics).values(deliveredTopic(created.taskId!, userId));
await workModel.registerDocument({
changeType: 'updated',
documentId: backlog.id,
@@ -558,20 +545,7 @@ describe('GoalService', () => {
tasks: ['First delivery', 'Second delivery'],
title: 'One claim per deliverable',
});
- const [backlog] = await serverDB
- .insert(documents)
- .values({
- content: 'Shared backlog body',
- fileType: 'markdown',
- filename: 'Shared backlog',
- source: 'notebook',
- sourceType: 'api',
- title: 'Shared backlog',
- totalCharCount: 19,
- totalLineCount: 1,
- userId,
- })
- .returning();
+ const [backlog] = await serverDB.insert(documents).values(sharedBacklog(userId)).returning();
const first = await service.tick(graph.goal.id);
await serverDB.insert(taskTopics).values({
diff --git a/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts b/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts
index 0a3868fd020..d55bced323b 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts
@@ -11,7 +11,11 @@ import type { LobeChatDatabase } from '@/database/type';
import { UserSkillService } from '../../../userSkill';
import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';
-import { approveRelease, registerGoalServiceTestCleanup } from '../../testUtils';
+import {
+ approveRelease,
+ createBatchDecomposition,
+ registerGoalServiceTestCleanup,
+} from '../../testUtils';
import { GoalService } from '../index';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -113,21 +117,9 @@ describe('GoalService', () => {
});
it('numbers a release after the waves a batch released before the counter existed', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -153,21 +145,9 @@ describe('GoalService', () => {
});
it('numbers a release after the waves a batch released before the counter existed, across a restart', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -196,21 +176,9 @@ describe('GoalService', () => {
});
it('records each gate verdict — the release and the hold — with what it checked', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -252,21 +220,9 @@ describe('GoalService', () => {
});
it('restarts the canary loop when a person answers a broken batch gate', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({ title: 'Migrate stores' });
await service.tick(graph.goal.id);
@@ -318,21 +274,9 @@ describe('GoalService', () => {
});
it('materializes and answers a pattern-break gate on a full rollout', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({
config: { rollout: { trigger: 'full' } },
@@ -381,21 +325,9 @@ describe('GoalService', () => {
});
it('opens one gate when two advances see a full rollout break together', async () => {
- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
- problemStatement: '把 50 个同构的 store 迁移到 replica',
- rollout: {
- recipeOutline: '把 store 换成 replica 支撑的实现',
- repeatable: true,
- unitCount: 50,
- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
- variants: [],
- },
- tasks: Array.from({ length: 5 }, (_, i) => ({
- dependsOn: [],
- instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
- title: `Unit ${i + 1}`,
- })),
- });
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue(
+ createBatchDecomposition(),
+ );
const service = new GoalService(serverDB, userId);
const graph = await service.create({
config: { rollout: { trigger: 'full' } },
diff --git a/apps/server/src/services/goal/report.test.ts b/apps/server/src/services/goal/report.test.ts
index aa70f80cd4c..a3a490dd00f 100644
--- a/apps/server/src/services/goal/report.test.ts
+++ b/apps/server/src/services/goal/report.test.ts
@@ -21,6 +21,25 @@ import {
validateGoalReport,
} from './report';
+const acceptanceChapter = (): GoalReportMetadata['chapters'][number] => ({
+ detours: [],
+ findingIds: [],
+ narrative: 'N',
+ nodeIds: ['acc'],
+ title: 'C2',
+ workVersionIds: [],
+});
+
+const submitTool = (): Parameters<typeof buildGoalReportInstruction>[2] => ({
+ kind: 'tool',
+ toolName: 'lobe-goal-report.submitGoalReport',
+});
+
+const mainlineInput = (): GoalReportMetadata['mainline'] => ({
+ edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
+ nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
+});
+
const node = (id: string, overrides: Partial<GoalGraphNode> = {}): GoalGraphNode =>
({
createdAt: new Date(1000),
@@ -377,10 +396,7 @@ describe('buildGoalReportSkeleton', () => {
});
it('asks for chapters, detour reasons and lessons, next steps and a submission', () => {
- const text = buildGoalReportInstruction(snapshot, 'accepted', {
- kind: 'tool',
- toolName: 'lobe-goal-report.submitGoalReport',
- });
+ const text = buildGoalReportInstruction(snapshot, 'accepted', submitTool());
expect(text).toContain('Candidate main path');
expect(text).toContain('t1b [task, resolved] t1b · superseded by t2 (revises) · fork: t2');
expect(text).toContain('Goal-level acceptance passed');
@@ -402,10 +418,7 @@ describe('buildGoalReportSkeleton', () => {
* skeleton found candidate detours, the contract must make one mandatory.
*/
it('requires at least one detour when the skeleton offers candidate detours', () => {
- const text = buildGoalReportInstruction(snapshot, 'accepted', {
- kind: 'tool',
- toolName: 'lobe-goal-report.submitGoalReport',
- });
+ const text = buildGoalReportInstruction(snapshot, 'accepted', submitTool());
expect(text).toContain('2 candidate detour');
expect(text).toContain('at least one MUST appear in your report');
expect(text).toContain('at least ONE of these must be told as a detour');
@@ -423,10 +436,7 @@ describe('buildGoalReportSkeleton', () => {
],
}),
);
- const text = buildGoalReportInstruction(noDetours, 'accepted', {
- kind: 'tool',
- toolName: 'lobe-goal-report.submitGoalReport',
- });
+ const text = buildGoalReportInstruction(noDetours, 'accepted', submitTool());
expect(text).not.toContain('MUST appear in your report');
expect(text).toContain('- none');
});
@@ -446,10 +456,7 @@ describe('buildGoalReportSkeleton', () => {
});
it('asks for the report as one self-contained HTML page and submits it with the markdown', () => {
- const tool = buildGoalReportInstruction(snapshot, 'accepted', {
- kind: 'tool',
- toolName: 'lobe-goal-report.submitGoalReport',
- });
+ const tool = buildGoalReportInstruction(snapshot, 'accepted', submitTool());
expect(tool).toContain('ONE HTML page');
expect(tool).toContain('The page MUST be self-contained');
expect(tool).toContain('all CSS in <style> and all JS in <script>');
@@ -475,22 +482,12 @@ describe('buildGoalReportSkeleton', () => {
title: 'C1',
workVersionIds: ['wv_doc'],
},
- {
- detours: [],
- findingIds: [],
- narrative: 'N',
- nodeIds: ['acc'],
- title: 'C2',
- workVersionIds: [],
- },
+ acceptanceChapter(),
],
deliverableWorkId: 'work_doc',
graphCursor: 'evt_new',
headline: 'H',
- mainline: {
- edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
- nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
- },
+ mainline: mainlineInput(),
nextSteps: [{ nodeIds: ['t2'], reason: 'R', title: 'Next' }],
};
@@ -675,22 +672,12 @@ describe('buildGoalReportSkeleton', () => {
title: 'C1',
workVersionIds: ['wv_doc'],
},
- {
- detours: [],
- findingIds: [],
- narrative: 'N',
- nodeIds: ['acc'],
- title: 'C2',
- workVersionIds: [],
- },
+ acceptanceChapter(),
],
deliverableWorkId: 'work_doc',
graphCursor: 'evt_new',
headline: 'H',
- mainline: {
- edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
- nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
- },
+ mainline: mainlineInput(),
nextSteps: [{ nodeIds: ['t2'], reason: 'R', title: 'Next' }],
};
@@ -848,10 +835,7 @@ describe('buildGoalReportSkeleton', () => {
workVersionIds: [],
},
],
- mainline: {
- edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
- nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
- },
+ mainline: mainlineInput(),
};
const aligned = alignGoalReportStoryline(snapshot, messy);
@@ -879,22 +863,12 @@ describe('buildGoalReportSkeleton', () => {
title: 'C1',
workVersionIds: ['wv_doc'],
},
- {
- detours: [],
- findingIds: [],
- narrative: 'N',
- nodeIds: ['acc'],
- title: 'C2',
- workVersionIds: [],
- },
+ acceptanceChapter(),
],
deliverableWorkId: 'work_doc',
graphCursor: 'evt_new',
headline: 'H',
- mainline: {
- edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
- nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
- },
+ mainline: mainlineInput(),
nextSteps: [],
};
expect(alignGoalReportStoryline(snapshot, detached)).toEqual(detached);
diff --git a/apps/server/src/services/goal/testUtils.ts b/apps/server/src/services/goal/testUtils.ts
index 56e0dc93acc..ae9979c6f42 100644
--- a/apps/server/src/services/goal/testUtils.ts
+++ b/apps/server/src/services/goal/testUtils.ts
@@ -25,6 +25,23 @@ import type { LobeChatDatabase } from '@/database/type';
import type { GoalService } from './index';
import { GoalManagerService } from './manager';
+/** Fresh planner response for the standard 50-unit, five-probe batch scenarios. */
+export const createBatchDecomposition = () => ({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+});
+
/** Seed the test user before each test and clear everything a goal test writes after it. */
export const registerGoalServiceTestCleanup = (serverDB: LobeChatDatabase, userId: string) => {
beforeEach(async () => {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index 99995ac594e..6e80a5806eb 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -12,6 +12,31 @@ const createSilentStreamManager = (): IStreamEventManager =>
publishStreamEvent: vi.fn(async () => 'ok'),
}) as unknown as IStreamEventManager;
+const createPersistenceHandler = (
+ findById: ReturnType<typeof vi.fn>,
+ updateMetadata: ReturnType<typeof vi.fn>,
+) =>
+ new HeterogeneousPersistenceHandler({
+ messageModel: {
+ findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
+ threadModel: {} as any,
+ topicModel: { findById, updateMetadata } as any,
+ });
+
+const createFinishTopicModel = (
+ findById: ReturnType<typeof vi.fn>,
+ updateMetadata: ReturnType<typeof vi.fn>,
+) => ({
+ findById,
+ settleRunningStatus: vi.fn(async () => undefined),
+ takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
+});
+
describe('HeterogeneousAgentService — phase 2c session id persistence + resume', () => {
beforeEach(() => {
__resetOperationStatesForTesting();
@@ -37,16 +62,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
}));
// Real handler so we exercise the persistSessionId path end-to-end
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
// Seed in-memory state by ingesting one event so finish has something to drain
await handler.ingest({
@@ -66,12 +82,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
await service.heteroFinish({
@@ -100,16 +111,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
{
@@ -127,12 +129,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
await service.heteroFinish({
@@ -157,16 +154,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
@@ -185,12 +173,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
// Simulate: sandbox was recycled, CC exited before emitting system.init
@@ -228,16 +211,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
runningOperation: { assistantMessageId: 'asst-busy', operationId: 'op-busy' },
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
{
@@ -287,16 +261,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
{
@@ -314,12 +279,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
await service.heteroFinish({
@@ -353,16 +313,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
{
@@ -380,12 +331,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: createSilentStreamManager(),
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
await service.heteroFinish({
@@ -422,16 +368,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
{
@@ -450,12 +387,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const service = new HeterogeneousAgentService({} as any, 'user-1', {
persistenceHandler: handler,
streamEventManager: stream,
- topicModel: {
- findById,
- settleRunningStatus: vi.fn(async () => undefined),
- takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
- updateMetadata,
- } as any,
+ topicModel: createFinishTopicModel(findById, updateMetadata) as any,
});
// Should not throw — sessionId persistence is best-effort
@@ -485,16 +417,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
},
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
// Only a stream_start reporting the CC session id — NO heteroFinish. This
// is the inactivity-watchdog path: the run starts, emits its session id,
@@ -527,16 +450,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
metadata: { runningOperation: { assistantMessageId: 'asst-d', operationId: 'op-dedupe' } },
}));
- const handler = new HeterogeneousPersistenceHandler({
- messageModel: {
- findById: vi.fn(async () => null),
- getLatestSpineMessageId: vi.fn(async () => null),
- listMessagePluginsByTopic: vi.fn(async () => []),
- update: vi.fn(async () => ({ success: true })),
- } as any,
- threadModel: {} as any,
- topicModel: { findById, updateMetadata } as any,
- });
+ const handler = createPersistenceHandler(findById, updateMetadata);
await handler.ingest({
events: [
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts
index 287637a5f90..8f9a2ede3ba 100644
--- a/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts
+++ b/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts
@@ -73,6 +73,21 @@ afterEach(() => {
vi.clearAllMocks();
});
+const createPersonalSlackLink = (activeAgentId: string) => ({
+ activeAgentId,
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+});
+
+const createStatefulSlackDmThread = <T>(state: T) => ({
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve(state),
+});
+
describe('MessengerRouter slash command dispatch', () => {
// `/agents` reads the user's agents from the live database via
// `fetchUserAgents` — stub that on the prototype so we don't have to
@@ -169,13 +184,7 @@ describe('MessengerRouter slash command dispatch', () => {
it('renders the picker as ephemeral when /agents is invoked from a public channel', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_a'));
// `onSlashCommand(paths, handler)` — second arg is the handler.
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -193,13 +202,7 @@ describe('MessengerRouter slash command dispatch', () => {
// handleSlashCommand for the workaround). The DM here is detected
// via the Slack channel-id prefix (`D...`).
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
mockOpenDM.mockResolvedValue(dmThread);
@@ -228,13 +231,7 @@ describe('MessengerRouter slash command dispatch', () => {
// conversation (the DM) instead of dropping the request. The
// confirmation is ephemeral so the channel doesn't see it.
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
mockOpenDM.mockResolvedValue(dmThread);
@@ -247,19 +244,8 @@ describe('MessengerRouter slash command dispatch', () => {
it('/mode chat writes the DM thread state and confirms', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
+ const dmThread = createStatefulSlackDmThread(null);
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -282,19 +268,8 @@ describe('MessengerRouter slash command dispatch', () => {
it('/mode without args renders the tap picker with the current mode marked', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve({ toolMode: 'agent', topicId: 'topic-1' }),
- };
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
+ const dmThread = createStatefulSlackDmThread({ toolMode: 'agent', topicId: 'topic-1' });
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -315,22 +290,11 @@ describe('MessengerRouter slash command dispatch', () => {
it('/mode without args marks the agent-config default when no override is set', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
// Active agent configured as chat-mode (enableAgentMode=false) — the
// picker must mark Chat Mode even though the thread has no override yet.
mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: false } });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
+ const dmThread = createStatefulSlackDmThread(null);
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -372,12 +336,7 @@ describe('MessengerRouter slash command dispatch', () => {
agentModeOverrides: { agt_main: false },
});
mockIsResourceAuthorOrAdmin.mockResolvedValue(false);
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
+ const dmThread = createStatefulSlackDmThread(null);
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -417,12 +376,7 @@ describe('MessengerRouter slash command dispatch', () => {
agentModeOverrides: { agt_main: false },
});
mockIsResourceAuthorOrAdmin.mockResolvedValue(true);
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
+ const dmThread = createStatefulSlackDmThread(null);
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -446,13 +400,7 @@ describe('MessengerRouter slash command dispatch', () => {
// next run would still read its own state. So no picker here: text
// status via the ephemeral reply instead.
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: true } });
const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
@@ -474,13 +422,7 @@ describe('MessengerRouter slash command dispatch', () => {
it('mode picker tap writes toolMode to the DM thread and re-renders the picker', async () => {
const router = new MessengerRouter();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
const chatBot = { openDM: vi.fn().mockResolvedValue(dmThread) };
const acknowledgeCallback = vi.fn();
@@ -547,19 +489,8 @@ describe('MessengerRouter slash command dispatch', () => {
it('/new slash preserves the /mode choice while clearing topicId', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve({ toolMode: 'chat', topicId: 'topic-1' }),
- };
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_main'));
+ const dmThread = createStatefulSlackDmThread({ toolMode: 'chat', topicId: 'topic-1' });
mockOpenDM.mockResolvedValue(dmThread);
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
@@ -573,13 +504,7 @@ describe('MessengerRouter slash command dispatch', () => {
it('renders the picker as a regular DM message when /agents is invoked from a DM', async () => {
await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
+ mockFindLink.mockResolvedValue(createPersonalSlackLink('agt_a'));
const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: true } }));
diff --git a/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts
index 62f149bf1da..1eb95c9c3bb 100644
--- a/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts
@@ -86,14 +86,9 @@ describe('RoomPageSessions character limit', () => {
expect(pushUpdate).toHaveBeenCalledTimes(1);
});
- it('exempts a system writer', async () => {
+ it('commits a system writer and preserves its persistence source', async () => {
await expect(commitWith('system', 5, 500)).resolves.toBe(true);
expect(pushUpdate).toHaveBeenCalledTimes(1);
- });
-
- it('persists under the writer source, so a system write is not refused by the projection', async () => {
- await commitWith('system', 5, 500);
-
expect(vi.mocked(persistPageState).mock.calls[0][3]).toMatchObject({ writeSource: 'system' });
});
});
diff --git a/apps/server/src/services/search/index.test.ts b/apps/server/src/services/search/index.test.ts
index 8a359847bdb..82753caa31f 100644
--- a/apps/server/src/services/search/index.test.ts
+++ b/apps/server/src/services/search/index.test.ts
@@ -6,6 +6,36 @@ import { toolsEnv } from '@/envs/tools';
import { createSearchServiceImpl, SearchImplType } from './impls';
import { DEFAULT_CRAWLER_IMPLS, resolveOrderedChannels, SearchService } from './index';
+const searchResultRows = () => [
+ {
+ category: 'general',
+ content: 'Result 1',
+ engines: ['google'],
+ parsedUrl: 'https://example.com',
+ score: 1,
+ title: 'Test 1',
+ url: 'https://example.com',
+ },
+];
+
+const emptySearchResponse = () => ({
+ costTime: 100,
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+});
+
+const engineSearchInput = () => ({
+ query: 'test',
+ searchEngines: ['google'],
+});
+
+const crawlResult = (crawler: string, content: string) => ({
+ crawler,
+ data: { content, contentType: 'text' },
+ originalUrl: 'https://example.com',
+});
+
// Mock dependencies
vi.mock('@lobechat/web-crawler');
vi.mock('./impls');
@@ -135,17 +165,7 @@ describe('SearchService', () => {
costTime: 100,
query: 'test',
resultNumbers: 2,
- results: [
- {
- category: 'general',
- content: 'Result 1',
- engines: ['google'],
- parsedUrl: 'https://example.com',
- score: 1,
- title: 'Test 1',
- url: 'https://example.com',
- },
- ],
+ results: searchResultRows(),
};
mockSearchImpl.query.mockResolvedValue(mockResponse);
@@ -160,27 +180,12 @@ describe('SearchService', () => {
});
it('should retry without searchEngines when no results found', async () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
const successResponse = {
costTime: 100,
query: 'test',
resultNumbers: 1,
- results: [
- {
- category: 'general',
- content: 'Result 1',
- engines: ['google'],
- parsedUrl: 'https://example.com',
- score: 1,
- title: 'Test 1',
- url: 'https://example.com',
- },
- ],
+ results: searchResultRows(),
};
mockSearchImpl.query
@@ -208,27 +213,12 @@ describe('SearchService', () => {
});
it('should retry without any params when still no results found', async () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
const successResponse = {
costTime: 100,
query: 'test',
resultNumbers: 1,
- results: [
- {
- category: 'general',
- content: 'Result 1',
- engines: ['google'],
- parsedUrl: 'https://example.com',
- score: 1,
- title: 'Test 1',
- url: 'https://example.com',
- },
- ],
+ results: searchResultRows(),
};
mockSearchImpl.query
@@ -249,27 +239,12 @@ describe('SearchService', () => {
});
it('should skip second retry if searchEngines not provided', async () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
const successResponse = {
costTime: 100,
query: 'test',
resultNumbers: 1,
- results: [
- {
- category: 'general',
- content: 'Result 1',
- engines: ['google'],
- parsedUrl: 'https://example.com',
- score: 1,
- title: 'Test 1',
- url: 'https://example.com',
- },
- ],
+ results: searchResultRows(),
};
mockSearchImpl.query
@@ -290,12 +265,7 @@ describe('SearchService', () => {
});
it('should not retry the same unrestricted query', async () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
vi.mocked(toolsEnv).SEARCH_PROVIDERS = '';
searchService = new SearchService();
@@ -338,19 +308,11 @@ describe('SearchService', () => {
});
it('should return the successful empty response after all retries find no results', async () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
mockSearchImpl.query.mockResolvedValue(emptyResponse);
- const result = await searchService.webSearch({
- query: 'test',
- searchEngines: ['google'],
- });
+ const result = await searchService.webSearch(engineSearchInput());
expect(mockSearchImpl.query).toHaveBeenCalledTimes(2);
expect(result).toBe(emptyResponse);
@@ -359,12 +321,7 @@ describe('SearchService', () => {
});
describe('webSearch - provider fallback (turn mode)', () => {
- const emptyResponse = {
- costTime: 100,
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ const emptyResponse = emptySearchResponse();
const successResponse = {
costTime: 200,
query: 'test',
@@ -452,10 +409,7 @@ describe('SearchService', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
searchService = new SearchService();
- const result = await searchService.webSearch({
- query: 'test',
- searchEngines: ['google'],
- });
+ const result = await searchService.webSearch(engineSearchInput());
// First provider: full params -> without engines = 2 calls
expect(mockImpl1.query).toHaveBeenCalledTimes(2);
@@ -474,10 +428,7 @@ describe('SearchService', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
searchService = new SearchService();
- const result = await searchService.webSearch({
- query: 'test',
- searchEngines: ['google'],
- });
+ const result = await searchService.webSearch(engineSearchInput());
expect(mockImpl1.query).toHaveBeenCalledTimes(1);
expect(mockImpl2.query).toHaveBeenCalledTimes(1);
@@ -518,10 +469,7 @@ describe('SearchService', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
searchService = new SearchService();
- const result = await searchService.webSearch({
- query: 'test',
- searchEngines: ['google'],
- });
+ const result = await searchService.webSearch(engineSearchInput());
expect(mockImpl1.query).toHaveBeenCalledTimes(1);
expect(mockImpl2.query).toHaveBeenCalledTimes(1);
@@ -539,11 +487,7 @@ describe('SearchService', () => {
describe('crawlPages', () => {
it('should crawl multiple pages concurrently', async () => {
- const mockCrawlResult = {
- crawler: 'naive',
- data: { content: 'Page content', contentType: 'text' },
- originalUrl: 'https://example.com',
- };
+ const mockCrawlResult = crawlResult('naive', 'Page content');
const mockCrawler = {
crawl: vi.fn().mockResolvedValue(mockCrawlResult),
@@ -566,11 +510,7 @@ describe('SearchService', () => {
it('should use crawler implementations from env', async () => {
vi.mocked(toolsEnv).CRAWLER_IMPLS = 'jina,reader';
- const mockSuccessResult = {
- crawler: 'jina',
- data: { content: 'ok', contentType: 'text' },
- originalUrl: 'https://example.com',
- };
+ const mockSuccessResult = crawlResult('jina', 'ok');
const mockCrawler = {
crawl: vi.fn().mockResolvedValue(mockSuccessResult),
};
@@ -586,11 +526,7 @@ describe('SearchService', () => {
});
it('should pass impls parameter to crawler.crawl', async () => {
- const mockSuccessResult = {
- crawler: 'jina',
- data: { content: 'ok', contentType: 'text' },
- originalUrl: 'https://example.com',
- };
+ const mockSuccessResult = crawlResult('jina', 'ok');
const mockCrawler = {
crawl: vi.fn().mockResolvedValue(mockSuccessResult),
};
@@ -641,11 +577,7 @@ describe('SearchService', () => {
data: { content: 'Fail', errorType: 'NetworkError', errorMessage: 'timeout' },
originalUrl: 'https://example.com',
};
- const successResult = {
- crawler: 'naive',
- data: { content: 'Page content', contentType: 'text' },
- originalUrl: 'https://example.com',
- };
+ const successResult = crawlResult('naive', 'Page content');
const mockCrawler = {
crawl: vi.fn().mockResolvedValueOnce(failedResult).mockResolvedValueOnce(successResult),
@@ -758,11 +690,7 @@ describe('SearchService', () => {
it('should detect successful results by contentType presence', async () => {
vi.mocked(toolsEnv).CRAWLER_RETRY = 1;
- const successResult = {
- crawler: 'naive',
- data: { content: 'Page content', contentType: 'text' },
- originalUrl: 'https://example.com',
- };
+ const successResult = crawlResult('naive', 'Page content');
const mockCrawler = {
crawl: vi.fn().mockResolvedValue(successResult),
@@ -875,11 +803,7 @@ describe('SearchService', () => {
describe('user channel preferences - crawler impls', () => {
const mockCrawler = () => {
const crawler = {
- crawl: vi.fn().mockResolvedValue({
- crawler: 'jina',
- data: { content: 'ok', contentType: 'text' },
- originalUrl: 'https://example.com',
- }),
+ crawl: vi.fn().mockResolvedValue(crawlResult('jina', 'ok')),
};
vi.mocked(Crawler).mockImplementation(function () {
return crawler as any;
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 11feeefdc9c..0a49a00efb2 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -1234,7 +1234,7 @@ describe('TaskService', () => {
expect(running?.cost).toBeNull();
});
- it('should not include topicCount when no topics exist', async () => {
+ it('should omit topicCount and heartbeat when both are absent', async () => {
const task = {
assigneeAgentId: null,
assigneeUserId: null,
@@ -1269,6 +1269,7 @@ describe('TaskService', () => {
const result = await service.getTaskDetail('TASK-1');
expect(result?.topicCount).toBeUndefined();
+ expect(result?.heartbeat).toBeUndefined();
});
it('should build workspace tree nodes from pinned documents', async () => {
@@ -1388,43 +1389,6 @@ describe('TaskService', () => {
});
});
- it('should not include heartbeat when neither heartbeatTimeout nor lastHeartbeatAt is set', async () => {
- const task = {
- assigneeAgentId: null,
- assigneeUserId: null,
- createdAt: null,
- description: null,
- error: null,
- heartbeatInterval: null,
- heartbeatTimeout: null,
- id: 'task_001',
- identifier: 'TASK-1',
- instruction: null,
- lastHeartbeatAt: null,
- name: 'Task 1',
- parentTaskId: null,
- priority: 'normal',
- status: 'todo',
- totalTopics: 0,
- };
-
- mockTaskModel.findById.mockResolvedValue(task);
- mockTaskModel.findAllDescendants.mockResolvedValue([]);
- mockTaskModel.getDependencies.mockResolvedValue([]);
- mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
- mockBriefModel.findByTaskId.mockResolvedValue([]);
- mockTaskModel.getComments.mockResolvedValue([]);
- mockTaskModel.getTreePinnedDocuments.mockResolvedValue({ nodeMap: {}, tree: [] });
- mockTaskModel.findByIds.mockResolvedValue([]);
- mockTaskModel.getCheckpointConfig.mockReturnValue({});
- mockTaskModel.getVerifyConfig.mockReturnValue(undefined);
-
- const service = new TaskService(db, userId);
- const result = await service.getTaskDetail('TASK-1');
-
- expect(result?.heartbeat).toBeUndefined();
- });
-
it('should gracefully handle failing optional calls via catch', async () => {
const task = {
assigneeAgentId: null,
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index a563ff8bad7..03fce5f912f 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -75,6 +75,26 @@ const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
...overrides,
}) as unknown as TaskItem;
+const createDoneParams = () => ({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+});
+
+const createErrorParams = (
+ runTrigger: NonNullable<Parameters<TaskLifecycleService['onTopicComplete']>[0]['runTrigger']>,
+) => ({
+ errorMessage: 'boom',
+ operationId: 'op-1',
+ reason: 'error',
+ runTrigger,
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+});
+
describe('TaskLifecycleService.onTopicComplete', () => {
let service: TaskLifecycleService;
let updateStatus: ReturnType<typeof vi.fn>;
@@ -137,13 +157,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const task = baseTask({ automationMode: 'heartbeat' });
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
@@ -177,13 +191,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const task = baseTask({ automationMode: 'schedule' });
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });
});
@@ -199,13 +207,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
findById.mockResolvedValue(task);
(service as any).taskTopicModel.countByTask = vi.fn().mockResolvedValue(3);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'completed', expect.anything());
@@ -225,13 +227,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
findById.mockResolvedValue(task);
(service as any).taskTopicModel.countByTask = vi.fn().mockResolvedValue(1);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).toHaveBeenCalledWith('task-1', 'completed', {
completedAt: expect.any(Date),
@@ -249,13 +245,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const countByTask = vi.fn().mockResolvedValue(99);
(service as any).taskTopicModel.countByTask = countByTask;
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
// Without scheduleStartedAt the helper short-circuits before querying,
// and the task falls through to the normal scheduled-park branch.
@@ -267,13 +257,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const task = baseTask({ automationMode: null });
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: null });
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());
@@ -287,13 +271,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
completeIfCompletionRequested.mockResolvedValue({ ...task, status: 'completed' });
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
// The request is consumed by the same write that completes the task.
expect(completeIfCompletionRequested).toHaveBeenCalledWith('task-1', 'op-1');
@@ -310,13 +288,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
findById.mockResolvedValue(task);
completeIfCompletionRequested.mockResolvedValue(null);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(cascadeOnCompletion).not.toHaveBeenCalled();
expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'paused', {
@@ -383,13 +355,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
.mockResolvedValue(task);
(service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(false);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
completedAt: expect.any(Date),
@@ -415,13 +381,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
.mockResolvedValue(task);
(service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(true);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
completedAt: expect.any(Date),
@@ -439,13 +399,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
.fn()
.mockReturnValue({ topic: { after: true } });
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'paused', {
error: null,
@@ -464,13 +418,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
findById.mockResolvedValue(task);
updateStatusIfCurrent.mockResolvedValue(null);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
completedAt: expect.any(Date),
@@ -485,13 +433,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
findById.mockResolvedValue(task);
(service as any).taskModel.shouldPauseOnTopicComplete = vi.fn().mockReturnValue(false);
- await service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createDoneParams());
expect(updateStatus).not.toHaveBeenCalled();
});
@@ -629,15 +571,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const task = baseTask({ automationMode: 'schedule', status: 'running' });
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'manual',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('manual'));
// Restored to the resting scheduled state so the next cron tick still
// fires — never paused off the schedule.
@@ -674,15 +608,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'schedule',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('schedule'));
// 1 prior + this one = 2, below the fuse of 3 → retryable, stays scheduled.
expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: 'boom' });
@@ -700,15 +626,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'schedule',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('schedule'));
// 2 prior + this one = 3 = fuse → pause.
expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: 'boom' });
@@ -729,15 +647,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'schedule',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('schedule'));
expect(updateContext).toHaveBeenCalledWith(
'task-1',
@@ -788,15 +698,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
it('leaves a Goal Task failure to the coordinator', async () => {
findById.mockResolvedValue(baseTask({ automationMode: null }));
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'goal',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('goal'));
expect(createBrief).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));
expect(notifyRunFailed).not.toHaveBeenCalled();
@@ -808,15 +710,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
it('still notifies for a manual rerun of a Goal Task', async () => {
findById.mockResolvedValue(baseTask({ automationMode: null }));
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'manual',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('manual'));
expect(notifyRunFailed).toHaveBeenCalledOnce();
});
@@ -824,15 +718,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
it('does not notify for a task deleted mid-run', async () => {
findById.mockResolvedValue(null);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'manual',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('manual'));
expect(notifyRunFailed).not.toHaveBeenCalled();
});
@@ -924,15 +810,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
runCompleted.mockRejectedValue(new Error('boom'));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- await expect(
- service.onTopicComplete({
- operationId: 'op-1',
- reason: 'done',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- }),
- ).resolves.toBeUndefined();
+ await expect(service.onTopicComplete(createDoneParams())).resolves.toBeUndefined();
expect(updateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: null });
// Logged where production sees it: the follow-up can change task state.
expect(consoleError).toHaveBeenCalled();
@@ -1046,15 +924,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
findById.mockResolvedValue(task);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'schedule',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('schedule'));
expect(notifyFailed).toHaveBeenCalledWith(
expect.objectContaining({ consecutiveFailures: 3, paused: true }),
@@ -1064,15 +934,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
it('manual failure of an automation task → run-failed notification, not an automation one', async () => {
findById.mockResolvedValue(baseTask({ automationMode: 'schedule' }));
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'manual',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('manual'));
expect(notifyFailed).not.toHaveBeenCalled();
expect(notifyRunFailed).toHaveBeenCalledWith(
@@ -1083,15 +945,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
it('transient heartbeat tick failure → NO notification (high-frequency ticks)', async () => {
findById.mockResolvedValue(baseTask({ automationMode: 'heartbeat' }));
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'heartbeat',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('heartbeat'));
expect(notifyFailed).not.toHaveBeenCalled();
});
@@ -1104,15 +958,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
}),
);
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'heartbeat',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
+ await service.onTopicComplete(createErrorParams('heartbeat'));
expect(notifyFailed).toHaveBeenCalledWith(
expect.objectContaining({ consecutiveFailures: 3, paused: true, runTrigger: 'heartbeat' }),
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
index c04363d8071..c3e588e9a61 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
@@ -26,6 +26,23 @@ import {
import { buildTaskPrompt } from './buildTaskPrompt';
+const promptDeps = (
+ db: Parameters<typeof buildTaskPrompt>[1]['db'],
+ taskModel: TaskModel,
+ userId: string,
+): Parameters<typeof buildTaskPrompt>[1] => ({
+ briefModel: new BriefModel(db, userId),
+ db,
+ taskModel,
+ taskTopicModel: new TaskTopicModel(db, userId),
+ userId,
+});
+
+const taskAcceptance = (subjectId: string): Parameters<AcceptanceModel['create']>[0] => ({
+ subjectId,
+ subjectType: 'task',
+});
+
const db = await getTestDB();
const userId = 'goal-work-prompt-test-user';
@@ -80,13 +97,7 @@ describe('buildTaskPrompt Goal loop context', () => {
});
const currentTask = await taskModel.findById(task.id);
- const result = await buildTaskPrompt(currentTask!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ const result = await buildTaskPrompt(currentTask!, promptDeps(db, taskModel, userId));
expect(result.prompt).toContain('Automatic Acceptance review:');
expect(result.prompt).toContain('Review feedback on the last delivery');
@@ -196,10 +207,7 @@ describe('buildTaskPrompt unresolved checks', () => {
const graphModel = new GoalGraphModel(db, userId);
const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Land it' });
await graphModel.bindTask(goal.id, taskNode!.id, task.id);
- const acceptance = await new AcceptanceModel(db, userId).create({
- subjectId: task.id,
- subjectType: 'task',
- });
+ const acceptance = await new AcceptanceModel(db, userId).create(taskAcceptance(task.id));
const [judged, unjudged] = await db
.insert(verifyRuns)
.values(
@@ -226,13 +234,10 @@ describe('buildTaskPrompt unresolved checks', () => {
].map((row) => ({ ...row, userId, verifierType: 'agent' as const })),
);
- const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ const result = await buildTaskPrompt(
+ (await taskModel.findById(task.id))!,
+ promptDeps(db, taskModel, userId),
+ );
expect(result.prompt).toContain('Unresolved checks from the last round:');
expect(result.prompt).toContain(
@@ -315,10 +320,7 @@ describe('buildTaskPrompt unresolved checks', () => {
const graphModel = new GoalGraphModel(db, userId);
const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Verify' });
await graphModel.bindTask(goal.id, taskNode!.id, task.id);
- const acceptance = await new AcceptanceModel(db, userId).create({
- subjectId: task.id,
- subjectType: 'task',
- });
+ const acceptance = await new AcceptanceModel(db, userId).create(taskAcceptance(task.id));
const flowItem = (id: string, node: string) => ({
...planItem(id),
sourceCriterionId: 'shared-criterion',
@@ -346,13 +348,10 @@ describe('buildTaskPrompt unresolved checks', () => {
].map((row) => ({ ...row, userId, verifierType: 'agent' as const, verifyRunId: run.id })),
);
- const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ const result = await buildTaskPrompt(
+ (await taskModel.findById(task.id))!,
+ promptDeps(db, taskModel, userId),
+ );
expect(result.prompt).toContain('1. Branch b — Branch b never reached the confirmation step.');
expect(result.prompt).not.toContain('Branch a');
@@ -370,10 +369,7 @@ describe('buildTaskPrompt unresolved checks', () => {
const graphModel = new GoalGraphModel(db, userId);
const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Retry' });
await graphModel.bindTask(goal.id, taskNode!.id, task.id);
- const acceptance = await new AcceptanceModel(db, userId).create({
- subjectId: task.id,
- subjectType: 'task',
- });
+ const acceptance = await new AcceptanceModel(db, userId).create(taskAcceptance(task.id));
const [judged, reworded] = await db
.insert(verifyRuns)
.values([
@@ -405,13 +401,10 @@ describe('buildTaskPrompt unresolved checks', () => {
},
]);
- const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ const result = await buildTaskPrompt(
+ (await taskModel.findById(task.id))!,
+ promptDeps(db, taskModel, userId),
+ );
expect(result.prompt).toContain('1. Check new-wording — The export still drops the table.');
});
@@ -432,10 +425,7 @@ describe('buildTaskPrompt owner change request', () => {
title: 'Complete full Goal acceptance',
});
await graphModel.bindTask(goal.id, taskNode!.id, task.id);
- const acceptance = await new AcceptanceModel(db, userId).create({
- subjectId: task.id,
- subjectType: 'task',
- });
+ const acceptance = await new AcceptanceModel(db, userId).create(taskAcceptance(task.id));
const runModel = new VerifyRunModel(db, userId);
const rejected = await runModel.create({ acceptanceId: acceptance.id, roundIndex: 1 });
await runModel.setDecision(rejected.id, 'reject', {
@@ -446,13 +436,10 @@ describe('buildTaskPrompt owner change request', () => {
// The rework's first attempt planned its own round, then failed to run.
await runModel.create({ acceptanceId: acceptance.id, roundIndex: 2 });
- const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ const result = await buildTaskPrompt(
+ (await taskModel.findById(task.id))!,
+ promptDeps(db, taskModel, userId),
+ );
expect(result.prompt).toContain('Review feedback on the last delivery');
expect(result.prompt).toContain('"Add a day-one agenda"');
@@ -463,13 +450,7 @@ describe('buildTaskPrompt delivery acceptance', () => {
const buildFor = async (taskId: string) => {
const taskModel = new TaskModel(db, userId);
const currentTask = await taskModel.findById(taskId);
- return buildTaskPrompt(currentTask!, {
- briefModel: new BriefModel(db, userId),
- db,
- taskModel,
- taskTopicModel: new TaskTopicModel(db, userId),
- userId,
- });
+ return buildTaskPrompt(currentTask!, promptDeps(db, taskModel, userId));
};
it('renders the acceptance section for a plain task with a verify config', async () => {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index d5b19a02bae..603f5f0af08 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -146,6 +146,19 @@ vi.mock('../resolveWorkspaceScope', () => ({
resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,
}));
+const createRuntimeContext = () => ({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+});
+
+const createDeviceCommandResult = () => ({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+});
+
describe('skillsRuntime', () => {
it.each(
(['runCommand', 'execScript', 'exportFile'] as const).flatMap((api) =>
@@ -175,12 +188,7 @@ describe('skillsRuntime', () => {
result: { success: false, exitCode: 1, stdout: '', stderr: 'Forbidden' },
});
}
- const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ const runtime = await skillsRuntime.factory(createRuntimeContext());
const execute = () =>
api === 'exportFile'
? runtime.exportFile({ path: '/page.html', filename: 'page.html' })
@@ -253,12 +261,7 @@ describe('skillsRuntime', () => {
});
mocks.sandboxService.callTool.mockImplementation(call);
mocks.sandboxService.exportAndUploadFile.mockImplementation(call);
- const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ const runtime = await skillsRuntime.factory(createRuntimeContext());
const execute = () =>
api === 'exportFile'
? runtime.exportFile({ path: '/page.html', filename: 'page.html' })
@@ -346,12 +349,7 @@ describe('skillsRuntime', () => {
// that cold cost alone, independent of test logic.
it('executes scripts through the sandbox service and only attaches persisted skill zips', async () => {
const { skillsRuntime } = await import('../skills');
- const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ const runtime = await skillsRuntime.factory(createRuntimeContext());
const result = await runtime.execScript({
activatedSkills: [
@@ -380,12 +378,7 @@ describe('skillsRuntime', () => {
it('tags sandbox exec results with executionEnv for plugin-state observability', async () => {
const { skillsRuntime } = await import('../skills');
- const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ const runtime = await skillsRuntime.factory(createRuntimeContext());
const result = await runtime.execScript({
activatedSkills: [],
@@ -405,10 +398,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workspaceId: 'workspace-1',
});
@@ -439,10 +429,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
await runtime.runCommand({ command: 'lh agent edit agt_123 -s "new prompt"' });
@@ -474,10 +461,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
operationId: 'op-abc',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workspaceId: 'workspace-1',
});
@@ -506,10 +490,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workspaceId: 'workspace-1',
});
@@ -546,12 +527,7 @@ describe('skillsRuntime', () => {
});
const { skillsRuntime } = await import('../skills');
- const runtime = await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ const runtime = await skillsRuntime.factory(createRuntimeContext());
const result = await runtime.execScript({
activatedSkills: [],
@@ -576,10 +552,7 @@ describe('skillsRuntime', () => {
activeDeviceId: 'device-1',
agentId: 'agent-1',
operationId: 'op-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workspaceId: 'workspace-1',
});
@@ -609,10 +582,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.activateSkill({ name: 'user-skill' });
@@ -636,10 +606,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.activateSkill({ name: 'user-skill' });
@@ -662,10 +629,7 @@ describe('skillsRuntime', () => {
return skillsRuntime.factory({
agentId: 'agent-1',
agentShareVisitor: { skillGrants },
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
} as never);
};
@@ -785,10 +749,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
agentId: 'agent-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
expect((await runtime.activateSkill({ name: 'user-skill' })).success).toBe(true);
@@ -805,19 +766,12 @@ describe('skillsRuntime', () => {
extractedDir: '/home/user/.lobehub/skills/extracted/zip-hash-1',
success: true,
});
- mocks.executeToolCall.mockResolvedValue({
- content: 'ok',
- state: { exitCode: 0, stdout: 'ok', success: true },
- success: true,
- });
+ mocks.executeToolCall.mockResolvedValue(createDeviceCommandResult());
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -860,10 +814,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -890,10 +841,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -927,10 +875,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -956,10 +901,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -974,19 +916,12 @@ describe('skillsRuntime', () => {
});
it('runs without a skill dir (workingDirectory cwd) when no archive exists', async () => {
- mocks.executeToolCall.mockResolvedValue({
- content: 'ok',
- state: { exitCode: 0, stdout: 'ok', success: true },
- success: true,
- });
+ mocks.executeToolCall.mockResolvedValue(createDeviceCommandResult());
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workingDirectory: '/Users/me/project',
});
@@ -1015,11 +950,7 @@ describe('skillsRuntime', () => {
extractedDir: '/home/user/.lobehub/skills/extracted/zip-hash-1',
success: true,
});
- mocks.executeToolCall.mockResolvedValue({
- content: 'ok',
- state: { exitCode: 0, stdout: 'ok', success: true },
- success: true,
- });
+ mocks.executeToolCall.mockResolvedValue(createDeviceCommandResult());
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
@@ -1027,10 +958,7 @@ describe('skillsRuntime', () => {
projectSkills: [
{ location: '/ws/.agents/skills/foo/SKILL.md', name: 'foo', source: 'project' },
],
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1083,19 +1011,12 @@ describe('skillsRuntime', () => {
mocks.prepareSkillDirectory.mockImplementation(function () {
return new Promise((resolve) => resolvers.push(resolve));
});
- mocks.executeToolCall.mockResolvedValue({
- content: 'ok',
- state: { exitCode: 0, stdout: 'ok', success: true },
- success: true,
- });
+ mocks.executeToolCall.mockResolvedValue(createDeviceCommandResult());
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const pending = runtime.execScript({
@@ -1150,10 +1071,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1185,10 +1103,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1219,10 +1134,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1248,10 +1160,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1266,20 +1175,13 @@ describe('skillsRuntime', () => {
});
it('forwards executionTimeoutMs as the shell observation timeout in the runCommand args', async () => {
- mocks.executeToolCall.mockResolvedValue({
- content: 'ok',
- state: { exitCode: 0, stdout: 'ok', success: true },
- success: true,
- });
+ mocks.executeToolCall.mockResolvedValue(createDeviceCommandResult());
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
executionTimeoutMs: 300_000,
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
await runtime.execScript({
@@ -1321,10 +1223,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.execScript({
@@ -1348,10 +1247,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.runCommand({ command: 'ls' });
@@ -1365,10 +1261,7 @@ describe('skillsRuntime', () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
const result = await runtime.exportFile({ filename: 'out.csv', path: '/tmp/out.csv' });
@@ -1386,12 +1279,7 @@ describe('skillsRuntime', () => {
const { filterBuiltinSkills } = await import('@/helpers/skillFilters');
const { skillsRuntime } = await import('../skills');
- await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ await skillsRuntime.factory(createRuntimeContext());
expect(filterBuiltinSkills).toHaveBeenLastCalledWith(expect.anything(), {
canExecuteOnDevice: false,
@@ -1399,10 +1287,7 @@ describe('skillsRuntime', () => {
await skillsRuntime.factory({
activeDeviceId: 'device-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
expect(filterBuiltinSkills).toHaveBeenLastCalledWith(expect.anything(), {
@@ -1426,10 +1311,7 @@ describe('skillsRuntime', () => {
mocks.resolveContentWorkspaceId.mockResolvedValueOnce('workspace-1');
await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
workspaceId: 'workspace-1',
});
@@ -1439,12 +1321,7 @@ describe('skillsRuntime', () => {
}),
);
- await skillsRuntime.factory({
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
- });
+ await skillsRuntime.factory(createRuntimeContext());
expect(MarketService).toHaveBeenLastCalledWith(
expect.objectContaining({
@@ -1465,10 +1342,7 @@ describe('skillsRuntime', () => {
await skillsRuntime.factory({
agentId: 'agt-1',
- serverDB: {} as never,
- toolManifestMap: {},
- topicId: 'topic-1',
- userId: 'user-1',
+ ...createRuntimeContext(),
});
// The same id the session is keyed by, so the sandbox this runtime reaches
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
index 88fea0739cd..44ec7131add 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
@@ -50,6 +50,14 @@ vi.mock('@/database/models/verifyRun', () => ({
}));
describe('acceptanceEvidenceRuntime', () => {
+ const createRuntime = (operationId: string) =>
+ acceptanceEvidenceRuntime.factory({
+ operationId,
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
beforeEach(() => {
vi.clearAllMocks();
mocks.operationFindById.mockResolvedValue({
@@ -79,12 +87,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('records a documents.id reference as first-class evidence', async () => {
mocks.documentFindByIds.mockResolvedValue([{ id: 'docs_123' }]);
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -99,12 +102,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('rejects an agent-document binding id instead of inserting it as a file', async () => {
mocks.documentFindByIds.mockResolvedValue([]);
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -122,12 +120,7 @@ describe('acceptanceEvidenceRuntime', () => {
// could only ever be evidenced by the text-only post-run turn.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
mocks.fileFindById.mockResolvedValue({ id: 'files_shot' });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -149,12 +142,7 @@ describe('acceptanceEvidenceRuntime', () => {
{ id: 'criterion-1', index: 0, required: true, title: 'Document', verifierType: 'llm' },
],
}));
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'repair-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('repair-op');
expect(
(
await runtime.submitEvidence({
@@ -170,12 +158,7 @@ describe('acceptanceEvidenceRuntime', () => {
});
it('keeps writing into the parent run from the post-run evidence turn', async () => {
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -207,12 +190,7 @@ describe('acceptanceEvidenceRuntime', () => {
{ checkItemId: 'criterion-1' },
]);
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.listCriteria();
@@ -245,12 +223,7 @@ describe('acceptanceEvidenceRuntime', () => {
// times and every call was rejected as UNKNOWN_FILE, so the acceptance
// ended with zero evidence. Empty strings are absent, not references.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -270,12 +243,7 @@ describe('acceptanceEvidenceRuntime', () => {
// `{"error":"Tool call failed"}`, which made a live builder abandon the
// plan-driven path on its first call.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.listCriteria();
@@ -290,12 +258,7 @@ describe('acceptanceEvidenceRuntime', () => {
// written into the text — the text-only outcome this path exists to prevent.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
mocks.fileFindById.mockResolvedValue({ id: 'files_shot' });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -312,12 +275,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('rejects an item that references both a document and a file', async () => {
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -340,12 +298,7 @@ describe('acceptanceEvidenceRuntime', () => {
plan: [{ id: 'criterion-1', index: 0, required: true, title: 'Late', verifierType: 'llm' }],
});
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.listCriteria();
@@ -359,12 +312,7 @@ describe('acceptanceEvidenceRuntime', () => {
// screenshot file)' } with no file, which would render on the acceptance
// as a visual check with nothing to open.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -383,12 +331,7 @@ describe('acceptanceEvidenceRuntime', () => {
// fail the structural gate again, round after round.
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
mocks.fileFindById.mockResolvedValue({ id: 'files_gif' });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -408,12 +351,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('stores a GIF cited as a screenshot as a gif', async () => {
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
mocks.fileFindById.mockResolvedValue({ fileType: 'image/gif', id: 'files_gif', name: 'a.gif' });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -428,12 +366,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('rejects a gif with no artifact behind it', async () => {
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -447,12 +380,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('rejects an unknown files.id before the evidence foreign key is evaluated', async () => {
mocks.fileFindById.mockResolvedValue(undefined);
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -466,12 +394,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('echoes received fields when rejecting an empty evidence item', async () => {
// T-574: a live builder resubmitted {type}-only items six times because the
// rejection never showed what had arrived. The echo makes the gap visible.
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -485,12 +408,7 @@ describe('acceptanceEvidenceRuntime', () => {
});
it('echoes "no fields" when an item arrives with nothing recognizable', async () => {
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'evidence-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('evidence-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
@@ -503,12 +421,7 @@ describe('acceptanceEvidenceRuntime', () => {
it('echoes received fields when rejecting an unbacked visual item', async () => {
mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
- const runtime = acceptanceEvidenceRuntime.factory({
- operationId: 'task-op',
- serverDB: {} as never,
- toolManifestMap: {},
- userId: 'user-1',
- });
+ const runtime = createRuntime('task-op');
const result = await runtime.submitEvidence({
checkItemId: 'criterion-1',
diff --git a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
index 1a09ee61059..dc33e5b4ef3 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
@@ -264,7 +264,6 @@ describe('AcceptanceService task lifecycle', () => {
]);
await expect(service().recomputeStatus('acc-1')).resolves.toBe('closed');
- expect(mocks.isRetiredGoalTask).toHaveBeenCalledWith('task_1');
expect(mocks.updatePolicyStatus).toHaveBeenCalledWith('acc-1', 'closed');
expect(mocks.taskServiceUpdateStatus).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
index d0d2f629cf7..feba1aafd4f 100644
--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
@@ -106,6 +106,15 @@ const confirmedRun = {
status: 'planned',
};
+const createTaskOperation = () => ({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+});
+
describe('runVerifyOnCompletion — verification claim', () => {
beforeEach(() => {
[
@@ -149,14 +158,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
{ id: 'c2', required: true },
],
});
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
claimEvidenceCollection.mockResolvedValue(true);
@@ -176,14 +178,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
{ id: 'repaired', required: true },
],
});
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
resultListByRun.mockResolvedValue([
{
checkItemId: 'carried',
@@ -214,14 +209,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
},
],
});
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
claimEvidenceCollection.mockResolvedValue(true);
@@ -288,14 +276,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
id: 'folded-run',
status: 'planned',
});
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
await runVerifyOnCompletion(db, 'u1', params);
@@ -312,14 +293,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
*/
it('stops instead of judging with the fallback verifier when resolution fails', async () => {
resolveTaskAcceptance.mockRejectedValue(new Error('connection terminated'));
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
await runVerifyOnCompletion(db, 'u1', params);
@@ -337,14 +311,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
it('binds a task-bound round to its Acceptance before judging it', async () => {
const orphan = { ...confirmedRun, acceptanceId: null };
findByOperation.mockResolvedValue(orphan);
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
await runVerifyOnCompletion(db, 'u1', params);
@@ -364,14 +331,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
});
it('judges directly when the builder already submitted evidence inside the Task run', async () => {
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'screenshot' }]);
await runVerifyOnCompletion(db, 'u1', params);
@@ -383,14 +343,7 @@ describe('runVerifyOnCompletion — verification claim', () => {
});
it('starts builder evidence collection before judging a task-bound run', async () => {
- operationFindById.mockResolvedValue({
- agentId: 'builder',
- id: 'op-1',
- model: 'm',
- provider: 'p',
- taskId: 'task-1',
- topicId: 'topic-1',
- });
+ operationFindById.mockResolvedValue(createTaskOperation());
claimEvidenceCollection.mockResolvedValue(true);
await runVerifyOnCompletion(db, 'u1', params);
diff --git a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
index 34b533b7557..43707855489 100644
--- a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
+++ b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
@@ -116,7 +116,6 @@ describe('MarketWidgetSandboxRunner', () => {
[503, { error: 'sandbox_not_configured' }, 'SANDBOX_NOT_CONFIGURED'],
[401, { error: 'invalid_token' }, 'SANDBOX_UNAUTHORIZED'],
[403, { error: 'forbidden_client' }, 'SANDBOX_UNAUTHORIZED'],
- [400, { error: 'invalid_request', error_description: 'bad host' }, 'SANDBOX_BAD_REQUEST'],
[422, { error: 'secret_unusable' }, 'SANDBOX_BAD_REQUEST'],
[429, { error: 'rate_limited' }, 'SANDBOX_BUSY'],
[429, { error: 'concurrency_limited' }, 'SANDBOX_BUSY'],
@@ -137,7 +136,9 @@ describe('MarketWidgetSandboxRunner', () => {
});
await expect(runner.run(request)).rejects.toMatchObject({
+ code: 'SANDBOX_BAD_REQUEST',
message: expect.stringContaining('invalid_request: bad host'),
+ name: 'WidgetSandboxError',
});
});
diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.ts
index 14fdc1f7e93..754a93f21a4 100644
--- a/packages/agent-gateway-client/src/client.test.ts
+++ b/packages/agent-gateway-client/src/client.test.ts
@@ -3,6 +3,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentStreamClient } from './client';
import type { ConnectionStatus } from './types';
+const createTerminalMessage = (
+ data: Record<string, unknown>,
+ operationId: string,
+ stepIndex: number,
+ timestamp: number,
+) => ({
+ event: {
+ data,
+ operationId,
+ stepIndex,
+ timestamp,
+ type: 'agent_runtime_end',
+ },
+ type: 'agent_event',
+});
+
// ─── Mock WebSocket ───
class MockWebSocket {
@@ -363,16 +379,7 @@ describe('AgentStreamClient', () => {
});
expect(client.connectionStatus).toBe('connected');
- ws.simulateMessage({
- event: {
- data: {},
- operationId: 'op-123',
- stepIndex: 1,
- timestamp: 2,
- type: 'agent_runtime_end',
- },
- type: 'agent_event',
- });
+ ws.simulateMessage(createTerminalMessage({}, 'op-123', 1, 2));
expect(client.connectionStatus).toBe('disconnected');
});
@@ -386,16 +393,7 @@ describe('AgentStreamClient', () => {
client.on('agent_event', (e) => events.push(e));
const ws = await connectAndAuth(client);
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member-456',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- },
- type: 'agent_event',
- });
+ ws.simulateMessage(createTerminalMessage({ reason: 'done' }, 'op-member-456', 0, 1));
expect(events).toHaveLength(1);
expect(events[0].operationId).toBe('op-member-456');
@@ -403,16 +401,7 @@ describe('AgentStreamClient', () => {
expect(client.connectionStatus).toBe('connected');
// The owner op's own terminal still ends the session.
- ws.simulateMessage({
- event: {
- data: {},
- operationId: 'op-123',
- stepIndex: 1,
- timestamp: 2,
- type: 'agent_runtime_end',
- },
- type: 'agent_event',
- });
+ ws.simulateMessage(createTerminalMessage({}, 'op-123', 1, 2));
expect(client.connectionStatus).toBe('disconnected');
});
@@ -425,16 +414,7 @@ describe('AgentStreamClient', () => {
client.on('session_complete', onComplete);
const ws = await connectAndAuth(client);
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member-456',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- },
- type: 'agent_event',
- });
+ ws.simulateMessage(createTerminalMessage({ reason: 'done' }, 'op-member-456', 0, 1));
ws.simulateMessage({ type: 'session_complete' });
expect(onComplete).not.toHaveBeenCalled();
@@ -467,16 +447,7 @@ describe('AgentStreamClient', () => {
client.on('session_complete', onComplete);
const ws = await connectAndAuth(client);
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member-456',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- },
- type: 'agent_event',
- });
+ ws.simulateMessage(createTerminalMessage({ reason: 'done' }, 'op-member-456', 0, 1));
await vi.advanceTimersByTimeAsync(30_000); // renderer suspended
ws.simulateMessage({ type: 'session_complete' });
expect(onComplete).not.toHaveBeenCalled();
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
index 23a53bf1243..c5e2b948446 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
@@ -3,6 +3,33 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GatewayMuxClient } from './GatewayMuxClient';
import type { GatewayMuxClientOptions, MuxServerMessage } from './types';
+const memberEnd = (reason: string): MuxServerMessage => ({
+ event: {
+ data: { reason },
+ operationId: 'op-member',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'agent_runtime_end',
+ } as any,
+ id: '1',
+ operationId: 'op-1',
+ type: 'agent_event',
+});
+
+const createResumeComplete = (status: 'running' | 'completed'): MuxServerMessage => ({
+ gap: false,
+ operationId: 'op-1',
+ status,
+ type: 'resume_complete',
+});
+
+const createErrorStatusChange = (): MuxServerMessage => ({
+ id: '2',
+ operationId: 'op-1',
+ status: 'error',
+ type: 'status_change',
+});
+
// ─── Mock WebSocket ───
class MockWebSocket {
@@ -391,12 +418,7 @@ describe('GatewayMuxClient', () => {
// replay
ws.simulateMessage(agentEvent('op-1', '1'));
ws.simulateMessage(agentEvent('op-1', '2'));
- ws.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'running',
- type: 'resume_complete',
- });
+ ws.simulateMessage(createResumeComplete('running'));
// live, including a duplicate that raced the resubscribe
ws.simulateMessage(agentEvent('op-1', '3'));
ws.simulateMessage(agentEvent('op-1', '2'));
@@ -683,25 +705,9 @@ describe('GatewayMuxClient', () => {
const onComplete = vi.fn();
sub.on('session_complete', onComplete);
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- } as any,
- id: '1',
- operationId: 'op-1',
- type: 'agent_event',
- });
+ ws.simulateMessage(memberEnd('done'));
ws.simulateMessage(agentEvent('op-1', '2', 'step_start'));
- ws.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'completed',
- type: 'resume_complete',
- });
+ ws.simulateMessage(createResumeComplete('completed'));
expect(onComplete).not.toHaveBeenCalled();
expect(sub.active).toBe(true);
@@ -726,18 +732,7 @@ describe('GatewayMuxClient', () => {
const onComplete = vi.fn();
sub.on('session_complete', onComplete);
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- } as any,
- id: '1',
- operationId: 'op-1',
- type: 'agent_event',
- });
+ ws.simulateMessage(memberEnd('done'));
ws.simulateMessage({
gap: true,
operationId: 'op-1',
@@ -755,36 +750,15 @@ describe('GatewayMuxClient', () => {
const onComplete = vi.fn();
sub.on('session_complete', onComplete);
- ws.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'running',
- type: 'resume_complete',
- });
- ws.simulateMessage({
- event: {
- data: { reason: 'done' },
- operationId: 'op-member',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- } as any,
- id: '1',
- operationId: 'op-1',
- type: 'agent_event',
- });
+ ws.simulateMessage(createResumeComplete('running'));
+ ws.simulateMessage(memberEnd('done'));
ws.simulateClose();
await vi.advanceTimersByTimeAsync(500);
const ws2 = await settle();
ws2.simulateMessage(READY);
// Hibernated DO: empty replay, authoritative `completed`.
- ws2.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'completed',
- type: 'resume_complete',
- });
+ ws2.simulateMessage(createResumeComplete('completed'));
expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'completed' });
});
@@ -792,19 +766,6 @@ describe('GatewayMuxClient', () => {
// Codex P1 on #20102 (round 2): the member terminal was acknowledged before
// the socket dropped, so the resubscribe replays only its sequenced echo.
describe('carries an owed echo across a reconnect (G-02)', () => {
- const memberEnd = (reason: string): MuxServerMessage => ({
- event: {
- data: { reason },
- operationId: 'op-member',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- } as any,
- id: '1',
- operationId: 'op-1',
- type: 'agent_event',
- });
-
const reconnectAfterMemberEnd = async (reason: string) => {
const { mux } = createMux();
const sub = mux.subscribe('op-1');
@@ -824,12 +785,7 @@ describe('GatewayMuxClient', () => {
const { onComplete, sub, ws2 } = await reconnectAfterMemberEnd('done');
ws2.simulateMessage({ id: '2', operationId: 'op-1', type: 'session_complete' } as any);
- ws2.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'completed',
- type: 'resume_complete',
- });
+ ws2.simulateMessage(createResumeComplete('completed'));
expect(onComplete).not.toHaveBeenCalled();
expect(sub.active).toBe(true);
@@ -842,12 +798,7 @@ describe('GatewayMuxClient', () => {
it('reads a replayed terminal status_change echo as the member end', async () => {
const { onComplete, sub, ws2 } = await reconnectAfterMemberEnd('error');
- ws2.simulateMessage({
- id: '2',
- operationId: 'op-1',
- status: 'error',
- type: 'status_change',
- });
+ ws2.simulateMessage(createErrorStatusChange());
ws2.simulateMessage({
gap: false,
operationId: 'op-1',
@@ -862,19 +813,9 @@ describe('GatewayMuxClient', () => {
it('stops owing an echo the replay did not deliver', async () => {
const { onComplete, ws2 } = await reconnectAfterMemberEnd('error');
- ws2.simulateMessage({
- gap: false,
- operationId: 'op-1',
- status: 'running',
- type: 'resume_complete',
- });
+ ws2.simulateMessage(createResumeComplete('running'));
// A later watchdog error is the supervisor's genuine end.
- ws2.simulateMessage({
- id: '2',
- operationId: 'op-1',
- status: 'error',
- type: 'status_change',
- });
+ ws2.simulateMessage(createErrorStatusChange());
expect(onComplete).toHaveBeenCalledWith({ source: 'status_change', status: 'error' });
});
@@ -909,20 +850,6 @@ describe('GatewayMuxClient', () => {
// its status — only that one may be owed, or the leftover swallows the
// supervisor's own end.
describe('owes only the v2 echo the member status produces (G-02)', () => {
- const memberEnd = (reason: string) =>
- ({
- event: {
- data: { reason },
- operationId: 'op-member',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_end',
- } as any,
- id: '1',
- operationId: 'op-1',
- type: 'agent_event',
- }) as MuxServerMessage;
-
it('interrupted member, then the supervisor completes via session_complete', async () => {
const { mux } = createMux();
const ws = await connectAndReady(mux);
@@ -973,12 +900,7 @@ describe('GatewayMuxClient', () => {
sub.on('session_complete', onComplete);
ws.simulateMessage(memberEnd('error'));
- ws.simulateMessage({
- id: '2',
- operationId: 'op-1',
- status: 'error',
- type: 'status_change',
- });
+ ws.simulateMessage(createErrorStatusChange());
expect(onComplete).not.toHaveBeenCalled();
ws.simulateMessage({
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index b575f882eff..270eed380cb 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -8,6 +8,74 @@ import { describe, expect, it } from 'vitest';
import { type AgentRuntimeContext, type AgentState } from '../../types';
import { GeneralChatAgent } from '../GeneralChatAgent';
+const createAgentOptions = (
+ modelRuntimeConfig: ConstructorParameters<typeof GeneralChatAgent>[0]['modelRuntimeConfig'],
+): ConstructorParameters<typeof GeneralChatAgent>[0] => ({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig,
+});
+
+const createToolCallingPayload = (toolCall: ChatToolPayload) => ({
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+});
+
+const createPathScopeManifest = (): AgentState['toolManifestMap'] => ({
+ 'local-system': {
+ identifier: 'local-system',
+ api: [
+ {
+ name: 'readLocalFile',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
+ },
+ ],
+ },
+});
+
+const createSearchToolCall = (): ChatToolPayload => ({
+ apiName: 'search',
+ arguments: '{"query":"test"}',
+ id: 'call-1',
+ identifier: 'lobe-web-browsing',
+ type: 'default',
+});
+
+const createCustomToolCall = (): ChatToolPayload => ({
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{}',
+ type: 'default',
+});
+
+const createAuditedAgentOptions = (
+ customResolver: GlobalInterventionAuditConfig,
+ modelRuntimeConfig: ConstructorParameters<typeof GeneralChatAgent>[0]['modelRuntimeConfig'],
+): ConstructorParameters<typeof GeneralChatAgent>[0] => ({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig,
+});
+
+const createCompressionOptions = (
+ compressionConfig: ConstructorParameters<typeof GeneralChatAgent>[0]['compressionConfig'],
+ modelRuntimeConfig: ConstructorParameters<typeof GeneralChatAgent>[0]['modelRuntimeConfig'],
+): ConstructorParameters<typeof GeneralChatAgent>[0] => ({
+ agentConfig: { maxSteps: 100 },
+ compressionConfig,
+ operationId: 'test-session',
+ modelRuntimeConfig,
+});
+
describe('GeneralChatAgent', () => {
const mockModelRuntimeConfig = {
model: 'gpt-4o-mini',
@@ -79,11 +147,7 @@ describe('GeneralChatAgent', () => {
describe('init and user_input phase', () => {
it('should return call_llm instruction for init phase', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [{ role: 'user', content: 'Hello' }] as any,
@@ -104,11 +168,7 @@ describe('GeneralChatAgent', () => {
});
it('should return call_llm instruction for user_input phase', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [{ role: 'user', content: 'What is the weather?' }] as any,
@@ -130,11 +190,7 @@ describe('GeneralChatAgent', () => {
});
it('should not infer allowedToolNames from normal state tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [{ role: 'user', content: 'Use tools if needed' }] as any,
tools: [{ function: { name: 'workspace____read' }, type: 'function' }] as any,
@@ -243,12 +299,9 @@ describe('GeneralChatAgent', () => {
const context = createMockContext('init', { model: 'gpt-4o-mini', provider: 'openai' });
// Without tools: raw=50K, adjusted=62.5K vs 100K threshold → no compression.
- const agentNoTools = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- compressionConfig,
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agentNoTools = new GeneralChatAgent(
+ createCompressionOptions(compressionConfig, mockModelRuntimeConfig),
+ );
const noToolsResult = await agentNoTools.runner(context, createMockState({ messages }));
expect((noToolsResult as any).type).toBe('call_llm');
@@ -262,12 +315,9 @@ describe('GeneralChatAgent', () => {
},
type: 'function',
};
- const agentWithTools = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- compressionConfig,
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agentWithTools = new GeneralChatAgent(
+ createCompressionOptions(compressionConfig, mockModelRuntimeConfig),
+ );
const withToolsResult = await agentWithTools.runner(
context,
createMockState({ messages, tools: [bigTool] as any }),
@@ -278,11 +328,7 @@ describe('GeneralChatAgent', () => {
describe('llm_result phase', () => {
it('should return finish when no tool calls', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('llm_result', {
@@ -306,11 +352,7 @@ describe('GeneralChatAgent', () => {
// empty assistant message while the requested work never ran. Reject the
// calls instead so the model can retry with a real name.
it('explains a device-picker call on a device-locked run instead of asking for the exact name', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
plan: { execution: { deviceId: 'device-a', kind: 'device', target: 'local' } },
@@ -346,11 +388,7 @@ describe('GeneralChatAgent', () => {
});
it('keeps the typo feedback for other names batched with a locked picker call', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
plan: { execution: { deviceId: 'device-a', kind: 'device', target: 'local' } },
@@ -382,11 +420,7 @@ describe('GeneralChatAgent', () => {
});
it('should reject unresolvable tool_calls so the model can retry', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('llm_result', {
@@ -437,11 +471,7 @@ describe('GeneralChatAgent', () => {
});
it('should fail the operation once the unresolvable-tool feedback budget is spent', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({ unresolvedToolFeedbackRounds: 2 });
const context = createMockContext('llm_result', {
@@ -464,11 +494,7 @@ describe('GeneralChatAgent', () => {
// Gemini 3.x 400s on the next tool-call turn unless `thoughtSignature` is
// round-tripped, which would kill the retry the rejection exists to enable.
it('should keep the thought signature of an unresolvable tool call', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const context = createMockContext('llm_result', {
hasToolsCalling: true,
@@ -498,11 +524,7 @@ describe('GeneralChatAgent', () => {
});
it('should finish instead of retrying unresolvable tool_calls past max steps', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const context = createMockContext('llm_result', {
hasToolsCalling: true,
@@ -529,11 +551,7 @@ describe('GeneralChatAgent', () => {
// rejections written by earlier operations, so the budget has to be
// operation-scoped state rather than a count of matching tool rows.
it('should not spend the budget on rejections from earlier operations', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const rejection = {
content:
@@ -564,11 +582,7 @@ describe('GeneralChatAgent', () => {
});
it('should fail when unresolvable tool_calls carry no name to reject', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const context = createMockContext('llm_result', {
hasToolsCalling: true,
@@ -586,11 +600,7 @@ describe('GeneralChatAgent', () => {
});
it('should return call_tool for single tool that does not need intervention', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -609,11 +619,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -629,11 +635,7 @@ describe('GeneralChatAgent', () => {
});
it('should return call_tools_batch for multiple tools that do not need intervention', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCalls: ChatToolPayload[] = [
{
@@ -829,11 +831,7 @@ describe('GeneralChatAgent', () => {
});
it('should handle invalid JSON in tool arguments gracefully', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -852,11 +850,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
// Should not throw, should proceed with call_tool (treats invalid JSON as empty args)
const result = await agent.runner(context, state);
@@ -873,11 +867,7 @@ describe('GeneralChatAgent', () => {
});
it('should return request_human_approve for tools requiring intervention', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -896,11 +886,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -918,11 +904,7 @@ describe('GeneralChatAgent', () => {
});
it('should return both call_tools_batch and request_human_approve for mixed tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const safeTool: ChatToolPayload = {
id: 'call-1',
@@ -981,11 +963,7 @@ describe('GeneralChatAgent', () => {
});
it('rejects parallel-batch calls that arrived with empty arguments instead of executing them', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
// The serialization-loss shape from T-673: fully-formed parallel calls
// whose per-call arguments were lost upstream, reaching the agent as ''.
@@ -1029,11 +1007,7 @@ describe('GeneralChatAgent', () => {
});
it('still executes the calls that kept their arguments in a mixed batch', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const lostArgsCall: ChatToolPayload = {
apiName: 'search',
@@ -1089,11 +1063,7 @@ describe('GeneralChatAgent', () => {
describe('tool_result phase', () => {
it('should return call_llm when no pending tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -1129,11 +1099,7 @@ describe('GeneralChatAgent', () => {
// The first call_llm after the tool result must carry it so the LLM turn fills
// that placeholder instead of creating a new message and orphaning the seed.
it('should reuse the seeded assistant placeholder for the first call_llm after a tool result', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -1317,12 +1283,9 @@ describe('GeneralChatAgent', () => {
const context = createMockContext('tool_result', { parentMessageId: 'tool-msg-1' });
// Sanity check: without forceFinish, the big tool manifest trips compression.
- const baselineAgent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- compressionConfig,
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const baselineAgent = new GeneralChatAgent(
+ createCompressionOptions(compressionConfig, mockModelRuntimeConfig),
+ );
const baseline = await baselineAgent.runner(
context,
createMockState({ messages, tools: [bigTool] as any }),
@@ -1331,12 +1294,9 @@ describe('GeneralChatAgent', () => {
// With forceFinish set, the executor will drop tools, so the agent must
// ignore them in the compression check and go straight to call_llm.
- const forceFinishAgent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- compressionConfig,
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const forceFinishAgent = new GeneralChatAgent(
+ createCompressionOptions(compressionConfig, mockModelRuntimeConfig),
+ );
const forced = await forceFinishAgent.runner(
context,
createMockState({ forceFinish: true, messages, tools: [bigTool] as any }),
@@ -1345,11 +1305,7 @@ describe('GeneralChatAgent', () => {
});
it('should return request_human_approve when there are pending tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const pendingPlugin: ChatToolPayload = {
id: 'call-2',
@@ -1410,11 +1366,7 @@ describe('GeneralChatAgent', () => {
});
it('should return request_human_approve when current assistant turn stores calls in tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const pendingPlugin: ChatToolPayload = {
id: 'call-2',
@@ -1481,11 +1433,7 @@ describe('GeneralChatAgent', () => {
// `pluginIntervention.status === 'pending'` row would be loaded back
// into state.messages via historyMessages and hijack every subsequent
// tool_result phase, parking the loop in waiting_for_human forever.
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const stalePendingPlugin: ChatToolPayload = {
id: 'old-call-1',
@@ -1558,11 +1506,7 @@ describe('GeneralChatAgent', () => {
describe('tools_batch_result phase', () => {
it('should return call_llm when no pending tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -1593,11 +1537,7 @@ describe('GeneralChatAgent', () => {
});
it('should return request_human_approve when there are pending tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const pendingPlugin: ChatToolPayload = {
id: 'call-3',
@@ -1666,11 +1606,7 @@ describe('GeneralChatAgent', () => {
});
it('should return request_human_approve when batch current assistant turn stores calls in tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const pendingPlugin: ChatToolPayload = {
id: 'call-3',
@@ -1770,11 +1706,7 @@ describe('GeneralChatAgent', () => {
describe('error phase', () => {
it('should return finish instruction with error details', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const errorMessage = 'Network timeout';
@@ -1792,11 +1724,7 @@ describe('GeneralChatAgent', () => {
});
it('should handle error without message', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('error', { error: {} });
@@ -1813,21 +1741,9 @@ describe('GeneralChatAgent', () => {
describe('unified abort check', () => {
it('should handle abort at llm_result phase when state is interrupted', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
- const toolCalls: ChatToolPayload[] = [
- {
- apiName: 'search',
- arguments: '{"query":"test"}',
- id: 'call-1',
- identifier: 'lobe-web-browsing',
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchToolCall()];
const state = createMockState({
status: 'interrupted', // State is interrupted
@@ -1852,11 +1768,7 @@ describe('GeneralChatAgent', () => {
});
it('should handle abort at tool_result phase when state is interrupted', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
status: 'interrupted',
@@ -1910,11 +1822,7 @@ describe('GeneralChatAgent', () => {
// Without the ids, `resolve_aborted_tools` would insert a second row per
// call and leave the originals `pending` — the approval cards would
// survive the Stop.
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
status: 'interrupted',
@@ -1965,11 +1873,7 @@ describe('GeneralChatAgent', () => {
});
it('should return finish when state is interrupted with no tools', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
status: 'interrupted',
@@ -1992,21 +1896,9 @@ describe('GeneralChatAgent', () => {
});
it('should continue normal flow when state is not interrupted', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
- const toolCalls: ChatToolPayload[] = [
- {
- apiName: 'search',
- arguments: '{"query":"test"}',
- id: 'call-1',
- identifier: 'lobe-web-browsing',
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchToolCall()];
const state = createMockState({
status: 'running', // Normal running state
@@ -2038,21 +1930,9 @@ describe('GeneralChatAgent', () => {
describe('unified abort check', () => {
it('should handle abort at human_abort phase when state is interrupted', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
- const toolCalls: ChatToolPayload[] = [
- {
- apiName: 'search',
- arguments: '{"query":"test"}',
- id: 'call-1',
- identifier: 'lobe-web-browsing',
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchToolCall()];
const state = createMockState({
status: 'interrupted', // Trigger unified abort check
@@ -2081,20 +1961,10 @@ describe('GeneralChatAgent', () => {
describe('human_abort phase', () => {
it('should return resolve_aborted_tools when there are pending tool calls', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCalls: ChatToolPayload[] = [
- {
- apiName: 'search',
- arguments: '{"query":"test"}',
- id: 'call-1',
- identifier: 'lobe-web-browsing',
- type: 'default',
- },
+ createSearchToolCall(),
{
apiName: 'getWeather',
arguments: '{"location":"NYC"}',
@@ -2125,11 +1995,7 @@ describe('GeneralChatAgent', () => {
});
it('should return finish when there are no tool calls', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('human_abort', {
@@ -2150,11 +2016,7 @@ describe('GeneralChatAgent', () => {
});
it('should return finish when toolsCalling is undefined', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('human_abort', {
@@ -2174,11 +2036,7 @@ describe('GeneralChatAgent', () => {
});
it('should return finish when toolsCalling is empty array', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('human_abort', {
@@ -2201,11 +2059,7 @@ describe('GeneralChatAgent', () => {
describe('sub_agent_result phase (single sub-agent)', () => {
it('should return call_llm when task completed', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -2239,11 +2093,7 @@ describe('GeneralChatAgent', () => {
});
it('should return call_llm even when task failed', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -2299,11 +2149,7 @@ describe('GeneralChatAgent', () => {
describe('sub_agents_batch_result phase (multiple sub-agents)', () => {
it('should return call_llm when tasks completed', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -2344,11 +2190,7 @@ describe('GeneralChatAgent', () => {
});
it('fills a resume-seeded assistant placeholder and keeps the summary prompt', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [{ role: 'user', content: 'Execute tasks' }] as any,
@@ -2372,11 +2214,7 @@ describe('GeneralChatAgent', () => {
});
it('should return call_llm even when some tasks failed', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
@@ -2522,11 +2360,7 @@ describe('GeneralChatAgent', () => {
describe('compression_result phase', () => {
it('should return call_llm with compressed messages and force a new assistant message', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const compressedMessages = [
{ content: 'Compressed summary', id: 'group-1', role: 'compressedGroup' },
@@ -2559,11 +2393,7 @@ describe('GeneralChatAgent', () => {
});
it('should fall back to state messages when a new producer omits compressed messages', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const compressedMessages = [
{ content: 'Compressed summary', id: 'group-1', role: 'compressedGroup' },
{ content: 'Latest user follow-up', role: 'user' },
@@ -2588,11 +2418,7 @@ describe('GeneralChatAgent', () => {
// before running, the seeded placeholder must still be reused after
// compression rather than orphaned by createAssistantMessage.
it('should reuse the seeded assistant placeholder instead of forcing a new message', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const compressedMessages = [
{ content: 'Compressed summary', id: 'group-1', role: 'compressedGroup' },
@@ -2630,11 +2456,7 @@ describe('GeneralChatAgent', () => {
describe('unknown phase', () => {
it('should return finish instruction for unknown phase', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState();
const context = createMockContext('unknown_phase' as any);
@@ -2675,30 +2497,10 @@ describe('GeneralChatAgent', () => {
const state = createMockState({
plan: { workingDirectory: '/workspace' },
- toolManifestMap: {
- 'local-system': {
- identifier: 'local-system',
- api: [
- {
- name: 'readLocalFile',
- humanIntervention: {
- dynamic: {
- default: 'never',
- policy: 'required',
- type: 'pathScopeAudit',
- },
- },
- },
- ],
- },
- },
+ toolManifestMap: createPathScopeManifest(),
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -2737,34 +2539,14 @@ describe('GeneralChatAgent', () => {
const state = createMockState({
plan: { workingDirectory: '/workspace' },
- toolManifestMap: {
- 'local-system': {
- identifier: 'local-system',
- api: [
- {
- name: 'readLocalFile',
- humanIntervention: {
- dynamic: {
- default: 'never',
- policy: 'required',
- type: 'pathScopeAudit',
- },
- },
- },
- ],
- },
- },
+ toolManifestMap: createPathScopeManifest(),
userInterventionConfig: {
approvalMode: 'auto-run',
allowList: [],
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -2804,30 +2586,10 @@ describe('GeneralChatAgent', () => {
const state = createMockState({
plan: { workingDirectory: '/workspace' },
- toolManifestMap: {
- 'local-system': {
- identifier: 'local-system',
- api: [
- {
- name: 'readLocalFile',
- humanIntervention: {
- dynamic: {
- default: 'never',
- policy: 'required',
- type: 'pathScopeAudit',
- },
- },
- },
- ],
- },
- },
+ toolManifestMap: createPathScopeManifest(),
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -2843,11 +2605,7 @@ describe('GeneralChatAgent', () => {
});
it('should check intervention at API level when configured', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -2878,11 +2636,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -2898,11 +2652,7 @@ describe('GeneralChatAgent', () => {
});
it('should execute all tools when user approvalMode is auto-run', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -2925,11 +2675,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -2946,11 +2692,7 @@ describe('GeneralChatAgent', () => {
});
it('should respect allowList when approvalMode is allow-list', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const allowedTool: ChatToolPayload = {
id: 'call-1',
@@ -3008,11 +2750,7 @@ describe('GeneralChatAgent', () => {
});
it('should use tool config when approvalMode is manual', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const safeTool: ChatToolPayload = {
id: 'call-1',
@@ -3073,11 +2811,7 @@ describe('GeneralChatAgent', () => {
});
it('should always require intervention for tools with "always" policy even in auto-run mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const alwaysTool: ChatToolPayload = {
id: 'call-1',
@@ -3125,11 +2859,7 @@ describe('GeneralChatAgent', () => {
});
it('should always require intervention for tools with tool-level "always" policy', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const alwaysTool: ChatToolPayload = {
id: 'call-1',
@@ -3172,11 +2902,7 @@ describe('GeneralChatAgent', () => {
});
it('should handle mixed tools with "always" and regular policies in auto-run mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const regularTool: ChatToolPayload = {
id: 'call-1',
@@ -3243,11 +2969,7 @@ describe('GeneralChatAgent', () => {
});
it('should handle "always" policy with rule-based configuration', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -3276,11 +2998,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3414,12 +3132,9 @@ describe('GeneralChatAgent', () => {
resolver: async (toolArgs) => toolArgs.dangerous === true,
};
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- globalInterventionAudits: [customResolver],
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(
+ createAuditedAgentOptions(customResolver, mockModelRuntimeConfig),
+ );
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -3435,11 +3150,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3460,12 +3171,9 @@ describe('GeneralChatAgent', () => {
resolver: async (toolArgs) => toolArgs.dangerous === true,
};
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- globalInterventionAudits: [customResolver],
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(
+ createAuditedAgentOptions(customResolver, mockModelRuntimeConfig),
+ );
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -3482,11 +3190,7 @@ describe('GeneralChatAgent', () => {
userInterventionConfig: { approvalMode: 'auto-run' },
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3519,12 +3223,9 @@ describe('GeneralChatAgent', () => {
resolver: async (toolArgs) => toolArgs.blocked === true,
};
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- globalInterventionAudits: [customResolver],
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(
+ createAuditedAgentOptions(customResolver, mockModelRuntimeConfig),
+ );
const blockedTool: ChatToolPayload = {
id: 'call-1',
@@ -3572,20 +3273,11 @@ describe('GeneralChatAgent', () => {
resolver: async () => true, // always triggers
};
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- globalInterventionAudits: [customResolver],
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(
+ createAuditedAgentOptions(customResolver, mockModelRuntimeConfig),
+ );
- const toolCall: ChatToolPayload = {
- id: 'call-1',
- identifier: 'my-tool',
- apiName: 'doSomething',
- arguments: '{}',
- type: 'default',
- };
+ const toolCall: ChatToolPayload = createCustomToolCall();
const state = createMockState({
toolManifestMap: {
@@ -3594,11 +3286,7 @@ describe('GeneralChatAgent', () => {
userInterventionConfig: { approvalMode: 'headless' },
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3618,20 +3306,11 @@ describe('GeneralChatAgent', () => {
resolver: async () => true,
};
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- globalInterventionAudits: [customResolver],
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(
+ createAuditedAgentOptions(customResolver, mockModelRuntimeConfig),
+ );
- const toolCall: ChatToolPayload = {
- id: 'call-1',
- identifier: 'my-tool',
- apiName: 'doSomething',
- arguments: '{}',
- type: 'default',
- };
+ const toolCall: ChatToolPayload = createCustomToolCall();
const state = createMockState({
toolManifestMap: {
@@ -3639,11 +3318,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3676,13 +3351,7 @@ describe('GeneralChatAgent', () => {
modelRuntimeConfig: mockModelRuntimeConfig,
});
- const toolCall: ChatToolPayload = {
- id: 'call-1',
- identifier: 'my-tool',
- apiName: 'doSomething',
- arguments: '{}',
- type: 'default',
- };
+ const toolCall: ChatToolPayload = createCustomToolCall();
const state = createMockState({
plan: { workingDirectory: '/workspace' },
@@ -3692,11 +3361,7 @@ describe('GeneralChatAgent', () => {
userInterventionConfig: { approvalMode: 'auto-run' },
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
await agent.runner(context, state);
@@ -3735,24 +3400,14 @@ describe('GeneralChatAgent', () => {
modelRuntimeConfig: mockModelRuntimeConfig,
});
- const toolCall: ChatToolPayload = {
- id: 'call-1',
- identifier: 'my-tool',
- apiName: 'doSomething',
- arguments: '{}',
- type: 'default',
- };
+ const toolCall: ChatToolPayload = createCustomToolCall();
const state = createMockState({
toolManifestMap: { 'my-tool': { identifier: 'my-tool' } },
userInterventionConfig: { approvalMode: 'auto-run' },
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3809,11 +3464,7 @@ describe('GeneralChatAgent', () => {
});
it('should still require intervention for default always blacklist tools in auto-run mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const alwaysTool: ChatToolPayload = {
id: 'call-1',
@@ -3896,11 +3547,7 @@ describe('GeneralChatAgent', () => {
);
it('should execute tool-level required tools in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -3922,11 +3569,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3939,11 +3582,7 @@ describe('GeneralChatAgent', () => {
});
it('should execute API-level required runCommand in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const toolCall: ChatToolPayload = {
id: 'call-1',
@@ -3970,11 +3609,7 @@ describe('GeneralChatAgent', () => {
},
});
- const context = createMockContext('llm_result', {
- hasToolsCalling: true,
- toolsCalling: [toolCall],
- parentMessageId: 'msg-1',
- });
+ const context = createMockContext('llm_result', createToolCallingPayload(toolCall));
const result = await agent.runner(context, state);
@@ -3987,11 +3622,7 @@ describe('GeneralChatAgent', () => {
});
it('should resolve tools with "always" policy in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const alwaysTool: ChatToolPayload = {
id: 'call-1',
@@ -4042,11 +3673,7 @@ describe('GeneralChatAgent', () => {
});
it('should resolve security blacklisted tools in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const blacklistedTool: ChatToolPayload = {
id: 'call-1',
@@ -4093,11 +3720,7 @@ describe('GeneralChatAgent', () => {
});
it('should resolve all tools needing approval in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const requiredTool: ChatToolPayload = {
id: 'call-1',
@@ -4175,11 +3798,7 @@ describe('GeneralChatAgent', () => {
});
it('should resolve multiple tools requiring approval in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const tool1: ChatToolPayload = {
id: 'call-1',
@@ -4235,11 +3854,7 @@ describe('GeneralChatAgent', () => {
});
it('should batch multiple tool-level required tools in headless mode', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const tool1: ChatToolPayload = {
id: 'call-1',
@@ -4332,11 +3947,7 @@ describe('GeneralChatAgent', () => {
});
it('re-parks on the parsed assistantGroup shape while siblings are still pending', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = parsedStateWith([
groupedToolEntry('call-a', 'approved'),
@@ -4375,11 +3986,7 @@ describe('GeneralChatAgent', () => {
});
it('continues to the LLM once every tool in the parsed group is resolved', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = parsedStateWith([
groupedToolEntry('call-a', 'approved'),
@@ -4475,11 +4082,7 @@ describe('GeneralChatAgent', () => {
);
it('still re-parks on the raw assistant + tool-row shape', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const plugin = {
apiName: 'calculate',
@@ -4513,11 +4116,7 @@ describe('GeneralChatAgent', () => {
});
it('ignores a stale pending row from an earlier turn', async () => {
- const agent = new GeneralChatAgent({
- agentConfig: { maxSteps: 100 },
- operationId: 'test-session',
- modelRuntimeConfig: mockModelRuntimeConfig,
- });
+ const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));
const state = createMockState({
messages: [
diff --git a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
index 2aacc4ca5ff..e29ea578f58 100644
--- a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
@@ -10,6 +10,14 @@ import { describe, expect, it } from 'vitest';
import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../../../types';
import { GraphAgent } from '../GraphAgent';
+const createGraphOptions = (
+ graph: ConstructorParameters<typeof GraphAgent>[0]['graph'],
+): ConstructorParameters<typeof GraphAgent>[0] => ({
+ agentConfig: { maxSteps: 100 },
+ graph,
+ operationId: 'test-operation',
+});
+
const GRAPH_RUNTIME_STATE_KEY = '__graphRuntimeState';
const TEST_DIR = path.dirname(fileURLToPath(import.meta.url));
@@ -468,11 +476,7 @@ describe('GraphAgent', () => {
describe('prompt', () => {
it('should attach node context and entry guidance without the legacy node envelope', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const messages = [{ content: '/goal inspect graph context', role: 'user' as const }];
const state = createMockState({ messages });
@@ -508,11 +512,7 @@ describe('GraphAgent', () => {
});
it('should attach node instruction, upstream field value, field description, and deliverable target', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal verify prompt contract', role: 'user' }],
});
@@ -546,11 +546,7 @@ describe('GraphAgent', () => {
});
it('should render multi-source input context and verifier output contract', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal verify multi-source prompt', role: 'user' }],
});
@@ -588,11 +584,7 @@ describe('GraphAgent', () => {
});
it('should render extraction instruction, format instruction, schema, and previous error', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal verify extraction prompt', role: 'user' }],
});
@@ -635,11 +627,7 @@ describe('GraphAgent', () => {
: edge,
),
};
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph,
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(graph));
const state = createMockState({
messages: [{ content: '/goal verify raw fallback prompt', role: 'user' }],
});
@@ -784,11 +772,7 @@ describe('GraphAgent', () => {
describe('e2e', () => {
it('should execute the /goal plan-work-verify loop with mocked llm outputs', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal refactor graph agent runtime', role: 'user' }],
});
@@ -1040,11 +1024,7 @@ describe('GraphAgent', () => {
});
it('should not increment instructionCount for graph finish instructions', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal finish without extra instruction count', role: 'user' }],
});
@@ -1199,11 +1179,7 @@ describe('GraphAgent', () => {
},
terminal: 'fallback',
};
- const matchedAgent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph,
- operationId: 'test-operation',
- });
+ const matchedAgent = new GraphAgent(createGraphOptions(graph));
const matchedState = createMockState({
messages: [{ content: '/goal route matched', role: 'user' }],
});
@@ -1218,11 +1194,7 @@ describe('GraphAgent', () => {
expect(getGraphNodeContextText(matchedInstruction)).toContain('Matched route instruction.');
expect(getGraphNodeContextText(matchedInstruction)).toContain('go');
- const fallbackAgent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph,
- operationId: 'test-operation',
- });
+ const fallbackAgent = new GraphAgent(createGraphOptions(graph));
const fallbackState = createMockState({
messages: [{ content: '/goal route fallback', role: 'user' }],
});
@@ -1283,11 +1255,7 @@ describe('GraphAgent', () => {
},
terminal: 'fallback',
};
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph,
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(graph));
const state = createMockState({
messages: [{ content: '/goal invalid condition fallback', role: 'user' }],
});
@@ -1308,11 +1276,7 @@ describe('GraphAgent', () => {
});
it('should retry extraction when parsed JSON does not match the edge output schema', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal validate planned output schema', role: 'user' }],
});
@@ -1351,11 +1315,7 @@ describe('GraphAgent', () => {
});
it('should request fenced json extraction and commit recovered node output', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal add graph tests', role: 'user' }],
});
@@ -1394,11 +1354,7 @@ describe('GraphAgent', () => {
});
it('should stop the verify-to-work loop when maxTraversals is reached', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal keep iterating until verified', role: 'user' }],
});
@@ -1464,11 +1420,7 @@ describe('GraphAgent', () => {
});
it('should commit raw output after extraction attempts are exhausted', async () => {
- const agent = new GraphAgent({
- agentConfig: { maxSteps: 100 },
- graph: loadGoalLoopGraph(),
- operationId: 'test-operation',
- });
+ const agent = new GraphAgent(createGraphOptions(loadGoalLoopGraph()));
const state = createMockState({
messages: [{ content: '/goal recover from bad planning output', role: 'user' }],
});
diff --git a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
index 7ca863e18c9..a1ddde3b254 100644
--- a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
@@ -4,24 +4,53 @@ import { describe, expect, it } from 'vitest';
import { AgentRuntime } from '../runtime';
import { UsageCounter } from '../UsageCounter';
+const createPricedModelUsage = (): ModelUsage => ({
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+});
+
+const createModelUsage = (): ModelUsage => ({
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+});
+
+const createOpenAIUsageInput = (
+ cost: Parameters<typeof UsageCounter.accumulateLLM>[0]['cost'],
+ modelUsage: ModelUsage,
+ usage: Parameters<typeof UsageCounter.accumulateLLM>[0]['usage'],
+): Parameters<typeof UsageCounter.accumulateLLM>[0] => ({
+ cost,
+ model: 'gpt-4',
+ modelUsage,
+ provider: 'openai',
+ usage,
+});
+
+const createAnthropicUsageInput = (
+ cost: Parameters<typeof UsageCounter.accumulateLLM>[0]['cost'],
+ modelUsage: ModelUsage,
+ usage: Parameters<typeof UsageCounter.accumulateLLM>[0]['usage'],
+): Parameters<typeof UsageCounter.accumulateLLM>[0] => ({
+ cost,
+ model: 'claude-3-5-sonnet-20241022',
+ modelUsage,
+ provider: 'anthropic',
+ usage,
+});
+
describe('UsageCounter', () => {
describe('UsageCounter.accumulateLLM', () => {
it('should accumulate LLM usage tokens', () => {
const state = AgentRuntime.createInitialState();
- const modelUsage: ModelUsage = {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createModelUsage();
- const { usage } = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage,
- provider: 'openai',
- usage: state.usage,
- });
+ const { usage } = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, modelUsage, state.usage),
+ );
expect(usage.llm.tokens.input).toBe(100);
expect(usage.llm.tokens.output).toBe(50);
@@ -32,19 +61,11 @@ describe('UsageCounter', () => {
it('should not mutate original usage', () => {
const state = AgentRuntime.createInitialState();
- const modelUsage: ModelUsage = {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createModelUsage();
- const { usage } = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage,
- provider: 'openai',
- usage: state.usage,
- });
+ const { usage } = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, modelUsage, state.usage),
+ );
expect(state.usage.llm.tokens.input).toBe(0);
expect(usage).not.toBe(state.usage);
@@ -53,20 +74,11 @@ describe('UsageCounter', () => {
it('should create new byModel entry when not exists', () => {
const state = AgentRuntime.createInitialState();
- const modelUsage: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createPricedModelUsage();
- const { cost } = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage,
- provider: 'openai',
- usage: state.usage,
- });
+ const { cost } = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, modelUsage, state.usage),
+ );
expect(cost?.llm.byModel).toHaveLength(1);
expect(cost?.llm.byModel[0]).toEqual({
@@ -86,12 +98,7 @@ describe('UsageCounter', () => {
it('should accumulate to existing byModel entry', () => {
const state = AgentRuntime.createInitialState();
- const usage1: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const usage1: ModelUsage = createPricedModelUsage();
const usage2: ModelUsage = {
cost: 0.03,
@@ -100,20 +107,12 @@ describe('UsageCounter', () => {
totalTokens: 75,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage: usage1,
- provider: 'openai',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'gpt-4',
- modelUsage: usage2,
- provider: 'openai',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel).toHaveLength(1);
expect(result2.cost?.llm.byModel[0]).toEqual({
@@ -133,12 +132,7 @@ describe('UsageCounter', () => {
it('should accumulate multiple models separately', () => {
const state = AgentRuntime.createInitialState();
- const usage1: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const usage1: ModelUsage = createPricedModelUsage();
const usage2: ModelUsage = {
cost: 0.02,
@@ -147,20 +141,12 @@ describe('UsageCounter', () => {
totalTokens: 75,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage: usage1,
- provider: 'openai',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage2,
- provider: 'anthropic',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel).toHaveLength(2);
expect(result2.cost?.llm.byModel[0].id).toBe('openai/gpt-4');
@@ -202,12 +188,7 @@ describe('UsageCounter', () => {
it('should accumulate total costs correctly', () => {
const state = AgentRuntime.createInitialState();
- const usage1: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const usage1: ModelUsage = createPricedModelUsage();
const usage2: ModelUsage = {
cost: 0.03,
@@ -216,20 +197,12 @@ describe('UsageCounter', () => {
totalTokens: 75,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage: usage1,
- provider: 'openai',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage2,
- provider: 'anthropic',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.total).toBe(0.08);
expect(result2.cost?.total).toBe(0.08);
@@ -239,19 +212,11 @@ describe('UsageCounter', () => {
it('should not accumulate cost when usage.cost is undefined', () => {
const state = AgentRuntime.createInitialState();
- const modelUsage: ModelUsage = {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createModelUsage();
- const { cost } = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage,
- provider: 'openai',
- usage: state.usage,
- });
+ const { cost } = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, modelUsage, state.usage),
+ );
expect(cost?.llm.byModel).toHaveLength(0);
expect(cost?.llm.total).toBe(0);
@@ -261,19 +226,11 @@ describe('UsageCounter', () => {
it('should increment apiCalls for each accumulation', () => {
const state = AgentRuntime.createInitialState();
- const modelUsage: ModelUsage = {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createModelUsage();
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage,
- provider: 'openai',
- usage: state.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, modelUsage, state.usage),
+ );
const result2 = UsageCounter.accumulateLLM({
cost: result1.cost,
model: 'gpt-4',
@@ -293,12 +250,7 @@ describe('UsageCounter', () => {
});
it('should auto-create usage and cost when not provided', () => {
- const modelUsage: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const modelUsage: ModelUsage = createPricedModelUsage();
const { usage, cost } = UsageCounter.accumulateLLM({
model: 'gpt-4',
@@ -491,12 +443,7 @@ describe('UsageCounter', () => {
it('should accumulate both LLM and tool costs correctly', () => {
const state = AgentRuntime.createInitialState();
- const llmUsage: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const llmUsage: ModelUsage = createPricedModelUsage();
const result1 = UsageCounter.accumulateLLM({
cost: state.cost,
@@ -524,12 +471,7 @@ describe('UsageCounter', () => {
it('should merge basic token counts', () => {
const state = AgentRuntime.createInitialState();
- const usage1: ModelUsage = {
- cost: 0.05,
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
+ const usage1: ModelUsage = createPricedModelUsage();
const usage2: ModelUsage = {
cost: 0.03,
@@ -538,20 +480,12 @@ describe('UsageCounter', () => {
totalTokens: 300,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage: usage1,
- provider: 'openai',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'gpt-4',
- modelUsage: usage2,
- provider: 'openai',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel[0].usage).toEqual({
cost: 0.08,
@@ -584,20 +518,12 @@ describe('UsageCounter', () => {
totalTokens: 225,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage1,
- provider: 'anthropic',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage2,
- provider: 'anthropic',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel[0].usage).toEqual({
cost: 0.08,
@@ -772,20 +698,12 @@ describe('UsageCounter', () => {
// totalInputTokens is missing
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'gpt-4',
- modelUsage: usage1,
- provider: 'openai',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'gpt-4',
- modelUsage: usage2,
- provider: 'openai',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createOpenAIUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel[0].usage).toEqual({
cost: 0.08,
@@ -839,20 +757,12 @@ describe('UsageCounter', () => {
totalTokens: 140,
};
- const result1 = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage1,
- provider: 'anthropic',
- usage: state.usage,
- });
- const result2 = UsageCounter.accumulateLLM({
- cost: result1.cost,
- model: 'claude-3-5-sonnet-20241022',
- modelUsage: usage2,
- provider: 'anthropic',
- usage: result1.usage,
- });
+ const result1 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(state.cost, usage1, state.usage),
+ );
+ const result2 = UsageCounter.accumulateLLM(
+ createAnthropicUsageInput(result1.cost, usage2, result1.usage),
+ );
expect(result2.cost?.llm.byModel[0].usage).toEqual({
acceptedPredictionTokens: 15,
diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.ts
index 4c7969c8733..dc0063631c7 100644
--- a/packages/agent-runtime/src/executors/resolveTools.test.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts
@@ -5,6 +5,16 @@ import type { AgentInstruction, AgentState } from '../types';
import { finish } from './finish';
import { resolveAbortedTools, resolveBlockedTools } from './resolveTools';
+const createBlockedInstruction = (
+ toolCall: ReturnType<typeof createToolCall>,
+): Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> => ({
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [toolCall],
+ },
+ type: 'resolve_blocked_tools',
+});
+
const createState = (overrides?: Partial<AgentState>): AgentState => ({
cost: {
calculatedAt: '2026-07-07T00:00:00.000Z',
@@ -115,13 +125,8 @@ describe('resolveTools executors', () => {
);
it('persists blocked tools as rejected tool messages and continues', async () => {
- const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
- payload: {
- parentMessageId: 'assistant-msg-1',
- toolsCalling: [createToolCall()],
- },
- type: 'resolve_blocked_tools',
- };
+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
+ createBlockedInstruction(createToolCall());
const result = await resolveBlockedTools(host)(instruction, createState());
@@ -203,13 +208,8 @@ describe('resolveTools executors', () => {
});
it('leaves the parent untouched for ordinary blocked tools', async () => {
- const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
- payload: {
- parentMessageId: 'assistant-msg-1',
- toolsCalling: [createToolCall()],
- },
- type: 'resolve_blocked_tools',
- };
+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
+ createBlockedInstruction(createToolCall());
const result = await resolveBlockedTools(host)(instruction, createState());
@@ -367,13 +367,8 @@ describe('resolveTools executors', () => {
const error = new Error('database went away');
createToolMessage.mockRejectedValueOnce(error);
- const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
- payload: {
- parentMessageId: 'assistant-msg-1',
- toolsCalling: [createToolCall()],
- },
- type: 'resolve_blocked_tools',
- };
+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =
+ createBlockedInstruction(createToolCall());
await expect(resolveBlockedTools(host)(instruction, createState())).rejects.toThrow(
'database went away',
diff --git a/packages/chat-adapter-qq/src/gateway.test.ts b/packages/chat-adapter-qq/src/gateway.test.ts
index 395f7b0f641..e0a052311ee 100644
--- a/packages/chat-adapter-qq/src/gateway.test.ts
+++ b/packages/chat-adapter-qq/src/gateway.test.ts
@@ -71,6 +71,18 @@ function createMockApi() {
} as any;
}
+const createReadyPayload = () => ({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+});
+
// ---- Tests ----
describe('QQGatewayConnection', () => {
@@ -120,17 +132,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
});
@@ -148,17 +150,7 @@ describe('QQGatewayConnection', () => {
expect(identifyPayload?.d.shard).toEqual([0, 1]);
// Complete the connection
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
});
@@ -189,17 +181,7 @@ describe('QQGatewayConnection', () => {
await vi.advanceTimersByTimeAsync(10);
// Complete READY
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Advance past jitter + interval to trigger heartbeat
@@ -219,17 +201,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Send heartbeat ACK
@@ -245,17 +217,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Simulate a message event
@@ -298,17 +260,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Server requests reconnect
@@ -324,17 +276,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Invalid session, cannot resume
@@ -348,17 +290,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
ws.close(4000, 'network reset');
@@ -375,17 +307,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
conn.close();
@@ -399,17 +321,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
abort.abort();
@@ -424,17 +336,7 @@ describe('QQGatewayConnection', () => {
ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
await vi.advanceTimersByTimeAsync(10);
- ws.simulateMessage({
- d: {
- session_id: 'sess_1',
- shard: [0, 1],
- user: { bot: true, id: 'bot_1', username: 'TestBot' },
- version: 1,
- },
- op: QQ_WS_OP_CODES.DISPATCH,
- s: 1,
- t: 'READY',
- });
+ ws.simulateMessage(createReadyPayload());
await connectPromise;
// Send another event with s=5
diff --git a/packages/context-engine/src/processors/__tests__/GroupOrchestrationFilter.test.ts b/packages/context-engine/src/processors/__tests__/GroupOrchestrationFilter.test.ts
index aec8d919a68..63cdce3dfd4 100644
--- a/packages/context-engine/src/processors/__tests__/GroupOrchestrationFilter.test.ts
+++ b/packages/context-engine/src/processors/__tests__/GroupOrchestrationFilter.test.ts
@@ -3,6 +3,21 @@ import { describe, expect, it } from 'vitest';
import type { PipelineContext } from '../../types';
import { GroupOrchestrationFilterProcessor } from '../GroupOrchestrationFilter';
+const createGroupManagementTool = (apiName: string, args: string, callId: string) => ({
+ apiName,
+ arguments: args,
+ id: callId,
+ identifier: 'lobe-group-management',
+});
+
+const createSupervisorOrchestrationMessage = () => ({
+ agentId: 'supervisor',
+ content: 'Orchestration message',
+ id: 'msg_1',
+ role: 'assistant',
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_1')],
+});
+
describe('GroupOrchestrationFilterProcessor', () => {
const createContext = (messages: any[]): PipelineContext => ({
initialState: { messages: [] },
@@ -31,12 +46,11 @@ describe('GroupOrchestrationFilterProcessor', () => {
id: 'msg_2',
role: 'assistant',
tools: [
- {
- apiName: 'broadcast',
- arguments: '{"agentIds": ["agent-a", "agent-b"], "instruction": "Please respond"}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
+ createGroupManagementTool(
+ 'broadcast',
+ '{"agentIds": ["agent-a", "agent-b"], "instruction": "Please respond"}',
+ 'call_1',
+ ),
],
},
{ content: 'Agent response', id: 'msg_3', role: 'assistant' },
@@ -58,12 +72,11 @@ describe('GroupOrchestrationFilterProcessor', () => {
id: 'msg_1',
role: 'assistant',
tools: [
- {
- apiName: 'speak',
- arguments: '{"agentId": "agent-a", "instruction": "Please help"}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
+ createGroupManagementTool(
+ 'speak',
+ '{"agentId": "agent-a", "instruction": "Please help"}',
+ 'call_1',
+ ),
],
},
]);
@@ -81,14 +94,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Executing task',
id: 'msg_1',
role: 'assistant',
- tools: [
- {
- apiName: 'executeTask',
- arguments: '{"task": "do something"}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('executeTask', '{"task": "do something"}', 'call_1')],
},
]);
@@ -106,12 +112,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
id: 'msg_1',
role: 'assistant',
tools: [
- {
- apiName: 'executeTasks',
- arguments: '{"tasks": ["task1", "task2"]}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
+ createGroupManagementTool('executeTasks', '{"tasks": ["task1", "task2"]}', 'call_1'),
],
},
]);
@@ -242,14 +243,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Participant response',
id: 'msg_1',
role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_1')],
},
{
agentId: 'agent-b',
@@ -294,14 +288,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Assistant without agentId',
id: 'msg_2',
role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_1')],
},
]);
@@ -317,22 +304,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
...defaultConfig,
enabled: false,
});
- const context = createContext([
- {
- agentId: 'supervisor',
- content: 'Orchestration message',
- id: 'msg_1',
- role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
- },
- ]);
+ const context = createContext([createSupervisorOrchestrationMessage()]);
const result = await processor.process(context);
@@ -345,20 +317,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
currentAgentId: 'supervisor', // Supervisor as current agent
});
const context = createContext([
- {
- agentId: 'supervisor',
- content: 'Orchestration message',
- id: 'msg_1',
- role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
- },
+ createSupervisorOrchestrationMessage(),
{
agentId: 'supervisor',
content: 'Tool result',
@@ -380,22 +339,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
it('should skip processing when no agentMap provided', async () => {
const processor = new GroupOrchestrationFilterProcessor({});
- const context = createContext([
- {
- agentId: 'supervisor',
- content: 'Orchestration message',
- id: 'msg_1',
- role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
- },
- ]);
+ const context = createContext([createSupervisorOrchestrationMessage()]);
const result = await processor.process(context);
@@ -407,22 +351,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
agentMap: defaultConfig.agentMap,
// No currentAgentId
});
- const context = createContext([
- {
- agentId: 'supervisor',
- content: 'Orchestration message',
- id: 'msg_1',
- role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
- },
- ]);
+ const context = createContext([createSupervisorOrchestrationMessage()]);
const result = await processor.process(context);
@@ -456,14 +385,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Default orchestration - should not be filtered',
id: 'msg_2',
role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_2',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_2')],
},
]);
@@ -484,28 +406,14 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Custom api name',
id: 'msg_1',
role: 'assistant',
- tools: [
- {
- apiName: 'customBroadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('customBroadcast', '{}', 'call_1')],
},
{
agentId: 'supervisor',
content: 'Default broadcast - should not be filtered',
id: 'msg_2',
role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_2',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_2')],
},
]);
@@ -602,14 +510,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Broadcast',
id: 'msg_1',
role: 'assistant',
- tools: [
- {
- apiName: 'broadcast',
- arguments: '{}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('broadcast', '{}', 'call_1')],
},
{
agentId: 'supervisor',
@@ -627,14 +528,7 @@ describe('GroupOrchestrationFilterProcessor', () => {
content: 'Speak',
id: 'msg_3',
role: 'assistant',
- tools: [
- {
- apiName: 'speak',
- arguments: '{}',
- id: 'call_2',
- identifier: 'lobe-group-management',
- },
- ],
+ tools: [createGroupManagementTool('speak', '{}', 'call_2')],
},
]);
@@ -668,12 +562,11 @@ describe('GroupOrchestrationFilterProcessor', () => {
id: 'msg_2',
role: 'assistant',
tools: [
- {
- apiName: 'broadcast',
- arguments: '{"agentIds": ["agent-a", "agent-b"], "instruction": "请给建议"}',
- id: 'call_1',
- identifier: 'lobe-group-management',
- },
+ createGroupManagementTool(
+ 'broadcast',
+ '{"agentIds": ["agent-a", "agent-b"], "instruction": "请给建议"}',
+ 'call_1',
+ ),
],
},
// 3. Broadcast tool result - SHOULD BE FILTERED
@@ -701,12 +594,11 @@ describe('GroupOrchestrationFilterProcessor', () => {
id: 'msg_7',
role: 'assistant',
tools: [
- {
- apiName: 'speak',
- arguments: '{"agentId": "agent-a", "instruction": "请总结"}',
- id: 'call_2',
- identifier: 'lobe-group-management',
- },
+ createGroupManagementTool(
+ 'speak',
+ '{"agentId": "agent-a", "instruction": "请总结"}',
+ 'call_2',
+ ),
],
},
// 8. Speak tool result - SHOULD BE FILTERED
diff --git a/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts b/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
index 40f8d825ef7..53accac55f1 100644
--- a/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
+++ b/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
+import { createContext } from '../../testUtils';
import { InputTemplateProcessor } from '../InputTemplate';
describe('InputTemplateProcessor', () => {
@@ -8,36 +9,22 @@ describe('InputTemplateProcessor', () => {
inputTemplate: 'Template: {{text}} - End',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Original user message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Original user message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '2',
- role: 'assistant',
- content: 'Assistant response',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: '2',
+ role: 'assistant',
+ content: 'Assistant response',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await processor.process(context);
@@ -49,29 +36,15 @@ describe('InputTemplateProcessor', () => {
it('should skip processing when no template is configured', async () => {
const processor = new InputTemplateProcessor({});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'User message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'User message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await processor.process(context);
@@ -84,29 +57,15 @@ describe('InputTemplateProcessor', () => {
inputTemplate: 'Static template content',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Original message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Original message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await processor.process(context);
@@ -121,29 +80,15 @@ describe('InputTemplateProcessor', () => {
inputTemplate: '<%- invalid javascript code %>',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'User message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'User message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
- },
- isAborted: false,
- };
+ ]);
const result = await processor.process(context);
@@ -159,29 +104,15 @@ describe('InputTemplateProcessor', () => {
inputTemplate: '{{text}} <%- throw new Error("Application error") %>',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'User message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'User message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await processor.process(context);
@@ -195,43 +126,29 @@ describe('InputTemplateProcessor', () => {
inputTemplate: 'Processed: {{text}}',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'User message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'User message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '2',
- role: 'assistant',
- content: 'Assistant message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '3',
- role: 'system',
- content: 'System message',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: '2',
+ role: 'assistant',
+ content: 'Assistant message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ {
+ id: '3',
+ role: 'system',
+ content: 'System message',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ]);
const result = await processor.process(context);
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 9104e95aa1e..e327e12e278 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -1,7 +1,7 @@
-import { createMediaFileRef } from '../../const/mediaRef';
import type { ChatAudioItem, ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
+import { createMediaFileRef } from '../../const/mediaRef';
import type { PipelineContext } from '../../types';
import { MessageContentProcessor, VISION_DOWNGRADE_PLACEHOLDER } from '../MessageContent';
@@ -27,17 +27,20 @@ const mockIsCanUseVision = vi.fn();
const mockIsCanUseVideo = vi.fn();
const mockIsCanUseAudio = vi.fn();
+const createVisionProcessor = (model: string, provider: string, fileContext = { enabled: false }) =>
+ new MessageContentProcessor({
+ model,
+ provider,
+ isCanUseVision: mockIsCanUseVision,
+ fileContext,
+ });
+
describe('MessageContentProcessor', () => {
describe('Image processing functionality', () => {
it('should downgrade image to placeholder text if model cannot use vision', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'any-model',
- provider: 'any-provider',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('any-model', 'any-provider');
const messages: UIChatMessage[] = [
{
@@ -60,12 +63,7 @@ describe('MessageContentProcessor', () => {
it('should process images if model can use vision', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -94,12 +92,7 @@ describe('MessageContentProcessor', () => {
it('should handle vision disabled scenario correctly', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'text-model',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('text-model', 'openai');
const messages: UIChatMessage[] = [
{
@@ -122,12 +115,7 @@ describe('MessageContentProcessor', () => {
it('should downgrade multiple images into separate placeholder lines', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'deepseek-chat',
- provider: 'deepseek',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('deepseek-chat', 'deepseek');
const messages: UIChatMessage[] = [
{
@@ -159,12 +147,7 @@ describe('MessageContentProcessor', () => {
it('should downgrade image_url parts in pre-existing array content when vision is disabled', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'deepseek-chat',
- provider: 'deepseek',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('deepseek-chat', 'deepseek');
const messages: UIChatMessage[] = [
{
@@ -192,12 +175,7 @@ describe('MessageContentProcessor', () => {
it('should preserve image_url parts in pre-existing array content when vision is supported', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4o',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4o', 'openai');
const messages: UIChatMessage[] = [
{
@@ -227,12 +205,7 @@ describe('MessageContentProcessor', () => {
it('should process local image URLs to base64', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -258,12 +231,7 @@ describe('MessageContentProcessor', () => {
it('should handle assistant message with imageList and content', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -290,12 +258,7 @@ describe('MessageContentProcessor', () => {
it('should handle assistant message with imageList but no content', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -323,12 +286,7 @@ describe('MessageContentProcessor', () => {
it('should convert tool message imageList to image_url parts when vision is supported', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -361,12 +319,7 @@ describe('MessageContentProcessor', () => {
it('should downgrade tool message images to placeholder when vision is not supported', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'any-model',
- provider: 'any-provider',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('any-model', 'any-provider');
const messages: UIChatMessage[] = [
{
@@ -396,12 +349,7 @@ describe('MessageContentProcessor', () => {
it('should keep AVIF as a media ref while forwarding supported tool images', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const avifUrl = 'https://example.com/f/image-id.avif?signature=secret';
const pngUrl = 'https://example.com/f/image-id.png?signature=secret';
const messages: UIChatMessage[] = [
@@ -447,12 +395,7 @@ describe('MessageContentProcessor', () => {
it('should remove uploaded image markdown URLs before adding a media ref', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'any-model',
- provider: 'any-provider',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('any-model', 'any-provider');
const imageUrl = 'https://example.com/f/image-id?signature=secret';
const messages: UIChatMessage[] = [
{
@@ -480,12 +423,7 @@ describe('MessageContentProcessor', () => {
it('should keep inline tool images as structured input only for vision models', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const dataUrl = 'data:image/png;base64,AAAA';
const messages: UIChatMessage[] = [
{
@@ -518,12 +456,7 @@ describe('MessageContentProcessor', () => {
it('should pass through tool messages without images unchanged', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -545,12 +478,7 @@ describe('MessageContentProcessor', () => {
it('should ignore image entries without a fetchable URL', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4-vision',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4-vision', 'openai');
const messages: UIChatMessage[] = [
{
@@ -583,12 +511,7 @@ describe('MessageContentProcessor', () => {
it('should add file context when enabled', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: true },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai', { enabled: true });
const messages: UIChatMessage[] = [
{
@@ -703,12 +626,7 @@ describe('MessageContentProcessor', () => {
it('should not add file context when disabled', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -744,12 +662,7 @@ describe('MessageContentProcessor', () => {
it('should not stringify array content when concatenating file context', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: true },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai', { enabled: true });
const messages: UIChatMessage[] = [
{
@@ -787,12 +700,7 @@ describe('MessageContentProcessor', () => {
describe('Reasoning/thinking content', () => {
it('should handle assistant messages with reasoning correctly', async () => {
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -825,12 +733,7 @@ describe('MessageContentProcessor', () => {
});
it('should serialize an explicit empty thinking string for signature-only reasoning', async () => {
- const processor = new MessageContentProcessor({
- model: 'claude-sonnet-5',
- provider: 'anthropic',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('claude-sonnet-5', 'anthropic');
const messages: UIChatMessage[] = [
{
@@ -869,12 +772,7 @@ describe('MessageContentProcessor', () => {
it('should update processing metadata correctly', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: true },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai', { enabled: true });
const messages: UIChatMessage[] = [
{
@@ -1237,12 +1135,7 @@ describe('MessageContentProcessor', () => {
it('should convert assistant message with metadata.isMultimodal to OpenAI format', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1276,12 +1169,7 @@ describe('MessageContentProcessor', () => {
});
it('should convert assistant message with reasoning.isMultimodal to plain text', async () => {
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1316,12 +1204,7 @@ describe('MessageContentProcessor', () => {
it('should handle both reasoning.isMultimodal and metadata.isMultimodal', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1364,12 +1247,7 @@ describe('MessageContentProcessor', () => {
});
it('should prioritize reasoning.signature over reasoning.isMultimodal', async () => {
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1402,12 +1280,7 @@ describe('MessageContentProcessor', () => {
});
it('should handle plain text when isMultimodal is true but content is not valid JSON', async () => {
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1432,12 +1305,7 @@ describe('MessageContentProcessor', () => {
it('should preserve thoughtSignature in multimodal content parts', async () => {
mockIsCanUseVision.mockReturnValue(true);
- const processor = new MessageContentProcessor({
- model: 'gpt-4',
- provider: 'openai',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('gpt-4', 'openai');
const messages: UIChatMessage[] = [
{
@@ -1481,12 +1349,7 @@ describe('MessageContentProcessor', () => {
it('should downgrade assistant multimodal image parts to placeholder text when vision is disabled', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'deepseek-chat',
- provider: 'deepseek',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('deepseek-chat', 'deepseek');
const messages: UIChatMessage[] = [
{
@@ -1519,12 +1382,7 @@ describe('MessageContentProcessor', () => {
it('should downgrade assistant legacy imageList to placeholder text when vision is disabled', async () => {
mockIsCanUseVision.mockReturnValue(false);
- const processor = new MessageContentProcessor({
- model: 'deepseek-chat',
- provider: 'deepseek',
- isCanUseVision: mockIsCanUseVision,
- fileContext: { enabled: false },
- });
+ const processor = createVisionProcessor('deepseek-chat', 'deepseek');
const messages: UIChatMessage[] = [
{
diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
index 3b4d474fd9a..fbe85d677b3 100644
--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
+import type { PipelineContext } from '../../types';
import {
buildContentPreview,
formatPlaceholderValues,
@@ -9,6 +10,23 @@ import {
renderPlaceholderTemplate,
} from '../PlaceholderVariables';
+const createContext = (messages: PipelineContext['messages']) => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: '',
+ tools: [],
+ },
+ messages,
+ metadata: {
+ model: 'gpt-4',
+ maxTokens: 4096,
+ },
+ isAborted: false,
+ executedProcessors: [],
+});
+
describe('PlaceholderVariablesProcessor', () => {
const mockVariableGenerators = {
date: () => '2023-12-25',
@@ -218,30 +236,15 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: mockVariableGenerators,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello {{username}}, today is {{date}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello {{username}}, today is {{date}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -261,37 +264,22 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: faultyGenerators,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: 'bad',
+ role: 'user',
+ content: 'This {{working}} but this {{error}} fails',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: 'bad',
- role: 'user',
- content: 'This {{working}} but this {{error}} fails',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: 'good',
- role: 'user',
- content: 'Only {{working}} here',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: 'good',
+ role: 'user',
+ content: 'Only {{working}} here',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -310,30 +298,15 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: undefined as unknown as Record<string, () => string>,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello {{username}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello {{username}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
await expect(processor.process(context)).rejects.toThrow(
/variableGenerators config is missing or invalid/,
@@ -345,30 +318,15 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: null as unknown as Record<string, () => string>,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello {{username}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello {{username}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
await expect(processor.process(context)).rejects.toThrow(
/variableGenerators config is missing or invalid/,
@@ -381,30 +339,15 @@ describe('PlaceholderVariablesProcessor', () => {
depth: 1,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Nested: {{nested}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Nested: {{nested}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -416,30 +359,15 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: mockVariableGenerators,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'No variables here',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'No variables here',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -452,30 +380,15 @@ describe('PlaceholderVariablesProcessor', () => {
});
const originalContent = 'Hello {{missing}}, see also {{alsoMissing}}';
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: originalContent,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: originalContent,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -495,30 +408,15 @@ describe('PlaceholderVariablesProcessor', () => {
{ type: 'text', text: 'Only {{missing}} here' },
{ type: 'image', image_url: 'https://example.com/x.png' },
];
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: arrayContent,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: arrayContent,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ ]);
const result = await processor.process(context);
@@ -532,44 +430,29 @@ describe('PlaceholderVariablesProcessor', () => {
variableGenerators: mockVariableGenerators,
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'No placeholders',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'No placeholders',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '2',
- role: 'user',
- content: 'Hello {{username}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '3',
- role: 'user',
- content: 'Only {{missing}}',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: '2',
+ role: 'user',
+ content: 'Hello {{username}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- executedProcessors: [],
- };
+ {
+ id: '3',
+ role: 'user',
+ content: 'Only {{missing}}',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ]);
const result = await processor.process(context);
diff --git a/packages/context-engine/src/providers/__tests__/SystemRoleInjector.test.ts b/packages/context-engine/src/providers/__tests__/SystemRoleInjector.test.ts
index 996167d5337..dc08190ac67 100644
--- a/packages/context-engine/src/providers/__tests__/SystemRoleInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/SystemRoleInjector.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
+import { createContext } from '../../testUtils';
import { SystemRoleInjector } from '../SystemRoleInjector';
describe('SystemRoleInjector', () => {
@@ -8,29 +9,15 @@ describe('SystemRoleInjector', () => {
systemRole: 'You are a helpful assistant.',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await provider.process(context);
@@ -55,29 +42,15 @@ describe('SystemRoleInjector', () => {
systemRole: '',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await provider.process(context);
@@ -91,36 +64,22 @@ describe('SystemRoleInjector', () => {
systemRole: 'You are a helpful assistant.',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ {
+ id: 'system-1',
+ role: 'system',
+ content: 'Existing system role',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- {
- id: 'system-1',
- role: 'system',
- content: 'Existing system role',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '1',
- role: 'user',
- content: 'Hello',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await provider.process(context);
@@ -139,37 +98,23 @@ describe('SystemRoleInjector', () => {
const beforeSystemDocContent =
'<agent_documents>\n<document title="rules">always reply in Chinese</document>\n</agent_documents>';
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
+ const context = createContext([
+ // Simulates the message that AgentDocumentBeforeSystemInjector unshifts
+ {
+ id: 'agent-doc-before-system-1700000000000',
+ role: 'system',
+ content: beforeSystemDocContent,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- messages: [
- // Simulates the message that AgentDocumentBeforeSystemInjector unshifts
- {
- id: 'agent-doc-before-system-1700000000000',
- role: 'system',
- content: beforeSystemDocContent,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- {
- id: '1',
- role: 'user',
- content: 'Hello',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await provider.process(context);
@@ -188,29 +133,15 @@ describe('SystemRoleInjector', () => {
systemRole: ' \n \t ',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [
- {
- id: '1',
- role: 'user',
- content: 'Hello',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- },
- ],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
+ const context = createContext([
+ {
+ id: '1',
+ role: 'user',
+ content: 'Hello',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
- isAborted: false,
- };
+ ]);
const result = await provider.process(context);
@@ -224,14 +155,9 @@ describe('SystemRoleInjector', () => {
systemRole: { nested: 'object' } as any,
});
- const context = {
- initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },
- messages: [
- { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
- ],
- metadata: { model: 'gpt-4', maxTokens: 4096 },
- isAborted: false,
- };
+ const context = createContext([
+ { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
+ ]);
const result = await provider.process(context);
@@ -245,14 +171,9 @@ describe('SystemRoleInjector', () => {
systemRole: ['system', 'role'] as any,
});
- const context = {
- initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },
- messages: [
- { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
- ],
- metadata: { model: 'gpt-4', maxTokens: 4096 },
- isAborted: false,
- };
+ const context = createContext([
+ { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
+ ]);
const result = await provider.process(context);
@@ -265,14 +186,9 @@ describe('SystemRoleInjector', () => {
systemRole: 42 as any,
});
- const context = {
- initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },
- messages: [
- { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
- ],
- metadata: { model: 'gpt-4', maxTokens: 4096 },
- isAborted: false,
- };
+ const context = createContext([
+ { id: '1', role: 'user', content: 'Hello', createdAt: Date.now(), updatedAt: Date.now() },
+ ]);
const result = await provider.process(context);
@@ -285,21 +201,7 @@ describe('SystemRoleInjector', () => {
systemRole: 'You are a helpful assistant.',
});
- const context = {
- initialState: {
- messages: [],
- model: 'gpt-4',
- provider: 'openai',
- systemRole: '',
- tools: [],
- },
- messages: [],
- metadata: {
- model: 'gpt-4',
- maxTokens: 4096,
- },
- isAborted: false,
- };
+ const context = createContext([]);
const result = await provider.process(context);
diff --git a/packages/context-engine/src/testUtils.ts b/packages/context-engine/src/testUtils.ts
new file mode 100644
index 00000000000..5575261bb71
--- /dev/null
+++ b/packages/context-engine/src/testUtils.ts
@@ -0,0 +1,17 @@
+import type { PipelineContext } from './types';
+
+export const createContext = (messages: PipelineContext['messages']): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: '',
+ tools: [],
+ },
+ messages,
+ metadata: {
+ model: 'gpt-4',
+ maxTokens: 4096,
+ },
+ isAborted: false,
+});
diff --git a/packages/conversation-flow/src/__tests__/dualForm.test.ts b/packages/conversation-flow/src/__tests__/dualForm.test.ts
index db58181868c..7570ebe31b7 100644
--- a/packages/conversation-flow/src/__tests__/dualForm.test.ts
+++ b/packages/conversation-flow/src/__tests__/dualForm.test.ts
@@ -3,6 +3,36 @@ import { describe, expect, it } from 'vitest';
import { parse } from '../parse';
import type { Message } from '../types/shared';
+const createFirstToolResult = (): Message => ({
+ content: 'r',
+ createdAt: 2,
+ id: 'a1__tc1',
+ parentId: 'a1',
+ role: 'tool',
+ tool_call_id: 'tc1',
+ updatedAt: 0,
+});
+
+const createFirstAssistantWithTool = (): Message => ({
+ agentId: 'agent-a',
+ content: 'step1',
+ createdAt: 1,
+ id: 'a1',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'x',
+ arguments: '{}',
+ id: 'tc1',
+ identifier: 'x',
+ result_msg_id: 'a1__tc1',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+});
+
/**
* Dual-form message-chain reader (phase 1)
*
@@ -154,34 +184,8 @@ describe('dual-form message chain', () => {
// a2 attaches old-style (under a1's tool); a3 attaches new-style (under a2)
const msgs: Message[] = [
{ content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
- {
- agentId: 'agent-a',
- content: 'step1',
- createdAt: 1,
- id: 'a1',
- parentId: 'u1',
- role: 'assistant',
- tools: [
- {
- apiName: 'x',
- arguments: '{}',
- id: 'tc1',
- identifier: 'x',
- result_msg_id: 'a1__tc1',
- type: 'default',
- },
- ],
- updatedAt: 0,
- },
- {
- content: 'r',
- createdAt: 2,
- id: 'a1__tc1',
- parentId: 'a1',
- role: 'tool',
- tool_call_id: 'tc1',
- updatedAt: 0,
- },
+ createFirstAssistantWithTool(),
+ createFirstToolResult(),
{
agentId: 'agent-a',
content: 'step2',
@@ -326,15 +330,7 @@ describe('dual-form message chain', () => {
],
updatedAt: 0,
},
- {
- content: 'r',
- createdAt: 2,
- id: 'a1__tc1',
- parentId: 'a1',
- role: 'tool',
- tool_call_id: 'tc1',
- updatedAt: 0,
- },
+ createFirstToolResult(),
// two regenerated continuations, both children of a1 (siblings of the tool)
{
agentId: 'agent-a',
@@ -381,34 +377,8 @@ describe('dual-form message chain', () => {
it('⑦ tool-anchored duplicate continuation omits the unselected sibling', () => {
const messages: Message[] = [
{ content: 'q', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
- {
- agentId: 'agent-a',
- content: 'step1',
- createdAt: 1,
- id: 'a1',
- parentId: 'u1',
- role: 'assistant',
- tools: [
- {
- apiName: 'x',
- arguments: '{}',
- id: 'tc1',
- identifier: 'x',
- result_msg_id: 'a1__tc1',
- type: 'default',
- },
- ],
- updatedAt: 0,
- },
- {
- content: 'r',
- createdAt: 2,
- id: 'a1__tc1',
- parentId: 'a1',
- role: 'tool',
- tool_call_id: 'tc1',
- updatedAt: 0,
- },
+ createFirstAssistantWithTool(),
+ createFirstToolResult(),
{
agentId: 'agent-a',
content: 'duplicate output',
@@ -489,15 +459,7 @@ describe('dual-form message chain', () => {
],
updatedAt: 0,
},
- {
- content: 'r',
- createdAt: 2,
- id: 'a1__tc1',
- parentId: 'a1',
- role: 'tool',
- tool_call_id: 'tc1',
- updatedAt: 0,
- },
+ createFirstToolResult(),
{
agentId: 'agent-a',
content: 'task 1',
diff --git a/packages/conversation-flow/src/__tests__/indexing.test.ts b/packages/conversation-flow/src/__tests__/indexing.test.ts
index 38ac83aa250..82f64df3941 100644
--- a/packages/conversation-flow/src/__tests__/indexing.test.ts
+++ b/packages/conversation-flow/src/__tests__/indexing.test.ts
@@ -3,25 +3,42 @@ import { describe, expect, it } from 'vitest';
import { buildHelperMaps } from '../indexing';
import type { Message, MessageGroupMetadata } from '../types';
+const createMessage = (
+ id: string,
+ role: Message['role'],
+ content: string,
+ createdAt: number,
+ updatedAt: number,
+): Message => ({
+ content,
+ createdAt,
+ id,
+ role,
+ updatedAt,
+});
+
+const createChildMessage = (
+ id: string,
+ parentId: string,
+ role: Message['role'],
+ content: string,
+ createdAt: number,
+ updatedAt: number,
+): Message => ({
+ content,
+ createdAt,
+ id,
+ parentId,
+ role,
+ updatedAt,
+});
+
describe('buildHelperMaps', () => {
describe('messageMap', () => {
it('should build messageMap for O(1) access', () => {
const messages: Message[] = [
- {
- content: 'Hello',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Hi there',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Hello', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Hi there', 2000, 2000),
];
const result = buildHelperMaps(messages);
@@ -38,15 +55,7 @@ describe('buildHelperMaps', () => {
});
it('should handle single message', () => {
- const messages: Message[] = [
- {
- content: 'Single message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Single message', 1000, 1000)];
const result = buildHelperMaps(messages);
@@ -58,29 +67,9 @@ describe('buildHelperMaps', () => {
describe('childrenMap', () => {
it('should build childrenMap for parent-child relationships', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Child 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Child 2',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 3000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Child 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-1', 'assistant', 'Child 2', 3000, 3000),
];
const result = buildHelperMaps(messages);
@@ -91,20 +80,8 @@ describe('buildHelperMaps', () => {
it('should handle messages with no parent (root messages)', () => {
const messages: Message[] = [
- {
- content: 'Root 1',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Root 2',
- createdAt: 2000,
- id: 'msg-2',
- role: 'user',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Root 1', 1000, 1000),
+ createMessage('msg-2', 'user', 'Root 2', 2000, 2000),
];
const result = buildHelperMaps(messages);
@@ -114,37 +91,10 @@ describe('buildHelperMaps', () => {
it('should handle deeply nested parent-child relationships', () => {
const messages: Message[] = [
- {
- content: 'Level 0',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Level 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Level 2',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Level 3',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-3',
- role: 'assistant',
- updatedAt: 4000,
- },
+ createMessage('msg-1', 'user', 'Level 0', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Level 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Level 2', 3000, 3000),
+ createChildMessage('msg-4', 'msg-3', 'assistant', 'Level 3', 4000, 4000),
];
const result = buildHelperMaps(messages);
@@ -157,45 +107,11 @@ describe('buildHelperMaps', () => {
it('should handle branching conversations', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Branch 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Branch 2',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 3000,
- },
- {
- content: 'Sub-branch 1',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 4000,
- },
- {
- content: 'Sub-branch 2',
- createdAt: 5000,
- id: 'msg-5',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 5000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Branch 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-1', 'assistant', 'Branch 2', 3000, 3000),
+ createChildMessage('msg-4', 'msg-2', 'user', 'Sub-branch 1', 4000, 4000),
+ createChildMessage('msg-5', 'msg-2', 'user', 'Sub-branch 2', 5000, 5000),
];
const result = buildHelperMaps(messages);
@@ -209,13 +125,7 @@ describe('buildHelperMaps', () => {
describe('threadMap', () => {
it('should build threadMap for messages with threadId', () => {
const messages: Message[] = [
- {
- content: 'Main message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
+ createMessage('msg-1', 'user', 'Main message', 1000, 1000),
{
content: 'Thread message 1',
createdAt: 2000,
@@ -280,13 +190,7 @@ describe('buildHelperMaps', () => {
it('should not include messages without threadId in threadMap', () => {
const messages: Message[] = [
- {
- content: 'No thread',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
+ createMessage('msg-1', 'user', 'No thread', 1000, 1000),
{
content: 'With thread',
createdAt: 2000,
@@ -305,20 +209,8 @@ describe('buildHelperMaps', () => {
it('should handle empty threadMap when no messages have threadId', () => {
const messages: Message[] = [
- {
- content: 'Message 1',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Message 2',
- createdAt: 2000,
- id: 'msg-2',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Message 1', 1000, 1000),
+ createMessage('msg-2', 'assistant', 'Message 2', 2000, 2000),
];
const result = buildHelperMaps(messages);
@@ -329,15 +221,7 @@ describe('buildHelperMaps', () => {
describe('messageGroupMap', () => {
it('should build messageGroupMap from provided metadata', () => {
- const messages: Message[] = [
- {
- content: 'Message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Message', 1000, 1000)];
const messageGroups: MessageGroupMetadata[] = [
{
@@ -358,15 +242,7 @@ describe('buildHelperMaps', () => {
});
it('should handle empty messageGroupMap when no metadata provided', () => {
- const messages: Message[] = [
- {
- content: 'Message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Message', 1000, 1000)];
const result = buildHelperMaps(messages);
@@ -374,15 +250,7 @@ describe('buildHelperMaps', () => {
});
it('should handle empty messageGroupMap when empty array provided', () => {
- const messages: Message[] = [
- {
- content: 'Message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Message', 1000, 1000)];
const result = buildHelperMaps(messages, []);
@@ -436,13 +304,7 @@ describe('buildHelperMaps', () => {
role: 'compressedGroup',
updatedAt: 1000,
} as any,
- {
- content: 'User message',
- createdAt: 2000,
- id: 'msg-4',
- role: 'user',
- updatedAt: 2000,
- },
+ createMessage('msg-4', 'user', 'User message', 2000, 2000),
{
content: 'Response to user',
createdAt: 3000,
@@ -479,22 +341,8 @@ describe('buildHelperMaps', () => {
role: 'compressedGroup',
updatedAt: 2000,
} as any,
- {
- content: 'Child of first group',
- createdAt: 3000,
- id: 'msg-new-1',
- parentId: 'msg-a',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Child of second group',
- createdAt: 4000,
- id: 'msg-new-2',
- parentId: 'msg-b',
- role: 'assistant',
- updatedAt: 4000,
- },
+ createChildMessage('msg-new-1', 'msg-a', 'user', 'Child of first group', 3000, 3000),
+ createChildMessage('msg-new-2', 'msg-b', 'assistant', 'Child of second group', 4000, 4000),
];
const result = buildHelperMaps(messages);
@@ -528,14 +376,14 @@ describe('buildHelperMaps', () => {
role: 'compressedGroup',
updatedAt: 1000,
} as any,
- {
- content: 'Follow-up after compression',
- createdAt: 2000,
- id: 'msg-new',
- parentId: 'msg-hidden-2',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createChildMessage(
+ 'msg-new',
+ 'msg-hidden-2',
+ 'assistant',
+ 'Follow-up after compression',
+ 2000,
+ 2000,
+ ),
];
const result = buildHelperMaps(messages);
@@ -572,14 +420,14 @@ describe('buildHelperMaps', () => {
role: 'compressedGroup',
updatedAt: 1000,
} as any,
- {
- content: 'Continue searching',
- createdAt: 2000,
- id: 'msg-new',
- parentId: 'msg-tool-result-1',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createChildMessage(
+ 'msg-new',
+ 'msg-tool-result-1',
+ 'assistant',
+ 'Continue searching',
+ 2000,
+ 2000,
+ ),
];
const result = buildHelperMaps(messages);
@@ -592,13 +440,7 @@ describe('buildHelperMaps', () => {
describe('integration scenarios', () => {
it('should build all maps correctly in complex conversation', () => {
const messages: Message[] = [
- {
- content: 'Root message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
+ createMessage('msg-1', 'user', 'Root message', 1000, 1000),
{
content: 'Assistant response',
createdAt: 2000,
@@ -617,14 +459,7 @@ describe('buildHelperMaps', () => {
threadId: 'thread-1',
updatedAt: 3000,
},
- {
- content: 'Branch message',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 4000,
- },
+ createChildMessage('msg-4', 'msg-1', 'assistant', 'Branch message', 4000, 4000),
];
const messageGroups: MessageGroupMetadata[] = [
diff --git a/packages/conversation-flow/src/__tests__/structuring.test.ts b/packages/conversation-flow/src/__tests__/structuring.test.ts
index 49b76522415..271fed2fcb0 100644
--- a/packages/conversation-flow/src/__tests__/structuring.test.ts
+++ b/packages/conversation-flow/src/__tests__/structuring.test.ts
@@ -4,18 +4,40 @@ import { buildHelperMaps } from '../indexing';
import { buildIdTree } from '../structuring';
import type { Message } from '../types';
+const createMessage = (
+ id: string,
+ role: Message['role'],
+ content: string,
+ createdAt: number,
+ updatedAt: number,
+): Message => ({
+ content,
+ createdAt,
+ id,
+ role,
+ updatedAt,
+});
+
+const createChildMessage = (
+ id: string,
+ parentId: string,
+ role: Message['role'],
+ content: string,
+ createdAt: number,
+ updatedAt: number,
+): Message => ({
+ content,
+ createdAt,
+ id,
+ parentId,
+ role,
+ updatedAt,
+});
+
describe('buildIdTree', () => {
describe('basic tree building', () => {
it('should build tree from single root message', () => {
- const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Root', 1000, 1000)];
const helperMaps = buildHelperMaps(messages);
const result = buildIdTree(helperMaps);
@@ -29,29 +51,9 @@ describe('buildIdTree', () => {
it('should build tree with linear conversation', () => {
const messages: Message[] = [
- {
- content: 'Message 1',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Message 2',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Message 3',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
+ createMessage('msg-1', 'user', 'Message 1', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Message 2', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Message 3', 3000, 3000),
];
const helperMaps = buildHelperMaps(messages);
@@ -67,20 +69,8 @@ describe('buildIdTree', () => {
it('should handle multiple root messages', () => {
const messages: Message[] = [
- {
- content: 'Root 1',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Root 2',
- createdAt: 2000,
- id: 'msg-2',
- role: 'user',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Root 1', 1000, 1000),
+ createMessage('msg-2', 'user', 'Root 2', 2000, 2000),
];
const helperMaps = buildHelperMaps(messages);
@@ -95,29 +85,9 @@ describe('buildIdTree', () => {
describe('branching conversations', () => {
it('should build tree with branches', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Branch 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Branch 2',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 3000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Branch 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-1', 'assistant', 'Branch 2', 3000, 3000),
];
const helperMaps = buildHelperMaps(messages);
@@ -132,37 +102,10 @@ describe('buildIdTree', () => {
it('should handle nested branches', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Branch 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Branch 1.1',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Branch 1.2',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 4000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Branch 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Branch 1.1', 3000, 3000),
+ createChildMessage('msg-4', 'msg-2', 'user', 'Branch 1.2', 4000, 4000),
];
const helperMaps = buildHelperMaps(messages);
@@ -177,37 +120,10 @@ describe('buildIdTree', () => {
it('should handle deeply nested tree (4 levels)', () => {
const messages: Message[] = [
- {
- content: 'Level 0',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Level 1',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Level 2',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Level 3',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-3',
- role: 'assistant',
- updatedAt: 4000,
- },
+ createMessage('msg-1', 'user', 'Level 0', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Level 1', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Level 2', 3000, 3000),
+ createChildMessage('msg-4', 'msg-3', 'assistant', 'Level 3', 4000, 4000),
];
const helperMaps = buildHelperMaps(messages);
@@ -233,21 +149,8 @@ describe('buildIdTree', () => {
describe('thread handling', () => {
it('should exclude messages with threadId from main tree', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Main flow',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Main flow', 2000, 2000),
{
content: 'Thread message',
createdAt: 3000,
@@ -270,13 +173,7 @@ describe('buildIdTree', () => {
it('should exclude root messages with threadId', () => {
const messages: Message[] = [
- {
- content: 'Main root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
+ createMessage('msg-1', 'user', 'Main root', 1000, 1000),
{
content: 'Thread root',
createdAt: 2000,
@@ -296,29 +193,9 @@ describe('buildIdTree', () => {
it('should filter out thread children at any level', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Main child',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Main grandchild',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Main child', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Main grandchild', 3000, 3000),
{
content: 'Thread grandchild',
createdAt: 4000,
@@ -349,15 +226,7 @@ describe('buildIdTree', () => {
});
it('should handle messages with no children', () => {
- const messages: Message[] = [
- {
- content: 'Lone message',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- ];
+ const messages: Message[] = [createMessage('msg-1', 'user', 'Lone message', 1000, 1000)];
const helperMaps = buildHelperMaps(messages);
const result = buildIdTree(helperMaps);
@@ -371,14 +240,7 @@ describe('buildIdTree', () => {
it('should handle messages with missing parent references', () => {
const messages: Message[] = [
- {
- content: 'Orphan',
- createdAt: 1000,
- id: 'msg-1',
- parentId: 'non-existent',
- role: 'user',
- updatedAt: 1000,
- },
+ createChildMessage('msg-1', 'non-existent', 'user', 'Orphan', 1000, 1000),
];
const helperMaps = buildHelperMaps(messages);
@@ -423,53 +285,12 @@ describe('buildIdTree', () => {
describe('complex scenarios', () => {
it('should build tree with mixed branches and linear paths', () => {
const messages: Message[] = [
- {
- content: 'Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Branch A',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
- {
- content: 'Branch A -> Child',
- createdAt: 3000,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Branch B',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 4000,
- },
- {
- content: 'Branch B -> Child 1',
- createdAt: 5000,
- id: 'msg-5',
- parentId: 'msg-4',
- role: 'user',
- updatedAt: 5000,
- },
- {
- content: 'Branch B -> Child 2',
- createdAt: 6000,
- id: 'msg-6',
- parentId: 'msg-4',
- role: 'user',
- updatedAt: 6000,
- },
+ createMessage('msg-1', 'user', 'Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Branch A', 2000, 2000),
+ createChildMessage('msg-3', 'msg-2', 'user', 'Branch A -> Child', 3000, 3000),
+ createChildMessage('msg-4', 'msg-1', 'assistant', 'Branch B', 4000, 4000),
+ createChildMessage('msg-5', 'msg-4', 'user', 'Branch B -> Child 1', 5000, 5000),
+ createChildMessage('msg-6', 'msg-4', 'user', 'Branch B -> Child 2', 6000, 6000),
];
const helperMaps = buildHelperMaps(messages);
@@ -494,37 +315,11 @@ describe('buildIdTree', () => {
it('should handle multiple root trees', () => {
const messages: Message[] = [
// Tree 1
- {
- content: 'Tree 1 Root',
- createdAt: 1000,
- id: 'msg-1',
- role: 'user',
- updatedAt: 1000,
- },
- {
- content: 'Tree 1 Child',
- createdAt: 2000,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 2000,
- },
+ createMessage('msg-1', 'user', 'Tree 1 Root', 1000, 1000),
+ createChildMessage('msg-2', 'msg-1', 'assistant', 'Tree 1 Child', 2000, 2000),
// Tree 2
- {
- content: 'Tree 2 Root',
- createdAt: 3000,
- id: 'msg-3',
- role: 'user',
- updatedAt: 3000,
- },
- {
- content: 'Tree 2 Child',
- createdAt: 4000,
- id: 'msg-4',
- parentId: 'msg-3',
- role: 'assistant',
- updatedAt: 4000,
- },
+ createMessage('msg-3', 'user', 'Tree 2 Root', 3000, 3000),
+ createChildMessage('msg-4', 'msg-3', 'assistant', 'Tree 2 Child', 4000, 4000),
];
const helperMaps = buildHelperMaps(messages);
diff --git a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts
index a86be33f5d6..3623615dec1 100644
--- a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts
@@ -3,39 +3,45 @@ import { describe, expect, it, vi } from 'vitest';
import type { IdNode, Message } from '../../types';
import { BranchResolver } from '../BranchResolver';
+const createUserMessage = (): Message => ({
+ content: 'test',
+ createdAt: 0,
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: 0,
+});
+
+const createBranchNode = (): IdNode => ({
+ children: [
+ { children: [], id: 'msg-2' },
+ { children: [], id: 'msg-3' },
+ ],
+ id: 'msg-1',
+});
+
+const createMessageWithActiveBranch = (activeBranchIndex: number): Message => ({
+ content: 'test',
+ createdAt: 0,
+ id: 'msg-1',
+ metadata: { activeBranchIndex },
+ role: 'user',
+ updatedAt: 0,
+});
+
describe('BranchResolver', () => {
const resolver = new BranchResolver();
describe('getActiveBranchId', () => {
it('should return branch by activeBranchIndex from metadata when present', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- metadata: { activeBranchIndex: 1 },
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createMessageWithActiveBranch(1);
- const idNode: IdNode = {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- };
+ const idNode: IdNode = createBranchNode();
expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-3');
});
it('should infer active branch from which branch has children', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createUserMessage();
const idNode: IdNode = {
children: [
@@ -49,21 +55,9 @@ describe('BranchResolver', () => {
});
it('should default to first branch when no hints available', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createUserMessage();
- const idNode: IdNode = {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- };
+ const idNode: IdNode = createBranchNode();
expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-2');
});
@@ -78,13 +72,7 @@ describe('BranchResolver', () => {
updatedAt: 0,
};
- const idNode: IdNode = {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- };
+ const idNode: IdNode = createBranchNode();
// When activeBranchIndex === children.length, it's an optimistic update
// The branch hasn't been created yet, so return undefined
@@ -101,13 +89,7 @@ describe('BranchResolver', () => {
updatedAt: 0,
};
- const idNode: IdNode = {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- };
+ const idNode: IdNode = createBranchNode();
// activeBranchIndex > children.length should be ignored, fallback to default
expect(resolver.getActiveBranchId(message, idNode)).toBe('msg-2');
@@ -116,14 +98,7 @@ describe('BranchResolver', () => {
describe('getActiveBranchIdFromMetadata', () => {
it('should return branch by activeBranchIndex from metadata', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- metadata: { activeBranchIndex: 1 },
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createMessageWithActiveBranch(1);
const childIds = ['msg-2', 'msg-3'];
const childrenMap = new Map<string | null, string[]>();
@@ -132,13 +107,7 @@ describe('BranchResolver', () => {
});
it('should infer active branch from which child has descendants', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createUserMessage();
const childIds = ['msg-2', 'msg-3'];
const childrenMap = new Map<string | null, string[]>([
@@ -151,13 +120,7 @@ describe('BranchResolver', () => {
it('should ignore newer user descendants from threads when selecting the active branch', () => {
const messages: Message[] = [
- {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createUserMessage(),
{
content: 'old branch',
createdAt: 1,
@@ -210,13 +173,7 @@ describe('BranchResolver', () => {
});
it('should default to first child when no hints available', () => {
- const message: Message = {
- content: 'test',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- };
+ const message: Message = createUserMessage();
const childIds = ['msg-2', 'msg-3'];
const childrenMap = new Map<string | null, string[]>();
diff --git a/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
index 88ebe38c95c..4c43c25a42b 100644
--- a/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/ContextTreeBuilder.test.ts
@@ -5,6 +5,38 @@ import { BranchResolver } from '../BranchResolver';
import { ContextTreeBuilder } from '../ContextTreeBuilder';
import { MessageCollector } from '../MessageCollector';
+const createMessage = (id: string, role: Message['role'], content: string): Message => ({
+ content,
+ createdAt: 0,
+ id,
+ role,
+ updatedAt: 0,
+});
+
+const createMessageWithMetadata = (
+ id: string,
+ role: Message['role'],
+ content: string,
+ metadata: NonNullable<Message['metadata']>,
+): Message => ({
+ content,
+ createdAt: 0,
+ id,
+ metadata,
+ role,
+ updatedAt: 0,
+});
+
+const createBranchNodes = (): IdNode[] => [
+ {
+ children: [
+ { children: [], id: 'msg-2' },
+ { children: [], id: 'msg-3' },
+ ],
+ id: 'msg-1',
+ },
+];
+
describe('ContextTreeBuilder', () => {
const createBuilder = (
messageMap: Map<string, Message>,
@@ -29,26 +61,8 @@ describe('ContextTreeBuilder', () => {
describe('transformAll', () => {
it('should transform regular message nodes', () => {
const messageMap = new Map<string, Message>([
- [
- 'msg-1',
- {
- content: 'Hello',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
- ],
- [
- 'msg-2',
- {
- content: 'Hi',
- createdAt: 0,
- id: 'msg-2',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
+ ['msg-1', createMessage('msg-1', 'user', 'Hello')],
+ ['msg-2', createMessage('msg-2', 'assistant', 'Hi')],
]);
const builder = createBuilder(messageMap);
@@ -68,49 +82,13 @@ describe('ContextTreeBuilder', () => {
it('should create branch node for multiple children', () => {
const messageMap = new Map<string, Message>([
- [
- 'msg-1',
- {
- content: 'Hello',
- createdAt: 0,
- id: 'msg-1',
- metadata: { activeBranchIndex: 0 },
- role: 'user',
- updatedAt: 0,
- },
- ],
- [
- 'msg-2',
- {
- content: 'Response 1',
- createdAt: 0,
- id: 'msg-2',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
- [
- 'msg-3',
- {
- content: 'Response 2',
- createdAt: 0,
- id: 'msg-3',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
+ ['msg-1', createMessageWithMetadata('msg-1', 'user', 'Hello', { activeBranchIndex: 0 })],
+ ['msg-2', createMessage('msg-2', 'assistant', 'Response 1')],
+ ['msg-3', createMessage('msg-3', 'assistant', 'Response 2')],
]);
const builder = createBuilder(messageMap);
- const idNodes: IdNode[] = [
- {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- },
- ];
+ const idNodes: IdNode[] = createBranchNodes();
const result = builder.transformAll(idNodes);
@@ -145,16 +123,7 @@ describe('ContextTreeBuilder', () => {
updatedAt: 0,
},
],
- [
- 'tool-1',
- {
- content: 'Tool result',
- createdAt: 0,
- id: 'tool-1',
- role: 'tool',
- updatedAt: 0,
- },
- ],
+ ['tool-1', createMessage('tool-1', 'tool', 'Tool result')],
]);
const builder = createBuilder(messageMap);
@@ -222,50 +191,16 @@ describe('ContextTreeBuilder', () => {
it('should create compare node from user message metadata', () => {
const messageMap = new Map<string, Message>([
- [
- 'msg-1',
- {
- content: 'User message',
- createdAt: 0,
- id: 'msg-1',
- metadata: { compare: true },
- role: 'user',
- updatedAt: 0,
- },
- ],
+ ['msg-1', createMessageWithMetadata('msg-1', 'user', 'User message', { compare: true })],
[
'msg-2',
- {
- content: 'Assistant 1',
- createdAt: 0,
- id: 'msg-2',
- metadata: { activeColumn: true },
- role: 'assistant',
- updatedAt: 0,
- },
- ],
- [
- 'msg-3',
- {
- content: 'Assistant 2',
- createdAt: 0,
- id: 'msg-3',
- role: 'assistant',
- updatedAt: 0,
- },
+ createMessageWithMetadata('msg-2', 'assistant', 'Assistant 1', { activeColumn: true }),
],
+ ['msg-3', createMessage('msg-3', 'assistant', 'Assistant 2')],
]);
const builder = createBuilder(messageMap);
- const idNodes: IdNode[] = [
- {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- },
- ];
+ const idNodes: IdNode[] = createBranchNodes();
const result = builder.transformAll(idNodes);
@@ -313,38 +248,12 @@ describe('ContextTreeBuilder', () => {
updatedAt: 0,
},
],
- [
- 'msg-2',
- {
- content: 'Response 1',
- createdAt: 0,
- id: 'msg-2',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
- [
- 'msg-3',
- {
- content: 'Response 2',
- createdAt: 0,
- id: 'msg-3',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
+ ['msg-2', createMessage('msg-2', 'assistant', 'Response 1')],
+ ['msg-3', createMessage('msg-3', 'assistant', 'Response 2')],
]);
const builder = createBuilder(messageMap);
- const idNodes: IdNode[] = [
- {
- children: [
- { children: [], id: 'msg-2' },
- { children: [], id: 'msg-3' },
- ],
- id: 'msg-1',
- },
- ];
+ const idNodes: IdNode[] = createBranchNodes();
const result = builder.transformAll(idNodes);
@@ -362,48 +271,13 @@ describe('ContextTreeBuilder', () => {
it('should continue with active column children in compare mode', () => {
const messageMap = new Map<string, Message>([
- [
- 'msg-1',
- {
- content: 'User',
- createdAt: 0,
- id: 'msg-1',
- metadata: { compare: true },
- role: 'user',
- updatedAt: 0,
- },
- ],
+ ['msg-1', createMessageWithMetadata('msg-1', 'user', 'User', { compare: true })],
[
'msg-2',
- {
- content: 'Assistant 1',
- createdAt: 0,
- id: 'msg-2',
- metadata: { activeColumn: true },
- role: 'assistant',
- updatedAt: 0,
- },
- ],
- [
- 'msg-3',
- {
- content: 'Assistant 2',
- createdAt: 0,
- id: 'msg-3',
- role: 'assistant',
- updatedAt: 0,
- },
- ],
- [
- 'msg-4',
- {
- content: 'Follow-up',
- createdAt: 0,
- id: 'msg-4',
- role: 'user',
- updatedAt: 0,
- },
+ createMessageWithMetadata('msg-2', 'assistant', 'Assistant 1', { activeColumn: true }),
],
+ ['msg-3', createMessage('msg-3', 'assistant', 'Assistant 2')],
+ ['msg-4', createMessage('msg-4', 'user', 'Follow-up')],
]);
const builder = createBuilder(messageMap);
diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
index c3e03704fcf..c76a4b4d68e 100644
--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
@@ -7,6 +7,28 @@ import { FlatListBuilder } from '../FlatListBuilder';
import { MessageCollector } from '../MessageCollector';
import { MessageTransformer } from '../MessageTransformer';
+const createRootMessage = (id: string, role: Message['role'], content: string): Message => ({
+ content,
+ createdAt: 0,
+ id,
+ role,
+ updatedAt: 0,
+});
+
+const createReplyMessage = (
+ id: string,
+ parentId: string,
+ role: Message['role'],
+ content: string,
+): Message => ({
+ content,
+ createdAt: 0,
+ id,
+ parentId,
+ role,
+ updatedAt: 0,
+});
+
describe('FlatListBuilder', () => {
const createBuilder = (
messages: Message[],
@@ -52,21 +74,8 @@ describe('FlatListBuilder', () => {
describe('flatten', () => {
it('should flatten simple message chain', () => {
const messages: Message[] = [
- {
- content: 'Hello',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: 'Hi',
- createdAt: 0,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'Hello'),
+ createReplyMessage('msg-2', 'msg-1', 'assistant', 'Hi'),
];
const builder = createBuilder(messages);
@@ -251,13 +260,7 @@ describe('FlatListBuilder', () => {
it('should create assistant group virtual message', () => {
const messages: Message[] = [
- {
- content: 'Request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'Request'),
{
content: 'Using tool',
createdAt: 0,
@@ -295,13 +298,7 @@ describe('FlatListBuilder', () => {
// Kimi Code only learns model/provider at run end (stamped on the LAST
// step's assistant via turn_metadata); the group spreads the first row.
const messages: Message[] = [
- {
- content: 'Request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'Request'),
{
content: 'Using tool',
createdAt: 0,
@@ -347,13 +344,7 @@ describe('FlatListBuilder', () => {
it('should keep the first assistant model/provider when already set', () => {
const messages: Message[] = [
- {
- content: 'Request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'Request'),
{
content: 'Using tool',
createdAt: 0,
@@ -398,13 +389,7 @@ describe('FlatListBuilder', () => {
it('should leave group model/provider undefined when no assistant carries one', () => {
const messages: Message[] = [
- {
- content: 'Request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'Request'),
{
content: 'Using tool',
createdAt: 0,
@@ -425,14 +410,7 @@ describe('FlatListBuilder', () => {
tool_call_id: 'tool-1',
updatedAt: 0,
},
- {
- content: 'Done',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'tool-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'tool-1', 'assistant', 'Done'),
];
const builder = createBuilder(messages);
@@ -445,7 +423,7 @@ describe('FlatListBuilder', () => {
it('keeps a terminal finish type on its originating assistant block', () => {
const messages: Message[] = [
- { content: 'Request', createdAt: 0, id: 'user-1', role: 'user', updatedAt: 0 },
+ createRootMessage('user-1', 'user', 'Request'),
{
content: 'Using tool',
createdAt: 1,
@@ -497,22 +475,8 @@ describe('FlatListBuilder', () => {
role: 'user',
updatedAt: 0,
},
- {
- content: 'Branch 1',
- createdAt: 0,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'Branch 2',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createReplyMessage('msg-2', 'msg-1', 'assistant', 'Branch 1'),
+ createReplyMessage('msg-3', 'msg-1', 'assistant', 'Branch 2'),
];
const builder = createBuilder(messages);
@@ -525,13 +489,7 @@ describe('FlatListBuilder', () => {
it('should handle assistant message with branches', () => {
const messages: Message[] = [
- {
- content: 'User',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'User'),
{
content: 'Assistant',
createdAt: 0,
@@ -541,22 +499,8 @@ describe('FlatListBuilder', () => {
role: 'assistant',
updatedAt: 0,
},
- {
- content: 'Branch 1',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: 'Branch 2',
- createdAt: 0,
- id: 'msg-4',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'msg-2', 'user', 'Branch 1'),
+ createReplyMessage('msg-4', 'msg-2', 'user', 'Branch 2'),
];
const builder = createBuilder(messages);
@@ -622,14 +566,7 @@ describe('FlatListBuilder', () => {
role: 'assistant',
updatedAt: 0,
},
- {
- content: 'Assistant 2',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'msg-1', 'assistant', 'Assistant 2'),
];
const builder = createBuilder(messages);
@@ -658,30 +595,9 @@ describe('FlatListBuilder', () => {
role: 'user',
updatedAt: 0,
},
- {
- content: 'Branch 1',
- createdAt: 0,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'Branch 2',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'Follow-up',
- createdAt: 0,
- id: 'msg-4',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 0,
- },
+ createReplyMessage('msg-2', 'msg-1', 'assistant', 'Branch 1'),
+ createReplyMessage('msg-3', 'msg-1', 'assistant', 'Branch 2'),
+ createReplyMessage('msg-4', 'msg-2', 'user', 'Follow-up'),
];
const builder = createBuilder(messages);
@@ -723,14 +639,7 @@ describe('FlatListBuilder', () => {
tool_call_id: 'tool-1',
updatedAt: 0,
},
- {
- content: 'Assistant 2',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'msg-1', 'assistant', 'Assistant 2'),
];
const builder = createBuilder(messages);
@@ -749,13 +658,7 @@ describe('FlatListBuilder', () => {
it('should include follow-up messages after assistant chain', () => {
const messages: Message[] = [
- {
- content: 'User request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'User request'),
{
content: 'Using tool',
createdAt: 0,
@@ -776,22 +679,8 @@ describe('FlatListBuilder', () => {
tool_call_id: 'tool-1',
updatedAt: 0,
},
- {
- content: 'Response based on tool',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'tool-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'User follow-up',
- createdAt: 0,
- id: 'msg-4',
- parentId: 'msg-3',
- role: 'user',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'tool-1', 'assistant', 'Response based on tool'),
+ createReplyMessage('msg-4', 'msg-3', 'user', 'User follow-up'),
];
const builder = createBuilder(messages);
@@ -806,13 +695,7 @@ describe('FlatListBuilder', () => {
it('should handle user reply to tool message', () => {
const messages: Message[] = [
- {
- content: 'User request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'User request'),
{
content: 'Using tool',
createdAt: 0,
@@ -833,14 +716,7 @@ describe('FlatListBuilder', () => {
tool_call_id: 'tool-1',
updatedAt: 0,
},
- {
- content: 'User reply to tool',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'tool-1',
- role: 'user',
- updatedAt: 0,
- },
+ createReplyMessage('msg-3', 'tool-1', 'user', 'User reply to tool'),
];
const builder = createBuilder(messages);
@@ -867,22 +743,8 @@ describe('FlatListBuilder', () => {
role: 'user',
updatedAt: 0,
},
- {
- content: 'Branch 1',
- createdAt: 0,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'Branch 2',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
+ createReplyMessage('msg-2', 'msg-1', 'assistant', 'Branch 1'),
+ createReplyMessage('msg-3', 'msg-1', 'assistant', 'Branch 2'),
];
const builder = createBuilder(messages);
@@ -901,30 +763,9 @@ describe('FlatListBuilder', () => {
// Scenario: Thread messages where the parent (source message) is not in the query result
// All messages have parentId pointing to a message not in the array
const messages: Message[] = [
- {
- content: 'Thread user message',
- createdAt: 0,
- id: 'msg-1',
- parentId: 'source-msg-not-in-array',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: 'Thread assistant reply',
- createdAt: 0,
- id: 'msg-2',
- parentId: 'msg-1',
- role: 'assistant',
- updatedAt: 0,
- },
- {
- content: 'Thread user follow-up',
- createdAt: 0,
- id: 'msg-3',
- parentId: 'msg-2',
- role: 'user',
- updatedAt: 0,
- },
+ createReplyMessage('msg-1', 'source-msg-not-in-array', 'user', 'Thread user message'),
+ createReplyMessage('msg-2', 'msg-1', 'assistant', 'Thread assistant reply'),
+ createReplyMessage('msg-3', 'msg-2', 'user', 'Thread user follow-up'),
];
const builder = createBuilder(messages);
@@ -939,21 +780,8 @@ describe('FlatListBuilder', () => {
it('should create tasks message when multiple tasks have same agentId', () => {
const messages: Message[] = [
- {
- content: 'User request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: 'Tool message',
- createdAt: 0,
- id: 'tool-1',
- parentId: 'msg-1',
- role: 'tool',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'User request'),
+ createReplyMessage('tool-1', 'msg-1', 'tool', 'Tool message'),
{
agentId: 'agent-1',
content: 'Task 1 result',
@@ -987,21 +815,8 @@ describe('FlatListBuilder', () => {
it('should create groupTasks message when multiple tasks have different agentIds', () => {
const messages: Message[] = [
- {
- content: 'User request',
- createdAt: 0,
- id: 'msg-1',
- role: 'user',
- updatedAt: 0,
- },
- {
- content: 'Tool message',
- createdAt: 0,
- id: 'tool-1',
- parentId: 'msg-1',
- role: 'tool',
- updatedAt: 0,
- },
+ createRootMessage('msg-1', 'user', 'User request'),
+ createReplyMessage('tool-1', 'msg-1', 'tool', 'Tool message'),
{
agentId: 'agent-1',
content: 'Task 1 result',
@@ -1046,13 +861,7 @@ describe('FlatListBuilder', () => {
it('should create groupTasks with correct timestamps from task messages', () => {
const messages: Message[] = [
- {
- content: 'Tool message',
- createdAt: 0,
- id: 'tool-1',
- role: 'tool',
- updatedAt: 0,
- },
+ createRootMessage('tool-1', 'tool', 'Tool message'),
{
agentId: 'agent-1',
content: 'Task 1',
@@ -1102,7 +911,7 @@ describe('FlatListBuilder', () => {
const messages: Message[] = [
// User
- { content: 'go', createdAt: 0, id: 'u-1', role: 'user', updatedAt: 0 },
+ createRootMessage('u-1', 'user', 'go'),
// Step 0: assistant with Monitor tool
{
agentId: 'a',
diff --git a/packages/database/src/models/__tests__/agentIntervention.test.ts b/packages/database/src/models/__tests__/agentIntervention.test.ts
index 7b45c22b462..c6626af0e27 100644
--- a/packages/database/src/models/__tests__/agentIntervention.test.ts
+++ b/packages/database/src/models/__tests__/agentIntervention.test.ts
@@ -28,6 +28,33 @@ import {
hashAgentInterventionRequestRevision,
} from '../agentIntervention';
+const createLeaseClaim = (
+ inputHash: string,
+ leaseDurationMs: number,
+ resolutionRequestId: string,
+): Parameters<AgentInterventionModel['claimCustomExecution']>[0] => ({
+ inputHash,
+ leaseDurationMs,
+ resolutionRequestId,
+});
+
+const createCompletion = (
+ inputHash: string,
+ leaseToken: string,
+ resolutionRequestId: string,
+ result: Parameters<AgentInterventionModel['completeCustomExecution']>[0]['result'],
+): Parameters<AgentInterventionModel['completeCustomExecution']>[0] => ({
+ inputHash,
+ leaseToken,
+ resolutionRequestId,
+ result,
+});
+
+const createInstallRequest = () => ({
+ apiName: 'installMarketplaceItem',
+ fields: [{ id: 'confirm', label: 'Install', required: true, type: 'boolean' }],
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const ownerId = 'agent-intervention-owner';
@@ -146,10 +173,7 @@ const createCustomResolution = async (resolutionRequestId = randomUUID()) => {
questionItem({
allowedActions: ['submit_custom'],
interactionKind: 'custom',
- sanitizedRequest: {
- apiName: 'installMarketplaceItem',
- fields: [{ id: 'confirm', label: 'Install', required: true, type: 'boolean' }],
- },
+ sanitizedRequest: createInstallRequest(),
toolCallId: `custom-execution-tool-${hashSequence + 1}`,
}),
],
@@ -176,10 +200,7 @@ const createMixedCustomResolution = async (resolutionRequestId = randomUUID()) =
questionItem({
allowedActions: ['submit_custom'],
interactionKind: 'custom',
- sanitizedRequest: {
- apiName: 'installMarketplaceItem',
- fields: [{ id: 'confirm', label: 'Install', required: true, type: 'boolean' }],
- },
+ sanitizedRequest: createInstallRequest(),
toolCallId: `mixed-custom-execution-tool-${hashSequence + 1}`,
}),
questionItem({ toolCallId: `mixed-custom-sibling-${hashSequence + 1}` }),
@@ -759,10 +780,7 @@ describe('AgentInterventionModel', () => {
questionItem({
allowedActions: ['submit_custom'],
interactionKind: 'custom',
- sanitizedRequest: {
- apiName: 'installMarketplaceItem',
- fields: [{ id: 'confirm', label: 'Install', required: true, type: 'boolean' }],
- },
+ sanitizedRequest: createInstallRequest(),
toolCallId: 'custom-1',
}),
questionItem({ toolCallId: 'question-2' }),
@@ -823,11 +841,7 @@ describe('AgentInterventionModel', () => {
const results = await Promise.all(
Array.from({ length: 8 }, () =>
model.claimCustomExecution(
- {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- },
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
now,
),
),
@@ -842,11 +856,7 @@ describe('AgentInterventionModel', () => {
it('returns in_progress without exposing the live lease token', async () => {
const { resolution } = await createCustomResolution();
const now = new Date('2026-08-26T10:00:00.000Z');
- const params = {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId);
expect(await model.claimCustomExecution(params, now)).toMatchObject({
attempt: 1,
outcome: 'applied',
@@ -864,11 +874,9 @@ describe('AgentInterventionModel', () => {
);
expect(
- await model.claimCustomExecution({
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- }),
+ await model.claimCustomExecution(
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
+ ),
).toEqual({ outcome: 'conflict' });
expect(await model.findResolutionByRequestId(resolution.resolutionRequestId)).toMatchObject({
customExecutionAttempt: 0,
@@ -886,11 +894,9 @@ describe('AgentInterventionModel', () => {
);
expect(terminalRows[0].status).toBe('session_ended');
expect(
- await model.claimCustomExecution({
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- }),
+ await model.claimCustomExecution(
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
+ ),
).toEqual({ outcome: 'conflict' });
expect(await model.findResolutionByRequestId(resolution.resolutionRequestId)).toMatchObject({
customExecutionState: 'pending',
@@ -901,11 +907,7 @@ describe('AgentInterventionModel', () => {
it('protects an executing winner while terminalizing its pending sibling', async () => {
const { resolution, rows } = await createMixedCustomResolution();
const now = new Date('2026-08-26T10:00:00.000Z');
- const params = {
- inputHash,
- leaseDurationMs: 1000,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, 1000, resolution.resolutionRequestId);
const claimed = await model.claimCustomExecution(params, now);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
@@ -933,11 +935,9 @@ describe('AgentInterventionModel', () => {
it('replays the exact completed result and conflicts on input or result drift', async () => {
const { resolution, row } = await createCustomResolution();
- const claimed = await model.claimCustomExecution({
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- });
+ const claimed = await model.claimCustomExecution(
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
+ );
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const result = {
@@ -945,12 +945,9 @@ describe('AgentInterventionModel', () => {
pluginState: { agentIds: ['agent-a', 'agent-b'], source: 'marketplace' },
};
expect(
- await model.completeCustomExecution({
- inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
- result,
- }),
+ await model.completeCustomExecution(
+ createCompletion(inputHash, claimed.leaseToken, resolution.resolutionRequestId, result),
+ ),
).toEqual({ outcome: 'completed', result });
expect(
await model.completeCustomExecution({
@@ -972,11 +969,9 @@ describe('AgentInterventionModel', () => {
}),
).toEqual({ outcome: 'conflict' });
expect(
- await model.claimCustomExecution({
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- }),
+ await model.claimCustomExecution(
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
+ ),
).toEqual({ outcome: 'completed', result });
expect(
await model.claimCustomExecution({
@@ -998,11 +993,7 @@ describe('AgentInterventionModel', () => {
it('takes over an expired lease and fences the stale completion', async () => {
const { resolution } = await createCustomResolution();
const now = new Date('2026-08-26T10:00:00.000Z');
- const params = {
- inputHash,
- leaseDurationMs: 1000,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, 1000, resolution.resolutionRequestId);
const first = await model.claimCustomExecution(params, now);
if (first.outcome !== 'applied') throw new Error('first execution lease claim failed');
const second = await model.claimCustomExecution(params, new Date(now.getTime() + 1000));
@@ -1031,21 +1022,14 @@ describe('AgentInterventionModel', () => {
it('protects a completed winner from terminal teardown and replays its result', async () => {
const { resolution, rows } = await createMixedCustomResolution();
- const params = {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId);
const claimed = await model.claimCustomExecution(params);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const result = { content: 'Installed', pluginState: { agentId: 'agent-a' } };
expect(
- await model.completeCustomExecution({
- inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
- result,
- }),
+ await model.completeCustomExecution(
+ createCompletion(inputHash, claimed.leaseToken, resolution.resolutionRequestId, result),
+ ),
).toEqual({ outcome: 'completed', result });
await model.markBatchTerminal(
@@ -1062,21 +1046,14 @@ describe('AgentInterventionModel', () => {
it('keeps a heterogeneous completed result replayable after producer ACK', async () => {
const { resolution } = await createCustomResolution();
- const params = {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId);
const claimed = await model.claimCustomExecution(params);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const result = { content: 'Installed', pluginState: { agentId: 'agent-a' } };
expect(
- await model.completeCustomExecution({
- inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
- result,
- }),
+ await model.completeCustomExecution(
+ createCompletion(inputHash, claimed.leaseToken, resolution.resolutionRequestId, result),
+ ),
).toEqual({ outcome: 'completed', result });
expect((await model.markResolutionPublished(resolution.resolutionRequestId)).outcome).toBe(
@@ -1094,11 +1071,7 @@ describe('AgentInterventionModel', () => {
it('keeps the original execution active when its claim wins before rollback', async () => {
const { resolution } = await createCustomResolution();
- const params = {
- inputHash,
- leaseDurationMs: 1000,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, 1000, resolution.resolutionRequestId);
const now = new Date('2026-08-26T10:00:00.000Z');
const claimed = await model.claimCustomExecution(params, now);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
@@ -1111,31 +1084,24 @@ describe('AgentInterventionModel', () => {
await model.claimCustomExecution(params, new Date(now.getTime() + 1000)),
).toMatchObject({ attempt: 2, outcome: 'applied' });
expect(
- await model.completeCustomExecution({
- inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
- result,
- }),
+ await model.completeCustomExecution(
+ createCompletion(inputHash, claimed.leaseToken, resolution.resolutionRequestId, result),
+ ),
).toEqual({ outcome: 'conflict' });
});
it('replays the durable result when completion wins before rollback', async () => {
const { resolution, row } = await createCustomResolution();
- const params = {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId);
const claimed = await model.claimCustomExecution(params);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const result = { content: 'Installed', pluginState: { agentId: 'agent-a' } };
- const completion = {
+ const completion = createCompletion(
inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
+ claimed.leaseToken,
+ resolution.resolutionRequestId,
result,
- };
+ );
expect(await model.completeCustomExecution(completion)).toEqual({
outcome: 'completed',
@@ -1166,11 +1132,9 @@ describe('AgentInterventionModel', () => {
it('rejects terminal writes from old instances once custom execution has started', async () => {
const { resolution } = await createCustomResolution();
- const claimed = await model.claimCustomExecution({
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- });
+ const claimed = await model.claimCustomExecution(
+ createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId),
+ );
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const oldTerminalWrite = (status: 'rolled_back' | 'session_ended' | 'timed_out') =>
@@ -1184,12 +1148,9 @@ describe('AgentInterventionModel', () => {
const result = { content: 'Installed', pluginState: { agentId: 'agent-a' } };
expect(
- await model.completeCustomExecution({
- inputHash,
- leaseToken: claimed.leaseToken,
- resolutionRequestId: resolution.resolutionRequestId,
- result,
- }),
+ await model.completeCustomExecution(
+ createCompletion(inputHash, claimed.leaseToken, resolution.resolutionRequestId, result),
+ ),
).toEqual({ outcome: 'completed', result });
for (const status of ['rolled_back', 'session_ended', 'timed_out'] as const) {
await expect(oldTerminalWrite(status)).rejects.toThrow();
@@ -1202,11 +1163,7 @@ describe('AgentInterventionModel', () => {
it('rejects the wrong lease, wrong owner, invalid hash, and out-of-bounds duration', async () => {
const { resolution } = await createCustomResolution();
- const params = {
- inputHash,
- leaseDurationMs,
- resolutionRequestId: resolution.resolutionRequestId,
- };
+ const params = createLeaseClaim(inputHash, leaseDurationMs, resolution.resolutionRequestId);
const claimed = await model.claimCustomExecution(params);
if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
const result = { content: 'Installed', pluginState: {} };
diff --git a/packages/database/src/models/__tests__/connector.test.ts b/packages/database/src/models/__tests__/connector.test.ts
index 25fffc0970b..ac433fbebfc 100644
--- a/packages/database/src/models/__tests__/connector.test.ts
+++ b/packages/database/src/models/__tests__/connector.test.ts
@@ -24,6 +24,24 @@ const gateKeeper = {
const apikeyCredentials: ConnectorCredentials = { apiKey: 'secret-key', type: 'apikey' };
+const createBuiltinConnectorInput = (
+ identifier: string,
+ name: string,
+): Parameters<ConnectorModel['create']>[0] => ({
+ identifier,
+ name,
+ sourceType: 'builtin',
+ status: 'connected',
+});
+
+const createGitHubConnectorInput = (): Parameters<ConnectorModel['create']>[0] => ({
+ credentials: JSON.stringify(apikeyCredentials),
+ identifier: 'github',
+ name: 'GitHub',
+ sourceType: 'builtin',
+ status: 'connected',
+});
+
beforeEach(async () => {
vi.clearAllMocks();
await serverDB.delete(users);
@@ -42,12 +60,7 @@ describe('ConnectorModel', () => {
it('creates a connector without credentials', async () => {
const model = new ConnectorModel(serverDB, userId);
- const result = await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const result = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
expect(result.id).toBeDefined();
expect(result.userId).toBe(userId);
@@ -59,13 +72,7 @@ describe('ConnectorModel', () => {
it('encrypts credentials with the constructor gateKeeper', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- const result = await model.create({
- credentials: JSON.stringify(apikeyCredentials),
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const result = await model.create(createGitHubConnectorInput());
expect(gateKeeper.encrypt).toHaveBeenCalledOnce();
expect(result.credentials).toBe(`enc:${JSON.stringify(apikeyCredentials)}`);
@@ -88,12 +95,7 @@ describe('ConnectorModel', () => {
it('persists workspaceId when the model is workspace-scoped', async () => {
const model = new ConnectorModel(serverDB, userId, workspaceId);
- const result = await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const result = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
expect(result.workspaceId).toBe(workspaceId);
});
@@ -105,16 +107,7 @@ describe('ConnectorModel', () => {
encrypt: vi.fn(async (plaintext: string) => `call:${plaintext}`),
};
- const result = await model.create(
- {
- credentials: JSON.stringify(apikeyCredentials),
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- },
- callGateKeeper,
- );
+ const result = await model.create(createGitHubConnectorInput(), callGateKeeper);
expect(callGateKeeper.encrypt).toHaveBeenCalledOnce();
expect(result.credentials).toBe(`call:${JSON.stringify(apikeyCredentials)}`);
@@ -125,21 +118,10 @@ describe('ConnectorModel', () => {
it('returns only the current user / workspace connectors with decrypted credentials', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- await model.create({
- credentials: JSON.stringify(apikeyCredentials),
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
+ await model.create(createGitHubConnectorInput());
// other user's connector must not leak
const otherModel = new ConnectorModel(serverDB, otherUserId, undefined, gateKeeper);
- await otherModel.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ await otherModel.create(createBuiltinConnectorInput('linear', 'Linear'));
const rows = await model.query();
@@ -150,12 +132,7 @@ describe('ConnectorModel', () => {
it('returns null credentials for rows without credentials', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ await model.create(createBuiltinConnectorInput('linear', 'Linear'));
const rows = await model.query();
@@ -242,24 +219,9 @@ describe('ConnectorModel', () => {
it('returns only connectors matching the given identifiers', async () => {
const model = new ConnectorModel(serverDB, userId);
- await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
- await model.create({
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
- await model.create({
- identifier: 'slack',
- name: 'Slack',
- sourceType: 'builtin',
- status: 'connected',
- });
+ await model.create(createBuiltinConnectorInput('linear', 'Linear'));
+ await model.create(createBuiltinConnectorInput('github', 'GitHub'));
+ await model.create(createBuiltinConnectorInput('slack', 'Slack'));
const rows = await model.queryByIdentifiers(['linear', 'slack']);
@@ -270,12 +232,7 @@ describe('ConnectorModel', () => {
describe('stable identifier order', () => {
const createConnectors = async (model: ConnectorModel, identifiers: string[]) => {
for (const identifier of identifiers) {
- await model.create({
- identifier,
- name: identifier,
- sourceType: 'builtin',
- status: 'connected',
- });
+ await model.create(createBuiltinConnectorInput(identifier, identifier));
}
};
@@ -344,12 +301,9 @@ describe('ConnectorModel', () => {
sourceType: 'builtin',
status: 'connected',
});
- await new ConnectorModel(serverDB, otherUserId).create({
- identifier: 'github',
- name: 'Other GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
+ await new ConnectorModel(serverDB, otherUserId).create(
+ createBuiltinConnectorInput('github', 'Other GitHub'),
+ );
await serverDB.insert(agents).values({ id: 'github-agent', userId });
await model.create({
agentId: 'github-agent',
@@ -482,13 +436,7 @@ describe('ConnectorModel', () => {
describe('findById', () => {
it('returns the decrypted connector by id', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- const created = await model.create({
- credentials: JSON.stringify(apikeyCredentials),
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await model.create(createGitHubConnectorInput());
const found = await model.findById(created.id);
@@ -503,12 +451,7 @@ describe('ConnectorModel', () => {
it('returns null when the connector belongs to another user', async () => {
const otherModel = new ConnectorModel(serverDB, otherUserId);
- const created = await otherModel.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await otherModel.create(createBuiltinConnectorInput('linear', 'Linear'));
const model = new ConnectorModel(serverDB, userId);
expect(await model.findById(created.id)).toBeNull();
@@ -518,12 +461,7 @@ describe('ConnectorModel', () => {
describe('update', () => {
it('updates non-credential fields without touching credentials', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- const created = await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
await model.update(created.id, { name: 'Linear Renamed' });
@@ -537,12 +475,7 @@ describe('ConnectorModel', () => {
it('encrypts credentials when provided in the patch', async () => {
const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
- const created = await model.create({
- identifier: 'github',
- name: 'GitHub',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await model.create(createBuiltinConnectorInput('github', 'GitHub'));
const newCredentials = JSON.stringify({ token: 'bearer-token', type: 'bearer' });
await model.update(created.id, { credentials: newCredentials });
@@ -554,12 +487,7 @@ describe('ConnectorModel', () => {
it('does not update connectors owned by another user', async () => {
const otherModel = new ConnectorModel(serverDB, otherUserId);
- const created = await otherModel.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await otherModel.create(createBuiltinConnectorInput('linear', 'Linear'));
const model = new ConnectorModel(serverDB, userId);
await model.update(created.id, { name: 'Hacked' });
@@ -575,12 +503,7 @@ describe('ConnectorModel', () => {
describe('updateStatus', () => {
it('updates the connector status', async () => {
const model = new ConnectorModel(serverDB, userId);
- const created = await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
await model.updateStatus(created.id, 'error');
@@ -672,12 +595,7 @@ describe('ConnectorModel', () => {
describe('delete', () => {
it('deletes a connector owned by the user', async () => {
const model = new ConnectorModel(serverDB, userId);
- const created = await model.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
await model.delete(created.id);
@@ -686,12 +604,7 @@ describe('ConnectorModel', () => {
it('does not delete connectors owned by another user', async () => {
const otherModel = new ConnectorModel(serverDB, otherUserId);
- const created = await otherModel.create({
- identifier: 'linear',
- name: 'Linear',
- sourceType: 'builtin',
- status: 'connected',
- });
+ const created = await otherModel.create(createBuiltinConnectorInput('linear', 'Linear'));
const model = new ConnectorModel(serverDB, userId);
await model.delete(created.id);
diff --git a/packages/database/src/models/__tests__/documentHistory.test.ts b/packages/database/src/models/__tests__/documentHistory.test.ts
index 99b512a23ad..bf485e1742c 100644
--- a/packages/database/src/models/__tests__/documentHistory.test.ts
+++ b/packages/database/src/models/__tests__/documentHistory.test.ts
@@ -9,6 +9,18 @@ import { DocumentModel } from '../document';
import { DocumentHistoryModel } from '../documentHistory';
import { FileModel } from '../file';
+const createTaggedHistory = (
+ documentId: string,
+ tag: number,
+ saveSource: Parameters<DocumentHistoryModel['create']>[0]['saveSource'],
+ savedAt: Date,
+): Parameters<DocumentHistoryModel['create']>[0] => ({
+ documentId,
+ editorData: { tag },
+ saveSource,
+ savedAt,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'document-history-model-test-user-id';
@@ -107,24 +119,15 @@ describe('DocumentHistoryModel', () => {
it('should return document history rows ordered by savedAt descending', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'autosave',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- await historyModel.create({
- documentId,
- editorData: { tag: 2 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:02.000Z'),
- });
- await historyModel.create({
- documentId,
- editorData: { tag: 3 },
- saveSource: 'restore',
- savedAt: new Date('2026-04-11T00:00:03.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'autosave', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ await historyModel.create(
+ createTaggedHistory(documentId, 2, 'manual', new Date('2026-04-11T00:00:02.000Z')),
+ );
+ await historyModel.create(
+ createTaggedHistory(documentId, 3, 'restore', new Date('2026-04-11T00:00:03.000Z')),
+ );
const rows = await historyModel.list({ documentId });
@@ -135,24 +138,15 @@ describe('DocumentHistoryModel', () => {
it('should support pagination via beforeSavedAt and limit', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'autosave',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- await historyModel.create({
- documentId,
- editorData: { tag: 2 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:02.000Z'),
- });
- await historyModel.create({
- documentId,
- editorData: { tag: 3 },
- saveSource: 'restore',
- savedAt: new Date('2026-04-11T00:00:03.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'autosave', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ await historyModel.create(
+ createTaggedHistory(documentId, 2, 'manual', new Date('2026-04-11T00:00:02.000Z')),
+ );
+ await historyModel.create(
+ createTaggedHistory(documentId, 3, 'restore', new Date('2026-04-11T00:00:03.000Z')),
+ );
const anchored = await historyModel.list({
beforeSavedAt: new Date('2026-04-11T00:00:03.000Z'),
@@ -168,18 +162,12 @@ describe('DocumentHistoryModel', () => {
it('should return the most recent history row by savedAt', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- const latest = await historyModel.create({
- documentId,
- editorData: { tag: 2 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:02.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ const latest = await historyModel.create(
+ createTaggedHistory(documentId, 2, 'manual', new Date('2026-04-11T00:00:02.000Z')),
+ );
const row = await historyModel.findLatestByDocumentId(documentId);
expect(row?.id).toBe(latest.id);
@@ -191,18 +179,12 @@ describe('DocumentHistoryModel', () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
- const created = await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- const otherCreated = await historyModel2.create({
- documentId: otherDocumentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
+ const created = await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ const otherCreated = await historyModel2.create(
+ createTaggedHistory(otherDocumentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
await historyModel.delete(created.id);
@@ -217,24 +199,15 @@ describe('DocumentHistoryModel', () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- await historyModel.create({
- documentId,
- editorData: { tag: 2 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:02.000Z'),
- });
- await historyModel2.create({
- documentId: otherDocumentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ await historyModel.create(
+ createTaggedHistory(documentId, 2, 'manual', new Date('2026-04-11T00:00:02.000Z')),
+ );
+ await historyModel2.create(
+ createTaggedHistory(otherDocumentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
await historyModel.deleteByDocumentId(documentId);
@@ -251,18 +224,12 @@ describe('DocumentHistoryModel', () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
- const first = await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- await historyModel2.create({
- documentId: otherDocumentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
+ const first = await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ await historyModel2.create(
+ createTaggedHistory(otherDocumentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
const rows = await historyModel.list({ documentId });
const otherRows = await historyModel2.list({ documentId: otherDocumentId });
@@ -279,18 +246,12 @@ describe('DocumentHistoryModel.deleteAll', () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
- await historyModel2.create({
- documentId: otherDocumentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
+ await historyModel2.create(
+ createTaggedHistory(otherDocumentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
await historyModel.deleteAll();
@@ -303,12 +264,9 @@ describe('DocumentHistoryModel.query', () => {
it('should mirror list', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
- await historyModel.create({
- documentId,
- editorData: { tag: 1 },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- });
+ await historyModel.create(
+ createTaggedHistory(documentId, 1, 'manual', new Date('2026-04-11T00:00:01.000Z')),
+ );
const rows = await historyModel.query({ documentId });
expect(rows).toHaveLength(1);
diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.ts
index e3ee640b068..8cffa4803d7 100644
--- a/packages/database/src/models/__tests__/file.test.ts
+++ b/packages/database/src/models/__tests__/file.test.ts
@@ -25,6 +25,45 @@ import {
import type { LobeChatDatabase } from '../../type';
import { FileModel } from '../file';
+const queryFiles = (): (typeof files.$inferInsert)[] => [
+ {
+ name: 'document.pdf',
+ url: 'https://example.com/document.pdf',
+ size: 1000,
+ fileType: 'application/pdf',
+ userId,
+ },
+ {
+ name: 'image.jpg',
+ url: 'https://example.com/image.jpg',
+ size: 500,
+ fileType: 'image/jpeg',
+ userId,
+ },
+ {
+ name: 'audio.mp3',
+ url: 'https://example.com/audio.mp3',
+ size: 2000,
+ fileType: 'audio/mpeg',
+ userId,
+ },
+];
+
+const globalFileInput = (): Parameters<FileModel['createGlobalFile']>[0] => ({
+ hashId: '1',
+ url: 'https://example.com/file1.txt',
+ size: 100,
+ fileType: 'text/plain',
+ creator: userId,
+});
+
+const newFileInput = (): Parameters<FileModel['create']>[0] => ({
+ name: 'test-file.txt',
+ url: 'https://example.com/test-file.txt',
+ size: 100,
+ fileType: 'text/plain',
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'file-model-test-user-id';
@@ -46,12 +85,7 @@ afterEach(async () => {
describe('FileModel', () => {
describe('create', () => {
it('should create a new file', async () => {
- const params = {
- name: 'test-file.txt',
- url: 'https://example.com/test-file.txt',
- size: 100,
- fileType: 'text/plain',
- };
+ const params = newFileInput();
const { id } = await fileModel.create(params);
expect(id).toBeDefined();
@@ -151,13 +185,7 @@ describe('FileModel', () => {
describe('delete', () => {
it('should delete a file by id', async () => {
- await fileModel.createGlobalFile({
- hashId: '1',
- url: 'https://example.com/file1.txt',
- size: 100,
- fileType: 'text/plain',
- creator: userId,
- });
+ await fileModel.createGlobalFile(globalFileInput());
const { id } = await fileModel.create({
name: 'test-file.txt',
@@ -178,13 +206,7 @@ describe('FileModel', () => {
expect(globalFile).toBeUndefined();
});
it('should delete a file by id but global file not removed ', async () => {
- await fileModel.createGlobalFile({
- hashId: '1',
- url: 'https://example.com/file1.txt',
- size: 100,
- fileType: 'text/plain',
- creator: userId,
- });
+ await fileModel.createGlobalFile(globalFileInput());
const { id } = await fileModel.create({
name: 'test-file.txt',
@@ -537,13 +559,7 @@ describe('FileModel', () => {
describe('deleteMany', () => {
it('should delete multiple files', async () => {
- await fileModel.createGlobalFile({
- hashId: '1',
- url: 'https://example.com/file1.txt',
- size: 100,
- fileType: 'text/plain',
- creator: userId,
- });
+ await fileModel.createGlobalFile(globalFileInput());
await fileModel.createGlobalFile({
hashId: '2',
url: 'https://example.com/file2.txt',
@@ -588,13 +604,7 @@ describe('FileModel', () => {
expect(deletedFiles.map((file) => file.id).sort()).toEqual([file1.id, file2.id].sort());
});
it('should delete multiple files but not remove global files if DISABLE_REMOVE_GLOBAL_FILE=true', async () => {
- await fileModel.createGlobalFile({
- hashId: '1',
- url: 'https://example.com/file1.txt',
- size: 100,
- fileType: 'text/plain',
- creator: userId,
- });
+ await fileModel.createGlobalFile(globalFileInput());
await fileModel.createGlobalFile({
hashId: '2',
url: 'https://example.com/file2.txt',
@@ -772,29 +782,7 @@ describe('FileModel', () => {
});
describe('Query', () => {
- const sharedFileList = [
- {
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- {
- name: 'image.jpg',
- url: 'https://example.com/image.jpg',
- size: 500,
- fileType: 'image/jpeg',
- userId,
- },
- {
- name: 'audio.mp3',
- url: 'https://example.com/audio.mp3',
- size: 2000,
- fileType: 'audio/mpeg',
- userId,
- },
- ];
+ const sharedFileList = queryFiles();
it('should query files for the user', async () => {
const file1 = await fileModel.create({
@@ -1075,12 +1063,7 @@ describe('FileModel', () => {
describe('findById', () => {
it('should find a file by id', async () => {
- const { id } = await fileModel.create({
- name: 'test-file.txt',
- url: 'https://example.com/test-file.txt',
- size: 100,
- fileType: 'text/plain',
- });
+ const { id } = await fileModel.create(newFileInput());
const file = await fileModel.findById(id);
expect(file).toMatchObject({
@@ -1124,12 +1107,7 @@ describe('FileModel', () => {
});
it('should update a file', async () => {
- const { id } = await fileModel.create({
- name: 'test-file.txt',
- url: 'https://example.com/test-file.txt',
- size: 100,
- fileType: 'text/plain',
- });
+ const { id } = await fileModel.create(newFileInput());
await fileModel.update(id, { name: 'updated-test-file.txt', size: 200 });
@@ -1199,29 +1177,7 @@ describe('FileModel', () => {
});
describe('countUsage', () => {
- const sharedFileList = [
- {
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- {
- name: 'image.jpg',
- url: 'https://example.com/image.jpg',
- size: 500,
- fileType: 'image/jpeg',
- userId,
- },
- {
- name: 'audio.mp3',
- url: 'https://example.com/audio.mp3',
- size: 2000,
- fileType: 'audio/mpeg',
- userId,
- },
- ];
+ const sharedFileList = queryFiles();
it('should get total size of files for the user', async () => {
await serverDB.insert(files).values(sharedFileList);
diff --git a/packages/database/src/models/__tests__/knowledgeBase.test.ts b/packages/database/src/models/__tests__/knowledgeBase.test.ts
index ca08bf1bb7c..92a84290c38 100644
--- a/packages/database/src/models/__tests__/knowledgeBase.test.ts
+++ b/packages/database/src/models/__tests__/knowledgeBase.test.ts
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { sleep } from '@/utils/sleep';
import { getTestDB } from '../../core/getTestDB';
-import type { NewKnowledgeBase } from '../../schemas';
+import type { NewDocument, NewKnowledgeBase } from '../../schemas';
import {
documents,
files,
@@ -164,25 +164,51 @@ describe('KnowledgeBaseModel', () => {
});
});
+ const createGlobalFile = (
+ hashId: string,
+ name: string,
+ size: number,
+ fileType = 'application/pdf',
+ ) => ({
+ hashId,
+ url: `https://example.com/${name}`,
+ size,
+ fileType,
+ creator: userId,
+ });
+
+ const createFile = (
+ id: string,
+ name: string,
+ fileHash: string,
+ size: number,
+ fileType = 'application/pdf',
+ ) => ({
+ id,
+ name,
+ url: `https://example.com/${name}`,
+ fileHash,
+ size,
+ fileType,
+ userId,
+ });
+
+ const createDocument = (id: string): NewDocument => ({
+ id,
+ title: 'Test Document',
+ content: 'Test content',
+ fileType: 'application/pdf',
+ totalCharCount: 100,
+ totalLineCount: 10,
+ sourceType: 'file',
+ source: 'test.pdf',
+ fileId: 'file1',
+ userId,
+ });
+
const fileList = [
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- {
- id: 'file2',
- name: 'image.jpg',
- url: 'https://example.com/image.jpg',
- fileHash: 'hash2',
- size: 500,
- fileType: 'image/jpeg',
- userId,
- },
+ createFile('file1', 'document.pdf', 'hash1', 1000),
+ createFile('file2', 'image.jpg', 'hash2', 500, 'image/jpeg'),
];
const createWorkspace = async (id: string, slug: string) => {
@@ -196,22 +222,12 @@ describe('KnowledgeBaseModel', () => {
describe('addFilesToKnowledgeBase', () => {
it('should add files to a knowledge base', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/image.jpg',
- size: 500,
- fileType: 'image/jpeg',
- creator: userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([
+ createGlobalFile('hash1', 'document.pdf', 1000),
+ createGlobalFile('hash2', 'image.jpg', 500, 'image/jpeg'),
+ ]);
await serverDB.insert(files).values(fileList);
@@ -234,44 +250,13 @@ describe('KnowledgeBaseModel', () => {
});
it('should add documents (with docs_ prefix) to a knowledge base by resolving to file IDs', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'document.pdf', 1000)]);
// Create mirror file first (document references it via fileId)
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(files).values([createFile('file1', 'document.pdf', 'hash1', 1000)]);
// Create document with fileId pointing to the mirror file
- await serverDB.insert(documents).values([
- {
- id: 'docs_test123',
- title: 'Test Document',
- content: 'Test content',
- fileType: 'application/pdf',
- totalCharCount: 100,
- totalLineCount: 10,
- sourceType: 'file',
- source: 'test.pdf',
- fileId: 'file1',
- userId,
- },
- ]);
+ await serverDB.insert(documents).values([createDocument('docs_test123')]);
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
@@ -436,52 +421,21 @@ describe('KnowledgeBaseModel', () => {
});
it('should handle mixed document IDs and file IDs', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/image.jpg',
- size: 500,
- fileType: 'image/jpeg',
- creator: userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([
+ createGlobalFile('hash1', 'document.pdf', 1000),
+ createGlobalFile('hash2', 'image.jpg', 500, 'image/jpeg'),
+ ]);
// Create files - file1 is mirror of the document, file2 is standalone
await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
+ createFile('file1', 'document.pdf', 'hash1', 1000),
fileList[1], // file2 - standalone file
]);
// Create document with fileId pointing to the mirror file
- await serverDB.insert(documents).values([
- {
- id: 'docs_test456',
- title: 'Test Document',
- content: 'Test content',
- fileType: 'application/pdf',
- totalCharCount: 100,
- totalLineCount: 10,
- sourceType: 'file',
- source: 'test.pdf',
- fileId: 'file1',
- userId,
- },
- ]);
+ await serverDB.insert(documents).values([createDocument('docs_test456')]);
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
@@ -499,22 +453,12 @@ describe('KnowledgeBaseModel', () => {
describe('removeFilesFromKnowledgeBase', () => {
it('should remove files from a knowledge base', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/image.jpg',
- size: 500,
- fileType: 'image/jpeg',
- creator: userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([
+ createGlobalFile('hash1', 'document.pdf', 1000),
+ createGlobalFile('hash2', 'image.jpg', 500, 'image/jpeg'),
+ ]);
await serverDB.insert(files).values(fileList);
@@ -533,44 +477,13 @@ describe('KnowledgeBaseModel', () => {
});
it('should remove documents (with docs_ prefix) from a knowledge base by resolving to file IDs', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'document.pdf', 1000)]);
// Create mirror file first (document references it via fileId)
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(files).values([createFile('file1', 'document.pdf', 'hash1', 1000)]);
// Create document with fileId pointing to the mirror file
- await serverDB.insert(documents).values([
- {
- id: 'docs_test789',
- title: 'Test Document',
- content: 'Test content',
- fileType: 'application/pdf',
- totalCharCount: 100,
- totalLineCount: 10,
- sourceType: 'file',
- source: 'test.pdf',
- fileId: 'file1',
- userId,
- },
- ]);
+ await serverDB.insert(documents).values([createDocument('docs_test789')]);
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
await knowledgeBaseModel.addFilesToKnowledgeBase(knowledgeBaseId, ['docs_test789']);
@@ -591,27 +504,9 @@ describe('KnowledgeBaseModel', () => {
});
it('should handle removing document IDs that resolve to null fileIds (empty resolvedFileIds)', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'document.pdf', 1000)]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(files).values([createFile('file1', 'document.pdf', 'hash1', 1000)]);
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
await knowledgeBaseModel.addFilesToKnowledgeBase(knowledgeBaseId, ['file1']);
@@ -646,15 +541,7 @@ describe('KnowledgeBaseModel', () => {
});
it('should not allow removing files from another user knowledge base', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/document.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'document.pdf', 1000)]);
await serverDB.insert(files).values([fileList[0]]);
@@ -676,42 +563,15 @@ describe('KnowledgeBaseModel', () => {
describe('findExclusiveFileIds', () => {
it('should return file IDs that belong only to this knowledge base', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/b.pdf',
- size: 200,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- {
- id: 'file2',
- name: 'b.pdf',
- url: 'https://example.com/b.pdf',
- fileHash: 'hash2',
- size: 200,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([createGlobalFile('hash1', 'a.pdf', 100), createGlobalFile('hash2', 'b.pdf', 200)]);
+ await serverDB
+ .insert(files)
+ .values([
+ createFile('file1', 'a.pdf', 'hash1', 100),
+ createFile('file2', 'b.pdf', 'hash2', 200),
+ ]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
const { id: kb2 } = await knowledgeBaseModel.create({ name: 'KB2' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1', 'file2']);
@@ -721,26 +581,8 @@ describe('KnowledgeBaseModel', () => {
});
it('should return empty array when all files are shared', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'a.pdf', 100)]);
+ await serverDB.insert(files).values([createFile('file1', 'a.pdf', 'hash1', 100)]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
const { id: kb2 } = await knowledgeBaseModel.create({ name: 'KB2' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1']);
@@ -750,42 +592,15 @@ describe('KnowledgeBaseModel', () => {
});
it('should return all files when none are shared', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/b.pdf',
- size: 200,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- {
- id: 'file2',
- name: 'b.pdf',
- url: 'https://example.com/b.pdf',
- fileHash: 'hash2',
- size: 200,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([createGlobalFile('hash1', 'a.pdf', 100), createGlobalFile('hash2', 'b.pdf', 200)]);
+ await serverDB
+ .insert(files)
+ .values([
+ createFile('file1', 'a.pdf', 'hash1', 100),
+ createFile('file2', 'b.pdf', 'hash2', 200),
+ ]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1', 'file2']);
const exclusiveIds = await knowledgeBaseModel.findExclusiveFileIds(kb1);
@@ -801,26 +616,8 @@ describe('KnowledgeBaseModel', () => {
describe('deleteWithFiles', () => {
it('should delete KB and its exclusive files', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'a.pdf', 100)]);
+ await serverDB.insert(files).values([createFile('file1', 'a.pdf', 'hash1', 100)]);
const { id: kbId } = await knowledgeBaseModel.create({ name: 'KB1' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kbId, ['file1']);
const result = await knowledgeBaseModel.deleteWithFiles(kbId);
@@ -838,42 +635,15 @@ describe('KnowledgeBaseModel', () => {
});
it('should NOT delete files shared with another KB', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/b.pdf',
- size: 200,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- {
- id: 'file2',
- name: 'b.pdf',
- url: 'https://example.com/b.pdf',
- fileHash: 'hash2',
- size: 200,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([createGlobalFile('hash1', 'a.pdf', 100), createGlobalFile('hash2', 'b.pdf', 200)]);
+ await serverDB
+ .insert(files)
+ .values([
+ createFile('file1', 'a.pdf', 'hash1', 100),
+ createFile('file2', 'b.pdf', 'hash2', 200),
+ ]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
const { id: kb2 } = await knowledgeBaseModel.create({ name: 'KB2' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1', 'file2']);
@@ -906,42 +676,15 @@ describe('KnowledgeBaseModel', () => {
describe('deleteAllWithFiles', () => {
it('should delete all KBs and their exclusive files', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- {
- hashId: 'hash2',
- url: 'https://example.com/b.pdf',
- size: 200,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- {
- id: 'file2',
- name: 'b.pdf',
- url: 'https://example.com/b.pdf',
- fileHash: 'hash2',
- size: 200,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB
+ .insert(globalFiles)
+ .values([createGlobalFile('hash1', 'a.pdf', 100), createGlobalFile('hash2', 'b.pdf', 200)]);
+ await serverDB
+ .insert(files)
+ .values([
+ createFile('file1', 'a.pdf', 'hash1', 100),
+ createFile('file2', 'b.pdf', 'hash2', 200),
+ ]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
const { id: kb2 } = await knowledgeBaseModel.create({ name: 'KB2' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1']);
@@ -961,26 +704,8 @@ describe('KnowledgeBaseModel', () => {
});
it('should delete shared file when both KBs sharing it are deleted', async () => {
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash1',
- url: 'https://example.com/a.pdf',
- size: 100,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'a.pdf',
- url: 'https://example.com/a.pdf',
- fileHash: 'hash1',
- size: 100,
- fileType: 'application/pdf',
- userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash1', 'a.pdf', 100)]);
+ await serverDB.insert(files).values([createFile('file1', 'a.pdf', 'hash1', 100)]);
const { id: kb1 } = await knowledgeBaseModel.create({ name: 'KB1' });
const { id: kb2 } = await knowledgeBaseModel.create({ name: 'KB2' });
await knowledgeBaseModel.addFilesToKnowledgeBase(kb1, ['file1']);
@@ -1005,24 +730,12 @@ describe('KnowledgeBaseModel', () => {
describe('transferTo', () => {
it('should transfer a knowledge base and its resources to another workspace', async () => {
await createWorkspace('workspace-target', 'workspace-target');
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash-transfer',
- url: 'https://example.com/transfer.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
- await serverDB.insert(files).values({
- id: 'file-transfer',
- name: 'transfer.pdf',
- url: 'https://example.com/transfer.pdf',
- fileHash: 'hash-transfer',
- size: 1000,
- fileType: 'application/pdf',
- userId,
- });
+ await serverDB
+ .insert(globalFiles)
+ .values([createGlobalFile('hash-transfer', 'transfer.pdf', 1000)]);
+ await serverDB
+ .insert(files)
+ .values(createFile('file-transfer', 'transfer.pdf', 'hash-transfer', 1000));
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Transfer KB' });
await serverDB.insert(documents).values({
@@ -1079,15 +792,7 @@ describe('KnowledgeBaseModel', () => {
describe('copyToWorkspace', () => {
it('should copy a knowledge base with files and document hierarchy to another workspace', async () => {
await createWorkspace('workspace-copy-target', 'workspace-copy-target');
- await serverDB.insert(globalFiles).values([
- {
- hashId: 'hash-copy',
- url: 'https://example.com/copy.pdf',
- size: 1000,
- fileType: 'application/pdf',
- creator: userId,
- },
- ]);
+ await serverDB.insert(globalFiles).values([createGlobalFile('hash-copy', 'copy.pdf', 1000)]);
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Copy KB' });
await serverDB.insert(documents).values([
diff --git a/packages/database/src/models/__tests__/messages/message.delete.test.ts b/packages/database/src/models/__tests__/messages/message.delete.test.ts
index a022d98397e..bb03f2601fb 100644
--- a/packages/database/src/models/__tests__/messages/message.delete.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.delete.test.ts
@@ -20,6 +20,28 @@ import {
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
+const ownedMessages = () => ({
+ where: eq(messages.userId, userId),
+});
+
+const branchAMessage = (): typeof messages.$inferInsert => ({
+ content: 'branch A',
+ createdAt: new Date('2026-01-01T00:00:01.000Z'),
+ id: 'branch-a',
+ parentId: 'parent',
+ role: 'user',
+ userId,
+});
+
+const branchBMessage = (): typeof messages.$inferInsert => ({
+ content: 'branch B',
+ createdAt: new Date('2026-01-01T00:00:02.000Z'),
+ id: 'branch-b',
+ parentId: 'parent',
+ role: 'user',
+ userId,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'message-delete-test';
@@ -110,22 +132,8 @@ describe('MessageModel Delete Tests', () => {
role: 'assistant',
userId,
},
- {
- content: 'branch A',
- createdAt: new Date('2026-01-01T00:00:01.000Z'),
- id: 'branch-a',
- parentId: 'parent',
- role: 'user',
- userId,
- },
- {
- content: 'branch B',
- createdAt: new Date('2026-01-01T00:00:02.000Z'),
- id: 'branch-b',
- parentId: 'parent',
- role: 'user',
- userId,
- },
+ branchAMessage(),
+ branchBMessage(),
]);
await messageModel.deleteMessage('branch-b');
@@ -154,22 +162,8 @@ describe('MessageModel Delete Tests', () => {
role: 'tool',
userId,
},
- {
- content: 'branch A',
- createdAt: new Date('2026-01-01T00:00:01.000Z'),
- id: 'branch-a',
- parentId: 'parent',
- role: 'user',
- userId,
- },
- {
- content: 'branch B',
- createdAt: new Date('2026-01-01T00:00:02.000Z'),
- id: 'branch-b',
- parentId: 'parent',
- role: 'user',
- userId,
- },
+ branchAMessage(),
+ branchBMessage(),
]);
await messageModel.deleteMessage('branch-a');
@@ -300,22 +294,8 @@ describe('MessageModel Delete Tests', () => {
role: 'assistant',
userId,
},
- {
- content: 'branch A',
- createdAt: new Date('2026-01-01T00:00:01.000Z'),
- id: 'branch-a',
- parentId: 'parent',
- role: 'user',
- userId,
- },
- {
- content: 'branch B',
- createdAt: new Date('2026-01-01T00:00:02.000Z'),
- id: 'branch-b',
- parentId: 'parent',
- role: 'user',
- userId,
- },
+ branchAMessage(),
+ branchBMessage(),
{
content: 'branch C',
createdAt: new Date('2026-01-01T00:00:03.000Z'),
@@ -344,22 +324,8 @@ describe('MessageModel Delete Tests', () => {
role: 'assistant',
userId,
},
- {
- content: 'branch A',
- createdAt: new Date('2026-01-01T00:00:01.000Z'),
- id: 'branch-a',
- parentId: 'parent',
- role: 'user',
- userId,
- },
- {
- content: 'branch B',
- createdAt: new Date('2026-01-01T00:00:02.000Z'),
- id: 'branch-b',
- parentId: 'parent',
- role: 'user',
- userId,
- },
+ branchAMessage(),
+ branchBMessage(),
]);
await messageModel.deleteMessages(['branch-a']);
@@ -832,9 +798,7 @@ describe('MessageModel Delete Tests', () => {
await messageModel.batchDeleteByAgentId('agent-del-1');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('msg-keep-1');
@@ -872,9 +836,7 @@ describe('MessageModel Delete Tests', () => {
await messageModel.batchDeleteByAgentId('agent-del-2');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('msg-keep-2');
@@ -922,9 +884,7 @@ describe('MessageModel Delete Tests', () => {
await messageModel.batchDeleteByAgentId('agent-del-mixed');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('msg-keep-mixed');
@@ -958,9 +918,7 @@ describe('MessageModel Delete Tests', () => {
await messageModel.batchDeleteByAgentId('agent-del-user');
// User's message should be deleted
- const userMessages = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const userMessages = await serverDB.query.messages.findMany(ownedMessages());
expect(userMessages).toHaveLength(0);
// Other user's message should remain
@@ -988,9 +946,7 @@ describe('MessageModel Delete Tests', () => {
await messageModel.batchDeleteByAgentId('agent-del-empty');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('msg-keep-empty');
@@ -1033,9 +989,7 @@ describe('MessageModel Delete Tests', () => {
it('deleteAllMessages should keep visitor messages', async () => {
await messageModel.deleteAllMessages();
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('visitor-msg');
@@ -1044,9 +998,7 @@ describe('MessageModel Delete Tests', () => {
it('batchDeleteByAgentId should keep visitor messages', async () => {
await messageModel.batchDeleteByAgentId('share-agent');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('visitor-msg');
@@ -1057,9 +1009,7 @@ describe('MessageModel Delete Tests', () => {
// export), so naming the id must not be enough to destroy it.
await messageModel.deleteMessage('visitor-msg');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id).sort()).toEqual(['creator-msg', 'visitor-msg']);
});
@@ -1067,9 +1017,7 @@ describe('MessageModel Delete Tests', () => {
it('deleteMessage should still delete the creator own message', async () => {
await messageModel.deleteMessage('creator-msg');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id)).toEqual(['visitor-msg']);
});
@@ -1077,9 +1025,7 @@ describe('MessageModel Delete Tests', () => {
it('deleteMessage should delete a visitor message when the runtime opts in', async () => {
await messageModel.deleteMessage('visitor-msg', { includeShareVisitor: true });
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);
});
@@ -1087,9 +1033,7 @@ describe('MessageModel Delete Tests', () => {
it('deleteMessages should drop only the non-visitor ids of a mixed batch', async () => {
await messageModel.deleteMessages(['creator-msg', 'visitor-msg']);
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id)).toEqual(['visitor-msg']);
});
@@ -1097,9 +1041,7 @@ describe('MessageModel Delete Tests', () => {
it('deleteMessages should delete visitor messages when the runtime opts in', async () => {
await messageModel.deleteMessages(['visitor-msg'], { includeShareVisitor: true });
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);
});
@@ -1110,9 +1052,7 @@ describe('MessageModel Delete Tests', () => {
// `deleteAllMessages` sweep above.
await messageModel.deleteMessagesBySession(undefined, 'visitor-topic');
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id).sort()).toEqual(['creator-msg', 'visitor-msg']);
});
@@ -1122,9 +1062,7 @@ describe('MessageModel Delete Tests', () => {
includeShareVisitor: true,
});
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);
});
@@ -1149,9 +1087,7 @@ describe('MessageModel Delete Tests', () => {
it('deleting the agent still cascades visitor messages away', async () => {
await serverDB.delete(agents).where(eq(agents.id, 'share-agent'));
- const remaining = await serverDB.query.messages.findMany({
- where: eq(messages.userId, userId),
- });
+ const remaining = await serverDB.query.messages.findMany(ownedMessages());
expect(remaining).toHaveLength(0);
});
diff --git a/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
index 014cf45e2a0..d954a744da4 100644
--- a/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
@@ -10,6 +10,25 @@ import { messagePlugins, messages, threads, topics, users } from '../../../schem
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
+const operationWindow = (
+ completedAt: Date,
+ startedAt: Date,
+): Parameters<MessageModel['listMessagePluginsForOperation']>[0] => ({
+ completedAt,
+ operationId: 'op-1',
+ startedAt,
+ threadId: 'thread1',
+ topicId: 'topic1',
+});
+
+const heterogeneousToolInput = (): Parameters<typeof seedToolCall>[0] => ({
+ createdAt: new Date('2027-01-01T00:00:00.000Z'),
+ id: 'hetero',
+ metadata: { heterogeneousToolStateOperationId: 'op-1' },
+ threadId: 'thread1',
+ topicId: 'topic1',
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'plugins-for-op-user';
@@ -119,13 +138,7 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
await seedToolCall({ createdAt: T2, id: 'm-b', threadId: 'thread1', topicId: 'topic1' });
await seedToolCall({ createdAt: T1, id: 'm-a', threadId: 'thread1', topicId: 'topic1' });
- const rows = await messageModel.listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const rows = await messageModel.listMessagePluginsForOperation(operationWindow(T3, T0));
expect(rows.map((r) => r.id)).toEqual(['m-a', 'm-b']);
expect(rows[0]).toMatchObject({ apiName: 'writeFile', identifier: 'lobe-cloud-sandbox' });
@@ -155,34 +168,16 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
// Same time window, different topic — must not leak in.
await seedToolCall({ createdAt: T1, id: 'other-topic', threadId: null, topicId: 'topic2' });
- const rows = await messageModel.listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const rows = await messageModel.listMessagePluginsForOperation(operationWindow(T3, T0));
expect(rows.map((r) => r.id)).toEqual(['right']);
});
it('matches heterogeneous rows by operation metadata even outside the window', async () => {
// createdAt sits well after the window, but the metadata op-id must still match.
- await seedToolCall({
- createdAt: new Date('2027-01-01T00:00:00.000Z'),
- id: 'hetero',
- metadata: { heterogeneousToolStateOperationId: 'op-1' },
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ await seedToolCall(heterogeneousToolInput());
- const rows = await messageModel.listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const rows = await messageModel.listMessagePluginsForOperation(operationWindow(T3, T0));
expect(rows.map((r) => r.id)).toEqual(['hetero']);
});
@@ -196,13 +191,7 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
topicId: 'topic2',
});
- const rows = await messageModel.listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const rows = await messageModel.listMessagePluginsForOperation(operationWindow(T3, T0));
expect(rows).toEqual([]);
});
@@ -234,13 +223,9 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
topicId: 'topic1',
});
- const asOther = await new MessageModel(serverDB, otherUserId).listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const asOther = await new MessageModel(serverDB, otherUserId).listMessagePluginsForOperation(
+ operationWindow(T3, T0),
+ );
expect(asOther).toEqual([]);
});
@@ -327,13 +312,7 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
threadId: 'thread1',
topicId: 'topic1',
});
- await seedToolCall({
- createdAt: new Date('2027-01-01T00:00:00.000Z'),
- id: 'hetero',
- metadata: { heterogeneousToolStateOperationId: 'op-1' },
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ await seedToolCall(heterogeneousToolInput());
const pool = (
serverDB as unknown as {
@@ -345,13 +324,9 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
// Capture the exact statements the method issues, faithfully.
const statements = await captureEmittedSql(async (db) => {
- const rows = await new MessageModel(db, userId).listMessagePluginsForOperation({
- completedAt: T3,
- operationId: 'op-1',
- startedAt: T0,
- threadId: 'thread1',
- topicId: 'topic1',
- });
+ const rows = await new MessageModel(db, userId).listMessagePluginsForOperation(
+ operationWindow(T3, T0),
+ );
// Correctness still holds across both branches under the skew.
expect(rows.map((r) => r.id).sort()).toEqual(['hetero', 'in-window', 'in-window-2']);
});
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 5a819dda5ed..4299ed7347b 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -39,6 +39,76 @@ const otherUserId = 'message-query-test-other';
const messageModel = new MessageModel(serverDB, userId);
const embeddingsId = uuid();
+const createFirstParentMessage = (): typeof messages.$inferInsert => ({
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+});
+
+const createSourceParentMessage = (): typeof messages.$inferInsert => ({
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message - source',
+ createdAt: new Date('2023-01-02'),
+});
+
+const createFirstThreadMessage = (): typeof messages.$inferInsert => ({
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+});
+
+const createSecondThreadMessage = (): typeof messages.$inferInsert => ({
+ id: 'thread-msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+});
+
+const createFirstStandaloneThread = (): typeof threads.$inferInsert => ({
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-1',
+ type: 'standalone',
+});
+
+const createSecondStandaloneThread = (): typeof threads.$inferInsert => ({
+ id: 'thread2',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-2',
+ type: 'standalone',
+});
+
+const createSpineToolMessage = (): typeof messages.$inferInsert => ({
+ id: 'tool-1',
+ userId,
+ topicId: 'topic1',
+ role: 'tool',
+ parentId: 'a1',
+ content: 'result',
+ createdAt: new Date('2023-01-01T00:00:01'),
+});
+
beforeEach(async () => {
// Clear tables before each test case
await serverDB.transaction(async (trx) => {
@@ -2821,22 +2891,9 @@ describe('MessageModel Query Tests', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create threads first due to foreign key constraint
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-1',
- type: 'standalone',
- },
- {
- id: 'thread2',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-2',
- type: 'standalone',
- },
- ]);
+ await trx
+ .insert(threads)
+ .values([createFirstStandaloneThread(), createSecondStandaloneThread()]);
await trx.insert(messages).values([
{
@@ -2892,15 +2949,7 @@ describe('MessageModel Query Tests', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create thread first
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-1',
- type: 'standalone',
- },
- ]);
+ await trx.insert(threads).values([createFirstStandaloneThread()]);
await trx.insert(messages).values([
{
@@ -2947,22 +2996,9 @@ describe('MessageModel Query Tests', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create threads first
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-1',
- type: 'standalone',
- },
- {
- id: 'thread2',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-2',
- type: 'standalone',
- },
- ]);
+ await trx
+ .insert(threads)
+ .values([createFirstStandaloneThread(), createSecondStandaloneThread()]);
await trx.insert(messages).values([
{
@@ -3015,22 +3051,9 @@ describe('MessageModel Query Tests', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create threads first
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-1',
- type: 'standalone',
- },
- {
- id: 'thread2',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'source-msg-2',
- type: 'standalone',
- },
- ]);
+ await trx
+ .insert(threads)
+ .values([createFirstStandaloneThread(), createSecondStandaloneThread()]);
await trx.insert(messages).values([
{
@@ -3110,16 +3133,7 @@ describe('MessageModel Query Tests', () => {
// Create main conversation messages
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
+ createFirstParentMessage(),
{
id: 'msg2',
userId,
@@ -3171,16 +3185,7 @@ describe('MessageModel Query Tests', () => {
// Create main conversation messages
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
+ createFirstParentMessage(),
{
id: 'msg2',
userId,
@@ -3383,26 +3388,8 @@ describe('MessageModel Query Tests', () => {
// Create main conversation messages (parent messages)
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
- {
- id: 'msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'assistant',
- content: 'second message - source',
- createdAt: new Date('2023-01-02'),
- },
+ createFirstParentMessage(),
+ createSourceParentMessage(),
{
id: 'msg3',
userId,
@@ -3414,26 +3401,8 @@ describe('MessageModel Query Tests', () => {
createdAt: new Date('2023-01-03'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
+ createFirstThreadMessage(),
+ createSecondThreadMessage(),
]);
});
@@ -3463,26 +3432,8 @@ describe('MessageModel Query Tests', () => {
// Create main conversation messages
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
- {
- id: 'msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'assistant',
- content: 'second message - source',
- createdAt: new Date('2023-01-02'),
- },
+ createFirstParentMessage(),
+ createSourceParentMessage(),
{
id: 'msg3',
userId,
@@ -3494,26 +3445,8 @@ describe('MessageModel Query Tests', () => {
createdAt: new Date('2023-01-03'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
+ createFirstThreadMessage(),
+ createSecondThreadMessage(),
]);
});
@@ -3542,48 +3475,14 @@ describe('MessageModel Query Tests', () => {
]);
// Insert messages in non-chronological order
- await trx.insert(messages).values([
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'assistant',
- content: 'second message - source',
- createdAt: new Date('2023-01-02'),
- },
- ]);
+ await trx
+ .insert(messages)
+ .values([
+ createSecondThreadMessage(),
+ createFirstParentMessage(),
+ createFirstThreadMessage(),
+ createSourceParentMessage(),
+ ]);
});
const result = await messageModel.query({ threadId: 'thread1' });
@@ -4147,16 +4046,8 @@ describe('MessageModel Query Tests', () => {
content: 'step',
createdAt: new Date('2023-01-01T00:00:00'),
},
- {
- // newest row, but a tool — must NOT be the spine
- id: 'tool-1',
- userId,
- topicId: 'topic1',
- role: 'tool',
- parentId: 'a1',
- content: 'result',
- createdAt: new Date('2023-01-01T00:00:01'),
- },
+ // newest row, but a tool — must NOT be the spine
+ createSpineToolMessage(),
{
id: 'a2',
userId,
@@ -4182,15 +4073,7 @@ describe('MessageModel Query Tests', () => {
content: 'spine',
createdAt: new Date('2023-01-01T00:00:00'),
},
- {
- id: 'tool-1',
- userId,
- topicId: 'topic1',
- role: 'tool',
- parentId: 'a1',
- content: 'result',
- createdAt: new Date('2023-01-01T00:00:01'),
- },
+ createSpineToolMessage(),
{
// newest, but a Monitor-stdout callback (metadata.signal) — excluded,
// so a normal turn doesn't re-mount onto a callback
@@ -4266,17 +4149,9 @@ describe('MessageModel Query Tests', () => {
content: 'final',
createdAt: new Date('2023-01-01T00:00:00'),
},
- {
- // newest row, but a tool result — an inline child of a1, never the
- // spine head. A new user turn must parent off the assistant (a1).
- id: 'tool-1',
- userId,
- topicId: 'topic1',
- role: 'tool',
- parentId: 'a1',
- content: 'result',
- createdAt: new Date('2023-01-01T00:00:01'),
- },
+ // newest row, but a tool result — an inline child of a1, never the
+ // spine head. A new user turn must parent off the assistant (a1).
+ createSpineToolMessage(),
]);
expect(await messageModel.getLatestSpineMessageId({ topicId: 'topic1' })).toBe('a1');
diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.ts
index c4aefe4197e..e463b0dfca8 100644
--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts
@@ -11,6 +11,22 @@ import { MessageModel } from '../../message';
import { MessageScope } from '../../message/scope';
import { codeEmbedding } from '../fixtures/embedding';
+const oldStatsMessage = (createdAt: Date): typeof messages.$inferInsert => ({
+ id: '1',
+ userId,
+ role: 'user',
+ content: 'old message',
+ createdAt,
+});
+
+const newStatsMessage = (createdAt: Date): typeof messages.$inferInsert => ({
+ id: '2',
+ userId,
+ role: 'user',
+ content: 'new message',
+ createdAt,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'message-stats-test';
@@ -268,13 +284,7 @@ describe('MessageModel Statistics Tests', () => {
it('should count words within date range', async () => {
// Create test data
await serverDB.insert(messages).values([
- {
- id: '1',
- userId,
- role: 'user',
- content: 'old message',
- createdAt: new Date('2023-01-01'),
- },
+ oldStatsMessage(new Date('2023-01-01')),
{
id: '2',
userId,
@@ -308,22 +318,9 @@ describe('MessageModel Statistics Tests', () => {
});
it('should count words with startDate filter', async () => {
- await serverDB.insert(messages).values([
- {
- id: '1',
- userId,
- role: 'user',
- content: 'old message',
- createdAt: new Date('2023-01-01'),
- },
- {
- id: '2',
- userId,
- role: 'user',
- content: 'new message',
- createdAt: new Date('2023-03-01'),
- },
- ]);
+ await serverDB
+ .insert(messages)
+ .values([oldStatsMessage(new Date('2023-01-01')), newStatsMessage(new Date('2023-03-01'))]);
const result = await messageModel.countWords({ startDate: '2023-02-01' });
@@ -332,22 +329,9 @@ describe('MessageModel Statistics Tests', () => {
});
it('should count words with endDate filter', async () => {
- await serverDB.insert(messages).values([
- {
- id: '1',
- userId,
- role: 'user',
- content: 'old message',
- createdAt: new Date('2023-01-01'),
- },
- {
- id: '2',
- userId,
- role: 'user',
- content: 'new message',
- createdAt: new Date('2023-03-01'),
- },
- ]);
+ await serverDB
+ .insert(messages)
+ .values([oldStatsMessage(new Date('2023-01-01')), newStatsMessage(new Date('2023-03-01'))]);
const result = await messageModel.countWords({ endDate: '2023-02-01' });
diff --git a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
index 2c4eee9f596..8dc0c765b0c 100644
--- a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
@@ -6,6 +6,60 @@ import { agents, messages, sessions, threads, topics, users } from '../../../sch
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
+const continuationThreads = (): (typeof threads.$inferInsert)[] => [
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'continuation',
+ },
+];
+
+const firstMessage = (content: string): typeof messages.$inferInsert => ({
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content,
+ createdAt: new Date('2023-01-01'),
+});
+
+const sessionThreadMessage = (): typeof messages.$inferInsert => ({
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+});
+
+const agentThreadMessage = (): typeof messages.$inferInsert => ({
+ id: 'thread-msg1',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+});
+
+const assistantThreadMessage = (): typeof messages.$inferInsert => ({
+ id: 'thread-msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'thread-query-test-user';
@@ -77,28 +131,11 @@ describe('MessageModel thread query', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create thread with Continuation type
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'msg2',
- type: 'continuation',
- },
- ]);
+ await trx.insert(threads).values(continuationThreads());
// Create main conversation messages (parent messages)
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
+ firstMessage('first message'),
{
id: 'msg2',
userId,
@@ -120,26 +157,8 @@ describe('MessageModel thread query', () => {
createdAt: new Date('2023-01-03'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
+ sessionThreadMessage(),
+ assistantThreadMessage(),
]);
});
@@ -158,15 +177,7 @@ describe('MessageModel thread query', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create thread with Continuation type
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'msg2',
- type: 'continuation',
- },
- ]);
+ await trx.insert(threads).values(continuationThreads());
// Create main conversation messages (parent messages) with agentId
await trx.insert(messages).values([
@@ -191,16 +202,7 @@ describe('MessageModel thread query', () => {
createdAt: new Date('2023-01-02'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- agentId: 'agent1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
+ agentThreadMessage(),
{
id: 'thread-msg2',
userId,
@@ -235,15 +237,7 @@ describe('MessageModel thread query', () => {
]);
// Create thread with Continuation type
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'msg2',
- type: 'continuation',
- },
- ]);
+ await trx.insert(threads).values(continuationThreads());
// Create messages in topic1
await trx.insert(messages).values([
@@ -268,16 +262,7 @@ describe('MessageModel thread query', () => {
createdAt: new Date('2023-01-02'),
},
// Thread messages in topic1
- {
- id: 'thread-msg1',
- userId,
- agentId: 'agent1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
+ agentThreadMessage(),
{
id: 'delegated-thread-reply',
userId,
@@ -339,16 +324,7 @@ describe('MessageModel thread query', () => {
// Create main conversation messages
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
+ firstMessage('first message'),
{
id: 'msg2',
userId,
@@ -370,26 +346,8 @@ describe('MessageModel thread query', () => {
createdAt: new Date('2023-01-03'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
+ sessionThreadMessage(),
+ assistantThreadMessage(),
]);
});
@@ -450,16 +408,7 @@ describe('MessageModel thread query', () => {
createdAt: new Date('2023-01-03'),
},
// Thread messages
- {
- id: 'thread-msg1',
- userId,
- agentId: 'agent1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
+ agentThreadMessage(),
{
id: 'thread-msg2',
userId,
@@ -538,28 +487,11 @@ describe('MessageModel thread query', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
// Create thread
- await trx.insert(threads).values([
- {
- id: 'thread1',
- userId,
- topicId: 'topic1',
- sourceMessageId: 'msg2',
- type: 'continuation',
- },
- ]);
+ await trx.insert(threads).values(continuationThreads());
// Insert messages in non-chronological order
await trx.insert(messages).values([
- {
- id: 'thread-msg2',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'assistant',
- content: 'thread message 2',
- createdAt: new Date('2023-01-02T11:00:00'),
- },
+ assistantThreadMessage(),
{
id: 'msg2',
userId,
@@ -570,26 +502,8 @@ describe('MessageModel thread query', () => {
content: 'source message',
createdAt: new Date('2023-01-02'),
},
- {
- id: 'thread-msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: 'thread1',
- role: 'user',
- content: 'thread message 1',
- createdAt: new Date('2023-01-02T10:00:00'),
- },
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first message',
- createdAt: new Date('2023-01-01'),
- },
+ sessionThreadMessage(),
+ firstMessage('first message'),
]);
});
@@ -676,16 +590,7 @@ describe('MessageModel thread query', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first',
- createdAt: new Date('2023-01-01'),
- },
+ firstMessage('first'),
{
id: 'msg2',
userId,
@@ -775,16 +680,7 @@ describe('MessageModel thread query', () => {
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first',
- createdAt: new Date('2023-01-01'),
- },
+ firstMessage('first'),
{
id: 'msg2',
userId,
@@ -837,16 +733,7 @@ describe('MessageModel thread query', () => {
]);
await trx.insert(messages).values([
- {
- id: 'msg1',
- userId,
- sessionId: 'session1',
- topicId: 'topic1',
- threadId: null,
- role: 'user',
- content: 'first',
- createdAt: new Date('2023-01-01'),
- },
+ firstMessage('first'),
{
id: 'msg2',
userId,
diff --git a/packages/database/src/models/__tests__/thread.test.ts b/packages/database/src/models/__tests__/thread.test.ts
index 6b940f69b61..7125faa16dc 100644
--- a/packages/database/src/models/__tests__/thread.test.ts
+++ b/packages/database/src/models/__tests__/thread.test.ts
@@ -15,6 +15,20 @@ import {
import type { LobeChatDatabase } from '../../type';
import { ThreadModel } from '../thread';
+const activeStandaloneThread = (): typeof threads.$inferInsert => ({
+ id: 'thread-1',
+ topicId,
+ type: ThreadType.Standalone,
+ status: ThreadStatus.Active,
+ userId,
+});
+
+const customThread = (id: string): Parameters<ThreadModel['create']>[0] => ({
+ id,
+ topicId,
+ type: ThreadType.Standalone,
+});
+
const userId = 'thread-user-test';
const otherUserId = 'other-user-test';
const sessionId = 'thread-session';
@@ -67,32 +81,20 @@ describe('ThreadModel', () => {
it('should honor caller-provided id', async () => {
const customId = 'thd_custom_abc';
- const result = await threadModel.create({
- id: customId,
- topicId,
- type: ThreadType.Standalone,
- });
+ const result = await threadModel.create(customThread(customId));
expect(result.id).toBe(customId);
});
it('should return undefined when caller-provided id collides (onConflictDoNothing)', async () => {
const customId = 'thd_collide_xyz';
- const first = await threadModel.create({
- id: customId,
- topicId,
- type: ThreadType.Standalone,
- });
+ const first = await threadModel.create(customThread(customId));
expect(first.id).toBe(customId);
// The router layer translates this undefined into TRPCError(CONFLICT)
// so callers using client-provided ids see an explicit error instead
// of writing follow-up rows against a missing thread.
- const second = await threadModel.create({
- id: customId,
- topicId,
- type: ThreadType.Standalone,
- });
+ const second = await threadModel.create(customThread(customId));
expect(second).toBeUndefined();
});
});
@@ -131,13 +133,7 @@ describe('ThreadModel', () => {
await serverDB.transaction(async (tx) => {
await tx.insert(topics).values({ id: 'other-topic', userId: otherUserId });
await tx.insert(threads).values([
- {
- id: 'thread-1',
- topicId,
- type: ThreadType.Standalone,
- status: ThreadStatus.Active,
- userId,
- },
+ activeStandaloneThread(),
{
id: 'thread-2',
topicId: 'other-topic',
@@ -503,13 +499,7 @@ describe('ThreadModel', () => {
describe('delete', () => {
it('should delete a thread', async () => {
- await serverDB.insert(threads).values({
- id: 'thread-1',
- topicId,
- type: ThreadType.Standalone,
- status: ThreadStatus.Active,
- userId,
- });
+ await serverDB.insert(threads).values(activeStandaloneThread());
await threadModel.delete('thread-1');
@@ -547,13 +537,7 @@ describe('ThreadModel', () => {
await serverDB.transaction(async (tx) => {
await tx.insert(topics).values({ id: 'other-topic', userId: otherUserId });
await tx.insert(threads).values([
- {
- id: 'thread-1',
- topicId,
- type: ThreadType.Standalone,
- status: ThreadStatus.Active,
- userId,
- },
+ activeStandaloneThread(),
{
id: 'thread-2',
topicId,
diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.ts
index 168d01b1e4b..7b16331cb3e 100644
--- a/packages/database/src/models/__tests__/topicComment.test.ts
+++ b/packages/database/src/models/__tests__/topicComment.test.ts
@@ -24,6 +24,22 @@ import {
TopicCommentModel,
} from '../topicComment';
+const toolPlugin = (messageId: string, toolCallId: string): typeof messagePlugins.$inferInsert => ({
+ id: messageId,
+ toolCallId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+});
+
+const issueMessage = (messageId: string): typeof messages.$inferInsert => ({
+ content: 'investigate and update this issue',
+ id: messageId,
+ role: 'user',
+ topicId: workspaceTopicId,
+ userId: authorId,
+ workspaceId: workspaceAId,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const authorId = 'tc-author';
@@ -225,12 +241,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-assistant-group-final',
@@ -345,12 +356,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-narrated-group-final',
@@ -369,14 +375,7 @@ describe('TopicCommentModel', () => {
const toolMessageId = 'tc-trailing-status-tool';
const toolCallId = 'tc-trailing-status-call';
await serverDB.insert(messages).values([
- {
- content: 'investigate and update this issue',
- id: userMessageId,
- role: 'user',
- topicId: workspaceTopicId,
- userId: authorId,
- workspaceId: workspaceAId,
- },
+ issueMessage(userMessageId),
{
content: 'This is the actual answer.',
id: rootAssistantId,
@@ -406,12 +405,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-trailing-status-preview',
@@ -430,14 +424,7 @@ describe('TopicCommentModel', () => {
const toolMessageId = 'tc-single-mixed-tool';
const toolCallId = 'tc-single-mixed-call';
await serverDB.insert(messages).values([
- {
- content: 'investigate and update this issue',
- id: userMessageId,
- role: 'user',
- topicId: workspaceTopicId,
- userId: authorId,
- workspaceId: workspaceAId,
- },
+ issueMessage(userMessageId),
{
content: 'This is the answer outside the workflow.',
id: rootAssistantId,
@@ -467,12 +454,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-single-mixed-preview',
@@ -495,14 +477,7 @@ describe('TopicCommentModel', () => {
const erroredAnswer =
'The operation failed after producing this answer. The details remain visible.';
await serverDB.insert(messages).values([
- {
- content: 'investigate and update this issue',
- id: userMessageId,
- role: 'user',
- topicId: workspaceTopicId,
- userId: authorId,
- workspaceId: workspaceAId,
- },
+ issueMessage(userMessageId),
{
content: 'This is the earlier answer.',
id: rootAssistantId,
@@ -536,12 +511,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-mixed-error-preview',
@@ -593,12 +563,7 @@ describe('TopicCommentModel', () => {
workspaceId: workspaceAId,
},
]);
- await serverDB.insert(messagePlugins).values({
- id: toolMessageId,
- toolCallId,
- userId: authorId,
- workspaceId: workspaceAId,
- });
+ await serverDB.insert(messagePlugins).values(toolPlugin(toolMessageId, toolCallId));
const result = await authorModel.createWithMentions({
clientId: 'client-task-completion-preview',
diff --git a/packages/database/src/models/__tests__/topicDocument.test.ts b/packages/database/src/models/__tests__/topicDocument.test.ts
index 464c51f0aab..fca3f6281c7 100644
--- a/packages/database/src/models/__tests__/topicDocument.test.ts
+++ b/packages/database/src/models/__tests__/topicDocument.test.ts
@@ -70,18 +70,6 @@ describe('TopicDocumentModel', () => {
expect(result.topicId).toBe(topicId);
});
- it('should associate the same document with multiple topics', async () => {
- const doc = await createTestDocument(documentModel, 'Shared Document');
-
- await topicDocumentModel.associate({ documentId: doc.id, topicId });
- await topicDocumentModel.associate({ documentId: doc.id, topicId: topicId2 });
-
- const topicIds = await topicDocumentModel.findByDocumentId(doc.id);
- expect(topicIds).toHaveLength(2);
- expect(topicIds).toContain(topicId);
- expect(topicIds).toContain(topicId2);
- });
-
it('should associate multiple documents with the same topic', async () => {
const doc1 = await createTestDocument(documentModel, 'Document 1');
const doc2 = await createTestDocument(documentModel, 'Document 2');
diff --git a/packages/database/src/models/__tests__/verifyReport.test.ts b/packages/database/src/models/__tests__/verifyReport.test.ts
index 71afb421bf0..c4485967413 100644
--- a/packages/database/src/models/__tests__/verifyReport.test.ts
+++ b/packages/database/src/models/__tests__/verifyReport.test.ts
@@ -8,6 +8,17 @@ import { AgentOperationModel } from '../agentOperation';
import { VerifyReportModel } from '../verifyReport';
import { VerifyRunModel } from '../verifyRun';
+const createPassedReport = (
+ verifyRunId: string,
+): Parameters<VerifyReportModel['upsertByRun']>[0] => ({
+ failedChecks: 0,
+ passedChecks: 1,
+ totalChecks: 1,
+ uncertainChecks: 0,
+ verdict: 'passed',
+ verifyRunId,
+});
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'verify-report-test-user';
@@ -134,14 +145,7 @@ describe('VerifyReportModel', () => {
it('marks a report reviewed by its run', async () => {
const model = new VerifyReportModel(serverDB, userId);
- await model.upsertByRun({
- failedChecks: 0,
- passedChecks: 1,
- totalChecks: 1,
- uncertainChecks: 0,
- verdict: 'passed',
- verifyRunId,
- });
+ await model.upsertByRun(createPassedReport(verifyRunId));
await model.markReviewed(verifyRunId);
expect((await model.findByRun(verifyRunId))?.reviewedByUser).toBe(true);
@@ -149,14 +153,7 @@ describe('VerifyReportModel', () => {
it('survives deletion of the linked Agent Run (decoupled from agent_operations)', async () => {
const model = new VerifyReportModel(serverDB, userId);
- await model.upsertByRun({
- failedChecks: 0,
- passedChecks: 1,
- totalChecks: 1,
- uncertainChecks: 0,
- verdict: 'passed',
- verifyRunId,
- });
+ await model.upsertByRun(createPassedReport(verifyRunId));
// Deleting the operation only nulls verify_runs.operation_id; the session and
// its report live on.
@@ -166,14 +163,7 @@ describe('VerifyReportModel', () => {
it('cascades when its verification session is removed', async () => {
const model = new VerifyReportModel(serverDB, userId);
- await model.upsertByRun({
- failedChecks: 0,
- passedChecks: 1,
- totalChecks: 1,
- uncertainChecks: 0,
- verdict: 'passed',
- verifyRunId,
- });
+ await model.upsertByRun(createPassedReport(verifyRunId));
await new VerifyRunModel(serverDB, userId).delete(verifyRunId);
expect(await model.findByRun(verifyRunId)).toBeUndefined();
@@ -181,14 +171,7 @@ describe('VerifyReportModel', () => {
it('reads a report by id and hides it from other users', async () => {
const model = new VerifyReportModel(serverDB, userId);
- const created = await model.upsertByRun({
- failedChecks: 0,
- passedChecks: 1,
- totalChecks: 1,
- uncertainChecks: 0,
- verdict: 'passed',
- verifyRunId,
- });
+ const created = await model.upsertByRun(createPassedReport(verifyRunId));
expect((await model.findById(created.id))?.id).toBe(created.id);
expect(await model.findById('00000000-0000-0000-0000-000000000000')).toBeUndefined();
@@ -206,14 +189,7 @@ describe('VerifyReportModel', () => {
secondOperationId,
);
- const first = await model.upsertByRun({
- failedChecks: 0,
- passedChecks: 1,
- totalChecks: 1,
- uncertainChecks: 0,
- verdict: 'passed',
- verifyRunId,
- });
+ const first = await model.upsertByRun(createPassedReport(verifyRunId));
const second = await model.upsertByRun({
failedChecks: 1,
passedChecks: 0,
diff --git a/packages/database/src/models/agentEval/__tests__/benchmark.test.ts b/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
index 20db68ec829..f8f7c5866fb 100644
--- a/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
@@ -198,7 +198,6 @@ describe('AgentEvalBenchmarkModel', () => {
expect(results.map((r) => r.identifier)).toContain('system-1');
expect(results.map((r) => r.identifier)).toContain('user-1');
expect(results.map((r) => r.identifier)).toContain('system-2');
- expect(results.map((r) => r.identifier)).not.toContain('other-user-1');
});
it('should query only user-created benchmarks', async () => {
diff --git a/packages/database/src/models/agentEval/__tests__/dataset.test.ts b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
index b34b18d5d16..2f806ff8aa3 100644
--- a/packages/database/src/models/agentEval/__tests__/dataset.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
@@ -218,7 +218,6 @@ describe('AgentEvalDatasetModel', () => {
expect(results.map((r) => r.identifier)).toContain('user-dataset-1');
expect(results.map((r) => r.identifier)).toContain('user-dataset-2');
expect(results.map((r) => r.identifier)).toContain('system-dataset');
- expect(results.map((r) => r.identifier)).not.toContain('other-user-dataset');
});
it('should query datasets by benchmarkId', async () => {
diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.ts
index e4c6d188b1a..b9e1aa89230 100644
--- a/packages/database/src/models/agentEval/__tests__/run.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts
@@ -192,7 +192,6 @@ describe('AgentEvalRunModel', () => {
expect(results.map((r) => r.name)).toContain('Run 1');
expect(results.map((r) => r.name)).toContain('Run 2');
expect(results.map((r) => r.name)).toContain('Run 3');
- expect(results.map((r) => r.name)).not.toContain('Run 4 - Other User');
});
it('should filter by datasetId', async () => {
diff --git a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
index 9e0b0355e94..87f5d8083b9 100644
--- a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
+++ b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
@@ -16,6 +16,15 @@ import {
import type { LobeChatDatabase } from '../../../type';
import { AgentSignalReviewContextModel } from '../reviewContext';
+const createReviewAgents = (agentId: string, userId: string) => [
+ {
+ chatConfig: { selfIteration: { enabled: true } },
+ id: agentId,
+ title: 'Review Context Agent',
+ userId,
+ },
+];
+
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'agent-signal-review-context-user';
@@ -131,14 +140,7 @@ describe('AgentSignalReviewContextModel', () => {
describe('listToolActivity', () => {
it('groups tool activity by identifier and api name with clipped samples', async () => {
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(topics).values({
agentId,
id: topicId,
@@ -233,14 +235,7 @@ describe('AgentSignalReviewContextModel', () => {
const agentDocumentId = '00000000-0000-0000-0000-000000000101';
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(documents).values([
{
content: 'Reusable release workflow.',
@@ -316,14 +311,7 @@ describe('AgentSignalReviewContextModel', () => {
describe('listTopicActivity', () => {
it('returns bounded failed tool and message evidence for nightly self-review', async () => {
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(topics).values({
agentId,
id: topicId,
@@ -398,14 +386,7 @@ describe('AgentSignalReviewContextModel', () => {
const channelTopicId = 'agent-signal-review-context-channel-topic';
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(topics).values([
{
agentId,
@@ -558,14 +539,7 @@ describe('AgentSignalReviewContextModel', () => {
const otherTopicId = 'agent-signal-review-context-other-topic';
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(topics).values([
{
agentId,
@@ -655,14 +629,7 @@ describe('AgentSignalReviewContextModel', () => {
it('returns an empty list when the topic has no in-window activity', async () => {
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
await serverDB.insert(topics).values({
agentId,
id: topicId,
@@ -695,14 +662,7 @@ describe('AgentSignalReviewContextModel', () => {
const visitorTopicId = 'agent-signal-review-context-reflection-visitor-topic';
await serverDB.insert(users).values({ id: userId });
- await serverDB.insert(agents).values([
- {
- chatConfig: { selfIteration: { enabled: true } },
- id: agentId,
- title: 'Review Context Agent',
- userId,
- },
- ]);
+ await serverDB.insert(agents).values(createReviewAgents(agentId, userId));
// Agent-share visitor topic: stored under the creator's userId (billing
// attribution) but carries a visitor senderId, so it must be excluded.
await serverDB.insert(topics).values({
diff --git a/packages/database/src/models/userMemory/__tests__/activity.test.ts b/packages/database/src/models/userMemory/__tests__/activity.test.ts
index 8d3ee0a7874..0ae704dd6a7 100644
--- a/packages/database/src/models/userMemory/__tests__/activity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/activity.test.ts
@@ -82,17 +82,13 @@ describe('UserMemoryActivityModel', () => {
]);
});
- it('should return activities for current user only', async () => {
+ it('returns current user activities newest first', async () => {
const result = await activityModel.query();
expect(result).toHaveLength(2);
expect(result.every((a) => a.userId === userId)).toBe(true);
- });
-
- it('should order by createdAt desc', async () => {
- const result = await activityModel.query();
- expect(result[0].id).toBe('activity-2'); // Most recent first
+ expect(result[0].id).toBe('activity-2');
expect(result[1].id).toBe('activity-1');
});
@@ -195,22 +191,21 @@ describe('UserMemoryActivityModel', () => {
]);
});
- it('should return paginated list with default parameters', async () => {
+ it('returns the default activity page with associations and owner scope', async () => {
const result = await activityModel.queryList();
expect(result.items).toHaveLength(3);
expect(result.page).toBe(1);
expect(result.pageSize).toBe(20);
expect(result.total).toBe(3);
- });
- it('returns the associated names, which pages link activities by', async () => {
- const result = await activityModel.queryList();
const item = result.items.find((row) => row.id === 'list-activity-1');
-
expect(item?.associatedSubjects).toEqual([{ name: '陈老师', type: 'person' }]);
expect(item?.associatedObjects).toEqual([{ name: 'IELTS' }]);
expect(item?.associatedLocations).toEqual([{ name: 'Office' }]);
+
+ const otherActivity = result.items.find((a) => a.id === 'other-list-activity');
+ expect(otherActivity).toBeUndefined();
});
it('should return correct page and pageSize', async () => {
@@ -358,13 +353,6 @@ describe('UserMemoryActivityModel', () => {
expect(result.items[1].id).toBe('list-activity-2');
});
- it('should not return other users activities', async () => {
- const result = await activityModel.queryList();
-
- const otherActivity = result.items.find((a) => a.id === 'other-list-activity');
- expect(otherActivity).toBeUndefined();
- });
-
it('should return correct fields structure', async () => {
const result = await activityModel.queryList({ pageSize: 1 });
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
index ed2b9ab9df5..ad255cb629d 100644
--- a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
@@ -15,6 +15,16 @@ import type { LobeChatDatabase } from '../../../type';
import { deriveContextStatus, UserMemoryConsolidationModel } from '../consolidation';
import { UserMemoryContextModel } from '../context';
+const createInitialContextPlan = (
+ contextId: string,
+): Parameters<UserMemoryConsolidationModel['applyContextPlan']>[1] => ({
+ dossiers: [{ memberIds: [contextId], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+});
+
const userId = 'consolidation-test-user';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -164,13 +174,7 @@ describe('UserMemoryConsolidationModel', () => {
it('extends an existing context and dossier in a later run', async () => {
const a = await createLegacy('scheduler backend', '2026-05-01');
- const first = await model.applyContextPlan('run_3', {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- });
+ const first = await model.applyContextPlan('run_3', createInitialContextPlan(a.context.id));
// Written by current extraction: has a single parent, but is still legacy, not consolidated.
const b = await createLegacy('scheduler cron mode', '2026-06-01', { singleParent: true });
const consolidated = await model.listConsolidated();
@@ -220,13 +224,7 @@ describe('UserMemoryConsolidationModel', () => {
it('reverts a run that updated the same context and dossier in several chunks', async () => {
const a = await createLegacy('scheduler backend', '2026-05-01');
- const first = await model.applyContextPlan('run_5', {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- });
+ const first = await model.applyContextPlan('run_5', createInitialContextPlan(a.context.id));
const chunk = async (title: string, day: string, version: string) => {
const legacy = await createLegacy(title, day);
await model.applyContextPlan('run_6', {
@@ -290,13 +288,7 @@ describe('UserMemoryConsolidationModel', () => {
it('ignores evidence a committed plan already filed when a step is retried', async () => {
const a = await createLegacy('scheduler backend', '2026-05-01');
- const plan = {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- };
+ const plan = createInitialContextPlan(a.context.id);
const first = await model.applyContextPlan('run_9', plan);
expect(first.activities).toBe(1);
expect(await model.getLegacyContextsByIds([a.context.id])).toEqual([]);
@@ -316,13 +308,7 @@ describe('UserMemoryConsolidationModel', () => {
it('keeps parent summaries in step with extended contexts and dossiers', async () => {
const a = await createLegacy('scheduler backend', '2026-05-01');
- const first = await model.applyContextPlan('run_10', {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- });
+ const first = await model.applyContextPlan('run_10', createInitialContextPlan(a.context.id));
const b = await createLegacy('scheduler cron mode', '2026-06-01');
await model.applyContextPlan('run_11', {
dossiers: [
@@ -363,13 +349,7 @@ describe('UserMemoryConsolidationModel', () => {
it('refuses to revert a run a later run extended, until the later one is reverted', async () => {
const a = await createLegacy('scheduler backend', '2026-05-01');
- const first = await model.applyContextPlan('run_12', {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- });
+ const first = await model.applyContextPlan('run_12', createInitialContextPlan(a.context.id));
expect(await model.listFiledContextIds('run_12', [a.context.id])).toEqual([first.contextId]);
const b = await createLegacy('scheduler cron mode', '2026-06-01');
await model.applyContextPlan('run_13', {
@@ -412,13 +392,7 @@ describe('UserMemoryConsolidationModel', () => {
{ id: a.context.id, key: 'product/tasks', route: 'evidence' },
{ id: b.context.id, key: 'product/tasks', route: 'evidence' },
]);
- const filed = await model.applyContextPlan('run_a', {
- dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
- nextSteps: [],
- now: 'v1',
- openQuestions: [],
- title: 'Task system',
- });
+ const filed = await model.applyContextPlan('run_a', createInitialContextPlan(a.context.id));
// run_a stops here: b is still queued.
expect(await model.findResumableQueue()).toEqual({
count: 1,
diff --git a/packages/database/src/models/userMemory/__tests__/context.test.ts b/packages/database/src/models/userMemory/__tests__/context.test.ts
index d6b813f8b47..cf93461de5a 100644
--- a/packages/database/src/models/userMemory/__tests__/context.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/context.test.ts
@@ -78,17 +78,13 @@ describe('UserMemoryContextModel', () => {
]);
});
- it('should return contexts for current user only', async () => {
+ it('returns current user contexts newest first', async () => {
const result = await contextModel.query();
expect(result).toHaveLength(2);
expect(result.every((c) => c.userId === userId)).toBe(true);
- });
-
- it('should order by createdAt desc', async () => {
- const result = await contextModel.query();
- expect(result[0].id).toBe('context-2'); // Most recent first
+ expect(result[0].id).toBe('context-2');
expect(result[1].id).toBe('context-1');
});
diff --git a/packages/database/src/models/userMemory/__tests__/experience.test.ts b/packages/database/src/models/userMemory/__tests__/experience.test.ts
index 7f2b6e21dae..533117d2350 100644
--- a/packages/database/src/models/userMemory/__tests__/experience.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/experience.test.ts
@@ -82,17 +82,13 @@ describe('UserMemoryExperienceModel', () => {
]);
});
- it('should return experiences for current user only', async () => {
+ it('returns current user experiences newest first', async () => {
const result = await experienceModel.query();
expect(result).toHaveLength(2);
expect(result.every((e) => e.userId === userId)).toBe(true);
- });
-
- it('should order by createdAt desc', async () => {
- const result = await experienceModel.query();
- expect(result[0].id).toBe('experience-2'); // Most recent first
+ expect(result[0].id).toBe('experience-2');
expect(result[1].id).toBe('experience-1');
});
@@ -389,13 +385,16 @@ describe('UserMemoryExperienceModel', () => {
]);
});
- it('should return paginated list with default parameters', async () => {
+ it('returns the default experience page within the user scope', async () => {
const result = await experienceModel.queryList();
expect(result.items).toHaveLength(3);
expect(result.page).toBe(1);
expect(result.pageSize).toBe(20);
expect(result.total).toBe(3);
+
+ const otherExperience = result.items.find((e) => e.id === 'other-list-exp');
+ expect(otherExperience).toBeUndefined();
});
it('should return correct page and pageSize', async () => {
@@ -532,13 +531,6 @@ describe('UserMemoryExperienceModel', () => {
expect(result.items[2].id).toBe('list-exp-3'); // 0.7
});
- it('should not return other users experiences', async () => {
- const result = await experienceModel.queryList();
-
- const otherExperience = result.items.find((e) => e.id === 'other-list-exp');
- expect(otherExperience).toBeUndefined();
- });
-
it('should return correct fields structure', async () => {
const result = await experienceModel.queryList({ pageSize: 1 });
diff --git a/packages/database/src/models/userMemory/__tests__/identity.test.ts b/packages/database/src/models/userMemory/__tests__/identity.test.ts
index c5040d21386..d66b9fcfe74 100644
--- a/packages/database/src/models/userMemory/__tests__/identity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/identity.test.ts
@@ -84,17 +84,13 @@ describe('UserMemoryIdentityModel', () => {
]);
});
- it('should return identities for current user only', async () => {
+ it('returns current user identities by descending capture time', async () => {
const result = await identityModel.query();
expect(result).toHaveLength(2);
expect(result.every((i) => i.userId === userId)).toBe(true);
- });
-
- it('should order by capturedAt desc', async () => {
- const result = await identityModel.query();
- expect(result[0].id).toBe('identity-2'); // Most recent first
+ expect(result[0].id).toBe('identity-2');
expect(result[1].id).toBe('identity-1');
});
@@ -400,13 +396,16 @@ describe('UserMemoryIdentityModel', () => {
expect(result.total).toBe(2);
});
- it('should return all relationships when specified', async () => {
+ it('returns requested identity relationships within the user scope', async () => {
const result = await identityModel.queryList({
relationships: [RelationshipEnum.Self, RelationshipEnum.Friend],
});
expect(result.items).toHaveLength(3);
expect(result.total).toBe(3);
+
+ const otherIdentity = result.items.find((i) => i.id === 'other-list-id');
+ expect(otherIdentity).toBeUndefined();
});
it('should return correct page and pageSize', async () => {
@@ -553,15 +552,6 @@ describe('UserMemoryIdentityModel', () => {
expect(result.items[1].type).toBe('professional');
});
- it('should not return other users identities', async () => {
- const result = await identityModel.queryList({
- relationships: [RelationshipEnum.Self, RelationshipEnum.Friend],
- });
-
- const otherIdentity = result.items.find((i) => i.id === 'other-list-id');
- expect(otherIdentity).toBeUndefined();
- });
-
it('should return correct fields structure', async () => {
const result = await identityModel.queryList({ pageSize: 1 });
@@ -627,7 +617,7 @@ describe('UserMemoryIdentityModel', () => {
]);
});
- it('should only return self and null relationship identities', async () => {
+ it('returns ordered self and unassigned identities with injection fields', async () => {
const result = await identityModel.queryForInjection();
expect(result).toHaveLength(2);
@@ -636,24 +626,9 @@ describe('UserMemoryIdentityModel', () => {
expect(ids).toContain('self-identity');
expect(ids).toContain('null-relationship-identity');
expect(ids).not.toContain('friend-identity');
- });
-
- it('should order by capturedAt desc', async () => {
- const result = await identityModel.queryForInjection();
- expect(result[0].id).toBe('self-identity'); // Most recent capturedAt
- expect(result[1].id).toBe('null-relationship-identity');
- });
-
- it('should respect limit parameter', async () => {
- const result = await identityModel.queryForInjection(1);
-
- expect(result).toHaveLength(1);
expect(result[0].id).toBe('self-identity');
- });
-
- it('should return correct fields for injection', async () => {
- const result = await identityModel.queryForInjection();
+ expect(result[1].id).toBe('null-relationship-identity');
expect(result[0]).toHaveProperty('id');
expect(result[0]).toHaveProperty('type');
@@ -664,6 +639,13 @@ describe('UserMemoryIdentityModel', () => {
expect(result[0]).toHaveProperty('updatedAt');
});
+ it('should respect limit parameter', async () => {
+ const result = await identityModel.queryForInjection(1);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('self-identity');
+ });
+
it('does not inject an identity whose base memory is in the recycle bin', async () => {
const [memory] = await serverDB
.insert(userMemories)
diff --git a/packages/database/src/models/userMemory/__tests__/preference.test.ts b/packages/database/src/models/userMemory/__tests__/preference.test.ts
index 103e69f94dd..d6df95e0843 100644
--- a/packages/database/src/models/userMemory/__tests__/preference.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/preference.test.ts
@@ -80,17 +80,13 @@ describe('UserMemoryPreferenceModel', () => {
]);
});
- it('should return preferences for current user only', async () => {
+ it('returns current user preferences newest first', async () => {
const result = await preferenceModel.query();
expect(result).toHaveLength(2);
expect(result.every((p) => p.userId === userId)).toBe(true);
- });
-
- it('should order by createdAt desc', async () => {
- const result = await preferenceModel.query();
- expect(result[0].id).toBe('preference-2'); // Most recent first
+ expect(result[0].id).toBe('preference-2');
expect(result[1].id).toBe('preference-1');
});
diff --git a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
index 4ae7b61b3ad..4949f055fa4 100644
--- a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
+++ b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts
@@ -17,6 +17,30 @@ import { getTestDB } from '../../../../core/getTestDB';
import { DeprecatedDataImporterRepos as DataImporterRepos } from '../index';
import mockImportData from './fixtures/messages.json';
+type ImportSession = NonNullable<ImporterEntryData['sessions']>[number];
+
+const createImportConfig = (model = 'abc', systemRole = 'abc'): ImportSession['config'] => ({
+ model,
+ chatConfig: {} as any,
+ params: {},
+ systemRole,
+ tts: {} as any,
+ openingQuestions: [],
+});
+
+const createImportSession = (
+ id: string,
+ title: string,
+ config = createImportConfig(),
+): ImportSession => ({
+ id,
+ createdAt: '2022-05-14T18:18:10.494Z',
+ updatedAt: '2023-01-01',
+ type: 'agent',
+ config,
+ meta: { title },
+});
+
const CURRENT_CONFIG_VERSION = 7;
const serverDB = await getTestDB();
@@ -84,40 +108,8 @@ describe('DataImporter', () => {
const data: ImporterEntryData = {
version: CURRENT_CONFIG_VERSION,
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
+ createImportSession('session1', 'Session 1'),
+ createImportSession('session2', 'Session 2'),
],
};
@@ -148,40 +140,8 @@ describe('DataImporter', () => {
const data: ImporterEntryData = {
version: CURRENT_CONFIG_VERSION,
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
+ createImportSession('session1', 'Session 1'),
+ createImportSession('session2', 'Session 2'),
],
};
@@ -206,14 +166,7 @@ describe('DataImporter', () => {
updatedAt: '2023-01-01',
type: 'agent',
group: 'group1',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
+ config: createImportConfig(),
meta: {
title: 'Session 1',
},
@@ -224,14 +177,7 @@ describe('DataImporter', () => {
createdAt: '2022-05-14T18:18:10.494Z',
updatedAt: '2023-01-01',
type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
+ config: createImportConfig(),
meta: {
title: 'Session 2',
},
@@ -242,14 +188,7 @@ describe('DataImporter', () => {
createdAt: '2022-05-14T18:18:10.494Z',
updatedAt: '2023-01-01',
type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
+ config: createImportConfig(),
meta: {
title: 'Session 3',
},
@@ -284,40 +223,8 @@ describe('DataImporter', () => {
const data: ImporterEntryData = {
version: CURRENT_CONFIG_VERSION,
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- {
- id: 'session2',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'def',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 2',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 2',
- },
- },
+ createImportSession('session1', 'Session 1', createImportConfig('abc', 'Test Agent 1')),
+ createImportSession('session2', 'Session 2', createImportConfig('def', 'Test Agent 2')),
],
};
@@ -366,23 +273,7 @@ describe('DataImporter', () => {
// First import some sessions
await importer.importData({
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
+ createImportSession('session1', 'Session 1', createImportConfig('abc', 'Test Agent 1')),
],
version: CURRENT_CONFIG_VERSION,
});
@@ -390,23 +281,7 @@ describe('DataImporter', () => {
// Import the same sessions again
await importer.importData({
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'Test Agent 1',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
+ createImportSession('session1', 'Session 1', createImportConfig('abc', 'Test Agent 1')),
],
version: CURRENT_CONFIG_VERSION,
});
@@ -440,23 +315,7 @@ describe('DataImporter', () => {
},
],
sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
+ createImportSession('session1', 'Session 1'),
{
id: 'session2',
createdAt: '2022-05-14T18:18:10.494Z',
@@ -510,25 +369,7 @@ describe('DataImporter', () => {
it('should associate imported topics with sessions', async () => {
const data: ImporterEntryData = {
version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
+ sessions: [createImportSession('session1', 'Session 1')],
topics: [
{
id: 'topic1',
@@ -586,25 +427,7 @@ describe('DataImporter', () => {
parentId: 'msg1',
},
],
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
+ sessions: [createImportSession('session1', 'Session 1')],
topics: [
{
id: 'topic1',
@@ -690,25 +513,7 @@ describe('DataImporter', () => {
it('should associate imported messages with sessions and topics', async () => {
const data: ImporterEntryData = {
version: CURRENT_CONFIG_VERSION,
- sessions: [
- {
- id: 'session1',
- createdAt: '2022-05-14T18:18:10.494Z',
- updatedAt: '2023-01-01',
- type: 'agent',
- config: {
- model: 'abc',
- chatConfig: {} as any,
- params: {},
- systemRole: 'abc',
- tts: {} as any,
- openingQuestions: [],
- },
- meta: {
- title: 'Session 1',
- },
- },
- ],
+ sessions: [createImportSession('session1', 'Session 1')],
topics: [
{
id: 'topic1',
@@ -807,8 +612,6 @@ describe('DataImporter', () => {
expect(msg2?.parent?.clientId).toBe('msg1');
});
-
- it('should import parentId Success', () => {});
});
describe('real world examples', { timeout: 15000 }, () => {
diff --git a/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts b/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts
index a90f93113aa..6e7e547d81c 100644
--- a/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts
+++ b/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts
@@ -155,18 +155,12 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
expect(topicResults[0].title).toBe('React Hooks Guide');
});
- // Note: ICU tokenizer treats "react-component.jsx" as a single token,
- // so we search by prefix "react" which matches via BM25
- it('should find files by name', async () => {
+ it('finds results across all types with the matching file name', async () => {
const results = await ftsSearchRepo.search({ query: 'react' });
const fileResults = results.filter((r) => r.type === 'file');
expect(fileResults).toHaveLength(1);
expect(fileResults[0].title).toBe('react-component.jsx');
- });
-
- it('should find results across all types', async () => {
- const results = await ftsSearchRepo.search({ query: 'react' });
// Should find: 1 agent, 1 topic, 1 file
expect(results.length).toBeGreaterThanOrEqual(3);
@@ -224,24 +218,16 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
await serverDB.insert(agents).values(testAgents);
});
- it('should assign relevance values in valid range', async () => {
+ it('returns ranked relevance values within the valid range', async () => {
const results = await ftsSearchRepo.search({ query: 'test' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBe(3);
- // All relevance values should be in [1, 3] range
for (const result of agentResults) {
expect(result.relevance).toBeGreaterThanOrEqual(1);
expect(result.relevance).toBeLessThanOrEqual(3);
}
- });
-
- it('should rank results by BM25 relevance (lower = better)', async () => {
- const results = await ftsSearchRepo.search({ query: 'test' });
-
- const agentResults = results.filter((r) => r.type === 'agent');
- expect(agentResults.length).toBe(3);
// Best match should have lowest relevance value
expect(agentResults[0].relevance).toBeLessThanOrEqual(agentResults[1].relevance);
@@ -296,7 +282,7 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
});
});
- it('should only return current user results', async () => {
+ it('returns current-user results and excludes the foreign agent', async () => {
const results = await ftsSearchRepo.search({ query: 'agent' });
expect(results.length).toBeGreaterThan(0);
@@ -305,11 +291,6 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
results.forEach((result) => {
expect(result.title).not.toContain('Other');
});
- });
-
- it('should not return other user agents', async () => {
- const results = await ftsSearchRepo.search({ query: 'agent' });
-
const otherAgent = results.find((r) => r.title === 'Other Agent');
expect(otherAgent).toBeUndefined();
});
@@ -590,16 +571,22 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
});
});
- it('should include topics from all agents when agentId is not provided', async () => {
+ it('includes topics from all agents with default limits and relevance', async () => {
const results = await ftsSearchRepo.search({
query: 'testing',
});
const topicResults = results.filter((r) => r.type === 'topic');
+ expect(topicResults.length).toBeLessThanOrEqual(3);
const agentIds = new Set(topicResults.map((t) => (t.type === 'topic' ? t.agentId : null)));
expect(agentIds.has(testAgentId)).toBe(true);
expect(agentIds.has(otherAgentId)).toBe(true);
+
+ topicResults.forEach((topic) => {
+ expect(topic.relevance).toBeGreaterThanOrEqual(1);
+ expect(topic.relevance).toBeLessThanOrEqual(3);
+ });
});
it('should populate agent metadata on topic results', async () => {
@@ -731,30 +718,6 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
expect(agentResults.length).toBeLessThanOrEqual(3);
expect(fileResults.length).toBeLessThanOrEqual(3);
});
-
- it('should use normal limits without agent context', async () => {
- const results = await ftsSearchRepo.search({
- query: 'testing',
- });
-
- const topicResults = results.filter((r) => r.type === 'topic');
-
- // Should use default limit of 3 per type
- expect(topicResults.length).toBeLessThanOrEqual(3);
- });
-
- it('should return topics with normal relevance range (1-3) when agentId is not provided', async () => {
- const results = await ftsSearchRepo.search({
- query: 'testing',
- });
-
- const topicResults = results.filter((r) => r.type === 'topic');
-
- topicResults.forEach((topic) => {
- expect(topic.relevance).toBeGreaterThanOrEqual(1);
- expect(topic.relevance).toBeLessThanOrEqual(3);
- });
- });
});
describe('search - folder search', () => {
@@ -966,17 +929,22 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
expect(results).toEqual([]);
});
- it('should match documents within KB scope by content', async () => {
+ it('returns scoped knowledge-base documents with bounded snippets and relevance', async () => {
const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
expect(results.length).toBeGreaterThan(0);
// Should hit ML overview, not cooking
expect(results.some((r) => r.title === 'Machine Learning Overview')).toBe(true);
expect(results.every((r) => r.knowledgeBaseId === kbA)).toBe(true);
- });
-
- it('should respect KB scope (KB-A query does not return KB-B docs)', async () => {
- const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
expect(results.every((r) => r.title !== 'Machine Learning in KB-B')).toBe(true);
+
+ results.forEach((r) => {
+ expect(r.snippet.length).toBeLessThanOrEqual(303); // 300 + '...' suffix
+ });
+
+ results.forEach((r) => {
+ expect(r.relevance).toBeGreaterThanOrEqual(1);
+ expect(r.relevance).toBeLessThanOrEqual(3);
+ });
});
it('should isolate across users', async () => {
@@ -1036,21 +1004,6 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
expect(publicAgentResults).toEqual([]);
});
- it('should produce snippet ≤ 300 characters', async () => {
- const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
- results.forEach((r) => {
- expect(r.snippet.length).toBeLessThanOrEqual(303); // 300 + '...' suffix
- });
- });
-
- it('should produce relevance in [1, 3] range', async () => {
- const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
- results.forEach((r) => {
- expect(r.relevance).toBeGreaterThanOrEqual(1);
- expect(r.relevance).toBeLessThanOrEqual(3);
- });
- });
-
describe('file-backed documents (PDF / parsed files)', () => {
const pdfFileId = 'file-bm25-pdf-1';
const pdfDocId = 'docs-bm25-pdf-1';
@@ -1227,7 +1180,7 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
]);
});
- it('should expand pages to 6 in page context', async () => {
+ it('expands pages while capping other types in page context', async () => {
const results = await ftsSearchRepo.search({
contextType: 'page',
query: 'context test',
@@ -1235,13 +1188,6 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
const pageResults = results.filter((r) => r.type === 'page');
expect(pageResults.length).toBe(6);
- });
-
- it('should limit other types to 3 in page context', async () => {
- const results = await ftsSearchRepo.search({
- contextType: 'page',
- query: 'context test',
- });
const agentResults = results.filter((r) => r.type === 'agent');
const topicResults = results.filter((r) => r.type === 'topic');
@@ -1581,10 +1527,25 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
expect(new Set(results.map((r) => r.type))).toEqual(new Set(REWRITTEN_RESULT_TYPES));
};
- it('should never surface workspace-scoped rows in personal mode', async () => {
+ it('keeps personal rows and their joined agent metadata', async () => {
const results = await createRepo(serverDB, userId).search({ query: 'Kubernetes' });
expectEveryHitScopedTo(results, 'personal');
+
+ const topic = results.find((r) => r.type === 'topic');
+ expect(topic).toBeDefined();
+ if (topic?.type === 'topic') {
+ expect(topic.agentId).toBe(personalAgentId);
+ expect(topic.agent?.title).toBe('Kubernetes Personal Agent');
+ }
+
+ const message = results.find((r) => r.type === 'message');
+ expect(message).toBeDefined();
+ if (message?.type === 'message') {
+ expect(message.agentId).toBe(personalAgentId);
+ // messages render the owning agent's title as their subtitle
+ expect(message.description).toBe('Kubernetes Personal Agent');
+ }
});
it('should never surface personal rows in workspace mode', async () => {
@@ -1608,25 +1569,6 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
}
});
- it('should keep joined agent metadata on topics and messages after the scan split', async () => {
- const results = await createRepo(serverDB, userId).search({ query: 'Kubernetes' });
-
- const topic = results.find((r) => r.type === 'topic');
- expect(topic).toBeDefined();
- if (topic?.type === 'topic') {
- expect(topic.agentId).toBe(personalAgentId);
- expect(topic.agent?.title).toBe('Kubernetes Personal Agent');
- }
-
- const message = results.find((r) => r.type === 'message');
- expect(message).toBeDefined();
- if (message?.type === 'message') {
- expect(message.agentId).toBe(personalAgentId);
- // messages render the owning agent's title as their subtitle
- expect(message.description).toBe('Kubernetes Personal Agent');
- }
- });
-
it('should keep knowledgeBaseId on files after the scan split', async () => {
const [file] = await serverDB
.select({ id: files.id })
@@ -1684,7 +1626,7 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
]);
});
- it('should only surface the requested agent rows in topics and messages', async () => {
+ it('returns only requested-agent rows with their joined metadata', async () => {
const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });
const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
@@ -1694,6 +1636,14 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
(r) => (r.type === 'topic' || r.type === 'message') && r.agentId !== agentAId,
);
expect(foreign.map((r) => `${r.type}: ${r.title}`)).toEqual([]);
+
+ const topic = results.find((r) => r.type === 'topic');
+ expect(topic).toBeDefined();
+ if (topic?.type === 'topic') expect(topic.agent?.title).toBe('Terraform Agent A');
+
+ const message = results.find((r) => r.type === 'message');
+ expect(message).toBeDefined();
+ if (message?.type === 'message') expect(message.description).toBe('Terraform Agent A');
});
it('should not leak rows between two agent-scoped searches', async () => {
@@ -1719,17 +1669,5 @@ export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehavi
);
expect(agentIds).toEqual(new Set([agentAId, agentBId, null]));
});
-
- it('should keep joined agent metadata after the agent filter moved above the scan', async () => {
- const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });
-
- const topic = results.find((r) => r.type === 'topic');
- expect(topic).toBeDefined();
- if (topic?.type === 'topic') expect(topic.agent?.title).toBe('Terraform Agent A');
-
- const message = results.find((r) => r.type === 'message');
- expect(message).toBeDefined();
- if (message?.type === 'message') expect(message.description).toBe('Terraform Agent A');
- });
});
};
diff --git a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
index 76e14beba0b..49687f6867f 100644
--- a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
+++ b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts
@@ -418,7 +418,7 @@ describe('FtsSearchRepo (pg_like)', () => {
{ lastAccessedAt: now, tags: ['personal'], title: 'Kubernetes hobby', userId },
])
.returning({ id: userMemories.id });
- const [split, ownOnly, mismatch, untagged] = await serverDB
+ const [split, , , untagged] = await serverDB
.insert(userMemoriesActivities)
.values([
// typescript on the layer, project on the parent: every tag is present
@@ -464,7 +464,6 @@ describe('FtsSearchRepo (pg_like)', () => {
query: { text: 'kubernetes' },
});
expect(all.candidates.map((candidate) => candidate.id)).toEqual([split.id]);
- expect(all.candidates.map((candidate) => candidate.id)).not.toContain(ownOnly.id);
const any = await repo.ftsSearchCandidates({
entity: 'memoryActivities',
@@ -475,8 +474,6 @@ describe('FtsSearchRepo (pg_like)', () => {
expect(any.candidates.map((candidate) => candidate.id).sort()).toEqual(
[split.id, untagged.id].sort(),
);
- expect(any.candidates.map((candidate) => candidate.id)).not.toContain(mismatch.id);
- expect(any.candidates.map((candidate) => candidate.id)).not.toContain(ownOnly.id);
});
it('applies the memory time range before the candidate limit', async () => {
@@ -504,7 +501,7 @@ describe('FtsSearchRepo (pg_like)', () => {
it('applies an activity time range on the requested field', async () => {
const day = (offset: number) => new Date(Date.UTC(2026, 0, 1 + offset));
- const [early, late] = await serverDB
+ const [, late] = await serverDB
.insert(userMemoriesActivities)
.values([
{ narrative: 'Kubernetes early', startsAt: day(1), type: 'event', userId },
@@ -521,7 +518,6 @@ describe('FtsSearchRepo (pg_like)', () => {
});
expect(response.candidates.map((candidate) => candidate.id)).toEqual([late.id]);
- expect(response.candidates.map((candidate) => candidate.id)).not.toContain(early.id);
});
it('reports a bounded pool as cut only when matches lie past its cutoff', async () => {
@@ -611,7 +607,7 @@ describe('FtsSearchRepo (pg_like)', () => {
.insert(sessions)
.values([{ userId }])
.returning({ id: sessions.id });
- const [topicA, topicB, topicGroup, topicSession] = await serverDB
+ const [topicA, , topicGroup, topicSession] = await serverDB
.insert(topics)
.values([
{ agentId: agentA.id, title: 'Kubernetes topic A', userId },
@@ -656,7 +652,6 @@ describe('FtsSearchRepo (pg_like)', () => {
query: { text: 'kubernetes' },
});
expect(ids(topicsByContainer)).toEqual([topicSession.id]);
- expect(ids(topicsByContainer)).not.toContain(topicB.id);
// Topic-bound messages may carry no agent id; they survive scope pruning so
// the consumer can resolve their parent topic.
diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.ts
index e6e7b3cfddf..d0b3f75238e 100644
--- a/packages/database/src/repositories/knowledge/index.test.ts
+++ b/packages/database/src/repositories/knowledge/index.test.ts
@@ -111,31 +111,6 @@ describe('KnowledgeRepo', () => {
await serverDB.insert(documents).values(testDocuments);
});
- it('should exclude documents with fileType="custom/document" from Documents category', async () => {
- const results = await knowledgeRepo.query({ category: FilesTabs.Documents });
-
- // Should not include editor document (custom/document)
- const editorDoc = results.find((item) => item.name === 'editor-doc.md');
- expect(editorDoc).toBeUndefined();
- });
-
- it('should exclude documents with sourceType="file" from Documents category', async () => {
- const results = await knowledgeRepo.query({ category: FilesTabs.Documents });
-
- // Should not include uploaded PDF document (sourceType='file')
- const uploadedPdf = results.find((item) => item.name === 'uploaded-pdf.pdf');
- expect(uploadedPdf).toBeUndefined();
- });
-
- it('should exclude document-table rows from Documents category (files only)', async () => {
- const results = await knowledgeRepo.query({ category: FilesTabs.Documents });
-
- // Documents means uploaded document FILES; derived document rows stay out
- expect(results.find((item) => item.name === 'api-pdf.pdf')).toBeUndefined();
- expect(results.find((item) => item.name === 'web-doc.txt')).toBeUndefined();
- expect(results.every((item) => item.sourceType === 'file')).toBe(true);
- });
-
it('should surface custom/* document rows under the Pages category', async () => {
const results = await knowledgeRepo.query({ category: FilesTabs.Pages });
@@ -147,15 +122,6 @@ describe('KnowledgeRepo', () => {
expect(results.every((item) => item.sourceType === 'document')).toBe(true);
});
- it('should include files from files table in Documents category', async () => {
- const results = await knowledgeRepo.query({ category: FilesTabs.Documents });
-
- // Should include regular files
- const regularFile = results.find((item) => item.name === 'regular-pdf-file.pdf');
- expect(regularFile).toBeDefined();
- expect(regularFile?.sourceType).toBe('file');
- });
-
it('should exclude sourceType=file documents from All category', async () => {
const results = await knowledgeRepo.query({ category: FilesTabs.All });
@@ -181,14 +147,25 @@ describe('KnowledgeRepo', () => {
expect(regularFile).toBeDefined();
});
- it('should keep the Documents category free of document-table rows', async () => {
+ it('keeps Documents limited to uploaded files', async () => {
const results = await knowledgeRepo.query({ category: FilesTabs.Documents });
+ // Documents means uploaded document FILES; derived document rows stay out
+ const editorDoc = results.find((item) => item.name === 'editor-doc.md');
+ expect(editorDoc).toBeUndefined();
+ const uploadedPdf = results.find((item) => item.name === 'uploaded-pdf.pdf');
+ expect(uploadedPdf).toBeUndefined();
+ expect(results.find((item) => item.name === 'api-pdf.pdf')).toBeUndefined();
+ expect(results.find((item) => item.name === 'web-doc.txt')).toBeUndefined();
+
const documentTypeItems = results.filter((item) => item.sourceType === 'document');
expect(documentTypeItems).toHaveLength(0);
+ expect(results.every((item) => item.sourceType === 'file')).toBe(true);
// the uploaded pdf file from the files table is still there
- expect(results.find((item) => item.name === 'regular-pdf-file.pdf')).toBeDefined();
+ const regularFile = results.find((item) => item.name === 'regular-pdf-file.pdf');
+ expect(regularFile).toBeDefined();
+ expect(regularFile?.sourceType).toBe('file');
});
});
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 7e3650de5ba..ac67e3ae4bf 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -2,6 +2,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GatewayHttpClient } from './http';
+const createAgentRunInput = (): Parameters<GatewayHttpClient['dispatchAgentRun']>[0] => ({
+ agentType: 'claude-code',
+ assistantMessageId: 'asst-1',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+});
+
+const createSuccessfulToolResponse = () => ({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+});
+
describe('GatewayHttpClient', () => {
let client: GatewayHttpClient;
@@ -418,10 +433,7 @@ describe('GatewayHttpClient', () => {
});
it('should pass optional deviceId and timeout', async () => {
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
const signal = AbortSignal.abort();
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(signal);
@@ -449,10 +461,7 @@ describe('GatewayHttpClient', () => {
// answers 503 DEVICE_OFFLINE. Aborting earlier turned every offline
// device into "timed out, the work may still be running".
const GATEWAY_RECOVERY_WINDOW_MS = 45_000;
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(AbortSignal.abort());
await client.executeToolCall(
@@ -464,10 +473,7 @@ describe('GatewayHttpClient', () => {
});
it('never pads a call past the agent function window', async () => {
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(AbortSignal.abort());
await client.executeToolCall(
@@ -479,10 +485,7 @@ describe('GatewayHttpClient', () => {
});
it('should pass optional operationId', async () => {
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
await client.executeToolCall(
{ operationId: 'op-1', userId: 'user-1' },
@@ -495,10 +498,7 @@ describe('GatewayHttpClient', () => {
});
it('should use default gateway timeout plus HTTP caller padding when timeout is absent', async () => {
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
const signal = AbortSignal.abort();
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(signal);
@@ -522,15 +522,7 @@ describe('GatewayHttpClient', () => {
ok: true,
});
- const result = await client.dispatchAgentRun({
- agentType: 'claude-code',
- assistantMessageId: 'asst-1',
- jwt: 'jwt',
- operationId: 'op-1',
- prompt: 'run',
- topicId: 'tpc-1',
- userId: 'user-1',
- });
+ const result = await client.dispatchAgentRun(createAgentRunInput());
expect(result).toEqual({ success: true });
expect(fetch).toHaveBeenCalledWith(
@@ -547,15 +539,7 @@ describe('GatewayHttpClient', () => {
ok: true,
});
- const result = await client.dispatchAgentRun({
- agentType: 'claude-code',
- assistantMessageId: 'asst-1',
- jwt: 'jwt',
- operationId: 'op-1',
- prompt: 'run',
- topicId: 'tpc-1',
- userId: 'user-1',
- });
+ const result = await client.dispatchAgentRun(createAgentRunInput());
expect(result).toEqual({ success: true });
});
@@ -569,15 +553,7 @@ describe('GatewayHttpClient', () => {
ok: true,
});
- const result = await client.dispatchAgentRun({
- agentType: 'claude-code',
- assistantMessageId: 'asst-1',
- jwt: 'jwt',
- operationId: 'op-1',
- prompt: 'run',
- topicId: 'tpc-1',
- userId: 'user-1',
- });
+ const result = await client.dispatchAgentRun(createAgentRunInput());
expect(result).toEqual({ error: 'spawn failed', success: false });
});
@@ -588,15 +564,7 @@ describe('GatewayHttpClient', () => {
ok: true,
});
- const result = await client.dispatchAgentRun({
- agentType: 'claude-code',
- assistantMessageId: 'asst-1',
- jwt: 'jwt',
- operationId: 'op-1',
- prompt: 'run',
- topicId: 'tpc-1',
- userId: 'user-1',
- });
+ const result = await client.dispatchAgentRun(createAgentRunInput());
expect(result).toEqual({ error: 'DEVICE_OFFLINE', success: false });
});
@@ -608,15 +576,7 @@ describe('GatewayHttpClient', () => {
text: vi.fn().mockResolvedValue('DEVICE_OFFLINE'),
});
- const result = await client.dispatchAgentRun({
- agentType: 'claude-code',
- assistantMessageId: 'asst-1',
- jwt: 'jwt',
- operationId: 'op-1',
- prompt: 'run',
- topicId: 'tpc-1',
- userId: 'user-1',
- });
+ const result = await client.dispatchAgentRun(createAgentRunInput());
expect(result).toEqual({ error: 'DEVICE_OFFLINE', success: false });
});
@@ -776,10 +736,7 @@ describe('GatewayHttpClient', () => {
});
it('should pass optional deviceId and timeout', async () => {
- mockFetch({
- json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
- ok: true,
- });
+ mockFetch(createSuccessfulToolResponse());
await client.executeMessageApi(
{ deviceId: 'device-1', timeout: 5000, userId: 'user-1' },
diff --git a/packages/file-loaders/src/utils/parser-utils.test.ts b/packages/file-loaders/src/utils/parser-utils.test.ts
index be9c4fb0c0f..72d09d90f63 100644
--- a/packages/file-loaders/src/utils/parser-utils.test.ts
+++ b/packages/file-loaders/src/utils/parser-utils.test.ts
@@ -4,6 +4,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ExtractedFile } from './parser-utils';
import { extractFiles, parseString } from './parser-utils';
+type ZipEventHandler = (payload?: unknown) => void;
+
+const zipModule = (fakeZipfile: unknown) => ({
+ default: {
+ fromBuffer: (_buf: Buffer, _opts: any, cb: (err: any, zf?: any) => void) =>
+ cb(null, fakeZipfile),
+ },
+});
+
describe('parser-utils', () => {
describe('parseString', () => {
it('should parse valid XML string into XMLDocument', () => {
@@ -49,7 +58,7 @@ describe('parser-utils', () => {
it('should read entries via yauzl.fromBuffer and filter matches', async () => {
// Arrange: build a fake zipfile object with two file entries and one directory
const entryHandlers: Record<string, (cb: () => void) => void> = {};
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
let idx = 0;
const sequence = [
{ fileName: 'folder/' },
@@ -91,7 +100,7 @@ describe('parser-utils', () => {
cb(null, undefined as any);
}
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
@@ -117,7 +126,7 @@ describe('parser-utils', () => {
});
it('should open zip by file path when input is string', async () => {
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
let idx = 0;
const entries = [{ fileName: 'keep.txt' }];
const emit2 = (name: string, payload?: any) =>
@@ -146,7 +155,7 @@ describe('parser-utils', () => {
};
cb(null, stream);
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
@@ -168,7 +177,7 @@ describe('parser-utils', () => {
});
it('should handle openReadStream error', async () => {
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
const emit = (name: string, payload?: any) =>
(listeners[name] || []).forEach((fn) => fn(payload));
@@ -179,19 +188,14 @@ describe('parser-utils', () => {
openReadStream: vi.fn((entry: any, cb: (err: any, stream?: any) => void) => {
cb(new Error('Failed to open stream'));
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
close: vi.fn(),
} as any;
- vi.doMock('yauzl', () => ({
- default: {
- fromBuffer: (_buf: Buffer, _opts: any, cb: (err: any, zf?: any) => void) =>
- cb(null, fakeZipfile),
- },
- }));
+ vi.doMock('yauzl', () => zipModule(fakeZipfile));
const { extractFiles: mockedExtractFiles } = await import('./parser-utils');
@@ -201,7 +205,7 @@ describe('parser-utils', () => {
});
it('should handle null readStream', async () => {
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
const emit = (name: string, payload?: any) =>
(listeners[name] || []).forEach((fn) => fn(payload));
@@ -212,19 +216,14 @@ describe('parser-utils', () => {
openReadStream: vi.fn((entry: any, cb: (err: any, stream?: any) => void) => {
cb(null, null); // readStream is null
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
close: vi.fn(),
} as any;
- vi.doMock('yauzl', () => ({
- default: {
- fromBuffer: (_buf: Buffer, _opts: any, cb: (err: any, zf?: any) => void) =>
- cb(null, fakeZipfile),
- },
- }));
+ vi.doMock('yauzl', () => zipModule(fakeZipfile));
const { extractFiles: mockedExtractFiles } = await import('./parser-utils');
@@ -234,8 +233,8 @@ describe('parser-utils', () => {
});
it('should handle readStream error', async () => {
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
- const streamListeners: Record<string, Function[]> = { error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
+ const streamListeners: Record<string, ZipEventHandler[]> = { error: [] };
const emit = (name: string, payload?: any) =>
(listeners[name] || []).forEach((fn) => fn(payload));
@@ -246,7 +245,7 @@ describe('parser-utils', () => {
openReadStream: vi.fn((entry: any, cb: (err: any, stream?: any) => void) => {
const stream = {
pipe: vi.fn().mockReturnThis(),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
streamListeners[evt] = streamListeners[evt] || [];
streamListeners[evt].push(handler);
// Immediately trigger error
@@ -257,19 +256,14 @@ describe('parser-utils', () => {
};
cb(null, stream);
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
close: vi.fn(),
} as any;
- vi.doMock('yauzl', () => ({
- default: {
- fromBuffer: (_buf: Buffer, _opts: any, cb: (err: any, zf?: any) => void) =>
- cb(null, fakeZipfile),
- },
- }));
+ vi.doMock('yauzl', () => zipModule(fakeZipfile));
const { extractFiles: mockedExtractFiles } = await import('./parser-utils');
@@ -279,7 +273,7 @@ describe('parser-utils', () => {
});
it('should handle zipfile error', async () => {
- const listeners: Record<string, Function[]> = { entry: [], end: [], error: [] };
+ const listeners: Record<string, ZipEventHandler[]> = { entry: [], end: [], error: [] };
const emit = (name: string, payload?: any) =>
(listeners[name] || []).forEach((fn) => fn(payload));
@@ -287,19 +281,14 @@ describe('parser-utils', () => {
readEntry: vi.fn().mockImplementation(() => {
queueMicrotask(() => emit('error', new Error('Zipfile error')));
}),
- on: vi.fn((evt: string, handler: Function) => {
+ on: vi.fn((evt: string, handler: ZipEventHandler) => {
listeners[evt] = listeners[evt] || [];
listeners[evt].push(handler);
}),
close: vi.fn(),
} as any;
- vi.doMock('yauzl', () => ({
- default: {
- fromBuffer: (_buf: Buffer, _opts: any, cb: (err: any, zf?: any) => void) =>
- cb(null, fakeZipfile),
- },
- }));
+ vi.doMock('yauzl', () => zipModule(fakeZipfile));
const { extractFiles: mockedExtractFiles } = await import('./parser-utils');
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 51ea23ec6f4..1bc7b90b8eb 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -2,6 +2,19 @@ import { describe, expect, it } from 'vitest';
import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from '.';
+const createToolUseEvent = (
+ messageId: string,
+ toolId: string,
+ toolName: string,
+ input: unknown,
+) => ({
+ message: {
+ id: messageId,
+ content: [{ id: toolId, input, name: toolName, type: 'tool_use' }],
+ },
+ type: 'assistant',
+});
+
describe('ClaudeCodeAdapter', () => {
describe('run cost', () => {
// CC restores the session's cost tally on `--resume`, so `total_cost_usd`
@@ -831,13 +844,7 @@ describe('ClaudeCodeAdapter', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- const events = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: { path: '/a' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const events = adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', { path: '/a' }));
const chunk = events.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
@@ -873,20 +880,9 @@ describe('ClaudeCodeAdapter', () => {
],
};
- const events = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- {
- id: 'tu_aq_1',
- input: askInput,
- name: 'mcp__lobe_cc__ask_user_question',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
+ const events = adapter.adapt(
+ createToolUseEvent('msg_1', 'tu_aq_1', 'mcp__lobe_cc__ask_user_question', askInput),
+ );
const chunk = events.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
@@ -908,13 +904,7 @@ describe('ClaudeCodeAdapter', () => {
it('emits tool_result event with content for user tool_result block', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
const events = adapter.adapt({
message: {
@@ -939,20 +929,9 @@ describe('ClaudeCodeAdapter', () => {
it('aligns tool_end with the server shape — carries payload + result', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- {
- id: 't1',
- input: { command: 'git worktree add ../wt' },
- name: 'Bash',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(
+ createToolUseEvent('msg_1', 't1', 'Bash', { command: 'git worktree add ../wt' }),
+ );
const events = adapter.adapt({
message: {
@@ -980,13 +959,7 @@ describe('ClaudeCodeAdapter', () => {
it('handles array-shaped tool_result content', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Bash', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Bash', {}));
const events = adapter.adapt({
message: {
@@ -1012,13 +985,7 @@ describe('ClaudeCodeAdapter', () => {
it('marks isError when tool_result is_error is true', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
const events = adapter.adapt({
message: {
@@ -1232,15 +1199,7 @@ describe('ClaudeCodeAdapter', () => {
it('joins tool_reference blocks into newline-separated tool names', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- { id: 'ts1', input: { query: 'linear' }, name: 'ToolSearch', type: 'tool_use' },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'ts1', 'ToolSearch', { query: 'linear' }));
const events = adapter.adapt({
message: {
@@ -1280,15 +1239,7 @@ describe('ClaudeCodeAdapter', () => {
it('mixes tool_reference with text blocks in a single tool_result', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- { id: 'ts1', input: { query: 'search' }, name: 'ToolSearch', type: 'tool_use' },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'ts1', 'ToolSearch', { query: 'search' }));
const events = adapter.adapt({
message: {
@@ -1314,13 +1265,7 @@ describe('ClaudeCodeAdapter', () => {
it('skips tool_reference entries with no tool_name', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 'ts1', input: { query: 'x' }, name: 'ToolSearch', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'ts1', 'ToolSearch', { query: 'x' }));
const events = adapter.adapt({
message: {
@@ -1356,13 +1301,7 @@ describe('ClaudeCodeAdapter', () => {
it('renders image blocks as a non-empty placeholder and preserves base64 on pluginState.images', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 'r1', input: { file_path: 'x.png' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'r1', 'Read', { file_path: 'x.png' }));
const events = adapter.adapt({
message: {
@@ -1398,13 +1337,7 @@ describe('ClaudeCodeAdapter', () => {
it('falls back to generic label when media_type is missing', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 'r1', input: { file_path: 'x' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'r1', 'Read', { file_path: 'x' }));
const events = adapter.adapt({
message: {
@@ -1429,13 +1362,7 @@ describe('ClaudeCodeAdapter', () => {
describe('TodoWrite pluginState synthesis', () => {
const driveTodoWrite = (adapter: ClaudeCodeAdapter, input: unknown, toolId = 't1') => {
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: toolId, input, name: 'TodoWrite', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', toolId, 'TodoWrite', input));
const events = adapter.adapt({
message: {
content: [
@@ -1495,13 +1422,7 @@ describe('ClaudeCodeAdapter', () => {
it('does not set pluginState for non-TodoWrite tools', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: { path: '/a' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', { path: '/a' }));
const events = adapter.adapt({
message: {
content: [{ content: 'ok', tool_use_id: 't1', type: 'tool_result' }],
@@ -1519,20 +1440,11 @@ describe('ClaudeCodeAdapter', () => {
// live todo UI with changes that never actually happened.
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- {
- id: 't1',
- input: { todos: [{ activeForm: 'A', content: 'a', status: 'pending' }] },
- name: 'TodoWrite',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(
+ createToolUseEvent('msg_1', 't1', 'TodoWrite', {
+ todos: [{ activeForm: 'A', content: 'a', status: 'pending' }],
+ }),
+ );
const events = adapter.adapt({
message: {
content: [
@@ -1553,20 +1465,11 @@ describe('ClaudeCodeAdapter', () => {
// Cache must still be drained — a later TodoWrite on a new id should
// synthesize only from its own args, not inherit the failed one.
- adapter.adapt({
- message: {
- id: 'msg_2',
- content: [
- {
- id: 't2',
- input: { todos: [{ activeForm: 'B', content: 'b', status: 'completed' }] },
- name: 'TodoWrite',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(
+ createToolUseEvent('msg_2', 't2', 'TodoWrite', {
+ todos: [{ activeForm: 'B', content: 'b', status: 'completed' }],
+ }),
+ );
const next = adapter.adapt({
message: {
content: [{ content: 'ok', tool_use_id: 't2', type: 'tool_result' }],
@@ -1587,20 +1490,11 @@ describe('ClaudeCodeAdapter', () => {
// Second TodoWrite on a new tool_use id — should resynthesize from its
// own args, not leak from the prior cache.
- adapter.adapt({
- message: {
- id: 'msg_2',
- content: [
- {
- id: 't2',
- input: { todos: [{ activeForm: 'B', content: 'b', status: 'completed' }] },
- name: 'TodoWrite',
- type: 'tool_use',
- },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(
+ createToolUseEvent('msg_2', 't2', 'TodoWrite', {
+ todos: [{ activeForm: 'B', content: 'b', status: 'completed' }],
+ }),
+ );
const events = adapter.adapt({
message: {
content: [{ content: 'ok', tool_use_id: 't2', type: 'tool_result' }],
@@ -1624,13 +1518,7 @@ describe('ClaudeCodeAdapter', () => {
msgId: string,
opts?: { isError?: boolean },
) => {
- adapter.adapt({
- message: {
- id: msgId,
- content: [{ id: toolId, input, name: 'TaskCreate', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent(msgId, toolId, 'TaskCreate', input));
const events = adapter.adapt({
message: {
content: [
@@ -1669,13 +1557,7 @@ describe('ClaudeCodeAdapter', () => {
msgId: string,
opts?: { isError?: boolean },
) => {
- adapter.adapt({
- message: {
- id: msgId,
- content: [{ id: toolId, input, name: 'TaskUpdate', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent(msgId, toolId, 'TaskUpdate', input));
const events = adapter.adapt({
message: {
content: [
@@ -1706,13 +1588,7 @@ describe('ClaudeCodeAdapter', () => {
resultContent: string,
msgId: string,
) => {
- adapter.adapt({
- message: {
- id: msgId,
- content: [{ id: toolId, input: {}, name: 'TaskList', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent(msgId, toolId, 'TaskList', {}));
const events = adapter.adapt({
message: {
content: [{ content: resultContent, tool_use_id: toolId, type: 'tool_result' }],
@@ -2093,15 +1969,7 @@ describe('ClaudeCodeAdapter', () => {
adapter.adapt({ subtype: 'init', type: 'system' });
// 1. Assistant issues a tool_use under msg_1.
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [
- { id: 'tu_1', input: { command: 'mock command' }, name: 'Bash', type: 'tool_use' },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 'tu_1', 'Bash', { command: 'mock command' }));
// 2. Tool returns.
adapter.adapt({
@@ -2144,15 +2012,7 @@ describe('ClaudeCodeAdapter', () => {
// Second turn (NEW id) — opened by a real newStep, so the reducer's
// currentMainMessageId becomes msg_2. This turn issues a tool_use.
- adapter.adapt({
- message: {
- id: 'msg_2',
- content: [
- { id: 'tu_1', input: { command: 'mock command' }, name: 'Bash', type: 'tool_use' },
- ],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_2', 'tu_1', 'Bash', { command: 'mock command' }));
adapter.adapt({
message: {
content: [{ content: 'mock tool output', tool_use_id: 'tu_1', type: 'tool_result' }],
@@ -2359,13 +2219,7 @@ describe('ClaudeCodeAdapter', () => {
adapter.adapt({ subtype: 'init', type: 'system' });
// Start a tool call without providing result
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
const events = adapter.flush();
expect(events).toHaveLength(1);
@@ -2381,13 +2235,7 @@ describe('ClaudeCodeAdapter', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
adapter.flush();
// Second flush should be empty
@@ -2480,26 +2328,14 @@ describe('ClaudeCodeAdapter', () => {
adapter.adapt({ subtype: 'init', type: 'system' });
// First tool_use block of msg_1
- const e1 = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: { path: '/a' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const e1 = adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', { path: '/a' }));
const chunk1 = e1.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
);
expect(chunk1!.data.toolsCalling.map((t: any) => t.id)).toEqual(['t1']);
// Second tool_use block on the SAME message.id — must carry both t1 + t2
- const e2 = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't2', input: { cmd: 'ls' }, name: 'Bash', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const e2 = adapter.adapt(createToolUseEvent('msg_1', 't2', 'Bash', { cmd: 'ls' }));
const chunk2 = e2.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
);
@@ -2510,21 +2346,9 @@ describe('ClaudeCodeAdapter', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
- const e2 = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't2', input: {}, name: 'Bash', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const e2 = adapter.adapt(createToolUseEvent('msg_1', 't2', 'Bash', {}));
const starts = e2.filter((e) => e.type === 'tool_start');
expect(starts).toHaveLength(1);
@@ -2535,23 +2359,11 @@ describe('ClaudeCodeAdapter', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
// 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_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const e2 = adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
const chunk = e2.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
@@ -2564,21 +2376,9 @@ describe('ClaudeCodeAdapter', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
- adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: {}, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', {}));
- const events = adapter.adapt({
- message: {
- id: 'msg_2',
- content: [{ id: 't2', input: {}, name: 'Bash', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const events = adapter.adapt(createToolUseEvent('msg_2', 't2', 'Bash', {}));
const chunk = events.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
@@ -2734,13 +2534,7 @@ describe('ClaudeCodeAdapter', () => {
// Same message.id continues with a tool_use block — tool_use never streams
// as delta (input_json_delta would be partial JSON), so handleAssistant
// remains the source of truth for tool invocations.
- const events = adapter.adapt({
- message: {
- id: 'msg_1',
- content: [{ id: 't1', input: { path: '/a' }, name: 'Read', type: 'tool_use' }],
- },
- type: 'assistant',
- });
+ const events = adapter.adapt(createToolUseEvent('msg_1', 't1', 'Read', { path: '/a' }));
const toolsChunk = events.find(
(e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',
diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
index 3f491f92526..5aebdf48101 100644
--- a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
@@ -23,7 +23,7 @@ describe('createFileStoreImageUploader', () => {
vi.unstubAllGlobals();
});
- it('uploads the bytes to S3 and returns the created file reference', async () => {
+ it('uploads a tool-result image and returns its stored file reference', async () => {
const port = createPort();
const upload = createFileStoreImageUploader(async () => port);
@@ -41,27 +41,21 @@ describe('createFileStoreImageUploader', () => {
pathname: expect.stringMatching(/^files\/\d{4}-\d{2}-\d{2}\/[a-f0-9]{64}\.png$/),
size: Buffer.from(PNG_BASE64, 'base64').length,
});
+ expect(port.checkFileHash).toHaveBeenCalledWith({ hash: PNG_HASH });
const createFileInput = vi.mocked(port.createFile).mock.calls[0][0];
expect(createFileInput).toMatchObject({
fileType: 'image/png',
+ hash: PNG_HASH,
name: 'cc-read-image.png',
size: Buffer.from(PNG_BASE64, 'base64').length,
+ // Run tokens may create tool-result attachments outside a Task run.
+ source: 'tool-result',
});
// `url` is the S3 pathname, not the pre-signed URL.
expect(createFileInput.url).toMatch(/^files\/\d{4}-\d{2}-\d{2}\/[a-f0-9]{64}\.png$/);
- });
-
- it('files the image as a tool-result attachment, the one source a run token may create', async () => {
- // A remote device uploads under the run's operation token, which may file
- // only `tool-result` images outside a Task run; it also keeps the image out
- // of the library when a desktop uploads under its own session.
- const port = createPort();
- const upload = createFileStoreImageUploader(async () => port);
-
- await upload({ data: PNG_BASE64, mediaType: 'image/png' });
-
- expect(vi.mocked(port.createFile).mock.calls[0][0].source).toBe('tool-result');
+ expect(createFileInput.metadata).not.toHaveProperty('width');
+ expect(createFileInput.metadata).not.toHaveProperty('ratio');
});
it('records the intrinsic size on the file metadata, matching the web uploader', async () => {
@@ -77,17 +71,6 @@ describe('createFileStoreImageUploader', () => {
});
});
- it('omits size metadata when the dimensions are unknown', async () => {
- const port = createPort();
- const upload = createFileStoreImageUploader(async () => port);
-
- await upload({ data: PNG_BASE64, mediaType: 'image/png' });
-
- const { metadata } = vi.mocked(port.createFile).mock.calls[0][0];
- expect(metadata).not.toHaveProperty('width');
- expect(metadata).not.toHaveProperty('ratio');
- });
-
it('reuses the stored object and skips the S3 PUT when the hash already exists', async () => {
const port = createPort({
checkFileHash: vi.fn().mockResolvedValue({ isExist: true, url: 'files/old/abc.png' }),
@@ -101,16 +84,6 @@ describe('createFileStoreImageUploader', () => {
expect(vi.mocked(port.createFile).mock.calls[0][0].url).toBe('files/old/abc.png');
});
- it('hashes the decoded bytes so identical images dedup across runs', async () => {
- const port = createPort();
- const upload = createFileStoreImageUploader(async () => port);
-
- await upload({ data: PNG_BASE64, mediaType: 'image/png' });
-
- expect(port.checkFileHash).toHaveBeenCalledWith({ hash: PNG_HASH });
- expect(vi.mocked(port.createFile).mock.calls[0][0].hash).toBe(PNG_HASH);
- });
-
it('falls back to a png extension for an unknown media type', async () => {
const port = createPort();
const upload = createFileStoreImageUploader(async () => port);
diff --git a/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts
index e32c9fd46fe..ab56278d972 100644
--- a/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts
+++ b/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts
@@ -93,34 +93,24 @@ describe('content search engine parity', () => {
pattern: 'needle',
scope: repo,
} as GrepContentParams);
- return [engine, [...r.matches].sort()] as const;
+ return [engine, r.matches] as const;
}),
);
// `dist/` and `*.log` are gitignored and must go; the tracked `build/` must
// stay, because only git decides what is build output — not the folder name.
for (const [engine, matches] of results) {
- expect(matches, `${engine} should honour .gitignore`).toEqual([
+ for (const match of matches) {
+ expect(path.isAbsolute(match), `${engine} returned a relative path: ${match}`).toBe(true);
+ }
+
+ expect([...matches].sort(), `${engine} should honour .gitignore`).toEqual([
path.join(repo, 'build', 'entitlements.plist'),
path.join(repo, 'src', 'a.ts'),
]);
}
}, 60_000);
- it('returns absolute paths from every engine', async () => {
- for (const engine of engines) {
- const r = await search(engine, {
- output_mode: 'files_with_matches',
- pattern: 'needle',
- scope: repo,
- } as GrepContentParams);
-
- for (const match of r.matches) {
- expect(path.isAbsolute(match), `${engine} returned a relative path: ${match}`).toBe(true);
- }
- }
- }, 60_000);
-
it('still searches a directory the caller explicitly scopes into, even if ignored', async () => {
for (const engine of engines) {
const r = await search(engine, {
diff --git a/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
index f43ed702e5a..79734c501dc 100644
--- a/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
@@ -145,17 +145,11 @@ describe('BaseFileSearch', () => {
expect(results[0].engine).toBe('mdfind');
});
- it('should handle undefined engine', async () => {
+ it('should infer content type without an engine', async () => {
const options: SearchOptions = { keywords: 'test' };
const results = await fileSearch.testProcessFilePaths(['/test/file.ts'], options);
expect(results[0].engine).toBeUndefined();
- });
-
- it('should determine content type from extension', async () => {
- const options: SearchOptions = { keywords: 'test' };
- const results = await fileSearch.testProcessFilePaths(['/test/file.ts'], options);
-
expect(results[0].contentType).toBe('code');
});
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index bc5cf7ffd35..fc179f939b9 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -7,6 +7,24 @@ import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import { getRuntimeSignatureScopeSource } from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import { createRouterRuntime } from './createRuntime';
+import type { RouterInstance, RouterOptions } from './routerOptions';
+
+const createOpenAITestRuntime = (
+ runtime: NonNullable<RouterInstance['runtime']>,
+ models: string[],
+ options: RouterOptions,
+) =>
+ createRouterRuntime({
+ id: 'test-runtime',
+ routers: [
+ {
+ apiType: 'openai',
+ options,
+ runtime,
+ models,
+ },
+ ],
+ });
describe('createRouterRuntime', () => {
beforeEach(() => {
@@ -45,16 +63,8 @@ describe('createRouterRuntime', () => {
textToSpeech = vi.fn();
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: { apiKey: 'test-key' },
- runtime: MockRuntime as any,
- models: ['gpt-4', 'gpt-3.5-turbo'],
- },
- ],
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4', 'gpt-3.5-turbo'], {
+ apiKey: 'test-key',
});
const runtime = new Runtime();
@@ -119,17 +129,7 @@ describe('createRouterRuntime', () => {
chat = mockChat;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4'], {});
const runtime = new Runtime();
const payload = { model: 'gpt-4', messages: [], temperature: 0.7 };
@@ -342,17 +342,7 @@ describe('createRouterRuntime', () => {
chat = mockChat;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: { id: 'channel-1' },
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4'], { id: 'channel-1' });
const runtime = new Runtime();
const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'chat' };
@@ -410,17 +400,7 @@ describe('createRouterRuntime', () => {
const handleError = vi.fn().mockReturnValue(undefined);
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4'], {});
const runtime = new Runtime({
chat: {
@@ -511,17 +491,7 @@ describe('createRouterRuntime', () => {
embeddings = mockEmbeddings;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['text-embedding-ada-002'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['text-embedding-ada-002'], {});
const runtime = new Runtime();
const payload = { model: 'text-embedding-ada-002', input: 'test input' };
@@ -541,17 +511,7 @@ describe('createRouterRuntime', () => {
textToSpeech = mockTextToSpeech;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['tts-1'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['tts-1'], {});
const runtime = new Runtime();
const payload = { model: 'tts-1', input: 'Hello world', voice: 'alloy' };
@@ -1595,17 +1555,11 @@ describe('createRouterRuntime', () => {
chat = mockChatAlwaysFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: AlwaysFailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ AlwaysFailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -1759,20 +1713,14 @@ describe('createRouterRuntime', () => {
chat = mockChatSuccess;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [
- { apiKey: 'key-1', runtime: FailRuntime as any },
- { apiKey: 'key-2', runtime: SuccessRuntime as any },
- ],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [
+ { apiKey: 'key-1', runtime: FailRuntime as any },
+ { apiKey: 'key-2', runtime: SuccessRuntime as any },
],
- });
+ );
const runtime = new Runtime();
await expect(
@@ -1801,17 +1749,11 @@ describe('createRouterRuntime', () => {
chat = mockChatFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -1963,17 +1905,11 @@ describe('createRouterRuntime', () => {
chat = mockChatFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -2004,17 +1940,11 @@ describe('createRouterRuntime', () => {
chat = mockChatFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -2088,17 +2018,11 @@ describe('createRouterRuntime', () => {
chat = mockChatFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -2123,17 +2047,11 @@ describe('createRouterRuntime', () => {
chat = mockChatFail;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
- runtime: FailRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ FailRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ );
const runtime = new Runtime();
await expect(
@@ -2153,17 +2071,11 @@ describe('createRouterRuntime', () => {
chat = vi.fn().mockResolvedValue('response');
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: [{ apiKey: 'openai-key' }, { apiKey: 'anthropic-key', apiType: 'anthropic' }],
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(
+ MockRuntime as any,
+ ['gpt-4'],
+ [{ apiKey: 'openai-key' }, { apiKey: 'anthropic-key', apiType: 'anthropic' }],
+ );
const runtime = new Runtime();
await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });
@@ -2359,17 +2271,7 @@ describe('createRouterRuntime', () => {
createImage = mockCreateImage;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['gpt-image-1'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-image-1'], {});
const runtime = new Runtime();
const payload = { model: 'gpt-image-1', params: { prompt: 'a cat' } };
@@ -2426,17 +2328,7 @@ describe('createRouterRuntime', () => {
getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['sora-1'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['sora-1'], {});
const runtime = new Runtime();
const payload = { model: 'sora-1', params: { prompt: 'a cat' } } as any;
@@ -2734,17 +2626,7 @@ describe('createRouterRuntime', () => {
generateObject = mockGenerateObject;
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4'], {});
const runtime = new Runtime();
const payload = { model: 'gpt-4', messages: [{ role: 'user' as const, content: 'test' }] };
@@ -2798,17 +2680,7 @@ describe('createRouterRuntime', () => {
chat = vi.fn().mockResolvedValue('response');
}
- const Runtime = createRouterRuntime({
- id: 'test-runtime',
- routers: [
- {
- apiType: 'openai',
- options: {},
- runtime: MockRuntime as any,
- models: ['gpt-4'],
- },
- ],
- });
+ const Runtime = createOpenAITestRuntime(MockRuntime as any, ['gpt-4'], {});
const runtime = new Runtime({
apiKey: ' trimmed-key ',
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
index dc126a294f1..166ed8b38db 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
@@ -6,6 +6,15 @@ import {
createAnthropicGenerateObject,
} from './generateObject';
+const createToolPayload = () => ({
+ messages: [{ content: 'Generate data', role: 'user' as const }],
+ model: 'claude-3-5-sonnet-20241022',
+ schema: {
+ name: 'test_tool',
+ schema: { type: 'object' },
+ },
+});
+
describe('Anthropic generateObject', () => {
it('should throw error when neither tools nor schema is provided', async () => {
const mockClient = {
@@ -546,14 +555,7 @@ describe('Anthropic generateObject', () => {
},
};
- const payload = {
- messages: [{ content: 'Generate data', role: 'user' as const }],
- model: 'claude-3-5-sonnet-20241022',
- schema: {
- name: 'test_tool',
- schema: { type: 'object' },
- },
- };
+ const payload = createToolPayload();
const result = await createAnthropicGenerateObject(mockClient as any, payload as any);
@@ -830,14 +832,7 @@ describe('Anthropic generateObject', () => {
},
};
- const payload = {
- messages: [{ content: 'Generate data', role: 'user' as const }],
- model: 'claude-3-5-sonnet-20241022',
- schema: {
- name: 'test_tool',
- schema: { type: 'object' },
- },
- };
+ const payload = createToolPayload();
await expect(createAnthropicGenerateObject(mockClient as any, payload as any)).rejects.toThrow(
'API Error: Model not found',
@@ -854,14 +849,7 @@ describe('Anthropic generateObject', () => {
},
};
- const payload = {
- messages: [{ content: 'Generate data', role: 'user' as const }],
- model: 'claude-3-5-sonnet-20241022',
- schema: {
- name: 'test_tool',
- schema: { type: 'object' },
- },
- };
+ const payload = createToolPayload();
const options = {
signal: new AbortController().signal,
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index 3ac34e19116..ba43c3b44bd 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -14,6 +14,24 @@ import {
handleDefaultAnthropicError,
} from './index';
+const createQuestionChatConfig = (): NonNullable<
+ Parameters<typeof createAnthropicCompatibleRuntime>[0]['chatCompletion']
+> => ({
+ handlePayload: (payload) => ({
+ max_tokens: 1024,
+ messages: [{ content: 'Question', role: 'user' }],
+ model: payload.model,
+ }),
+});
+
+const createCustomClientConfig = (messagesCreate: ReturnType<typeof vi.fn>) => ({
+ createClient: () =>
+ ({
+ baseURL: 'https://aihubmix.com',
+ messages: { create: messagesCreate },
+ }) as unknown as Anthropic,
+});
+
vi.mock('@anthropic-ai/sdk', () => {
const MockAnthropic = vi.fn();
return { default: MockAnthropic };
@@ -588,13 +606,7 @@ describe('createAnthropicCompatibleRuntime', () => {
withResponse: vi.fn().mockResolvedValue({ data: rawStream }),
}));
const Runtime = createAnthropicCompatibleRuntime({
- chatCompletion: {
- handlePayload: (payload) => ({
- max_tokens: 1024,
- messages: [{ content: 'Question', role: 'user' }],
- model: payload.model,
- }),
- },
+ chatCompletion: createQuestionChatConfig(),
customClient: {
createClient: () =>
({
@@ -683,20 +695,8 @@ describe('createAnthropicCompatibleRuntime', () => {
withResponse: vi.fn().mockResolvedValue({ data: rawStream }),
}));
const Runtime = createAnthropicCompatibleRuntime({
- chatCompletion: {
- handlePayload: (payload) => ({
- max_tokens: 1024,
- messages: [{ content: 'Question', role: 'user' }],
- model: payload.model,
- }),
- },
- customClient: {
- createClient: () =>
- ({
- baseURL: 'https://aihubmix.com',
- messages: { create: messagesCreate },
- }) as unknown as Anthropic,
- },
+ chatCompletion: createQuestionChatConfig(),
+ customClient: createCustomClientConfig(messagesCreate),
provider: 'test-provider',
});
const runtime = new Runtime({ apiKey: 'test-key' });
@@ -739,13 +739,7 @@ describe('createAnthropicCompatibleRuntime', () => {
usage: { cache_read_input_tokens: 300, input_tokens: 12, output_tokens: 42 },
});
const Runtime = createAnthropicCompatibleRuntime({
- chatCompletion: {
- handlePayload: (payload) => ({
- max_tokens: 1024,
- messages: [{ content: 'Question', role: 'user' }],
- model: payload.model,
- }),
- },
+ chatCompletion: createQuestionChatConfig(),
customClient: {
createClient: () =>
({
@@ -794,13 +788,7 @@ describe('createAnthropicCompatibleRuntime', () => {
model: payload.model,
}),
},
- customClient: {
- createClient: () =>
- ({
- baseURL: 'https://aihubmix.com',
- messages: { create: messagesCreate },
- }) as unknown as Anthropic,
- },
+ customClient: createCustomClientConfig(messagesCreate),
provider: 'test-provider',
});
const runtime = new Runtime({
@@ -832,13 +820,7 @@ describe('createAnthropicCompatibleRuntime', () => {
chatCompletion: {
handlePayload: buildDefaultAnthropicPayload,
},
- customClient: {
- createClient: () =>
- ({
- baseURL: 'https://aihubmix.com',
- messages: { create: messagesCreate },
- }) as unknown as Anthropic,
- },
+ customClient: createCustomClientConfig(messagesCreate),
provider: 'test-provider',
});
const runtime = new Runtime({
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
index ac006d71b7f..475e3bb9d0c 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
@@ -1,8 +1,8 @@
-import { imageUrlToBase64 } from '../../utils/imageToBase64';
import type { OpenAI } from 'openai';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { OpenAIChatMessage, UserMessageContentPart } from '../../types/chat';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
import { parseDataUri } from '../../utils/uriParser';
import {
buildAnthropicBlock,
@@ -11,6 +11,57 @@ import {
buildAnthropicTools,
} from './anthropic';
+const createAssistantToolMessage = (): OpenAIChatMessage => ({
+ content: '正在搜索...',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"location": "Singapore"}',
+ name: 'search_people',
+ },
+ id: 'toolu_01CnXPcBEqsGGbvRriem3Rth',
+ type: 'function',
+ },
+ ],
+});
+
+const createWeatherToolCalls = (): NonNullable<OpenAIChatMessage['tool_calls']> => [
+ {
+ function: {
+ arguments: '{"city": "\\u676d\\u5dde"}',
+ name: 'realtime-weather____fetchCurrentWeather',
+ },
+ id: 'toolu_018PNQkH8ChbjoJz4QBiFVod',
+ type: 'function',
+ },
+ {
+ function: {
+ arguments: '{"city": "\\u5317\\u4eac"}',
+ name: 'realtime-weather____fetchCurrentWeather',
+ },
+ id: 'toolu_018VQTQ6fwAEC3eppuEfMxPp',
+ type: 'function',
+ },
+];
+
+const createSearchTools = (): OpenAI.ChatCompletionTool[] => [
+ {
+ type: 'function',
+ function: {
+ name: 'search',
+ description: 'Searches the web',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ },
+ required: ['query'],
+ },
+ },
+ },
+];
+
// Mock the parseDataUri function since it's an implementation detail
vi.mock('../../utils/uriParser');
vi.mock('../../utils/imageToBase64', async (importOriginal) => ({
@@ -749,24 +800,7 @@ describe('anthropicHelpers', () => {
content:
'好的,我会为您查询杭州和北京的天气信息。我现在就开始查询这两个城市的当前天气情况。',
role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"city": "\\u676d\\u5dde"}',
- name: 'realtime-weather____fetchCurrentWeather',
- },
- id: 'toolu_018PNQkH8ChbjoJz4QBiFVod',
- type: 'function',
- },
- {
- function: {
- arguments: '{"city": "\\u5317\\u4eac"}',
- name: 'realtime-weather____fetchCurrentWeather',
- },
- id: 'toolu_018VQTQ6fwAEC3eppuEfMxPp',
- type: 'function',
- },
- ],
+ tool_calls: createWeatherToolCalls(),
},
{
content:
@@ -909,20 +943,7 @@ describe('anthropicHelpers', () => {
content: '搜索人员',
role: 'user',
},
- {
- content: '正在搜索...',
- role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"location": "Singapore"}',
- name: 'search_people',
- },
- id: 'toolu_01CnXPcBEqsGGbvRriem3Rth',
- type: 'function',
- },
- ],
- },
+ createAssistantToolMessage(),
{
content: null as any,
name: 'search_people',
@@ -966,20 +987,7 @@ describe('anthropicHelpers', () => {
content: '搜索人员',
role: 'user',
},
- {
- content: '正在搜索...',
- role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"location": "Singapore"}',
- name: 'search_people',
- },
- id: 'toolu_01CnXPcBEqsGGbvRriem3Rth',
- type: 'function',
- },
- ],
- },
+ createAssistantToolMessage(),
{
content: '',
name: 'search_people',
@@ -1023,20 +1031,7 @@ describe('anthropicHelpers', () => {
content: '搜索人员',
role: 'user',
},
- {
- content: '正在搜索...',
- role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"location": "Singapore"}',
- name: 'search_people',
- },
- id: 'toolu_01CnXPcBEqsGGbvRriem3Rth',
- type: 'function',
- },
- ],
- },
+ createAssistantToolMessage(),
{
content: [
{ type: 'text', text: 'Found 5 candidates' },
@@ -1303,24 +1298,7 @@ describe('anthropicHelpers', () => {
},
],
role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"city": "\\u676d\\u5dde"}',
- name: 'realtime-weather____fetchCurrentWeather',
- },
- id: 'toolu_018PNQkH8ChbjoJz4QBiFVod',
- type: 'function',
- },
- {
- function: {
- arguments: '{"city": "\\u5317\\u4eac"}',
- name: 'realtime-weather____fetchCurrentWeather',
- },
- id: 'toolu_018VQTQ6fwAEC3eppuEfMxPp',
- type: 'function',
- },
- ],
+ tool_calls: createWeatherToolCalls(),
},
{
content:
@@ -1440,22 +1418,7 @@ describe('anthropicHelpers', () => {
describe('buildAnthropicTools', () => {
it('should correctly convert OpenAI tools to Anthropic format', () => {
- const tools: OpenAI.ChatCompletionTool[] = [
- {
- type: 'function',
- function: {
- name: 'search',
- description: 'Searches the web',
- parameters: {
- type: 'object',
- properties: {
- query: { type: 'string' },
- },
- required: ['query'],
- },
- },
- },
- ];
+ const tools: OpenAI.ChatCompletionTool[] = createSearchTools();
const result = buildAnthropicTools(tools);
@@ -1474,22 +1437,7 @@ describe('anthropicHelpers', () => {
]);
});
it('should enable cache control', () => {
- const tools: OpenAI.ChatCompletionTool[] = [
- {
- type: 'function',
- function: {
- name: 'search',
- description: 'Searches the web',
- parameters: {
- type: 'object',
- properties: {
- query: { type: 'string' },
- },
- required: ['query'],
- },
- },
- },
- ];
+ const tools: OpenAI.ChatCompletionTool[] = createSearchTools();
const result = buildAnthropicTools(tools, { enabledContextCaching: true });
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index 6ee128a5117..c3183bfe923 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -1,8 +1,8 @@
// @vitest-environment node
-import * as imageToBase64Module from '../../utils/imageToBase64';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import * as imageToBase64Module from '../../utils/imageToBase64';
import { serializeScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { isPublicExternalUrl, parseDataUri, validateExternalUrl } from '../../utils/uriParser';
import {
@@ -14,6 +14,50 @@ import {
GEMINI_MAGIC_THOUGHT_SIGNATURE,
} from './google';
+const createUrlParseResult = (): ReturnType<typeof parseDataUri> => ({
+ base64: null,
+ mimeType: null,
+ type: 'url',
+});
+
+const createImagePart = (
+ imageUrl: string,
+): Extract<UserMessageContentPart, { type: 'image_url' }> => ({
+ image_url: { url: imageUrl },
+ type: 'image_url',
+});
+
+const createTestTool = (): ChatCompletionTool => ({
+ function: {
+ description: 'A test tool',
+ name: 'testTool',
+ parameters: {
+ properties: {
+ param1: { type: 'string' },
+ param2: { type: 'number' },
+ },
+ required: ['param1'],
+ type: 'object',
+ },
+ },
+ type: 'function',
+});
+
+const createSearchAssistantMessage = (): OpenAIChatMessage => ({
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"query":"杭州天气","searchEngines":["google"]}',
+ name: 'lobe-web-browsing____search',
+ },
+ id: 'call_001',
+ type: 'function',
+ },
+ ],
+});
+
// Mock the utils
vi.mock('../../utils/uriParser', () => ({
isPublicExternalUrl: vi.fn().mockReturnValue(false),
@@ -131,10 +175,7 @@ describe('google contextBuilders', () => {
mimeType: 'image/png',
});
- const content: UserMessageContentPart = {
- image_url: { url: imageUrl },
- type: 'image_url',
- };
+ const content: UserMessageContentPart = createImagePart(imageUrl);
const result = await buildGooglePart(content);
@@ -152,11 +193,7 @@ describe('google contextBuilders', () => {
it('should use fileData for external URL images on gemini-3+', async () => {
const imageUrl = 'https://example.com/image.png';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
vi.mocked(validateExternalUrl).mockResolvedValueOnce({
@@ -167,10 +204,7 @@ describe('google contextBuilders', () => {
const imageToBase64Spy = vi.spyOn(imageToBase64Module, 'imageUrlToBase64');
- const content: UserMessageContentPart = {
- image_url: { url: imageUrl },
- type: 'image_url',
- };
+ const content: UserMessageContentPart = createImagePart(imageUrl);
const result = await buildGooglePart(content, { model: 'gemini-3-flash-preview' });
@@ -188,11 +222,7 @@ describe('google contextBuilders', () => {
it('should fallback to inlineData when external URL validation fails for HEIC', async () => {
const imageUrl = 'https://example.com/image.heic';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
vi.mocked(validateExternalUrl).mockResolvedValueOnce({
@@ -209,10 +239,7 @@ describe('google contextBuilders', () => {
mimeType: 'image/heic',
});
- const content: UserMessageContentPart = {
- image_url: { url: imageUrl },
- type: 'image_url',
- };
+ const content: UserMessageContentPart = createImagePart(imageUrl);
const result = await buildGooglePart(content, { model: 'gemini-3-flash-preview' });
@@ -230,11 +257,7 @@ describe('google contextBuilders', () => {
it('should force inlineData for external URL images on gemini-2.5 and earlier', async () => {
const imageUrl = 'https://example.com/image.png';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
const imageToBase64Spy = vi
.spyOn(imageToBase64Module, 'imageUrlToBase64')
@@ -243,10 +266,7 @@ describe('google contextBuilders', () => {
mimeType: 'image/png',
});
- const content: UserMessageContentPart = {
- image_url: { url: imageUrl },
- type: 'image_url',
- };
+ const content: UserMessageContentPart = createImagePart(imageUrl);
const result = await buildGooglePart(content, { model: 'gemini-2.5-flash' });
@@ -283,10 +303,7 @@ describe('google contextBuilders', () => {
const imageToBase64Spy = vi.spyOn(imageToBase64Module, 'imageUrlToBase64');
- const content: UserMessageContentPart = {
- image_url: { url: imageUrl },
- type: 'image_url',
- };
+ const content: UserMessageContentPart = createImagePart(imageUrl);
await expect(buildGooglePart(content, { model: 'gemini-3-flash' })).rejects.toThrow(
RangeError,
@@ -339,11 +356,7 @@ describe('google contextBuilders', () => {
it('should use fileData for external URL videos on gemini-3+', async () => {
const videoUrl = 'https://example.com/video.mp4';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
vi.mocked(validateExternalUrl).mockResolvedValueOnce({
@@ -446,11 +459,7 @@ describe('google contextBuilders', () => {
it('should use fileData for external URL audio on gemini-3+', async () => {
const audioUrl = 'https://example.com/audio.mp3';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
vi.mocked(validateExternalUrl).mockResolvedValueOnce({
@@ -481,11 +490,7 @@ describe('google contextBuilders', () => {
it('should use persisted recorder metadata when an external URL is octet-stream', async () => {
const audioUrl = 'https://example.com/voice';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(true);
vi.mocked(validateExternalUrl).mockResolvedValueOnce({
contentLength: 1024,
@@ -510,11 +515,7 @@ describe('google contextBuilders', () => {
it('should send audio MIME when an inlined audio URL is sniffed as a video container', async () => {
const audioUrl = 'https://example.com/voice-message.m4a';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.mocked(isPublicExternalUrl).mockReturnValueOnce(false);
vi.spyOn(imageToBase64Module, 'imageUrlToBase64').mockResolvedValueOnce({
base64: 'm4aBase64Data',
@@ -554,11 +555,7 @@ describe('google contextBuilders', () => {
it('should return undefined for unsupported SVG image (URL)', async () => {
const svgUrl = 'https://example.com/image.svg';
- vi.mocked(parseDataUri).mockReturnValueOnce({
- base64: null,
- mimeType: null,
- type: 'url',
- });
+ vi.mocked(parseDataUri).mockReturnValueOnce(createUrlParseResult());
vi.spyOn(imageToBase64Module, 'imageUrlToBase64').mockResolvedValueOnce({
base64: 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==',
@@ -758,20 +755,7 @@ describe('google contextBuilders', () => {
content: '杭州天气如何',
role: 'user',
},
- {
- content: '',
- role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"query":"杭州天气","searchEngines":["google"]}',
- name: 'lobe-web-browsing____search',
- },
- id: 'call_001',
- type: 'function',
- },
- ],
- },
+ createSearchAssistantMessage(),
{
content: 'Tool execution was aborted by user.',
name: 'lobe-web-browsing____search',
@@ -1087,20 +1071,7 @@ describe('google contextBuilders', () => {
content: '杭州天气如何',
role: 'user',
},
- {
- content: '',
- role: 'assistant',
- tool_calls: [
- {
- function: {
- arguments: '{"query":"杭州天气","searchEngines":["google"]}',
- name: 'lobe-web-browsing____search',
- },
- id: 'call_001',
- type: 'function',
- },
- ],
- },
+ createSearchAssistantMessage(),
{
content: 'Tool execution was aborted by user.',
name: 'lobe-web-browsing____search',
@@ -1587,21 +1558,7 @@ describe('google contextBuilders', () => {
describe('buildGoogleTool', () => {
it('should use parametersJsonSchema to pass standard JSON Schema directly', () => {
- const tool: ChatCompletionTool = {
- function: {
- description: 'A test tool',
- name: 'testTool',
- parameters: {
- properties: {
- param1: { type: 'string' },
- param2: { type: 'number' },
- },
- required: ['param1'],
- type: 'object',
- },
- },
- type: 'function',
- };
+ const tool: ChatCompletionTool = createTestTool();
const result = buildGoogleTool(tool);
@@ -1772,23 +1729,7 @@ describe('google contextBuilders', () => {
});
it('should correctly convert ChatCompletionTool array to GoogleFunctionCallTool', () => {
- const tools: ChatCompletionTool[] = [
- {
- function: {
- description: 'A test tool',
- name: 'testTool',
- parameters: {
- properties: {
- param1: { type: 'string' },
- param2: { type: 'number' },
- },
- required: ['param1'],
- type: 'object',
- },
- },
- type: 'function',
- },
- ];
+ const tools: ChatCompletionTool[] = [createTestTool()];
const googleTools = buildGoogleTools(tools);
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index ea59dce7fcb..45df7a8a8aa 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -19,6 +19,70 @@ import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import * as openaiHelpers from '../contextBuilders/openai';
import { createOpenAICompatibleRuntime } from './index';
+const createBasicChatPayload = (): ChatStreamPayload => ({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'mistralai/mistral-7b-instruct:free',
+ temperature: 0,
+});
+
+const createEmptyToolSchema = () => ({
+ name: 'test_tool',
+ schema: { properties: {}, type: 'object' as const },
+});
+
+const createClosedResponseSource = () => ({
+ toReadableStream: () =>
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ }),
+});
+
+const createConstrainedPersonSchema = () => ({
+ name: 'person',
+ schema: {
+ maxLength: 100,
+ pattern: '^[a-z]+$',
+ properties: {
+ age: { type: 'number' },
+ name: { type: 'string' },
+ },
+ type: 'object' as const,
+ },
+});
+
+const createPersonExtractorSchema = () => ({
+ name: 'person_extractor',
+ schema: {
+ properties: { age: { type: 'number' }, name: { type: 'string' } },
+ type: 'object' as const,
+ },
+});
+
+const createPersonToolResponse = () => ({
+ choices: [
+ {
+ message: {
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"name":"Alice","age":28}',
+ name: 'person_extractor',
+ },
+ type: 'function' as const,
+ },
+ ],
+ },
+ },
+ ],
+});
+
+const createImagePayload = () => ({
+ model: 'dall-e-3',
+ params: { prompt: 'Test prompt' },
+});
+
const sleep = async (ms: number) =>
await new Promise((resolve) => {
setTimeout(resolve, ms);
@@ -365,11 +429,7 @@ describe('LobeOpenAICompatibleFactory', () => {
(instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);
// Act
- const result = await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ const result = await instance.chat(createBasicChatPayload());
// Assert
expect(result).toBeInstanceOf(Response);
@@ -588,11 +648,7 @@ describe('LobeOpenAICompatibleFactory', () => {
mockStream as any,
);
- const result = await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ const result = await instance.chat(createBasicChatPayload());
const decoder = new TextDecoder();
const reader = result.body!.getReader();
@@ -882,14 +938,7 @@ describe('LobeOpenAICompatibleFactory', () => {
it('should add user in payload correctly', async () => {
const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');
- await instance.chat(
- {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- },
- { user: 'abc' },
- );
+ await instance.chat(createBasicChatPayload(), { user: 'abc' });
expect(mockCreateMethod).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1278,14 +1327,7 @@ describe('LobeOpenAICompatibleFactory', () => {
}) as any,
);
- const chatPromise = instance.chat(
- {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- },
- { signal: controller.signal },
- );
+ const chatPromise = instance.chat(createBasicChatPayload(), { signal: controller.signal });
// Give some time for the request to start
await sleep(50);
@@ -1331,11 +1373,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Act
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1457,11 +1495,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Act
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1492,11 +1526,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Act
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: 'https://api.***.com/v1',
@@ -1516,11 +1546,7 @@ describe('LobeOpenAICompatibleFactory', () => {
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(error);
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
error,
@@ -1538,11 +1564,7 @@ describe('LobeOpenAICompatibleFactory', () => {
vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
// Expect the chat method to throw an error with InvalidMoonshotAPIKey
expect(e).toMatchObject({
@@ -1570,11 +1592,7 @@ describe('LobeOpenAICompatibleFactory', () => {
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1606,11 +1624,7 @@ describe('LobeOpenAICompatibleFactory', () => {
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1644,11 +1658,7 @@ describe('LobeOpenAICompatibleFactory', () => {
vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1673,11 +1683,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Act
try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
} catch (e) {
expect(e).toEqual({
endpoint: defaultBaseURL,
@@ -1725,14 +1731,10 @@ describe('LobeOpenAICompatibleFactory', () => {
const mockHeaders = { 'Custom-Header': 'TestValue' };
// Execute test
- const result = await instance.chat(
- {
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- },
- { callback: mockCallback, headers: mockHeaders },
- );
+ const result = await instance.chat(createBasicChatPayload(), {
+ callback: mockCallback,
+ headers: mockHeaders,
+ });
// Verify callback is called
await result.text(); // Ensure stream is consumed
@@ -1903,14 +1905,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Mock responses.create to return a proper stream-like object
const mockResponsesCreate = vi
.spyOn(inst['client'].responses, 'create')
- .mockResolvedValue({
- toReadableStream: () =>
- new ReadableStream({
- start(controller) {
- controller.close();
- },
- }),
- } as any);
+ .mockResolvedValue(createClosedResponseSource() as any);
// Mock getModelPricing to prevent async issues
try {
@@ -1941,14 +1936,9 @@ describe('LobeOpenAICompatibleFactory', () => {
.spyOn(openaiHelpers, 'convertOpenAIResponseInputs')
.mockResolvedValue([{ role: 'user', content: 'mocked input' }] as any);
- vi.spyOn(inst['client'].responses, 'create').mockResolvedValue({
- toReadableStream: () =>
- new ReadableStream({
- start(controller) {
- controller.close();
- },
- }),
- } as any);
+ vi.spyOn(inst['client'].responses, 'create').mockResolvedValue(
+ createClosedResponseSource() as any,
+ );
try {
await inst.chat({
@@ -2105,14 +2095,7 @@ describe('LobeOpenAICompatibleFactory', () => {
);
// First invocation: model contains the string
- spy.mockResolvedValueOnce({
- toReadableStream: () =>
- new ReadableStream({
- start(controller) {
- controller.close();
- },
- }),
- } as any);
+ spy.mockResolvedValueOnce(createClosedResponseSource() as any);
try {
await inst.chat({
messages: [{ content: 'hi', role: 'user' }],
@@ -2125,14 +2108,7 @@ describe('LobeOpenAICompatibleFactory', () => {
expect(spy).toHaveBeenCalledTimes(1);
// Second invocation: model matches the RegExp
- spy.mockResolvedValueOnce({
- toReadableStream: () =>
- new ReadableStream({
- start(controller) {
- controller.close();
- },
- }),
- } as any);
+ spy.mockResolvedValueOnce(createClosedResponseSource() as any);
try {
await inst.chat({
messages: [{ content: 'hi', role: 'user' }],
@@ -2186,11 +2162,7 @@ describe('LobeOpenAICompatibleFactory', () => {
// Execute test
// Run your test function, ensuring it calls debugStream when conditions are met
// Hypothetical test function call, you may need to adjust based on actual situation
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'mistralai/mistral-7b-instruct:free',
- temperature: 0,
- });
+ await instance.chat(createBasicChatPayload());
// Verify debugStream is called
expect(debugStreamModule.debugStream).toHaveBeenCalled();
@@ -2526,10 +2498,7 @@ describe('LobeOpenAICompatibleFactory', () => {
it('should throw error when API response is invalid - no data', async () => {
vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({} as any);
- const payload = {
- model: 'dall-e-3',
- params: { prompt: 'Test prompt' },
- };
+ const payload = createImagePayload();
await expect((instance as any).createImage(payload)).rejects.toThrow(
'Invalid image response: missing or empty data array',
@@ -2541,10 +2510,7 @@ describe('LobeOpenAICompatibleFactory', () => {
data: [],
} as any);
- const payload = {
- model: 'dall-e-3',
- params: { prompt: 'Test prompt' },
- };
+ const payload = createImagePayload();
await expect((instance as any).createImage(payload)).rejects.toThrow(
'Invalid image response: missing or empty data array',
@@ -2556,10 +2522,7 @@ describe('LobeOpenAICompatibleFactory', () => {
data: [null],
} as any);
- const payload = {
- model: 'dall-e-3',
- params: { prompt: 'Test prompt' },
- };
+ const payload = createImagePayload();
await expect((instance as any).createImage(payload)).rejects.toThrow(
'Invalid image response: first data item is null or undefined',
@@ -2571,10 +2534,7 @@ describe('LobeOpenAICompatibleFactory', () => {
data: [{ url: 'https://example.com/generated-image.jpg' }],
} as any);
- const payload = {
- model: 'dall-e-3',
- params: { prompt: 'Test prompt' },
- };
+ const payload = createImagePayload();
const result = await (instance as any).createImage(payload);
@@ -2588,10 +2548,7 @@ describe('LobeOpenAICompatibleFactory', () => {
data: [{ some_other_field: 'value' }],
} as any);
- const payload = {
- model: 'dall-e-3',
- params: { prompt: 'Test prompt' },
- };
+ const payload = createImagePayload();
await expect((instance as any).createImage(payload)).rejects.toThrow(
'Invalid image response: missing both b64_json and url fields',
@@ -2762,13 +2719,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Generate a person object', role: 'user' as const }],
model: 'gpt-5.4-mini',
- schema: {
- name: 'person_extractor',
- schema: {
- properties: { age: { type: 'number' }, name: { type: 'string' } },
- type: 'object' as const,
- },
- },
+ schema: createPersonExtractorSchema(),
thinking: { budget_tokens: 0, type: 'disabled' as const },
};
@@ -2794,13 +2745,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate a person object', role: 'user' as const }],
model: 'gpt-5.4-pro',
reasoning_effort: 'medium' as const,
- schema: {
- name: 'person_extractor',
- schema: {
- properties: { age: { type: 'number' }, name: { type: 'string' } },
- type: 'object' as const,
- },
- },
+ schema: createPersonExtractorSchema(),
};
await instance.generateObject(payload);
@@ -2899,10 +2844,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-4o',
responseApi: true,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toMatchObject({
@@ -2925,10 +2867,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-4o',
responseApi: true,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toMatchObject({
@@ -3000,10 +2939,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-4o',
responseApi: true,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toThrow(
@@ -3031,10 +2967,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-5.4-mini',
responseApi: true,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toEqual({
@@ -3071,13 +3004,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Generate a person object', role: 'user' as const }],
model: 'gpt-4o',
- schema: {
- name: 'person_extractor',
- schema: {
- properties: { age: { type: 'number' }, name: { type: 'string' } },
- type: 'object' as const,
- },
- },
+ schema: createPersonExtractorSchema(),
// responseApi: false or undefined - uses chat completions API
};
@@ -3204,10 +3131,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-4o',
responseApi: false,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toMatchObject({
@@ -3238,10 +3162,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'gpt-4o',
responseApi: false,
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instance.generateObject(payload)).rejects.toMatchObject({
@@ -3633,18 +3554,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Extract person', role: 'user' as const }],
model: 'gpt-4o',
responseApi: true,
- schema: {
- name: 'person',
- schema: {
- maxLength: 100,
- pattern: '^[a-z]+$',
- properties: {
- age: { type: 'number' },
- name: { type: 'string' },
- },
- type: 'object' as const,
- },
- },
+ schema: createConstrainedPersonSchema(),
};
await instanceWithSchemaHandler.generateObject(payload);
@@ -3686,18 +3596,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Extract person', role: 'user' as const }],
model: 'test-model',
- schema: {
- name: 'person',
- schema: {
- maxLength: 100,
- pattern: '^[a-z]+$',
- properties: {
- age: { type: 'number' },
- name: { type: 'string' },
- },
- type: 'object' as const,
- },
- },
+ schema: createConstrainedPersonSchema(),
};
await instanceWithSchemaHandler.generateObject(payload);
@@ -3758,18 +3657,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Extract person', role: 'user' as const }],
model: 'test-model',
- schema: {
- name: 'person',
- schema: {
- maxLength: 100,
- pattern: '^[a-z]+$',
- properties: {
- age: { type: 'number' },
- name: { type: 'string' },
- },
- type: 'object' as const,
- },
- },
+ schema: createConstrainedPersonSchema(),
};
await instance.generateObject(payload);
@@ -3924,23 +3812,7 @@ describe('LobeOpenAICompatibleFactory', () => {
});
it('should use tool calling when configured', async () => {
- const mockResponse = {
- choices: [
- {
- message: {
- tool_calls: [
- {
- function: {
- arguments: '{"name":"Alice","age":28}',
- name: 'person_extractor',
- },
- type: 'function' as const,
- },
- ],
- },
- },
- ],
- };
+ const mockResponse = createPersonToolResponse();
vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
mockResponse as any,
@@ -3987,23 +3859,7 @@ describe('LobeOpenAICompatibleFactory', () => {
});
it('should not forward internal thinking to generic OpenAI-compatible generateObject requests', async () => {
- const mockResponse = {
- choices: [
- {
- message: {
- tool_calls: [
- {
- function: {
- arguments: '{"name":"Alice","age":28}',
- name: 'person_extractor',
- },
- type: 'function' as const,
- },
- ],
- },
- },
- ],
- };
+ const mockResponse = createPersonToolResponse();
vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
mockResponse as any,
@@ -4013,13 +3869,7 @@ describe('LobeOpenAICompatibleFactory', () => {
messages: [{ content: 'Extract person info', role: 'user' as const }],
model: 'deepseek-v4-pro',
reasoning_effort: 'high' as const,
- schema: {
- name: 'person_extractor',
- schema: {
- properties: { age: { type: 'number' }, name: { type: 'string' } },
- type: 'object' as const,
- },
- },
+ schema: createPersonExtractorSchema(),
thinking: { budget_tokens: 0, type: 'disabled' as const },
};
@@ -4055,10 +3905,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'test-model',
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(
@@ -4096,10 +3943,7 @@ describe('LobeOpenAICompatibleFactory', () => {
const payload = {
messages: [{ content: 'Generate data', role: 'user' as const }],
model: 'test-model',
- schema: {
- name: 'test_tool',
- schema: { properties: {}, type: 'object' as const },
- },
+ schema: createEmptyToolSchema(),
};
await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
index 9927e9cedee..2a48b8f4eaf 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
@@ -4,6 +4,14 @@ import { describe, expect, it } from 'vitest';
import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
+const createInputOnlyUsage = () => ({
+ total_tokens: 5,
+ input_tokens: 5,
+ output_tokens: 0,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+});
+
describe('nonStreamToStream', () => {
describe('transformResponseToStream', () => {
it('should transform ChatCompletion to stream events correctly', async () => {
@@ -433,13 +441,7 @@ describe('nonStreamToStream', () => {
// Missing content property
},
],
- usage: {
- total_tokens: 5,
- input_tokens: 5,
- output_tokens: 0,
- input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
- output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
- },
+ usage: createInputOnlyUsage(),
created: 1677652288,
created_at: 1677652288,
model: 'gpt-4o-realtime-preview',
@@ -568,13 +570,7 @@ describe('nonStreamToStream', () => {
],
},
],
- usage: {
- total_tokens: 5,
- input_tokens: 5,
- output_tokens: 0,
- input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
- output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
- },
+ usage: createInputOnlyUsage(),
created: 1677652288,
created_at: 1677652288,
model: 'gpt-4o-realtime-preview',
@@ -663,13 +659,7 @@ describe('nonStreamToStream', () => {
status: 'completed',
status_details: null,
output: [],
- usage: {
- total_tokens: 5,
- input_tokens: 5,
- output_tokens: 0,
- input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
- output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
- },
+ usage: createInputOnlyUsage(),
created: 1677652288,
created_at: 1677652288,
model: 'gpt-4o-realtime-preview',
@@ -702,13 +692,7 @@ describe('nonStreamToStream', () => {
status: 'completed',
status_details: null,
// output field is missing
- usage: {
- total_tokens: 5,
- input_tokens: 5,
- output_tokens: 0,
- input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
- output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
- },
+ usage: createInputOnlyUsage(),
created: 1677652288,
created_at: 1677652288,
model: 'gpt-4o-realtime-preview',
diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.ts
index 98cffec2cfe..457b021fe6e 100644
--- a/packages/model-runtime/src/core/streams/anthropic.test.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts
@@ -2,6 +2,21 @@ import type { Stream } from '@anthropic-ai/sdk/streaming';
import { describe, expect, it, vi } from 'vitest';
import { AnthropicStream } from './anthropic';
+import { createReadableStream } from './utils';
+
+const createMessageStart = <T>(id: string, model: string, usage: T) => ({
+ type: 'message_start',
+ message: {
+ id,
+ type: 'message',
+ role: 'assistant',
+ model,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage,
+ },
+});
describe('AnthropicStream', () => {
it('should transform Anthropic stream to protocol stream', async () => {
@@ -120,19 +135,10 @@ describe('AnthropicStream', () => {
it('should handle tool use event and ReadableStream input', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_017aTuY86wNxth5TE544yqJq',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-sonnet-20240229',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: { input_tokens: 457, output_tokens: 1 },
- },
- },
+ createMessageStart('msg_017aTuY86wNxth5TE544yqJq', 'claude-3-sonnet-20240229', {
+ input_tokens: 457,
+ output_tokens: 1,
+ }),
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '好' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '的:' } },
@@ -176,14 +182,7 @@ describe('AnthropicStream', () => {
},
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const onToolCallMock = vi.fn();
@@ -255,19 +254,10 @@ describe('AnthropicStream', () => {
});
it('should handle parallel tools use event and ReadableStream input', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_0175ryA67RbGrnRrGBXFQEYK',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-5-sonnet-20240620',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: { input_tokens: 485, output_tokens: 4 },
- },
- },
+ createMessageStart('msg_0175ryA67RbGrnRrGBXFQEYK', 'claude-3-5-sonnet-20240620', {
+ input_tokens: 485,
+ output_tokens: 4,
+ }),
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{
type: 'content_block_delta',
@@ -330,14 +320,7 @@ describe('AnthropicStream', () => {
{ type: 'message_stop' },
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const onToolCallMock = vi.fn();
@@ -417,24 +400,12 @@ describe('AnthropicStream', () => {
it('should handle prompts context caching', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_01Vxc4yQTEjkDSba3N3BMbH8',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-7-sonnet-20250219',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: {
- input_tokens: 6,
- cache_creation_input_tokens: 457,
- cache_read_input_tokens: 17918,
- output_tokens: 2,
- },
- },
- },
+ createMessageStart('msg_01Vxc4yQTEjkDSba3N3BMbH8', 'claude-3-7-sonnet-20250219', {
+ input_tokens: 6,
+ cache_creation_input_tokens: 457,
+ cache_read_input_tokens: 17918,
+ output_tokens: 2,
+ }),
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '\n\n根' } },
{
@@ -451,14 +422,7 @@ describe('AnthropicStream', () => {
{ type: 'message_stop' },
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const protocolStream = AnthropicStream(mockReadableStream);
@@ -503,24 +467,12 @@ describe('AnthropicStream', () => {
describe('thinking', () => {
it('should handle normal thinking ', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_01MNsLe7n1uVLtu6W8rCFujD',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-7-sonnet-20250219',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: {
- input_tokens: 46,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- output_tokens: 11,
- },
- },
- },
+ createMessageStart('msg_01MNsLe7n1uVLtu6W8rCFujD', 'claude-3-7-sonnet-20250219', {
+ input_tokens: 46,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ output_tokens: 11,
+ }),
{
type: 'content_block_start',
index: 0,
@@ -566,14 +518,7 @@ describe('AnthropicStream', () => {
{ type: 'message_stop' },
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const protocolStream = AnthropicStream(mockReadableStream);
@@ -633,24 +578,12 @@ describe('AnthropicStream', () => {
it('should handle flagged thinking ', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_019q32esPvu3TftzZnL6JPys',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-7-sonnet-20250219',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: {
- input_tokens: 92,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- output_tokens: 4,
- },
- },
- },
+ createMessageStart('msg_019q32esPvu3TftzZnL6JPys', 'claude-3-7-sonnet-20250219', {
+ input_tokens: 92,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ output_tokens: 4,
+ }),
{
type: 'content_block_start',
index: 0,
@@ -714,14 +647,7 @@ describe('AnthropicStream', () => {
{ type: 'message_stop' },
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const protocolStream = AnthropicStream(mockReadableStream);
@@ -835,24 +761,12 @@ describe('AnthropicStream', () => {
it('should handle un-normal block type', async () => {
const streams = [
- {
- type: 'message_start',
- message: {
- id: 'msg_01MNsLe7n1uVLtu6W8rCFujD',
- type: 'message',
- role: 'assistant',
- model: 'claude-3-7-sonnet-20250219',
- content: [],
- stop_reason: null,
- stop_sequence: null,
- usage: {
- input_tokens: 46,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- output_tokens: 11,
- },
- },
- },
+ createMessageStart('msg_01MNsLe7n1uVLtu6W8rCFujD', 'claude-3-7-sonnet-20250219', {
+ input_tokens: 46,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ output_tokens: 11,
+ }),
{
type: 'content_block_start',
index: 0,
@@ -876,14 +790,7 @@ describe('AnthropicStream', () => {
{ type: 'message_stop' },
];
- const mockReadableStream = new ReadableStream({
- start(controller) {
- streams.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockReadableStream = createReadableStream(streams);
const protocolStream = AnthropicStream(mockReadableStream);
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 1bc971d0a36..5ea82f6ced2 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -3,27 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
import * as uuidModule from '../../../utils/uuid';
+import { createReadableStream, readStreamChunk as decodeStreamChunks } from '../utils';
import { GoogleGenerativeAIStream, LOBE_ERROR_KEY } from './index';
const thoughtSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
const scopedThoughtSignature = (signature: string) =>
serializeScopedSignature(signature, thoughtSignatureScope, 'thought_signature')!;
-/**
- * Helper function to decode stream chunks into string array
- */
-async function decodeStreamChunks(stream: ReadableStream): Promise<string[]> {
- const decoder = new TextDecoder();
- const chunks: string[] = [];
-
- // @ts-ignore
- for await (const chunk of stream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
-
- return chunks;
-}
-
describe('GoogleGenerativeAIStream', () => {
beforeEach(() => {
vi.restoreAllMocks();
@@ -33,56 +19,50 @@ describe('GoogleGenerativeAIStream', () => {
it('should transform Google Generative AI stream to protocol stream', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1').mockReturnValueOnce('abcd1234');
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- // Text chunk
- controller.enqueue({
- text: 'Hello',
- candidates: [{ content: { parts: [{ text: 'Hello' }], role: 'model' }, index: 0 }],
- } as unknown as GenerateContentResponse);
-
- // Function call chunk
- controller.enqueue({
- text: '',
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- name: 'testFunction',
- args: { arg1: 'value1' },
- },
+ const mockGoogleStream = createReadableStream([
+ // Text chunk
+ {
+ text: 'Hello',
+ candidates: [{ content: { parts: [{ text: 'Hello' }], role: 'model' }, index: 0 }],
+ } as unknown as GenerateContentResponse,
+ // Function call chunk
+ {
+ text: '',
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ name: 'testFunction',
+ args: { arg1: 'value1' },
},
- ],
- role: 'model',
- },
- index: 0,
- },
- ],
- } as unknown as GenerateContentResponse);
-
- // Final chunk with finishReason and usageMetadata to mark terminal event
- controller.enqueue({
- text: ' world!',
- candidates: [
- {
- content: { parts: [{ text: ' world!' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
+ },
+ ],
+ role: 'model',
},
- ],
- usageMetadata: {
- promptTokenCount: 1,
- totalTokenCount: 1,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 1 }],
+ index: 0,
},
- modelVersion: 'gemini-test',
- } as unknown as GenerateContentResponse);
-
- controller.close();
- },
- });
+ ],
+ } as unknown as GenerateContentResponse,
+ // Final chunk with finishReason and usageMetadata to mark terminal event
+ {
+ text: ' world!',
+ candidates: [
+ {
+ content: { parts: [{ text: ' world!' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 1,
+ totalTokenCount: 1,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 1 }],
+ },
+ modelVersion: 'gemini-test',
+ } as unknown as GenerateContentResponse,
+ ]);
const onStartMock = vi.fn();
const onTextMock = vi.fn();
@@ -134,25 +114,21 @@ describe('GoogleGenerativeAIStream', () => {
it('should handle empty stream', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('E5M9dFKw');
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- candidates: [{ content: { role: 'model' }, finishReason: 'STOP', index: 0 }],
- usageMetadata: {
- promptTokenCount: 0,
- cachedContentTokenCount: 0,
- totalTokenCount: 0,
- promptTokensDetails: [
- { modality: 'TEXT', tokenCount: 0 },
- { modality: 'IMAGE', tokenCount: 0 },
- ],
- },
- modelVersion: 'gemini-test',
- } as unknown as GenerateContentResponse);
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([
+ {
+ candidates: [{ content: { role: 'model' }, finishReason: 'STOP', index: 0 }],
+ usageMetadata: {
+ promptTokenCount: 0,
+ cachedContentTokenCount: 0,
+ totalTokenCount: 0,
+ promptTokensDetails: [
+ { modality: 'TEXT', tokenCount: 0 },
+ { modality: 'IMAGE', tokenCount: 0 },
+ ],
+ },
+ modelVersion: 'gemini-test',
+ } as unknown as GenerateContentResponse,
+ ]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -170,21 +146,18 @@ describe('GoogleGenerativeAIStream', () => {
it('should expose missing usage diagnostics when finishReason has no usageMetadata', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('missingUsage');
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- candidates: [
- {
- content: { parts: [{ text: '' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- modelVersion: 'gemini-test',
- } as unknown as GenerateContentResponse);
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([
+ {
+ candidates: [
+ {
+ content: { parts: [{ text: '' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ modelVersion: 'gemini-test',
+ } as unknown as GenerateContentResponse,
+ ]);
const onFinal = vi.fn();
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
@@ -283,15 +256,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -408,15 +373,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -503,15 +460,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -556,13 +505,7 @@ describe('GoogleGenerativeAIStream', () => {
modelVersion: 'gemini-2.0-flash-exp',
};
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue(data);
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([data]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -596,13 +539,7 @@ describe('GoogleGenerativeAIStream', () => {
modelVersion: 'gemini-2.0-flash-exp',
};
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue(data);
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([data]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -669,15 +606,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -731,13 +660,7 @@ describe('GoogleGenerativeAIStream', () => {
modelVersion: 'gemini-2.0-flash-exp',
};
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue(data);
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([data]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -863,15 +786,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -956,12 +871,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -1050,12 +960,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -1125,12 +1030,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -1224,14 +1124,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
payload: { thoughtSignatureScope },
@@ -1364,14 +1257,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
payload: { thoughtSignatureScope },
@@ -1528,14 +1414,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
payload: { thoughtSignatureScope },
@@ -1639,15 +1518,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -1688,12 +1559,7 @@ describe('GoogleGenerativeAIStream', () => {
responseId: 'THOUaKaNOeiGz7IPjL_VgQc',
};
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue(data);
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([data]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -1728,12 +1594,7 @@ describe('GoogleGenerativeAIStream', () => {
modelVersion: 'gemini-3.1-flash-lite-preview',
};
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue(data);
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([data]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -1751,26 +1612,23 @@ describe('GoogleGenerativeAIStream', () => {
it('should classify IMAGE_PROHIBITED_CONTENT as a content policy violation', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- candidates: [
- {
- content: {},
- finishReason: 'IMAGE_PROHIBITED_CONTENT',
- index: 0,
- },
- ],
- usageMetadata: {
- candidatesTokenCount: 0,
- promptTokenCount: 10,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
- totalTokenCount: 10,
+ const mockGoogleStream = createReadableStream([
+ {
+ candidates: [
+ {
+ content: {},
+ finishReason: 'IMAGE_PROHIBITED_CONTENT',
+ index: 0,
},
- });
- controller.close();
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 0,
+ promptTokenCount: 10,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ totalTokenCount: 10,
+ },
},
- });
+ ]);
const chunks = await decodeStreamChunks(GoogleGenerativeAIStream(mockGoogleStream));
@@ -1789,12 +1647,7 @@ describe('GoogleGenerativeAIStream', () => {
const errorPayload = { message: 'internal error', code: 123 };
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue({ [LOBE_ERROR_KEY]: errorPayload });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream([{ [LOBE_ERROR_KEY]: errorPayload }]);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -1844,14 +1697,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
payload: { thoughtSignatureScope },
@@ -1882,28 +1728,25 @@ describe('GoogleGenerativeAIStream', () => {
it('should omit thoughtSignature from parts when no scope is available', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- candidates: [
- {
- content: {
- parts: [{ text: 'Here is my answer', thoughtSignature: 'sig123' }],
- role: 'model',
- },
- finishReason: 'STOP',
- index: 0,
+ const mockGoogleStream = createReadableStream([
+ {
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Here is my answer', thoughtSignature: 'sig123' }],
+ role: 'model',
},
- ],
- usageMetadata: {
- candidatesTokenCount: 4,
- promptTokenCount: 3,
- totalTokenCount: 7,
+ finishReason: 'STOP',
+ index: 0,
},
- });
- controller.close();
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 4,
+ promptTokenCount: 3,
+ totalTokenCount: 7,
+ },
},
- });
+ ]);
const chunks = await decodeStreamChunks(GoogleGenerativeAIStream(mockGoogleStream));
@@ -2091,14 +1934,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
payload: { thoughtSignatureScope },
@@ -2230,14 +2066,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -2307,14 +2136,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
@@ -2368,14 +2190,7 @@ describe('GoogleGenerativeAIStream', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const chunks = await decodeStreamChunks(protocolStream);
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.ts
index 5364fa6b480..4731f93cbce 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts
@@ -3,44 +3,43 @@ import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../../types/error';
import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
+import { createReadableStream, readStreamChunk } from '../utils';
import { OpenAIStream } from './openai';
describe('OpenAIStream', () => {
it('should transform OpenAI stream to protocol stream', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: { content: 'Hello' },
- index: 0,
- },
- ],
- id: '1',
- });
- controller.enqueue({
- choices: [
- {
- delta: { content: ' world!' },
- index: 1,
- },
- ],
- id: '1',
- });
- controller.enqueue({
- choices: [
- {
- delta: null,
- finish_reason: 'stop',
- index: 2,
- },
- ],
- id: '1',
- });
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: { content: 'Hello' },
+ index: 0,
+ },
+ ],
+ id: '1',
+ },
- controller.close();
+ {
+ choices: [
+ {
+ delta: { content: ' world!' },
+ index: 1,
+ },
+ ],
+ id: '1',
},
- });
+
+ {
+ choices: [
+ {
+ delta: null,
+ finish_reason: 'stop',
+ index: 2,
+ },
+ ],
+ id: '1',
+ },
+ ]);
const onStartMock = vi.fn();
const onTextMock = vi.fn();
@@ -54,13 +53,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: 1\n',
@@ -81,21 +74,18 @@ describe('OpenAIStream', () => {
});
it('should expose missing usage diagnostics when terminal chunk has no usage', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {},
- finish_reason: 'stop',
- index: 0,
- },
- ],
- id: 'chatcmpl_missing_usage',
- });
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {},
+ finish_reason: 'stop',
+ index: 0,
+ },
+ ],
+ id: 'chatcmpl_missing_usage',
},
- });
+ ]);
const onFinal = vi.fn();
const protocolStream = OpenAIStream(mockOpenAIStream, {
@@ -132,21 +122,18 @@ describe('OpenAIStream', () => {
});
it('should emit a content policy error when finish_reason is content_filter', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {},
- finish_reason: 'content_filter',
- index: 0,
- },
- ],
- id: 'chatcmpl_content_filter',
- });
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {},
+ finish_reason: 'content_filter',
+ index: 0,
+ },
+ ],
+ id: 'chatcmpl_content_filter',
},
- });
+ ]);
const onError = vi.fn();
const onFinal = vi.fn();
@@ -158,12 +145,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks: string[] = [];
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
const expectedError = {
body: {
@@ -195,83 +177,53 @@ describe('OpenAIStream', () => {
});
it('should handle empty stream', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.close();
- },
- });
+ const mockStream = createReadableStream([]);
const protocolStream = OpenAIStream(mockStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([]);
});
it('should handle delta content null', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: { content: null },
- index: 0,
- },
- ],
- id: '3',
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: { content: null },
+ index: 0,
+ },
+ ],
+ id: '3',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: 3\n', 'event: data\n', `data: {"content":null}\n\n`]);
});
it('should handle content with finish_reason', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: '123',
- model: 'deepl',
- choices: [
- {
- index: 0,
- delta: { role: 'assistant', content: 'Introduce yourself.' },
- finish_reason: 'stop',
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: '123',
+ model: 'deepl',
+ choices: [
+ {
+ index: 0,
+ delta: { role: 'assistant', content: 'Introduce yourself.' },
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
['id: 123', 'event: text', `data: "Introduce yourself."\n`].map((i) => `${i}\n`),
@@ -299,22 +251,11 @@ describe('OpenAIStream', () => {
{ id: 'img-1', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((c) => controller.enqueue(c));
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks: string[] = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -333,27 +274,23 @@ describe('OpenAIStream', () => {
it('should handle content with tool_calls but is an empty object', async () => {
// data: {"id":"chatcmpl-A7pokGUqSov0JuMkhiHhWU9GRtAgJ", "object":"chat.completion.chunk", "created":1726430846, "model":"gpt-4o-2024-05-13", "choices":[{"index":0, "delta":{"content":" today", "role":"", "tool_calls":[]}, "finish_reason":"", "logprobs":""}], "prompt_annotations":[{"prompt_index":0, "content_filter_results":null}]}
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- index: 0,
- delta: {
- content: 'Some contents',
- role: '',
- tool_calls: [],
- },
- finish_reason: '',
- logprobs: '',
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ index: 0,
+ delta: {
+ content: 'Some contents',
+ role: '',
+ tool_calls: [],
},
- ],
- id: '456',
- });
-
- controller.close();
+ finish_reason: '',
+ logprobs: '',
+ },
+ ],
+ id: '456',
},
- });
+ ]);
const onToolCallMock = vi.fn();
@@ -363,13 +300,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
['id: 456', 'event: text', `data: "Some contents"\n`].map((i) => `${i}\n`),
@@ -377,31 +308,21 @@ describe('OpenAIStream', () => {
});
it('should handle other delta data', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: { custom_field: 'custom_value' },
- index: 0,
- },
- ],
- id: '4',
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: { custom_field: 'custom_value' },
+ index: 0,
+ },
+ ],
+ id: '4',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: 4\n',
@@ -411,31 +332,21 @@ describe('OpenAIStream', () => {
});
it('should emit usage when choices are missing but usage exists', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: '99',
- usage: {
- prompt_tokens: 1,
- completion_tokens: 2,
- total_tokens: 3,
- prompt_cache_miss_tokens: 1,
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: '99',
+ usage: {
+ prompt_tokens: 1,
+ completion_tokens: 2,
+ total_tokens: 3,
+ prompt_cache_miss_tokens: 1,
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks: string[] = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: 99\n',
@@ -445,34 +356,25 @@ describe('OpenAIStream', () => {
});
it('should handle error when there is not correct error', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: { content: 'Hello' },
- index: 0,
- },
- ],
- id: '1',
- });
- controller.enqueue({
- id: '1',
- });
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: { content: 'Hello' },
+ index: 0,
+ },
+ ],
+ id: '1',
+ },
- controller.close();
+ {
+ id: '1',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
['id: 1', 'event: text', `data: "Hello"\n`, 'id: 1', 'event: data', `data: {"id":"1"}\n`].map(
@@ -482,26 +384,17 @@ describe('OpenAIStream', () => {
});
it('should handle FIRST_CHUNK_ERROR_KEY', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- [FIRST_CHUNK_ERROR_KEY]: true,
- errorType: AgentRuntimeErrorType.ProviderBizError,
- message: 'Test error',
- });
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ [FIRST_CHUNK_ERROR_KEY]: true,
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ message: 'Test error',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: first_chunk_error\n',
@@ -511,15 +404,9 @@ describe('OpenAIStream', () => {
});
it('should use bizErrorTypeTransformer', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue(
- '%FIRST_CHUNK_ERROR%: ' +
- JSON.stringify({ message: 'Custom error', name: 'CustomError' }),
- );
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream([
+ '%FIRST_CHUNK_ERROR%: ' + JSON.stringify({ message: 'Custom error', name: 'CustomError' }),
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream, {
bizErrorTypeTransformer: () => AgentRuntimeErrorType.PermissionDenied,
@@ -528,13 +415,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: first_chunk_error\n',
@@ -596,25 +477,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -695,25 +562,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -739,35 +592,31 @@ describe('OpenAIStream', () => {
describe('Tools Calling', () => {
it('should handle OpenAI official tool calls', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { name: 'tool1', arguments: '{}' },
- id: 'call_1',
- index: 0,
- type: 'function',
- },
- {
- function: { name: 'tool2', arguments: '{}' },
- id: 'call_2',
- index: 1,
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { name: 'tool1', arguments: '{}' },
+ id: 'call_1',
+ index: 0,
+ type: 'function',
+ },
+ {
+ function: { name: 'tool2', arguments: '{}' },
+ id: 'call_2',
+ index: 1,
+ },
+ ],
},
- ],
- id: '2',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: '2',
},
- });
+ ]);
const onToolCallMock = vi.fn();
@@ -777,13 +626,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: 2\n',
@@ -795,42 +638,32 @@ describe('OpenAIStream', () => {
});
it('should handle tool calls without index and type like mistral and minimax', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { name: 'tool1', arguments: '{}' },
- id: 'call_1',
- },
- {
- function: { name: 'tool2', arguments: '{}' },
- id: 'call_2',
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { name: 'tool1', arguments: '{}' },
+ id: 'call_1',
+ },
+ {
+ function: { name: 'tool2', arguments: '{}' },
+ id: 'call_2',
+ },
+ ],
},
- ],
- id: '5',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: '5',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: 5\n',
@@ -892,15 +725,7 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- streamData.forEach((data) => {
- controller.enqueue(data);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(streamData);
const onToolCallMock = vi.fn();
@@ -910,13 +735,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -942,58 +761,48 @@ describe('OpenAIStream', () => {
});
it('should handle tool calls without id using streamContext', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- // First chunk with id to initialize streamContext.tool
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { name: 'tool1', arguments: '{' },
- id: 'call_123',
- index: 0,
- type: 'function',
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ // First chunk with id to initialize streamContext.tool
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { name: 'tool1', arguments: '{' },
+ id: 'call_123',
+ index: 0,
+ type: 'function',
+ },
+ ],
},
- ],
- id: 'stream-context-1',
- });
- // Second chunk without id, should use streamContext.tool.id
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { arguments: '}' },
- index: 0,
- },
- ],
- },
- index: 0,
+ index: 0,
+ },
+ ],
+ id: 'stream-context-1',
+ },
+ // Second chunk without id, should use streamContext.tool.id
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { arguments: '}' },
+ index: 0,
+ },
+ ],
},
- ],
- id: 'stream-context-1',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'stream-context-1',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: stream-context-1\n',
@@ -1111,15 +920,7 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- streamData.forEach((data) => {
- controller.enqueue(data);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(streamData);
const onToolCallMock = vi.fn();
@@ -1129,13 +930,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -1168,32 +963,28 @@ describe('OpenAIStream', () => {
// OpenRouter returns thoughtSignature in tool_calls for Gemini models
// This is required for preserving reasoning blocks across turns
// Ref: https://openrouter.ai/docs/guides/best-practices/reasoning-tokens
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { name: 'github__get_me', arguments: '{}' },
- id: 'call_123',
- index: 0,
- type: 'function',
- // OpenRouter adds thoughtSignature for Gemini 3 models
- thoughtSignature: 'ErEDCq4DAdHtim...',
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { name: 'github__get_me', arguments: '{}' },
+ id: 'call_123',
+ index: 0,
+ type: 'function',
+ // OpenRouter adds thoughtSignature for Gemini 3 models
+ thoughtSignature: 'ErEDCq4DAdHtim...',
+ },
+ ],
},
- ],
- id: 'or-123',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'or-123',
},
- });
+ ]);
const onToolCallMock = vi.fn();
const thoughtSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
@@ -1210,13 +1001,7 @@ describe('OpenAIStream', () => {
payload: { thoughtSignatureScope },
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: or-123\n',
@@ -1249,31 +1034,27 @@ describe('OpenAIStream', () => {
it('should NOT include thoughtSignature in output when not present in tool call', async () => {
// Standard tool calls without thoughtSignature should not include the field
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- tool_calls: [
- {
- function: { name: 'search', arguments: '{"query":"test"}' },
- id: 'call_456',
- index: 0,
- type: 'function',
- // No thoughtSignature field
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ tool_calls: [
+ {
+ function: { name: 'search', arguments: '{"query":"test"}' },
+ id: 'call_456',
+ index: 0,
+ type: 'function',
+ // No thoughtSignature field
+ },
+ ],
},
- ],
- id: 'standard-123',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'standard-123',
},
- });
+ ]);
const onToolCallMock = vi.fn();
@@ -1283,13 +1064,7 @@ describe('OpenAIStream', () => {
},
});
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: standard-123\n',
@@ -1444,23 +1219,10 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- streamData.forEach((data) => {
- controller.enqueue(data);
- });
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(streamData);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks: string[] = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
// Verify the exact output - each tool call chunk should have the correct id based on index
expect(chunks).toEqual(
@@ -1529,21 +1291,10 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks: string[] = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -1675,23 +1426,10 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -1766,21 +1504,10 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -1948,25 +1675,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2164,25 +1877,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2251,25 +1950,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2436,25 +2121,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2637,25 +2308,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2838,25 +2495,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -2999,25 +2642,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -3168,25 +2797,11 @@ describe('OpenAIStream', () => {
},
];
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => {
- controller.enqueue(chunk);
- });
-
- controller.close();
- },
- });
+ const mockOpenAIStream = createReadableStream(data);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -3226,39 +2841,29 @@ describe('OpenAIStream', () => {
const base64 =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- images: [
- {
- type: 'image_url',
- image_url: { url: base64 },
- index: 0,
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ images: [
+ {
+ type: 'image_url',
+ image_url: { url: base64 },
+ index: 0,
+ },
+ ],
},
- ],
- id: '6',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: '6',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: 6\n', 'event: base64_image\n', `data: "${base64}"\n\n`]);
});
@@ -3266,32 +2871,22 @@ describe('OpenAIStream', () => {
it('should handle finish_reason with markdown image in content', async () => {
const base64 =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAAAgAElEQVR4nFy9a5okSY4jCFBU3SOr53HdvcZeYW/YVZnhZqpCYn+AVIuZ7PqqKyPczfQhQgIgSOH/+//9PxRVu7QzX5nvqveVP5mv+3rf+XPt985b2NIVgVgK1jr0da7zrAiegWPhPBABLi1GILhCEMkFnCuOFRFxHN/r/CbOym/om/h1X+d1H/v667rP9328r9g3VNblpoXsAwsnTtnWp0kQ40siih6NixuHlN9Rt7ehv1mbW2dkg1ef03J9zQQpQg5yc/XllveG4wa4arKtSr0NwSCdGEJVNeKlkDZMov695YaQ5NVK3fmjn4OrE9N/U04C0EqT/2HCBxrf9pJe1L2nPBjqhKEq1TEi1Q/OXiIq+IrqX2fUb+qF+2kF10k/4ScwIXidU6/T6vGkA/bSR/fZ7Ok8yOd0s+27CnP8PH3cijINdbAcAAAAASUVORK5CYII=';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'chatcmpl-test',
- choices: [
- {
- index: 0,
- delta: { content: `这有一张图片: ![image](${base64})` },
- finish_reason: 'stop',
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'chatcmpl-test',
+ choices: [
+ {
+ index: 0,
+ delta: { content: `这有一张图片: ![image](${base64})` },
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: chatcmpl-test\n',
@@ -3306,32 +2901,22 @@ describe('OpenAIStream', () => {
it('should handle finish_reason with multiple markdown images in content', async () => {
const base64_1 = 'data:image/png;base64,first';
const base64_2 = 'data:image/jpeg;base64,second';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'chatcmpl-multi',
- choices: [
- {
- index: 0,
- delta: { content: `![img1](${base64_1}) and ![img2](${base64_2})` },
- finish_reason: 'stop',
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'chatcmpl-multi',
+ choices: [
+ {
+ index: 0,
+ delta: { content: `![img1](${base64_1}) and ![img2](${base64_2})` },
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: chatcmpl-multi\n',
@@ -3348,136 +2933,96 @@ describe('OpenAIStream', () => {
it('should handle delta.images with nested image_url.image_url.url structure', async () => {
const base64 = 'data:image/png;base64,nestedurl';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- images: [
- {
- image_url: { image_url: { url: base64 } },
- },
- ],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ images: [
+ {
+ image_url: { image_url: { url: base64 } },
+ },
+ ],
},
- ],
- id: 'nested-url',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'nested-url',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: nested-url\n', 'event: base64_image\n', `data: "${base64}"\n\n`]);
});
it('should handle delta.images with direct url property', async () => {
const base64 = 'data:image/png;base64,directurl';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- images: [{ url: base64 }],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ images: [{ url: base64 }],
},
- ],
- id: 'direct-url',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'direct-url',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: direct-url\n', 'event: base64_image\n', `data: "${base64}"\n\n`]);
});
it('should handle delta.images with string format', async () => {
const base64 = 'data:image/png;base64,stringformat';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- images: [base64],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ images: [base64],
},
- ],
- id: 'string-img',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'string-img',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: string-img\n', 'event: base64_image\n', `data: "${base64}"\n\n`]);
});
it('should filter out images without valid url', async () => {
const base64 = 'data:image/png;base64,validurl';
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- choices: [
- {
- delta: {
- images: [{ invalid: 'data' }, { url: base64 }, null],
- },
- index: 0,
+ const mockOpenAIStream = createReadableStream([
+ {
+ choices: [
+ {
+ delta: {
+ images: [{ invalid: 'data' }, { url: base64 }, null],
},
- ],
- id: 'filtered-images',
- });
-
- controller.close();
+ index: 0,
+ },
+ ],
+ id: 'filtered-images',
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: filtered-images\n',
@@ -3487,75 +3032,55 @@ describe('OpenAIStream', () => {
});
it('should ignore content when role is tool in finish_reason', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-tool-role',
- choices: [
- {
- index: 0,
- delta: { content: 'should be ignored', role: 'tool' },
- finish_reason: 'stop',
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-tool-role',
+ choices: [
+ {
+ index: 0,
+ delta: { content: 'should be ignored', role: 'tool' },
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(['id: minimax-tool-role\n', 'event: text\n', `data: null\n\n`]);
});
it('should handle OpenAI Search Preview annotations in finish_reason', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'openai-search',
- choices: [
- {
- index: 0,
- delta: {
- annotations: [
- {
- type: 'url_citation',
- url_citation: {
- url: 'https://example.com',
- title: 'Example',
- start_index: 0,
- end_index: 10,
- },
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'openai-search',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ annotations: [
+ {
+ type: 'url_citation',
+ url_citation: {
+ url: 'https://example.com',
+ title: 'Example',
+ start_index: 0,
+ end_index: 10,
},
- ],
- },
- finish_reason: 'stop',
+ },
+ ],
},
- ],
- });
-
- controller.close();
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: openai-search\n',
@@ -3568,40 +3093,30 @@ describe('OpenAIStream', () => {
// OpenRouter's built-in web search may emit empty citation objects like `{}`,
// which previously crashed rendering (`new URL(undefined)`) and message persistence.
// See https://github.com/lobehub/lobehub/issues/15043
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'openrouter-search',
- choices: [
- {
- index: 0,
- delta: {
- annotations: [
- { type: 'url_citation', url_citation: {} },
- {
- type: 'url_citation',
- url_citation: { url: 'https://example.com', title: 'Example' },
- },
- ],
- },
- finish_reason: 'stop',
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'openrouter-search',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ annotations: [
+ { type: 'url_citation', url_citation: {} },
+ {
+ type: 'url_citation',
+ url_citation: { url: 'https://example.com', title: 'Example' },
+ },
+ ],
},
- ],
- });
-
- controller.close();
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: openrouter-search\n',
@@ -3611,82 +3126,70 @@ describe('OpenAIStream', () => {
});
it('should handle XiaomiMiMo annotations', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'mimo-v2-omni',
- choices: [
- {
- index: 0,
- delta: {
- role: 'assistant',
- content: '',
- annotations: [
- {
- type: 'url_citation',
- url: 'https://biz.finance.sina.com.cn/usstock/usstock_news.php?symbol=ZNH',
- title: '南方航空相关新闻_美股 - 新浪财经',
- site_name: 'biz.finance.sina.com.cn',
- summary:
- '(ZNH) · 格隆汇 APP | 2026 年 03 月 19 日 11:09 港股异动丨航空股跌势不止成本压力巨大国内航司集体上调燃油附加费',
- },
- ],
- },
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'mimo-v2-omni',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ role: 'assistant',
+ content: '',
+ annotations: [
+ {
+ type: 'url_citation',
+ url: 'https://biz.finance.sina.com.cn/usstock/usstock_news.php?symbol=ZNH',
+ title: '南方航空相关新闻_美股 - 新浪财经',
+ site_name: 'biz.finance.sina.com.cn',
+ summary:
+ '(ZNH) · 格隆汇 APP | 2026 年 03 月 19 日 11:09 港股异动丨航空股跌势不止成本压力巨大国内航司集体上调燃油附加费',
+ },
+ ],
},
- ],
- });
-
- // Second chunk with finish_reason
- controller.enqueue({
- id: 'mimo-v2-omni',
- choices: [
- {
- index: 0,
- delta: {
- role: 'assistant',
- content: 'Some response text with annotations, should has no annotations',
- annotations: [
- {
- type: 'url_citation',
- url: 'https://biz.finance.sina.com.cn/usstock/usstock_news.php?symbol=ZNH',
- title: '南方航空相关新闻_美股 - 新浪财经',
- site_name: 'biz.finance.sina.com.cn',
- summary:
- '(ZNH) · 格隆汇 APP | 2026 年 03 月 19 日 11:09 港股异动丨航空股跌势不止成本压力巨大国内航司集体上调燃油附加费',
- },
- ],
- },
+ },
+ ],
+ },
+ // Second chunk with finish_reason
+ {
+ id: 'mimo-v2-omni',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ role: 'assistant',
+ content: 'Some response text with annotations, should has no annotations',
+ annotations: [
+ {
+ type: 'url_citation',
+ url: 'https://biz.finance.sina.com.cn/usstock/usstock_news.php?symbol=ZNH',
+ title: '南方航空相关新闻_美股 - 新浪财经',
+ site_name: 'biz.finance.sina.com.cn',
+ summary:
+ '(ZNH) · 格隆汇 APP | 2026 年 03 月 19 日 11:09 港股异动丨航空股跌势不止成本压力巨大国内航司集体上调燃油附加费',
+ },
+ ],
},
- ],
- });
-
- // Third chunk with finish_reason
- controller.enqueue({
- id: 'mimo-v2-omni',
- choices: [
- {
- index: 0,
- delta: {
- content: 'Some response text',
- },
- finish_reason: 'stop',
+ },
+ ],
+ },
+ // Third chunk with finish_reason
+ {
+ id: 'mimo-v2-omni',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ content: 'Some response text',
},
- ],
- });
-
- controller.close();
+ finish_reason: 'stop',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
// Should emit grounding event from first chunk, then text from second chunk
expect(chunks).toEqual([
@@ -3703,47 +3206,37 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax messages with annotations in finish_reason', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-messages',
- choices: [
- {
- index: 0,
- messages: [
- { content: '', role: 'user' },
- { content: '', role: 'assistant' },
- { content: '', role: 'tool' },
- {
- content: '',
- role: 'assistant',
- annotations: [
- {
- text: '【5†source】',
- url: 'https://example.com',
- quote: 'Example quote',
- },
- ],
- },
- ],
- finish_reason: 'tool_calls',
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-messages',
+ choices: [
+ {
+ index: 0,
+ messages: [
+ { content: '', role: 'user' },
+ { content: '', role: 'assistant' },
+ { content: '', role: 'tool' },
+ {
+ content: '',
+ role: 'assistant',
+ annotations: [
+ {
+ text: '【5†source】',
+ url: 'https://example.com',
+ quote: 'Example quote',
+ },
+ ],
+ },
+ ],
+ finish_reason: 'tool_calls',
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: minimax-messages\n',
@@ -3753,33 +3246,23 @@ describe('OpenAIStream', () => {
});
it('should handle xAI citations in finish_reason', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'xai-citations',
- choices: [
- {
- index: 0,
- delta: { role: 'assistant' },
- finish_reason: 'stop',
- },
- ],
- citations: ['https://example1.com', 'https://example2.com'],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'xai-citations',
+ choices: [
+ {
+ index: 0,
+ delta: { role: 'assistant' },
+ finish_reason: 'stop',
+ },
+ ],
+ citations: ['https://example1.com', 'https://example2.com'],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: xai-citations\n',
@@ -3789,37 +3272,27 @@ describe('OpenAIStream', () => {
});
it('should handle finish_reason with usage', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'finish-usage',
- choices: [
- {
- index: 0,
- delta: {},
- finish_reason: 'stop',
- },
- ],
- usage: {
- prompt_tokens: 10,
- completion_tokens: 20,
- total_tokens: 30,
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'finish-usage',
+ choices: [
+ {
+ index: 0,
+ delta: {},
+ finish_reason: 'stop',
},
- });
-
- controller.close();
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ total_tokens: 30,
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: finish-usage\n',
@@ -3829,37 +3302,27 @@ describe('OpenAIStream', () => {
});
it('should handle finish_reason with text and usage', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'finish-text-usage',
- choices: [
- {
- index: 0,
- delta: { content: 'done' },
- finish_reason: 'stop',
- },
- ],
- usage: {
- prompt_tokens: 10,
- completion_tokens: 20,
- total_tokens: 30,
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'finish-text-usage',
+ choices: [
+ {
+ index: 0,
+ delta: { content: 'done' },
+ finish_reason: 'stop',
},
- });
-
- controller.close();
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ total_tokens: 30,
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: finish-text-usage\n',
@@ -3872,46 +3335,36 @@ describe('OpenAIStream', () => {
});
it('should handle mistral AI Magistral thinking blocks in content array', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'mistral-thinking',
- choices: [
- {
- index: 0,
- delta: {
- content: [
- {
- type: 'thinking',
- thinking: [
- { type: 'text', text: 'First thought' },
- { type: 'text', text: 'Second thought' },
- { type: 'other', data: 'ignored' },
- ],
- },
- {
- type: 'thinking',
- thinking: [{ type: 'text', text: 'Third thought' }],
- },
- ],
- },
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'mistral-thinking',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ content: [
+ {
+ type: 'thinking',
+ thinking: [
+ { type: 'text', text: 'First thought' },
+ { type: 'text', text: 'Second thought' },
+ { type: 'other', data: 'ignored' },
+ ],
+ },
+ {
+ type: 'thinking',
+ thinking: [{ type: 'text', text: 'Third thought' }],
+ },
+ ],
},
- ],
- });
-
- controller.close();
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: mistral-thinking\n',
@@ -3921,62 +3374,42 @@ describe('OpenAIStream', () => {
});
it('should handle empty content and empty reasoning_content (still outputs reasoning)', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'empty-both',
- choices: [
- {
- index: 0,
- delta: { content: '', reasoning_content: '' },
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'empty-both',
+ choices: [
+ {
+ index: 0,
+ delta: { content: '', reasoning_content: '' },
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
// When both are empty strings, content becomes null but reasoning_content stays as empty string
expect(chunks).toEqual(['id: empty-both\n', 'event: reasoning\n', `data: ""\n\n`]);
});
it('should handle empty content with non-empty reasoning_content', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'empty-content-with-reasoning',
- choices: [
- {
- index: 0,
- delta: { content: '', reasoning_content: 'some thinking' },
- },
- ],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'empty-content-with-reasoning',
+ choices: [
+ {
+ index: 0,
+ delta: { content: '', reasoning_content: 'some thinking' },
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: empty-content-with-reasoning\n',
@@ -3986,36 +3419,26 @@ describe('OpenAIStream', () => {
});
it('should handle Gemini empty content with usage', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'gemini-usage',
- choices: [
- {
- index: 0,
- delta: { content: '' },
- },
- ],
- usage: {
- prompt_tokens: 5,
- completion_tokens: 10,
- total_tokens: 15,
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'gemini-usage',
+ choices: [
+ {
+ index: 0,
+ delta: { content: '' },
},
- });
-
- controller.close();
+ ],
+ usage: {
+ prompt_tokens: 5,
+ completion_tokens: 10,
+ total_tokens: 15,
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual([
'id: gemini-usage\n',
@@ -4026,36 +3449,28 @@ describe('OpenAIStream', () => {
describe('Grounding/Citations', () => {
it('should handle Perplexity citations', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'perplexity-1',
- choices: [{ index: 0, delta: { content: 'Here is some info' } }],
- citations: ['https://source1.com', 'https://source2.com'],
- });
- controller.enqueue({
- id: 'perplexity-1',
- choices: [{ index: 0, delta: { content: ' more content' } }],
- citations: ['https://source1.com', 'https://source2.com'],
- });
- controller.enqueue({
- id: 'perplexity-1',
- choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'perplexity-1',
+ choices: [{ index: 0, delta: { content: 'Here is some info' } }],
+ citations: ['https://source1.com', 'https://source2.com'],
},
- });
- const protocolStream = OpenAIStream(mockOpenAIStream);
+ {
+ id: 'perplexity-1',
+ choices: [{ index: 0, delta: { content: ' more content' } }],
+ citations: ['https://source1.com', 'https://source2.com'],
+ },
- const decoder = new TextDecoder();
- const chunks = [];
+ {
+ id: 'perplexity-1',
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
+ },
+ ]);
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const protocolStream = OpenAIStream(mockOpenAIStream);
+
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -4076,36 +3491,27 @@ describe('OpenAIStream', () => {
});
it('should handle Hunyuan search_info.search_results', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'hunyuan-1',
- choices: [{ index: 0, delta: { content: 'Result' } }],
- search_info: {
- search_results: [
- { title: 'Title 1', url: 'https://result1.com' },
- { title: 'Title 2', link: 'https://result2.com' },
- ],
- },
- });
- controller.enqueue({
- id: 'hunyuan-1',
- choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
- });
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'hunyuan-1',
+ choices: [{ index: 0, delta: { content: 'Result' } }],
+ search_info: {
+ search_results: [
+ { title: 'Title 1', url: 'https://result1.com' },
+ { title: 'Title 2', link: 'https://result2.com' },
+ ],
+ },
+ },
- controller.close();
+ {
+ id: 'hunyuan-1',
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -4123,31 +3529,22 @@ describe('OpenAIStream', () => {
});
it('should handle Wenxin search_results', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'wenxin-1',
- choices: [{ index: 0, delta: { content: 'Content' } }],
- search_results: [{ title: 'Wenxin', url: 'https://wenxin.com' }],
- });
- controller.enqueue({
- id: 'wenxin-1',
- choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'wenxin-1',
+ choices: [{ index: 0, delta: { content: 'Content' } }],
+ search_results: [{ title: 'Wenxin', url: 'https://wenxin.com' }],
},
- });
- const protocolStream = OpenAIStream(mockOpenAIStream);
+ {
+ id: 'wenxin-1',
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
+ },
+ ]);
- const decoder = new TextDecoder();
- const chunks = [];
+ const protocolStream = OpenAIStream(mockOpenAIStream);
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -4165,35 +3562,26 @@ describe('OpenAIStream', () => {
});
it('should handle Zhipu web_search and filter empty links', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'zhipu-1',
- choices: [{ index: 0, delta: { content: 'Search result' } }],
- web_search: [
- { title: 'Valid', url: 'https://valid.com' },
- { title: 'Empty link', link: '' },
- { title: 'No link' },
- ],
- });
- controller.enqueue({
- id: 'zhipu-1',
- choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
- });
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'zhipu-1',
+ choices: [{ index: 0, delta: { content: 'Search result' } }],
+ web_search: [
+ { title: 'Valid', url: 'https://valid.com' },
+ { title: 'Empty link', link: '' },
+ { title: 'No link' },
+ ],
+ },
- controller.close();
+ {
+ id: 'zhipu-1',
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks).toEqual(
[
@@ -4213,35 +3601,25 @@ describe('OpenAIStream', () => {
describe('Error handling', () => {
it('should handle stream chunk error and return error chunk', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- // This will cause an error when trying to process
- controller.enqueue({
- id: 'error-chunk',
- choices: [
- {
- index: 0,
- delta: {
- // This will trigger the error in tool_calls processing
- tool_calls: [{ function: null }],
- },
+ const mockOpenAIStream = createReadableStream([
+ // This will cause an error when trying to process
+ {
+ id: 'error-chunk',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ // This will trigger the error in tool_calls processing
+ tool_calls: [{ function: null }],
},
- ],
- });
-
- controller.close();
+ },
+ ],
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: error-chunk\n');
expect(chunks[1]).toBe('event: error\n');
@@ -4252,30 +3630,20 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax base_resp error with insufficient quota (1008)', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-error-1008',
- choices: null,
- base_resp: {
- status_code: 1008,
- status_msg: 'insufficient balance',
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-error-1008',
+ choices: null,
+ base_resp: {
+ status_code: 1008,
+ status_msg: 'insufficient balance',
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: minimax-error-1008\n');
expect(chunks[1]).toBe('event: error\n');
@@ -4285,30 +3653,20 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax base_resp error with invalid API key (2049)', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-error-2049',
- choices: null,
- base_resp: {
- status_code: 2049,
- status_msg: 'invalid API Key',
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-error-2049',
+ choices: null,
+ base_resp: {
+ status_code: 2049,
+ status_msg: 'invalid API Key',
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: minimax-error-2049\n');
expect(chunks[1]).toBe('event: error\n');
@@ -4317,30 +3675,20 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax base_resp error with rate limit (1002)', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-error-1002',
- choices: null,
- base_resp: {
- status_code: 1002,
- status_msg: 'request frequency exceeds limit',
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-error-1002',
+ choices: null,
+ base_resp: {
+ status_code: 1002,
+ status_msg: 'request frequency exceeds limit',
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: minimax-error-1002\n');
expect(chunks[1]).toBe('event: error\n');
@@ -4349,30 +3697,20 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax base_resp error with context window exceeded (1039)', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-error-1039',
- choices: null,
- base_resp: {
- status_code: 1039,
- status_msg: 'token limit exceeded',
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-error-1039',
+ choices: null,
+ base_resp: {
+ status_code: 1039,
+ status_msg: 'token limit exceeded',
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: minimax-error-1039\n');
expect(chunks[1]).toBe('event: error\n');
@@ -4381,30 +3719,20 @@ describe('OpenAIStream', () => {
});
it('should handle MiniMax base_resp error with fallback to ProviderBizError', async () => {
- const mockOpenAIStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- id: 'minimax-error-unknown',
- choices: null,
- base_resp: {
- status_code: 9999,
- status_msg: 'unknown error',
- },
- });
-
- controller.close();
+ const mockOpenAIStream = createReadableStream([
+ {
+ id: 'minimax-error-unknown',
+ choices: null,
+ base_resp: {
+ status_code: 9999,
+ status_msg: 'unknown error',
+ },
},
- });
+ ]);
const protocolStream = OpenAIStream(mockOpenAIStream);
- const decoder = new TextDecoder();
- const chunks = [];
-
- // @ts-ignore
- for await (const chunk of protocolStream) {
- chunks.push(decoder.decode(chunk, { stream: true }));
- }
+ const chunks = await readStreamChunk(protocolStream);
expect(chunks[0]).toBe('id: minimax-error-unknown\n');
expect(chunks[1]).toBe('event: error\n');
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
index d682c6a5a10..7441043f927 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
@@ -6,122 +6,101 @@ import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
import { createReadableStream, readStreamChunk } from '../utils';
import { OpenAIResponsesStream } from './responsesStream';
+const createdResponse = (id: string) => ({
+ type: 'response.created',
+ response: { id, status: 'in_progress' },
+});
+
+const createWebBrowsingTools = () => [
+ {
+ type: 'function',
+ description:
+ 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
+ name: 'lobe-web-browsing____search',
+ parameters: {
+ properties: {
+ query: { description: 'The search query', type: 'string' },
+ searchCategories: {
+ description: 'The search categories you can set:',
+ items: {
+ enum: ['general', 'images', 'news', 'science', 'videos'],
+ type: 'string',
+ },
+ type: 'array',
+ },
+ searchEngines: {
+ description: 'The search engines you can use:',
+ items: {
+ enum: [
+ 'google',
+ 'bilibili',
+ 'bing',
+ 'duckduckgo',
+ 'npm',
+ 'pypi',
+ 'github',
+ 'arxiv',
+ 'google scholar',
+ 'z-library',
+ 'reddit',
+ 'imdb',
+ 'brave',
+ 'wikipedia',
+ 'pinterest',
+ 'unsplash',
+ 'vimeo',
+ 'youtube',
+ ],
+ type: 'string',
+ },
+ type: 'array',
+ },
+ searchTimeRange: {
+ description: 'The time range you can set:',
+ enum: ['anytime', 'day', 'week', 'month', 'year'],
+ type: 'string',
+ },
+ },
+ required: ['query'],
+ type: 'object',
+ },
+ strict: true,
+ },
+ {
+ type: 'function',
+ description:
+ 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
+ name: 'lobe-web-browsing____crawlSinglePage',
+ parameters: {
+ properties: { url: { description: 'The url need to be crawled', type: 'string' } },
+ required: ['url'],
+ type: 'object',
+ },
+ strict: true,
+ },
+ {
+ type: 'function',
+ description:
+ 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
+ name: 'lobe-web-browsing____crawlMultiPages',
+ parameters: {
+ properties: {
+ urls: {
+ items: { description: 'The urls need to be crawled', type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['urls'],
+ type: 'object',
+ },
+ strict: true,
+ },
+];
+
describe('OpenAIResponsesStream', () => {
it('should transform OpenAI stream to protocol stream', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_683e7b8ca3308190b6837f20d2c015cd0cf93af363cdcf58',
- object: 'response',
- created_at: 1748925324,
- status: 'in_progress',
- error: null,
- incomplete_details: null,
- instructions: null,
- max_output_tokens: null,
- model: 'o4-mini',
- output: [],
- parallel_tool_calls: true,
- previous_response_id: null,
- reasoning: { effort: 'medium', summary: null },
- service_tier: 'auto',
- store: false,
- temperature: 1,
- text: { format: { type: 'text' } },
- tool_choice: 'auto',
- tools: [
- {
- type: 'function',
- description:
- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
- name: 'lobe-web-browsing____search',
- parameters: {
- properties: {
- query: { description: 'The search query', type: 'string' },
- searchCategories: {
- description: 'The search categories you can set:',
- items: {
- enum: ['general', 'images', 'news', 'science', 'videos'],
- type: 'string',
- },
- type: 'array',
- },
- searchEngines: {
- description: 'The search engines you can use:',
- items: {
- enum: [
- 'google',
- 'bilibili',
- 'bing',
- 'duckduckgo',
- 'npm',
- 'pypi',
- 'github',
- 'arxiv',
- 'google scholar',
- 'z-library',
- 'reddit',
- 'imdb',
- 'brave',
- 'wikipedia',
- 'pinterest',
- 'unsplash',
- 'vimeo',
- 'youtube',
- ],
- type: 'string',
- },
- type: 'array',
- },
- searchTimeRange: {
- description: 'The time range you can set:',
- enum: ['anytime', 'day', 'week', 'month', 'year'],
- type: 'string',
- },
- },
- required: ['query'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlSinglePage',
- parameters: {
- properties: { url: { description: 'The url need to be crawled', type: 'string' } },
- required: ['url'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlMultiPages',
- parameters: {
- properties: {
- urls: {
- items: { description: 'The urls need to be crawled', type: 'string' },
- type: 'array',
- },
- },
- required: ['urls'],
- type: 'object',
- },
- strict: true,
- },
- ],
- top_p: 1,
- truncation: 'disabled',
- usage: null,
- user: null,
- metadata: {},
- },
- },
+ createdResponse('resp_683e7b8ca3308190b6837f20d2c015cd0cf93af363cdcf58'),
{
type: 'response.in_progress',
response: {
@@ -143,91 +122,7 @@ describe('OpenAIResponsesStream', () => {
temperature: 1,
text: { format: { type: 'text' } },
tool_choice: 'auto',
- tools: [
- {
- type: 'function',
- description:
- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
- name: 'lobe-web-browsing____search',
- parameters: {
- properties: {
- query: { description: 'The search query', type: 'string' },
- searchCategories: {
- description: 'The search categories you can set:',
- items: {
- enum: ['general', 'images', 'news', 'science', 'videos'],
- type: 'string',
- },
- type: 'array',
- },
- searchEngines: {
- description: 'The search engines you can use:',
- items: {
- enum: [
- 'google',
- 'bilibili',
- 'bing',
- 'duckduckgo',
- 'npm',
- 'pypi',
- 'github',
- 'arxiv',
- 'google scholar',
- 'z-library',
- 'reddit',
- 'imdb',
- 'brave',
- 'wikipedia',
- 'pinterest',
- 'unsplash',
- 'vimeo',
- 'youtube',
- ],
- type: 'string',
- },
- type: 'array',
- },
- searchTimeRange: {
- description: 'The time range you can set:',
- enum: ['anytime', 'day', 'week', 'month', 'year'],
- type: 'string',
- },
- },
- required: ['query'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlSinglePage',
- parameters: {
- properties: { url: { description: 'The url need to be crawled', type: 'string' } },
- required: ['url'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlMultiPages',
- parameters: {
- properties: {
- urls: {
- items: { description: 'The urls need to be crawled', type: 'string' },
- type: 'array',
- },
- },
- required: ['urls'],
- type: 'object',
- },
- strict: true,
- },
- ],
+ tools: createWebBrowsingTools(),
top_p: 1,
truncation: 'disabled',
usage: null,
@@ -341,17 +236,7 @@ describe('OpenAIResponsesStream', () => {
});
it('should handle response.created event', async () => {
- const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_test_123',
- status: 'in_progress',
- object: 'response',
- created_at: 1234567890,
- },
- },
- ]);
+ const mockOpenAIStream = createReadableStream([createdResponse('resp_test_123')]);
const protocolStream = OpenAIResponsesStream(mockOpenAIStream);
const chunks = await readStreamChunk(protocolStream);
@@ -363,13 +248,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle function_call in response.output_item.added', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_test_456',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_test_456'),
{
type: 'response.output_item.added',
output_index: 0,
@@ -392,13 +271,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle multiple function_calls with incrementing index', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_multi_tool',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_multi_tool'),
{
type: 'response.output_item.added',
output_index: 0,
@@ -430,13 +303,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.function_call_arguments.delta', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_delta_test',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_delta_test'),
{
type: 'response.output_item.added',
output_index: 0,
@@ -463,13 +330,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.output_text.delta', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_text_delta',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_text_delta'),
{
type: 'response.output_text.delta',
item_id: 'msg_123',
@@ -493,13 +354,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.reasoning_summary_part.added for first part', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_reasoning',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_reasoning'),
{
type: 'response.reasoning_summary_part.added',
item_id: 'reasoning_1',
@@ -517,13 +372,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.reasoning_summary_part.added for subsequent parts', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_reasoning_multi',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_reasoning_multi'),
{
type: 'response.reasoning_summary_part.added',
item_id: 'reasoning_1',
@@ -547,13 +396,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.reasoning_summary_text.delta', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_reasoning_delta',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_reasoning_delta'),
{
type: 'response.reasoning_summary_text.delta',
item_id: 'reasoning_123',
@@ -580,13 +423,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle xAI response.reasoning_text.delta', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_reasoning_text_delta',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_reasoning_text_delta'),
{
type: 'response.reasoning_text.delta',
item_id: 'reasoning_123',
@@ -603,13 +440,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.output_text.annotation.added', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_annotation',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_annotation'),
{
type: 'response.output_text.annotation.added',
item_id: 'msg_citation',
@@ -631,13 +462,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle multiple annotations and accumulate citations', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_multi_citation',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_multi_citation'),
{
type: 'response.output_text.annotation.added',
item_id: 'msg_cite',
@@ -670,13 +495,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.output_item.done with citations', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_done_citation',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_done_citation'),
{
type: 'response.output_text.annotation.added',
item_id: 'msg_final',
@@ -709,13 +528,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.output_item.done without citations', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_done_no_citation',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_done_no_citation'),
{
type: 'response.output_item.done',
output_index: 0,
@@ -736,13 +549,7 @@ describe('OpenAIResponsesStream', () => {
it('should emit encrypted reasoning content as a reasoning signature', async () => {
const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_reasoning_signature',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_reasoning_signature'),
{
type: 'response.output_item.done',
output_index: 0,
@@ -893,13 +700,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.completed with usage', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_completed_usage',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_completed_usage'),
{
type: 'response.completed',
response: {
@@ -926,13 +727,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle response.completed without usage', async () => {
const onFinal = vi.fn();
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_completed_no_usage',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_completed_no_usage'),
{
type: 'response.completed',
response: {
@@ -968,13 +763,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle unknown chunk type as data', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_unknown',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_unknown'),
{
type: 'response.unknown_event',
data: 'some data',
@@ -990,13 +779,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle non-standard item types in output_item.added', async () => {
// Test the default case in output_item.added when item type is not function_call
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_other_item',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_other_item'),
{
type: 'response.output_item.added',
output_index: 0,
@@ -1020,13 +803,7 @@ describe('OpenAIResponsesStream', () => {
it('should handle chunks with undefined values gracefully', async () => {
// Test handling of chunks with undefined/missing properties
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_undefined_vals',
- status: 'in_progress',
- },
- },
+ createdResponse('resp_undefined_vals'),
{
type: 'response.reasoning_summary_text.delta',
item_id: undefined,
@@ -1044,121 +821,7 @@ describe('OpenAIResponsesStream', () => {
describe('Reasoning', () => {
it('summary', async () => {
const mockOpenAIStream = createReadableStream([
- {
- type: 'response.created',
- response: {
- id: 'resp_684313b89200819087f27686e0c822260b502bf083132d0d',
- object: 'response',
- created_at: 1749226424,
- status: 'in_progress',
- error: null,
- incomplete_details: null,
- instructions: null,
- max_output_tokens: null,
- model: 'o4-mini',
- output: [],
- parallel_tool_calls: true,
- previous_response_id: null,
- reasoning: { effort: 'medium', summary: 'detailed' },
- service_tier: 'auto',
- store: false,
- temperature: 1,
- text: { format: { type: 'text' } },
- tool_choice: 'auto',
- tools: [
- {
- type: 'function',
- description:
- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
- name: 'lobe-web-browsing____search',
- parameters: {
- properties: {
- query: { description: 'The search query', type: 'string' },
- searchCategories: {
- description: 'The search categories you can set:',
- items: {
- enum: ['general', 'images', 'news', 'science', 'videos'],
- type: 'string',
- },
- type: 'array',
- },
- searchEngines: {
- description: 'The search engines you can use:',
- items: {
- enum: [
- 'google',
- 'bilibili',
- 'bing',
- 'duckduckgo',
- 'npm',
- 'pypi',
- 'github',
- 'arxiv',
- 'google scholar',
- 'z-library',
- 'reddit',
- 'imdb',
- 'brave',
- 'wikipedia',
- 'pinterest',
- 'unsplash',
- 'vimeo',
- 'youtube',
- ],
- type: 'string',
- },
- type: 'array',
- },
- searchTimeRange: {
- description: 'The time range you can set:',
- enum: ['anytime', 'day', 'week', 'month', 'year'],
- type: 'string',
- },
- },
- required: ['query'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlSinglePage',
- parameters: {
- properties: {
- url: { description: 'The url need to be crawled', type: 'string' },
- },
- required: ['url'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlMultiPages',
- parameters: {
- properties: {
- urls: {
- items: { description: 'The urls need to be crawled', type: 'string' },
- type: 'array',
- },
- },
- required: ['urls'],
- type: 'object',
- },
- strict: true,
- },
- ],
- top_p: 1,
- truncation: 'disabled',
- usage: null,
- user: null,
- metadata: {},
- },
- },
+ createdResponse('resp_684313b89200819087f27686e0c822260b502bf083132d0d'),
{
type: 'response.in_progress',
response: {
@@ -1180,93 +843,7 @@ describe('OpenAIResponsesStream', () => {
temperature: 1,
text: { format: { type: 'text' } },
tool_choice: 'auto',
- tools: [
- {
- type: 'function',
- description:
- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
- name: 'lobe-web-browsing____search',
- parameters: {
- properties: {
- query: { description: 'The search query', type: 'string' },
- searchCategories: {
- description: 'The search categories you can set:',
- items: {
- enum: ['general', 'images', 'news', 'science', 'videos'],
- type: 'string',
- },
- type: 'array',
- },
- searchEngines: {
- description: 'The search engines you can use:',
- items: {
- enum: [
- 'google',
- 'bilibili',
- 'bing',
- 'duckduckgo',
- 'npm',
- 'pypi',
- 'github',
- 'arxiv',
- 'google scholar',
- 'z-library',
- 'reddit',
- 'imdb',
- 'brave',
- 'wikipedia',
- 'pinterest',
- 'unsplash',
- 'vimeo',
- 'youtube',
- ],
- type: 'string',
- },
- type: 'array',
- },
- searchTimeRange: {
- description: 'The time range you can set:',
- enum: ['anytime', 'day', 'week', 'month', 'year'],
- type: 'string',
- },
- },
- required: ['query'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlSinglePage',
- parameters: {
- properties: {
- url: { description: 'The url need to be crawled', type: 'string' },
- },
- required: ['url'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlMultiPages',
- parameters: {
- properties: {
- urls: {
- items: { description: 'The urls need to be crawled', type: 'string' },
- type: 'array',
- },
- },
- required: ['urls'],
- type: 'object',
- },
- strict: true,
- },
- ],
+ tools: createWebBrowsingTools(),
top_p: 1,
truncation: 'disabled',
usage: null,
@@ -1417,130 +994,7 @@ describe('OpenAIResponsesStream', () => {
type: 'response.completed',
response: {
id: 'resp_684313b89200819087f27686e0c822260b502bf083132d0d',
- object: 'response',
- created_at: 1749226424,
status: 'completed',
- error: null,
- incomplete_details: null,
- instructions: null,
- max_output_tokens: null,
- model: 'o4-mini',
- output: [
- {
- id: 'rs_684313b9774481908ee856625f82fb8c0b502bf083132d0d',
- type: 'reasoning',
- summary: [
- {
- type: 'summary_text',
- text: '**Answering a numeric comparison**\n\nThe user is asking in Chinese which number is larger: 9.1 or 9.92. This is straightforward since 9.92 is clearly larger, as it\'s greater than 9.1. We can respond with "9.92大于9.1" without needing to search for more information. It\'s a simplcomparison, but I could also add a little explanation, noting that 9.92 is indeed 0.82 more than 9.1. However, keeping it simple with "9.92 > 9.1" is perfectly fine!',
- },
- ],
- },
- {
- id: 'msg_684313bee2c88190b0f4b09621ad7dc60b502bf083132d0d',
- type: 'message',
- status: 'completed',
- content: [{ type: 'output_text', annotations: [], text: '9.92 比 9.1 大。' }],
- role: 'assistant',
- },
- ],
- parallel_tool_calls: true,
- previous_response_id: null,
- reasoning: { effort: 'medium', summary: 'detailed' },
- service_tier: 'default',
- store: false,
- temperature: 1,
- text: { format: { type: 'text' } },
- tool_choice: 'auto',
- tools: [
- {
- type: 'function',
- description:
- 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
- name: 'lobe-web-browsing____search',
- parameters: {
- properties: {
- query: { description: 'The search query', type: 'string' },
- searchCategories: {
- description: 'The search categories you can set:',
- items: {
- enum: ['general', 'images', 'news', 'science', 'videos'],
- type: 'string',
- },
- type: 'array',
- },
- searchEngines: {
- description: 'The search engines you can use:',
- items: {
- enum: [
- 'google',
- 'bilibili',
- 'bing',
- 'duckduckgo',
- 'npm',
- 'pypi',
- 'github',
- 'arxiv',
- 'google scholar',
- 'z-library',
- 'reddit',
- 'imdb',
- 'brave',
- 'wikipedia',
- 'pinterest',
- 'unsplash',
- 'vimeo',
- 'youtube',
- ],
- type: 'string',
- },
- type: 'array',
- },
- searchTimeRange: {
- description: 'The time range you can set:',
- enum: ['anytime', 'day', 'week', 'month', 'year'],
- type: 'string',
- },
- },
- required: ['query'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlSinglePage',
- parameters: {
- properties: {
- url: { description: 'The url need to be crawled', type: 'string' },
- },
- required: ['url'],
- type: 'object',
- },
- strict: true,
- },
- {
- type: 'function',
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website',
- name: 'lobe-web-browsing____crawlMultiPages',
- parameters: {
- properties: {
- urls: {
- items: { description: 'The urls need to be crawled', type: 'string' },
- type: 'array',
- },
- },
- required: ['urls'],
- type: 'object',
- },
- strict: true,
- },
- ],
- top_p: 1,
- truncation: 'disabled',
usage: {
input_tokens: 2391,
input_tokens_details: { cached_tokens: 2298 },
@@ -1548,8 +1002,6 @@ describe('OpenAIResponsesStream', () => {
output_tokens_details: { reasoning_tokens: 128 },
total_tokens: 2535,
},
- user: null,
- metadata: {},
},
},
]);
@@ -1587,7 +1039,7 @@ describe('OpenAIResponsesStream', () => {
it('surfaces response.failed as an error carrying the upstream message', async () => {
const { chunks, completion } = await collect([
- { type: 'response.created', response: { id: 'resp_failed', status: 'in_progress' } },
+ createdResponse('resp_failed'),
{
type: 'response.failed',
response: {
@@ -1611,7 +1063,7 @@ describe('OpenAIResponsesStream', () => {
it('surfaces a bare error event as an error', async () => {
const { completion } = await collect([
- { type: 'response.created', response: { id: 'resp_error', status: 'in_progress' } },
+ createdResponse('resp_error'),
{ type: 'error', code: 'rate_limit_exceeded', message: 'Rate limit reached', param: null },
]);
@@ -1620,7 +1072,7 @@ describe('OpenAIResponsesStream', () => {
it('reports usage and a length stop for response.incomplete', async () => {
const { completion } = await collect([
- { type: 'response.created', response: { id: 'resp_incomplete', status: 'in_progress' } },
+ createdResponse('resp_incomplete'),
{
type: 'response.incomplete',
response: {
diff --git a/packages/model-runtime/src/core/streams/vertex-ai.test.ts b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
index 28905f870b9..cfde338fdeb 100644
--- a/packages/model-runtime/src/core/streams/vertex-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
@@ -2,6 +2,25 @@ import { describe, expect, it, vi } from 'vitest';
import * as uuidModule from '../../utils/uuid';
import { GoogleGenerativeAIStream } from './google';
+import { createReadableStream } from './utils';
+
+const createTextCandidate = () => ({
+ content: { parts: [{ text: '234' }], role: 'model' },
+ safetyRatings: [
+ { category: 'HARM_CATEGORY_HATE_SPEECH', probability: 'NEGLIGIBLE' },
+ { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', probability: 'NEGLIGIBLE' },
+ { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
+ { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', probability: 'NEGLIGIBLE' },
+ ],
+});
+
+const createTextUsageMetadata = () => ({
+ promptTokenCount: 20,
+ candidatesTokenCount: 3,
+ totalTokenCount: 23,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 20 }],
+ candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
+});
describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
it('should transform Vertex AI stream to protocol stream', async () => {
@@ -88,13 +107,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- rawChunks.forEach((chunk) => controller.enqueue(chunk));
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(rawChunks);
const onStartMock = vi.fn();
const onTextMock = vi.fn();
@@ -197,13 +210,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- rawChunks.forEach((chunk) => controller.enqueue(chunk));
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(rawChunks);
const onStartMock = vi.fn();
const onTextMock = vi.fn();
@@ -250,17 +257,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
const data = [
{
- candidates: [
- {
- content: { parts: [{ text: '234' }], role: 'model' },
- safetyRatings: [
- { category: 'HARM_CATEGORY_HATE_SPEECH', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', probability: 'NEGLIGIBLE' },
- ],
- },
- ],
+ candidates: [createTextCandidate()],
text: () => '234',
usageMetadata: {
promptTokenCount: 20,
@@ -294,15 +291,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -340,47 +329,17 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
const data = [
{
- candidates: [
- {
- content: { parts: [{ text: '234' }], role: 'model' },
- safetyRatings: [
- { category: 'HARM_CATEGORY_HATE_SPEECH', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', probability: 'NEGLIGIBLE' },
- ],
- },
- ],
- usageMetadata: {
- promptTokenCount: 20,
- candidatesTokenCount: 3,
- totalTokenCount: 23,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 20 }],
- candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
- },
+ candidates: [createTextCandidate()],
+ usageMetadata: createTextUsageMetadata(),
modelVersion: 'gemini-2.5-flash-preview-04-17',
},
{
- usageMetadata: {
- promptTokenCount: 20,
- candidatesTokenCount: 3,
- totalTokenCount: 23,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 20 }],
- candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
- },
+ usageMetadata: createTextUsageMetadata(),
modelVersion: 'gemini-2.5-flash-preview-04-17',
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -458,12 +417,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockStream);
const decoder = new TextDecoder();
@@ -563,12 +517,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockStream);
const decoder = new TextDecoder();
@@ -636,12 +585,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => controller.enqueue(item));
- controller.close();
- },
- });
+ const mockStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockStream);
const decoder = new TextDecoder();
@@ -678,48 +622,18 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
const data = [
{
- candidates: [
- {
- content: { parts: [{ text: '234' }], role: 'model' },
- safetyRatings: [
- { category: 'HARM_CATEGORY_HATE_SPEECH', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
- { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', probability: 'NEGLIGIBLE' },
- ],
- },
- ],
- usageMetadata: {
- promptTokenCount: 20,
- candidatesTokenCount: 3,
- totalTokenCount: 23,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 20 }],
- candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
- },
+ candidates: [createTextCandidate()],
+ usageMetadata: createTextUsageMetadata(),
modelVersion: 'gemini-2.5-flash-preview-04-17',
},
{
candidates: [{}],
- usageMetadata: {
- promptTokenCount: 20,
- candidatesTokenCount: 3,
- totalTokenCount: 23,
- promptTokensDetails: [{ modality: 'TEXT', tokenCount: 20 }],
- candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
- },
+ usageMetadata: createTextUsageMetadata(),
modelVersion: 'gemini-2.5-flash-preview-04-17',
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- data.forEach((item) => {
- controller.enqueue(item);
- });
-
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(data);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -794,12 +708,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- rawChunks.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(rawChunks);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -889,12 +798,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- rawChunks.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(rawChunks);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
@@ -974,12 +878,7 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
},
];
- const mockGoogleStream = new ReadableStream({
- start(controller) {
- rawChunks.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
- });
+ const mockGoogleStream = createReadableStream(rawChunks);
const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index c85b5ed1cbb..80580dcaa1c 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -12,6 +12,25 @@ import { describe, expect, it } from 'vitest';
import { computeChatCost } from './computeChatCost';
+const createCachedAudioPricing = (): Pricing => ({
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ {
+ name: 'textInput_cacheRead',
+ rate: 0.1,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
+ {
+ name: 'audioInput_cacheRead',
+ rate: 1,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+});
+
describe('computeChatPricing', () => {
describe('OpenAI', () => {
it('handles simple request without cache for gpt-4.1', () => {
@@ -495,24 +514,7 @@ describe('computeChatPricing', () => {
});
it('does not produce a cost when aggregate cache usage omits the cached audio split', () => {
- const pricing: Pricing = {
- units: [
- { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'textInput_cacheRead',
- rate: 0.1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'audioInput_cacheRead',
- rate: 1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createCachedAudioPricing();
const usage: ModelTokensUsage = {
inputAudioTokens: 80,
inputCachedTokens: 40,
@@ -528,24 +530,7 @@ describe('computeChatPricing', () => {
});
it('continues when the provider explicitly reports zero audio tokens', () => {
- const pricing: Pricing = {
- units: [
- { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'textInput_cacheRead',
- rate: 0.1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'audioInput_cacheRead',
- rate: 1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createCachedAudioPricing();
const usage: ModelTokensUsage = {
inputAudioTokens: 0,
inputCachedTokens: 40,
@@ -566,24 +551,7 @@ describe('computeChatPricing', () => {
});
it('continues when the provider explicitly reports zero cached audio tokens', () => {
- const pricing: Pricing = {
- units: [
- { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'textInput_cacheRead',
- rate: 0.1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
- {
- name: 'audioInput_cacheRead',
- rate: 1,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createCachedAudioPricing();
const usage: ModelTokensUsage = {
inputAudioTokens: 20,
inputCachedAudioTokens: 0,
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
index fefff846399..fa34386289c 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.test.ts
@@ -4,6 +4,22 @@ import { describe, expect, it } from 'vitest';
import type { ImageGenerationParams } from './computeImageCost';
import { computeImageCost } from './computeImageCost';
+const createLookupPricing = (): Pricing => ({
+ units: [
+ {
+ name: 'imageGeneration',
+ strategy: 'lookup',
+ unit: 'image',
+ lookup: {
+ pricingParams: ['quality', 'size'],
+ prices: {
+ standard_1024x1024: 0.04,
+ },
+ },
+ },
+ ],
+});
+
describe('computeImageCost', () => {
describe('lookup pricing strategy', () => {
it('should compute dall-e-3 lookup pricing correctly', () => {
@@ -79,21 +95,7 @@ describe('computeImageCost', () => {
});
it('should return undefined if required lookup param is missing', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'imageGeneration',
- strategy: 'lookup',
- unit: 'image',
- lookup: {
- pricingParams: ['quality', 'size'],
- prices: {
- standard_1024x1024: 0.04,
- },
- },
- },
- ],
- };
+ const pricing: Pricing = createLookupPricing();
const params: ImageGenerationParams = {
quality: 'standard',
@@ -106,21 +108,7 @@ describe('computeImageCost', () => {
});
it('should return undefined if lookup key has no matching price', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'imageGeneration',
- strategy: 'lookup',
- unit: 'image',
- lookup: {
- pricingParams: ['quality', 'size'],
- prices: {
- standard_1024x1024: 0.04,
- },
- },
- },
- ],
- };
+ const pricing: Pricing = createLookupPricing();
const params: ImageGenerationParams = {
quality: 'hd',
@@ -295,21 +283,7 @@ describe('computeImageCost', () => {
});
it('should handle null lookup param value', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'imageGeneration',
- strategy: 'lookup',
- unit: 'image',
- lookup: {
- pricingParams: ['quality', 'size'],
- prices: {
- standard_1024x1024: 0.04,
- },
- },
- },
- ],
- };
+ const pricing: Pricing = createLookupPricing();
const params: ImageGenerationParams = {
quality: null as any, // null value for testing
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts
index 639241c2bfa..e2e49a3d1e4 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts
@@ -4,19 +4,35 @@ import { describe, expect, it } from 'vitest';
import type { VideoGenerationParams } from './computeVideoCost';
import { computeVideoCost, computeVideoRequestCost } from './computeVideoCost';
+const createAudioLookupPricing = (): Pricing => ({
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: { true: 0.42 },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+});
+
+const createFixedTokenPricing = (): Pricing => ({
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+});
+
describe('computeVideoCost', () => {
describe('fixed pricing strategy', () => {
it('should compute cost with millionTokens unit', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'videoGeneration',
- rate: 0.21,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createFixedTokenPricing();
const result = computeVideoCost(pricing, 500_000, {});
@@ -45,16 +61,7 @@ describe('computeVideoCost', () => {
});
it('should handle zero tokens', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'videoGeneration',
- rate: 0.21,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createFixedTokenPricing();
const result = computeVideoCost(pricing, 0, {});
@@ -93,19 +100,7 @@ describe('computeVideoCost', () => {
});
it('should return undefined when lookup param is missing', () => {
- const pricing: Pricing = {
- units: [
- {
- lookup: {
- pricingParams: ['generateAudio'],
- prices: { true: 0.42 },
- },
- name: 'videoGeneration',
- strategy: 'lookup',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createAudioLookupPricing();
// generateAudio is undefined
const result = computeVideoCost(pricing, 1_000_000, {});
@@ -114,19 +109,7 @@ describe('computeVideoCost', () => {
});
it('should return undefined when lookup key has no matching price', () => {
- const pricing: Pricing = {
- units: [
- {
- lookup: {
- pricingParams: ['generateAudio'],
- prices: { true: 0.42 },
- },
- name: 'videoGeneration',
- strategy: 'lookup',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createAudioLookupPricing();
const params: VideoGenerationParams = { generateAudio: false };
const result = computeVideoCost(pricing, 1_000_000, params);
@@ -155,19 +138,7 @@ describe('computeVideoCost', () => {
});
it('should return undefined when param value is null', () => {
- const pricing: Pricing = {
- units: [
- {
- lookup: {
- pricingParams: ['generateAudio'],
- prices: { true: 0.42 },
- },
- name: 'videoGeneration',
- strategy: 'lookup',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createAudioLookupPricing();
const params: VideoGenerationParams = { generateAudio: null as any };
const result = computeVideoCost(pricing, 1_000_000, params);
@@ -216,16 +187,7 @@ describe('computeVideoCost', () => {
});
it('should default to USD when currency is not specified', () => {
- const pricing: Pricing = {
- units: [
- {
- name: 'videoGeneration',
- rate: 0.21,
- strategy: 'fixed',
- unit: 'millionTokens',
- },
- ],
- };
+ const pricing: Pricing = createFixedTokenPricing();
const result = computeVideoCost(pricing, 1_000_000, {});
diff --git a/packages/model-runtime/src/providers/ai360/index.test.ts b/packages/model-runtime/src/providers/ai360/index.test.ts
index db712e2d6e4..88a0f6326db 100644
--- a/packages/model-runtime/src/providers/ai360/index.test.ts
+++ b/packages/model-runtime/src/providers/ai360/index.test.ts
@@ -1,8 +1,19 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Ai360ModelCard } from './index';
import { LobeAi360AI, params } from './index';
+const createModel = (id: string, maxTokens: number, totalTokens: number): Ai360ModelCard => ({
+ id,
+ max_tokens: maxTokens,
+ total_tokens: totalTokens,
+});
+
+const createModelsClient = (data: Ai360ModelCard[]) => ({
+ models: { list: vi.fn().mockResolvedValue({ data }) },
+});
+
describe('LobeAi360AI - custom features', () => {
let instance: InstanceType<typeof LobeAi360AI>;
@@ -195,24 +206,10 @@ describe('LobeAi360AI - custom features', () => {
describe('params.models', () => {
it('should fetch and process models successfully', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- {
- id: '360gpt2-o1',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([
+ createModel('360gpt-pro', 4096, 8192),
+ createModel('360gpt2-o1', 8192, 16384),
+ ]);
const models = await params.models!({ client: mockClient as any });
@@ -221,19 +218,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should correctly map model properties', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -244,19 +229,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should detect 360gpt-pro as function call capable', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -264,19 +237,7 @@ describe('LobeAi360AI - custom features', () => {
expect(model.functionCall).toBe(true);
});
it('should handle case-insensitive reasoning keyword matching', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360GPT2-O1',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360GPT2-O1', 8192, 16384)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -285,19 +246,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should merge with LOBE_DEFAULT_MODEL_LIST for known models', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -308,19 +257,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle models not in LOBE_DEFAULT_MODEL_LIST', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'unknown-model',
- max_tokens: 2048,
- total_tokens: 4096,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('unknown-model', 2048, 4096)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -331,19 +268,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should inherit abilities from LOBE_DEFAULT_MODEL_LIST', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -354,19 +279,7 @@ describe('LobeAi360AI - custom features', () => {
expect(typeof model.reasoning).toBe('boolean');
});
it('should handle models with null max_tokens', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'test-model',
- max_tokens: null as any,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('test-model', null as any, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -375,13 +288,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle empty model list', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [],
- }),
- },
- };
+ const mockClient = createModelsClient([]);
const models = await params.models!({ client: mockClient as any });
@@ -389,24 +296,10 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle model list with valid models only', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'model1',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- {
- id: 'model2',
- max_tokens: 2048,
- total_tokens: 4096,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([
+ createModel('model1', 4096, 8192),
+ createModel('model2', 2048, 4096),
+ ]);
const models = await params.models!({ client: mockClient as any });
@@ -425,19 +318,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should set reasoning to false for non-reasoning models', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-base',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-base', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -446,19 +327,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should set functionCall to false for non-360gpt-pro models without functionCall ability', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'test-model',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('test-model', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -467,19 +336,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should set vision to false for models without vision ability', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'test-model',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('test-model', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -488,19 +345,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle case-insensitive model ID matching with LOBE_DEFAULT_MODEL_LIST', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360GPT-PRO',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360GPT-PRO', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -511,19 +356,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle models with all properties present', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -538,34 +371,12 @@ describe('LobeAi360AI - custom features', () => {
});
it('should detect all reasoning model variants correctly', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt2-o1',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- {
- id: '360gpt2-o1-preview',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- {
- id: '360zhinao2-o1',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- {
- id: '360zhinao2-o1-mini',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([
+ createModel('360gpt2-o1', 8192, 16384),
+ createModel('360gpt2-o1-preview', 8192, 16384),
+ createModel('360zhinao2-o1', 8192, 16384),
+ createModel('360zhinao2-o1-mini', 8192, 16384),
+ ]);
const models = await params.models!({ client: mockClient as any });
@@ -574,19 +385,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should handle models with zero context window', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: 'test-model',
- max_tokens: 0,
- total_tokens: 0,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('test-model', 0, 0)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -595,19 +394,7 @@ describe('LobeAi360AI - custom features', () => {
expect(model.maxOutput).toBe(0);
});
it('should handle models with special characters in ID', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt-pro-v2.0-beta',
- max_tokens: 4096,
- total_tokens: 8192,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt-pro-v2.0-beta', 4096, 8192)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -615,19 +402,7 @@ describe('LobeAi360AI - custom features', () => {
expect(model.id).toBe('360gpt-pro-v2.0-beta');
});
it('should prioritize reasoning from keyword over knownModel', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt2-o1-custom',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt2-o1-custom', 8192, 16384)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
@@ -637,19 +412,7 @@ describe('LobeAi360AI - custom features', () => {
});
it('should merge multiple capabilities correctly', async () => {
- const mockClient = {
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- id: '360gpt2-o1',
- max_tokens: 8192,
- total_tokens: 16384,
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient([createModel('360gpt2-o1', 8192, 16384)]);
const models = await params.models!({ client: mockClient as any });
const model = models[0];
diff --git a/packages/model-runtime/src/providers/anthropic/index.test.ts b/packages/model-runtime/src/providers/anthropic/index.test.ts
index 0cc37453a00..1889a5c2070 100644
--- a/packages/model-runtime/src/providers/anthropic/index.test.ts
+++ b/packages/model-runtime/src/providers/anthropic/index.test.ts
@@ -8,6 +8,14 @@ import type { ChatCompletionTool, ChatStreamPayload } from '../../types/chat';
import * as debugStreamModule from '../../utils/debugStream';
import { LobeAnthropicAI } from './index';
+const createHelloStream = () =>
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue('Hello, world!');
+ controller.close();
+ },
+ });
+
const provider = 'anthropic';
const bizErrorType = 'ProviderBizError';
@@ -70,12 +78,7 @@ describe('LobeAnthropicAI', () => {
it('should handle text messages correctly', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createHelloStream();
const mockResponse = Promise.resolve(mockStream);
(instance['client'].messages.create as Mock).mockResolvedValue(mockResponse);
@@ -132,12 +135,7 @@ describe('LobeAnthropicAI', () => {
it('should handle system prompt correctly', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createHelloStream();
const mockResponse = Promise.resolve(mockStream);
(instance['client'].messages.create as Mock).mockResolvedValue(mockResponse);
@@ -182,12 +180,7 @@ describe('LobeAnthropicAI', () => {
it('should call Anthropic API with supported opions in streaming mode', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createHelloStream();
const mockResponse = Promise.resolve(mockStream);
(instance['client'].messages.create as Mock).mockResolvedValue(mockResponse);
@@ -222,12 +215,7 @@ describe('LobeAnthropicAI', () => {
it('should call Anthropic API without unsupported opions', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createHelloStream();
const mockResponse = Promise.resolve(mockStream);
(instance['client'].messages.create as Mock).mockResolvedValue(mockResponse);
@@ -264,12 +252,7 @@ describe('LobeAnthropicAI', () => {
it('should call debugStream in DEBUG mode', async () => {
// Arrange
- const mockProdStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- }) as any;
+ const mockProdStream = createHelloStream() as any;
const mockDebugStream = new ReadableStream({
start(controller) {
controller.enqueue('Debug stream content');
diff --git a/packages/model-runtime/src/providers/baichuan/index.test.ts b/packages/model-runtime/src/providers/baichuan/index.test.ts
index 3aaef85e1e5..63a96815227 100644
--- a/packages/model-runtime/src/providers/baichuan/index.test.ts
+++ b/packages/model-runtime/src/providers/baichuan/index.test.ts
@@ -7,6 +7,14 @@ import type { LobeOpenAICompatibleRuntime } from '../../core/BaseAI';
import { testProvider } from '../../providerTestUtils';
import { LobeBaichuanAI, params } from './index';
+const createTurboModel = () => ({
+ function_call: true,
+ max_input_length: 32768,
+ max_tokens: 4096,
+ model: 'Baichuan3-Turbo',
+ model_show_name: 'Baichuan3-Turbo',
+});
+
testProvider({
Runtime: LobeBaichuanAI,
provider: ModelProvider.Baichuan,
@@ -273,13 +281,7 @@ describe('LobeBaichuanAI - custom features', () => {
it('should fetch and process models correctly', async () => {
mockClient.models.list.mockResolvedValue({
data: [
- {
- function_call: true,
- max_input_length: 32768,
- max_tokens: 4096,
- model: 'Baichuan3-Turbo',
- model_show_name: 'Baichuan3-Turbo',
- },
+ createTurboModel(),
{
function_call: false,
max_input_length: 4096,
@@ -362,15 +364,7 @@ describe('LobeBaichuanAI - custom features', () => {
it('should preserve abilities from known model list', async () => {
mockClient.models.list.mockResolvedValue({
- data: [
- {
- function_call: true,
- max_input_length: 32768,
- max_tokens: 4096,
- model: 'Baichuan3-Turbo',
- model_show_name: 'Baichuan3-Turbo',
- },
- ],
+ data: [createTurboModel()],
});
const models = await params.models({ client: mockClient as any });
@@ -448,17 +442,7 @@ describe('LobeBaichuanAI - custom features', () => {
it('should filter out null or undefined models', async () => {
mockClient.models.list.mockResolvedValue({
- data: [
- {
- function_call: true,
- max_input_length: 32768,
- max_tokens: 4096,
- model: 'Baichuan3-Turbo',
- model_show_name: 'Baichuan3-Turbo',
- },
- null,
- undefined,
- ],
+ data: [createTurboModel(), null, undefined],
});
const models = await params.models({ client: mockClient as any });
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index 1e7012bcccb..6b80d4ef3bb 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -7,6 +7,7 @@ import { ModelProvider } from 'model-bank';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createReadableStream } from '../../core/streams/utils';
import { AgentRuntimeErrorType } from '../../types/error';
import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
@@ -207,12 +208,7 @@ describe('LobeBedrockAI', () => {
it('should handle text messages correctly', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -252,12 +248,7 @@ describe('LobeBedrockAI', () => {
});
it('should drop assistant prefill for Claude Opus 4.7', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
await instance.chat({
@@ -281,12 +272,7 @@ describe('LobeBedrockAI', () => {
});
it('should drop ALL stacked trailing assistant messages', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
// Failed-run placeholder rows can stack several assistant turns at the
@@ -320,12 +306,7 @@ describe('LobeBedrockAI', () => {
modelIdMapping: { 'claude-sonnet-5': 'global.anthropic.claude-sonnet-5-5' },
region: 'us-west-2',
});
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(
Promise.resolve(mockStream) as any,
);
@@ -351,12 +332,7 @@ describe('LobeBedrockAI', () => {
modelIdMapping: { 'my-router-model': 'global.anthropic.claude-opus-5' },
region: 'us-west-2',
});
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(
Promise.resolve(mockStream) as any,
);
@@ -378,12 +354,7 @@ describe('LobeBedrockAI', () => {
});
it('should convert Claude assistant reasoning signatures to thinking content', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
await instance.chat({
@@ -421,12 +392,7 @@ describe('LobeBedrockAI', () => {
});
it('should not convert non-Claude reasoning signatures to thinking content', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
await instance.chat({
@@ -459,12 +425,7 @@ describe('LobeBedrockAI', () => {
it('should handle system prompt correctly', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -515,12 +476,7 @@ describe('LobeBedrockAI', () => {
it('should call Anthropic model with supported opions', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -562,12 +518,7 @@ describe('LobeBedrockAI', () => {
it('should handle tools parameter', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -607,12 +558,7 @@ describe('LobeBedrockAI', () => {
it('should use default max_tokens when not provided', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -650,12 +596,7 @@ describe('LobeBedrockAI', () => {
it('should call Anthropic model without unsupported opions', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -718,12 +659,7 @@ describe('LobeBedrockAI', () => {
describe('Parameter conflict handling for Claude 4+ models', () => {
it('should forward effort and visible thinking when Claude Opus 5 uses default adaptive thinking', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
await instance.chat({
@@ -761,12 +697,7 @@ describe('LobeBedrockAI', () => {
});
it('should forward disabled thinking without effort for Claude Opus 5', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
(instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));
await instance.chat({
@@ -801,223 +732,92 @@ describe('LobeBedrockAI', () => {
});
});
- it('should send only temperature for Claude 4+ models when both temperature and top_p are provided', async () => {
- // Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
- const mockResponse = Promise.resolve(mockStream);
- (instance['client'].send as Mock).mockResolvedValue(mockResponse);
-
- // Act
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'anthropic.claude-opus-4-1-20250805-v1:0',
- temperature: 0.8,
- top_p: 0.9,
- });
-
- // Assert
- expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
- accept: 'application/json',
- body: JSON.stringify({
- anthropic_version: 'bedrock-2023-05-31',
- max_tokens: 64_000,
- messages: [
- {
- content: [
- {
- cache_control: { type: 'ephemeral' },
- text: 'Hello',
- type: 'text',
- },
- ],
- role: 'user',
- },
- ],
- temperature: 0.4, // temperature / 2, top_p omitted due to conflict
- }),
- contentType: 'application/json',
- modelId: 'anthropic.claude-opus-4-1-20250805-v1:0',
- });
- });
-
- it('should send only top_p for Claude 4+ models when temperature is not provided', async () => {
- // Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
- const mockResponse = Promise.resolve(mockStream);
- (instance['client'].send as Mock).mockResolvedValue(mockResponse);
-
- // Act
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'anthropic.claude-sonnet-4-20250514-v1:0',
- top_p: 0.9,
- });
-
- // Assert
- expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
- accept: 'application/json',
- body: JSON.stringify({
- anthropic_version: 'bedrock-2023-05-31',
- max_tokens: 64_000,
- messages: [
- {
- content: [
- {
- cache_control: { type: 'ephemeral' },
- text: 'Hello',
- type: 'text',
- },
- ],
- role: 'user',
- },
- ],
- top_p: 0.9, // temperature omitted since not provided
- }),
- contentType: 'application/json',
- modelId: 'anthropic.claude-sonnet-4-20250514-v1:0',
- });
- });
-
- it('should send both temperature and top_p for non-Claude-4+ models', async () => {
- // Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
+ [
+ {
+ caseName:
+ 'should send only temperature for Claude 4+ models when both temperature and top_p are provided',
+ input: {
+ model: 'anthropic.claude-opus-4-1-20250805-v1:0',
+ temperature: 0.8,
+ top_p: 0.9,
},
- });
- const mockResponse = Promise.resolve(mockStream);
- (instance['client'].send as Mock).mockResolvedValue(mockResponse);
-
- // Act
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
- temperature: 0.8,
- top_p: 0.9,
- });
-
- // Assert
- expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
- accept: 'application/json',
- body: JSON.stringify({
- anthropic_version: 'bedrock-2023-05-31',
- max_tokens: 8192,
- messages: [
- {
- content: [
- {
- cache_control: { type: 'ephemeral' },
- text: 'Hello',
- type: 'text',
- },
- ],
- role: 'user',
- },
- ],
- temperature: 0.4, // temperature / 2
- top_p: 0.9, // both parameters allowed for older models
- }),
- contentType: 'application/json',
- modelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
- });
- });
-
- it('should handle US region Claude 4+ model IDs correctly', async () => {
- // Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
+ expectedMaxTokens: 64_000,
+ expectedModel: 'anthropic.claude-opus-4-1-20250805-v1:0',
+ expectedSampling: { temperature: 0.4 },
+ },
+ {
+ caseName:
+ 'should send only top_p for Claude 4+ models when temperature is not provided',
+ input: { model: 'anthropic.claude-sonnet-4-20250514-v1:0', top_p: 0.9 },
+ expectedMaxTokens: 64_000,
+ expectedModel: 'anthropic.claude-sonnet-4-20250514-v1:0',
+ expectedSampling: { top_p: 0.9 },
+ },
+ {
+ caseName: 'should send both temperature and top_p for non-Claude-4+ models',
+ input: {
+ model: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
+ temperature: 0.8,
+ top_p: 0.9,
},
- });
- const mockResponse = Promise.resolve(mockStream);
- (instance['client'].send as Mock).mockResolvedValue(mockResponse);
-
- // Act
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
- temperature: 0.6,
- top_p: 0.8,
- });
-
- // Assert
- expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
- accept: 'application/json',
- body: JSON.stringify({
- anthropic_version: 'bedrock-2023-05-31',
- max_tokens: 64_000,
- messages: [
- {
- content: [
- {
- cache_control: { type: 'ephemeral' },
- text: 'Hello',
- type: 'text',
- },
- ],
- role: 'user',
- },
- ],
- temperature: 0.3, // temperature / 2, top_p omitted due to conflict
- }),
- contentType: 'application/json',
- modelId: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
- });
- });
-
- it('should handle standard Claude 4+ model IDs (non-Bedrock format)', async () => {
- // Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
+ expectedMaxTokens: 8192,
+ expectedModel: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
+ expectedSampling: { temperature: 0.4, top_p: 0.9 },
+ },
+ {
+ caseName: 'should handle US region Claude 4+ model IDs correctly',
+ input: {
+ model: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
+ temperature: 0.6,
+ top_p: 0.8,
},
- });
- const mockResponse = Promise.resolve(mockStream);
- (instance['client'].send as Mock).mockResolvedValue(mockResponse);
-
- // Act
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'claude-opus-4-1',
- temperature: 0.7,
- top_p: 0.95,
- });
-
- // Assert
- expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
- accept: 'application/json',
- body: JSON.stringify({
- anthropic_version: 'bedrock-2023-05-31',
- max_tokens: 64_000,
- messages: [
- {
- content: [
- {
- cache_control: { type: 'ephemeral' },
- text: 'Hello',
- type: 'text',
- },
- ],
- role: 'user',
- },
- ],
- temperature: 0.35, // temperature / 2, top_p omitted due to conflict
- }),
- contentType: 'application/json',
- modelId: 'claude-opus-4-1',
+ expectedMaxTokens: 64_000,
+ expectedModel: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
+ expectedSampling: { temperature: 0.3 },
+ },
+ {
+ caseName: 'should handle standard Claude 4+ model IDs (non-Bedrock format)',
+ input: { model: 'claude-opus-4-1', temperature: 0.7, top_p: 0.95 },
+ expectedMaxTokens: 64_000,
+ expectedModel: 'claude-opus-4-1',
+ expectedSampling: { temperature: 0.35 },
+ },
+ ].forEach(({ caseName, input, expectedMaxTokens, expectedModel, expectedSampling }) => {
+ it(caseName, async () => {
+ // Arrange
+ const mockStream = createReadableStream(['Hello, world!']);
+ const mockResponse = Promise.resolve(mockStream);
+ (instance['client'].send as Mock).mockResolvedValue(mockResponse);
+
+ // Act
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ ...input,
+ });
+
+ // Assert
+ expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
+ accept: 'application/json',
+ body: JSON.stringify({
+ anthropic_version: 'bedrock-2023-05-31',
+ max_tokens: expectedMaxTokens,
+ messages: [
+ {
+ content: [
+ {
+ cache_control: { type: 'ephemeral' },
+ text: 'Hello',
+ type: 'text',
+ },
+ ],
+ role: 'user',
+ },
+ ],
+ ...expectedSampling,
+ }),
+ contentType: 'application/json',
+ modelId: expectedModel,
+ });
});
});
@@ -1031,12 +831,7 @@ describe('LobeBedrockAI', () => {
'claude-opus-4-8': 'us.anthropic.claude-opus-4-8',
},
});
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(mockResponse as any);
@@ -1124,12 +919,7 @@ describe('LobeBedrockAI', () => {
it('should call Llama model with valid payload', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -1206,12 +996,7 @@ describe('LobeBedrockAI', () => {
it('should use default max_tokens (400) when not provided', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
@@ -1236,12 +1021,7 @@ describe('LobeBedrockAI', () => {
it('should handle system message in Llama prompt', async () => {
// Arrange
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Hello, world!');
- controller.close();
- },
- });
+ const mockStream = createReadableStream(['Hello, world!']);
const mockResponse = Promise.resolve(mockStream);
(instance['client'].send as Mock).mockResolvedValue(mockResponse);
diff --git a/packages/model-runtime/src/providers/bfl/createImage.test.ts b/packages/model-runtime/src/providers/bfl/createImage.test.ts
index 404d612a5cf..4ae4b83bd3d 100644
--- a/packages/model-runtime/src/providers/bfl/createImage.test.ts
+++ b/packages/model-runtime/src/providers/bfl/createImage.test.ts
@@ -31,6 +31,16 @@ const mockOptions = {
provider: 'bfl' as const,
};
+const createTaskSubmissionResponse = () =>
+ ({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ id: 'task-123',
+ polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
+ }),
+ }) as Response;
+
beforeEach(() => {
clearReferenceImageCache();
vi.clearAllMocks();
@@ -47,14 +57,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -101,14 +104,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -143,14 +139,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -202,14 +191,7 @@ describe('createBflImage', () => {
mimeType: 'image/jpeg',
});
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -257,14 +239,7 @@ describe('createBflImage', () => {
mimeType: 'image/jpeg',
});
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -305,14 +280,7 @@ describe('createBflImage', () => {
.mockResolvedValueOnce({ base64: 'base64image2', mimeType: 'image/jpeg' })
.mockResolvedValueOnce({ base64: 'base64image3', mimeType: 'image/jpeg' });
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -366,14 +334,7 @@ describe('createBflImage', () => {
.mockResolvedValueOnce({ base64: 'base64image3', mimeType: 'image/jpeg' })
.mockResolvedValueOnce({ base64: 'base64image4', mimeType: 'image/jpeg' });
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -422,14 +383,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValue({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValue(createTaskSubmissionResponse());
mockAsyncifyPolling.mockResolvedValue({
imageUrl: 'https://example.com/result.jpg',
@@ -527,14 +481,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
// Mock the asyncifyPolling to call checkStatus with Ready status
mockAsyncifyPolling.mockImplementation(async ({ checkStatus }) => {
@@ -573,14 +520,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockImplementation(async ({ checkStatus }) => {
const result = checkStatus({
@@ -615,14 +555,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
const errorStatuses = [
BflStatusResponse.Error,
@@ -665,14 +598,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockImplementation(async ({ checkStatus }) => {
const result = checkStatus({
@@ -706,14 +632,7 @@ describe('createBflImage', () => {
const { asyncifyPolling } = await import('../../utils/asyncifyPolling');
const mockAsyncifyPolling = vi.mocked(asyncifyPolling);
- mockFetch.mockResolvedValueOnce({
- ok: true,
- json: () =>
- Promise.resolve({
- id: 'task-123',
- polling_url: 'https://api.bfl.ai/v1/get_result?id=task-123',
- }),
- } as Response);
+ mockFetch.mockResolvedValueOnce(createTaskSubmissionResponse());
mockAsyncifyPolling.mockImplementation(async ({ checkStatus }) => {
// First call - Pending status
diff --git a/packages/model-runtime/src/providers/cloudflare/index.test.ts b/packages/model-runtime/src/providers/cloudflare/index.test.ts
index b9c5fbe1089..87dfc620f20 100644
--- a/packages/model-runtime/src/providers/cloudflare/index.test.ts
+++ b/packages/model-runtime/src/providers/cloudflare/index.test.ts
@@ -7,6 +7,14 @@ import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import { LobeCloudflareAI } from './index';
+const createTextStream = (textEncoder: TextEncoder) =>
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(textEncoder.encode('data: {"response": "Hello, world!"}\n\n'));
+ controller.close();
+ },
+ });
+
const provider = 'cloudflare';
const bizErrorType = 'ProviderBizError';
@@ -57,16 +65,7 @@ describe('LobeCloudflareAI', () => {
});
// Mock fetch
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(textEncoder.encode('data: {"response": "Hello, world!"}\n\n'));
- controller.close();
- },
- }),
- ),
- );
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(createTextStream(textEncoder)));
});
it('should return a Response on successful API call', async () => {
@@ -104,14 +103,7 @@ describe('LobeCloudflareAI', () => {
it('should handle text messages correctly', async () => {
// Arrange
const textEncoder = new TextEncoder();
- const mockResponse = new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(textEncoder.encode('data: {"response": "Hello, world!"}\n\n'));
- controller.close();
- },
- }),
- );
+ const mockResponse = new Response(createTextStream(textEncoder));
(globalThis.fetch as Mock).mockResolvedValue(mockResponse);
// Act
@@ -153,14 +145,7 @@ describe('LobeCloudflareAI', () => {
it('should handle system prompt correctly', async () => {
// Arrange
const textEncoder = new TextEncoder();
- const mockResponse = new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(textEncoder.encode('data: {"response": "Hello, world!"}\n\n'));
- controller.close();
- },
- }),
- );
+ const mockResponse = new Response(createTextStream(textEncoder));
(globalThis.fetch as Mock).mockResolvedValue(mockResponse);
// Act
@@ -205,14 +190,7 @@ describe('LobeCloudflareAI', () => {
it('should call Cloudflare API with supported options', async () => {
// Arrange
- const mockResponse = new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(textEncoder.encode('data: {"response": "Hello, world!"}\n\n'));
- controller.close();
- },
- }),
- );
+ const mockResponse = new Response(createTextStream(textEncoder));
(globalThis.fetch as Mock).mockResolvedValue(mockResponse);
// Act
diff --git a/packages/model-runtime/src/providers/cohere/index.test.ts b/packages/model-runtime/src/providers/cohere/index.test.ts
index 095d43da5e2..42f0621e74e 100644
--- a/packages/model-runtime/src/providers/cohere/index.test.ts
+++ b/packages/model-runtime/src/providers/cohere/index.test.ts
@@ -5,6 +5,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { LobeOpenAICompatibleRuntime } from '../../core/BaseAI';
import { LobeCohereAI, params } from './index';
+const createCommandRPlusModel = () => ({
+ name: 'command-r-plus',
+ context_length: 128000,
+ features: ['tools', 'chat'],
+ supports_vision: false,
+});
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -191,12 +198,7 @@ describe('LobeCohereAI - custom features', () => {
mockClient.models.list.mockResolvedValue({
body: {
models: [
- {
- name: 'command-r-plus',
- context_length: 128000,
- features: ['tools', 'chat'],
- supports_vision: false,
- },
+ createCommandRPlusModel(),
{
name: 'command-r',
context_length: 128000,
@@ -299,14 +301,7 @@ describe('LobeCohereAI - custom features', () => {
it('should merge with known model list for display name and enabled status', async () => {
mockClient.models.list.mockResolvedValue({
body: {
- models: [
- {
- name: 'command-r-plus',
- context_length: 128000,
- features: ['tools', 'chat'],
- supports_vision: false,
- },
- ],
+ models: [createCommandRPlusModel()],
},
});
@@ -370,14 +365,7 @@ describe('LobeCohereAI - custom features', () => {
it('should combine capabilities from both API and known model list', async () => {
mockClient.models.list.mockResolvedValue({
body: {
- models: [
- {
- name: 'command-r-plus',
- context_length: 128000,
- features: ['tools', 'chat'],
- supports_vision: false,
- },
- ],
+ models: [createCommandRPlusModel()],
},
});
diff --git a/packages/model-runtime/src/providers/cometapi/index.test.ts b/packages/model-runtime/src/providers/cometapi/index.test.ts
index f034dae4630..5ccf44e2db0 100644
--- a/packages/model-runtime/src/providers/cometapi/index.test.ts
+++ b/packages/model-runtime/src/providers/cometapi/index.test.ts
@@ -371,35 +371,5 @@ describe('LobeCometAPIAI - custom features', () => {
const models = await params.models!({ client: mockClient as any });
expect(models.length).toBe(4);
});
-
- it('should preserve object field in processed models', async () => {
- const mockClient = {
- apiKey: 'test',
- baseURL: 'https://api.cometapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [{ id: 'gpt-3.5-turbo', object: 'model', owned_by: 'openai' }],
- }),
- },
- };
-
- await params.models!({ client: mockClient as any });
- // The mapped model list should preserve the object field
- });
-
- it('should call processMultiProviderModelList with correct arguments', async () => {
- const mockClient = {
- apiKey: 'test',
- baseURL: 'https://api.cometapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [{ id: 'gpt-3.5-turbo', object: 'model', owned_by: 'openai' }],
- }),
- },
- };
-
- await params.models!({ client: mockClient as any });
- // processMultiProviderModelList should be called with modelList and 'cometapi'
- });
});
});
diff --git a/packages/model-runtime/src/providers/fal/index.test.ts b/packages/model-runtime/src/providers/fal/index.test.ts
index 5596939cc2e..3a39702dabd 100644
--- a/packages/model-runtime/src/providers/fal/index.test.ts
+++ b/packages/model-runtime/src/providers/fal/index.test.ts
@@ -21,6 +21,11 @@ const mockFal = vi.mocked(fal);
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
+const createImageResponse = (image: { url: string; width?: number; height?: number }) => ({
+ requestId: 'test-request-id',
+ data: { images: [image] },
+});
+
const provider = 'fal';
const bizErrorType = 'ProviderBizError';
const invalidErrorType = 'InvalidProviderAPIKey';
@@ -70,18 +75,11 @@ describe('LobeFalAI', () => {
describe('createImage', () => {
it('should create image successfully with basic parameters', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -143,18 +141,11 @@ describe('LobeFalAI', () => {
it('should map standard parameters to fal-specific parameters', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- width: 512,
- height: 512,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ width: 512,
+ height: 512,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -191,18 +182,11 @@ describe('LobeFalAI', () => {
it('should map imageUrls parameter to image_urls', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- width: 512,
- height: 512,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ width: 512,
+ height: 512,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -229,18 +213,11 @@ describe('LobeFalAI', () => {
it('should handle parameters without width and height', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -267,18 +244,11 @@ describe('LobeFalAI', () => {
it('should handle custom parameters that are not in the mapping', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- width: 768,
- height: 768,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ width: 768,
+ height: 768,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -311,16 +281,9 @@ describe('LobeFalAI', () => {
it('should return only imageUrl when width and height are not provided in response', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -403,16 +366,9 @@ describe('LobeFalAI', () => {
describe('Parameter filtering', () => {
it('should filter out null values', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -441,16 +397,9 @@ describe('LobeFalAI', () => {
it('should filter out undefined values', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -479,16 +428,9 @@ describe('LobeFalAI', () => {
it('should filter out empty arrays', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -518,18 +460,11 @@ describe('LobeFalAI', () => {
describe('Seedream and Hunyuan special endpoints', () => {
it('should use text-to-image endpoint when no imageUrls provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/generated.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/generated.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -563,18 +498,11 @@ describe('LobeFalAI', () => {
it('should use edit endpoint when imageUrls is provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/edited.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/edited.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -607,18 +535,11 @@ describe('LobeFalAI', () => {
it('should use edit endpoint when multiple imageUrls are provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/edited.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/edited.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -651,18 +572,11 @@ describe('LobeFalAI', () => {
it('should use text-to-image endpoint when imageUrls is empty array', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/generated.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/generated.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -697,16 +611,9 @@ describe('LobeFalAI', () => {
it('should handle seedream v4 with other parameters', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/edited.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/edited.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -737,18 +644,11 @@ describe('LobeFalAI', () => {
it('should use text-to-image endpoint for seedream v4.5 when no imageUrls provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/generated.jpg',
- width: 2048,
- height: 2048,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/generated.jpg',
+ width: 2048,
+ height: 2048,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -782,18 +682,11 @@ describe('LobeFalAI', () => {
it('should use edit endpoint for seedream v4.5 when imageUrls is provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/edited.jpg',
- width: 2048,
- height: 2048,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/edited.jpg',
+ width: 2048,
+ height: 2048,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -826,18 +719,11 @@ describe('LobeFalAI', () => {
it('should use text-to-image endpoint for hunyuan-image v3 when no imageUrls provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/generated.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/generated.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -868,18 +754,11 @@ describe('LobeFalAI', () => {
it('should use edit endpoint for hunyuan-image v3 when imageUrls is provided', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/edited.jpg',
- width: 1024,
- height: 1024,
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/edited.jpg',
+ width: 1024,
+ height: 1024,
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -913,10 +792,9 @@ describe('LobeFalAI', () => {
describe('Qwen Image 3 (alibaba namespace)', () => {
beforeEach(() => {
- mockFal.subscribe.mockResolvedValue({
- requestId: 'test-request-id',
- data: { images: [{ url: 'https://example.com/generated.jpg' }] },
- } as any);
+ mockFal.subscribe.mockResolvedValue(
+ createImageResponse({ url: 'https://example.com/generated.jpg' }) as any,
+ );
});
it('should keep the alibaba namespace and use text-to-image without imageUrls', async () => {
@@ -979,16 +857,9 @@ describe('LobeFalAI', () => {
describe('Edge cases', () => {
it('should handle empty params object', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -1016,16 +887,9 @@ describe('LobeFalAI', () => {
it('should handle model with different format', async () => {
// Arrange
- const mockImageResponse = {
- requestId: 'test-request-id',
- data: {
- images: [
- {
- url: 'https://example.com/image.jpg',
- },
- ],
- },
- };
+ const mockImageResponse = createImageResponse({
+ url: 'https://example.com/image.jpg',
+ });
mockFal.subscribe.mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
diff --git a/packages/model-runtime/src/providers/google/createImage.test.ts b/packages/model-runtime/src/providers/google/createImage.test.ts
index d41c992e1ce..268b5724501 100644
--- a/packages/model-runtime/src/providers/google/createImage.test.ts
+++ b/packages/model-runtime/src/providers/google/createImage.test.ts
@@ -1,10 +1,10 @@
// @vitest-environment node
import type { GoogleGenAI } from '@google/genai';
import { MediaModality } from '@google/genai';
-import * as imageToBase64Module from '../../utils/imageToBase64';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateImagePayload } from '../../types/image';
+import * as imageToBase64Module from '../../utils/imageToBase64';
import {
createGoogleImage,
GOOGLE_IMAGE_GENERATION_SYSTEM_PROMPT,
@@ -29,6 +29,28 @@ const expectGoogleImagePromptPart = (prompt: string) => ({
),
});
+const createImagenResponse = (imageBytes: string) => ({
+ generatedImages: [
+ {
+ image: { imageBytes },
+ },
+ ],
+});
+
+const createGeminiImageResponse = (data: string) => ({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: { data, mimeType: 'image/png' },
+ },
+ ],
+ },
+ },
+ ],
+});
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -55,15 +77,7 @@ describe('createGoogleImage', () => {
// Arrange - Use real base64 image data (5x5 red pixel PNG)
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockImageResponse = {
- generatedImages: [
- {
- image: {
- imageBytes: realBase64ImageData,
- },
- },
- ],
- };
+ const mockImageResponse = createImagenResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateImages').mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -95,15 +109,7 @@ describe('createGoogleImage', () => {
// Arrange - Use real base64 data
const realBase64Data =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
- const mockImageResponse = {
- generatedImages: [
- {
- image: {
- imageBytes: realBase64Data,
- },
- },
- ],
- };
+ const mockImageResponse = createImagenResponse(realBase64Data);
vi.spyOn(mockClient.models, 'generateImages').mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -132,15 +138,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64Data =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
- const mockImageResponse = {
- generatedImages: [
- {
- image: {
- imageBytes: realBase64Data,
- },
- },
- ],
- };
+ const mockImageResponse = createImagenResponse(realBase64Data);
vi.spyOn(mockClient.models, 'generateImages').mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -326,15 +324,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64Data =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
- const mockImageResponse = {
- generatedImages: [
- {
- image: {
- imageBytes: realBase64Data,
- },
- },
- ],
- };
+ const mockImageResponse = createImagenResponse(realBase64Data);
vi.spyOn(mockClient.models, 'generateImages').mockResolvedValue(mockImageResponse as any);
const payload: CreateImagePayload = {
@@ -366,22 +356,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -530,22 +505,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -581,22 +541,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -634,22 +579,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -688,22 +618,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -756,22 +671,7 @@ describe('createGoogleImage', () => {
// Arrange
const realBase64ImageData =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: realBase64ImageData,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(realBase64ImageData);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -804,22 +704,7 @@ describe('createGoogleImage', () => {
const outputImageBase64 =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: outputImageBase64,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(outputImageBase64);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -873,22 +758,7 @@ describe('createGoogleImage', () => {
mimeType: 'image/jpeg',
});
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: outputImageBase64,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(outputImageBase64);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
@@ -937,22 +807,7 @@ describe('createGoogleImage', () => {
const outputImageBase64 =
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
- const mockContentResponse = {
- candidates: [
- {
- content: {
- parts: [
- {
- inlineData: {
- data: outputImageBase64,
- mimeType: 'image/png',
- },
- },
- ],
- },
- },
- ],
- };
+ const mockContentResponse = createGeminiImageResponse(outputImageBase64);
vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
const payload: CreateImagePayload = {
diff --git a/packages/model-runtime/src/providers/google/generateObject.test.ts b/packages/model-runtime/src/providers/google/generateObject.test.ts
index 58f740acfdc..ea270d39f82 100644
--- a/packages/model-runtime/src/providers/google/generateObject.test.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.test.ts
@@ -9,6 +9,19 @@ import {
createGoogleGenerateObjectWithTools,
} from './generateObject';
+const createGoogleClient = (response: unknown) => ({
+ models: { generateContent: vi.fn().mockResolvedValue(response) },
+});
+
+const createEmptyTestTool = () => ({
+ function: {
+ description: 'Test function',
+ name: 'test_function',
+ parameters: { properties: {}, type: 'object' as const },
+ },
+ type: 'function' as const,
+});
+
describe('Google generateObject', () => {
describe('convertOpenAISchemaToGoogleSchema', () => {
it('should convert basic types correctly', () => {
@@ -535,13 +548,9 @@ describe('Google generateObject', () => {
describe('createGoogleGenerateObject', () => {
it('should return parsed JSON object on successful API call', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- text: '{"name": "John", "age": 30}',
- }),
- },
- };
+ const mockClient = createGoogleClient({
+ text: '{"name": "John", "age": 30}',
+ });
const contents = [{ parts: [{ text: 'Generate a person object' }], role: 'user' }];
@@ -579,13 +588,9 @@ describe('Google generateObject', () => {
});
it('should handle options correctly', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- text: '{"status": "success"}',
- }),
- },
- };
+ const mockClient = createGoogleClient({
+ text: '{"status": "success"}',
+ });
const contents = [{ parts: [{ text: 'Generate status' }], role: 'user' }];
@@ -626,18 +631,14 @@ describe('Google generateObject', () => {
});
it('should call onUsage callback with usage data', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- text: '{"result": "ok"}',
- usageMetadata: {
- candidatesTokenCount: 20,
- promptTokenCount: 80,
- totalTokenCount: 100,
- },
- }),
+ const mockClient = createGoogleClient({
+ text: '{"result": "ok"}',
+ usageMetadata: {
+ candidatesTokenCount: 20,
+ promptTokenCount: 80,
+ totalTokenCount: 100,
},
- };
+ });
const contents = [{ parts: [{ text: 'Generate data' }], role: 'user' }];
@@ -666,13 +667,9 @@ describe('Google generateObject', () => {
});
it('should return undefined when JSON parsing fails', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- text: 'invalid json string',
- }),
- },
- };
+ const mockClient = createGoogleClient({
+ text: 'invalid json string',
+ });
const contents: any[] = [];
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -698,13 +695,9 @@ describe('Google generateObject', () => {
});
it('should handle complex nested schemas', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- text: '{"user": {"name": "Alice", "profile": {"age": 25, "preferences": ["music", "sports"]}}, "metadata": {"created": "2024-01-01"}}',
- }),
- },
- };
+ const mockClient = createGoogleClient({
+ text: '{"user": {"name": "Alice", "profile": {"age": 25, "preferences": ["music", "sports"]}}, "metadata": {"created": "2024-01-01"}}',
+ });
const contents: any[] = [];
@@ -813,26 +806,22 @@ describe('Google generateObject', () => {
describe('createGoogleGenerateObjectWithTools', () => {
it('should return function calls on successful API call with tools', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- args: { city: 'New York', unit: 'celsius' },
- name: 'get_weather',
- },
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: { city: 'New York', unit: 'celsius' },
+ name: 'get_weather',
+ },
},
- },
- ],
- }),
- },
- };
+ ],
+ },
+ },
+ ],
+ });
const contents = [{ parts: [{ text: 'What is the weather in New York?' }], role: 'user' }];
@@ -897,31 +886,27 @@ describe('Google generateObject', () => {
});
it('should call onUsage callback with usage data', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- args: { city: 'Tokyo' },
- name: 'get_weather',
- },
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: { city: 'Tokyo' },
+ name: 'get_weather',
+ },
},
- },
- ],
- usageMetadata: {
- candidatesTokenCount: 30,
- promptTokenCount: 70,
- totalTokenCount: 100,
+ ],
},
- }),
+ },
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 30,
+ promptTokenCount: 70,
+ totalTokenCount: 100,
},
- };
+ });
const contents = [{ parts: [{ text: 'What is the weather in Tokyo?' }], role: 'user' }];
@@ -959,32 +944,28 @@ describe('Google generateObject', () => {
});
it('should handle multiple function calls', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- args: { city: 'New York', unit: 'celsius' },
- name: 'get_weather',
- },
- },
- {
- functionCall: {
- args: { timezone: 'America/New_York' },
- name: 'get_time',
- },
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: { city: 'New York', unit: 'celsius' },
+ name: 'get_weather',
+ },
},
- },
- ],
- }),
- },
- };
+ {
+ functionCall: {
+ args: { timezone: 'America/New_York' },
+ name: 'get_time',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ });
const contents: any[] = [];
@@ -1033,26 +1014,22 @@ describe('Google generateObject', () => {
});
it('should handle options correctly', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- args: { a: 5, b: 3, operation: 'add' },
- name: 'calculate',
- },
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: { a: 5, b: 3, operation: 'add' },
+ name: 'calculate',
+ },
},
- },
- ],
- }),
- },
- };
+ ],
+ },
+ },
+ ],
+ });
const contents: any[] = [];
@@ -1097,42 +1074,26 @@ describe('Google generateObject', () => {
});
it('should return undefined when no function calls in response', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- text: 'Some text response without function call',
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ text: 'Some text response without function call',
},
- },
- ],
- }),
- },
- };
+ ],
+ },
+ },
+ ],
+ });
const contents: any[] = [];
const payload = {
contents,
model: 'gemini-2.5-flash',
- tools: [
- {
- function: {
- description: 'Test function',
- name: 'test_function',
- parameters: {
- properties: {},
- type: 'object' as const,
- },
- },
- type: 'function' as const,
- },
- ],
+ tools: [createEmptyTestTool()],
};
const result = await createGoogleGenerateObjectWithTools(mockClient as any, payload);
@@ -1141,36 +1102,20 @@ describe('Google generateObject', () => {
});
it('should return undefined when no content parts in response', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {},
- },
- ],
- }),
- },
- };
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {},
+ },
+ ],
+ });
const contents: any[] = [];
const payload = {
contents,
model: 'gemini-2.5-flash',
- tools: [
- {
- function: {
- description: 'Test function',
- name: 'test_function',
- parameters: {
- properties: {},
- type: 'object' as const,
- },
- },
- type: 'function' as const,
- },
- ],
+ tools: [createEmptyTestTool()],
};
const result = await createGoogleGenerateObjectWithTools(mockClient as any, payload);
@@ -1192,19 +1137,7 @@ describe('Google generateObject', () => {
const payload = {
contents,
model: 'gemini-2.5-flash',
- tools: [
- {
- function: {
- description: 'Test function',
- name: 'test_function',
- parameters: {
- properties: {},
- type: 'object' as const,
- },
- },
- type: 'function' as const,
- },
- ],
+ tools: [createEmptyTestTool()],
};
await expect(createGoogleGenerateObjectWithTools(mockClient as any, payload)).rejects.toThrow(
@@ -1227,19 +1160,7 @@ describe('Google generateObject', () => {
const payload = {
contents,
model: 'gemini-2.5-flash',
- tools: [
- {
- function: {
- description: 'Test function',
- name: 'test_function',
- parameters: {
- properties: {},
- type: 'object' as const,
- },
- },
- type: 'function' as const,
- },
- ],
+ tools: [createEmptyTestTool()],
};
const options = {
@@ -1252,26 +1173,22 @@ describe('Google generateObject', () => {
});
it('should handle tools with empty parameters', async () => {
- const mockClient = {
- models: {
- generateContent: vi.fn().mockResolvedValue({
- candidates: [
- {
- content: {
- parts: [
- {
- functionCall: {
- args: {},
- name: 'simple_function',
- },
- },
- ],
+ const mockClient = createGoogleClient({
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ args: {},
+ name: 'simple_function',
+ },
},
- },
- ],
- }),
- },
- };
+ ],
+ },
+ },
+ ],
+ });
const contents: any[] = [];
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index 4e1818e3f92..1d437df997f 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -15,6 +15,25 @@ import {
import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import { LobeGoogleAI } from './index';
+const createTextStream = (modelVersion: string) =>
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ text: 'test',
+ candidates: [
+ {
+ content: { parts: [{ text: 'test' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
+ modelVersion,
+ });
+ controller.close();
+ },
+ });
+
const provider = 'google';
const defaultBaseURL = 'https://generativelanguage.googleapis.com';
const bizErrorType = 'ProviderBizError';
@@ -1122,23 +1141,7 @@ describe('sampling params compatibility', () => {
describe('buildGoogleToolsWithSearch', () => {
it('should include imageSearch searchTypes for models in modelsWithImageSearch when search is enabled', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.1-flash-image-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.1-flash-image-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1158,23 +1161,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should use plain googleSearch for non-imageSearch models when search is enabled', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-2.0-flash',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-2.0-flash');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1192,23 +1179,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should drop function declarations for image response models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-2.5-flash-image',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-2.5-flash-image');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1227,23 +1198,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should drop googleSearch for image response models without search support', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-2.5-flash-image',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-2.5-flash-image');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1262,23 +1217,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should only keep googleSearch for image response models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.1-flash-image-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.1-flash-image-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1301,23 +1240,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should combine search tools with function declarations for Gemini 3+ models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.1-pro-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.1-pro-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1354,23 +1277,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should combine search tools with function declarations for future Gemini 3.5 Pro models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.5-pro',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.5-pro');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1410,23 +1317,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should derive image-response payload for future Gemini image models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.5-pro-image-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.5-pro-image-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1494,23 +1385,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should keep image resolution in imageConfig when aspect ratio is auto', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.5-pro-image-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.5-pro-image-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1529,23 +1404,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should omit imageConfig when aspect ratio is auto and no resolution is set', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.5-pro-image-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.5-pro-image-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1563,23 +1422,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should not build imageConfig for non-image-response models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-2.0-flash',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-2.0-flash');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1600,23 +1443,7 @@ describe('buildGoogleToolsWithSearch', () => {
it('should not set includeServerSideToolInvocations for Vertex AI', async () => {
const vertexInstance = new LobeGoogleAI({ apiKey: 'test', isVertexAi: true });
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.1-pro-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.1-pro-preview');
vi.spyOn(vertexInstance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1636,23 +1463,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should not set toolConfig when Gemini 3+ has only search tools without function declarations', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-3.1-pro-preview',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-3.1-pro-preview');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
@@ -1671,23 +1482,7 @@ describe('buildGoogleToolsWithSearch', () => {
});
it('should exclude function declarations when search is enabled for pre-Gemini 3 models', async () => {
- const mockStream = new ReadableStream({
- start(controller) {
- controller.enqueue({
- text: 'test',
- candidates: [
- {
- content: { parts: [{ text: 'test' }], role: 'model' },
- finishReason: 'STOP',
- index: 0,
- },
- ],
- usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
- modelVersion: 'gemini-2.5-pro',
- });
- controller.close();
- },
- });
+ const mockStream = createTextStream('gemini-2.5-pro');
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
mockStream as any,
);
diff --git a/packages/model-runtime/src/providers/huggingface/index.test.ts b/packages/model-runtime/src/providers/huggingface/index.test.ts
index e859b63c49c..f3e6c9019fd 100644
--- a/packages/model-runtime/src/providers/huggingface/index.test.ts
+++ b/packages/model-runtime/src/providers/huggingface/index.test.ts
@@ -11,6 +11,14 @@ vi.mock('@lobechat/business-model-bank/model-config', () => ({
loadModels: loadModelsMock,
}));
+const createStreamClient = () => ({
+ chatCompletionStream: vi.fn().mockReturnValue({
+ async *[Symbol.asyncIterator]() {
+ yield { choices: [] } as any;
+ },
+ }),
+});
+
describe('LobeHuggingFaceAI', () => {
let instance: any;
@@ -141,13 +149,7 @@ describe('LobeHuggingFaceAI', () => {
describe('createChatCompletionStream', () => {
it('should call client.chatCompletionStream with correct parameters', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
+ const mockClient = createStreamClient() as any;
const mockInstance = {
baseURL: 'https://api.example.com',
@@ -175,13 +177,7 @@ describe('LobeHuggingFaceAI', () => {
});
it('should handle undefined baseURL', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
+ const mockClient = createStreamClient() as any;
const mockInstance = {
baseURL: undefined,
@@ -201,157 +197,29 @@ describe('LobeHuggingFaceAI', () => {
);
});
- it('should clamp top_p to 0.99 when >= 1', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
-
- const mockInstance = { baseURL: 'https://api.example.com' };
-
- const payload = {
- messages: [{ role: 'user', content: 'test' }],
- model: 'test-model',
- top_p: 1,
- };
-
- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
-
- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
- expect.objectContaining({
- top_p: 0.99,
- }),
- );
- });
-
- it('should clamp top_p to 0.99 when > 1', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
-
- const mockInstance = { baseURL: 'https://api.example.com' };
-
- const payload = {
- messages: [{ role: 'user', content: 'test' }],
- model: 'test-model',
- top_p: 1.5,
- };
-
- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
-
- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
- expect.objectContaining({
- top_p: 0.99,
- }),
- );
- });
-
- it('should set top_p to undefined when 0 (falsy value)', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
-
- const mockInstance = { baseURL: 'https://api.example.com' };
-
- const payload = {
- messages: [{ role: 'user', content: 'test' }],
- model: 'test-model',
- top_p: 0,
- };
-
- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
-
- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
- expect.objectContaining({
- top_p: undefined,
- }),
- );
- });
-
- it('should clamp top_p to 0.01 when < 0', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
-
- const mockInstance = { baseURL: 'https://api.example.com' };
-
- const payload = {
- messages: [{ role: 'user', content: 'test' }],
- model: 'test-model',
- top_p: -0.5,
- };
-
- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
-
- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
- expect.objectContaining({
- top_p: 0.01,
- }),
- );
- });
-
- it('should keep top_p unchanged when in valid range', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
-
- const mockInstance = { baseURL: 'https://api.example.com' };
-
- const payload = {
- messages: [{ role: 'user', content: 'test' }],
- model: 'test-model',
- top_p: 0.5,
- };
-
- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
-
- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
- expect.objectContaining({
- top_p: 0.5,
- }),
- );
- });
-
- it('should set top_p to undefined when not provided', () => {
- const mockClient = {
- chatCompletionStream: vi.fn().mockReturnValue({
- async *[Symbol.asyncIterator]() {
- yield { choices: [] } as any;
- },
- }),
- } as any;
+ it.each([
+ ['should clamp top_p to 0.99 when >= 1', { top_p: 1 }, 0.99],
+ ['should clamp top_p to 0.99 when > 1', { top_p: 1.5 }, 0.99],
+ ['should set top_p to undefined when 0 (falsy value)', { top_p: 0 }, undefined],
+ ['should clamp top_p to 0.01 when < 0', { top_p: -0.5 }, 0.01],
+ ['should keep top_p unchanged when in valid range', { top_p: 0.5 }, 0.5],
+ ['should set top_p to undefined when not provided', {}, undefined],
+ ] as const)('%s', (_name, topPInput, expected) => {
+ const mockClient = createStreamClient() as any;
const mockInstance = { baseURL: 'https://api.example.com' };
const payload = {
messages: [{ role: 'user', content: 'test' }],
model: 'test-model',
+ ...topPInput,
};
params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);
expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(
expect.objectContaining({
- top_p: undefined,
+ top_p: expected,
}),
);
});
diff --git a/packages/model-runtime/src/providers/hunyuan/createImage.test.ts b/packages/model-runtime/src/providers/hunyuan/createImage.test.ts
index 301eb2f127e..b3faafb79b5 100644
--- a/packages/model-runtime/src/providers/hunyuan/createImage.test.ts
+++ b/packages/model-runtime/src/providers/hunyuan/createImage.test.ts
@@ -5,6 +5,14 @@ import type { CreateImageOptions } from '../../core/openaiCompatibleFactory';
import type { CreateImagePayload } from '../../types/image';
import { createHunyuanImage } from './createImage';
+const createCompletedImageResponse = (imageUrl: string) => ({
+ ok: true,
+ json: async () => ({
+ status: 'completed',
+ data: [{ url: imageUrl }],
+ }),
+});
+
vi.spyOn(console, 'error').mockImplementation(() => {});
const mockOptions: CreateImageOptions = {
@@ -123,13 +131,7 @@ describe('createHunyuanImage', () => {
ok: true,
json: async () => ({ id: mockJobId }),
})
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- status: 'completed',
- data: [{ url: mockImageUrl }],
- }),
- });
+ .mockResolvedValueOnce(createCompletedImageResponse(mockImageUrl));
const payload: CreateImagePayload = {
model: 'HY-Image-V3.0',
@@ -158,13 +160,7 @@ describe('createHunyuanImage', () => {
ok: true,
json: async () => ({ id: mockJobId }),
})
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- status: 'completed',
- data: [{ url: mockImageUrl }],
- }),
- });
+ .mockResolvedValueOnce(createCompletedImageResponse(mockImageUrl));
const payload: CreateImagePayload = {
model: 'HY-Image-V3.0',
@@ -194,13 +190,7 @@ describe('createHunyuanImage', () => {
ok: true,
json: async () => ({ id: mockJobId }),
})
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- status: 'completed',
- data: [{ url: mockImageUrl }],
- }),
- });
+ .mockResolvedValueOnce(createCompletedImageResponse(mockImageUrl));
const payload: CreateImagePayload = {
model: 'HY-Image-V3.0',
@@ -228,13 +218,7 @@ describe('createHunyuanImage', () => {
ok: true,
json: async () => ({ id: mockJobId }),
})
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- status: 'completed',
- data: [{ url: mockImageUrl }],
- }),
- });
+ .mockResolvedValueOnce(createCompletedImageResponse(mockImageUrl));
const payload: CreateImagePayload = {
model: 'HY-Image-V3.0',
@@ -271,13 +255,7 @@ describe('createHunyuanImage', () => {
ok: true,
json: async () => ({ status: 'processing' }),
})
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- status: 'completed',
- data: [{ url: mockImageUrl }],
- }),
- });
+ .mockResolvedValueOnce(createCompletedImageResponse(mockImageUrl));
const payload: CreateImagePayload = {
model: 'HY-Image-V3.0',
diff --git a/packages/model-runtime/src/providers/newapi/index.test.ts b/packages/model-runtime/src/providers/newapi/index.test.ts
index 7be4b53c663..25137e4d84f 100644
--- a/packages/model-runtime/src/providers/newapi/index.test.ts
+++ b/packages/model-runtime/src/providers/newapi/index.test.ts
@@ -189,27 +189,29 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
describe('Models Function - Integration Testing', () => {
+ const createModelsClient = (id = 'test-model') => ({
+ apiKey: 'test-key',
+ baseURL: 'https://api.newapi.com/v1',
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ created: 123,
+ id,
+ object: 'model',
+ owned_by: 'openai',
+ },
+ ],
+ }),
+ },
+ });
+
beforeEach(() => {
mockProcessMultiProviderModelList.mockReturnValue([]);
});
it('should fetch models and process with processMultiProviderModelList', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
ok: false,
@@ -237,22 +239,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle successful pricing fetch and enrich models', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -300,22 +287,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle pricing fetch with model_ratio instead of model_price', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -355,22 +327,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should skip pricing for quota_type = 1 (pay-per-call)', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -397,22 +354,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle pricing fetch failure gracefully', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
ok: false,
@@ -426,22 +368,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle pricing fetch network error gracefully', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockRejectedValue(new Error('Network error'));
@@ -460,22 +387,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
global.document = {} as any;
try {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -513,22 +425,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
global.document = {} as any;
try {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'custom-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient('custom-model');
mockFetch.mockResolvedValue({
json: async () => ({
@@ -562,22 +459,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle pricing data with success=false', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -595,22 +477,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle pricing data with missing data field', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'test-model',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient();
mockFetch.mockResolvedValue({
json: async () => ({
@@ -628,15 +495,8 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle empty model list', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [],
- }),
- },
- };
+ const mockClient = createModelsClient();
+ mockClient.models.list.mockResolvedValue({ data: [] });
mockFetch.mockResolvedValue({
ok: false,
@@ -650,15 +510,8 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should handle undefined model data', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: undefined,
- }),
- },
- };
+ const mockClient = createModelsClient();
+ mockClient.models.list.mockResolvedValue({ data: undefined });
mockFetch.mockResolvedValue({
ok: false,
@@ -682,13 +535,9 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
];
for (const testCase of testCases) {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: testCase.input,
- models: {
- list: vi.fn().mockResolvedValue({ data: [] }),
- },
- };
+ const mockClient = createModelsClient();
+ mockClient.baseURL = testCase.input;
+ mockClient.models.list.mockResolvedValue({ data: [] });
mockFetch.mockResolvedValue({ ok: false });
mockProcessMultiProviderModelList.mockReturnValue([]);
@@ -705,22 +554,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should add models from pricing list that are not in models list', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'model-a',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient('model-a');
mockFetch.mockResolvedValue({
json: async () => ({
@@ -778,22 +612,7 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should not duplicate models that exist in both lists', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [
- {
- created: 123,
- id: 'model-a',
- object: 'model',
- owned_by: 'openai',
- },
- ],
- }),
- },
- };
+ const mockClient = createModelsClient('model-a');
mockFetch.mockResolvedValue({
json: async () => ({
@@ -822,15 +641,8 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
});
it('should verify that additionalModels get processed with displayName and type through processMultiProviderModelList', async () => {
- const mockClient = {
- apiKey: 'test-key',
- baseURL: 'https://api.newapi.com/v1',
- models: {
- list: vi.fn().mockResolvedValue({
- data: [],
- }),
- },
- };
+ const mockClient = createModelsClient();
+ mockClient.models.list.mockResolvedValue({ data: [] });
mockFetch.mockResolvedValue({
json: async () => ({
diff --git a/packages/model-runtime/src/providers/openrouter/index.test.ts b/packages/model-runtime/src/providers/openrouter/index.test.ts
index 5e111cce762..644d7e791c3 100644
--- a/packages/model-runtime/src/providers/openrouter/index.test.ts
+++ b/packages/model-runtime/src/providers/openrouter/index.test.ts
@@ -29,6 +29,15 @@ afterEach(() => {
vi.clearAllMocks();
});
+const stubModelsResponse = (models: unknown[]) =>
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: models }),
+ }),
+ );
+
describe('LobeOpenRouterAI - custom features', () => {
describe('Debug Configuration', () => {
it('should disable debug by default', () => {
@@ -464,13 +473,7 @@ describe('LobeOpenRouterAI - custom features', () => {
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- } as any),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
const gpt55 = models.find((m) => m.id === 'openai/gpt-5.5');
@@ -512,13 +515,7 @@ describe('LobeOpenRouterAI - custom features', () => {
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- } as any),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
const geminiPro = models.find((m) => m.id === 'google/gemini-3-pro');
@@ -540,38 +537,21 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'openai/gpt-4',
- canonical_slug: 'openai/gpt-4',
name: 'OpenAI: GPT-4',
created: 1679587200,
description: 'GPT-4 model',
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'gpt-4',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00003',
completion: '0.00006',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: ['tools', 'temperature'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -583,37 +563,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'anthropic/claude-3-opus',
- canonical_slug: 'anthropic/claude-3-opus',
name: 'Anthropic: Claude 3 Opus',
created: 1679587200,
context_length: 200000,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text', 'image'],
- output_modalities: ['text'],
- tokenizer: 'claude',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text', 'image'] },
pricing: {
prompt: '0.000015',
completion: '0.000075',
},
- top_provider: {
- context_length: 200000,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 200000, max_completion_tokens: 4096 },
supported_parameters: ['tools', 'reasoning'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -625,37 +588,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'deepseek/deepseek-chat',
- canonical_slug: 'deepseek/deepseek-chat',
name: 'DeepSeek: Chat',
created: 1679587200,
context_length: 32768,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'deepseek',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00000014',
completion: '0.00000028',
},
- top_provider: {
- context_length: 32768,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 32768, max_completion_tokens: 4096 },
supported_parameters: ['tools'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -667,37 +613,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'deepseek/deepseek-r1',
- canonical_slug: 'deepseek/deepseek-r1',
name: 'DeepSeek: DeepSeek R1',
created: 1679587200,
context_length: 64000,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'deepseek',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00000055',
completion: '0.0000022',
},
- top_provider: {
- context_length: 64000,
- max_completion_tokens: 8192,
- is_moderated: false,
- },
+ top_provider: { context_length: 64000, max_completion_tokens: 8192 },
supported_parameters: ['reasoning'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -709,37 +638,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'free/model',
- canonical_slug: 'free/model',
name: 'Provider: Free Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0',
completion: '0',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -751,37 +663,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'free/model',
- canonical_slug: 'free/model',
name: 'Provider: Free Model (free)',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0',
completion: '0',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -794,37 +689,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'vision/model',
- canonical_slug: 'vision/model',
name: 'Vision Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text+image->text',
- input_modalities: ['text', 'image'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text', 'image'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -836,37 +714,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'function/model',
- canonical_slug: 'function/model',
name: 'Function Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: ['tools', 'temperature'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -878,37 +739,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'reasoning/model',
- canonical_slug: 'reasoning/model',
name: 'Reasoning Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: ['reasoning', 'temperature'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -920,39 +764,22 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'pricing/model',
- canonical_slug: 'pricing/model',
name: 'Pricing Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
input_cache_read: '0.000001',
input_cache_write: '0.0000015',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -985,37 +812,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'no-cache-pricing/model',
- canonical_slug: 'no-cache-pricing/model',
name: 'No Cache Pricing Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1037,37 +847,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'invalid-pricing/model',
- canonical_slug: 'invalid-pricing/model',
name: 'Invalid Pricing Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '-1',
completion: '-1',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1080,37 +873,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'context/model',
- canonical_slug: 'context/model',
name: 'Context Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1122,37 +898,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'fallback-context/model',
- canonical_slug: 'fallback-context/model',
name: 'Fallback Context Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 0,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 0, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1164,37 +923,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'maxoutput/model',
- canonical_slug: 'maxoutput/model',
name: 'Max Output Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1206,37 +948,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'null-maxoutput/model',
- canonical_slug: 'null-maxoutput/model',
name: 'Null Max Output Model',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: null,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: null },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1249,37 +974,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'released/model',
- canonical_slug: 'released/model',
name: 'Released Model',
created: 1679587200, // 2023-03-23
context_length: 8192,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1325,37 +1033,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'minimal/model',
- canonical_slug: 'minimal/model',
name: 'Minimal Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: [],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: [] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1370,37 +1061,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'simple/model',
- canonical_slug: 'simple/model',
name: 'Simple Model Name',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1412,55 +1086,27 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'model-1',
- canonical_slug: 'model-1',
name: 'Provider: Model 1',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: { prompt: '0.00001', completion: '0.00002' },
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: ['tools'],
},
{
id: 'model-2',
- canonical_slug: 'model-2',
name: 'Provider: Model 2',
created: 1679587200,
context_length: 8192,
- architecture: {
- modality: 'text+image->text',
- input_modalities: ['text', 'image'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text', 'image'] },
pricing: { prompt: '0.00002', completion: '0.00004' },
- top_provider: {
- context_length: 8192,
- max_completion_tokens: 4096,
- is_moderated: false,
- },
+ top_provider: { context_length: 8192, max_completion_tokens: 4096 },
supported_parameters: ['reasoning'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1478,37 +1124,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'advanced/model',
- canonical_slug: 'advanced/model',
name: 'Advanced Model',
created: 1679587200,
context_length: 128000,
- architecture: {
- modality: 'text+image->text',
- input_modalities: ['text', 'image'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text', 'image'] },
pricing: {
prompt: '0.00003',
completion: '0.00009',
},
- top_provider: {
- context_length: 128000,
- max_completion_tokens: 8192,
- is_moderated: false,
- },
+ top_provider: { context_length: 128000, max_completion_tokens: 8192 },
supported_parameters: ['tools', 'reasoning', 'temperature'],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1522,37 +1151,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'empty-modalities/model',
- canonical_slug: 'empty-modalities/model',
name: 'Empty Modalities Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: [],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: [] },
pricing: {
prompt: '0.00001',
completion: '0.00002',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1564,37 +1176,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'null-pricing/model',
- canonical_slug: 'null-pricing/model',
name: 'Null Pricing Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: null,
completion: null,
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1611,37 +1206,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'zero-pricing/model',
- canonical_slug: 'zero-pricing/model',
name: 'Zero Pricing Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0',
completion: '0',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1658,37 +1236,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'mixed-free/model',
- canonical_slug: 'mixed-free/model',
name: 'Mixed Free Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0',
completion: '0.00001',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1702,37 +1263,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'expensive/model',
- canonical_slug: 'expensive/model',
name: 'Expensive Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '1.5',
completion: '3.0',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1751,37 +1295,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'test/model',
- canonical_slug: 'test/model',
name: 'Test Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: undefined,
completion: undefined,
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1793,37 +1320,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'invalid-price/model',
- canonical_slug: 'invalid-price/model',
name: 'Invalid Price Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '-1',
completion: '-1',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
@@ -1835,37 +1345,20 @@ describe('LobeOpenRouterAI - custom features', () => {
const mockModels = [
{
id: 'micro-price/model',
- canonical_slug: 'micro-price/model',
name: 'Micro Price Model',
created: 1679587200,
context_length: 4096,
- architecture: {
- modality: 'text->text',
- input_modalities: ['text'],
- output_modalities: ['text'],
- tokenizer: 'default',
- instruct_type: null,
- },
+ architecture: { input_modalities: ['text'] },
pricing: {
prompt: '0.0000001',
completion: '0.0000002',
},
- top_provider: {
- context_length: 4096,
- max_completion_tokens: 2048,
- is_moderated: false,
- },
+ top_provider: { context_length: 4096, max_completion_tokens: 2048 },
supported_parameters: [],
},
];
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ data: mockModels }),
- }),
- );
+ stubModelsResponse(mockModels);
const models = await params.models();
diff --git a/packages/model-runtime/src/providers/qwen/createImage.test.ts b/packages/model-runtime/src/providers/qwen/createImage.test.ts
index db3ea32ca80..25c9e50fe58 100644
--- a/packages/model-runtime/src/providers/qwen/createImage.test.ts
+++ b/packages/model-runtime/src/providers/qwen/createImage.test.ts
@@ -5,6 +5,26 @@ import { type CreateImageOptions } from '../../core/openaiCompatibleFactory';
import { type CreateImagePayload } from '../../types/image';
import { createQwenImage } from './createImage';
+const createSucceededTaskResponse = (taskId: string, imageUrl: string) => ({
+ ok: true,
+ json: async () => ({
+ output: {
+ task_id: taskId,
+ task_status: 'SUCCEEDED',
+ results: [{ url: imageUrl }],
+ },
+ request_id: 'req-124',
+ }),
+});
+
+const createSubmittedTaskResponse = (taskId: string) => ({
+ ok: true,
+ json: async () => ({
+ output: { task_id: taskId },
+ request_id: 'req-123',
+ }),
+});
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -32,24 +52,8 @@ describe('createQwenImage', () => {
// Mock fetch for task creation and immediate success
global.fetch = vi
.fn()
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: { task_id: mockTaskId },
- request_id: 'req-123',
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: {
- task_id: mockTaskId,
- task_status: 'SUCCEEDED',
- results: [{ url: mockImageUrl }],
- },
- request_id: 'req-124',
- }),
- });
+ .mockResolvedValueOnce(createSubmittedTaskResponse(mockTaskId))
+ .mockResolvedValueOnce(createSucceededTaskResponse(mockTaskId, mockImageUrl));
const payload: CreateImagePayload = {
model: 'wanx-v1',
@@ -88,24 +92,8 @@ describe('createQwenImage', () => {
// Mock fetch for task creation and immediate success
global.fetch = vi
.fn()
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: { task_id: mockTaskId },
- request_id: 'req-123',
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: {
- task_id: mockTaskId,
- task_status: 'SUCCEEDED',
- results: [{ url: mockImageUrl }],
- },
- request_id: 'req-124',
- }),
- });
+ .mockResolvedValueOnce(createSubmittedTaskResponse(mockTaskId))
+ .mockResolvedValueOnce(createSucceededTaskResponse(mockTaskId, mockImageUrl));
const payload: CreateImagePayload = {
model: 'wanx-v1',
@@ -134,24 +122,8 @@ describe('createQwenImage', () => {
// Mock fetch for task creation and immediate success
global.fetch = vi
.fn()
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: { task_id: mockTaskId },
- request_id: 'req-123',
- }),
- })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({
- output: {
- task_id: mockTaskId,
- task_status: 'SUCCEEDED',
- results: [{ url: mockImageUrl }],
- },
- request_id: 'req-124',
- }),
- });
+ .mockResolvedValueOnce(createSubmittedTaskResponse(mockTaskId))
+ .mockResolvedValueOnce(createSucceededTaskResponse(mockTaskId, mockImageUrl));
const payload: CreateImagePayload = {
model: 'wanx2.1-t2i-turbo',
diff --git a/packages/model-runtime/src/utils/asyncifyPolling.test.ts b/packages/model-runtime/src/utils/asyncifyPolling.test.ts
index 4320cd43e8a..f58f74ae7c2 100644
--- a/packages/model-runtime/src/utils/asyncifyPolling.test.ts
+++ b/packages/model-runtime/src/utils/asyncifyPolling.test.ts
@@ -1,8 +1,16 @@
+import type { Mock } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import type { TaskResult } from './asyncifyPolling';
import { asyncifyPolling } from './asyncifyPolling';
+const createErrorOptions = (mockTask: Mock, mockCheckStatus: Mock, onPollingError: Mock) => ({
+ pollingQuery: mockTask,
+ checkStatus: mockCheckStatus,
+ onPollingError,
+ initialInterval: 1,
+});
+
describe('asyncifyPolling', () => {
describe('basic functionality', () => {
it('should return data when task succeeds immediately', async () => {
@@ -357,12 +365,9 @@ describe('asyncifyPolling', () => {
isContinuePolling: true,
});
- const result = await asyncifyPolling({
- pollingQuery: mockTask,
- checkStatus: mockCheckStatus,
- onPollingError,
- initialInterval: 1,
- });
+ const result = await asyncifyPolling(
+ createErrorOptions(mockTask, mockCheckStatus, onPollingError),
+ );
expect(result).toBe('final-result');
expect(mockTask).toHaveBeenCalledTimes(3);
@@ -385,12 +390,7 @@ describe('asyncifyPolling', () => {
});
await expect(
- asyncifyPolling({
- pollingQuery: mockTask,
- checkStatus: mockCheckStatus,
- onPollingError,
- initialInterval: 1,
- }),
+ asyncifyPolling(createErrorOptions(mockTask, mockCheckStatus, onPollingError)),
).rejects.toThrow('Fatal error');
expect(mockTask).toHaveBeenCalledTimes(1);
@@ -409,12 +409,7 @@ describe('asyncifyPolling', () => {
});
await expect(
- asyncifyPolling({
- pollingQuery: mockTask,
- checkStatus: mockCheckStatus,
- onPollingError,
- initialInterval: 1,
- }),
+ asyncifyPolling(createErrorOptions(mockTask, mockCheckStatus, onPollingError)),
).rejects.toThrow('Custom error message');
expect(onPollingError).toHaveBeenCalledWith({
@@ -440,12 +435,7 @@ describe('asyncifyPolling', () => {
.mockReturnValueOnce({ isContinuePolling: false });
await expect(
- asyncifyPolling({
- pollingQuery: mockTask,
- checkStatus: mockCheckStatus,
- onPollingError,
- initialInterval: 1,
- }),
+ asyncifyPolling(createErrorOptions(mockTask, mockCheckStatus, onPollingError)),
).rejects.toThrow('Error 3');
// Verify context progression
diff --git a/packages/web-crawler/src/crawImpl/__tests__/firecrawl.test.ts b/packages/web-crawler/src/crawImpl/__tests__/firecrawl.test.ts
index 5b8216363e9..896301f0d34 100644
--- a/packages/web-crawler/src/crawImpl/__tests__/firecrawl.test.ts
+++ b/packages/web-crawler/src/crawImpl/__tests__/firecrawl.test.ts
@@ -4,6 +4,16 @@ import { createMockResponse } from '../../test-utils';
import { NetworkConnectionError, PageNotFoundError, TimeoutError } from '../../utils/errorType';
import { firecrawl } from '../firecrawl';
+const pageMetadata = () => ({
+ title: 'Test',
+ description: 'Test',
+ sourceURL: 'https://example.com',
+ statusCode: 200,
+ language: 'en',
+ keywords: 'test',
+ robots: 'index',
+});
+
// Mock dependencies
vi.mock('../../utils/withTimeout', () => ({
DEFAULT_TIMEOUT: 30000,
@@ -62,15 +72,7 @@ describe('firecrawl crawler', () => {
success: true,
data: {
markdown: 'Test content with sufficient length. '.repeat(5),
- metadata: {
- title: 'Test',
- description: 'Test',
- sourceURL: 'https://example.com',
- statusCode: 200,
- language: 'en',
- keywords: 'test',
- robots: 'index',
- },
+ metadata: pageMetadata(),
},
});
@@ -89,15 +91,7 @@ describe('firecrawl crawler', () => {
success: true,
data: {
markdown: 'Short', // Content too short
- metadata: {
- title: 'Test',
- description: 'Test',
- sourceURL: 'https://example.com',
- statusCode: 200,
- language: 'en',
- keywords: 'test',
- robots: 'index',
- },
+ metadata: pageMetadata(),
},
});
@@ -116,15 +110,7 @@ describe('firecrawl crawler', () => {
success: true,
data: {
// markdown is missing
- metadata: {
- title: 'Test',
- description: 'Test',
- sourceURL: 'https://example.com',
- statusCode: 200,
- language: 'en',
- keywords: 'test',
- robots: 'index',
- },
+ metadata: pageMetadata(),
},
});
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index e82a8d17faf..c30f36e7d1a 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -208,6 +208,15 @@ vi.mock('../../TopicListContent/ThreadList', () => ({
}));
describe('TopicItem active state', () => {
+ beforeEach(() => {
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+ });
+
afterEach(() => {
scopedTopicMock.value = undefined;
prefetchMessagesMock.mockClear();
@@ -317,13 +326,6 @@ describe('TopicItem active state', () => {
});
it('prefixes the cmd-click href with the active workspace slug', () => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
render(<TopicItem id="tpc_test" title="Topic" />);
expect(screen.getByTestId('nav-item')).toHaveAttribute(
@@ -337,12 +339,6 @@ describe('TopicItem active state', () => {
const now = Date.UTC(2026, 0, 1, 0, 0, 33);
vi.setSystemTime(now);
runningStartTimeMock.value = now - 33_000;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" status="running" title="Topic" />);
@@ -359,12 +355,6 @@ describe('TopicItem active state', () => {
const now = Date.UTC(2026, 0, 1, 0, 2, 37);
vi.setSystemTime(now);
runningStartTimeMock.value = undefined;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(
<TopicItem
@@ -383,12 +373,6 @@ describe('TopicItem active state', () => {
const now = Date.UTC(2026, 0, 1, 0, 0, 33);
vi.setSystemTime(now);
runningStartTimeMock.value = now - 33_000;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(
<TopicItem
@@ -454,13 +438,6 @@ describe('TopicItem active state', () => {
});
it('hides the inline archive action while the topic is running', () => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
render(<TopicItem id="tpc_test" status="running" title="Topic" />);
expect(screen.getByTestId('topic-actions')).toHaveAttribute(
@@ -470,26 +447,12 @@ describe('TopicItem active state', () => {
});
it('offers the inline archive action once the topic is idle', () => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
render(<TopicItem id="tpc_test" title="Topic" />);
expect(screen.getByTestId('topic-actions')).toHaveAttribute('data-show-inline-archive', 'true');
});
it('keeps idle topics iconless', () => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
render(<TopicItem id="tpc_test" title="Topic" />);
expect(screen.queryByTestId('topic-item-icon')).not.toBeInTheDocument();
@@ -497,12 +460,6 @@ describe('TopicItem active state', () => {
it('prefetches messages when a topic is an unread completion', async () => {
topicUnreadCompletedMock.value = true;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" title="Topic" />);
@@ -518,12 +475,6 @@ describe('TopicItem active state', () => {
it('prefetches unread completed messages after the runtime stops', async () => {
agentRuntimeRunningMock.value = true;
topicUnreadCompletedMock.value = true;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
const { rerender } = render(<TopicItem id="tpc_test" title="Topic" />);
@@ -542,13 +493,6 @@ describe('TopicItem active state', () => {
});
it('shows the topic worktree and branch from structured metadata', () => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
render(
<TopicItem
showWorkingDirectory
@@ -571,12 +515,6 @@ describe('TopicItem active state', () => {
describe('draft hint', () => {
beforeEach(() => {
hasDraftMock.value = true;
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
});
it('stacks the draft hint under the leading icon on a two-line row', () => {
@@ -606,12 +544,6 @@ describe('TopicItem active state', () => {
it('keeps the unread dot visible when the topic has a linked pull request', () => {
topicUnreadCompletedMock.value = true;
topicMetaCardMock.value = { pullRequest: { state: 'open' } };
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" title="Topic" />);
@@ -621,12 +553,6 @@ describe('TopicItem active state', () => {
/** @example A project row is not in the chat store, so only its own status says unread. */
it('shows the unread dot for a project row whose own status is unread', () => {
scopedTopicMock.value = { agentId: 'other-agent', agentName: 'Other Agent' };
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(
<TopicListScopeContext value={{ projectId: 'project-1' }}>
@@ -639,12 +565,6 @@ describe('TopicItem active state', () => {
it('shows the pull request marker once the topic is no longer unread', () => {
topicMetaCardMock.value = { pullRequest: { state: 'open' } };
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" title="Topic" />);
@@ -653,15 +573,6 @@ describe('TopicItem active state', () => {
});
describe('goal marker', () => {
- beforeEach(() => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
- });
-
it('marks a topic that has a goal, ahead of its pull request', () => {
topicMetaCardMock.value = { pullRequest: { state: 'open' } };
@@ -691,12 +602,6 @@ describe('TopicItem active state', () => {
it('adds the CI status to the pull request marker', () => {
topicMetaCardMock.value = { pullRequest: { ciStatus: 'pending', state: 'open' } };
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" title="Topic" />);
@@ -709,13 +614,6 @@ describe('TopicItem active state', () => {
it.each([{ state: 'merged' }, { mergedAt: '2026-11-05T03:58:11Z', state: 'closed' }])(
'uses the merged PR icon as the avatar badge for %o regardless of CI',
(pullRequest) => {
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
-
for (const ciStatus of ['pending', 'failure', 'success'] as const) {
topicMetaCardMock.value = { pullRequest: { ...pullRequest, ciStatus } };
@@ -736,12 +634,6 @@ describe('TopicItem active state', () => {
['completed', 'CircleCheck'],
] as const)('keeps the %s status above linked pull request metadata', (status, icon) => {
topicMetaCardMock.value = { pullRequest: { state: 'open' } };
- useTopicNavigationMock.mockReturnValue({
- isInAgentSubRoute: false,
- isInTopicContextRoute: false,
- navigateToTopic: vi.fn(),
- routeTopicId: undefined,
- });
render(<TopicItem id="tpc_test" status={status} title="Topic" />);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
index 78f1d5f4e57..9ffd9ff53f7 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -277,7 +277,6 @@ describe('TaskDetailHeaderActions', () => {
expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('archive');
const button = screen.getByRole('button', { name: 'taskList.contextMenu.archive' });
const moreButton = screen.getAllByRole('button').at(-1);
- expect(button).not.toBe(moreButton);
expect(
button.compareDocumentPosition(moreButton!) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
index 41b4fa651cf..1a3e77f11c9 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -755,9 +755,6 @@ describe('CreateTaskInlineEntry', () => {
// The answer reaches the task through the rewritten brief, not as a list
// bolted underneath one written before the answer existed.
expect(createTaskMock.mock.calls[0][0].instruction).toBe('Write the Q3 plan for lobe-chat.');
- expect(createTaskMock.mock.calls[0][0].instruction).not.toContain(
- 'taskIntent.answersHeading',
- );
expect(createTaskMock.mock.calls[0][0].name).toBe('Write the Q3 project plan');
});
diff --git a/src/features/Channels/channelScope.test.ts b/src/features/Channels/channelScope.test.ts
index 7f0b44b6791..c32acf024bd 100644
--- a/src/features/Channels/channelScope.test.ts
+++ b/src/features/Channels/channelScope.test.ts
@@ -21,10 +21,6 @@ describe('channelsInScope', () => {
expect(channelsInScope(channels)?.map((c) => c.id)).toEqual(['standalone', 'legacy']);
});
- it('leaves direct Agent Channels out of the list', () => {
- expect(channelsInScope(channels)?.map((c) => c.id)).not.toContain('direct');
- });
-
it('waits for the list to load', () => {
expect(channelsInScope(undefined, 'pro_1')).toBeUndefined();
});
diff --git a/src/features/ChatInput/Dictation/client.test.ts b/src/features/ChatInput/Dictation/client.test.ts
index 40a10f57263..394426a48d5 100644
--- a/src/features/ChatInput/Dictation/client.test.ts
+++ b/src/features/ChatInput/Dictation/client.test.ts
@@ -13,6 +13,27 @@ import {
} from './contract';
import type { DictationEditorAdapter } from './editor';
+const createEditor = (): DictationEditorAdapter => ({
+ begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
+ dispose: vi.fn(),
+ finalize: vi.fn(),
+ render: vi.fn(),
+});
+
+const mockCapture = (): RealtimeAudioCapture => ({
+ cancel: vi.fn().mockResolvedValue(undefined),
+ start: vi.fn().mockResolvedValue(undefined),
+ stop: vi.fn().mockResolvedValue(undefined),
+});
+
+const finalTranscript = (sessionId: string): RealtimeAsrServerEvent => ({
+ segmentId: 'segment-1',
+ sequence: 2,
+ sessionId,
+ text: 'confirmed',
+ type: 'transcript.final',
+});
+
const SESSION_ID = '00000000-0000-4000-8000-000000000001';
const OLD_SESSION_ID = '00000000-0000-4000-8000-000000000002';
const FRESH_SESSION_ID = '00000000-0000-4000-8000-000000000003';
@@ -177,11 +198,7 @@ describe('RealtimeDictationClient', () => {
let resolvePermission!: (stream: MediaStream) => void;
let resolveCapture!: (capture: RealtimeAudioCapture) => void;
const socket = new FakeSocket();
- const capture: RealtimeAudioCapture = {
- cancel: vi.fn().mockResolvedValue(undefined),
- start: vi.fn().mockResolvedValue(undefined),
- stop: vi.fn().mockResolvedValue(undefined),
- };
+ const capture: RealtimeAudioCapture = mockCapture();
const createWebSocket = vi.fn(() => socket as unknown as RealtimeAsrWebSocket);
const client = new RealtimeDictationClient({
createCapture: vi.fn(
@@ -192,12 +209,7 @@ describe('RealtimeDictationClient', () => {
),
createSession: vi.fn().mockResolvedValue(session()),
createWebSocket,
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
requestMicrophone: vi.fn(
() =>
new Promise<MediaStream>((resolve) => {
@@ -244,12 +256,7 @@ describe('RealtimeDictationClient', () => {
createCapture,
createSession,
createWebSocket,
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
requestMicrophone: vi.fn(
() =>
new Promise<MediaStream>((resolve) => {
@@ -285,12 +292,7 @@ describe('RealtimeDictationClient', () => {
createCapture: vi.fn(),
createSession,
createWebSocket,
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
requestMicrophone: vi
.fn()
.mockRejectedValue(new DOMException('Permission denied', 'NotAllowedError')),
@@ -313,11 +315,7 @@ describe('RealtimeDictationClient', () => {
it('releases a late audio capture when concurrent session admission fails', async () => {
let resolveCapture!: (capture: RealtimeAudioCapture) => void;
- const capture: RealtimeAudioCapture = {
- cancel: vi.fn().mockResolvedValue(undefined),
- start: vi.fn().mockResolvedValue(undefined),
- stop: vi.fn().mockResolvedValue(undefined),
- };
+ const capture: RealtimeAudioCapture = mockCapture();
const client = new RealtimeDictationClient({
createCapture: vi.fn(
() =>
@@ -329,12 +327,7 @@ describe('RealtimeDictationClient', () => {
.fn()
.mockRejectedValue(new RealtimeDictationError('SESSION_CREATE_FAILED', true)),
createWebSocket: vi.fn(() => new FakeSocket() as unknown as RealtimeAsrWebSocket),
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
requestMicrophone: vi
.fn()
.mockResolvedValue({ getTracks: () => [] } as unknown as MediaStream),
@@ -422,19 +415,10 @@ describe('RealtimeDictationClient', () => {
});
const createWebSocket = vi.fn(() => socket as unknown as RealtimeAsrWebSocket);
const client = new RealtimeDictationClient({
- createCapture: vi.fn().mockResolvedValue({
- cancel: vi.fn().mockResolvedValue(undefined),
- start: vi.fn().mockResolvedValue(undefined),
- stop: vi.fn().mockResolvedValue(undefined),
- }),
+ createCapture: vi.fn().mockResolvedValue(mockCapture()),
createSession,
createWebSocket,
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
now: () => timingNow,
onTiming: (timing) => timings.push(timing),
requestMicrophone: vi.fn().mockResolvedValue({ getTracks: () => [] }),
@@ -455,11 +439,7 @@ describe('RealtimeDictationClient', () => {
});
it('fails without opening the WS when the single refreshed Admission is still expiring', async () => {
- const capture: RealtimeAudioCapture = {
- cancel: vi.fn().mockResolvedValue(undefined),
- start: vi.fn().mockResolvedValue(undefined),
- stop: vi.fn().mockResolvedValue(undefined),
- };
+ const capture: RealtimeAudioCapture = mockCapture();
const staleSession = session({ expiresAt: new Date(100_500).toISOString() });
const createSession = vi.fn().mockResolvedValue(staleSession);
const createWebSocket = vi.fn(() => new FakeSocket() as unknown as RealtimeAsrWebSocket);
@@ -467,12 +447,7 @@ describe('RealtimeDictationClient', () => {
createCapture: vi.fn().mockResolvedValue(capture),
createSession,
createWebSocket,
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
requestMicrophone: vi
.fn()
.mockResolvedValue({ getTracks: () => [] } as unknown as MediaStream),
@@ -498,11 +473,7 @@ describe('RealtimeDictationClient', () => {
let resolveSession!: (session: RealtimeAsrSessionResponse) => void;
const timings: RealtimeDictationTiming[] = [];
const socket = new FakeSocket();
- const capture: RealtimeAudioCapture = {
- cancel: vi.fn().mockResolvedValue(undefined),
- start: vi.fn().mockResolvedValue(undefined),
- stop: vi.fn().mockResolvedValue(undefined),
- };
+ const capture: RealtimeAudioCapture = mockCapture();
const markSpy = vi.spyOn(performance, 'mark');
const client = new RealtimeDictationClient({
createCapture: vi.fn(
@@ -518,12 +489,7 @@ describe('RealtimeDictationClient', () => {
}),
),
createWebSocket: vi.fn(() => socket as unknown as RealtimeAsrWebSocket),
- editor: {
- begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),
- dispose: vi.fn(),
- finalize: vi.fn(),
- render: vi.fn(),
- },
+ editor: createEditor(),
now: () => clock,
onTiming: (timing) => timings.push(timing),
requestMicrophone: vi.fn(
@@ -592,13 +558,7 @@ describe('RealtimeDictationClient', () => {
it('keeps final text and drops only partial text on cancel', async () => {
const fixture = createFixture();
await fixture.start();
- fixture.socket.serverEvent({
- segmentId: 'segment-1',
- sequence: 2,
- sessionId: SESSION_ID,
- text: 'confirmed',
- type: 'transcript.final',
- });
+ fixture.socket.serverEvent(finalTranscript(SESSION_ID));
fixture.socket.serverEvent({
segmentId: 'segment-2',
sequence: 3,
@@ -691,13 +651,7 @@ describe('RealtimeDictationClient', () => {
it('ends safely on user edit and preserves confirmed text', async () => {
const fixture = createFixture();
await fixture.start();
- fixture.socket.serverEvent({
- segmentId: 'segment-1',
- sequence: 2,
- sessionId: SESSION_ID,
- text: 'confirmed',
- type: 'transcript.final',
- });
+ fixture.socket.serverEvent(finalTranscript(SESSION_ID));
fixture.onUserEdit();
await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('finalizing'));
@@ -713,13 +667,7 @@ describe('RealtimeDictationClient', () => {
it('keeps confirmed text and reports a network disconnect', async () => {
const fixture = createFixture();
await fixture.start();
- fixture.socket.serverEvent({
- segmentId: 'segment-1',
- sequence: 2,
- sessionId: SESSION_ID,
- text: 'confirmed',
- type: 'transcript.final',
- });
+ fixture.socket.serverEvent(finalTranscript(SESSION_ID));
fixture.socket.disconnect();
await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('error'));
diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts
index 3ef4cd45fd2..329cecbd25b 100644
--- a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts
+++ b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts
@@ -398,6 +398,14 @@ describe('executeLegacyMigrationSave', () => {
let calls: string[];
let consoleErrorSpy: MockInstance<typeof console.error>;
+ const getMigrationDeps = (): MigrationSaveDeps => ({
+ createConnector,
+ deleteConnector,
+ hasExistingConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+
beforeEach(() => {
calls = [];
createConnector = vi.fn<MigrationSaveDeps['createConnector']>(async () => {
@@ -423,13 +431,7 @@ describe('executeLegacyMigrationSave', () => {
});
it('runs create → sync → uninstall in exact order on the happy path', async () => {
- const result = await executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps());
expect(result).toEqual({ connectorId: 'new-conn-id', ok: true });
expect(calls).toEqual(['createConnector', 'syncConnectorTools', 'uninstallCustomPlugin']);
});
@@ -443,13 +445,7 @@ describe('executeLegacyMigrationSave', () => {
type: 'customPlugin',
} as LobeToolCustomPlugin;
- await executeLegacyMigrationSave(legacy('agent-x'), value, {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ await executeLegacyMigrationSave(legacy('agent-x'), value, getMigrationDeps());
const payload = createConnector.mock.calls[0][0];
expect(payload.identifier).toBe('agent-x');
@@ -465,13 +461,11 @@ describe('executeLegacyMigrationSave', () => {
// gets deleted under the OLD key, and `agentConfig.plugins[i]` matches
// neither. The orchestrator must pin the create payload to the legacy
// identifier regardless of what the form ended up with.
- await executeLegacyMigrationSave(legacy('legacy-id'), legacy('renamed-in-form'), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ await executeLegacyMigrationSave(
+ legacy('legacy-id'),
+ legacy('renamed-in-form'),
+ getMigrationDeps(),
+ );
expect(createConnector).toHaveBeenCalledTimes(1);
expect(createConnector.mock.calls[0][0].identifier).toBe('legacy-id');
@@ -485,13 +479,7 @@ describe('executeLegacyMigrationSave', () => {
identifier: 'broken',
type: 'customPlugin',
} as LobeToolCustomPlugin;
- const result = await executeLegacyMigrationSave(broken, broken, {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ const result = await executeLegacyMigrationSave(broken, broken, getMigrationDeps());
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason).toBe('no-endpoint');
@@ -503,13 +491,7 @@ describe('executeLegacyMigrationSave', () => {
it('rethrows createConnector failure and leaves legacy plugin in place', async () => {
createConnector.mockRejectedValueOnce(new Error('boom: bad network'));
await expect(
- executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- }),
+ executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),
).rejects.toThrow('boom: bad network');
expect(syncConnectorTools).not.toHaveBeenCalled();
expect(uninstallCustomPlugin).not.toHaveBeenCalled();
@@ -524,13 +506,7 @@ describe('executeLegacyMigrationSave', () => {
// can retry the save once the endpoint is healthy.
syncConnectorTools.mockRejectedValueOnce(new Error('mcp tools/list timeout'));
await expect(
- executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- }),
+ executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),
).rejects.toThrow('mcp tools/list timeout');
// `syncConnectorTools` is invoked but its mock rejects without recording a
// call, so `calls` shows create → rollback delete.
@@ -548,13 +524,7 @@ describe('executeLegacyMigrationSave', () => {
hasExistingConnector.mockReturnValue(true);
syncConnectorTools.mockRejectedValueOnce(new Error('mcp tools/list timeout'));
await expect(
- executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- }),
+ executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),
).rejects.toThrow('mcp tools/list timeout');
expect(deleteConnector).not.toHaveBeenCalled();
expect(uninstallCustomPlugin).not.toHaveBeenCalled();
@@ -564,13 +534,7 @@ describe('executeLegacyMigrationSave', () => {
syncConnectorTools.mockRejectedValueOnce(new Error('mcp tools/list timeout'));
deleteConnector.mockRejectedValueOnce(new Error('rollback network error'));
await expect(
- executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- }),
+ executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),
).rejects.toThrow('mcp tools/list timeout');
expect(consoleErrorSpy).toHaveBeenCalledWith(
'[connector-migration] rollback after failed sync failed',
@@ -581,13 +545,7 @@ describe('executeLegacyMigrationSave', () => {
it('swallows uninstallCustomPlugin failure (connector is the source of truth)', async () => {
uninstallCustomPlugin.mockRejectedValueOnce(new Error('legacy delete failed'));
- const result = await executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps());
// Migration is still considered SUCCESSFUL — the runtime dedupes by
// identifier and the connector wins, so the leaked legacy row is harmless.
// Sync succeeded, so the connector is NOT rolled back.
@@ -603,26 +561,14 @@ describe('executeLegacyMigrationSave', () => {
// First attempt: sync fails → the created connector is rolled back.
syncConnectorTools.mockRejectedValueOnce(new Error('first attempt fails'));
await expect(
- executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- }),
+ executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),
).rejects.toThrow('first attempt fails');
expect(calls).toEqual(['createConnector', 'deleteConnector']);
// Reset call log; retry. Server-side `connector.create` is idempotent on
// (user_id, identifier), so the second create is an UPDATE.
calls.length = 0;
- const result = await executeLegacyMigrationSave(legacy(), legacy(), {
- createConnector,
- deleteConnector,
- hasExistingConnector,
- syncConnectorTools,
- uninstallCustomPlugin,
- });
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps());
expect(result.ok).toBe(true);
expect(calls).toEqual(['createConnector', 'syncConnectorTools', 'uninstallCustomPlugin']);
});
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
index 5c4dccea224..e354084c1e7 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { agentSignalService } from '@/services/agentSignal';
+import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';
import AgentSignalReceiptList from './AgentSignalReceiptList';
const mocks = vi.hoisted(() => ({
@@ -59,6 +60,42 @@ vi.mock('@/services/agentSignal', () => ({
},
}));
+const createGatewayMemoryReceipt = (
+ target: AgentSignalReceiptView['target'],
+): AgentSignalReceiptView => ({
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target,
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+});
+
+const createGatewaySkillReceipt = (
+ target: AgentSignalReceiptView['target'],
+ metadata?: AgentSignalReceiptView['metadata'],
+): AgentSignalReceiptView => ({
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ ...(metadata === undefined ? {} : { metadata }),
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target,
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+});
+
describe('AgentSignalReceiptList', () => {
afterEach(() => {
mocks.mutate.mockReset();
@@ -73,24 +110,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Saved this for future replies',
- id: 'receipt-1',
- kind: 'memory',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- target: {
- summary: 'Use decision-first PR reviews in future chats',
- title: 'Decision-first PR review preference',
- type: 'memory',
- },
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewayMemoryReceipt({
+ summary: 'Use decision-first PR reviews in future chats',
+ title: 'Decision-first PR review preference',
+ type: 'memory',
+ }),
{
agentId: 'agent-1',
createdAt: 2,
@@ -126,24 +150,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Saved this for future replies',
- id: 'receipt-1',
- kind: 'memory',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- target: {
- summary: 'Saved this for future replies',
- title: 'Future reply preference',
- type: 'memory',
- },
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewayMemoryReceipt({
+ summary: 'Saved this for future replies',
+ title: 'Future reply preference',
+ type: 'memory',
+ }),
]}
/>,
);
@@ -157,24 +168,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewaySkillReceipt({
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ }),
]}
/>,
);
@@ -220,24 +218,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewaySkillReceipt({
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ }),
]}
/>,
);
@@ -251,26 +236,13 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- agentDocumentId: 'index-agent-document-1',
- documentId: 'index-document-1',
- id: 'bundle-document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewaySkillReceipt({
+ agentDocumentId: 'index-agent-document-1',
+ documentId: 'index-document-1',
+ id: 'bundle-document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ }),
]}
/>,
);
@@ -284,23 +256,10 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Saved this for future replies',
- id: 'receipt-1',
- kind: 'memory',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- target: {
- title: 'Remember this PR review workflow',
- type: 'memory',
- },
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewayMemoryReceipt({
+ title: 'Remember this PR review workflow',
+ type: 'memory',
+ }),
]}
/>,
);
@@ -314,24 +273,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Saved this for future replies',
- id: 'receipt-1',
- kind: 'memory',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- target: {
- id: 'base-memory-1',
- title: 'AmAzing- prefers the assistant to respond in Chinese.',
- type: 'memory',
- },
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewayMemoryReceipt({
+ id: 'base-memory-1',
+ title: 'AmAzing- prefers the assistant to respond in Chinese.',
+ type: 'memory',
+ }),
]}
/>,
);
@@ -349,26 +295,13 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Saved this for future replies',
- id: 'receipt-1',
- kind: 'memory',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- target: {
- id: 'preference-1',
- memoryId: 'memory-1',
- memoryLayer: LayersEnum.Preference,
- title: 'Decision-first PR review preference',
- type: 'memory',
- },
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewayMemoryReceipt({
+ id: 'preference-1',
+ memoryId: 'memory-1',
+ memoryLayer: LayersEnum.Preference,
+ title: 'Decision-first PR review preference',
+ type: 'memory',
+ }),
]}
/>,
);
@@ -530,30 +463,19 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- metadata: {
+ createGatewaySkillReceipt(
+ {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ {
agentDocumentId: 'agent-document-1',
documentId: 'document-1',
historyId: 'history-1',
rollbackStatus: 'available',
},
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ ),
{
agentId: 'agent-1',
createdAt: 2,
@@ -614,30 +536,19 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- metadata: {
+ createGatewaySkillReceipt(
+ {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ {
agentDocumentId: 'agent-document-1',
documentId: 'document-1',
historyId: 'history-1',
rollbackStatus: 'available',
},
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ ),
]}
/>,
);
@@ -673,30 +584,19 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- metadata: {
+ createGatewaySkillReceipt(
+ {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ {
agentDocumentId: 'agent-document-1',
documentId: 'document-1',
historyId: 'history-1',
rollbackStatus: 'available',
},
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ ),
]}
/>,
);
@@ -768,29 +668,18 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- metadata: {
- documentId: 'document-1',
- historyId: 'history-1',
- rollbackStatus: 'not_found',
- },
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
+ createGatewaySkillReceipt(
+ {
id: 'document-1',
title: 'GitHub PR review workflow',
type: 'skill',
},
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ {
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'not_found',
+ },
+ ),
]}
/>,
);
@@ -803,24 +692,11 @@ describe('AgentSignalReceiptList', () => {
render(
<AgentSignalReceiptList
receipts={[
- {
- agentId: 'agent-1',
- createdAt: 1,
- detail: 'Improved how this assistant handles similar requests',
- id: 'receipt-1',
- kind: 'skill',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'updated',
- target: {
- id: 'document-1',
- title: 'GitHub PR review workflow',
- type: 'skill',
- },
- title: 'Skill updated',
- topicId: 'topic-1',
- userId: 'user-1',
- },
+ createGatewaySkillReceipt({
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ }),
]}
/>,
);
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
index cc2d807476e..c2f4d98159e 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -83,6 +83,14 @@ const refOf = (handle: FakeVList | null): RefObject<VListHandle | null> => ({
current: handle as unknown as VListHandle | null,
});
+const useTopicScrollFixture = (handle: FakeVList) =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ });
+
// One rAF tick in happy-dom is ~16ms; advancing 32ms covers two scheduled
// frames reliably without running all queued timers (which would fire the
// entire poll loop at once).
@@ -324,14 +332,7 @@ describe('useTopicScrollPersist', () => {
// resize within 150ms, so a restore landing while a reply streamed kept
// pulling the user back to the bottom after they scrolled up.
const handle = createFakeVList({ scrollSize: 5000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(4);
@@ -342,14 +343,7 @@ describe('useTopicScrollPersist', () => {
it('keeps jumping to the end until the measured height stops changing', async () => {
const handle = createFakeVList({ scrollSize: 5000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
// virtua measures the rows revealed by the first jump.
handle.scrollSize = 5600;
@@ -367,14 +361,7 @@ describe('useTopicScrollPersist', () => {
// opened topic short of the bottom once virtua re-rendered the
// measured rows a few frames later.
const handle = createFakeVList({ scrollSize: 5000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(3);
handle.scrollSize = 7600;
@@ -388,14 +375,7 @@ describe('useTopicScrollPersist', () => {
handle.scroller.setScrollTop.mockImplementation(() => {
handle.scrollSize += 50;
});
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(2);
handle.scroller.emit('wheel');
@@ -411,14 +391,7 @@ describe('useTopicScrollPersist', () => {
handle.scroller.setScrollTop.mockImplementation(() => {
handle.scrollSize += 50;
});
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await vi.advanceTimersByTimeAsync(1200);
const writes = handle.scroller.setScrollTop.mock.calls.length;
@@ -435,14 +408,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 5000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(4);
@@ -458,14 +424,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
// A few frames in, virtua still hasn't measured items below the fold —
// scrollTo would be clamped, so the hook must keep polling instead.
@@ -481,14 +440,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(3);
expect(handle.scroller.setScrollTop).not.toHaveBeenCalled();
@@ -512,14 +464,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
// 30-frame cap + a few extra for the release rAFs, then the anchor row reveal.
await advanceFrames(80);
@@ -540,14 +485,7 @@ describe('useTopicScrollPersist', () => {
handle.scrollOffset = Math.min(offset, handle.scrollSize - handle.viewportSize);
});
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(40);
@@ -571,14 +509,7 @@ describe('useTopicScrollPersist', () => {
handle.scrollOffset = offset;
});
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(20);
@@ -629,14 +560,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', startingSnapshot);
const handle = createFakeVList({ scrollSize: 6000 });
- const { result } = renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ const { result } = renderHook(() => useTopicScrollFixture(handle));
// Simulate the onScroll volley triggered by the programmatic scrollTo
// landing at offset 0 (because virtua clamped — what used to corrupt
@@ -661,14 +585,7 @@ describe('useTopicScrollPersist', () => {
});
const handle = createFakeVList({ scrollSize: 6000 });
- const { result } = renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ const { result } = renderHook(() => useTopicScrollFixture(handle));
// Wait for restore to land + guard release (2 rAFs after scrollTo).
await advanceFrames(20);
@@ -756,14 +673,7 @@ describe('useTopicScrollPersist', () => {
vi.setSystemTime(fixedNow);
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
- const { result, unmount } = renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ const { result, unmount } = renderHook(() => useTopicScrollFixture(handle));
// Initial restore (no snapshot) settles, then the user scrolls up.
await advanceFrames(10);
@@ -800,14 +710,7 @@ describe('useTopicScrollPersist', () => {
handle.scrollOffset = offset;
});
- const { unmount } = renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ const { unmount } = renderHook(() => useTopicScrollFixture(handle));
// Let the restore land and seed lastKnownRef from where it landed.
await advanceFrames(4);
@@ -853,14 +756,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 10_000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(4);
@@ -915,14 +811,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 20_000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(40);
@@ -943,14 +832,7 @@ describe('useTopicScrollPersist', () => {
handle.scroller.setScrollTop.mockImplementation(() => {
measuredRows += 1;
});
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(30);
@@ -968,14 +850,7 @@ describe('useTopicScrollPersist', () => {
const handle = createFakeVList({ scrollSize: 20_000 });
let shift = 0;
handle.getItemOffset = (index: number) => index * ROW_HEIGHT + shift;
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(2);
handle.scroller.emit('wheel');
@@ -1019,14 +894,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 6000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(4);
@@ -1041,14 +909,7 @@ describe('useTopicScrollPersist', () => {
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 6000 });
- renderHook(() =>
- useTopicScrollPersist({
- contextKey: 'main_agt_1_tpc_a',
- dataSource: ROWS,
- getScroller: () => handle.scroller,
- virtuaRef: refOf(handle),
- }),
- );
+ renderHook(() => useTopicScrollFixture(handle));
await advanceFrames(4);
diff --git a/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts b/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts
index bfa5a25e7c8..de5758268b1 100644
--- a/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts
@@ -9,72 +9,37 @@ vi.mock('@/services/topic', () => ({
}));
// Mock useChatStore
-const mockCancelOperations = vi.fn();
-const mockCancelOperation = vi.fn();
-const mockCancelSendMessageInServer = vi.fn();
-const mockRegenerateUserMessage = vi.fn();
-const mockRegenerateAssistantMessage = vi.fn();
-const mockContinueGenerationMessage = vi.fn();
-const mockDeleteMessage = vi.fn();
-const mockSwitchMessageBranch = vi.fn();
const mockStartOperation = vi.fn(() => ({ operationId: 'test-op-id' }));
const mockCompleteOperation = vi.fn();
const mockAssociateMessageWithOperation = vi.fn();
const mockFailOperation = vi.fn();
const mockExecuteClientAgent = vi.fn();
const mockIsGatewayModeEnabled = vi.fn(() => false);
-const mockExecuteGatewayAgent = vi.fn();
-const mockUpdateTopicMetadata = vi.fn();
-const mockUpdateTopicStatus = vi.fn();
-const mockOpenThreadCreator = vi.fn();
-const mockSourceTopic = {
- status: 'scheduled',
- metadata: { scheduledRun: { kind: 'resume_after_rate_limit' } },
-};
vi.mock('@/store/chat', () => ({
useChatStore: {
- getState: vi.fn(() => ({
- dbMessagesMap: {},
- messagesMap: {
- 'session-1-': [
- { id: 'msg-1', role: 'user', content: 'Hello' },
- { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },
- ],
- },
- topicDataMap: {},
- topicDetailMap: { 'source-topic': mockSourceTopic },
- operations: {},
- operationsByMessage: {},
-
- cancelOperations: mockCancelOperations,
- cancelOperation: mockCancelOperation,
- cancelSendMessageInServer: mockCancelSendMessageInServer,
- regenerateUserMessage: mockRegenerateUserMessage,
- regenerateAssistantMessage: mockRegenerateAssistantMessage,
- continueGenerationMessage: mockContinueGenerationMessage,
- deleteMessage: mockDeleteMessage,
- switchMessageBranch: mockSwitchMessageBranch,
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- executeGatewayAgent: mockExecuteGatewayAgent,
- internal_dispatchTopic: vi.fn(),
- openThreadCreator: mockOpenThreadCreator,
- updateTopicMetadata: mockUpdateTopicMetadata,
- updateTopicStatus: mockUpdateTopicStatus,
- })),
+ getState: vi.fn(),
setState: vi.fn(),
},
}));
+const createContinueChatState = (executeClientAgent = mockExecuteClientAgent) => ({
+ dbMessagesMap: {},
+ messagesMap: {},
+ operations: {},
+ operationsByMessage: {},
+ topicDataMap: {},
+ startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ executeClientAgent,
+ isGatewayModeEnabled: mockIsGatewayModeEnabled,
+});
+
describe('Generation Actions', () => {
beforeEach(() => {
vi.clearAllMocks();
- mockSourceTopic.status = 'scheduled';
});
afterEach(() => {
@@ -84,19 +49,9 @@ describe('Generation Actions', () => {
describe('continueGeneration', () => {
it('should continue generation from assistantGroup message with last child as blockId', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState() as any,
+ );
const context: ConversationContext = {
agentId: 'session-1',
@@ -147,19 +102,9 @@ describe('Generation Actions', () => {
it('should not continue if message is not assistantGroup', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState() as any,
+ );
const context: ConversationContext = {
agentId: 'session-1',
@@ -187,19 +132,9 @@ describe('Generation Actions', () => {
it('should not continue if assistantGroup has no children', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState() as any,
+ );
const context: ConversationContext = {
agentId: 'session-1',
@@ -229,19 +164,9 @@ describe('Generation Actions', () => {
it('should call onBeforeContinue hook and respect false return', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState() as any,
+ );
const onBeforeContinue = vi.fn().mockResolvedValue(false);
@@ -279,19 +204,9 @@ describe('Generation Actions', () => {
it('should call onContinueComplete hook after continuation', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent.mockResolvedValue(undefined),
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState(mockExecuteClientAgent.mockResolvedValue(undefined)) as any,
+ );
const onContinueComplete = vi.fn();
@@ -327,19 +242,9 @@ describe('Generation Actions', () => {
it('should not continue if message is not found', async () => {
// Reset mock to ensure all required functions are available
- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue(
+ createContinueChatState() as any,
+ );
const context: ConversationContext = {
agentId: 'session-1',
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index 36def426471..29da69af224 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -82,6 +82,31 @@ vi.mock('@/store/chat', () => ({
},
}));
+const createContext = (topicId: string | null): ConversationContext => ({
+ agentId: 'session-1',
+ topicId,
+ threadId: null,
+});
+
+const createRegenerationChatState = () => ({
+ dbMessagesMap: {},
+ messagesMap: {},
+ operations: {},
+ operationsByMessage: {},
+ topicDataMap: {},
+
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ executeClientAgent: mockExecuteClientAgent,
+ isGatewayModeEnabled: mockIsGatewayModeEnabled,
+});
+
describe('Generation Actions', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -155,11 +180,7 @@ describe('Generation Actions', () => {
describe('stopGenerating', () => {
it('should cancel all running execAgentRuntime operations', () => {
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -214,11 +235,7 @@ describe('Generation Actions', () => {
it('should call onGenerationStop hook', () => {
const onGenerationStop = vi.fn();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const hooks: ConversationHooks = { onGenerationStop };
const store = createStore({ context, hooks });
@@ -233,11 +250,7 @@ describe('Generation Actions', () => {
describe('cancelOperation', () => {
it('should cancel specific operation via ChatStore', () => {
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const store = createStore({ context });
@@ -250,11 +263,7 @@ describe('Generation Actions', () => {
it('should call onOperationCancelled hook', () => {
const onOperationCancelled = vi.fn();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const hooks: ConversationHooks = { onOperationCancelled };
const store = createStore({ context, hooks });
@@ -269,11 +278,7 @@ describe('Generation Actions', () => {
describe('clearOperations', () => {
it('should be a no-op since operations are managed by ChatStore', () => {
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const store = createStore({ context });
@@ -287,11 +292,7 @@ describe('Generation Actions', () => {
});
describe('retryFailedAssistantStep', () => {
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const mockChatStore = async () => {
const { useChatStore } = await import('@/store/chat');
@@ -481,24 +482,7 @@ describe('Generation Actions', () => {
it('should create operation with context and pass operationId to deleteMessage', async () => {
// Re-setup mock to ensure all required functions are available
const { useChatStore } = await import('@/store/chat');
- vi.mocked(useChatStore.getState).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
-
- cancelOperations: mockCancelOperations,
- cancelOperation: mockCancelOperation,
- deleteMessage: mockDeleteMessage,
- switchMessageBranch: mockSwitchMessageBranch,
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(useChatStore.getState).mockReturnValue(createRegenerationChatState() as any);
const context: ConversationContext = {
agentId: 'session-1',
@@ -635,11 +619,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const store = createStore({ context });
@@ -936,24 +916,7 @@ describe('Generation Actions', () => {
it('should pass operationId to switchMessageBranch for correct context', async () => {
// Re-setup mock with all required properties
const { useChatStore } = await import('@/store/chat');
- vi.mocked(useChatStore.getState).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
-
- cancelOperations: mockCancelOperations,
- cancelOperation: mockCancelOperation,
- deleteMessage: mockDeleteMessage,
- switchMessageBranch: mockSwitchMessageBranch,
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(useChatStore.getState).mockReturnValue(createRegenerationChatState() as any);
const context: ConversationContext = {
agentId: 'session-1',
@@ -997,24 +960,7 @@ describe('Generation Actions', () => {
it('should pass context to executeClientAgent', async () => {
// Re-setup mock with all required properties
const { useChatStore } = await import('@/store/chat');
- vi.mocked(useChatStore.getState).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
-
- cancelOperations: mockCancelOperations,
- cancelOperation: mockCancelOperation,
- deleteMessage: mockDeleteMessage,
- switchMessageBranch: mockSwitchMessageBranch,
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(useChatStore.getState).mockReturnValue(createRegenerationChatState() as any);
const context: ConversationContext = {
agentId: 'session-1',
@@ -1070,11 +1016,7 @@ describe('Generation Actions', () => {
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1126,11 +1068,7 @@ describe('Generation Actions', () => {
});
vi.mocked(useChatStore.getState).mockReturnValue(chatState);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1153,30 +1091,9 @@ describe('Generation Actions', () => {
it('should restore mention-based initialContext when regenerating a user message', async () => {
const { useChatStore } = await import('@/store/chat');
- vi.mocked(useChatStore.getState).mockReturnValue({
- dbMessagesMap: {},
- messagesMap: {},
- operations: {},
- operationsByMessage: {},
- topicDataMap: {},
-
- cancelOperations: mockCancelOperations,
- cancelOperation: mockCancelOperation,
- deleteMessage: mockDeleteMessage,
- switchMessageBranch: mockSwitchMessageBranch,
- startOperation: mockStartOperation,
- associateMessageWithOperation: mockAssociateMessageWithOperation,
- completeOperation: mockCompleteOperation,
- failOperation: mockFailOperation,
- executeClientAgent: mockExecuteClientAgent,
- isGatewayModeEnabled: mockIsGatewayModeEnabled,
- } as any);
+ vi.mocked(useChatStore.getState).mockReturnValue(createRegenerationChatState() as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1246,11 +1163,7 @@ describe('Generation Actions', () => {
switchMessageBranch: mockSwitchMessageBranch,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1319,11 +1232,7 @@ describe('Generation Actions', () => {
} as any);
const onRegenerateComplete = vi.fn();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context, hooks: { onRegenerateComplete } });
@@ -1365,11 +1274,7 @@ describe('Generation Actions', () => {
switchMessageBranch: mockSwitchMessageBranch,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1408,11 +1313,7 @@ describe('Generation Actions', () => {
associateMessageWithOperation: mockAssociateMessageWithOperation,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const store = createStore({ context });
@@ -1459,11 +1360,7 @@ describe('Generation Actions', () => {
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: null,
- threadId: null,
- };
+ const context: ConversationContext = createContext(null);
const store = createStore({ context });
@@ -1561,11 +1458,7 @@ describe('Generation Actions', () => {
it('routes regenerateUserMessage through executeHeterogeneousAgent with imageList + parentOperationId', async () => {
const { mockRefreshMessages } = await setupHeteroChatStore();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1848,11 +1741,7 @@ describe('Generation Actions', () => {
const { mockHeteroStartOperation, mockAssociateMessageWithOperation } =
await setupHeteroChatStore();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
@@ -1900,11 +1789,7 @@ describe('Generation Actions', () => {
void mockHeteroStartOperation;
const onRegenerateComplete = vi.fn();
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context, hooks: { onRegenerateComplete } });
@@ -1956,11 +1841,7 @@ describe('Generation Actions', () => {
isGatewayModeEnabled: vi.fn(() => false),
} as any);
- const context: ConversationContext = {
- agentId: 'session-1',
- topicId: 'topic-1',
- threadId: null,
- };
+ const context: ConversationContext = createContext('topic-1');
const store = createStore({ context });
diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.ts
index fc3cf9189ef..c5d116f3050 100644
--- a/src/features/Conversation/store/slices/message/action/crud.test.ts
+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts
@@ -7,6 +7,54 @@ import { useChatStore } from '@/store/chat';
import { type ConversationContext } from '../../../../types';
import { createStore } from '../../../index';
+import type { MessageDispatch } from '../../data/reducer';
+
+const emptyMessageResult = (): { success: true; messages: UIChatMessage[] } => ({
+ success: true,
+ messages: [],
+});
+
+const toolMessage = (): Extract<MessageDispatch, { type: 'createMessage' }> => ({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: '',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ plugin: {
+ apiName: 'test',
+ arguments: '{"key": "old"}',
+ identifier: 'test-plugin',
+ type: 'default',
+ },
+ },
+});
+
+const assistantTool = (): Extract<MessageDispatch, { type: 'addMessageTool' }> => ({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "old"}',
+ },
+});
+
+const assistantMessage = (): Extract<MessageDispatch, { type: 'createMessage' }> => ({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+});
+
+const userMessage = (): Extract<MessageDispatch, { type: 'createMessage' }> => ({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
+});
// Mock conversation-flow parse function (必须 mock,因为这是外部库)
vi.mock('@lobechat/conversation-flow', () => ({
@@ -144,10 +192,7 @@ describe('Message CRUD Actions', () => {
// Use removeMessage for single message deletion
const removeMessageSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessage')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -178,10 +223,7 @@ describe('Message CRUD Actions', () => {
it('should delete assistantGroup with children and tool results', async () => {
const removeMessagesSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessages')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -375,10 +417,7 @@ describe('Message CRUD Actions', () => {
it('should delete a single DB message directly', async () => {
const removeMessageSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessage')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -422,10 +461,7 @@ describe('Message CRUD Actions', () => {
it('should not handle assistantGroup aggregation like deleteMessage does', async () => {
const removeMessageSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessage')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -466,19 +502,12 @@ describe('Message CRUD Actions', () => {
it('should delete multiple messages', async () => {
const removeMessagesSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessages')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'msg-1',
- value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(userMessage());
store.getState().internal_dispatchMessage({
type: 'createMessage',
id: 'msg-2',
@@ -500,10 +529,7 @@ describe('Message CRUD Actions', () => {
it('should delete tool message and remove from parent', async () => {
const removeMessageSpy = vi
.spyOn(messageServiceModule.messageService, 'removeMessage')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -558,11 +584,7 @@ describe('Message CRUD Actions', () => {
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'msg-1',
- value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(userMessage());
});
await act(async () => {
@@ -594,11 +616,7 @@ describe('Message CRUD Actions', () => {
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'msg-1',
- value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(userMessage());
});
await act(async () => {
@@ -617,19 +635,12 @@ describe('Message CRUD Actions', () => {
it('should update message metadata', async () => {
const updateMessageMetadataSpy = vi
.spyOn(messageServiceModule.messageService, 'updateMessageMetadata')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'msg-1',
- value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(userMessage());
});
await act(async () => {
@@ -648,10 +659,7 @@ describe('Message CRUD Actions', () => {
it('should toggle message collapsed state', async () => {
const updateMessageMetadataSpy = vi
.spyOn(messageServiceModule.messageService, 'updateMessageMetadata')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -712,10 +720,9 @@ describe('Message CRUD Actions', () => {
describe('modifyMessageContent', () => {
it('should modify message content and call hook', async () => {
- vi.spyOn(messageServiceModule.messageService, 'updateMessage').mockResolvedValue({
- success: true,
- messages: [],
- });
+ vi.spyOn(messageServiceModule.messageService, 'updateMessage').mockResolvedValue(
+ emptyMessageResult(),
+ );
const onMessageModified = vi.fn();
@@ -748,10 +755,7 @@ describe('Message CRUD Actions', () => {
it('should add tool to message', async () => {
const updateMessageSpy = vi
.spyOn(messageServiceModule.messageService, 'updateMessage')
- .mockResolvedValue({
- success: true,
- messages: [],
- });
+ .mockResolvedValue(emptyMessageResult());
const store = createTestStore();
@@ -794,39 +798,9 @@ describe('Message CRUD Actions', () => {
// Create an assistant message with a tool, and a tool message
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'assistant-1',
- value: { content: '', role: 'assistant', sessionId: 'test-session' },
- });
- store.getState().internal_dispatchMessage({
- type: 'addMessageTool',
- id: 'assistant-1',
- value: {
- id: 'tool-call-1',
- type: 'default',
- identifier: 'test',
- apiName: 'testFunc',
- arguments: '{"key": "old"}',
- },
- });
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'tool-msg-1',
- value: {
- content: '',
- role: 'tool',
- sessionId: 'test-session',
- parentId: 'assistant-1',
- tool_call_id: 'tool-call-1',
- plugin: {
- apiName: 'test',
- arguments: '{"key": "old"}',
- identifier: 'test-plugin',
- type: 'default',
- },
- },
- });
+ store.getState().internal_dispatchMessage(assistantMessage());
+ store.getState().internal_dispatchMessage(assistantTool());
+ store.getState().internal_dispatchMessage(toolMessage());
});
await act(async () => {
@@ -892,11 +866,7 @@ describe('Message CRUD Actions', () => {
// Create an assistant message with a tool, but NO tool message (simulating intervention pending)
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'assistant-1',
- value: { content: '', role: 'assistant', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(assistantMessage());
store.getState().internal_dispatchMessage({
type: 'addMessageTool',
id: 'assistant-1',
@@ -941,39 +911,9 @@ describe('Message CRUD Actions', () => {
// Create assistant with tool and tool message
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'assistant-1',
- value: { content: '', role: 'assistant', sessionId: 'test-session' },
- });
- store.getState().internal_dispatchMessage({
- type: 'addMessageTool',
- id: 'assistant-1',
- value: {
- id: 'tool-call-1',
- type: 'default',
- identifier: 'test',
- apiName: 'testFunc',
- arguments: '{"key": "old"}',
- },
- });
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'tool-msg-1',
- value: {
- content: '',
- role: 'tool',
- sessionId: 'test-session',
- parentId: 'assistant-1',
- tool_call_id: 'tool-call-1',
- plugin: {
- apiName: 'test',
- arguments: '{"key": "old"}',
- identifier: 'test-plugin',
- type: 'default',
- },
- },
- });
+ store.getState().internal_dispatchMessage(assistantMessage());
+ store.getState().internal_dispatchMessage(assistantTool());
+ store.getState().internal_dispatchMessage(toolMessage());
});
// Start update (don't await yet)
@@ -1008,11 +948,7 @@ describe('Message CRUD Actions', () => {
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'assistant-1',
- value: { content: '', role: 'assistant', sessionId: 'test-session' },
- });
+ store.getState().internal_dispatchMessage(assistantMessage());
store.getState().internal_dispatchMessage({
type: 'addMessageTool',
id: 'assistant-1',
@@ -1070,39 +1006,9 @@ describe('Message CRUD Actions', () => {
const store = createTestStore();
act(() => {
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'assistant-1',
- value: { content: '', role: 'assistant', sessionId: 'test-session' },
- });
- store.getState().internal_dispatchMessage({
- type: 'addMessageTool',
- id: 'assistant-1',
- value: {
- id: 'tool-call-1',
- type: 'default',
- identifier: 'test',
- apiName: 'testFunc',
- arguments: '{"key": "old"}',
- },
- });
- store.getState().internal_dispatchMessage({
- type: 'createMessage',
- id: 'tool-msg-1',
- value: {
- content: '',
- role: 'tool',
- sessionId: 'test-session',
- parentId: 'assistant-1',
- tool_call_id: 'tool-call-1',
- plugin: {
- apiName: 'test',
- arguments: '{"key": "old"}',
- identifier: 'test-plugin',
- type: 'default',
- },
- },
- });
+ store.getState().internal_dispatchMessage(assistantMessage());
+ store.getState().internal_dispatchMessage(assistantTool());
+ store.getState().internal_dispatchMessage(toolMessage());
});
// Start update without awaiting (using toolCallId)
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
index 80dc41db8d8..1d7c6289615 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -154,6 +154,31 @@ const getMenuItem = (
return found;
};
+type PublicAgentMenuOptions = Partial<
+ Pick<
+ Parameters<typeof useAgentDropdownMenu>[0],
+ 'id' | 'labelsEnabled' | 'sidebarVisibilityEnabled'
+ >
+>;
+
+const renderPublicAgentMenu = (
+ userId: string,
+ { id = 'agent-1', labelsEnabled, sidebarVisibilityEnabled }: PublicAgentMenuOptions = {},
+) =>
+ renderHook(() =>
+ useAgentDropdownMenu({
+ group: undefined,
+ id,
+ ...(labelsEnabled === undefined ? {} : { labelsEnabled }),
+ openCreateGroupModal: vi.fn(),
+ pinned: false,
+ ...(sidebarVisibilityEnabled === undefined ? {} : { sidebarVisibilityEnabled }),
+ title: 'Public Agent',
+ userId,
+ visibility: 'public',
+ }),
+ );
+
describe('useAgentDropdownMenu', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -167,17 +192,7 @@ describe('useAgentDropdownMenu', () => {
});
it('keeps non-config actions available to a use-only Workspace member', () => {
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1');
expect(getMenuKeys(result.current())).toEqual([
'pin',
@@ -190,18 +205,7 @@ describe('useAgentDropdownMenu', () => {
});
it('shows the Labels submenu only where it is enabled (the agents list page)', () => {
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- labelsEnabled: true,
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1', { labelsEnabled: true });
expect(getMenuKeys(result.current())).toContain('labels');
});
@@ -212,18 +216,7 @@ describe('useAgentDropdownMenu', () => {
// server agrees (role scope only, no per-resource check).
mocks.canEditResource = false;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- labelsEnabled: true,
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1', { labelsEnabled: true });
expect(getMenuKeys(result.current())).toContain('labels');
});
@@ -233,18 +226,7 @@ describe('useAgentDropdownMenu', () => {
// this is the line labelling still respects.
mocks.canEdit = false;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- labelsEnabled: true,
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1', { labelsEnabled: true });
expect(getMenuKeys(result.current())).not.toContain('labels');
});
@@ -253,17 +235,7 @@ describe('useAgentDropdownMenu', () => {
mocks.canCreate = false;
mocks.canEdit = false;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1');
expect(getMenuKeys(result.current())).toEqual([
'hideFromSidebar',
@@ -273,17 +245,7 @@ describe('useAgentDropdownMenu', () => {
});
it('copies the Agent ID from the row menu', async () => {
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agt_sidebar',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'creator-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('creator-1', { id: 'agt_sidebar' });
const stopPropagation = vi.fn();
await getMenuItem(result.current(), 'copyAgentId').onClick({ domEvent: { stopPropagation } });
@@ -294,17 +256,7 @@ describe('useAgentDropdownMenu', () => {
});
it('hides an Agent through the caller sidebar preference', async () => {
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
const hideItem = (result.current() ?? []).find(
(item) => item && typeof item === 'object' && item.key === 'hideFromSidebar',
@@ -319,18 +271,7 @@ describe('useAgentDropdownMenu', () => {
});
it('omits the hide action for lists that ignore the sidebar preference', () => {
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- sidebarVisibilityEnabled: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1', { sidebarVisibilityEnabled: false });
const keys = (result.current() ?? []).map((item) =>
item && typeof item === 'object' && 'key' in item ? item.key : undefined,
@@ -350,17 +291,7 @@ describe('useAgentDropdownMenu', () => {
}),
);
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
const deleteItem = (result.current() ?? []).find(
(item) => item && typeof item === 'object' && 'key' in item && item.key === 'delete',
@@ -377,17 +308,7 @@ describe('useAgentDropdownMenu', () => {
it('stays native-eligible (string labels only, including the Move to Category submenu)', () => {
mocks.canEditResource = true;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
expect(canGoNative(result.current() ?? [])).toBe(true);
});
@@ -398,17 +319,7 @@ describe('useAgentDropdownMenu', () => {
mocks.canManageResource = true;
mocks.transferMenuItems = [{ key: 'copy-agent', label: 'Copy to…' }];
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
expect(getMenuLayout(result.current())).toEqual([
'pin',
@@ -431,17 +342,7 @@ describe('useAgentDropdownMenu', () => {
it('hides the Permission shortcut from a non-author member who can configure the agent', () => {
mocks.canEditResource = true;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
expect(getMenuKeys(result.current())).not.toContain('permission');
});
@@ -450,17 +351,7 @@ describe('useAgentDropdownMenu', () => {
mocks.canEditResource = true;
mocks.canManageResource = true;
- const { result } = renderHook(() =>
- useAgentDropdownMenu({
- group: undefined,
- id: 'agent-1',
- openCreateGroupModal: vi.fn(),
- pinned: false,
- title: 'Public Agent',
- userId: 'member-1',
- visibility: 'public',
- }),
- );
+ const { result } = renderPublicAgentMenu('member-1');
const permissionItem = (result.current() ?? []).find(
(item) => item && typeof item === 'object' && 'key' in item && item.key === 'permission',
diff --git a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
index c516c32553b..a64953d6a8b 100644
--- a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
@@ -50,67 +50,33 @@ vi.mock('@/libs/analytics/client', () => ({
vi.mock('@lobehub/ui', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
- const factories: ((original: typeof importOriginal) => unknown)[] = [
- async (importOriginal) => ({
- ...(await importOriginal<object>()),
- Button: ({
- children,
- disabled,
- loading,
- onClick,
- type,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- loading?: boolean;
- onClick?: () => void;
- type?: string;
- }) => (
- <button
- data-button-loading={loading ? 'true' : undefined}
- data-button-type={type}
- disabled={disabled}
- type="button"
- onClick={onClick}
- >
- {children}
- </button>
- ),
- }),
- async (importOriginal) => ({
- ...(await importOriginal<object>()),
- Button: ({
- children,
- disabled,
- loading,
- onClick,
- type,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- loading?: boolean;
- onClick?: () => void;
- type?: string;
- }) => (
- <button
- data-button-loading={loading ? 'true' : undefined}
- data-button-type={type}
- disabled={disabled}
- type="button"
- onClick={onClick}
- >
- {children}
- </button>
- ),
- createModal: vi.fn(),
- }),
- ];
- const merged: Record<string, unknown> = { ...actual };
- for (const factory of factories) {
- const part = (await factory(importOriginal)) as Record<string, unknown>;
- for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
- }
- return merged;
+ return {
+ ...actual,
+ Button: ({
+ children,
+ disabled,
+ loading,
+ onClick,
+ type,
+ }: {
+ children?: ReactNode;
+ disabled?: boolean;
+ loading?: boolean;
+ onClick?: () => void;
+ type?: string;
+ }) => (
+ <button
+ data-button-loading={loading ? 'true' : undefined}
+ data-button-type={type}
+ disabled={disabled}
+ type="button"
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ ),
+ createModal: vi.fn(),
+ };
});
vi.mock('@/services/marketApi', () => ({
@@ -230,6 +196,23 @@ vi.mock('@/store/tool', () => ({
}),
}));
+const createResumeSkillSearchResult = () => ({
+ currentPage: 1,
+ items: [
+ {
+ createdAt: '2026-01-01',
+ description: 'Review and improve resumes with a reusable checklist.',
+ identifier: 'resume-reviewer',
+ installCount: 12,
+ name: 'Resume Reviewer',
+ updatedAt: '2026-01-01',
+ },
+ ],
+ pageSize: 3,
+ totalCount: 1,
+ totalPages: 1,
+});
+
const renderModal = (type: 'agent' | 'group' = 'agent') => {
const onClose = vi.fn();
const onCreateBlank = vi.fn().mockResolvedValue(undefined);
@@ -409,22 +392,7 @@ describe('CreateAgentModal analytics', () => {
});
it('interrupts high-confidence skill prompts with a stronger skill recommendation', async () => {
- marketApiMocks.searchSkill.mockResolvedValueOnce({
- currentPage: 1,
- items: [
- {
- createdAt: '2026-01-01',
- description: 'Review and improve resumes with a reusable checklist.',
- identifier: 'resume-reviewer',
- installCount: 12,
- name: 'Resume Reviewer',
- updatedAt: '2026-01-01',
- },
- ],
- pageSize: 3,
- totalCount: 1,
- totalPages: 1,
- });
+ marketApiMocks.searchSkill.mockResolvedValueOnce(createResumeSkillSearchResult());
const { onSubmit } = renderModal();
fireEvent.change(screen.getByLabelText('chat input'), {
@@ -488,22 +456,7 @@ describe('CreateAgentModal analytics', () => {
});
it('interrupts role-framed reusable prompts when the role maps to a skill workflow', async () => {
- marketApiMocks.searchSkill.mockResolvedValueOnce({
- currentPage: 1,
- items: [
- {
- createdAt: '2026-01-01',
- description: 'Review and improve resumes with a reusable checklist.',
- identifier: 'resume-reviewer',
- installCount: 12,
- name: 'Resume Reviewer',
- updatedAt: '2026-01-01',
- },
- ],
- pageSize: 3,
- totalCount: 1,
- totalPages: 1,
- });
+ marketApiMocks.searchSkill.mockResolvedValueOnce(createResumeSkillSearchResult());
const { onSubmit } = renderModal();
fireEvent.change(screen.getByLabelText('chat input'), {
@@ -570,22 +523,7 @@ describe('CreateAgentModal analytics', () => {
});
it('shows an installing state while adding the suggested skill', async () => {
- marketApiMocks.searchSkill.mockResolvedValueOnce({
- currentPage: 1,
- items: [
- {
- createdAt: '2026-01-01',
- description: 'Review and improve resumes with a reusable checklist.',
- identifier: 'resume-reviewer',
- installCount: 12,
- name: 'Resume Reviewer',
- updatedAt: '2026-01-01',
- },
- ],
- pageSize: 3,
- totalCount: 1,
- totalPages: 1,
- });
+ marketApiMocks.searchSkill.mockResolvedValueOnce(createResumeSkillSearchResult());
let resolveImport: (value: {
skill: { id: string; name: string };
status: string;
@@ -615,22 +553,7 @@ describe('CreateAgentModal analytics', () => {
});
it('shows a completed skill state after installing the recommended skill', async () => {
- marketApiMocks.searchSkill.mockResolvedValueOnce({
- currentPage: 1,
- items: [
- {
- createdAt: '2026-01-01',
- description: 'Review and improve resumes with a reusable checklist.',
- identifier: 'resume-reviewer',
- installCount: 12,
- name: 'Resume Reviewer',
- updatedAt: '2026-01-01',
- },
- ],
- pageSize: 3,
- totalCount: 1,
- totalPages: 1,
- });
+ marketApiMocks.searchSkill.mockResolvedValueOnce(createResumeSkillSearchResult());
const { onClose, onOpenSkills, onSubmit, onTryInLobeAI, update } = renderModal();
fireEvent.change(screen.getByLabelText('chat input'), {
@@ -681,22 +604,7 @@ describe('CreateAgentModal analytics', () => {
});
it('keeps the suggestion visible when installing the recommended skill fails', async () => {
- marketApiMocks.searchSkill.mockResolvedValueOnce({
- currentPage: 1,
- items: [
- {
- createdAt: '2026-01-01',
- description: 'Review and improve resumes with a reusable checklist.',
- identifier: 'resume-reviewer',
- installCount: 12,
- name: 'Resume Reviewer',
- updatedAt: '2026-01-01',
- },
- ],
- pageSize: 3,
- totalCount: 1,
- totalPages: 1,
- });
+ marketApiMocks.searchSkill.mockResolvedValueOnce(createResumeSkillSearchResult());
skillServiceMocks.importFromMarket.mockRejectedValueOnce(new Error('Import failed'));
const { onClose } = renderModal();
diff --git a/src/features/MCPApp/appHost.test.ts b/src/features/MCPApp/appHost.test.ts
index 45849ef64d1..66fff1dcb79 100644
--- a/src/features/MCPApp/appHost.test.ts
+++ b/src/features/MCPApp/appHost.test.ts
@@ -322,18 +322,6 @@ describe('connectAppView', () => {
expect(confirmAppToolCall).toHaveBeenCalledTimes(4);
});
- it('withdraws its pending approvals when the view goes away', async () => {
- confirmAppToolCall.mockReturnValue(new Promise(() => {}));
- const { call, dispose } = setup();
-
- await call(1, 'Rome');
- const { signal } = confirmAppToolCall.mock.calls[0][0] as { signal: AbortSignal };
- expect(signal.aborted).toBe(false);
-
- dispose();
- expect(signal.aborted).toBe(true);
- });
-
it('drops an approval once the view stops waiting for that request', async () => {
// Like the real confirm: an aborted approval resolves `false`, whatever the user clicks later
const settle = ({ signal }: { signal: AbortSignal }) =>
diff --git a/src/features/MCPApp/sendAppMessage.test.ts b/src/features/MCPApp/sendAppMessage.test.ts
index ecbb2913085..5e6a5b8cb11 100644
--- a/src/features/MCPApp/sendAppMessage.test.ts
+++ b/src/features/MCPApp/sendAppMessage.test.ts
@@ -4,34 +4,11 @@ import { describe, expect, it, vi } from 'vitest';
import { sendAppMessage } from './sendAppMessage';
describe('sendAppMessage', () => {
- it('does not acknowledge a send that finishes without accepting the message', async () => {
+ it('preserves the draft when a send finishes without accepting the message', async () => {
// Gateway task creation can fail internally without rejecting the outer send.
const send = vi.fn().mockResolvedValue(undefined);
await expect(sendAppMessage(send, 'Follow up', 'weather')).resolves.toBe(false);
- });
-
- it('acknowledges acceptance without waiting for the agent run to finish', async () => {
- let params!: SendMessageParams;
- const send = vi.fn((value: SendMessageParams) => {
- params = value;
- return new Promise<void>(() => {});
- });
- const result = sendAppMessage(send, 'Follow up', 'weather');
-
- expect(params.message).toBe('Follow up');
- expect(params.metadata?.mcpAppSource).toEqual({ identifier: 'weather' });
- expect(params.onMessageAccepted).toBeTypeOf('function');
- params.onMessageAccepted?.();
-
- await expect(result).resolves.toBe(true);
- });
-
- it('sends as a separate turn that leaves the composer draft alone', async () => {
- const send = vi.fn().mockResolvedValue(undefined);
-
- await sendAppMessage(send, 'Follow up', 'weather');
-
expect(send).toHaveBeenCalledWith(expect.objectContaining({ preserveComposer: true }));
});
@@ -44,7 +21,7 @@ describe('sendAppMessage', () => {
expect(send).toHaveBeenCalledWith(expect.objectContaining({ signal: view.signal }));
});
- it('does not acknowledge before the acceptance callback fires', async () => {
+ it('waits for acceptance without waiting for the agent run to finish', async () => {
let params!: SendMessageParams;
const send = vi.fn((value: SendMessageParams) => {
params = value;
@@ -55,6 +32,8 @@ describe('sendAppMessage', () => {
await Promise.resolve();
expect(settled).not.toHaveBeenCalled();
+ expect(params.message).toBe('Follow up');
+ expect(params.metadata?.mcpAppSource).toEqual({ identifier: 'weather' });
expect(params.onMessageAccepted).toBeTypeOf('function');
params.onMessageAccepted?.();
await result;
diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsx
index 7f89f7603b4..bd70b92a91f 100644
--- a/src/features/Settings/labs/index.test.tsx
+++ b/src/features/Settings/labs/index.test.tsx
@@ -136,12 +136,6 @@ describe('Labs settings page', () => {
expect(screen.queryByText('features.integrations.title')).toBeNull();
});
- it('renders the topic acceptance (tray) lab toggle', () => {
- renderPage();
-
- expect(screen.getByText('features.goals.title')).toBeDefined();
- });
-
it('does not render released task verify as a lab toggle', () => {
renderPage();
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
index 5f64595d164..cd7246bebd0 100644
--- a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
@@ -65,7 +65,7 @@ afterEach(() => {
describe('workspace settings useCategory', () => {
// Account-level tabs follow the user, not the workspace, so they are shown
// to every role — including viewers with no workspace permissions.
- it('mirrors the account-level tabs in a leading Account group for every role', () => {
+ it('shows Account and System tabs without workspace permissions', () => {
mocks.canCreateContent = false;
mocks.canManageWorkspace = false;
mocks.canViewBilling = false;
@@ -90,14 +90,7 @@ describe('workspace settings useCategory', () => {
expect(generalGroup?.items.map((item) => item.key)).not.toContain(
WorkspaceSettingsTabs.Profile,
);
- });
-
- it('shows Trash and About in a System group for every role', () => {
- mocks.canCreateContent = false;
- mocks.canManageWorkspace = false;
- mocks.canViewBilling = false;
- const { result } = renderHook(() => useWorkspaceSettingCategory(), { wrapper });
const systemGroup = result.current.find(
(group) => group.key === WorkspaceSettingsGroupKey.System,
);
@@ -135,6 +128,33 @@ describe('workspace settings useCategory', () => {
expect(generalGroup?.items.map((item) => item.key)).not.toContain(
WorkspaceSettingsTabs.Devices,
);
+
+ const adminGroup = result.current.find(
+ (group) => group.key === WorkspaceSettingsGroupKey.Admin,
+ );
+ const developerGroup = result.current.find(
+ (group) => group.key === WorkspaceSettingsGroupKey.Developer,
+ );
+
+ expect(developerGroup?.items.map((item) => item.key)).toContain(WorkspaceSettingsTabs.APIKey);
+ expect(adminGroup?.items.map((item) => item.key)).not.toContain(WorkspaceSettingsTabs.APIKey);
+
+ const itemKeys = result.current.flatMap((group) => group.items.map((item) => item.key));
+
+ expect(itemKeys).not.toContain(WorkspaceSettingsTabs.OAuthApps);
+
+ // Admin-or-higher reads the billing numbers; the pages keep the
+ // money-moving controls behind the narrower manage_subscription gate.
+ expect(itemKeys).toContain(WorkspaceSettingsTabs.Credits);
+ expect(itemKeys).toContain(WorkspaceSettingsTabs.Billing);
+
+ const accountGroup = result.current.find(
+ (group) => group.key === WorkspaceSettingsGroupKey.Account,
+ );
+
+ expect(accountGroup?.items.map((item) => item.key)).toContain(
+ WorkspaceSettingsTabs.Integrations,
+ );
});
// Accounts are shared capacity every agent routes onto, so managing them is
@@ -146,10 +166,6 @@ describe('workspace settings useCategory', () => {
expect(getItemKeys()).toContain(WorkspaceSettingsTabs.Devices);
});
- it('hides OAuth Apps by default', () => {
- expect(getItemKeys()).not.toContain(WorkspaceSettingsTabs.OAuthApps);
- });
-
it('shows OAuth Apps when the Labs preference is enabled', () => {
useUserStore.setState({
preference: {
@@ -174,19 +190,6 @@ describe('workspace settings useCategory', () => {
);
});
- it('places API Key in the Developer group', () => {
- const { result } = renderHook(() => useWorkspaceSettingCategory(), { wrapper });
- const adminGroup = result.current.find(
- (group) => group.key === WorkspaceSettingsGroupKey.Admin,
- );
- const developerGroup = result.current.find(
- (group) => group.key === WorkspaceSettingsGroupKey.Developer,
- );
-
- expect(developerGroup?.items.map((item) => item.key)).toContain(WorkspaceSettingsTabs.APIKey);
- expect(adminGroup?.items.map((item) => item.key)).not.toContain(WorkspaceSettingsTabs.APIKey);
- });
-
it('exposes API Key settings to members', () => {
mocks.canManageWorkspace = false;
@@ -238,15 +241,6 @@ describe('workspace settings useCategory', () => {
]);
});
- // Admin-or-higher reads the billing numbers; the pages keep the
- // money-moving controls behind the narrower manage_subscription gate.
- it('shows Credits and Billing to roles that may view billing', () => {
- const itemKeys = getItemKeys();
-
- expect(itemKeys).toContain(WorkspaceSettingsTabs.Credits);
- expect(itemKeys).toContain(WorkspaceSettingsTabs.Billing);
- });
-
it('hides financial settings below Admin', () => {
mocks.canViewBilling = false;
@@ -257,15 +251,4 @@ describe('workspace settings useCategory', () => {
expect(itemKeys).toContain(WorkspaceSettingsTabs.Plans);
expect(itemKeys).toContain(WorkspaceSettingsTabs.Usage);
});
-
- it('lists Integrations with the account tabs without any Labs flag', () => {
- const { result } = renderHook(() => useWorkspaceSettingCategory(), { wrapper });
- const accountGroup = result.current.find(
- (group) => group.key === WorkspaceSettingsGroupKey.Account,
- );
-
- expect(accountGroup?.items.map((item) => item.key)).toContain(
- WorkspaceSettingsTabs.Integrations,
- );
- });
});
diff --git a/src/libs/oidc-provider/provider.test.ts b/src/libs/oidc-provider/provider.test.ts
index 5c4f9deee49..e666afc1f5d 100644
--- a/src/libs/oidc-provider/provider.test.ts
+++ b/src/libs/oidc-provider/provider.test.ts
@@ -45,7 +45,6 @@ describe('OIDC Provider - Market Client Integration', () => {
const { defaultClients } = await import('./config');
const marketClient = defaultClients.find((c) => c.client_id === MARKET_CLIENT_ID);
- expect(marketClient).toBeDefined();
expect(marketClient?.client_id).toBe('lobehub-market');
expect(marketClient?.client_name).toBe('LobeHub Marketplace');
@@ -198,7 +197,6 @@ describe('OIDC Provider - Market Client Integration', () => {
}));
const module = await import('./provider');
- expect(module.createOIDCProvider).toBeDefined();
expect(typeof module.createOIDCProvider).toBe('function');
vi.doUnmock('@/envs/app');
diff --git a/src/services/import/index.test.ts b/src/services/import/index.test.ts
index 74e3a9ea420..816dfaa27f5 100644
--- a/src/services/import/index.test.ts
+++ b/src/services/import/index.test.ts
@@ -42,6 +42,26 @@ vi.mock('@/utils/uuid', () => ({
uuid: () => 'mock-uuid-123',
}));
+const createMessageData = (count: number) => ({
+ messages: Array.from({ length: count }).fill({ id: '1', content: 'test' }),
+ version: 1,
+});
+
+const createUploadResult = () => ({
+ success: true as const,
+ data: {
+ path: 'import_config/mock-uuid-123.json',
+ filename: 'mock-uuid-123.json',
+ dirname: 'import_config',
+ date: '2024-01-01',
+ },
+});
+
+const createImportResult = <T extends Record<string, unknown>>(results: T) => ({
+ results,
+ success: true as const,
+});
+
describe('ImportService', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -78,15 +98,12 @@ describe('ImportService', () => {
version: 1,
};
- const mockResult = {
- results: {
- messages: { added: 100, errors: 0, skips: 0 },
- sessionGroups: { added: 50, errors: 0, skips: 0 },
- sessions: { added: 100, errors: 0, skips: 0 },
- topics: { added: 100, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ messages: { added: 100, errors: 0, skips: 0 },
+ sessionGroups: { added: 50, errors: 0, skips: 0 },
+ sessions: { added: 100, errors: 0, skips: 0 },
+ topics: { added: 100, errors: 0, skips: 0 },
+ });
vi.mocked(lambdaClient.importer.importByPost.mutate).mockResolvedValue(mockResult);
@@ -106,10 +123,7 @@ describe('ImportService', () => {
});
it('should handle error during small dataset import', async () => {
- const mockData = {
- messages: Array.from({ length: 100 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(100);
const mockError = {
data: {
@@ -142,17 +156,11 @@ describe('ImportService', () => {
});
it('should calculate duration correctly', async () => {
- const mockData = {
- messages: Array.from({ length: 10 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(10);
- const mockResult = {
- results: {
- messages: { added: 10, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ messages: { added: 10, errors: 0, skips: 0 },
+ });
let callCount = 0;
vi.spyOn(Date, 'now').mockImplementation(() => {
@@ -174,27 +182,13 @@ describe('ImportService', () => {
describe('large dataset (>= 500 items)', () => {
it('should upload to S3 and import via file when total items >= 500', async () => {
- const mockData = {
- messages: Array.from({ length: 500 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(500);
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
- const mockImportResult = {
- results: {
- messages: { added: 500, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockImportResult = createImportResult({
+ messages: { added: 500, errors: 0, skips: 0 },
+ });
vi.mocked(uploadService.uploadDataToS3).mockResolvedValue(mockUploadResult as any);
vi.mocked(lambdaClient.importer.importByFile.mutate).mockResolvedValue(mockImportResult);
@@ -225,10 +219,7 @@ describe('ImportService', () => {
});
it('should handle upload error', async () => {
- const mockData = {
- messages: Array.from({ length: 500 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(500);
vi.mocked(uploadService.uploadDataToS3).mockRejectedValue(new Error('S3 upload failed'));
@@ -244,20 +235,9 @@ describe('ImportService', () => {
});
it('should handle import error after successful upload', async () => {
- const mockData = {
- messages: Array.from({ length: 500 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(500);
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
const mockError = {
data: {
@@ -288,27 +268,13 @@ describe('ImportService', () => {
});
it('should trigger file upload progress callback', async () => {
- const mockData = {
- messages: Array.from({ length: 500 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(500);
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
- const mockImportResult = {
- results: {
- messages: { added: 500, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockImportResult = createImportResult({
+ messages: { added: 500, errors: 0, skips: 0 },
+ });
vi.mocked(uploadService.uploadDataToS3).mockImplementation(async (_data, options: any) => {
// Simulate progress callback
@@ -341,17 +307,11 @@ describe('ImportService', () => {
describe('edge cases', () => {
it('should handle data with exactly 499 items via POST', async () => {
- const mockData = {
- messages: Array.from({ length: 499 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(499);
- const mockResult = {
- results: {
- messages: { added: 499, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ messages: { added: 499, errors: 0, skips: 0 },
+ });
vi.mocked(lambdaClient.importer.importByPost.mutate).mockResolvedValue(mockResult);
@@ -362,27 +322,13 @@ describe('ImportService', () => {
});
it('should handle data with exactly 500 items via file upload', async () => {
- const mockData = {
- messages: Array.from({ length: 500 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(500);
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
- const mockImportResult = {
- results: {
- messages: { added: 500, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockImportResult = createImportResult({
+ messages: { added: 500, errors: 0, skips: 0 },
+ });
vi.mocked(uploadService.uploadDataToS3).mockResolvedValue(mockUploadResult as any);
vi.mocked(lambdaClient.importer.importByFile.mutate).mockResolvedValue(mockImportResult);
@@ -398,10 +344,7 @@ describe('ImportService', () => {
version: 1,
};
- const mockResult = {
- results: {},
- success: true as const,
- };
+ const mockResult = createImportResult({});
vi.mocked(lambdaClient.importer.importByPost.mutate).mockResolvedValue(mockResult);
@@ -411,17 +354,11 @@ describe('ImportService', () => {
});
it('should work without callbacks', async () => {
- const mockData = {
- messages: Array.from({ length: 10 }).fill({ id: '1', content: 'test' }),
- version: 1,
- };
+ const mockData = createMessageData(10);
- const mockResult = {
- results: {
- messages: { added: 10, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ messages: { added: 10, errors: 0, skips: 0 },
+ });
vi.mocked(lambdaClient.importer.importByPost.mutate).mockResolvedValue(mockResult);
@@ -442,13 +379,10 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockResult = {
- results: {
- users: { added: 100, errors: 0, skips: 0 },
- sessions: { added: 200, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ users: { added: 100, errors: 0, skips: 0 },
+ sessions: { added: 200, errors: 0, skips: 0 },
+ });
vi.mocked(lambdaClient.importer.importPgByPost.mutate).mockResolvedValue(mockResult);
@@ -512,22 +446,11 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
- const mockImportResult = {
- results: {
- messages: { added: 500, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockImportResult = createImportResult({
+ messages: { added: 500, errors: 0, skips: 0 },
+ });
vi.mocked(uploadService.uploadDataToS3).mockResolvedValue(mockUploadResult as any);
vi.mocked(lambdaClient.importer.importByFile.mutate).mockResolvedValue(mockImportResult);
@@ -562,24 +485,13 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockUploadResult = {
- success: true as const,
- data: {
- path: 'import_config/mock-uuid-123.json',
- filename: 'mock-uuid-123.json',
- dirname: 'import_config',
- date: '2024-01-01',
- },
- };
+ const mockUploadResult = createUploadResult();
- const mockImportResult = {
- results: {
- users: { added: 100, errors: 0, skips: 0 },
- messages: { added: 300, errors: 0, skips: 0 },
- sessions: { added: 150, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockImportResult = createImportResult({
+ users: { added: 100, errors: 0, skips: 0 },
+ messages: { added: 300, errors: 0, skips: 0 },
+ sessions: { added: 150, errors: 0, skips: 0 },
+ });
vi.mocked(uploadService.uploadDataToS3).mockResolvedValue(mockUploadResult as any);
vi.mocked(lambdaClient.importer.importByFile.mutate).mockResolvedValue(mockImportResult);
@@ -600,12 +512,9 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockResult = {
- results: {
- users: { added: 10, errors: 0, skips: 0 },
- },
- success: true as const,
- };
+ const mockResult = createImportResult({
+ users: { added: 10, errors: 0, skips: 0 },
+ });
vi.mocked(lambdaClient.importer.importPgByPost.mutate).mockResolvedValue(mockResult);
@@ -619,10 +528,7 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockResult = {
- results: {},
- success: true as const,
- };
+ const mockResult = createImportResult({});
vi.mocked(lambdaClient.importer.importPgByPost.mutate).mockResolvedValue(mockResult);
@@ -642,10 +548,7 @@ describe('ImportService', () => {
schemaHash: 'hash123',
};
- const mockResult = {
- results: {},
- success: true as const,
- };
+ const mockResult = createImportResult({});
vi.mocked(lambdaClient.importer.importPgByPost.mutate).mockResolvedValue(mockResult);
diff --git a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
index 64c9dadcefa..00c00a60d46 100644
--- a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
+++ b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
@@ -113,6 +113,30 @@ const createInitialState = (overrides: Partial<AgentState> = {}): AgentState =>
} as AgentState;
};
+const createExecutors = (store: ChatStore) =>
+ createGroupOrchestrationExecutors({
+ get: () => store,
+ messageContext: {
+ agentId: TEST_IDS.GROUP_ID,
+ groupId: TEST_IDS.GROUP_ID,
+ scope: 'group',
+ topicId: TEST_IDS.TOPIC_ID,
+ },
+ orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
+ supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
+ });
+
+const createBatchInstruction = () => ({
+ payload: {
+ tasks: [
+ { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
+ { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
+ ],
+ toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
+ },
+ type: 'batch_exec_async_tasks' as const,
+});
+
describe('createGroupOrchestrationExecutors', () => {
describe('batch_exec_async_tasks executor', () => {
beforeEach(() => {
@@ -135,19 +159,7 @@ describe('createGroupOrchestrationExecutors', () => {
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
- const result = await batchExecTasksExecutor(
- {
- payload: {
- tasks: [
- { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
- { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
- ],
- toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
- },
- type: 'batch_exec_async_tasks',
- },
- createInitialState(),
- );
+ const result = await batchExecTasksExecutor(createBatchInstruction(), createInitialState());
expect(result.result?.type).toBe('tasks_completed');
expect((result.result?.payload as any).results).toHaveLength(2);
@@ -169,33 +181,11 @@ describe('createGroupOrchestrationExecutors', () => {
status: 'completed',
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
- await batchExecTasksExecutor(
- {
- payload: {
- tasks: [
- { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
- { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
- ],
- toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
- },
- type: 'batch_exec_async_tasks',
- },
- createInitialState(),
- );
+ await batchExecTasksExecutor(createBatchInstruction(), createInitialState());
expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
expect(aiAgentService.execSubAgentTask).toHaveBeenCalledTimes(2);
@@ -247,33 +237,11 @@ describe('createGroupOrchestrationExecutors', () => {
status: 'completed',
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
- const result = await batchExecTasksExecutor(
- {
- payload: {
- tasks: [
- { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
- { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
- ],
- toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
- },
- type: 'batch_exec_async_tasks',
- },
- createInitialState(),
- );
+ const result = await batchExecTasksExecutor(createBatchInstruction(), createInitialState());
expect(result.result?.type).toBe('tasks_completed');
expect((result.result?.payload as any).results).toHaveLength(2);
@@ -306,33 +274,11 @@ describe('createGroupOrchestrationExecutors', () => {
status: 'completed',
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
- const result = await batchExecTasksExecutor(
- {
- payload: {
- tasks: [
- { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
- { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
- ],
- toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
- },
- type: 'batch_exec_async_tasks',
- },
- createInitialState(),
- );
+ const result = await batchExecTasksExecutor(createBatchInstruction(), createInitialState());
expect(result.result?.type).toBe('tasks_completed');
// First task should fail
@@ -360,17 +306,7 @@ describe('createGroupOrchestrationExecutors', () => {
status: 'failed',
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
@@ -408,17 +344,7 @@ describe('createGroupOrchestrationExecutors', () => {
status: 'processing',
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
@@ -460,17 +386,7 @@ describe('createGroupOrchestrationExecutors', () => {
taskDetail,
});
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createExecutors(mockStore);
const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
diff --git a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
index c624026afc5..19c6272b6eb 100644
--- a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
+++ b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
@@ -7,6 +7,33 @@ import { type ChatStore } from '@/store/chat/store';
import { createGroupOrchestrationExecutors } from '../createGroupOrchestrationExecutors';
+const createGroupStoreOptions = (): Partial<ChatStore> => ({
+ dbMessagesMap: {
+ [`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
+ {
+ content: 'Hello',
+ createdAt: Date.now(),
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ],
+ },
+});
+
+const createOrchestrationContext = (
+ mockStore: ChatStore,
+): Parameters<typeof createGroupOrchestrationExecutors>[0] => ({
+ get: () => mockStore,
+ messageContext: {
+ agentId: TEST_IDS.GROUP_ID,
+ scope: 'group',
+ topicId: TEST_IDS.TOPIC_ID,
+ },
+ orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
+ supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
+});
+
const TEST_IDS = {
GROUP_ID: 'test-group-id',
OPERATION_ID: 'test-operation-id',
@@ -81,30 +108,9 @@ const createInitialState = (overrides: Partial<AgentState> = {}): AgentState =>
describe('createGroupOrchestrationExecutors', () => {
describe('call_supervisor executor', () => {
it('should NOT pass operationId to executeClientAgent (creates new child operation)', async () => {
- const mockStore = createMockStore({
- dbMessagesMap: {
- [`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
- {
- content: 'Hello',
- createdAt: Date.now(),
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- updatedAt: Date.now(),
- } as UIChatMessage,
- ],
- },
- });
+ const mockStore = createMockStore(createGroupStoreOptions());
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createGroupOrchestrationExecutors(createOrchestrationContext(mockStore));
const callSupervisorExecutor = executors.call_supervisor!;
@@ -135,30 +141,9 @@ describe('createGroupOrchestrationExecutors', () => {
});
it('should pass isSupervisor: true in context for supervisor messages metadata', async () => {
- const mockStore = createMockStore({
- dbMessagesMap: {
- [`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
- {
- content: 'Hello',
- createdAt: Date.now(),
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- updatedAt: Date.now(),
- } as UIChatMessage,
- ],
- },
- });
+ const mockStore = createMockStore(createGroupStoreOptions());
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createGroupOrchestrationExecutors(createOrchestrationContext(mockStore));
const callSupervisorExecutor = executors.call_supervisor!;
@@ -185,30 +170,9 @@ describe('createGroupOrchestrationExecutors', () => {
describe('call_agent executor', () => {
it('should NOT pass operationId to executeClientAgent (creates new child operation)', async () => {
- const mockStore = createMockStore({
- dbMessagesMap: {
- [`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
- {
- content: 'Hello',
- createdAt: Date.now(),
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- updatedAt: Date.now(),
- } as UIChatMessage,
- ],
- },
- });
+ const mockStore = createMockStore(createGroupStoreOptions());
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createGroupOrchestrationExecutors(createOrchestrationContext(mockStore));
const callAgentExecutor = executors.call_agent!;
const targetAgentId = 'target-agent-id';
@@ -239,30 +203,9 @@ describe('createGroupOrchestrationExecutors', () => {
describe('operation structure comparison', () => {
it('call_supervisor and call_agent should both create independent child operations', async () => {
- const mockStore = createMockStore({
- dbMessagesMap: {
- [`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
- {
- content: 'Hello',
- createdAt: Date.now(),
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- updatedAt: Date.now(),
- } as UIChatMessage,
- ],
- },
- });
+ const mockStore = createMockStore(createGroupStoreOptions());
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
+ const executors = createGroupOrchestrationExecutors(createOrchestrationContext(mockStore));
// Execute call_supervisor
await executors.call_supervisor!(
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
index bf7a5545af8..9ed2d1f51ff 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
@@ -9,6 +9,15 @@ import { messageService } from '@/services/message';
import { createClientRuntimeExecutors } from '@/store/chat/agents/transports/createClientRuntimeExecutors';
import type { ChatStore } from '@/store/chat/store';
+const createClientExecutorContext = (
+ store: ChatStore,
+): Parameters<typeof createClientRuntimeExecutors>[0] => ({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+});
+
const messageKey = 'agent-1_topic-1';
const operationId = 'operation-1';
@@ -133,12 +142,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
});
return new Response();
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
const result = await executor(
createInstruction({ messages: [userMessage] }),
@@ -185,12 +189,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
await options?.onFinish?.('Answer after compression', { type: 'stop' });
return new Response();
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
const result = await executor(
createInstruction({
@@ -224,12 +223,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
await options?.onFinish?.('', { type: 'stop' });
return new Response();
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
const result = await executor(
createInstruction({ messages: [userMessage] }),
@@ -262,12 +256,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
await options?.onFinish?.('Regenerated', { type: 'stop' });
return new Response();
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
await executor(
createInstruction({
@@ -301,12 +290,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
await options?.onFinish?.('Partial', { type: 'abort' });
return new Response();
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
const result = await executor(
createInstruction({ messages: [userMessage] }),
@@ -329,12 +313,7 @@ describe('createClientRuntimeExecutors call_llm', () => {
operation.abortController.abort();
throw new DOMException('The operation was aborted', 'AbortError');
});
- const executor = createClientRuntimeExecutors({
- agentConfig: createResolvedAgentConfig(),
- get: () => store,
- messageKey,
- operationId,
- }).call_llm!;
+ const executor = createClientRuntimeExecutors(createClientExecutorContext(store)).call_llm!;
const result = await executor(
createInstruction({ messages: [userMessage] }),
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.ts
index cf2d222e50f..9991adb6812 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-task.test.ts
@@ -8,6 +8,26 @@ import { createExecSubAgentInstruction } from './fixtures';
import { createMockStore } from './fixtures/mockStore';
import { createInitialState, createTestContext, executeWithMockContext } from './helpers';
+const createTaskSuccessResponse = () => ({
+ assistantMessageId: 'asst_1',
+ operationId: 'op_1',
+ success: true,
+ threadId: 'thread_1',
+});
+
+const createTaskExecutionOptions = (
+ context: Parameters<typeof executeWithMockContext>[0]['context'],
+ instruction: Parameters<typeof executeWithMockContext>[0]['instruction'],
+ mockStore: Parameters<typeof executeWithMockContext>[0]['mockStore'],
+ state: Parameters<typeof executeWithMockContext>[0]['state'],
+): Parameters<typeof executeWithMockContext>[0] => ({
+ context,
+ executor: 'exec_sub_agent',
+ instruction,
+ mockStore,
+ state,
+});
+
// Mock aiAgentService
vi.mock('@/services/aiAgent', () => ({
aiAgentService: {
@@ -39,12 +59,7 @@ describe('exec_sub_agent executor', () => {
const state = createInitialState({ operationId: 'test-op' });
// Mock task execution
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
// Mock task status polling - completed on first poll
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
@@ -53,13 +68,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
expect(result.nextContext).toBeDefined();
@@ -99,13 +110,9 @@ describe('exec_sub_agent executor', () => {
};
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
expect(result.nextContext).toBeDefined();
@@ -130,13 +137,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
@@ -159,12 +162,7 @@ describe('exec_sub_agent executor', () => {
const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
error: 'Execution error',
@@ -172,13 +170,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
@@ -195,12 +189,7 @@ describe('exec_sub_agent executor', () => {
const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
// Return completed with taskDetail on first poll
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
@@ -210,13 +199,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
@@ -238,12 +223,7 @@ describe('exec_sub_agent executor', () => {
const instruction = createExecSubAgentInstruction(undefined, 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
// Use mockImplementationOnce to ensure fresh mock behavior
mockGetSubAgentTaskStatus.mockImplementationOnce(async () => ({
@@ -251,13 +231,9 @@ describe('exec_sub_agent executor', () => {
}));
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
@@ -290,22 +266,13 @@ describe('exec_sub_agent executor', () => {
// After task creation API is called, mark operation as cancelled
// This simulates cancellation happening right after task creation
mockStore.operations[operationId].status = 'cancelled';
- return {
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- };
+ return createTaskSuccessResponse();
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
@@ -328,12 +295,7 @@ describe('exec_sub_agent executor', () => {
);
const state = createInitialState({ operationId: 'test-op', stepCount: 5 });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
result: 'Done',
@@ -341,13 +303,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
expect(result.nextContext).toBeDefined();
@@ -370,12 +328,7 @@ describe('exec_sub_agent executor', () => {
const updatedMessages = [{ content: 'test', id: 'msg_1', role: 'user' }];
mockStore.dbMessagesMap[context.messageKey] = updatedMessages as any;
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createTaskSuccessResponse());
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
result: 'Done',
@@ -383,13 +336,9 @@ describe('exec_sub_agent executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agent',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeWithMockContext(
+ createTaskExecutionOptions(context, instruction, mockStore, state),
+ );
// Then
expect(result.newState.messages).toEqual(updatedMessages);
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.ts
index b7582ddddac..1f7c4c35483 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/exec-tasks.test.ts
@@ -25,6 +25,30 @@ const mockExecSubAgentTask = aiAgentService.execSubAgentTask as Mock;
const mockGetSubAgentTaskStatus = aiAgentService.getSubAgentTaskStatus as Mock;
const mockInterruptTask = aiAgentService.interruptTask as Mock;
+const createStartedTask = (index: number) => ({
+ assistantMessageId: `asst_${index}`,
+ operationId: `op_${index}`,
+ success: true,
+ threadId: `thread_${index}`,
+});
+
+const executeSubAgents = ({
+ context,
+ instruction,
+ mockStore,
+ state,
+}: Pick<
+ Parameters<typeof executeWithMockContext>[0],
+ 'context' | 'instruction' | 'mockStore' | 'state'
+>) =>
+ executeWithMockContext({
+ context,
+ executor: 'exec_sub_agents',
+ instruction,
+ mockStore,
+ state,
+ });
+
describe('exec_sub_agents executor', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -42,12 +66,7 @@ describe('exec_sub_agents executor', () => {
const state = createInitialState({ operationId: 'test-op' });
// Mock task execution
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
// Mock task status polling - completed on first poll
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
@@ -56,13 +75,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(result.nextContext).toBeDefined();
@@ -95,24 +108,9 @@ describe('exec_sub_agents executor', () => {
// Mock task execution for each task
mockExecSubAgentTask
- .mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- })
- .mockResolvedValueOnce({
- assistantMessageId: 'asst_2',
- operationId: 'op_2',
- success: true,
- threadId: 'thread_2',
- })
- .mockResolvedValueOnce({
- assistantMessageId: 'asst_3',
- operationId: 'op_3',
- success: true,
- threadId: 'thread_3',
- });
+ .mockResolvedValueOnce(createStartedTask(1))
+ .mockResolvedValueOnce(createStartedTask(2))
+ .mockResolvedValueOnce(createStartedTask(3));
// Mock task status polling - all completed
mockGetSubAgentTaskStatus
@@ -121,13 +119,7 @@ describe('exec_sub_agents executor', () => {
.mockResolvedValueOnce({ result: 'Result 3', status: 'completed' });
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(result.nextContext).toBeDefined();
@@ -161,13 +153,7 @@ describe('exec_sub_agents executor', () => {
};
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(result.nextContext).toBeDefined();
@@ -194,13 +180,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
const payload = (result.nextContext as AgentRuntimeContext)
@@ -224,12 +204,7 @@ describe('exec_sub_agents executor', () => {
const instruction = createExecSubAgentsInstruction([], 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
error: 'Execution error',
@@ -237,13 +212,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
const payload = (result.nextContext as AgentRuntimeContext)
@@ -261,12 +230,7 @@ describe('exec_sub_agents executor', () => {
const instruction = createExecSubAgentsInstruction([], 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
// Return completed with taskDetail on first poll
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
@@ -276,13 +240,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
@@ -305,12 +263,7 @@ describe('exec_sub_agents executor', () => {
const instruction = createExecSubAgentsInstruction([], 'msg_parent');
const state = createInitialState({ operationId: 'test-op' });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
// Use mockImplementationOnce to ensure fresh mock behavior
mockGetSubAgentTaskStatus.mockImplementationOnce(async () => ({
@@ -318,13 +271,7 @@ describe('exec_sub_agents executor', () => {
}));
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
const payload = (result.nextContext as AgentRuntimeContext)
@@ -359,22 +306,11 @@ describe('exec_sub_agents executor', () => {
// This simulates cancellation happening right after task creation
// Note: state.operationId is used in the polling loop for cancellation check
mockStore.operations[operationId].status = 'cancelled';
- return {
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- };
+ return createStartedTask(1);
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
const payload = (result.nextContext as AgentRuntimeContext)
@@ -398,12 +334,7 @@ describe('exec_sub_agents executor', () => {
);
const state = createInitialState({ operationId: 'test-op', stepCount: 5 });
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
result: 'Done',
@@ -411,13 +342,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(result.nextContext).toBeDefined();
@@ -440,12 +365,7 @@ describe('exec_sub_agents executor', () => {
const updatedMessages = [{ content: 'test', id: 'msg_1', role: 'user' }];
mockStore.dbMessagesMap[context.messageKey] = updatedMessages as any;
- mockExecSubAgentTask.mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- });
+ mockExecSubAgentTask.mockResolvedValueOnce(createStartedTask(1));
mockGetSubAgentTaskStatus.mockResolvedValueOnce({
result: 'Done',
@@ -453,13 +373,7 @@ describe('exec_sub_agents executor', () => {
});
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
expect(result.newState.messages).toEqual(updatedMessages);
@@ -481,31 +395,15 @@ describe('exec_sub_agents executor', () => {
const state = createInitialState({ operationId: 'test-op' });
mockExecSubAgentTask
- .mockResolvedValueOnce({
- assistantMessageId: 'asst_1',
- operationId: 'op_1',
- success: true,
- threadId: 'thread_1',
- })
- .mockResolvedValueOnce({
- assistantMessageId: 'asst_2',
- operationId: 'op_2',
- success: true,
- threadId: 'thread_2',
- });
+ .mockResolvedValueOnce(createStartedTask(1))
+ .mockResolvedValueOnce(createStartedTask(2));
mockGetSubAgentTaskStatus
.mockResolvedValueOnce({ result: 'Success', status: 'completed' })
.mockResolvedValueOnce({ error: 'Task failed', status: 'failed' });
// When
- const result = await executeWithMockContext({
- context,
- executor: 'exec_sub_agents',
- instruction,
- mockStore,
- state,
- });
+ const result = await executeSubAgents({ context, instruction, mockStore, state });
// Then
const payload = (result.nextContext as AgentRuntimeContext)
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts
index 50e1c7bb357..4c3e0bac0d5 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts
@@ -9,6 +9,27 @@ import {
} from './fixtures';
import { createInitialState, createTestContext, executeWithMockContext } from './helpers';
+const createSearchTool = (): ChatToolPayload => ({
+ id: 'tool_1',
+ identifier: 'lobe-web-browsing',
+ apiName: 'search',
+ arguments: JSON.stringify({ query: 'test' }),
+ type: 'default',
+});
+
+const createApprovalExecutionOptions = (
+ instruction: Parameters<typeof executeWithMockContext>[0]['instruction'],
+ state: Parameters<typeof executeWithMockContext>[0]['state'],
+ mockStore: Parameters<typeof executeWithMockContext>[0]['mockStore'],
+ context: Parameters<typeof executeWithMockContext>[0]['context'],
+): Parameters<typeof executeWithMockContext>[0] => ({
+ executor: 'request_human_approve',
+ instruction,
+ state,
+ mockStore,
+ context,
+});
+
describe('request_human_approve executor', () => {
describe('Basic Behavior', () => {
it('should create tool messages with pending intervention status', async () => {
@@ -18,27 +39,15 @@ describe('request_human_approve executor', () => {
mockStore.dbMessagesMap['test-session_test-topic'] = [assistantMessage];
const context = createTestContext();
- const toolCalls: ChatToolPayload[] = [
- {
- id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'test' }),
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchTool()];
const instruction = createRequestHumanApproveInstruction(toolCalls);
const state = createInitialState();
// When
- await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledTimes(1);
@@ -69,13 +78,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(result.newState.status).toBe('waiting_for_human');
@@ -89,13 +94,7 @@ describe('request_human_approve executor', () => {
const context = createTestContext();
const toolCalls: ChatToolPayload[] = [
- {
- id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'test' }),
- type: 'default',
- },
+ createSearchTool(),
{
id: 'tool_2',
identifier: 'lobe-web-browsing',
@@ -109,13 +108,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(result.newState.pendingToolsCalling).toEqual(toolCalls);
@@ -128,27 +123,15 @@ describe('request_human_approve executor', () => {
mockStore.dbMessagesMap['test-session_test-topic'] = [assistantMessage];
const context = createTestContext();
- const toolCalls: ChatToolPayload[] = [
- {
- id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'test' }),
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchTool()];
const instruction = createRequestHumanApproveInstruction(toolCalls);
const state = createInitialState({ operationId: 'test-session' });
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(result.events).toContainEqual(
@@ -173,13 +156,9 @@ describe('request_human_approve executor', () => {
// When/Then
await expect(
- executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- }),
+ executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ ),
).rejects.toThrow('No assistant message found for intervention');
});
@@ -197,13 +176,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
@@ -227,13 +202,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
@@ -254,15 +225,7 @@ describe('request_human_approve executor', () => {
const assistantMessage = createAssistantMessage({ id: 'msg_assistant' });
const context = createTestContext();
- const toolCalls: ChatToolPayload[] = [
- {
- id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'test' }),
- type: 'default',
- },
- ];
+ const toolCalls: ChatToolPayload[] = [createSearchTool()];
const durableToolMessage = createPendingToolMessage({
id: 'msg_tool_1',
parentId: assistantMessage.id,
@@ -285,13 +248,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
@@ -338,13 +297,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledTimes(3);
@@ -378,13 +333,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState({ lastModified: oldTimestamp });
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(result.newState.lastModified).not.toBe(oldTimestamp);
@@ -437,13 +388,9 @@ describe('request_human_approve executor', () => {
});
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(result.newState.operationId).toBe(state.operationId);
@@ -464,13 +411,9 @@ describe('request_human_approve executor', () => {
const originalState = structuredClone(state);
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(state).toEqual(originalState);
@@ -495,13 +438,9 @@ describe('request_human_approve executor', () => {
// When/Then
await expect(
- executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- }),
+ executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ ),
).rejects.toThrow('Failed to create tool message');
});
});
@@ -526,13 +465,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- const result = await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ const result = await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledTimes(50);
@@ -556,13 +491,9 @@ describe('request_human_approve executor', () => {
const state = createInitialState();
// When
- await executeWithMockContext({
- executor: 'request_human_approve',
- instruction,
- state,
- mockStore,
- context,
- });
+ await executeWithMockContext(
+ createApprovalExecutionOptions(instruction, state, mockStore, context),
+ );
// Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.ts
index a4d3e1607e0..334590aeb0b 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/resolve-aborted-tools.test.ts
@@ -139,7 +139,7 @@ describe('resolve_aborted_tools executor', () => {
expect(result.newState.status).toBe('done');
});
- it('should emit done event with user_aborted reason', async () => {
+ it('should emit a done event with the final state and user_aborted reason', async () => {
// Given
const mockStore = createMockStore();
const context = createTestContext();
@@ -162,8 +162,9 @@ describe('resolve_aborted_tools executor', () => {
type: 'done',
reason: 'user_aborted',
reasonDetail: 'User aborted operation with pending tool calls',
- finalState: result.newState,
});
+ expect(doneEvent.finalState).toEqual(result.newState);
+ expect(doneEvent.finalState.status).toBe('done');
});
});
@@ -392,30 +393,6 @@ describe('resolve_aborted_tools executor', () => {
});
});
- describe('Event Handling', () => {
- it('should include finalState in event', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createResolveAbortedToolsInstruction();
- const state = createInitialState();
-
- // When
- const result = await executeWithMockContext({
- executor: 'resolve_aborted_tools',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const doneEvent = result.events[0] as AgentEventDone;
- expect(doneEvent.finalState).toEqual(result.newState);
- expect(doneEvent.finalState.status).toBe('done');
- });
- });
-
describe('Edge Cases', () => {
it('should handle empty toolsCalling array', async () => {
// Given
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.test.ts b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
index c86a7faca78..07fd02faeef 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
@@ -6,6 +6,15 @@ import { chatService } from '@/services/chat';
import type { ChatStore } from '../../store';
import { ClientLLMTransport } from './ClientLLMTransport';
+const createContentPolicyFailure = () => ({
+ error: {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ },
+ events: [],
+ interrupted: false,
+});
+
// A grounding-only completion streams no text into `content`, but carries
// citation metadata and burns real output tokens. The stream (driven via
// `chatService.getChatCompletion`) finishes with `grounding` + `usage`, and the
@@ -210,14 +219,7 @@ describe('ClientLLMTransport.retryPolicy.onError · terminal operation teardown'
scope: 'group',
});
- transport.retryPolicy.onError?.({
- error: {
- message: 'The content may contain prohibited content. Please adjust it and try again.',
- type: 'ProviderContentPolicyViolation',
- },
- events: [],
- interrupted: false,
- });
+ transport.retryPolicy.onError?.(createContentPolicyFailure());
expect(store.updateTopicStatus).toHaveBeenCalledWith({
agentId: 'agent-1',
@@ -246,14 +248,7 @@ describe('ClientLLMTransport.retryPolicy.onError · terminal operation teardown'
const { store, transport } = createTransport();
store.operations['op-1'].status = 'cancelled';
- transport.retryPolicy.onError?.({
- error: {
- message: 'The content may contain prohibited content. Please adjust it and try again.',
- type: 'ProviderContentPolicyViolation',
- },
- events: [],
- interrupted: false,
- });
+ transport.retryPolicy.onError?.(createContentPolicyFailure());
expect(store.internal_dispatchMessage).toHaveBeenCalled();
expect(store.failOperation).not.toHaveBeenCalled();
@@ -263,14 +258,7 @@ describe('ClientLLMTransport.retryPolicy.onError · terminal operation teardown'
it('does not reset topic status for nested sub-agent operations', () => {
const { store, transport } = createTransport({ scope: 'sub_agent' });
- transport.retryPolicy.onError?.({
- error: {
- message: 'The content may contain prohibited content. Please adjust it and try again.',
- type: 'ProviderContentPolicyViolation',
- },
- events: [],
- interrupted: false,
- });
+ transport.retryPolicy.onError?.(createContentPolicyFailure());
expect(store.failOperation).toHaveBeenCalled();
expect(store.updateTopicStatus).not.toHaveBeenCalled();
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 349d3359b77..a0fba3251e1 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -92,6 +92,32 @@ afterEach(() => {
vi.restoreAllMocks();
});
+const createToolMessageState = (
+ agentId: string,
+ topicId: string,
+ chatKey: string,
+ toolMessage: ReturnType<typeof createMockMessage>,
+) => ({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ dbMessagesMap: { [chatKey]: [toolMessage] },
+ messagesMap: { [chatKey]: [toolMessage] },
+});
+
+const createHeteroQuestionMessage = (parentId: string) =>
+ createMockMessage({
+ id: 'tool-msg-1',
+ parentId,
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-claude-code',
+ type: 'default',
+ },
+ role: 'tool',
+ tool_call_id: 'cc_call_1',
+ } as any);
+
const captureActError = async (action: () => Promise<void>): Promise<unknown> => {
let captured: unknown;
await act(async () => {
@@ -894,12 +920,7 @@ describe('ConversationControl actions', () => {
);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
@@ -1125,12 +1146,7 @@ describe('ConversationControl actions', () => {
} as any;
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
const executeGatewayAgentSpy = vi
@@ -1200,12 +1216,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
pausedOperationId = result.current.startOperation({
context: { agentId, topicId, threadId: null },
type: 'execServerAgentRuntime',
@@ -1266,12 +1277,7 @@ describe('ConversationControl actions', () => {
tool_call_id: 'call-claim-failure',
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
const mutation = vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate);
@@ -1312,12 +1318,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
const executeGatewayAgentSpy = vi
@@ -1417,12 +1418,7 @@ describe('ConversationControl actions', () => {
let serverOpId: string | undefined;
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
serverOpId = result.current.startOperation({
context: { agentId, topicId, threadId: null },
@@ -1488,12 +1484,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
result.current.startOperation({
context: { agentId, topicId, threadId: null },
@@ -1546,12 +1537,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
@@ -1599,12 +1585,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
// Server op is indexed under the group-scope key. Without scope
// forwarding the lookup would hit the default 'main' bucket instead.
@@ -1777,12 +1758,7 @@ describe('ConversationControl actions', () => {
let pausedOperationId!: string;
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
pausedOperationId = result.current.startOperation({
context: { agentId, topicId, threadId: null },
type: 'execServerAgentRuntime',
@@ -1932,12 +1908,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
result.current.startOperation({
context: { agentId, topicId, threadId: null },
@@ -1989,12 +1960,7 @@ describe('ConversationControl actions', () => {
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
result.current.startOperation({
context: { agentId, topicId, threadId: null },
@@ -2519,12 +2485,7 @@ describe('ConversationControl actions', () => {
tool_call_id: 'call-custom-failure',
} as any);
act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- activeTopicId: topicId,
- dbMessagesMap: { [chatKey]: [toolMessage] },
- messagesMap: { [chatKey]: [toolMessage] },
- });
+ useChatStore.setState(createToolMessageState(agentId, topicId, chatKey, toolMessage));
});
vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
const legacySideEffect = vi.fn().mockResolvedValue({
@@ -3713,18 +3674,7 @@ describe('ConversationControl actions', () => {
id: 'assistant-msg-1',
role: 'assistant',
});
- const toolMessage = createMockMessage({
- id: 'tool-msg-1',
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- role: 'tool',
- tool_call_id: 'cc_call_1',
- } as any);
+ const toolMessage = createHeteroQuestionMessage(assistantMessage.id);
let assistantOpId!: string;
act(() => {
@@ -3792,18 +3742,7 @@ describe('ConversationControl actions', () => {
id: 'assistant-msg-1',
role: 'assistant',
});
- const toolMessage = createMockMessage({
- id: 'tool-msg-1',
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- role: 'tool',
- tool_call_id: 'cc_call_1',
- } as any);
+ const toolMessage = createHeteroQuestionMessage(assistantMessage.id);
let executionOpId!: string;
let reasoningOpId!: string;
@@ -3869,18 +3808,7 @@ describe('ConversationControl actions', () => {
const chatKey = messageMapKey({ agentId, topicId });
const assistantMessage = createMockMessage({ id: 'assistant-msg-1', role: 'assistant' });
- const toolMessage = createMockMessage({
- id: 'tool-msg-1',
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- role: 'tool',
- tool_call_id: 'cc_call_1',
- } as any);
+ const toolMessage = createHeteroQuestionMessage(assistantMessage.id);
act(() => {
useChatStore.setState({
@@ -4002,18 +3930,7 @@ describe('ConversationControl actions', () => {
const chatKey = messageMapKey({ agentId, topicId: cardTopicId });
const assistantMessage = createMockMessage({ id: 'assistant-msg-1', role: 'assistant' });
- const toolMessage = createMockMessage({
- id: 'tool-msg-1',
- parentId: assistantMessage.id,
- plugin: {
- apiName: 'askUserQuestion',
- arguments: '{}',
- identifier: 'lobe-claude-code',
- type: 'default',
- },
- role: 'tool',
- tool_call_id: 'cc_call_1',
- } as any);
+ const toolMessage = createHeteroQuestionMessage(assistantMessage.id);
let assistantOpId!: string;
act(() => {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
index 590cf788f05..1cf4cbf72d8 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
@@ -51,6 +51,17 @@ const directoryRow = {
projectId: 'prj-1',
} as ProjectDirectory;
+const deviceAgent = () =>
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: DEVICE_ID,
+ executionTarget: 'device',
+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
+ },
+ },
+ });
+
beforeEach(() => {
resetTestEnvironment();
spyOnMessageService();
@@ -83,15 +94,7 @@ describe('sendMessage in a project directory', () => {
// branch, and the next turn was refused for a mismatched directory.
it('seeds the new topic with the project directory, not the agent default', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
const agentId = TEST_IDS.SESSION_ID;
@@ -211,15 +214,7 @@ describe('sendMessage in a project directory', () => {
// must not inherit the directory it was sent from.
it('keeps a /newTopic sent from a project topic on the agent default', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
const agentId = TEST_IDS.SESSION_ID;
@@ -384,15 +379,7 @@ describe('sendMessage continuing a source topic', () => {
// agent's default directory instead of the one the source topic ran in.
it('starts a forwarded topic in the source project directory', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
const params = await sendForward({
metadata: { boundDeviceId: DEVICE_ID, workingDirectory: PROJECT_PATH },
@@ -408,15 +395,7 @@ describe('sendMessage continuing a source topic', () => {
it('carries the source bare directory to the server on the same machine', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
const params = await sendForward({
metadata: {
@@ -443,15 +422,7 @@ describe('sendMessage continuing a source topic', () => {
['on an unknown machine', { workingDirectory: SOURCE_PATH }],
])('keeps the agent default when the source directory is %s', async (_, metadata) => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
const params = await sendForward({ metadata });
@@ -486,15 +457,7 @@ describe('sendMessage continuing a source topic', () => {
// off) must not fail the handoff: it continues in the source's bare cwd.
it('falls back to the source cwd when its project directory cannot be resolved', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
+ deviceAgent();
useProjectDirectoryStore.setState({ directoriesMap: {} });
vi.spyOn(projectWorkingDirectoryService, 'resolve').mockRejectedValue(
new Error('Directory not found'),
@@ -513,17 +476,6 @@ describe('sendMessage continuing a source topic', () => {
// The source directory may have been deleted since it ran; the receiving
// agent then takes the handoff in its own default instead of a run that can
// only fail with "working directory not found".
- const deviceAgent = () =>
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- boundDeviceId: DEVICE_ID,
- executionTarget: 'device',
- workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },
- },
- },
- });
-
it('falls back to the agent default when the source cwd no longer exists', async () => {
mockConstEnv.isDesktop = true;
deviceAgent();
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 7c52f793a32..e7899c4d933 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -122,6 +122,64 @@ const createTestContext = (agentId: string = TEST_IDS.SESSION_ID) => ({
threadId: null,
});
+const createDefaultServerMessages = () => [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+];
+
+const createEmptyTopicPage = () => ({
+ currentPage: 0,
+ hasMore: false,
+ isExpandingPageSize: false,
+ isLoadingMore: false,
+ items: [],
+ pageSize: 20,
+ total: 0,
+});
+
+const createCodexSelectorOptions = () => ({
+ agentConfig: {
+ agencyConfig: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ },
+ },
+});
+
+const createSendResponseWithTopic = (topicIdValue: string) => ({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: createDefaultServerMessages(),
+ topicId: topicIdValue,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+});
+
+const createSendResponseWithoutTopicId = () => ({
+ messages: createDefaultServerMessages(),
+ topics: [],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+});
+
+const createCreatedTopicResponse = (topicIdValue: string) => ({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ isCreateNewTopic: true,
+ messages: [
+ createMockMessage({
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ topicId: topicIdValue,
+ }),
+ createMockMessage({
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ role: 'assistant',
+ topicId: topicIdValue,
+ }),
+ ],
+ topicId: topicIdValue,
+ topics: { items: [{ id: topicIdValue, title: 'Server Topic' }], total: 1 },
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+});
+
describe('ConversationLifecycle actions', () => {
describe('sendMessage', () => {
describe('validation', () => {
@@ -901,13 +959,7 @@ describe('ConversationLifecycle actions', () => {
// Same silent-discard shape as the gateway branch above: persistence
// throws, the temp rows are cleaned up, and the typed text is gone.
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const { result } = renderHook(() => useChatStore());
const inputEditorState = {
@@ -1279,10 +1331,7 @@ describe('ConversationLifecycle actions', () => {
});
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -1384,15 +1433,7 @@ describe('ConversationLifecycle actions', () => {
activeAgentId: agentId,
activeTopicId: undefined,
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -1477,10 +1518,7 @@ describe('ConversationLifecycle actions', () => {
const { result } = renderHook(() => useChatStore());
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: [],
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
} as any);
@@ -1501,10 +1539,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
.mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: undefined,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
@@ -1606,15 +1641,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -1791,15 +1818,7 @@ describe('ConversationLifecycle actions', () => {
executeClientAgent: vi.fn().mockReturnValue(executePromise),
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -1834,25 +1853,7 @@ describe('ConversationLifecycle actions', () => {
).toBe(true);
await act(async () => {
- resolveServerSend({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- isCreateNewTopic: true,
- messages: [
- createMockMessage({
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- topicId: newTopicId,
- }),
- createMockMessage({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- role: 'assistant',
- topicId: newTopicId,
- }),
- ],
- topicId: newTopicId,
- topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ resolveServerSend(createCreatedTopicResponse(newTopicId) as any);
});
await waitFor(() =>
@@ -1905,25 +1906,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- isCreateNewTopic: true,
- messages: [
- createMockMessage({
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- topicId: newTopicId,
- }),
- createMockMessage({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- role: 'assistant',
- topicId: newTopicId,
- }),
- ],
- topicId: newTopicId,
- topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createCreatedTopicResponse(newTopicId) as any);
await act(async () => {
await result.current.sendMessage({
@@ -2014,15 +1997,7 @@ describe('ConversationLifecycle actions', () => {
isGatewayModeEnabled: () => true,
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -2129,13 +2104,7 @@ describe('ConversationLifecycle actions', () => {
it('should keep the sidebar spinner on through a hetero new-topic run and stop it at the end', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
@@ -2148,38 +2117,14 @@ describe('ConversationLifecycle actions', () => {
activeTopicId: undefined,
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- isCreateNewTopic: true,
- messages: [
- createMockMessage({
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- topicId: newTopicId,
- }),
- createMockMessage({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- role: 'assistant',
- topicId: newTopicId,
- }),
- ],
- topicId: newTopicId,
- topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createCreatedTopicResponse(newTopicId) as any,
+ );
let resolveExecutor!: () => void;
executeHeterogeneousAgentMock.mockImplementation(
@@ -2229,13 +2174,7 @@ describe('ConversationLifecycle actions', () => {
it('notifies an isolated hetero caller before execution and returns its created topic', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
@@ -2248,38 +2187,14 @@ describe('ConversationLifecycle actions', () => {
activeTopicId: undefined,
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- isCreateNewTopic: true,
- messages: [
- createMockMessage({
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- topicId: newTopicId,
- }),
- createMockMessage({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- role: 'assistant',
- topicId: newTopicId,
- }),
- ],
- topicId: newTopicId,
- topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createCreatedTopicResponse(newTopicId) as any,
+ );
let resolveExecutor!: () => void;
executeHeterogeneousAgentMock.mockImplementation(
@@ -2360,15 +2275,7 @@ describe('ConversationLifecycle actions', () => {
executeGatewayAgent: executeGatewayAgentSpy,
isGatewayModeEnabled: () => true,
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -2466,15 +2373,7 @@ describe('ConversationLifecycle actions', () => {
executeGatewayAgent: executeGatewayAgentSpy,
isGatewayModeEnabled: () => true,
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -2588,16 +2487,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.NEW_TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithTopic(TEST_IDS.NEW_TOPIC_ID) as any);
const { result } = renderHook(() => useChatStore());
act(() => {
@@ -2639,16 +2529,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.NEW_TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithTopic(TEST_IDS.NEW_TOPIC_ID) as any);
const { result } = renderHook(() => useChatStore());
act(() => {
@@ -2744,16 +2625,9 @@ describe('ConversationLifecycle actions', () => {
});
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
- return vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.NEW_TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ return vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockResolvedValue(createSendResponseWithTopic(TEST_IDS.NEW_TOPIC_ID) as any);
};
const sendHeteroMessage = async () => {
@@ -2929,25 +2803,14 @@ describe('ConversationLifecycle actions', () => {
executeClientAgent: vi.fn().mockResolvedValue(undefined),
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: undefined,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -2991,15 +2854,7 @@ describe('ConversationLifecycle actions', () => {
executeClientAgent: vi.fn().mockResolvedValue(undefined),
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [groupKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [groupKey]: createEmptyTopicPage(),
},
});
});
@@ -3077,15 +2932,7 @@ describe('ConversationLifecycle actions', () => {
executeClientAgent: vi.fn().mockResolvedValue(undefined),
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -3112,10 +2959,7 @@ describe('ConversationLifecycle actions', () => {
await act(async () => {
resolveServerSend({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: undefined,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -3144,15 +2988,7 @@ describe('ConversationLifecycle actions', () => {
executeClientAgent: vi.fn().mockResolvedValue(undefined),
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
topicDataMap: {
- [topicKey]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [],
- pageSize: 20,
- total: 0,
- },
+ [topicKey]: createEmptyTopicPage(),
},
});
});
@@ -3189,10 +3025,7 @@ describe('ConversationLifecycle actions', () => {
await act(async () => {
resolveServerSend({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: undefined,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -3215,10 +3048,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
.mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: undefined,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
@@ -3805,10 +3635,7 @@ describe('ConversationLifecycle actions', () => {
.mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
isCreateNewTopic: true,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topicId: TEST_IDS.TOPIC_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -4002,15 +3829,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -4051,15 +3870,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -4090,15 +3901,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -4128,15 +3931,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -4171,16 +3966,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any);
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
@@ -4253,16 +4039,9 @@ describe('ConversationLifecycle actions', () => {
},
});
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
const { result } = renderHook(() => useChatStore());
@@ -4297,16 +4076,9 @@ describe('ConversationLifecycle actions', () => {
});
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
const { result } = renderHook(() => useChatStore());
@@ -4475,16 +4247,9 @@ describe('ConversationLifecycle actions', () => {
useChatStore.setState({ executeGatewayAgent });
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
const { result } = renderHook(() => useChatStore());
@@ -4521,16 +4286,9 @@ describe('ConversationLifecycle actions', () => {
useChatStore.setState({ executeGatewayAgent });
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
const { result } = renderHook(() => useChatStore());
await act(async () => {
@@ -4576,16 +4334,9 @@ describe('ConversationLifecycle actions', () => {
act(() => {
useChatStore.setState({ executeGatewayAgent });
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
const { result } = renderHook(() => useChatStore());
@@ -4641,16 +4392,9 @@ describe('ConversationLifecycle actions', () => {
act(() => {
useChatStore.setState({ executeGatewayAgent });
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
try {
@@ -4709,16 +4453,9 @@ describe('ConversationLifecycle actions', () => {
act(() => {
useChatStore.setState({ executeGatewayAgent });
});
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any,
+ );
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
try {
@@ -4742,13 +4479,7 @@ describe('ConversationLifecycle actions', () => {
it('should route new-topic heterogeneous streaming updates to the persisted topic key', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const createdTopicId = 'created-topic-id';
const { result } = renderHook(() => useChatStore());
@@ -4818,13 +4549,7 @@ describe('ConversationLifecycle actions', () => {
it('reconciles a persisted heterogeneous message but skips CLI execution after cancellation', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const { result } = renderHook(() => useChatStore());
const controller = new AbortController();
const onMessageAccepted = vi.fn();
@@ -4884,22 +4609,13 @@ describe('ConversationLifecycle actions', () => {
it('should preserve the isNew marker for heterogeneous new-thread contexts', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const { result } = renderHook(() => useChatStore());
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topicId: TEST_IDS.TOPIC_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
@@ -5006,13 +4722,7 @@ describe('ConversationLifecycle actions', () => {
it('should recover heterogeneous context selections from the persisted user message metadata', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const persistedContextSelections = [
{
@@ -5057,13 +4767,7 @@ describe('ConversationLifecycle actions', () => {
it('should materialize local file mention editor data into persisted tool-result snapshots', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
mockLocalFileService.readLocalFile.mockResolvedValue({
charCount: 17,
content: 'export const x = 1;',
@@ -5077,16 +4781,7 @@ describe('ConversationLifecycle actions', () => {
const { result } = renderHook(() => useChatStore());
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topicId: TEST_IDS.TOPIC_ID,
- topics: [],
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithTopic(TEST_IDS.TOPIC_ID) as any);
executeHeterogeneousAgentMock.mockResolvedValue(undefined);
@@ -5155,10 +4850,7 @@ describe('ConversationLifecycle actions', () => {
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
isCreateNewTopic: true,
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topicId: TEST_IDS.TOPIC_ID,
topics: { items: [], total: 0 },
userMessageId: TEST_IDS.USER_MESSAGE_ID,
@@ -5249,10 +4941,7 @@ describe('ConversationLifecycle actions', () => {
const dispatchTopicSpy = vi.spyOn(result.current, 'internal_dispatchTopic');
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
+ messages: createDefaultServerMessages(),
topics: { items: [{ id: 'new-topic', title: 'New Topic' }], total: 1 },
topicId: 'new-topic',
isCreateNewTopic: true,
@@ -5281,15 +4970,7 @@ describe('ConversationLifecycle actions', () => {
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
- .mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ .mockResolvedValue(createSendResponseWithoutTopicId() as any);
await act(async () => {
await result.current.sendMessage({
@@ -5454,13 +5135,7 @@ describe('ConversationLifecycle actions', () => {
it('should isolate a direct mention executed by a local heterogeneous agent', async () => {
mockConstEnv.isDesktop = true;
- setupMockSelectors({
- agentConfig: {
- agencyConfig: {
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- },
- },
- });
+ setupMockSelectors(createCodexSelectorOptions());
const targetAgentId = 'agent-direct-codex';
const threadId = 'thread-direct-codex';
@@ -5676,15 +5351,9 @@ describe('ConversationLifecycle actions', () => {
it('should keep supervisor delegation for multiple @agent mentions', async () => {
const { result } = renderHook(() => useChatStore());
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithoutTopicId() as any,
+ );
await act(async () => {
await result.current.sendMessage({
@@ -5737,15 +5406,9 @@ describe('ConversationLifecycle actions', () => {
it('should forward mentionedAgents to the gateway for multi-mention when gateway mode is enabled', async () => {
const { result } = renderHook(() => useChatStore());
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithoutTopicId() as any,
+ );
const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
@@ -5818,15 +5481,9 @@ describe('ConversationLifecycle actions', () => {
},
} as any);
- vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- messages: [
- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
- createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
- ],
- topics: [],
- assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- userMessageId: TEST_IDS.USER_MESSAGE_ID,
- } as any);
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue(
+ createSendResponseWithoutTopicId() as any,
+ );
await act(async () => {
await result.current.sendMessage({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 743f429ff4c..57c804096ae 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -4769,31 +4769,14 @@ describe('GatewayActionImpl', () => {
expect(connectToGateway).toHaveBeenCalled();
});
- // The operation is created optimistically off the marker, so every bail-out
- // has to retire it — otherwise a stale marker leaves the composer spinning
- // on a run that nothing will ever settle.
- it('retires the optimistic operation when refreshGatewayToken returns NOT_FOUND', async () => {
- const { action, completeOperation } = createSeededReconnectHarness();
- vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce({
- data: { code: 'NOT_FOUND' },
- });
-
- await action.reconnectToGatewayOperation({
- assistantMessageId: 'ast-1',
- operationId: 'server-op-1',
- topicId: 'topic-1',
- });
-
- expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
- });
-
// Regression: a stale local runningOperation fires a reconnect,
// but the server already cleared its marker and answers refreshGatewayToken
// with TRPC NOT_FOUND. The reconnect must clear the local marker and bail
// silently (no connect, no throw) so the SWR fetcher resolves instead of
// looping 404s.
- it('clears the local marker and bails when refreshGatewayToken returns NOT_FOUND', async () => {
- const { action, connectToGateway, internalDispatchTopic } = createSeededReconnectHarness();
+ it('retires the local operation and clears the marker on NOT_FOUND', async () => {
+ const { action, completeOperation, connectToGateway, internalDispatchTopic } =
+ createSeededReconnectHarness();
vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce({
data: { code: 'NOT_FOUND' },
});
@@ -4806,6 +4789,11 @@ describe('GatewayActionImpl', () => {
}),
).resolves.toBeUndefined();
+ // The operation is created optimistically off the marker, so every bail-out
+ // has to retire it — otherwise a stale marker leaves the composer spinning
+ // on a run that nothing will ever settle.
+ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
+
expect(internalDispatchTopic).toHaveBeenCalledWith({
id: 'topic-1',
type: 'updateTopic',
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 d084d52624f..d771b364094 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1440,6 +1440,27 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
severity: 'warning',
};
+ const createExpectedAuthError = (rawAuthError: string) => ({
+ ...authMetadata,
+ body: expect.objectContaining({
+ agentType: 'claude-code',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ stderr: rawAuthError,
+ }),
+ message:
+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
+ type: 'AgentRuntimeError',
+ });
+
+ const createExpectedAuthErrorUpdate = (rawAuthError: string) => ({
+ id: 'ast-initial',
+ type: 'updateMessage',
+ value: {
+ content: '',
+ error: createExpectedAuthError(rawAuthError),
+ },
+ });
+
it('preserves structured quota fields for a flattened local CLI error', async () => {
const store = createMockStore();
mockSendPrompt.mockRejectedValueOnce({
@@ -1530,38 +1551,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(contentWrite).toBeUndefined();
expect(mockUpdateMessageError).toHaveBeenCalledWith(
'ast-initial',
- {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
+ createExpectedAuthError(rawAuthError),
expect.any(Object),
);
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- {
- id: 'ast-initial',
- type: 'updateMessage',
- value: {
- content: '',
- error: {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
- },
- },
+ createExpectedAuthErrorUpdate(rawAuthError),
{ operationId: 'op-1' },
);
});
@@ -1583,38 +1577,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(contentWrite).toBeUndefined();
expect(mockUpdateMessageError).toHaveBeenCalledWith(
'ast-initial',
- {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
+ createExpectedAuthError(rawAuthError),
expect.any(Object),
);
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- {
- id: 'ast-initial',
- type: 'updateMessage',
- value: {
- content: '',
- error: {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
- },
- },
+ createExpectedAuthErrorUpdate(rawAuthError),
{ operationId: 'op-1' },
);
});
@@ -1653,38 +1620,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(contentWrite).toBeUndefined();
expect(mockUpdateMessageError).toHaveBeenCalledWith(
'ast-initial',
- {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
+ createExpectedAuthError(rawAuthError),
expect.any(Object),
);
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- {
- id: 'ast-initial',
- type: 'updateMessage',
- value: {
- content: '',
- error: {
- ...authMetadata,
- body: expect.objectContaining({
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- stderr: rawAuthError,
- }),
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- type: 'AgentRuntimeError',
- },
- },
- },
+ createExpectedAuthErrorUpdate(rawAuthError),
{ operationId: 'op-1' },
);
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 42c200522d4..9a065783a0f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -221,6 +221,15 @@ afterEach(() => {
vi.restoreAllMocks();
});
+const createUserMessage = () =>
+ ({
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ }) as UIChatMessage;
+
describe('StreamingExecutor actions', () => {
it('keeps the original source message when initializing and resuming a run', () => {
const params = {
@@ -255,13 +264,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const messages = [userMessage];
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, messages);
@@ -412,15 +415,7 @@ describe('StreamingExecutor actions', () => {
await act(async () => {
await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
- messages: [
- {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage,
- ],
+ messages: [createUserMessage()],
parentMessageId: TEST_IDS.USER_MESSAGE_ID,
parentMessageType: 'user',
});
@@ -458,15 +453,7 @@ describe('StreamingExecutor actions', () => {
await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
isSubAgent: true,
- messages: [
- {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage,
- ],
+ messages: [createUserMessage()],
parentMessageId: TEST_IDS.USER_MESSAGE_ID,
parentMessageType: 'user',
});
@@ -486,13 +473,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let streamCallCount = 0;
@@ -542,13 +523,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let streamCallCount = 0;
@@ -631,13 +606,7 @@ describe('StreamingExecutor actions', () => {
const stepSpy = vi.spyOn(agentRuntime.AgentRuntime.prototype, 'step');
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
@@ -676,13 +645,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
@@ -723,13 +686,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
const updateMessageErrorSpy = vi.spyOn(messageService, 'updateMessageError');
@@ -783,13 +740,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let cancelledAfterLLM = false;
@@ -900,6 +851,50 @@ describe('StreamingExecutor actions', () => {
});
describe('afterCompletion hooks', () => {
+ const createEmptyStateResult = (
+ operationId: string,
+ ): ReturnType<typeof realCreateAgentState> => ({
+ state: {
+ status: 'done' as const,
+ operationId,
+ messages: [],
+ maxSteps: 10,
+ stepCount: 0,
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ toolManifestMap: {},
+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },
+ usage: {
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ },
+ cost: {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ total: 0,
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ },
+ },
+ context: {
+ phase: 'init',
+ payload: { model: 'gpt-4o-mini', provider: 'openai' },
+ session: {
+ sessionId: TEST_IDS.SESSION_ID,
+ messageCount: 0,
+ status: 'done',
+ stepCount: 0,
+ },
+ },
+ agentConfig: createMockResolvedAgentConfig(),
+ });
+
it('should execute afterCompletion callbacks after runtime completes', async () => {
const { result } = renderHook(() => useChatStore());
@@ -941,47 +936,9 @@ describe('StreamingExecutor actions', () => {
).toHaveLength(2);
// Mock internal_createAgentState to return minimal state
- vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
- state: {
- status: 'done' as const,
- operationId: operationId!,
- messages: [],
- maxSteps: 10,
- stepCount: 0,
- createdAt: new Date().toISOString(),
- lastModified: new Date().toISOString(),
- toolManifestMap: {},
- userInterventionConfig: { approvalMode: 'manual', allowList: [] },
- usage: {
- llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
- tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- },
- cost: {
- calculatedAt: new Date().toISOString(),
- currency: 'USD',
- total: 0,
- llm: { byModel: [], currency: 'USD', total: 0 },
- tools: { byTool: [], currency: 'USD', total: 0 },
- },
- },
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 0,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue(
+ createEmptyStateResult(operationId!),
+ );
// Execute executeClientAgent with the pre-created operationId
await act(async () => {
@@ -1037,47 +994,9 @@ describe('StreamingExecutor actions', () => {
});
// Mock internal_createAgentState to return minimal state
- vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
- state: {
- status: 'done' as const,
- operationId: operationId!,
- messages: [],
- maxSteps: 10,
- stepCount: 0,
- createdAt: new Date().toISOString(),
- lastModified: new Date().toISOString(),
- toolManifestMap: {},
- userInterventionConfig: { approvalMode: 'manual', allowList: [] },
- usage: {
- llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
- tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- },
- cost: {
- calculatedAt: new Date().toISOString(),
- currency: 'USD',
- total: 0,
- llm: { byModel: [], currency: 'USD', total: 0 },
- tools: { byTool: [], currency: 'USD', total: 0 },
- },
- },
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 0,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue(
+ createEmptyStateResult(operationId!),
+ );
// Suppress console.error for this test
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -1138,47 +1057,9 @@ describe('StreamingExecutor actions', () => {
});
// Mock internal_createAgentState to return minimal state
- vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
- state: {
- status: 'done' as const,
- operationId: operationId!,
- messages: [],
- maxSteps: 10,
- stepCount: 0,
- createdAt: new Date().toISOString(),
- lastModified: new Date().toISOString(),
- toolManifestMap: {},
- userInterventionConfig: { approvalMode: 'manual', allowList: [] },
- usage: {
- llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
- tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- },
- cost: {
- calculatedAt: new Date().toISOString(),
- currency: 'USD',
- total: 0,
- llm: { byModel: [], currency: 'USD', total: 0 },
- tools: { byTool: [], currency: 'USD', total: 0 },
- },
- },
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 0,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue(
+ createEmptyStateResult(operationId!),
+ );
// Should not throw
await act(async () => {
@@ -1206,13 +1087,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
// Track initialContext passed to chatService across multiple calls
const capturedInitialContexts: any[] = [];
@@ -1281,13 +1156,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const capturedInitialContexts: any[] = [];
let streamCallCount = 0;
@@ -1356,13 +1225,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
agentConfig: createMockAgentConfig(),
@@ -1411,13 +1274,7 @@ describe('StreamingExecutor actions', () => {
desktopFlag.value = true;
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const createToolsEngineSpy = vi
.spyOn(toolEngineering, 'createAgentToolsEngine')
.mockImplementation(() => {
@@ -1456,13 +1313,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const generateToolsDetailed = vi.fn().mockReturnValue({
enabledManifests: [],
@@ -1628,13 +1479,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const generateToolsDetailed = vi.fn().mockReturnValue({
enabledManifests: [],
@@ -1675,13 +1520,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const generateToolsDetailed = vi.fn().mockReturnValue({
enabledManifests: [],
@@ -1720,13 +1559,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
const generateToolsDetailed = vi.fn().mockReturnValue({
enabledManifests: [],
@@ -1766,13 +1599,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
agentConfig: createMockAgentConfig({
@@ -1819,13 +1646,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
agentConfig: createMockAgentConfig(),
@@ -1938,13 +1759,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
// Get actual internal_createAgentState result with disableTools: true
const { state } = result.current.internal_createAgentState({
@@ -1966,13 +1781,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
// Get actual internal_createAgentState result with disableTools: true
const { agentConfig } = result.current.internal_createAgentState({
@@ -1995,13 +1804,7 @@ describe('StreamingExecutor actions', () => {
});
const { result } = renderHook(() => useChatStore());
- const userMessage = {
- id: TEST_IDS.USER_MESSAGE_ID,
- role: 'user',
- content: TEST_CONTENT.USER_MESSAGE,
- sessionId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- } as UIChatMessage;
+ const userMessage = createUserMessage();
// Mock resolveAgentConfig to return plugins
vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
@@ -2040,6 +1843,23 @@ describe('StreamingExecutor actions', () => {
});
describe('operation status handling', () => {
+ const createCompletedStateResult = (
+ operationId: string,
+ ): ReturnType<typeof realCreateAgentState> => ({
+ state: createMockRuntimeState(operationId, 'done'),
+ context: {
+ phase: 'init',
+ payload: { model: 'gpt-4o-mini', provider: 'openai' },
+ session: {
+ sessionId: TEST_IDS.SESSION_ID,
+ messageCount: 0,
+ status: 'done',
+ stepCount: 1,
+ },
+ },
+ agentConfig: createMockResolvedAgentConfig(),
+ });
+
it('emits client.runtime.complete with the latest assistant message id', async () => {
const { result } = renderHook(() => useChatStore());
@@ -2081,20 +1901,7 @@ describe('StreamingExecutor actions', () => {
}));
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
@@ -2159,20 +1966,7 @@ describe('StreamingExecutor actions', () => {
}));
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
@@ -2256,20 +2050,7 @@ describe('StreamingExecutor actions', () => {
}));
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
@@ -2342,20 +2123,7 @@ describe('StreamingExecutor actions', () => {
}));
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
@@ -2417,20 +2185,7 @@ describe('StreamingExecutor actions', () => {
operationId = res.operationId;
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
@@ -2476,20 +2231,7 @@ describe('StreamingExecutor actions', () => {
result.current.cancelOperation(operationId, 'user_cancelled');
});
- mockInternalCreateAgentState({
- state: createMockRuntimeState(operationId!, 'done'),
- context: {
- phase: 'init',
- payload: { model: 'gpt-4o-mini', provider: 'openai' },
- session: {
- sessionId: TEST_IDS.SESSION_ID,
- messageCount: 0,
- status: 'done',
- stepCount: 1,
- },
- },
- agentConfig: createMockResolvedAgentConfig(),
- });
+ mockInternalCreateAgentState(createCompletedStateResult(operationId!));
await act(async () => {
await result.current.executeClientAgent({
diff --git a/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.test.ts b/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.test.ts
index 135a0258d02..d3e8624c00e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.test.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands.test.ts
@@ -9,82 +9,56 @@ import {
parseSingleAgentMentionDirectRoute,
} from './parseCommands';
+const createEditorData = (children: unknown[]) => ({
+ root: { children: [{ children, type: 'paragraph' }], type: 'root' },
+});
+
describe('parseCommandsFromEditorData', () => {
it('should return empty array for undefined editorData', () => {
expect(parseCommandsFromEditorData(undefined)).toEqual([]);
});
it('should return empty array for editorData with no action tags', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [{ text: 'hello', type: 'text' }],
- type: 'paragraph',
- },
- ],
- type: 'root',
- },
- };
+ const editorData = createEditorData([{ text: 'hello', type: 'text' }]);
expect(parseCommandsFromEditorData(editorData)).toEqual([]);
});
it('should extract command tags from editorData', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'command',
- actionLabel: 'Send in new topic',
- actionType: 'newTopic',
- type: 'action-tag',
- },
- { text: ' some message', type: 'text' },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
},
- };
+ { text: ' some message', type: 'text' },
+ ]);
const result = parseCommandsFromEditorData(editorData);
expect(result).toEqual([{ category: 'command', label: 'Send in new topic', type: 'newTopic' }]);
});
it('should extract multiple tags in document order', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'command',
- actionLabel: 'Send in new topic',
- actionType: 'newTopic',
- type: 'action-tag',
- },
- {
- actionCategory: 'skill',
- actionLabel: 'Translate',
- actionType: 'translate',
- type: 'action-tag',
- },
- {
- actionCategory: 'tool',
- actionLabel: 'Notebook',
- actionType: 'lobe-notebook',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Translate',
+ actionType: 'translate',
+ type: 'action-tag',
},
- };
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ ]);
const result = parseCommandsFromEditorData(editorData);
expect(result).toHaveLength(3);
@@ -96,36 +70,26 @@ describe('parseCommandsFromEditorData', () => {
describe('parseSelectedSkillsFromEditorData', () => {
it('should return selected skills only', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'command',
- actionLabel: 'Compact context',
- actionType: 'compact',
- type: 'action-tag',
- },
- {
- actionCategory: 'skill',
- actionLabel: 'User Memory',
- actionType: 'user_memory',
- type: 'action-tag',
- },
- {
- actionCategory: 'skill',
- actionLabel: 'Instruction',
- actionType: 'instruction',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
},
- };
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Instruction',
+ actionType: 'instruction',
+ type: 'action-tag',
+ },
+ ]);
expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
{ identifier: 'user_memory', name: 'User Memory' },
@@ -134,30 +98,20 @@ describe('parseSelectedSkillsFromEditorData', () => {
});
it('should deduplicate selected skills by identifier', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'skill',
- actionLabel: 'User Memory',
- actionType: 'user_memory',
- type: 'action-tag',
- },
- {
- actionCategory: 'skill',
- actionLabel: 'User Memory Duplicate',
- actionType: 'user_memory',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
},
- };
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory Duplicate',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ ]);
expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
{ identifier: 'user_memory', name: 'User Memory' },
@@ -165,30 +119,20 @@ describe('parseSelectedSkillsFromEditorData', () => {
});
it('should ignore tool tags when selecting skills', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'tool',
- actionLabel: 'Notebook',
- actionType: 'lobe-notebook',
- type: 'action-tag',
- },
- {
- actionCategory: 'skill',
- actionLabel: 'User Memory',
- actionType: 'user_memory',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
},
- };
+ ]);
expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
{ identifier: 'user_memory', name: 'User Memory' },
@@ -198,36 +142,26 @@ describe('parseSelectedSkillsFromEditorData', () => {
describe('parseSelectedToolsFromEditorData', () => {
it('should return selected tools only', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'command',
- actionLabel: 'Compact context',
- actionType: 'compact',
- type: 'action-tag',
- },
- {
- actionCategory: 'tool',
- actionLabel: 'Notebook',
- actionType: 'lobe-notebook',
- type: 'action-tag',
- },
- {
- actionCategory: 'tool',
- actionLabel: 'Artifacts',
- actionType: 'lobe-artifacts',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
},
- };
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Artifacts',
+ actionType: 'lobe-artifacts',
+ type: 'action-tag',
+ },
+ ]);
expect(parseSelectedToolsFromEditorData(editorData)).toEqual([
{ identifier: 'lobe-notebook', name: 'Notebook' },
@@ -236,30 +170,20 @@ describe('parseSelectedToolsFromEditorData', () => {
});
it('should deduplicate selected tools by identifier', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'tool',
- actionLabel: 'Notebook',
- actionType: 'lobe-notebook',
- type: 'action-tag',
- },
- {
- actionCategory: 'tool',
- actionLabel: 'Notebook Duplicate',
- actionType: 'lobe-notebook',
- type: 'action-tag',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
},
- };
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook Duplicate',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ ]);
expect(parseSelectedToolsFromEditorData(editorData)).toEqual([
{ identifier: 'lobe-notebook', name: 'Notebook' },
@@ -273,38 +197,18 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should return empty array for editorData with no mention nodes', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [{ text: 'hello', type: 'text' }],
- type: 'paragraph',
- },
- ],
- type: 'root',
- },
- };
+ const editorData = createEditorData([{ text: 'hello', type: 'text' }]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
});
it('should extract agent mentions only (whitelist)', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'My Agent',
- metadata: { id: 'agent-1', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'My Agent',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
},
- };
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
{ id: 'agent-1', name: 'My Agent' },
@@ -312,77 +216,47 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should exclude topic mentions', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Some Topic',
- metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Some Topic',
+ metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
+ type: 'mention',
},
- };
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
});
it('should exclude ALL_MEMBERS and other non-agent mentions', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'All Members',
- metadata: { id: 'ALL_MEMBERS', type: 'all_members' },
- type: 'mention',
- },
- {
- label: 'Unknown',
- metadata: { id: 'x', type: 'custom' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'All Members',
+ metadata: { id: 'ALL_MEMBERS', type: 'all_members' },
+ type: 'mention',
},
- };
+ {
+ label: 'Unknown',
+ metadata: { id: 'x', type: 'custom' },
+ type: 'mention',
+ },
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
});
it('should deduplicate agents by id', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Agent A',
- metadata: { id: 'agent-1', type: 'agent' },
- type: 'mention',
- },
- {
- label: 'Agent A again',
- metadata: { id: 'agent-1', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
},
- };
+ {
+ label: 'Agent A again',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
+ },
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
{ id: 'agent-1', name: 'Agent A' },
@@ -390,28 +264,18 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should extract multiple distinct agent mentions', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Agent A',
- metadata: { id: 'agent-1', type: 'agent' },
- type: 'mention',
- },
- {
- label: 'Agent B',
- metadata: { id: 'agent-2', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
},
- };
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-2', type: 'agent' },
+ type: 'mention',
+ },
+ ]);
const result = parseMentionedAgentsFromEditorData(editorData);
expect(result).toEqual([
@@ -421,28 +285,18 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should only extract agents when mixed with topic mentions', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Topic X',
- metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
- type: 'mention',
- },
- {
- label: 'Agent Y',
- metadata: { id: 'agent-y', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Topic X',
+ metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
+ type: 'mention',
+ },
+ {
+ label: 'Agent Y',
+ metadata: { id: 'agent-y', type: 'agent' },
+ type: 'mention',
},
- };
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
{ id: 'agent-y', name: 'Agent Y' },
@@ -450,28 +304,18 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should handle nested children correctly', () => {
- const editorData = {
- root: {
+ const editorData = createEditorData([
+ {
children: [
{
- children: [
- {
- children: [
- {
- label: 'Nested Agent',
- metadata: { id: 'nested-1', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'paragraph',
+ label: 'Nested Agent',
+ metadata: { id: 'nested-1', type: 'agent' },
+ type: 'mention',
},
],
- type: 'root',
+ type: 'paragraph',
},
- };
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
{ id: 'nested-1', name: 'Nested Agent' },
@@ -479,23 +323,13 @@ describe('parseMentionedAgentsFromEditorData', () => {
});
it('should use id as fallback name when label is empty', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: '',
- metadata: { id: 'agent-no-label', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: '',
+ metadata: { id: 'agent-no-label', type: 'agent' },
+ type: 'mention',
},
- };
+ ]);
expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
{ id: 'agent-no-label', name: 'agent-no-label' },
@@ -509,24 +343,14 @@ describe('parseSingleAgentMentionDirectRoute', () => {
});
it('should detect a single leading agent mention', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Agent B',
- metadata: { id: 'agent-b', type: 'agent' },
- type: 'mention',
- },
- { text: ' please review this', type: 'text' },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-b', type: 'agent' },
+ type: 'mention',
},
- };
+ { text: ' please review this', type: 'text' },
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toEqual({
agent: { id: 'agent-b', name: 'Agent B' },
@@ -534,24 +358,14 @@ describe('parseSingleAgentMentionDirectRoute', () => {
});
it('should allow whitespace before the leading agent mention', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- { text: ' \n\t ', type: 'text' },
- {
- label: 'Agent B',
- metadata: { id: 'agent-b', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ { text: ' \n\t ', type: 'text' },
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-b', type: 'agent' },
+ type: 'mention',
},
- };
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toEqual({
agent: { id: 'agent-b', name: 'Agent B' },
@@ -559,101 +373,61 @@ describe('parseSingleAgentMentionDirectRoute', () => {
});
it('should reject an agent mention when text appears first', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- { text: 'please ask ', type: 'text' },
- {
- label: 'Agent B',
- metadata: { id: 'agent-b', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ { text: 'please ask ', type: 'text' },
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-b', type: 'agent' },
+ type: 'mention',
},
- };
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();
});
it('should reject multiple mention nodes even when only one is an agent', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Agent B',
- metadata: { id: 'agent-b', type: 'agent' },
- type: 'mention',
- },
- {
- label: 'Topic X',
- metadata: { id: 'topic-x', type: 'topic' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-b', type: 'agent' },
+ type: 'mention',
+ },
+ {
+ label: 'Topic X',
+ metadata: { id: 'topic-x', type: 'topic' },
+ type: 'mention',
},
- };
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();
});
it('should reject a single non-agent mention', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'Topic X',
- metadata: { id: 'topic-x', type: 'topic' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'Topic X',
+ metadata: { id: 'topic-x', type: 'topic' },
+ type: 'mention',
},
- };
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();
});
it('should reject when an action tag appears before the mention', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- actionCategory: 'skill',
- actionLabel: 'User Memory',
- actionType: 'user_memory',
- type: 'action-tag',
- },
- {
- label: 'Agent B',
- metadata: { id: 'agent-b', type: 'agent' },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
},
- };
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-b', type: 'agent' },
+ type: 'mention',
+ },
+ ]);
expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();
});
@@ -661,37 +435,27 @@ describe('parseSingleAgentMentionDirectRoute', () => {
describe('parseLocalFileReferencesFromEditorData', () => {
it('should extract local file mention metadata in document order', () => {
- const editorData = {
- root: {
- children: [
- {
- children: [
- {
- label: 'README.md',
- metadata: {
- name: 'README.md',
- path: '/Users/me/project/README.md',
- type: 'localFile',
- },
- type: 'mention',
- },
- {
- label: 'src',
- metadata: {
- isDirectory: true,
- name: 'src',
- path: '/Users/me/project/src',
- type: 'localFile',
- },
- type: 'mention',
- },
- ],
- type: 'paragraph',
- },
- ],
- type: 'root',
+ const editorData = createEditorData([
+ {
+ label: 'README.md',
+ metadata: {
+ name: 'README.md',
+ path: '/Users/me/project/README.md',
+ type: 'localFile',
+ },
+ type: 'mention',
},
- };
+ {
+ label: 'src',
+ metadata: {
+ isDirectory: true,
+ name: 'src',
+ path: '/Users/me/project/src',
+ type: 'localFile',
+ },
+ type: 'mention',
+ },
+ ]);
expect(parseLocalFileReferencesFromEditorData(editorData)).toEqual([
{ isDirectory: false, name: 'README.md', path: '/Users/me/project/README.md' },
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index 41637593cac..83112ae8df1 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -9,6 +9,13 @@ import type { AgentRuntimeType } from '../dispatch/agentDispatcher';
import { buildRunLifecycle } from './buildRunLifecycle';
import type { RunCompleteEvent, RunTerminalStatus, UserMessagePersistedEvent } from './types';
+const createDefaultTopicMap = () => ({
+ [topicMapKey({ agentId: 'a1' })]: {
+ items: [{ id: 't1', title: 'defaultTitle' }],
+ total: 1,
+ },
+});
+
const agentSignalBridgeMock = vi.hoisted(() => ({
emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),
}));
@@ -138,12 +145,7 @@ describe('buildRunLifecycle.completeRun — transport-driven disposition', () =>
store.drainQueuedMessages = vi.fn(() => [{ content: 'follow up', id: 'q1' } as any]);
store.queuedMessages = { [messageMapKey(CONTEXT)]: [{ content: 'follow up', id: 'q1' }] };
store.messagesMap = { [messageMapKey(CONTEXT)]: messages } as any;
- store.topicDataMap = {
- [topicMapKey({ agentId: 'a1' })]: {
- items: [{ id: 't1', title: 'defaultTitle' }],
- total: 1,
- },
- } as any;
+ store.topicDataMap = createDefaultTopicMap() as any;
const { requeued } = await lifecycle('client', get).completeRun(
completeEvent('client', { runtimeStatus: 'done' }),
@@ -492,12 +494,7 @@ describe('buildRunLifecycle.afterRunComplete — client desktop notification bod
} as any;
const messages = [voiceMessage, thisTurnAssistant];
store.messagesMap = { [KEY]: messages } as any;
- store.topicDataMap = {
- [topicMapKey({ agentId: 'a1' })]: {
- items: [{ id: 't1', title: 'defaultTitle' }],
- total: 1,
- },
- } as any;
+ store.topicDataMap = createDefaultTopicMap() as any;
await lifecycle('client', get).afterRunComplete(
completeEvent('client', { runtimeStatus: 'done' }),
@@ -530,12 +527,7 @@ describe('buildRunLifecycle.afterRunComplete — client desktop notification bod
},
];
store.messagesMap = { [KEY]: messages } as any;
- store.topicDataMap = {
- [topicMapKey({ agentId: 'a1' })]: {
- items: [{ id: 't1', title: 'defaultTitle' }],
- total: 1,
- },
- } as any;
+ store.topicDataMap = createDefaultTopicMap() as any;
await lifecycle('client', get).afterRunComplete(
completeEvent('client', { runtimeStatus: 'done' }),
@@ -561,12 +553,7 @@ describe('buildRunLifecycle.afterRunComplete — client desktop notification bod
{ ...thisTurnAssistant, content: 'Partial reply' },
],
} as any;
- store.topicDataMap = {
- [topicMapKey({ agentId: 'a1' })]: {
- items: [{ id: 't1', title: 'defaultTitle' }],
- total: 1,
- },
- } as any;
+ store.topicDataMap = createDefaultTopicMap() as any;
await lifecycle('client', get).afterRunComplete(completeEvent('client', { runtimeStatus }));
@@ -580,12 +567,7 @@ describe('buildRunLifecycle.afterRunComplete — client desktop notification bod
store.messagesMap = {
[KEY]: [{ content: 'hello', id: 'u1', role: 'user' }, thisTurnAssistant],
} as any;
- store.topicDataMap = {
- [topicMapKey({ agentId: 'a1' })]: {
- items: [{ id: 't1', title: 'defaultTitle' }],
- total: 1,
- },
- } as any;
+ store.topicDataMap = createDefaultTopicMap() as any;
await lifecycle('client', get).afterRunComplete(
completeEvent('client', { runtimeStatus: 'done' }),
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
index 0cb2bcb35b2..570820dce12 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
@@ -50,6 +50,26 @@ const createStore = (dbMessagesMap: Record<string, UIChatMessage[]> = {}) =>
updateOperationMetadata: vi.fn(),
}) as unknown as ChatStore;
+const createDefaultHandler = (store: ChatStore, assistantMessageId: string) =>
+ createGatewayEventHandler(() => store, {
+ assistantMessageId,
+ context,
+ operationId: 'op-1',
+ });
+
+const createGatewayLifecycleHandler = (
+ store: ChatStore,
+ assistantMessageId: string,
+ lifecycle: unknown,
+) =>
+ createGatewayEventHandler(() => store, {
+ assistantMessageId,
+ context,
+ operationId: 'op-1',
+ runLifecycle: lifecycle as any,
+ runtimeType: 'gateway',
+ });
+
// The handler enqueues work on an internal promise chain; flush the microtask
// queue so async event handlers settle before assertions. Each `await` inside a
// queued handler costs a tick, so keep this comfortably above the longest chain
@@ -115,11 +135,7 @@ describe('createGatewayEventHandler', () => {
it('inserts the assistant shell locally when stream_start carries the message seed (new server)', async () => {
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_start', {
@@ -156,11 +172,7 @@ describe('createGatewayEventHandler', () => {
.spyOn(messageService, 'getMessages')
.mockResolvedValue([] as unknown as UIChatMessage[]);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(makeEvent('stream_start', { assistantMessage: { id: 'step2-msg' } }));
await flush();
@@ -195,11 +207,7 @@ describe('createGatewayEventHandler', () => {
.spyOn(messageService, 'getMessages')
.mockResolvedValue([] as unknown as UIChatMessage[]);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(makeEvent('tool_end', { isSuccess: true, skipMessageFetch: true }));
await flush();
@@ -258,11 +266,7 @@ describe('createGatewayEventHandler', () => {
},
);
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -295,11 +299,7 @@ describe('createGatewayEventHandler', () => {
.spyOn(messageService, 'getMessages')
.mockResolvedValue([] as unknown as UIChatMessage[]);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('step_complete', {
@@ -342,11 +342,7 @@ describe('createGatewayEventHandler', () => {
store.dbMessagesMap[key] = messages;
},
);
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -431,11 +427,7 @@ describe('createGatewayEventHandler', () => {
store.dbMessagesMap[key] = messages;
},
);
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -482,11 +474,7 @@ describe('createGatewayEventHandler', () => {
} as UIChatMessage,
],
});
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -518,11 +506,7 @@ describe('createGatewayEventHandler', () => {
store.dbMessagesMap[key] = messages;
},
);
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -665,11 +649,7 @@ describe('createGatewayEventHandler', () => {
store.dbMessagesMap[key] = messages;
},
);
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_chunk', {
@@ -712,11 +692,7 @@ describe('createGatewayEventHandler', () => {
it('ignores a sub-agent progress event with no tool message anchor', async () => {
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(makeEvent('step_complete', { phase: 'subagent_progress', totalTokens: 10 }));
await flush();
@@ -775,11 +751,7 @@ describe('createGatewayEventHandler', () => {
const store = createStore({
key: [{ content: 'existing', id: 'step2-msg', role: 'assistant' } as UIChatMessage],
});
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'seed-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'seed-msg');
handler(
makeEvent('stream_start', {
@@ -793,11 +765,7 @@ describe('createGatewayEventHandler', () => {
it('skips the visible_output_end hint while the assistant row is missing ', async () => {
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'missing-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'missing-msg');
handler(makeEvent('visible_output_end'));
await flush();
@@ -809,11 +777,7 @@ describe('createGatewayEventHandler', () => {
const store = createStore({
key: [{ content: 'answer', id: 'answer-msg', role: 'assistant' } as UIChatMessage],
});
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'answer-msg');
handler(makeEvent('visible_output_end'));
await flush();
@@ -836,13 +800,7 @@ describe('createGatewayEventHandler', () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
// Stream the report text so `accumulatedContent` (the optimistic in-memory
// source) holds it, then end the run with no terminal uiMessages snapshot.
@@ -865,13 +823,7 @@ describe('createGatewayEventHandler', () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
// The stream dropped the tail; the server-finalized snapshot has the whole
// report, and the chat is reconciled to it — so must the notification be.
@@ -915,13 +867,7 @@ describe('createGatewayEventHandler', () => {
},
};
store.operationsByContext = { [contextKey]: ['op-1', 'op-2'] };
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
handler(
makeEvent('agent_runtime_end', {
@@ -960,13 +906,7 @@ describe('createGatewayEventHandler', () => {
},
};
store.operationsByContext = { [contextKey]: ['op-1', 'op-2'] };
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
const getMessages = vi.spyOn(messageService, 'getMessages');
handler(makeEvent('agent_runtime_end', { reason: 'completed' }));
@@ -1001,13 +941,7 @@ describe('createGatewayEventHandler', () => {
},
};
store.operationsByContext = { [contextKey]: ['op-1', 'op-member'] };
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
const uiMessages = [
{ content: 'council result', id: 'answer-msg', role: 'assistant' },
] as unknown as UIChatMessage[];
@@ -1046,11 +980,7 @@ describe('createGatewayEventHandler', () => {
);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'asst-1',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'asst-1');
handler(makeEvent('tool_end', { isSuccess: true }));
await flush();
@@ -1080,11 +1010,7 @@ describe('createGatewayEventHandler', () => {
const settled = { ...current[1], content: 'settled' };
const tool = { content: 'result', id: 'tool-1', role: 'tool' } as UIChatMessage;
const store = createStore({ [key]: current });
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'asst-1',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'asst-1');
handler(
makeEvent('message_patch', {
@@ -1111,11 +1037,7 @@ describe('createGatewayEventHandler', () => {
] as unknown as UIChatMessage[];
const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue(recovered);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'asst-1',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'asst-1');
handler(makeEvent('message_patch', { deletes: [], revision: 2, upserts: [] }));
await flush();
@@ -1142,11 +1064,7 @@ describe('createGatewayEventHandler', () => {
vi.mocked(store.replaceMessages).mockImplementation((messages) => {
store.dbMessagesMap[key] = messages;
});
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'asst-1',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'asst-1');
handler(
makeEvent('message_patch', {
@@ -1194,11 +1112,7 @@ describe('createGatewayEventHandler', () => {
);
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'asst-1',
- context,
- operationId: 'op-1',
- });
+ const handler = createDefaultHandler(store, 'asst-1');
handler(makeEvent('stream_start', { newStep: true }));
await flush();
@@ -1217,13 +1131,7 @@ describe('createGatewayEventHandler', () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'The final report.' }));
handler(
@@ -1245,13 +1153,7 @@ describe('createGatewayEventHandler', () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
handler(makeEvent('agent_runtime_end', { reason: 'completed' }));
await flush();
@@ -1265,13 +1167,7 @@ describe('createGatewayEventHandler', () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
const store = createStore();
- const handler = createGatewayEventHandler(() => store, {
- assistantMessageId: 'answer-msg',
- context,
- operationId: 'op-1',
- runLifecycle: lifecycle as any,
- runtimeType: 'gateway',
- });
+ const handler = createGatewayLifecycleHandler(store, 'answer-msg', lifecycle);
handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial' }));
handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));
diff --git a/src/store/chat/slices/message/actions/transcript.sync.test.ts b/src/store/chat/slices/message/actions/transcript.sync.test.ts
index 842b05d5a50..60aa8d32047 100644
--- a/src/store/chat/slices/message/actions/transcript.sync.test.ts
+++ b/src/store/chat/slices/message/actions/transcript.sync.test.ts
@@ -26,6 +26,48 @@ import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';
+const previousReplyInput = (): UIChatMessage => ({
+ id: 'previous-reply',
+ content: 'Previous reply',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+});
+
+const sentMessage = (): UIChatMessage => ({
+ id: 'tmp_client',
+ content: 'Sent',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+});
+
+const pendingQuestion = (): UIChatMessage => ({
+ id: 'question',
+ content: '',
+ role: 'tool',
+ tool_call_id: 'call-1',
+ createdAt: 1,
+ updatedAt: 1,
+ pluginIntervention: { status: 'pending' },
+});
+
+const followupMessage = (): UIChatMessage => ({
+ id: 'msg_user',
+ content: 'Follow-up question',
+ role: 'user',
+ createdAt: 2000,
+ updatedAt: 2000,
+});
+
+const assistantPlaceholder = (): UIChatMessage => ({
+ id: 'msg_assistant',
+ content: '...',
+ role: 'assistant',
+ createdAt: 2001,
+ updatedAt: 2001,
+});
+
vi.mock('@lobechat/conversation-flow', () => ({
parse: (messages: UIChatMessage[]) => ({
flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),
@@ -507,27 +549,9 @@ describe('useFetchMessages', () => {
});
it('keeps optimistic send rows when a stale fetch resolves before the server run starts', async () => {
- const previousReply: UIChatMessage = {
- id: 'previous-reply',
- content: 'Previous reply',
- role: 'assistant',
- createdAt: 1000,
- updatedAt: 1000,
- };
- const optimisticUser: UIChatMessage = {
- id: 'msg_user',
- content: 'Follow-up question',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
- const optimisticAssistant: UIChatMessage = {
- id: 'msg_assistant',
- content: '...',
- role: 'assistant',
- createdAt: 2001,
- updatedAt: 2001,
- };
+ const previousReply: UIChatMessage = previousReplyInput();
+ const optimisticUser: UIChatMessage = followupMessage();
+ const optimisticAssistant: UIChatMessage = assistantPlaceholder();
// The fetch was issued before the server persisted the new rows.
vi.mocked(messageService.getMessages).mockResolvedValue([
{ ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 },
@@ -557,27 +581,9 @@ describe('useFetchMessages', () => {
});
it('keeps optimistic rows that were already present when the read started', async () => {
- const previousReply: UIChatMessage = {
- id: 'previous-reply',
- content: 'Previous reply',
- role: 'assistant',
- createdAt: 1000,
- updatedAt: 1000,
- };
- const sentUser: UIChatMessage = {
- id: 'msg_user',
- content: 'Follow-up question',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
- const sentAssistant: UIChatMessage = {
- id: 'msg_assistant',
- content: '...',
- role: 'assistant',
- createdAt: 2001,
- updatedAt: 2001,
- };
+ const previousReply: UIChatMessage = previousReplyInput();
+ const sentUser: UIChatMessage = followupMessage();
+ const sentAssistant: UIChatMessage = assistantPlaceholder();
// The server has not persisted the optimistic pair when a poll or focus
// read starts, so its snapshot omits them even though they exist locally.
@@ -658,13 +664,7 @@ describe('useFetchMessages', () => {
});
it('forgets a temporary id once a server replacement remaps it', () => {
- const temp: UIChatMessage = {
- id: 'tmp_client',
- content: 'Sent',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
+ const temp: UIChatMessage = sentMessage();
useChatStore
.getState()
.internal_dispatchMessage(
@@ -681,23 +681,9 @@ describe('useFetchMessages', () => {
});
it('lets the forced reread drop a row confirmed while awaiting the topic decision', async () => {
- const question: UIChatMessage = {
- id: 'question',
- content: '',
- role: 'tool',
- tool_call_id: 'call-1',
- createdAt: 1,
- updatedAt: 1,
- pluginIntervention: { status: 'pending' },
- };
+ const question: UIChatMessage = pendingQuestion();
const answered: UIChatMessage = { ...question, pluginIntervention: { status: 'approved' } };
- const temp: UIChatMessage = {
- id: 'tmp_client',
- content: 'Sent',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
+ const temp: UIChatMessage = sentMessage();
const serverRow: UIChatMessage = { ...temp, id: 'msg_server' };
let calls = 0;
@@ -741,15 +727,7 @@ describe('useFetchMessages', () => {
});
it('keeps a client row when two fetches share a result across the topic wait', async () => {
- const question: UIChatMessage = {
- id: 'question',
- content: '',
- role: 'tool',
- tool_call_id: 'call-1',
- createdAt: 1,
- updatedAt: 1,
- pluginIntervention: { status: 'pending' },
- };
+ const question: UIChatMessage = pendingQuestion();
const answered: UIChatMessage = { ...question, pluginIntervention: { status: 'approved' } };
const sent: UIChatMessage = {
id: 'msg_user',
@@ -832,20 +810,8 @@ describe('useFetchMessages', () => {
});
it('keeps a remapped row when a read issued before its temporary id resolves', async () => {
- const previousReply: UIChatMessage = {
- id: 'previous-reply',
- content: 'Previous reply',
- role: 'assistant',
- createdAt: 1000,
- updatedAt: 1000,
- };
- const temp: UIChatMessage = {
- id: 'tmp_client',
- content: 'Sent',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
+ const previousReply: UIChatMessage = previousReplyInput();
+ const temp: UIChatMessage = sentMessage();
const persisted: UIChatMessage = { ...temp, id: 'msg_server' };
// The read starts before the optimistic create.
@@ -882,20 +848,8 @@ describe('useFetchMessages', () => {
});
it('drops a remapped row omitted by a generation restarted after the remap', async () => {
- const previousReply: UIChatMessage = {
- id: 'previous-reply',
- content: 'Previous reply',
- role: 'assistant',
- createdAt: 1000,
- updatedAt: 1000,
- };
- const temp: UIChatMessage = {
- id: 'tmp_client',
- content: 'Sent',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
+ const previousReply: UIChatMessage = previousReplyInput();
+ const temp: UIChatMessage = sentMessage();
const persisted: UIChatMessage = { ...temp, id: 'msg_server' };
let resolveFirst!: (messages: UIChatMessage[]) => void;
@@ -938,27 +892,9 @@ describe('useFetchMessages', () => {
});
it('keeps a send whose stale fetch resolves after the send operation handed off', async () => {
- const previousReply: UIChatMessage = {
- id: 'previous-reply',
- content: 'Previous reply',
- role: 'assistant',
- createdAt: 1000,
- updatedAt: 1000,
- };
- const sentUser: UIChatMessage = {
- id: 'msg_user',
- content: 'Follow-up question',
- role: 'user',
- createdAt: 2000,
- updatedAt: 2000,
- };
- const sentAssistant: UIChatMessage = {
- id: 'msg_assistant',
- content: '...',
- role: 'assistant',
- createdAt: 2001,
- updatedAt: 2001,
- };
+ const previousReply: UIChatMessage = previousReplyInput();
+ const sentUser: UIChatMessage = followupMessage();
+ const sentAssistant: UIChatMessage = assistantPlaceholder();
// The topic's read is still in flight from before the send.
let resolveFetch!: (messages: UIChatMessage[]) => void;
@@ -1102,15 +1038,7 @@ describe('useFetchMessages', () => {
});
it('keeps a client row created while the fetch waits for the topic decision', async () => {
- const question: UIChatMessage = {
- id: 'question',
- content: '',
- role: 'tool',
- tool_call_id: 'call-1',
- createdAt: 1,
- updatedAt: 1,
- pluginIntervention: { status: 'pending' },
- };
+ const question: UIChatMessage = pendingQuestion();
const answered: UIChatMessage = {
...question,
pluginIntervention: { status: 'approved' },
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
index 1fb9e7255f9..cb5adb4f9db 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -18,7 +18,7 @@ vi.mock('i18next', () => ({
const initialStore = initialState as ChatStore;
-const mockMessages = [
+const createMessageFixture = () => [
{
id: 'msg1',
content: 'Hello World',
@@ -43,7 +43,24 @@ const mockMessages = [
},
],
},
-] as UIChatMessage[];
+];
+
+const createTestTool = (): NonNullable<UIChatMessage['tools']>[number] => ({
+ id: 'tool-1',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '{}',
+ type: 'default',
+});
+
+const createDisplayState = (message: UIChatMessage): Partial<ChatStore> => ({
+ activeAgentId: 'test-id',
+ messagesMap: {
+ [messageMapKey({ agentId: 'test-id' })]: [message],
+ },
+});
+
+const mockMessages = createMessageFixture() as UIChatMessage[];
const mockReasoningMessages = [
{
@@ -66,32 +83,7 @@ const mockReasoningMessages = [
},
] as UIChatMessage[];
-const mockedChats = [
- {
- id: 'msg1',
- content: 'Hello World',
- role: 'user',
- },
- {
- id: 'msg2',
- content: 'Goodbye World',
- role: 'user',
- },
- {
- id: 'msg3',
- content: 'Function Message',
- role: 'tool',
- tools: [
- {
- arguments: ['arg1', 'arg2'],
- identifier: 'func1',
- apiName: 'ttt',
- type: 'pluginType',
- id: 'abc',
- },
- ],
- },
-] as UIChatMessage[];
+const mockedChats = createMessageFixture() as UIChatMessage[];
const mockChatStore = {
messagesMap: {
@@ -406,15 +398,7 @@ describe('displayMessageSelectors', () => {
{
id: 'child-1',
content: 'First response',
- tools: [
- {
- id: 'tool-1',
- identifier: 'test',
- apiName: 'test',
- arguments: '{}',
- type: 'default',
- },
- ],
+ tools: [createTestTool()],
},
{
id: 'child-2',
@@ -428,12 +412,7 @@ describe('displayMessageSelectors', () => {
],
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-1')(
state as ChatStore,
@@ -456,25 +435,12 @@ describe('displayMessageSelectors', () => {
{
id: 'child-2',
content: 'Second response with tools',
- tools: [
- {
- id: 'tool-1',
- identifier: 'test',
- apiName: 'test',
- arguments: '{}',
- type: 'default',
- },
- ],
+ tools: [createTestTool()],
},
],
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-2')(
state as ChatStore,
@@ -491,15 +457,7 @@ describe('displayMessageSelectors', () => {
{
id: 'child-1',
content: 'First response with tools',
- tools: [
- {
- id: 'tool-1',
- identifier: 'test',
- apiName: 'test',
- arguments: '{}',
- type: 'default',
- },
- ],
+ tools: [createTestTool()],
},
{
id: 'child-2',
@@ -509,12 +467,7 @@ describe('displayMessageSelectors', () => {
],
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-3')(
state as ChatStore,
@@ -531,12 +484,7 @@ describe('displayMessageSelectors', () => {
content: 'Regular message',
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [assistantMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(assistantMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('msg-1')(
state as ChatStore,
@@ -552,12 +500,7 @@ describe('displayMessageSelectors', () => {
children: undefined,
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-4')(
state as ChatStore,
@@ -573,12 +516,7 @@ describe('displayMessageSelectors', () => {
children: [],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-5')(
state as ChatStore,
@@ -595,15 +533,7 @@ describe('displayMessageSelectors', () => {
{
id: 'child-1',
content: 'First response',
- tools: [
- {
- id: 'tool-1',
- identifier: 'test',
- apiName: 'test',
- arguments: '{}',
- type: 'default',
- },
- ],
+ tools: [createTestTool()],
},
{
id: 'child-2',
@@ -621,12 +551,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-6')(
state as ChatStore,
@@ -648,12 +573,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.getGroupLatestMessageWithoutTools('group-7')(
state as ChatStore,
@@ -685,12 +605,7 @@ describe('displayMessageSelectors', () => {
content: 'Simple message',
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [message],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(message);
const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
expect(result).toBe('msg-1');
@@ -713,12 +628,7 @@ describe('displayMessageSelectors', () => {
],
} as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [groupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(groupMessage);
const result = displayMessageSelectors.findLastMessageId('group-1')(state as ChatStore);
expect(result).toBe('child-2');
@@ -749,12 +659,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [messageWithTools],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(messageWithTools);
const result = displayMessageSelectors.findLastMessageId('msg-with-tools')(
state as ChatStore,
@@ -785,12 +690,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [message],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(message);
const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
expect(result).toBe('child-1');
@@ -835,12 +735,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [messageWithChildrenAndTools],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(messageWithChildrenAndTools);
const result = displayMessageSelectors.findLastMessageId('msg-1')(state as ChatStore);
expect(result).toBe('child-2');
@@ -887,12 +782,7 @@ describe('displayMessageSelectors', () => {
],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [assistantGroup],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(assistantGroup);
const result = displayMessageSelectors.findLastMessageId('assistant-group-1')(
state as ChatStore,
@@ -911,12 +801,7 @@ describe('displayMessageSelectors', () => {
pinnedMessages: [],
} as unknown as UIChatMessage;
- const state: Partial<ChatStore> = {
- activeAgentId: 'test-id',
- messagesMap: {
- [messageMapKey({ agentId: 'test-id' })]: [compressedGroupMessage],
- },
- };
+ const state: Partial<ChatStore> = createDisplayState(compressedGroupMessage);
const result = displayMessageSelectors.findLastMessageId('mg_123456')(state as ChatStore);
expect(result).toBe('msg-999');
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.ts
index 1c9f919023b..bee60c4c638 100644
--- a/src/store/chat/slices/thread/action.test.ts
+++ b/src/store/chat/slices/thread/action.test.ts
@@ -103,6 +103,19 @@ const makeThread = (id: string, title: string, topicId = 'test-topic-id'): Threa
userId: 'user-1',
});
+const makeUpdateThread = (title: string): ThreadItem => ({
+ createdAt: new Date(),
+ id: 'thread-id',
+ lastActiveAt: new Date(),
+ sourceMessageId: 'msg-1',
+ status: ThreadStatus.Active,
+ title,
+ topicId: 'test-topic-id',
+ type: ThreadType.Continuation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+});
+
/** Fetch a topic's threads through the replica and wait until they are persisted. */
const seedPersistedThreads = async (topicId: string, threads: ThreadItem[]) => {
(threadService.getThreads as Mock).mockResolvedValueOnce(threads);
@@ -585,18 +598,7 @@ describe('thread action', () => {
it('should generate and update thread title via AI', async () => {
const { result } = renderHook(() => useChatStore());
- const mockThread: ThreadItem = {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Old Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- };
+ const mockThread: ThreadItem = makeUpdateThread('Old Title');
act(() => {
useChatStore.setState({
@@ -647,18 +649,7 @@ describe('thread action', () => {
it('should show loading indicator during generation', async () => {
const { result } = renderHook(() => useChatStore());
- const mockThread: ThreadItem = {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Old Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- };
+ const mockThread: ThreadItem = makeUpdateThread('Old Title');
act(() => {
useChatStore.setState({
@@ -688,18 +679,7 @@ describe('thread action', () => {
it('should revert title on error', async () => {
const { result } = renderHook(() => useChatStore());
- const mockThread: ThreadItem = {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Old Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- };
+ const mockThread: ThreadItem = makeUpdateThread('Old Title');
act(() => {
useChatStore.setState({
@@ -754,20 +734,7 @@ describe('thread action', () => {
useChatStore.setState({
activeTopicId: 'test-topic-id',
threadMaps: {
- 'test-topic-id': [
- {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Old Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- },
- ],
+ 'test-topic-id': [makeUpdateThread('Old Title')],
},
});
});
@@ -882,18 +849,7 @@ describe('thread action', () => {
it('should update threadMaps with reducer result', () => {
const { result } = renderHook(() => useChatStore());
- const mockThread: ThreadItem = {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Old Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- };
+ const mockThread: ThreadItem = makeUpdateThread('Old Title');
act(() => {
useChatStore.setState({
@@ -921,18 +877,7 @@ describe('thread action', () => {
it('should not update if result is the same', () => {
const { result } = renderHook(() => useChatStore());
- const mockThread: ThreadItem = {
- createdAt: new Date(),
- id: 'thread-id',
- lastActiveAt: new Date(),
- sourceMessageId: 'msg-1',
- status: ThreadStatus.Active,
- title: 'Title',
- topicId: 'test-topic-id',
- type: ThreadType.Continuation,
- updatedAt: new Date(),
- userId: 'user-1',
- };
+ const mockThread: ThreadItem = makeUpdateThread('Title');
act(() => {
useChatStore.setState({
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 475d4e24a99..1c1276e218d 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -31,6 +31,35 @@ import { type ChatTopic } from '@/types/topic';
import { useChatStore } from '../../store';
import { topicListResource } from './projection';
+const topicState = (key: string, topics: ChatTopic[], total: number) => ({
+ activeAgentId: 'test',
+ topicDataMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: false,
+ items: topics,
+ pageSize: 20,
+ total,
+ },
+ },
+});
+
+const topicPage = (topics: ChatTopic[], total: number) => ({
+ items: topics,
+ total,
+ currentPage: 0,
+ hasMore: false,
+ pageSize: 20,
+});
+
+const singleTopicPage = (topic: ChatTopic) => ({
+ currentPage: 0,
+ hasMore: false,
+ items: [topic],
+ pageSize: 20,
+ total: 1,
+});
+
// Revalidation is narrowed to the active identity scope.
const topicListSyncKey = (containerKey: string, scope = cacheScope.get()) =>
replicaKeys.sync(topicListResource.name, topicListResource.version, scope, containerKey, {
@@ -2593,13 +2622,7 @@ describe('topic action', () => {
useChatStore.setState({
activeAgentId: 'abc',
topicDataMap: {
- [topicMapKey({ agentId: 'abc' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'abc' })]: topicPage(topics, topics.length),
},
});
});
@@ -2771,13 +2794,7 @@ describe('topic action', () => {
operationsByContext: {},
operationsByMessage: {},
topicDataMap: {
- [key]: {
- currentPage: 0,
- hasMore: false,
- items: [topic],
- pageSize: 20,
- total: 1,
- },
+ [key]: singleTopicPage(topic),
},
});
});
@@ -2842,13 +2859,7 @@ describe('topic action', () => {
operationsByContext: {},
operationsByMessage: {},
topicDataMap: {
- [groupKey]: {
- currentPage: 0,
- hasMore: false,
- items: [topic],
- pageSize: 20,
- total: 1,
- },
+ [groupKey]: singleTopicPage(topic),
},
});
});
@@ -2901,13 +2912,7 @@ describe('topic action', () => {
operationsByContext: {},
operationsByMessage: {},
topicDataMap: {
- [key]: {
- currentPage: 0,
- hasMore: false,
- items: [topic],
- pageSize: 20,
- total: 1,
- },
+ [key]: singleTopicPage(topic),
},
});
});
@@ -3695,13 +3700,7 @@ describe('topic action', () => {
useChatStore.setState({
activeAgentId: agentId,
topicDataMap: {
- [key]: {
- currentPage: 0,
- hasMore: false,
- items: [topic],
- pageSize: 20,
- total: 1,
- },
+ [key]: singleTopicPage(topic),
},
});
};
@@ -4000,18 +3999,7 @@ describe('topic action', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- useChatStore.setState({
- activeAgentId: 'test',
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- currentPage: 0,
- hasMore: false,
- items: topics,
- pageSize: 20,
- total: topics.length,
- },
- },
- });
+ useChatStore.setState(topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));
});
const updateTitleSpy = vi.spyOn(result.current, 'internal_updateTopicTitleInSummary');
@@ -4040,18 +4028,7 @@ describe('topic action', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- useChatStore.setState({
- activeAgentId: 'test',
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- currentPage: 0,
- hasMore: false,
- items: topics,
- pageSize: 20,
- total: topics.length,
- },
- },
- });
+ useChatStore.setState(topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));
});
const updateTitleSpy = vi.spyOn(result.current, 'internal_updateTopicTitleInSummary');
@@ -4100,18 +4077,7 @@ describe('topic action', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- useChatStore.setState({
- activeAgentId: 'test',
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- currentPage: 0,
- hasMore: false,
- items: topics,
- pageSize: 20,
- total: topics.length,
- },
- },
- });
+ useChatStore.setState(topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));
});
const generateSpy = vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({
@@ -4134,18 +4100,7 @@ describe('topic action', () => {
const { result } = renderHook(() => useChatStore());
await act(async () => {
- useChatStore.setState({
- activeAgentId: 'test',
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- currentPage: 0,
- hasMore: false,
- items: topics,
- pageSize: 20,
- total: topics.length,
- },
- },
- });
+ useChatStore.setState(topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));
});
let resolveGeneration!: (value: unknown) => void;
@@ -4179,13 +4134,7 @@ describe('topic action', () => {
await act(async () => {
useChatStore.setState({
topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'test' })]: topicPage(topics, topics.length),
},
activeAgentId: 'test',
});
@@ -4221,13 +4170,7 @@ describe('topic action', () => {
await act(async () => {
useChatStore.setState({
topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'test' })]: topicPage(topics, topics.length),
},
activeAgentId: 'test',
});
@@ -4263,13 +4206,7 @@ describe('topic action', () => {
await act(async () => {
useChatStore.setState({
topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'test' })]: topicPage(topics, topics.length),
},
activeAgentId: 'test',
});
@@ -4441,13 +4378,7 @@ describe('topic action', () => {
useChatStore.setState({
activeAgentId: 'abc',
topicDataMap: {
- [topicMapKey({ agentId: 'abc' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'abc' })]: topicPage(topics, topics.length),
},
});
});
@@ -4477,13 +4408,7 @@ describe('topic action', () => {
activeAgentId: 'abc',
activeTopicId: topicId,
topicDataMap: {
- [topicMapKey({ agentId: 'abc' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
+ [topicMapKey({ agentId: 'abc' })]: topicPage(topics, topics.length),
},
});
});
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 5025c2117de..df2aa0b2650 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -8,6 +8,19 @@ import { merge } from '@/utils/merge';
import { topicSelectors } from './selectors';
+const topicState = <T>(key: string, topics: T[], total: number) => ({
+ topicDataMap: {
+ [key]: {
+ items: topics,
+ total,
+ currentPage: 0,
+ hasMore: false,
+ pageSize: 20,
+ },
+ },
+ activeAgentId: 'test',
+});
+
// Mock i18next
vi.mock('i18next', () => ({
t: vi.fn().mockImplementation((key) => key),
@@ -467,18 +480,10 @@ describe('topicSelectors', () => {
{ id: 'topic2', name: 'Topic 2', favorite: false, createAt: '2023-01-01' },
];
- const state = merge(initialStore, {
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
- },
- activeAgentId: 'test',
- });
+ const state = merge(
+ initialStore,
+ topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
+ );
const grouped = topicSelectors.groupedTopicsSelector()(state);
expect(grouped).toHaveLength(1); // One time-based group
@@ -492,18 +497,10 @@ describe('topicSelectors', () => {
{ id: 'topic3', name: 'Topic 3', favorite: true, createAt: '2023-01-01' },
];
- const state = merge(initialStore, {
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
- },
- activeAgentId: 'test',
- });
+ const state = merge(
+ initialStore,
+ topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
+ );
const grouped = topicSelectors.groupedTopicsSelector()(state);
@@ -526,18 +523,10 @@ describe('topicSelectors', () => {
{ id: 'topic2', name: 'Topic 2', favorite: false, createAt: '2023-02-01' },
];
- const state = merge(initialStore, {
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
- },
- activeAgentId: 'test',
- });
+ const state = merge(
+ initialStore,
+ topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
+ );
const grouped = topicSelectors.groupedTopicsSelector()(state);
@@ -831,18 +820,7 @@ describe('topicSelectors', () => {
];
const createStateWithTopics = (topics: any[]) =>
- merge(initialStore, {
- topicDataMap: {
- [topicMapKey({ agentId: 'test' })]: {
- items: topics,
- total: topics.length,
- currentPage: 0,
- hasMore: false,
- pageSize: 20,
- },
- },
- activeAgentId: 'test',
- });
+ merge(initialStore, topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));
it('should group by createdAt when sortBy is createdAt', () => {
const state = createStateWithTopics(topicsWithDifferentTimes);
diff --git a/src/store/discover/slices/mcp/action.test.ts b/src/store/discover/slices/mcp/action.test.ts
index 731e4da076f..c333daae8e6 100644
--- a/src/store/discover/slices/mcp/action.test.ts
+++ b/src/store/discover/slices/mcp/action.test.ts
@@ -222,19 +222,13 @@ describe('MCPSlice (replica)', () => {
});
describe('useMcpCategories', () => {
- it('does not revalidate the categories on window focus', async () => {
- renderHook(() => useStore.getState().useMcpCategories({ q: 'github' }));
-
- const [call] = await syncCalls('mcpCategories');
- expect(call.config.revalidateOnFocus).toBe(false);
- });
-
it('requests category counts with the search term and the locale', async () => {
const { discoverService } = await import('@/services/discover');
renderHook(() => useStore.getState().useMcpCategories({ q: 'github' }));
const [call] = await syncCalls('mcpCategories');
+ expect(call.config.revalidateOnFocus).toBe(false);
await call.fetcher();
expect(discoverService.getMcpCategories).toHaveBeenCalledWith({
diff --git a/src/store/discover/slices/user/action.test.ts b/src/store/discover/slices/user/action.test.ts
index ba30b79756e..c5e12a3c5b3 100644
--- a/src/store/discover/slices/user/action.test.ts
+++ b/src/store/discover/slices/user/action.test.ts
@@ -84,7 +84,6 @@ describe('UserSlice (replica)', () => {
const [call] = await syncCalls('discoverUserProfile');
- expect(call.key[1]).toBe('discoverUserProfile');
expect(call.key[4]).toBe(entryKey('alice'));
});
diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.ts
index 38a164605ba..fa0713c1661 100644
--- a/src/store/file/slices/document/action.test.ts
+++ b/src/store/file/slices/document/action.test.ts
@@ -31,6 +31,19 @@ import { getResourceQueryKey } from '../resource/utils';
import { initialDocumentState } from './initialState';
import { fileDocumentResource } from './projection';
+const documentResourceState = (document: LobeDocument, existingResource: ResourceItem) => ({
+ documentMap: { 'doc-1': { document } },
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [existingResource],
+ resourceMap: new Map([[existingResource.id, existingResource]]),
+});
+
+const savedDocumentResponse = () => ({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+});
+
const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
@@ -385,24 +398,12 @@ describe('file document replica', () => {
it('updates the replica and the visible resource after a successful save', async () => {
const existingResource = createResourceFixture();
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
- } as any);
+ vi.mocked(documentService.updateDocument).mockResolvedValue(savedDocumentResponse() as any);
const { result } = renderHook(() => useFileStore(), { wrapper });
act(() => {
- useFileStore.setState(
- {
- documentMap: { 'doc-1': { document: lobeDocument() } },
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
- );
+ useFileStore.setState(documentResourceState(lobeDocument(), existingResource), false);
});
await act(async () => {
@@ -444,15 +445,7 @@ describe('file document replica', () => {
const { result } = renderHook(() => useFileStore(), { wrapper });
act(() => {
- useFileStore.setState(
- {
- documentMap: { 'doc-1': { document: lobeDocument() } },
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
- );
+ useFileStore.setState(documentResourceState(lobeDocument(), existingResource), false);
});
let pendingUpdate!: Promise<void>;
@@ -499,15 +492,7 @@ describe('file document replica', () => {
const { result } = renderHook(() => useFileStore(), { wrapper });
act(() => {
- useFileStore.setState(
- {
- documentMap: { 'doc-1': { document: lobeDocument() } },
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
- );
+ useFileStore.setState(documentResourceState(lobeDocument(), existingResource), false);
});
await act(async () => {
@@ -531,11 +516,7 @@ describe('file document replica', () => {
},
} as any;
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
- } as any);
+ vi.mocked(documentService.updateDocument).mockResolvedValue(savedDocumentResponse() as any);
const { result } = renderHook(() => useFileStore(), { wrapper });
@@ -581,24 +562,12 @@ describe('file document replica', () => {
delete existingResource.knowledgeBaseId;
delete existingResource.parentId;
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
- } as any);
+ vi.mocked(documentService.updateDocument).mockResolvedValue(savedDocumentResponse() as any);
const { result } = renderHook(() => useFileStore(), { wrapper });
act(() => {
- useFileStore.setState(
- {
- documentMap: { 'doc-1': { document: lobeDocument() } },
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
- );
+ useFileStore.setState(documentResourceState(lobeDocument(), existingResource), false);
});
await act(async () => {
diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.ts
index 378151bc90e..33b9b810d06 100644
--- a/src/store/file/slices/fileManager/action.test.ts
+++ b/src/store/file/slices/fileManager/action.test.ts
@@ -60,6 +60,27 @@ vi.mock('@/libs/trpc/client', () => ({
},
}));
+const createFileBackedDocumentState = (): Pick<
+ ReturnType<typeof useStore.getState>,
+ 'resourceMap'
+> => ({
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+});
+
beforeEach(() => {
vi.clearAllMocks();
useStore.setState(
@@ -289,23 +310,7 @@ describe('FileManagerActions', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({
- resourceMap: new Map([
- [
- 'docs_1',
- {
- createdAt: new Date(),
- fileId: 'file_1',
- fileType: 'text/plain',
- id: 'docs_1',
- name: 'Document-backed file',
- size: 1,
- sourceType: 'file',
- updatedAt: new Date(),
- },
- ],
- ]),
- });
+ useStore.setState(createFileBackedDocumentState());
});
const createTaskSpy = vi
@@ -366,23 +371,7 @@ describe('FileManagerActions', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({
- resourceMap: new Map([
- [
- 'docs_1',
- {
- createdAt: new Date(),
- fileId: 'file_1',
- fileType: 'text/plain',
- id: 'docs_1',
- name: 'Document-backed file',
- size: 1,
- sourceType: 'file',
- updatedAt: new Date(),
- },
- ],
- ]),
- });
+ useStore.setState(createFileBackedDocumentState());
});
const createTaskSpy = vi
@@ -833,23 +822,7 @@ describe('FileManagerActions', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({
- resourceMap: new Map([
- [
- 'docs_1',
- {
- createdAt: new Date(),
- fileId: 'file_1',
- fileType: 'text/plain',
- id: 'docs_1',
- name: 'Document-backed file',
- size: 1,
- sourceType: 'file',
- updatedAt: new Date(),
- },
- ],
- ]),
- });
+ useStore.setState(createFileBackedDocumentState());
});
const toggleSpy = vi.spyOn(result.current, 'toggleEmbeddingIds');
@@ -895,23 +868,7 @@ describe('FileManagerActions', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({
- resourceMap: new Map([
- [
- 'docs_1',
- {
- createdAt: new Date(),
- fileId: 'file_1',
- fileType: 'text/plain',
- id: 'docs_1',
- name: 'Document-backed file',
- size: 1,
- sourceType: 'file',
- updatedAt: new Date(),
- },
- ],
- ]),
- });
+ useStore.setState(createFileBackedDocumentState());
});
const toggleSpy = vi.spyOn(result.current, 'toggleParsingIds');
@@ -991,131 +948,70 @@ describe('FileManagerActions', () => {
});
});
- describe('toggleEmbeddingIds', () => {
- it('should add ids when loading is true', () => {
- const { result } = renderHook(() => useStore());
-
- act(() => {
- result.current.toggleEmbeddingIds(['file-1', 'file-2'], true);
- });
-
- expect(result.current.creatingEmbeddingTaskIds).toEqual(['file-1', 'file-2']);
- });
-
- it('should remove ids when loading is false', () => {
- const { result } = renderHook(() => useStore());
-
- act(() => {
- useStore.setState({ creatingEmbeddingTaskIds: ['file-1', 'file-2', 'file-3'] });
- });
-
- act(() => {
- result.current.toggleEmbeddingIds(['file-1', 'file-2'], false);
- });
-
- expect(result.current.creatingEmbeddingTaskIds).toEqual(['file-3']);
- });
-
- it('should toggle ids when loading is undefined', () => {
- const { result } = renderHook(() => useStore());
-
- act(() => {
- useStore.setState({ creatingEmbeddingTaskIds: ['file-1'] });
- });
-
- act(() => {
- result.current.toggleEmbeddingIds(['file-1', 'file-2']);
- });
-
- expect(result.current.creatingEmbeddingTaskIds).toEqual(['file-2']);
- });
-
- it('should handle empty initial state', () => {
- const { result } = renderHook(() => useStore());
-
- act(() => {
- result.current.toggleEmbeddingIds(['file-1'], true);
- });
-
- expect(result.current.creatingEmbeddingTaskIds).toEqual(['file-1']);
- });
-
- it('should not duplicate ids', () => {
- const { result } = renderHook(() => useStore());
-
- act(() => {
- useStore.setState({ creatingEmbeddingTaskIds: ['file-1'] });
- });
-
- act(() => {
- result.current.toggleEmbeddingIds(['file-1'], true);
- });
-
- expect(result.current.creatingEmbeddingTaskIds).toEqual(['file-1']);
- });
- });
-
- describe('toggleParsingIds', () => {
+ describe.each([
+ { action: 'toggleEmbeddingIds', stateKey: 'creatingEmbeddingTaskIds' },
+ { action: 'toggleParsingIds', stateKey: 'creatingChunkingTaskIds' },
+ ] as const)('$action', ({ action, stateKey }) => {
it('should add ids when loading is true', () => {
const { result } = renderHook(() => useStore());
act(() => {
- result.current.toggleParsingIds(['file-1', 'file-2'], true);
+ result.current[action](['file-1', 'file-2'], true);
});
- expect(result.current.creatingChunkingTaskIds).toEqual(['file-1', 'file-2']);
+ expect(result.current[stateKey]).toEqual(['file-1', 'file-2']);
});
it('should remove ids when loading is false', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({ creatingChunkingTaskIds: ['file-1', 'file-2', 'file-3'] });
+ useStore.setState({ [stateKey]: ['file-1', 'file-2', 'file-3'] });
});
act(() => {
- result.current.toggleParsingIds(['file-1', 'file-2'], false);
+ result.current[action](['file-1', 'file-2'], false);
});
- expect(result.current.creatingChunkingTaskIds).toEqual(['file-3']);
+ expect(result.current[stateKey]).toEqual(['file-3']);
});
it('should toggle ids when loading is undefined', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({ creatingChunkingTaskIds: ['file-1'] });
+ useStore.setState({ [stateKey]: ['file-1'] });
});
act(() => {
- result.current.toggleParsingIds(['file-1', 'file-2']);
+ result.current[action](['file-1', 'file-2']);
});
- expect(result.current.creatingChunkingTaskIds).toEqual(['file-2']);
+ expect(result.current[stateKey]).toEqual(['file-2']);
});
it('should handle empty initial state', () => {
const { result } = renderHook(() => useStore());
act(() => {
- result.current.toggleParsingIds(['file-1'], true);
+ result.current[action](['file-1'], true);
});
- expect(result.current.creatingChunkingTaskIds).toEqual(['file-1']);
+ expect(result.current[stateKey]).toEqual(['file-1']);
});
it('should not duplicate ids', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({ creatingChunkingTaskIds: ['file-1'] });
+ useStore.setState({ [stateKey]: ['file-1'] });
});
act(() => {
- result.current.toggleParsingIds(['file-1'], true);
+ result.current[action](['file-1'], true);
});
- expect(result.current.creatingChunkingTaskIds).toEqual(['file-1']);
+ expect(result.current[stateKey]).toEqual(['file-1']);
});
});
diff --git a/src/store/image/slices/generationConfig/selectors.test.ts b/src/store/image/slices/generationConfig/selectors.test.ts
index 2059e410f28..f5831cc9dee 100644
--- a/src/store/image/slices/generationConfig/selectors.test.ts
+++ b/src/store/image/slices/generationConfig/selectors.test.ts
@@ -156,12 +156,6 @@ describe('imageGenerationConfigSelectors', () => {
});
describe('isSupportParam', () => {
- it('should return true when parameter exists in parametersSchema', () => {
- const state = merge(initialStore, { parametersSchema: testModelSchema });
- const result = imageGenerationConfigSelectors.isSupportedParam('size')(state);
- expect(result).toBe(true);
- });
-
it('should return false when parameter does not exist in parametersSchema', () => {
const state = merge(initialStore, { parametersSchema: testModelSchema });
const result = imageGenerationConfigSelectors.isSupportedParam('nonexistent' as any)(state);
diff --git a/src/store/serverConfig/action.test.ts b/src/store/serverConfig/action.test.ts
index 27da44f598f..e68eb647f8c 100644
--- a/src/store/serverConfig/action.test.ts
+++ b/src/store/serverConfig/action.test.ts
@@ -141,7 +141,7 @@ describe('ServerConfigAction', () => {
});
describe('SWR integration', () => {
- it('should use correct SWR key', async () => {
+ it('should pass the server config key, fetcher and callbacks', async () => {
const { useOnlyFetchOnceSWR } = vi.mocked(await import('@/libs/swr'));
const store = initServerConfigStore({});
@@ -155,13 +155,6 @@ describe('ServerConfigAction', () => {
onSuccess: expect.any(Function),
}),
);
- });
-
- it('should pass globalService.getGlobalConfig as fetcher', async () => {
- const { useOnlyFetchOnceSWR } = vi.mocked(await import('@/libs/swr'));
-
- const store = initServerConfigStore({});
- store.getState().useInitServerConfig();
expect(useOnlyFetchOnceSWR).toHaveBeenCalledWith(
'serverConfig:get',
diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.ts
index c462690cbf9..e727bd1effb 100644
--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts
+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts
@@ -53,6 +53,21 @@ vi.mock('@/libs/trpc/client', () => ({
},
}));
+const createSkillServerState = (
+ lobehubSkillServers: typeof initialLobehubSkillStoreState.lobehubSkillServers = [],
+) => ({
+ lobehubSkillServers,
+ lobehubSkillLoadingIds: new Set<string>(),
+ lobehubSkillExecutingToolIds: new Set<string>(),
+});
+
+const createConnectedLinearServer = () => ({
+ identifier: 'linear',
+ name: 'Linear',
+ isConnected: true,
+ status: LobehubSkillStatus.CONNECTED,
+});
+
const createSWRWrapper = () => {
const value = { dedupingInterval: 0, provider: () => new Map() };
@@ -67,11 +82,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
const mockResponse = {
@@ -101,11 +112,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillExecutingToolIds: new Set(),
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillServers: [],
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({
@@ -136,11 +143,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillExecutingToolIds: new Set(),
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillServers: [],
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({
@@ -170,11 +173,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillExecutingToolIds: new Set(),
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillServers: [],
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({
@@ -203,11 +202,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillExecutingToolIds: new Set(),
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillServers: [],
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectCallTool.mutate).mockResolvedValue({
@@ -236,11 +231,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
let resolvePromise: (value: any) => void;
@@ -324,11 +315,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectCallTool.mutate).mockRejectedValue(
@@ -355,11 +342,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
const mockResponse = {
@@ -398,11 +381,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
const mockResponse = {
@@ -428,18 +407,16 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
+ useToolStore.setState(
+ createSkillServerState([
{
identifier: 'linear',
name: 'Linear',
isConnected: false,
status: LobehubSkillStatus.NOT_CONNECTED,
},
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ ]),
+ );
});
const mockResponse = {
@@ -472,11 +449,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
let resolvePromise: (value: any) => void;
@@ -506,11 +479,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectGetStatus.query).mockRejectedValue(
@@ -589,18 +558,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
act(() => {
@@ -621,11 +579,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
act(() => {
@@ -643,8 +597,8 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
+ useToolStore.setState(
+ createSkillServerState([
{
identifier: 'linear',
name: 'Linear',
@@ -652,10 +606,8 @@ describe('lobehubSkillStore actions', () => {
status: LobehubSkillStatus.CONNECTED,
tokenExpiresAt: '2024-01-01T00:00:00Z',
},
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ ]),
+ );
});
const mockResponse = {
@@ -684,18 +636,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
const mockResponse = {
@@ -715,11 +656,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectRefresh.mutate).mockRejectedValue(
@@ -740,18 +677,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
const mockTools = {
@@ -777,11 +703,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
await act(async () => {
@@ -796,18 +718,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
vi.mocked(toolsClient.market.connectListTools.query).mockRejectedValue(
@@ -828,24 +739,17 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
+ useToolStore.setState(
+ createSkillServerState([
+ createConnectedLinearServer(),
{
identifier: 'github',
name: 'GitHub',
isConnected: true,
status: LobehubSkillStatus.CONNECTED,
},
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ ]),
+ );
});
vi.mocked(toolsClient.market.connectRevoke.mutate).mockResolvedValue({} as any);
@@ -865,18 +769,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
let resolvePromise: (value: any) => void;
@@ -906,18 +799,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState([createConnectedLinearServer()]));
});
vi.mocked(toolsClient.market.connectRevoke.mutate).mockRejectedValue(
@@ -942,11 +824,7 @@ describe('lobehubSkillStore actions', () => {
describe('useFetchLobehubSkillConnections', () => {
it('should not fetch when disabled', async () => {
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectListConnections.query).mockClear();
@@ -962,11 +840,7 @@ describe('lobehubSkillStore actions', () => {
it('should not fetch when user is not signed in', async () => {
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
useUserStore.setState({ isSignedIn: false });
});
@@ -983,11 +857,7 @@ describe('lobehubSkillStore actions', () => {
it('should sync the connections into the replica view when enabled', async () => {
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
useUserStore.setState({ isSignedIn: true });
});
@@ -1096,11 +966,7 @@ describe('lobehubSkillStore actions', () => {
const { result } = renderHook(() => useToolStore());
act(() => {
- useToolStore.setState({
- lobehubSkillServers: [],
- lobehubSkillLoadingIds: new Set(),
- lobehubSkillExecutingToolIds: new Set(),
- });
+ useToolStore.setState(createSkillServerState());
});
vi.mocked(toolsClient.market.connectGetStatus.query).mockResolvedValue({
diff --git a/src/store/tool/slices/lobehubSkillStore/selectors.test.ts b/src/store/tool/slices/lobehubSkillStore/selectors.test.ts
index 873daa2eade..57b3e6257a9 100644
--- a/src/store/tool/slices/lobehubSkillStore/selectors.test.ts
+++ b/src/store/tool/slices/lobehubSkillStore/selectors.test.ts
@@ -6,6 +6,20 @@ import { lobehubSkillStoreSelectors } from './selectors';
import { type LobehubSkillServer } from './types';
import { LobehubSkillStatus } from './types';
+const createConnectedLinearServer = (): LobehubSkillServer => ({
+ identifier: 'linear',
+ name: 'Linear',
+ isConnected: true,
+ status: LobehubSkillStatus.CONNECTED,
+});
+
+const createDisconnectedGitHubServer = (): LobehubSkillServer => ({
+ identifier: 'github',
+ name: 'GitHub',
+ isConnected: false,
+ status: LobehubSkillStatus.NOT_CONNECTED,
+});
+
describe('lobehubSkillStoreSelectors', () => {
describe('getServers', () => {
it('should return empty array when no servers exist', () => {
@@ -16,18 +30,8 @@ describe('lobehubSkillStoreSelectors', () => {
it('should return all servers', () => {
const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- {
- identifier: 'github',
- name: 'GitHub',
- isConnected: false,
- status: LobehubSkillStatus.NOT_CONNECTED,
- },
+ createConnectedLinearServer(),
+ createDisconnectedGitHubServer(),
];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.getServers(state);
@@ -38,18 +42,8 @@ describe('lobehubSkillStoreSelectors', () => {
describe('getConnectedServers', () => {
it('should return only connected servers', () => {
const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- {
- identifier: 'github',
- name: 'GitHub',
- isConnected: false,
- status: LobehubSkillStatus.NOT_CONNECTED,
- },
+ createConnectedLinearServer(),
+ createDisconnectedGitHubServer(),
{
identifier: 'slack',
name: 'Slack',
@@ -64,14 +58,7 @@ describe('lobehubSkillStoreSelectors', () => {
});
it('should return empty array when no servers are connected', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'github',
- name: 'GitHub',
- isConnected: false,
- status: LobehubSkillStatus.NOT_CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createDisconnectedGitHubServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.getConnectedServers(state);
expect(result).toEqual([]);
@@ -87,18 +74,8 @@ describe('lobehubSkillStoreSelectors', () => {
describe('getAllServerIdentifiers', () => {
it('should return set of all server identifiers', () => {
const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- {
- identifier: 'github',
- name: 'GitHub',
- isConnected: false,
- status: LobehubSkillStatus.NOT_CONNECTED,
- },
+ createConnectedLinearServer(),
+ createDisconnectedGitHubServer(),
];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.getAllServerIdentifiers(state);
@@ -114,14 +91,7 @@ describe('lobehubSkillStoreSelectors', () => {
describe('getServerByIdentifier', () => {
it('should return server by identifier', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createConnectedLinearServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.getServerByIdentifier('linear')(state);
expect(result?.identifier).toBe('linear');
@@ -143,14 +113,7 @@ describe('lobehubSkillStoreSelectors', () => {
describe('isLobehubSkillServer', () => {
it('should return true for existing server', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createConnectedLinearServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.isLobehubSkillServer('linear')(state);
expect(result).toBe(true);
@@ -269,14 +232,7 @@ describe('lobehubSkillStoreSelectors', () => {
});
it('should return empty array when no connected servers have tools', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createConnectedLinearServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.getAllTools(state);
expect(result).toEqual([]);
@@ -360,14 +316,7 @@ describe('lobehubSkillStoreSelectors', () => {
});
it('should not include servers without tools', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createConnectedLinearServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.lobehubSkillAsLobeTools(state);
expect(result).toEqual([]);
@@ -495,14 +444,7 @@ describe('lobehubSkillStoreSelectors', () => {
});
it('should use default avatar when icon is not provided', () => {
- const servers: LobehubSkillServer[] = [
- {
- identifier: 'linear',
- name: 'Linear',
- isConnected: true,
- status: LobehubSkillStatus.CONNECTED,
- },
- ];
+ const servers: LobehubSkillServer[] = [createConnectedLinearServer()];
const state = { ...initialState, lobehubSkillServers: servers } as ToolStore;
const result = lobehubSkillStoreSelectors.metaList(state);