1
import { describe, it, expect, vi, beforeEach } from 'vitest';
2
import { z } from 'zod/v3';
3
import { ToolRouter } from '../../src/models/ToolRouter';
4
-import ComposioClient, { ConflictError } from '@composio/client';
4
+import ComposioClient, {
5
+ BadRequestError,
6
+ ConflictError,
7
+ NotFoundError,
8
+ PermissionDeniedError,
9
+} from '@composio/client';
10
import { telemetry } from '../../src/telemetry/Telemetry';
11
import { MockProvider } from '../utils/mocks/provider.mock';
12
import { Tools } from '../../src/models/Tools';
1833
});
1834
});
1835
1836
+ describe('session configs', () => {
1837
+ const createPayload = () => mockClient.toolRouter.session.create.mock.calls[0][0];
1838
+
1839
+ it('sends sessionConfigId as experimental.session_config_id', async () => {
1840
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1841
+
1842
+ await toolRouter.create(userId, { experimental: { sessionConfigId: 'sc_1' } });
1843
+
1844
+ expect(createPayload().experimental).toEqual({ session_config_id: 'sc_1' });
1845
+ });
1846
+
1847
+ it('sends the same payload as before when no sessionConfigId is set', async () => {
1848
+ mockClient.toolRouter.session.create.mockResolvedValue(mockSessionCreateResponse);
1849
+
1850
+ await toolRouter.create(userId);
1851
+ await toolRouter.create(userId, { toolkits: ['gmail'] });
1852
+
1853
+ const [[bare], [withToolkits]] = mockClient.toolRouter.session.create.mock.calls;
1854
+ expect(bare.experimental).toBeUndefined();
1855
+ expect(withToolkits.experimental).toBeUndefined();
1856
+ expect(JSON.stringify(bare)).toBe(
1857
+ JSON.stringify({ user_id: userId, manage_connections: { enable: true } })
1858
+ );
1859
+ expect(JSON.stringify(withToolkits)).toBe(
1860
+ JSON.stringify({
1861
+ user_id: userId,
1862
+ toolkits: { enable: ['gmail'] },
1863
+ manage_connections: { enable: true },
1864
+ })
1865
+ );
1866
+ });
1867
+
1868
+ it('sends session_config_id together with assistive_prompt_config', async () => {
1869
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1870
+
1871
+ await toolRouter.create(userId, {
1872
+ experimental: {
1873
+ sessionConfigId: 'sc_1',
1874
+ assistivePrompt: { userTimezone: 'Europe/Rome' },
1875
+ },
1876
+ });
1877
+
1878
+ expect(createPayload().experimental).toEqual({
1879
+ session_config_id: 'sc_1',
1880
+ assistive_prompt_config: { user_timezone: 'Europe/Rome' },
1881
+ });
1882
+ });
1883
+
1884
+ it('sends every per-session field unchanged next to sessionConfigId', async () => {
1885
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1886
+
1887
+ await toolRouter.create(userId, {
1888
+ authConfigs: { github: 'ac_1' },
1889
+ connectedAccounts: { github: 'ca_1' },
1890
+ manageConnections: false,
1891
+ sandbox: { enable: false },
1892
+ multiAccount: { enable: true, maxAccountsPerToolkit: 3 },
1893
+ preload: { tools: ['GITHUB_GET_REPO'] },
1894
+ experimental: { sessionConfigId: 'sc_1' },
1895
+ });
1896
+
1897
+ expect(createPayload()).toEqual({
1898
+ user_id: userId,
1899
+ auth_configs: { github: 'ac_1' },
1900
+ connected_accounts: { github: ['ca_1'] },
1901
+ manage_connections: { enable: false },
1902
+ workbench: { enable: false },
1903
+ multi_account: {
1904
+ enable: true,
1905
+ max_accounts_per_toolkit: 3,
1906
+ require_explicit_selection: true,
1907
+ },
1908
+ preload: { tools: ['GITHUB_GET_REPO'] },
1909
+ experimental: { session_config_id: 'sc_1' },
1910
+ });
1911
+ });
1912
+
1913
+ it('rejects an empty sessionConfigId before any client call', async () => {
1914
+ await expect(
1915
+ toolRouter.create(userId, { experimental: { sessionConfigId: '' } })
1916
+ ).rejects.toThrow();
1917
+ expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1918
+ });
1919
+
1920
+ // Plain JavaScript callers bypass the compile-time union, so these go
1921
+ // through `unknown`.
1922
+ const createUnchecked = (config: Record<string, unknown>) =>
1923
+ toolRouter.create(userId, config as unknown as ToolRouterCreateSessionConfig);
1924
+ const customTool = { slug: 'MY_TOOL' };
1925
+ const customToolkit = { slug: 'MY_TOOLKIT', tools: [] };
1926
+
1927
+ it.each([
1928
+ ['toolkits', { toolkits: ['github'] }],
1929
+ ['toolkits', { toolkits: { disable: ['x'] } }],
1930
+ ['tools', { tools: { github: ['GITHUB_GET_REPO'] } }],
1931
+ ['tags', { tags: ['readOnlyHint'] }],
1932
+ ['experimental.customTools', { experimental: { customTools: [customTool] } }],
1933
+ ['experimental.customToolkits', { experimental: { customToolkits: [customToolkit] } }],
1934
+ ['toolkits', { toolkits: [] }],
1935
+ ['experimental.customTools', { experimental: { customTools: [] } }],
1936
+ ])(
1937
+ 'rejects sessionConfigId combined with %s (%j) without calling the API',
1938
+ async (field, inline) => {
1939
+ const inlineExperimental = (inline as { experimental?: object }).experimental;
1940
+ const error = await createUnchecked({
1941
+ ...inline,
1942
+ experimental: { ...inlineExperimental, sessionConfigId: 'sc_1' },
1943
+ }).catch(e => e);
1944
+
1945
+ expect(error).toBeInstanceOf(ValidationError);
1946
+ expect(error.message).toContain(
1947
+ `experimental.sessionConfigId cannot be combined with ${field}`
1948
+ );
1949
+ expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1950
+ }
1951
+ );
1952
+
1953
+ it('names every conflicting field in one error', async () => {
1954
+ const error = await createUnchecked({
1955
+ toolkits: ['github'],
1956
+ tags: ['readOnlyHint'],
1957
+ experimental: { sessionConfigId: 'sc_1', customTools: [customTool] },
1958
+ }).catch(e => e);
1959
+
1960
+ expect(error).toBeInstanceOf(ValidationError);
1961
+ expect(error.message).toContain(
1962
+ 'experimental.sessionConfigId cannot be combined with toolkits, tags, experimental.customTools'
1963
+ );
1964
+ expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1965
+ });
1966
+
1967
+ it('treats an explicit undefined inline field as absent', async () => {
1968
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1969
+
1970
+ await toolRouter.create(userId, {
1971
+ toolkits: undefined,
1972
+ experimental: { sessionConfigId: 'sc_1' },
1973
+ });
1974
+
1975
+ expect(createPayload().experimental).toEqual({ session_config_id: 'sc_1' });
1976
+ });
1977
+
1978
+ it('keeps throwing ZodError for unrelated invalid input', async () => {
1979
+ const error = await createUnchecked({
1980
+ multiAccount: { maxAccountsPerToolkit: 1 },
1981
+ }).catch(e => e);
1982
+
1983
+ expect(error).toBeInstanceOf(z.ZodError);
1984
+ expect(error).not.toBeInstanceOf(ValidationError);
1985
+ expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
1986
+ });
1987
+
1988
+ it('allows the direct tools preset with a saved config and sends preload all', async () => {
1989
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1990
+
1991
+ await toolRouter.create(userId, {
1992
+ sessionPreset: SessionPreset.DIRECT_TOOLS,
1993
+ experimental: { sessionConfigId: 'sc_1' },
1994
+ });
1995
+
1996
+ expect(createPayload()).toMatchObject({
1997
+ preload: { tools: 'all' },
1998
+ experimental: { session_config_id: 'sc_1' },
1999
+ });
2000
+ });
2001
+ });
2002
+
2003
describe('error handling', () => {
2004
it('should throw error if API call fails', async () => {
2005
const apiError = new Error('API error: Invalid session configuration');
4340
});
4341
});
4342
});
4343
+
4344
+ describe('saved Session configs on an existing session', () => {
4345
+ const sessionId = 'session_123';
4346
+
4347
+ const patchResponse = (configVersion: number, experimental?: Record<string, unknown>) => ({
4348
+ session_id: sessionId,
4349
+ config: mockSessionRetrieveResponse.config,
4350
+ config_version: configVersion,
4351
+ warnings: [],
4352
+ ...(experimental && { experimental }),
4353
+ });
4354
+
4355
+ const patchBody = (callIndex = 0) =>
4356
+ mockClient.toolRouter.session.patch.mock.calls[callIndex][1] as Record<string, unknown>;
4357
+
4358
+ // Plain JavaScript callers bypass the compile-time union.
4359
+ type UpdateInput = Parameters<Session<unknown, unknown, MockProvider>['update']>[0];
4360
+ const unchecked = (config: Record<string, unknown>) => config as unknown as UpdateInput;
4361
+
4362
+ beforeEach(() => {
4363
+ mockClient.toolRouter.session.patch.mockResolvedValue(patchResponse(8));
4364
+ });
4365
+
4366
+ describe('mixed-input rejection', () => {
4367
+ it.each([
4368
+ ['toolkits', { toolkits: ['gmail'] }],
4369
+ ['toolkits', { toolkits: null }],
4370
+ ['tools', { tools: { gmail: ['GMAIL_SEND_EMAIL'] } }],
4371
+ ['tools', { tools: null }],
4372
+ ['tags', { tags: ['readOnlyHint'] }],
4373
+ ['tags', { tags: null }],
4374
+ ])('rejects sessionConfigId combined with %s (%j) without a PATCH', async (field, inline) => {
4375
+ const session = await toolRouter.use(sessionId);
4376
+
4377
+ const error = await session
4378
+ .update(unchecked({ ...inline, experimental: { sessionConfigId: 'sc_1' } }))
4379
+ .catch(e => e);
4380
+
4381
+ expect(error).toBeInstanceOf(ValidationError);
4382
+ expect(error.message).toContain(
4383
+ `experimental.sessionConfigId cannot be combined with ${field}`
4384
+ );
4385
+ expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4386
+ });
4387
+
4388
+ it('sends sessionConfigId next to per-session fields', async () => {
4389
+ const session = await toolRouter.use(sessionId);
4390
+
4391
+ await session.update({
4392
+ authConfigs: { github: 'ac_1' },
4393
+ preload: null,
4394
+ experimental: { sessionConfigId: 'sc_1' },
4395
+ });
4396
+
4397
+ expect(patchBody()).toEqual({
4398
+ auth_configs: { github: 'ac_1' },
4399
+ preload: null,
4400
+ experimental: { session_config_id: 'sc_1' },
4401
+ });
4402
+ });
4403
+
4404
+ it('allows sessionConfigId with other experimental settings', async () => {
4405
+ const session = await toolRouter.use(sessionId);
4406
+
4407
+ await session.update({ experimental: { sessionConfigId: 'sc_1', fastMode: true } });
4408
+
4409
+ expect(patchBody().experimental).toEqual({ session_config_id: 'sc_1', fast_mode: true });
4410
+ });
4411
+
4412
+ it('treats an explicit undefined toolkits as absent', async () => {
4413
+ const session = await toolRouter.use(sessionId);
4414
+
4415
+ await session.update({ toolkits: undefined, experimental: { sessionConfigId: 'sc_1' } });
4416
+
4417
+ expect(patchBody()).not.toHaveProperty('toolkits');
4418
+ expect(patchBody().experimental).toEqual({ session_config_id: 'sc_1' });
4419
+ });
4420
+
4421
+ it('rejects an empty sessionConfigId before any PATCH', async () => {
4422
+ const session = await toolRouter.use(sessionId);
4423
+
4424
+ await expect(session.update({ experimental: { sessionConfigId: '' } })).rejects.toThrow();
4425
+ expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4426
+ });
4427
+
4428
+ it('keeps throwing ZodError for unrelated invalid input', async () => {
4429
+ const session = await toolRouter.use(sessionId);
4430
+
4431
+ const error = await session.update({ expectedConfigVersion: 0 }).catch(e => e);
4432
+
4433
+ expect(error).toBeInstanceOf(z.ZodError);
4434
+ expect(error).not.toBeInstanceOf(ValidationError);
4435
+ expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
4436
+ });
4437
+ });
4438
+
4439
+ describe('sourceSessionConfig', () => {
4440
+ const withSource = <T extends object>(response: T, id: string) => ({
4441
+ ...response,
4442
+ experimental: { source_session_config: { id } },
4443
+ });
4444
+
4445
+ it('is set from the create response', async () => {
4446
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(
4447
+ withSource(mockSessionCreateResponse, 'sc_1')
4448
+ );
4449
+
4450
+ const session = await toolRouter.create('user_123', {
4451
+ experimental: { sessionConfigId: 'sc_1' },
4452
+ });
4453
+
4454
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4455
+ });
4456
+
4457
+ it('is undefined when the create response has no experimental block', async () => {
4458
+ mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
4459
+
4460
+ const session = await toolRouter.create('user_123');
4461
+
4462
+ expect(session.experimental.sourceSessionConfig).toBeUndefined();
4463
+ });
4464
+
4465
+ it('is set from the retrieve response on use()', async () => {
4466
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4467
+ withSource(mockSessionRetrieveResponse, 'sc_1')
4468
+ );
4469
+
4470
+ const session = await toolRouter.use(sessionId);
4471
+
4472
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4473
+ });
4474
+
4475
+ it('is set from the attach response on use() with custom tools', async () => {
4476
+ const customTool = createCustomTool('MY_TOOL', {
4477
+ name: 'My tool',
4478
+ description: 'Does a thing',
4479
+ inputParams: z.object({}),
4480
+ execute: async () => ({ ok: true }),
4481
+ });
4482
+ mockClient.toolRouter.session.attach.mockResolvedValueOnce(
4483
+ withSource(mockSessionRetrieveResponse, 'sc_1')
4484
+ );
4485
+
4486
+ const session = await toolRouter.use(sessionId, { customTools: [customTool] });
4487
+
4488
+ expect(mockClient.toolRouter.session.attach).toHaveBeenCalled();
4489
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4490
+ });
4491
+
4492
+ it('copies only the id', async () => {
4493
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce({
4494
+ ...mockSessionRetrieveResponse,
4495
+ experimental: { source_session_config: { id: 'sc_1', name: 'Daily digest' } },
4496
+ });
4497
+
4498
+ const session = await toolRouter.use(sessionId);
4499
+
4500
+ expect(session.experimental.sourceSessionConfig).toStrictEqual({ id: 'sc_1' });
4501
+ });
4502
+
4503
+ it('is replaced by the config the update response reports', async () => {
4504
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4505
+ withSource(mockSessionRetrieveResponse, 'sc_1')
4506
+ );
4507
+ mockClient.toolRouter.session.patch.mockResolvedValueOnce(
4508
+ withSource(patchResponse(8), 'sc_2')
4509
+ );
4510
+ const session = await toolRouter.use(sessionId);
4511
+
4512
+ await session.update({ experimental: { sessionConfigId: 'sc_2' } });
4513
+
4514
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_2' });
4515
+ });
4516
+
4517
+ it('survives an inline update whose response still carries it, then clears when omitted', async () => {
4518
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4519
+ withSource(mockSessionRetrieveResponse, 'sc_1')
4520
+ );
4521
+ mockClient.toolRouter.session.patch
4522
+ .mockResolvedValueOnce(withSource(patchResponse(8), 'sc_1'))
4523
+ .mockResolvedValueOnce(patchResponse(9));
4524
+ const session = await toolRouter.use(sessionId);
4525
+
4526
+ await session.update({ toolkits: ['gmail'] });
4527
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4528
+
4529
+ await session.update({ toolkits: ['slack'] });
4530
+ expect(session.experimental.sourceSessionConfig).toBeUndefined();
4531
+ });
4532
+
4533
+ it('makes no extra lookups from tools(), search() or execute()', async () => {
4534
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(
4535
+ withSource(mockSessionRetrieveResponse, 'sc_1')
4536
+ );
4537
+ mockClient.toolRouter.session.search.mockResolvedValueOnce({
4538
+ success: true,
4539
+ error: null,
4540
+ results: [],
4541
+ tool_schemas: {},
4542
+ toolkit_connection_statuses: [],
4543
+ next_steps_guidance: [],
4544
+ session: { id: sessionId, generate_id: false, instructions: '' },
4545
+ time_info: {
4546
+ current_time_utc: '2026-01-01T00:00:00Z',
4547
+ current_time_utc_epoch_seconds: 0,
4548
+ message: '',
4549
+ },
4550
+ });
4551
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
4552
+ data: {},
4553
+ error: null,
4554
+ log_id: 'log_1',
4555
+ });
4556
+ const session = await toolRouter.use(sessionId);
4557
+
4558
+ await session.tools();
4559
+ await session.search({ query: 'send an email' });
4560
+ await session.execute('GMAIL_SEND_EMAIL', {});
4561
+
4562
+ // The mock client has no `sessionConfigs`, so any lookup would throw.
4563
+ expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledTimes(1);
4564
+ });
4565
+ });
4566
+
4567
+ describe('fail closed', () => {
4568
+ it.each([
4569
+ [new BadRequestError(400, undefined, 'Bad request', {}), {}],
4570
+ [new PermissionDeniedError(403, undefined, 'Forbidden', {}), {}],
4571
+ [new NotFoundError(404, undefined, 'Not found', {}), {}],
4572
+ [new ConflictError(409, undefined, 'Conflict', {}), {}],
4573
+ [new ConflictError(409, undefined, 'Conflict', {}), { expectedConfigVersion: 7 }],
4574
+ ])('preserves state and does not retry after %s with %j', async (error, precondition) => {
4575
+ mockClient.toolRouter.session.retrieve.mockResolvedValueOnce({
4576
+ ...mockSessionRetrieveResponse,
4577
+ experimental: { source_session_config: { id: 'sc_1' } },
4578
+ });
4579
+ mockClient.toolRouter.session.patch.mockRejectedValueOnce(error);
4580
+ const session = await toolRouter.use(sessionId);
4581
+ const configBefore = session.config;
4582
+
4583
+ const failure = await session
4584
+ .update({ experimental: { sessionConfigId: 'sc_2' }, ...precondition })
4585
+ .catch(e => e);
4586
+
4587
+ if (error.status === 409) {
4588
+ expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4589
+ expect(failure.statusCode).toBe(409);
4590
+ expect(failure.message).toContain(sessionId);
4591
+ expect(failure.message).toContain('sc_2');
4592
+ expect(failure.message).toMatch(/re-fetch/i);
4593
+ expect(failure.message).toMatch(/retry/i);
4594
+ expect(failure.message).not.toMatch(/no longer at version/);
4595
+ expect(failure.meta).toMatchObject({ sessionId, sessionConfigId: 'sc_2' });
4596
+ } else {
4597
+ expect(failure).toBe(error);
4598
+ }
4599
+ expect(mockClient.toolRouter.session.patch).toHaveBeenCalledTimes(1);
4600
+ expect(session.config).toBe(configBefore);
4601
+ expect(session.configVersion).toBe(7);
4602
+ expect(session.experimental.sourceSessionConfig).toEqual({ id: 'sc_1' });
4603
+ });
4604
+
4605
+ it.each([
4606
+ ['403', () => new PermissionDeniedError(403, undefined, 'Forbidden', {})],
4607
+ ['404', () => new NotFoundError(404, undefined, 'Not found', {})],
4608
+ ])(
4609
+ 'surfaces a %s from create unchanged and never retries without the config',
4610
+ async (_status, makeError) => {
4611
+ const error = makeError();
4612
+ mockClient.toolRouter.session.create.mockRejectedValueOnce(error);
4613
+
4614
+ await expect(
4615
+ toolRouter.create('user_123', { experimental: { sessionConfigId: 'sc_archived' } })
4616
+ ).rejects.toBe(error);
4617
+
4618
+ expect(mockClient.toolRouter.session.create).toHaveBeenCalledTimes(1);
4619
+ expect(mockClient.toolRouter.session.create.mock.calls[0][0].experimental).toEqual({
4620
+ session_config_id: 'sc_archived',
4621
+ });
4622
+ }
4623
+ );
4624
+ });
4625
+ });
4626
});