Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 134 lines 4.46 KB
Raw
1 import { describe, it, expect, vi } from 'vitest';
2 import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3 import { Tools } from '../../src/models/Tools';
4 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 import { SessionContextImpl } from '../../src/models/SessionContext';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7 import { toolMocks } from '../utils/mocks/data.mock';
8 import type { Tool } from '../../src/types/tool.types';
9
10 vi.mock('../../src/telemetry/Telemetry', () => ({
11 telemetry: { instrument: vi.fn() },
12 }));
13
14 // Regression for https://github.com/ComposioHQ/composio/issues/3654: executing
15 // a tool or proxying an API call is a non-idempotent write, and the backend does
16 // not deduplicate executions. A retry after the backend already acted duplicates
17 // the side effect (e.g. sends the same email twice), so every execution path
18 // must reach the transport exactly once. Reads keep the client's default retries.
19 //
20 // These tests run a real client against a counting `fetch` so they observe the
21 // retry loop itself, not just the options the SDK passes to it.
22
23 const SESSION_ID = 'sess_123';
24
25 /** A real client whose every request is answered with a retryable 503. */
26 const createFailingClient = () => {
27 const fetch = vi.fn<typeof globalThis.fetch>(
28 async () =>
29 new Response(JSON.stringify({ error: { message: 'unavailable' } }), {
30 status: 503,
31 // Keep the retry backoff out of the test's wall-clock time.
32 headers: { 'content-type': 'application/json', 'retry-after-ms': '1' },
33 })
34 );
35 const client = new ComposioClient({
36 auth: Auth.project('test-api-key'),
37 baseURL: 'https://backend.invalid',
38 transport: createFetchTransport({ fetch }),
39 });
40 return { client, fetch };
41 };
42
43 const createTools = (client: ComposioClient) => new Tools(client, { provider: new MockProvider() });
44
45 const createSession = (client: ComposioClient) =>
46 new ToolRouterSession(client, { apiKey: 'key', provider: new MockProvider() }, SESSION_ID, {
47 type: 'http' as const,
48 url: `https://backend.invalid/api/v3/tool_router/session/${SESSION_ID}`,
49 });
50
51 const proxyParams = {
52 toolkit: 'github',
53 endpoint: 'https://api.github.com/user/repos',
54 method: 'POST' as const,
55 body: { name: 'repo' },
56 };
57
58 const executionPaths: Array<{
59 name: string;
60 run: (client: ComposioClient) => Promise<unknown>;
61 }> = [
62 {
63 name: 'tools.execute',
64 run: client => {
65 const tools = createTools(client);
66 // Keep the (read) tool-schema lookup off the transport.
67 vi.spyOn(tools, 'getRawComposioToolBySlug').mockResolvedValue(
68 toolMocks.transformedTool as unknown as Tool
69 );
70 return tools.execute('COMPOSIO_TOOL', {
71 userId: 'test-user',
72 arguments: { query: 'test' },
73 dangerouslySkipVersionCheck: true,
74 });
75 },
76 },
77 {
78 name: 'tools.proxyExecute',
79 run: client =>
80 createTools(client).proxyExecute({
81 endpoint: '/api/test',
82 method: 'POST',
83 body: { data: 'test' },
84 connectedAccountId: 'test-account-id',
85 }),
86 },
87 {
88 name: 'provider-wrapped session tool',
89 run: client =>
90 createTools(client).executeSessionTool('GMAIL_SEND_EMAIL', {
91 sessionId: SESSION_ID,
92 arguments: { to: 'test@test.com' },
93 }),
94 },
95 {
96 name: 'session.execute',
97 run: client => createSession(client).execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' }),
98 },
99 {
100 name: 'session.proxyExecute',
101 run: client => createSession(client).proxyExecute(proxyParams),
102 },
103 {
104 name: 'custom tool context execute',
105 run: client =>
106 new SessionContextImpl(client, 'test-user', SESSION_ID).execute('GMAIL_SEND_EMAIL', {
107 to: 'test@test.com',
108 }),
109 },
110 {
111 name: 'custom tool context proxyExecute',
112 run: client =>
113 new SessionContextImpl(client, 'test-user', SESSION_ID).proxyExecute(proxyParams),
114 },
115 ];
116
117 describe('tool execution is never retried', () => {
118 it.each(executionPaths)('$name reaches the backend exactly once', async ({ run }) => {
119 const { client, fetch } = createFailingClient();
120
121 await expect(run(client)).rejects.toThrow();
122
123 expect(fetch).toHaveBeenCalledTimes(1);
124 });
125
126 it('reads keep the default retries', async () => {
127 const { client, fetch } = createFailingClient();
128
129 await expect(createTools(client).getToolsEnum()).rejects.toThrow();
130
131 // The first attempt plus the client's two default retries.
132 expect(fetch).toHaveBeenCalledTimes(3);
133 });
134 });