The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Migrate server unit tests from node:test to Jest.
debajyoti-truefoundryecb878b84a0e
diff --git a/packages/server/jest.unit.config.cjs b/packages/server/jest.unit.config.cjsnew file mode 100644index 000000000..03ad8eb4b--- /dev/null+++ b/packages/server/jest.unit.config.cjs@@ -0,0 +1,42 @@+/** @type {import('jest').Config} */+module.exports = {+ testEnvironment: 'node',+ transform: {+ '^.+\\.tsx?$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'typescript', decorators: true, dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ // Vercel AI SDK and provider packages ship as ESM — compile them to CJS for Jest.+ '^.+\\.m?js$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'ecmascript', dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ },+ // pnpm stores packages under node_modules/.pnpm/; AI SDK + transitive deps ship as ESM.+ transformIgnorePatterns: [],+ moduleNameMapper: {+ '^(\\.{1,2}/.*)\\.js$': '$1',+ '^@truefoundry/utils/agent-session$': '<rootDir>/../harness/src/agent-session/index.ts',+ '^@truefoundry/utils/agent-session/(.*)$': '<rootDir>/../harness/src/agent-session/$1',+ '^@truefoundry/utils/request-reply$': '<rootDir>/../harness/src/request-reply/index.ts',+ '^@truefoundry/utils/request-reply/(.*)$': '<rootDir>/../harness/src/request-reply/$1',+ '^@truefoundry/utils/core$': '<rootDir>/../harness/src/core/index.ts',+ '^@truefoundry/utils/core/(.*)$': '<rootDir>/../harness/src/core/$1',+ },+ testTimeout: 30_000,+ maxWorkers: '50%',+ roots: ['<rootDir>/tests/unit'],+ testMatch: ['<rootDir>/tests/unit/**/*.test.ts'],+};diff --git a/packages/server/package.json b/packages/server/package.jsonindex 89e53a7e8..d0ee521ef 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -19,7 +19,7 @@"migrate": "NODE_OPTIONS='--conditions=development' tsx --env-file=.env src/db/postgres/migrate-cli.ts","typecheck": "pnpm run build:gen && tsc --noEmit && tsc --noEmit -p tests/db/tsconfig.json && tsc --noEmit -p tests/unit/tsconfig.json","openapi:write": "pnpm run build:gen && NODE_OPTIONS='--conditions=development' tsx --env-file=.env.test scripts/write-openapi.ts",- "test": "pnpm run build:gen && NODE_OPTIONS='--conditions=development' tsx --env-file=.env.test --test \"tests/unit/**/*.test.ts\"",+ "test": "pnpm run build:gen && NODE_OPTIONS='--conditions=development' node --env-file=.env.test ./node_modules/jest/bin/jest.js --config jest.unit.config.cjs","test:store:postgres": "jest --config jest.store.postgres.config.cjs","test:store:sqlite": "jest --config jest.store.sqlite.config.cjs"},diff --git a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts b/packages/server/tests/unit/apis/deletedSessionCrud.test.tsindex c516bbb4a..7894d2a35 100644--- a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts+++ b/packages/server/tests/unit/apis/deletedSessionCrud.test.ts@@ -1,8 +1,6 @@import { OpenAPIHono } from '@hono/zod-openapi';import { InMemorySessionStore, Sessions } from '@truefoundry/utils/agent-session';import { RequestReplyRouter } from '@truefoundry/utils/request-reply';-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';import { createClient } from 'redis';import { createLogger } from 'winston';import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';@@ -54,7 +52,7 @@ describe('public CRUD after session deletion', () => {},custom: null,});- assert.equal((await app.request('/s1', { method: 'DELETE' })).status, 204);+ expect((await app.request('/s1', { method: 'DELETE' })).status).toBe(204);const requests = [app.request('/s1'),@@ -76,12 +74,12 @@ describe('public CRUD after session deletion', () => {];for (const response of await Promise.all(requests)) {- assert.equal(response.status, 404);+ expect(response.status).toBe(404);}const listed = await app.request('/');- assert.equal(listed.status, 200);- assert.deepEqual(ListSessionsResponseSchema.parse(await listed.json()).data, []);- assert.equal((await app.request('/s1', { method: 'DELETE' })).status, 204);+ expect(listed.status).toBe(200);+ expect(ListSessionsResponseSchema.parse(await listed.json()).data).toEqual([]);+ expect((await app.request('/s1', { method: 'DELETE' })).status).toBe(204);});});diff --git a/packages/server/tests/unit/apis/modelProviders.test.ts b/packages/server/tests/unit/apis/modelProviders.test.tsindex 6ebc4fc87..bd611f905 100644--- a/packages/server/tests/unit/apis/modelProviders.test.ts+++ b/packages/server/tests/unit/apis/modelProviders.test.ts@@ -1,5 +1,3 @@-import assert from 'node:assert/strict';-import { before, describe, it } from 'node:test';import { createModelsRouter } from '../../../src/apis/models';import { createSettingsRouter } from '../../../src/apis/settings';import { ModelCatalog } from '../../../src/catalog/ModelCatalog';@@ -33,7 +31,7 @@ describe('settings model-providers and models routers', () => {let settingsRouter: ReturnType<typeof createSettingsRouter>;let modelsRouter: ReturnType<typeof createModelsRouter>;- before(async () => {+ beforeAll(async () => {const db = createSqliteDb(':memory:');await migrateSqliteToLatest(db);const modelProviderStore = new SqliteModelProviderStore(db);@@ -43,40 +41,39 @@ describe('settings model-providers and models routers', () => {it('GET /model-providers/catalog returns the shipped catalog verbatim', async () => {const response = await settingsRouter.request('/model-providers/catalog');- assert.equal(response.status, 200);+ expect(response.status).toBe(200);const body = (await response.json()) as { data: { type: string; name: string }[] };- assert.deepEqual(- body.data.map(provider => provider.name),+ expect(body.data.map(provider => provider.name)).toEqual(ModelCatalog.load().list().map(provider => provider.name),);- assert.ok(body.data.every(provider => provider.type !== 'custom'));+ expect(body.data.every(provider => provider.type !== 'custom')).toBe(true);});it('PUT upserts a provider and echoes the stored auth', async () => {const response = await settingsRouter.request('/model-providers', putInit(putBody));- assert.equal(response.status, 200);- assert.deepEqual(await response.json(), { data: putBody });+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ data: putBody });const list = await settingsRouter.request('/model-providers');- assert.equal(list.status, 200);- assert.deepEqual(await list.json(), { data: [putBody] });+ expect(list.status).toBe(200);+ expect(await list.json()).toEqual({ data: [putBody] });});it('PUT rejects invalid bodies at the Zod layer', async () => {const { base_url: _, ...withoutBaseUrl } = putBody;const missingBaseUrl = await settingsRouter.request('/model-providers', putInit(withoutBaseUrl));- assert.equal(missingBaseUrl.status, 400);+ expect(missingBaseUrl.status).toBe(400);const badName = await settingsRouter.request('/model-providers', putInit({ ...putBody, name: 'Not A Slug' }));- assert.equal(badName.status, 400);+ expect(badName.status).toBe(400);});it('GET /models returns the FQN read view', async () => {const response = await modelsRouter.request('/');- assert.equal(response.status, 200);- assert.deepEqual(await response.json(), {+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({data: [{name: 'anthropic/claude-sonnet-4-6',diff --git a/packages/server/tests/unit/apis/sessions.test.ts b/packages/server/tests/unit/apis/sessions.test.tsindex 7b121bf2f..e59ee16ce 100644--- a/packages/server/tests/unit/apis/sessions.test.ts+++ b/packages/server/tests/unit/apis/sessions.test.ts@@ -1,8 +1,6 @@import type { ISessionStore, TurnRecord, TurnState } from '@truefoundry/utils/agent-session';import { CancellationReason } from '@truefoundry/utils/agent-session';import { HTTPException } from 'hono/http-exception';-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';import { createClient, type RedisClientType } from 'redis';import { cancelSessionTurn } from '../../../src/apis/sessions';import configuration from '../../../src/config';@@ -67,8 +65,8 @@ describe('cancelSessionTurn', () => {{ sessionId: SESSION_ID, turnId },);- assert.equal(abortController.signal.aborted, true);- assert.equal(abortController.signal.reason, CancellationReason.ClientCancelled);+ expect(abortController.signal.aborted).toBe(true);+ expect(abortController.signal.reason).toBe(CancellationReason.ClientCancelled);});it('does not look for a peer without a Redis client', async () => {@@ -76,7 +74,7 @@ describe('cancelSessionTurn', () => {const turnId = mintPeeredTurnId('other1');// A peer hop here would dereference the absent client and throw.- await assert.doesNotReject(+ await expect(cancelSessionTurn({activeTurns,@@ -84,7 +82,7 @@ describe('cancelSessionTurn', () => {},{ sessionId: SESSION_ID, turnId },),- );+ ).resolves.toBeUndefined();});it('routes to the owning peer when the turn id names another replica', async () => {@@ -92,7 +90,7 @@ describe('cancelSessionTurn', () => {const turnId = mintPeeredTurnId('other1');// The unconnected client makes the hop fail; the point is that it happened.- await assert.rejects(+ await expect(cancelSessionTurn({activeTurns,@@ -101,7 +99,6 @@ describe('cancelSessionTurn', () => {},{ sessionId: SESSION_ID, turnId },),- (error: unknown) => error instanceof HTTPException,- );+ ).rejects.toBeInstanceOf(HTTPException);});});diff --git a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts b/packages/server/tests/unit/apis/turnStreamAfterDelete.test.tsindex d46e781ea..a1e56c7f5 100644--- a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts+++ b/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts@@ -1,8 +1,6 @@import { OpenAPIHono } from '@hono/zod-openapi';import type { Sessions } from '@truefoundry/utils/agent-session';import { TurnNotFoundError } from '@truefoundry/utils/agent-session';-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';import { createLogger } from 'winston';import { createTurnsRouter } from '../../../src/apis/turns';import { McpStore } from '../../../src/legacy-registry-store/McpStore';@@ -49,13 +47,13 @@ describe('turn SSE after session deletion', () => {headers: { 'content-type': 'application/json' },body: '{}',});- assert.equal(response.status, 200);+ expect(response.status).toBe(200);await response.text();- assert.ok(+ expect(warnings.some(message => typeof message === 'string' && message.includes('Turn stream ended after session/turn was removed'),),- );+ ).toBe(true);});});diff --git a/packages/server/tests/unit/runtime/activeTurns.test.ts b/packages/server/tests/unit/runtime/activeTurns.test.tsindex 31ff24814..136a05ea7 100644--- a/packages/server/tests/unit/runtime/activeTurns.test.ts+++ b/packages/server/tests/unit/runtime/activeTurns.test.ts@@ -1,6 +1,4 @@import { CancellationReason } from '@truefoundry/utils/agent-session';-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';async function* values<T>(items: T[]): AsyncGenerator<T> {@@ -43,15 +41,14 @@ describe('ActiveTurnRegistry', () => {for await (const value of tracked) {seen.push(value);}- assert.deepEqual(seen, [1, 2, 3]);- assert.equal(+ expect(seen).toEqual([1, 2, 3]);+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.ClientCancelled,}),- false,- );+ ).toBe(false);});it('track cleans up when the consumer breaks early', async () => {@@ -65,17 +62,16 @@ describe('ActiveTurnRegistry', () => {});for await (const value of tracked) {- assert.equal(value, 1);+ expect(value).toBe(1);break;}- assert.equal(+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.ClientCancelled,}),- false,- );+ ).toBe(false);});it('track cleans up when the stream throws', async () => {@@ -88,19 +84,18 @@ describe('ActiveTurnRegistry', () => {stream: throwingStream(),});- await assert.rejects(async () => {+ await expect(async () => {for await (const value of tracked) {void value;}- }, /stream boom/);- assert.equal(+ }).rejects.toThrow(/stream boom/);+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.ClientCancelled,}),- false,- );+ ).toBe(false);});it('cancelIfRunning aborts with the given reason and returns true', () => {@@ -113,28 +108,26 @@ describe('ActiveTurnRegistry', () => {stream: values([1]),});- assert.equal(+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.ClientCancelled,}),- true,- );- assert.equal(abortController.signal.aborted, true);- assert.equal(abortController.signal.reason, CancellationReason.ClientCancelled);+ ).toBe(true);+ expect(abortController.signal.aborted).toBe(true);+ expect(abortController.signal.reason).toBe(CancellationReason.ClientCancelled);});it('cancelIfRunning returns false for unknown ids', () => {const registry = new ActiveTurnRegistry();- assert.equal(+ expect(registry.cancelIfRunning({sessionId: 'missing',turnId: 'missing',abortReason: CancellationReason.ClientCancelled,}),- false,- );+ ).toBe(false);});it('cancelIfRunning does not re-abort an already-aborted controller', () => {@@ -148,15 +141,14 @@ describe('ActiveTurnRegistry', () => {});abortController.abort(CancellationReason.ClientCancelled);- assert.equal(+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.Abandoned,}),- true,- );- assert.equal(abortController.signal.reason, CancellationReason.ClientCancelled);+ ).toBe(true);+ expect(abortController.signal.reason).toBe(CancellationReason.ClientCancelled);});it('shutdownAndWait aborts runs and waits until tracked streams finish', async () => {@@ -176,17 +168,16 @@ describe('ActiveTurnRegistry', () => {})();await registry.shutdownAndWait(CancellationReason.Abandoned);- assert.equal(abortController.signal.aborted, true);- assert.equal(abortController.signal.reason, CancellationReason.Abandoned);+ expect(abortController.signal.aborted).toBe(true);+ expect(abortController.signal.reason).toBe(CancellationReason.Abandoned);await drain;- assert.equal(+ expect(registry.cancelIfRunning({sessionId: 's1',turnId: 't1',abortReason: CancellationReason.ClientCancelled,}),- false,- );+ ).toBe(false);});it('late track after shutdownAndWait aborts immediately with the shutdown reason', async () => {@@ -201,8 +192,8 @@ describe('ActiveTurnRegistry', () => {stream: values(['x']),});- assert.equal(abortController.signal.aborted, true);- assert.equal(abortController.signal.reason, CancellationReason.Abandoned);+ expect(abortController.signal.aborted).toBe(true);+ expect(abortController.signal.reason).toBe(CancellationReason.Abandoned);for await (const value of tracked) {void value;diff --git a/packages/server/tests/unit/runtime/peeringIds.test.ts b/packages/server/tests/unit/runtime/peeringIds.test.tsindex 133b10805..051bd8ec6 100644--- a/packages/server/tests/unit/runtime/peeringIds.test.ts+++ b/packages/server/tests/unit/runtime/peeringIds.test.ts@@ -1,20 +1,24 @@import { HTTPException } from 'hono/http-exception';-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';import { executorFromTurnId, mintPeeredTurnId } from '../../../src/runtime/peeringIds';describe('turn ids', () => {it('decodes back to the owning executor', () => {- assert.equal(executorFromTurnId(mintPeeredTurnId('abc123')), 'abc123');+ expect(executorFromTurnId(mintPeeredTurnId('abc123'))).toBe('abc123');});it('rejects ids outside the grammar', () => {for (const invalid of ['', '.', 'a.', '.b', 'a.b.c', 'noseparator']) {- assert.throws(- () => executorFromTurnId(invalid),- (error: unknown) => error instanceof HTTPException && error.status === 400,- `expected ${JSON.stringify(invalid)} to be rejected`,- );+ let thrown: unknown;+ try {+ executorFromTurnId(invalid);+ } catch (error) {+ thrown = error;+ }+ expect(thrown).toBeInstanceOf(HTTPException);+ if (!(thrown instanceof HTTPException)) {+ throw new Error(`expected ${JSON.stringify(invalid)} to be rejected`);+ }+ expect(thrown.status).toBe(400);}});});diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.jsonindex 4d723d148..23064b887 100644--- a/packages/server/tsconfig.json+++ b/packages/server/tsconfig.json@@ -9,6 +9,5 @@}},"include": ["src/**/*", "scripts/**/*", "tsup.config.ts"],- // node:test files under src/ stay out of the Jest-typed project.- "exclude": ["node_modules", "dist", "src/**/*.test.ts"]+ "exclude": ["node_modules", "dist"]}