Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import path from 'node:path'; |
| 2 | import * as tempy from 'tempy'; |
| 3 | import { |
| 4 | Auth, |
| 5 | make as makeComposioClient, |
| 6 | type ComposioError, |
| 7 | type RequestOptions, |
| 8 | } from '@composio/client/effect'; |
| 9 | import type { |
| 10 | TriggerInstanceListActiveParams, |
| 11 | TriggerInstanceUpsertParams, |
| 12 | } from '@composio/client/resources/trigger-instances'; |
| 13 | import { TIMESTAMP } from '../models/account'; |
| 14 | import * as BunFileSystem from '@effect/platform-bun/BunFileSystem'; |
| 15 | import * as BunPath from '@effect/platform-bun/BunPath'; |
| 16 | import { |
| 17 | ConfigProvider, |
| 18 | Console, |
| 19 | Context, |
| 20 | DateTime, |
| 21 | Effect, |
| 22 | FileSystem, |
| 23 | Layer, |
| 24 | Option, |
| 25 | Path, |
| 26 | References, |
| 27 | Schedule, |
| 28 | Stream, |
| 29 | } from 'effect'; |
| 30 | import { CliConfig, type Command as CliCommand } from 'effect/cli'; |
| 31 | import { ChildProcess, ChildProcessSpawner } from 'effect/process'; |
| 32 | import { ComposioCliConfig } from 'src/cli-config'; |
| 33 | import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider'; |
| 34 | import * as MockConsole from './mock-console'; |
| 35 | import * as MockTerminal from './mock-terminal'; |
| 36 | import { TerminalUITest } from './terminal-ui-test'; |
| 37 | import { NodeProcess } from 'src/services/node-process'; |
| 38 | import { cliDebugFlagsLayer } from 'src/services/runtime-flags'; |
| 39 | import { PendingLoginSession } from 'src/services/pending-login-session'; |
| 40 | import { |
| 41 | ComposioClientSingleton, |
| 42 | ComposioSessionRepository, |
| 43 | ComposioToolkitsRepository, |
| 44 | type ClientScope, |
| 45 | } from 'src/services/composio-clients'; |
| 46 | import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector'; |
| 47 | import type { TriggerInstanceItem } from 'src/models/triggers'; |
| 48 | import { ComposioUserContextLive } from 'src/services/user-context'; |
| 49 | import { ComposioCliUserConfig } from 'src/services/cli-user-config'; |
| 50 | import { CliUserConfig } from 'src/models/cli-user-config'; |
| 51 | import { UpgradeBinary } from 'src/services/upgrade-binary'; |
| 52 | import { NodeOs } from 'src/services/node-os'; |
| 53 | import { TriggersRealtime } from 'src/services/triggers-realtime'; |
| 54 | import { ShutdownSignal } from 'src/services/shutdown-signal'; |
| 55 | import { ToolsExecutor, ToolsExecutorLive } from 'src/services/tools-executor'; |
| 56 | import { DashboardToolExecutionTest, type DashboardTestResponder } from '../layers/dashboard'; |
| 57 | import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog'; |
| 58 | import type { ToolExecuteResponse } from 'src/services/tools-executor'; |
| 59 | import type { |
| 60 | SessionCreateResponse, |
| 61 | SessionExecuteResponse, |
| 62 | SessionExecuteMetaResponse, |
| 63 | SessionLinkResponse, |
| 64 | SessionSearchResponse, |
| 65 | SessionToolkitsResponse, |
| 66 | SessionProxyExecuteResponse, |
| 67 | SessionCreateParams, |
| 68 | SessionExecuteParams, |
| 69 | SessionExecuteMetaParams, |
| 70 | SessionLinkParams, |
| 71 | SessionProxyExecuteParams, |
| 72 | SessionSearchParams, |
| 73 | SessionToolkitsParams, |
| 74 | } from '@composio/client/resources/tool-router'; |
| 75 | import { makeStreamStdin, Stdin } from 'src/services/stdin'; |
| 76 | import { ProjectContext } from 'src/services/project-context'; |
| 77 | import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector'; |
| 78 | import type { CommandRunnerShape } from 'src/services/command-runner'; |
| 79 | import { TerminalUI } from 'src/services/terminal-ui'; |
| 80 | import type { SetupSkillInstallerShape } from 'src/services/setup-skill-installer'; |
| 81 | import { FetchHttpClient, HttpClient } from 'effect/http'; |
| 82 | import * as BunServices from '@effect/platform-bun/BunServices'; |
| 83 | import { notFoundError } from '../layers/not-found'; |
| 84 | import { DEFAULT_PAGE_LIMIT } from '../layers/page'; |
| 85 | import { CommandRunnerTest } from '../layers/command-runner'; |
| 86 | import { SetupSkillInstallerTest } from '../layers/setup'; |
| 87 | import { InvocationHooksTest } from '../layers/invocation-hooks'; |
| 88 | import { |
| 89 | resolveToolkitsTestData, |
| 90 | toolkitCatalogMethods, |
| 91 | type ToolkitsTestData, |
| 92 | } from '../layers/toolkits'; |
| 93 | import { |
| 94 | mockAccountResources, |
| 95 | type AccountTestData, |
| 96 | type MockRequestScope, |
| 97 | } from '../layers/accounts'; |
| 98 | import { |
| 99 | connectedAccountRepositoryMethods, |
| 100 | mockConnectedAccountResources, |
| 101 | resolveAuthConfigsTestData, |
| 102 | resolveConnectedAccountsTestData, |
| 103 | type AuthConfigsTestData, |
| 104 | type ConnectedAccountsTestData, |
| 105 | } from '../layers/connected-accounts'; |
| 106 | |
| 107 | export type { MockAccountRequest, MockRequestScope } from '../layers/accounts'; |
| 108 | |
| 109 | export interface TestLiveInput { |
| 110 | /** |
| 111 | * Config provider to use in test. Its values win; anything it leaves unset falls through to |
| 112 | * `hostOnlyEnvConfigProvider`, the live host environment without any `COMPOSIO_*`, |
| 113 | * `DEBUG_OVERRIDE_*`, or `FORCE_*` variable, so `HOST_CONFIG` (`CI`, `VITEST`, `PATH`, the |
| 114 | * agent-host markers) keeps reading the real process the way the old raw-provider bypass did. |
| 115 | */ |
| 116 | baseConfigProvider?: ConfigProvider.ConfigProvider; |
| 117 | |
| 118 | /** |
| 119 | * Fixture to use in test. |
| 120 | * TODO: consider extracting `fixture` into another `Effect`. |
| 121 | */ |
| 122 | fixture?: string; |
| 123 | |
| 124 | /** |
| 125 | * Override the running-executable path reported by `NodeProcess`. |
| 126 | * |
| 127 | * A relative value resolves against the per-test home directory, which is a |
| 128 | * fresh temp dir created while the layer is being built — so a scenario that |
| 129 | * needs an exec path underneath it (e.g. `.local/bin/composio`) can stay |
| 130 | * relative instead of spelling out a path it cannot know up front. |
| 131 | * Defaults to `<homedir>/composio`. |
| 132 | */ |
| 133 | execPath?: string; |
| 134 | |
| 135 | /** |
| 136 | * Mock toolkit-related data to use in test. |
| 137 | */ |
| 138 | toolkitsData?: ToolkitsTestData; |
| 139 | |
| 140 | /** |
| 141 | * Account, session-info, and consumer data served by the mock client's |
| 142 | * `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post` |
| 143 | * escape hatch. |
| 144 | */ |
| 145 | accountData?: AccountTestData; |
| 146 | |
| 147 | /** |
| 148 | * Mock auth-config data to use in test. |
| 149 | */ |
| 150 | authConfigsData?: AuthConfigsTestData; |
| 151 | |
| 152 | /** |
| 153 | * Mock connected-account data to use in test. |
| 154 | */ |
| 155 | connectedAccountsData?: ConnectedAccountsTestData; |
| 156 | |
| 157 | /** |
| 158 | * Mock trigger instance data to use in test. |
| 159 | */ |
| 160 | triggersData?: { |
| 161 | items?: TriggerInstanceItem[]; |
| 162 | /** |
| 163 | * Make `triggerInstances.upsert` reject slugs missing from `toolkitsData.triggerTypes`, |
| 164 | * as the API does for an unknown trigger type. |
| 165 | */ |
| 166 | rejectUnknownTriggerSlugs?: boolean; |
| 167 | }; |
| 168 | |
| 169 | /** |
| 170 | * Mock realtime trigger data to use in test. |
| 171 | */ |
| 172 | realtimeData?: { |
| 173 | events?: ReadonlyArray<Record<string, unknown>>; |
| 174 | }; |
| 175 | |
| 176 | cliUserConfig?: { |
| 177 | developerModeEnabled?: boolean; |
| 178 | developerDangerousCommandsEnabled?: boolean; |
| 179 | experimentalFeatures?: Record<string, boolean>; |
| 180 | }; |
| 181 | |
| 182 | /** |
| 183 | * Mock stdin for commands that read input. |
| 184 | */ |
| 185 | stdin?: { |
| 186 | isTTY: boolean; |
| 187 | data: string; |
| 188 | /** |
| 189 | * Reads this stream with the real stdin reader instead of returning `data`: a `PassThrough` |
| 190 | * the test writes to (or leaves open, like an agent harness can) when timing matters. |
| 191 | */ |
| 192 | stream?: NodeJS.ReadableStream; |
| 193 | }; |
| 194 | |
| 195 | /** |
| 196 | * Override tools executor behavior for tests. |
| 197 | * |
| 198 | * When set, the `ToolsExecutor` service is replaced with a canned mock |
| 199 | * that bypasses the real `ToolsExecutorLive` and the Tool Router entirely. |
| 200 | * Use this only for tests that need to control the executor response directly |
| 201 | * (e.g. soft failure tests). |
| 202 | * |
| 203 | * When NOT set, the real `ToolsExecutorLive` is used, which flows through |
| 204 | * the mock `ComposioClientSingleton` → Tool Router session mocks. |
| 205 | */ |
| 206 | toolsExecutor?: { |
| 207 | failWith?: unknown; |
| 208 | respondWith?: ToolExecuteResponse; |
| 209 | /** Called each time the mock executor actually runs a tool call. */ |
| 210 | onExecute?: (slug: string) => void; |
| 211 | }; |
| 212 | |
| 213 | /** |
| 214 | * Stand in for the Dashboard endpoints `composio execute` sends consumer |
| 215 | * executions to. |
| 216 | * |
| 217 | * By default the test Dashboard does what the real one does with a request: |
| 218 | * it creates a Tool Router session itself and executes on the mock client's |
| 219 | * `toolRouter.session.*` handlers, relaying their answer or their status |
| 220 | * error. Set `respond` to answer yourself; a rejection is delivered to the |
| 221 | * CLI as a network failure. |
| 222 | */ |
| 223 | dashboard?: { |
| 224 | respond?: DashboardTestResponder; |
| 225 | }; |
| 226 | |
| 227 | /** |
| 228 | * Override Tool Router session behavior for tests. |
| 229 | * |
| 230 | * Controls the mock `ComposioClientSingleton`'s `toolRouter.session.*` methods. |
| 231 | * Each method can be overridden individually; defaults are provided for all. |
| 232 | * |
| 233 | * Each override answers with an Effect, so a test can fail a call with one |
| 234 | * of the client's own errors or route it to a client over a stub transport. |
| 235 | * |
| 236 | * When `toolsExecutor` is also set, its mock takes precedence for `tools execute` |
| 237 | * (the Tool Router mock is still used by `toolkits list`, `toolkits info`, etc.). |
| 238 | */ |
| 239 | toolRouter?: { |
| 240 | /** Override `session.create`. Receives the create params. */ |
| 241 | create?: (params: SessionCreateParams) => Effect.Effect<SessionCreateResponse, ComposioError>; |
| 242 | /** Override `session.execute`. Receives sessionId, params, and request options. */ |
| 243 | execute?: ( |
| 244 | sessionId: string, |
| 245 | params: SessionExecuteParams, |
| 246 | options?: RequestOptions |
| 247 | ) => Effect.Effect<SessionExecuteResponse, ComposioError>; |
| 248 | /** Override `session.executeMeta`. Receives sessionId, params, and request options. */ |
| 249 | executeMeta?: ( |
| 250 | sessionId: string, |
| 251 | params: SessionExecuteMetaParams, |
| 252 | options?: RequestOptions |
| 253 | ) => Effect.Effect<SessionExecuteMetaResponse, ComposioError>; |
| 254 | /** Override `session.link`. Receives sessionId, params, and request options. */ |
| 255 | link?: ( |
| 256 | sessionId: string, |
| 257 | params: SessionLinkParams, |
| 258 | options?: RequestOptions |
| 259 | ) => Effect.Effect<SessionLinkResponse, ComposioError>; |
| 260 | /** Override `session.proxyExecute`. Receives sessionId, params, and request options. */ |
| 261 | proxyExecute?: ( |
| 262 | sessionId: string, |
| 263 | params: SessionProxyExecuteParams, |
| 264 | options?: RequestOptions |
| 265 | ) => Effect.Effect<SessionProxyExecuteResponse, ComposioError>; |
| 266 | /** Override `session.search`. Receives sessionId and params. */ |
| 267 | search?: ( |
| 268 | sessionId: string, |
| 269 | params: SessionSearchParams |
| 270 | ) => Effect.Effect<SessionSearchResponse, ComposioError>; |
| 271 | /** Override `session.toolkits`. Receives sessionId and optional params. */ |
| 272 | toolkits?: ( |
| 273 | sessionId: string, |
| 274 | params?: SessionToolkitsParams | null |
| 275 | ) => Effect.Effect<SessionToolkitsResponse, ComposioError>; |
| 276 | }; |
| 277 | |
| 278 | /** |
| 279 | * Override CommandRunner behavior for tests. |
| 280 | * When set, the `CommandRunner` service uses the provided mock instance. |
| 281 | * When NOT set, uses a default mock that always returns exit code 0. |
| 282 | */ |
| 283 | commandRunner?: CommandRunnerShape; |
| 284 | |
| 285 | /** Override setup's Claude skill installer. Defaults to an idempotent no-op. */ |
| 286 | setupSkillInstaller?: SetupSkillInstallerShape; |
| 287 | |
| 288 | /** |
| 289 | * Override TerminalUI behavior for tests. |
| 290 | * When set, replaces the default TerminalUITest (which auto-selects first option). |
| 291 | */ |
| 292 | terminalUI?: TerminalUI; |
| 293 | } |
| 294 | |
| 295 | /** |
| 296 | * Concrete Effect layer compositions for the Composio test suites. |
| 297 | * |
| 298 | * ┌─── The service to be created |
| 299 | * │ ┌─── The possible error |
| 300 | * │ │ ┌─── The required dependencies |
| 301 | * ▼ ▼ ▼ |
| 302 | * Layer<RequirementsOut, Error, RequirementsIn> |
| 303 | */ |
| 304 | |
| 305 | type RequiredLayer = Layer.Layer<CliCommand.Environment, unknown, never>; |
| 306 | |
| 307 | /** |
| 308 | * Effect layer that injects all the services needed for tests, using mocks to avoid |
| 309 | * side-effects like unwanted HTTP requests to remote services. |
| 310 | */ |
| 311 | export const TestLayer = (input?: TestLiveInput) => |
| 312 | Effect.gen(function* () { |
| 313 | const fixture = input?.fixture; |
| 314 | const toolkitsData = resolveToolkitsTestData(input?.toolkitsData); |
| 315 | |
| 316 | const authConfigsData = resolveAuthConfigsTestData(input?.authConfigsData); |
| 317 | const connectedAccountsData = resolveConnectedAccountsTestData(input?.connectedAccountsData); |
| 318 | |
| 319 | const defaultRealtimeData = { |
| 320 | events: [] as ReadonlyArray<Record<string, unknown>>, |
| 321 | } satisfies TestLiveInput['realtimeData']; |
| 322 | const realtimeData = { |
| 323 | ...defaultRealtimeData, |
| 324 | ...(input?.realtimeData ?? {}), |
| 325 | }; |
| 326 | |
| 327 | const defaultTriggersData = { |
| 328 | items: [] as TriggerInstanceItem[], |
| 329 | } satisfies TestLiveInput['triggersData']; |
| 330 | const triggersData = { |
| 331 | ...defaultTriggersData, |
| 332 | ...(input?.triggersData ?? {}), |
| 333 | }; |
| 334 | |
| 335 | const tempDir = tempy.temporaryDirectory({ prefix: 'test' }); |
| 336 | const cwd = (yield* setupFixtureFolder({ fixture, tempDir })) ?? tempDir; |
| 337 | |
| 338 | const ComposioToolkitsRepositoryTest = Layer.succeed( |
| 339 | ComposioToolkitsRepository, |
| 340 | ComposioToolkitsRepository.of({ |
| 341 | ...toolkitCatalogMethods(toolkitsData), |
| 342 | ...connectedAccountRepositoryMethods(authConfigsData, connectedAccountsData), |
| 343 | listActiveTriggers: (_scope, params: TriggerInstanceListActiveParams) => { |
| 344 | let results = [...triggersData.items]; |
| 345 | |
| 346 | const userIds = params.user_ids; |
| 347 | if (userIds && userIds.length > 0) { |
| 348 | const set = new Set(userIds); |
| 349 | results = results.filter(item => set.has(item.user_id)); |
| 350 | } |
| 351 | |
| 352 | const connectedAccountIds = params.connected_account_ids; |
| 353 | if (connectedAccountIds && connectedAccountIds.length > 0) { |
| 354 | const set = new Set(connectedAccountIds); |
| 355 | results = results.filter(item => set.has(item.connected_account_id)); |
| 356 | } |
| 357 | |
| 358 | const authConfigIds = params.auth_config_ids; |
| 359 | if (authConfigIds && authConfigIds.length > 0) { |
| 360 | const set = new Set(authConfigIds); |
| 361 | results = results.filter(item => set.has(item.auth_config_id)); |
| 362 | } |
| 363 | |
| 364 | const triggerIds = params.trigger_ids; |
| 365 | if (triggerIds && triggerIds.length > 0) { |
| 366 | const set = new Set(triggerIds); |
| 367 | results = results.filter(item => set.has(item.id)); |
| 368 | } |
| 369 | |
| 370 | const triggerNames = params.trigger_names; |
| 371 | if (triggerNames && triggerNames.length > 0) { |
| 372 | const set = new Set(triggerNames.map(name => name.toUpperCase())); |
| 373 | results = results.filter(item => set.has(item.trigger_name.toUpperCase())); |
| 374 | } |
| 375 | |
| 376 | const includeDisabled = params.show_disabled ?? false; |
| 377 | if (!includeDisabled) { |
| 378 | results = results.filter(item => item.disabled_at === null); |
| 379 | } |
| 380 | |
| 381 | const limit = params.limit ?? DEFAULT_PAGE_LIMIT; |
| 382 | const items = results.slice(0, limit); |
| 383 | return Effect.succeed({ |
| 384 | items, |
| 385 | total_items: results.length, |
| 386 | total_pages: Math.ceil(results.length / limit), |
| 387 | current_page: 1, |
| 388 | next_cursor: null, |
| 389 | }); |
| 390 | }, |
| 391 | createTrigger: (_scope, triggerSlug: string, params?: TriggerInstanceUpsertParams) => |
| 392 | Effect.succeed({ |
| 393 | trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`, |
| 394 | type: 'webhook' as const, |
| 395 | fallback_reason: null, |
| 396 | polling_interval: null, |
| 397 | }), |
| 398 | enableTrigger: () => Effect.succeed({ status: 'success' as const }), |
| 399 | disableTrigger: () => Effect.succeed({ status: 'success' as const }), |
| 400 | }) |
| 401 | ); |
| 402 | const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository(); |
| 403 | const TriggersRealtimeTest = Layer.succeed( |
| 404 | TriggersRealtime, |
| 405 | TriggersRealtime.of({ |
| 406 | listen: (onEvent, options) => |
| 407 | Effect.gen(function* () { |
| 408 | yield* options?.onSubscribed ?? Effect.void; |
| 409 | yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event))); |
| 410 | return yield* Effect.never; |
| 411 | }).pipe(Effect.scoped), |
| 412 | listenInProject: (_scope, onEvent, options) => |
| 413 | Effect.gen(function* () { |
| 414 | yield* options?.onSubscribed ?? Effect.void; |
| 415 | yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event))); |
| 416 | return yield* Effect.never; |
| 417 | }).pipe(Effect.scoped), |
| 418 | }) |
| 419 | ); |
| 420 | |
| 421 | // Mock operating-system details |
| 422 | const NodeOsTest = Layer.succeed( |
| 423 | NodeOs, |
| 424 | NodeOs.of({ |
| 425 | homedir: cwd, |
| 426 | tmpdir: tempy.rootTemporaryDirectory, |
| 427 | arch: 'arm64', |
| 428 | platform: 'darwin', |
| 429 | }) |
| 430 | ); |
| 431 | |
| 432 | // Mock `node:process` |
| 433 | const NodeProcessTest = Layer.succeed( |
| 434 | NodeProcess, |
| 435 | NodeProcess.of({ |
| 436 | cwd, |
| 437 | execPath: input?.execPath ? path.resolve(cwd, input.execPath) : path.join(cwd, 'composio'), |
| 438 | platform: 'darwin', |
| 439 | arch: 'arm64', |
| 440 | }) |
| 441 | ); |
| 442 | |
| 443 | const ComposioUserContextTest = Layer.provideMerge( |
| 444 | ComposioUserContextLive, |
| 445 | Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest) |
| 446 | ); |
| 447 | |
| 448 | let rawCliUserConfig = CliUserConfig.make({ |
| 449 | developer: { |
| 450 | enabled: input?.cliUserConfig?.developerModeEnabled ?? true, |
| 451 | destructiveActions: input?.cliUserConfig?.developerDangerousCommandsEnabled ?? false, |
| 452 | }, |
| 453 | experimentalFeatures: input?.cliUserConfig?.experimentalFeatures ?? {}, |
| 454 | artifactDirectory: Option.none(), |
| 455 | security: 'auto', |
| 456 | }); |
| 457 | |
| 458 | const ComposioCliUserConfigTest = Layer.succeed( |
| 459 | ComposioCliUserConfig, |
| 460 | ComposioCliUserConfig.of({ |
| 461 | get data() { |
| 462 | return { |
| 463 | channel: 'beta' as const, |
| 464 | developerModeEnabled: rawCliUserConfig.developer.enabled, |
| 465 | developerDangerousCommandsEnabled: rawCliUserConfig.developer.destructiveActions, |
| 466 | experimentalFeatures: rawCliUserConfig.experimentalFeatures, |
| 467 | artifactDirectory: Option.getOrUndefined(rawCliUserConfig.artifactDirectory), |
| 468 | security: 'auto' as const, |
| 469 | }; |
| 470 | }, |
| 471 | get raw() { |
| 472 | return rawCliUserConfig; |
| 473 | }, |
| 474 | channel: 'beta', |
| 475 | isDevModeEnabled: () => rawCliUserConfig.developer.enabled, |
| 476 | areDeveloperDangerousCommandsEnabled: () => rawCliUserConfig.developer.destructiveActions, |
| 477 | isExperimentalFeatureEnabled: feature => |
| 478 | rawCliUserConfig.experimentalFeatures[feature] ?? true, |
| 479 | update: next => |
| 480 | Effect.sync(() => { |
| 481 | rawCliUserConfig = CliUserConfig.make({ |
| 482 | ...rawCliUserConfig, |
| 483 | ...next, |
| 484 | }); |
| 485 | }), |
| 486 | }) |
| 487 | ); |
| 488 | |
| 489 | const UpgradeBinaryTest = Layer.provide( |
| 490 | UpgradeBinary.Default, |
| 491 | Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer, NodeOsTest) |
| 492 | ); |
| 493 | |
| 494 | const StdinTest = Layer.succeed( |
| 495 | Stdin, |
| 496 | input?.stdin?.stream === undefined |
| 497 | ? Stdin.of({ |
| 498 | isTTY: () => input?.stdin?.isTTY ?? true, |
| 499 | readAll: () => Effect.succeed(input?.stdin?.data ?? ''), |
| 500 | readAllUnlessSilent: () => Effect.succeed(Option.some(input?.stdin?.data ?? '')), |
| 501 | }) |
| 502 | : makeStreamStdin(input.stdin.stream, () => input.stdin?.isTTY ?? true) |
| 503 | ); |
| 504 | |
| 505 | // --- Tool Router mock (ComposioClientSingleton) --- |
| 506 | // Provides a fake `@composio/client` Composio instance with configurable |
| 507 | // `toolRouter.session.*` methods. Each method has a sensible default that |
| 508 | // can be overridden per-test via `input.toolRouter.<method>`. |
| 509 | |
| 510 | const toolRouterOverrides = input?.toolRouter; |
| 511 | |
| 512 | const defaultToolkitsHandler = ( |
| 513 | _sessionId: string, |
| 514 | params?: SessionToolkitsParams | null |
| 515 | ): Effect.Effect<SessionToolkitsResponse> => |
| 516 | Effect.sync(() => { |
| 517 | let results: SessionToolkitsResponse['items'] = toolkitsData.toolkits.map(t => ({ |
| 518 | slug: t.slug, |
| 519 | name: t.name, |
| 520 | meta: { description: t.meta.description, logo: '' }, |
| 521 | is_no_auth: t.no_auth ?? false, |
| 522 | enabled: true, |
| 523 | connected_account: null, |
| 524 | composio_managed_auth_schemes: [...(t.composio_managed_auth_schemes ?? [])], |
| 525 | })); |
| 526 | |
| 527 | if (params?.search) { |
| 528 | const q = params.search.toLowerCase(); |
| 529 | results = results.filter( |
| 530 | t => |
| 531 | t.name.toLowerCase().includes(q) || |
| 532 | t.slug.toLowerCase().includes(q) || |
| 533 | t.meta.description.toLowerCase().includes(q) |
| 534 | ); |
| 535 | } |
| 536 | |
| 537 | if (params?.toolkits) { |
| 538 | const slugSet = new Set(params.toolkits.map(s => s.toLowerCase())); |
| 539 | results = results.filter(t => slugSet.has(t.slug.toLowerCase())); |
| 540 | } |
| 541 | |
| 542 | const limit = params?.limit ?? 1000; |
| 543 | const items = results.slice(0, limit); |
| 544 | return { |
| 545 | items, |
| 546 | current_page: 1, |
| 547 | total_items: results.length, |
| 548 | total_pages: Math.ceil(results.length / limit), |
| 549 | next_cursor: null, |
| 550 | }; |
| 551 | }); |
| 552 | |
| 553 | const defaultSearchHandler = ( |
| 554 | _sessionId: string, |
| 555 | params: SessionSearchParams |
| 556 | ): Effect.Effect<SessionSearchResponse> => |
| 557 | Effect.sync(() => { |
| 558 | const results = params.queries.map((query, index) => { |
| 559 | const queryUseCase = query.use_case ?? ''; |
| 560 | const normalizedQuery = queryUseCase.toLowerCase(); |
| 561 | const matchedTools = toolkitsData.tools.filter( |
| 562 | tool => |
| 563 | tool.name.toLowerCase().includes(normalizedQuery) || |
| 564 | tool.slug.toLowerCase().includes(normalizedQuery) || |
| 565 | tool.description.toLowerCase().includes(normalizedQuery) |
| 566 | ); |
| 567 | |
| 568 | return { |
| 569 | index: index + 1, |
| 570 | use_case: queryUseCase, |
| 571 | primary_tool_slugs: matchedTools.map(tool => tool.slug), |
| 572 | related_tool_slugs: [], |
| 573 | toolkits: Array.from( |
| 574 | new Set( |
| 575 | matchedTools |
| 576 | .map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '') |
| 577 | .filter(Boolean) |
| 578 | ) |
| 579 | ), |
| 580 | matchedTools, |
| 581 | }; |
| 582 | }); |
| 583 | |
| 584 | const allMatchedTools = results.flatMap(result => result.matchedTools); |
| 585 | const toolSchemas = Object.fromEntries( |
| 586 | allMatchedTools.map(tool => [ |
| 587 | tool.slug, |
| 588 | { |
| 589 | tool_slug: tool.slug, |
| 590 | toolkit: tool.slug.split('_')[0]?.toLowerCase() ?? '', |
| 591 | description: tool.description, |
| 592 | hasFullSchema: true, |
| 593 | input_schema: tool.input_parameters, |
| 594 | output_schema: tool.output_parameters, |
| 595 | }, |
| 596 | ]) |
| 597 | ); |
| 598 | const toolkitConnectionStatuses = Array.from( |
| 599 | new Set( |
| 600 | allMatchedTools |
| 601 | .map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '') |
| 602 | .filter(Boolean) |
| 603 | ) |
| 604 | ).map(toolkitSlug => ({ |
| 605 | toolkit: toolkitSlug, |
| 606 | description: `${toolkitSlug} toolkit`, |
| 607 | has_active_connection: false, |
| 608 | status_message: 'No active connection', |
| 609 | })); |
| 610 | |
| 611 | return { |
| 612 | success: true, |
| 613 | error: null, |
| 614 | results: results.map(({ matchedTools: _matchedTools, ...result }) => result), |
| 615 | tool_schemas: toolSchemas, |
| 616 | toolkit_connection_statuses: toolkitConnectionStatuses, |
| 617 | next_steps_guidance: [], |
| 618 | session: { |
| 619 | id: 'trs_test_session', |
| 620 | generate_id: false, |
| 621 | instructions: 'Reuse this session id for follow-up calls.', |
| 622 | }, |
| 623 | time_info: { |
| 624 | current_time_utc: TIMESTAMP, |
| 625 | current_time_utc_epoch_seconds: 1767225600, |
| 626 | message: 'UTC time', |
| 627 | }, |
| 628 | }; |
| 629 | }); |
| 630 | |
| 631 | // What the mock client answers with instead of calling the network. |
| 632 | const resourceShadows = { |
| 633 | ...mockConnectedAccountResources(connectedAccountsData), |
| 634 | triggersTypes: { |
| 635 | retrieve: (slug: string) => { |
| 636 | const found = toolkitsData.triggerTypes.find( |
| 637 | trigger => trigger.slug.toUpperCase() === slug.toUpperCase() |
| 638 | ); |
| 639 | return found |
| 640 | ? Effect.succeed(found) |
| 641 | : Effect.fail(notFoundError(`Trigger type "${slug}" not found`)); |
| 642 | }, |
| 643 | }, |
| 644 | triggerInstances: { |
| 645 | upsert: ( |
| 646 | triggerSlug: string, |
| 647 | params?: { |
| 648 | connected_account_id?: string; |
| 649 | trigger_config?: Record<string, unknown>; |
| 650 | } |
| 651 | ) => { |
| 652 | if ( |
| 653 | input?.triggersData?.rejectUnknownTriggerSlugs && |
| 654 | !toolkitsData.triggerTypes.some( |
| 655 | trigger => trigger.slug.toUpperCase() === triggerSlug.toUpperCase() |
| 656 | ) |
| 657 | ) { |
| 658 | return Effect.fail(notFoundError(`Trigger type "${triggerSlug}" not found`)); |
| 659 | } |
| 660 | return Effect.succeed({ |
| 661 | trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`, |
| 662 | type: 'webhook' as const, |
| 663 | fallback_reason: null, |
| 664 | polling_interval: null, |
| 665 | }); |
| 666 | }, |
| 667 | manage: { |
| 668 | update: (triggerId: string, params: { status: 'enable' | 'disable' }) => |
| 669 | Effect.succeed({ |
| 670 | trigger_id: triggerId, |
| 671 | status: params.status, |
| 672 | }), |
| 673 | }, |
| 674 | }, |
| 675 | toolkits: { |
| 676 | retrieve: (slug: string) => { |
| 677 | const detailed = toolkitsData.detailedToolkits.find( |
| 678 | t => t.slug.toLowerCase() === slug.toLowerCase() |
| 679 | ); |
| 680 | if (detailed) { |
| 681 | return Effect.succeed({ |
| 682 | name: detailed.name, |
| 683 | slug: detailed.slug, |
| 684 | is_local_toolkit: detailed.is_local_toolkit, |
| 685 | composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes], |
| 686 | no_auth: detailed.no_auth, |
| 687 | meta: detailed.meta, |
| 688 | }); |
| 689 | } |
| 690 | |
| 691 | const found = toolkitsData.toolkits.find( |
| 692 | t => t.slug.toLowerCase() === slug.toLowerCase() |
| 693 | ); |
| 694 | if (!found) { |
| 695 | return Effect.fail(notFoundError(`Toolkit "${slug}" not found`)); |
| 696 | } |
| 697 | return Effect.succeed({ |
| 698 | name: found.name, |
| 699 | slug: found.slug, |
| 700 | is_local_toolkit: found.is_local_toolkit, |
| 701 | composio_managed_auth_schemes: [...found.composio_managed_auth_schemes], |
| 702 | no_auth: found.no_auth, |
| 703 | meta: found.meta, |
| 704 | }); |
| 705 | }, |
| 706 | }, |
| 707 | files: { |
| 708 | createPresignedURL: (params: { |
| 709 | filename: string; |
| 710 | mimetype: string; |
| 711 | md5: string; |
| 712 | tool_slug: string; |
| 713 | toolkit_slug: string; |
| 714 | }) => |
| 715 | Effect.succeed({ |
| 716 | key: `uploads/${params.filename}`, |
| 717 | new_presigned_url: 'https://s3.test.composio.dev/upload', |
| 718 | }), |
| 719 | }, |
| 720 | toolRouter: { |
| 721 | session: { |
| 722 | create: |
| 723 | toolRouterOverrides?.create ?? |
| 724 | ((params: SessionCreateParams) => |
| 725 | Effect.succeed({ |
| 726 | session_id: 'trs_test_session', |
| 727 | config: { user_id: params.user_id }, |
| 728 | mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' }, |
| 729 | tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'], |
| 730 | })), |
| 731 | execute: |
| 732 | toolRouterOverrides?.execute ?? |
| 733 | ((_sessionId: string, params: SessionExecuteParams) => |
| 734 | Effect.succeed({ |
| 735 | result_type: 'completed' as const, |
| 736 | data: { tool_slug: params.tool_slug, arguments: params.arguments }, |
| 737 | error: null, |
| 738 | log_id: 'log_test', |
| 739 | })), |
| 740 | executeMeta: |
| 741 | toolRouterOverrides?.executeMeta ?? |
| 742 | ((_sessionId: string, params: SessionExecuteMetaParams) => |
| 743 | Effect.succeed({ |
| 744 | result_type: 'completed' as const, |
| 745 | data: { slug: params.slug, arguments: params.arguments }, |
| 746 | error: null, |
| 747 | log_id: 'log_test', |
| 748 | })), |
| 749 | link: |
| 750 | toolRouterOverrides?.link ?? |
| 751 | (() => |
| 752 | Effect.succeed({ |
| 753 | connected_account_id: 'con_test_link', |
| 754 | link_token: 'lt_test_token', |
| 755 | redirect_url: 'https://app.composio.dev/link?token=lt_test_token', |
| 756 | account_type: 'PRIVATE' as const, |
| 757 | })), |
| 758 | proxyExecute: |
| 759 | toolRouterOverrides?.proxyExecute ?? |
| 760 | ((_sessionId: string, params: SessionProxyExecuteParams) => |
| 761 | Effect.succeed({ |
| 762 | status: 200, |
| 763 | data: { |
| 764 | toolkit_slug: params.toolkit_slug, |
| 765 | endpoint: params.endpoint, |
| 766 | method: params.method, |
| 767 | body: params.body ?? null, |
| 768 | parameters: params.parameters ?? [], |
| 769 | }, |
| 770 | headers: {}, |
| 771 | })), |
| 772 | search: toolRouterOverrides?.search ?? defaultSearchHandler, |
| 773 | toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler, |
| 774 | }, |
| 775 | }, |
| 776 | }; |
| 777 | |
| 778 | // A resource the shadows do not cover reaches the transport, which dies |
| 779 | // with the URL instead of sending a live request. |
| 780 | const dieOnNetworkCall = HttpClient.make(request => |
| 781 | Effect.die(new Error(`unexpected network call from the mock Composio client: ${request.url}`)) |
| 782 | ); |
| 783 | |
| 784 | // Each shadow builds its Effect or Stream when consumed. A shadow |
| 785 | // ignores the request options |
| 786 | // (`signal`, `maxRetries`, headers beyond `decode`), and the |
| 787 | // connected-account shadows serve fixture data without cursor traversal: |
| 788 | // pagination, retries, and abort are covered by `stubComposioClient`, |
| 789 | // the real `make` over a recording transport. |
| 790 | const withShadows = <Resources extends object>(base: Resources, shadows: object): Resources => { |
| 791 | const shadowed = { ...base } as Record<string, unknown>; |
| 792 | for (const [key, shadow] of Object.entries(shadows) as Array<[string, unknown]>) { |
| 793 | shadowed[key] = |
| 794 | typeof shadow === 'function' && key === 'listStream' |
| 795 | ? (...args: ReadonlyArray<unknown>) => |
| 796 | Stream.suspend(() => shadow(...args) as Stream.Stream<unknown, unknown>) |
| 797 | : typeof shadow === 'function' |
| 798 | ? (...args: ReadonlyArray<unknown>) => |
| 799 | Effect.suspend(() => shadow(...args) as Effect.Effect<unknown, unknown>) |
| 800 | : withShadows((shadowed[key] ?? {}) as object, shadow as object); |
| 801 | } |
| 802 | return shadowed as Resources; |
| 803 | }; |
| 804 | |
| 805 | const mockComposioClient = withShadows( |
| 806 | makeComposioClient( |
| 807 | { |
| 808 | auth: Auth.project('test'), |
| 809 | baseURL: 'https://mock.invalid', |
| 810 | }, |
| 811 | dieOnNetworkCall |
| 812 | ), |
| 813 | resourceShadows |
| 814 | ); |
| 815 | |
| 816 | // --- Account, session-info, and consumer endpoints --- |
| 817 | // Served per client scope; see `mockAccountResources`. |
| 818 | const accountData = input?.accountData ?? {}; |
| 819 | |
| 820 | const scopedClients = new Map<string, typeof mockComposioClient>(); |
| 821 | const mockClientFor = (scope: MockRequestScope) => { |
| 822 | const key = JSON.stringify([scope.userApiKey, scope.apiKey, scope.orgId, scope.projectId]); |
| 823 | const cached = scopedClients.get(key); |
| 824 | if (cached) return cached; |
| 825 | const scoped = withShadows(mockComposioClient, mockAccountResources(accountData, scope)); |
| 826 | scopedClients.set(key, scoped); |
| 827 | return scoped; |
| 828 | }; |
| 829 | |
| 830 | const ComposioClientSingletonTest = Layer.succeed( |
| 831 | ComposioClientSingleton, |
| 832 | ComposioClientSingleton.of({ |
| 833 | get: Effect.fn(function* () { |
| 834 | return mockClientFor({}); |
| 835 | }), |
| 836 | getFor: Effect.fn(function* (params: ClientScope) { |
| 837 | return mockClientFor({ |
| 838 | userApiKey: params.userApiKey, |
| 839 | apiKey: params.projectApiKey, |
| 840 | orgId: params.orgId, |
| 841 | projectId: params.projectId, |
| 842 | }); |
| 843 | }), |
| 844 | getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }), |
| 845 | }) |
| 846 | ); |
| 847 | |
| 848 | // Built per test layer, so each test resolves toolkit slugs against its own |
| 849 | // cache directory rather than inheriting a memo from an earlier test. |
| 850 | const ToolkitSlugCatalogTest = Layer.provide( |
| 851 | ToolkitSlugCatalog.Default, |
| 852 | ComposioToolkitsRepositoryTest |
| 853 | ); |
| 854 | |
| 855 | // --- ToolsExecutor --- |
| 856 | // When `input.toolsExecutor` is set, use a canned mock (bypasses Tool Router). |
| 857 | // Otherwise, use the real ToolsExecutorLive which flows through the mock ComposioClientSingleton. |
| 858 | const ToolsExecutorTest = input?.toolsExecutor |
| 859 | ? Layer.succeed( |
| 860 | ToolsExecutor, |
| 861 | ToolsExecutor.of({ |
| 862 | execute: (slug, params) => |
| 863 | Effect.suspend(() => { |
| 864 | input.toolsExecutor!.onExecute?.(slug); |
| 865 | if (input.toolsExecutor!.failWith) { |
| 866 | return Effect.fail(input.toolsExecutor!.failWith); |
| 867 | } |
| 868 | if (input.toolsExecutor!.respondWith) { |
| 869 | return Effect.succeed(input.toolsExecutor!.respondWith); |
| 870 | } |
| 871 | return Effect.succeed({ |
| 872 | data: { slug, params }, |
| 873 | error: null, |
| 874 | successful: true, |
| 875 | logId: 'log_test', |
| 876 | }); |
| 877 | }), |
| 878 | }) |
| 879 | ) |
| 880 | : Layer.provide( |
| 881 | ToolsExecutorLive, |
| 882 | Layer.mergeAll( |
| 883 | ComposioClientSingletonTest, |
| 884 | ToolkitSlugCatalogTest, |
| 885 | Layer.provide( |
| 886 | DashboardToolExecutionTest({ |
| 887 | toolRouter: mockComposioClient.toolRouter, |
| 888 | respond: input?.dashboard?.respond, |
| 889 | }), |
| 890 | ComposioUserContextTest |
| 891 | ) |
| 892 | ) |
| 893 | ); |
| 894 | |
| 895 | const CliConfigLive = CliConfig.layer(ComposioCliConfig); |
| 896 | |
| 897 | // TerminalUI — use provided override or default TerminalUITest |
| 898 | const TerminalUILayer = input?.terminalUI |
| 899 | ? Layer.succeed(TerminalUI, input.terminalUI) |
| 900 | : TerminalUITest; |
| 901 | |
| 902 | const _console = yield* MockConsole.make; |
| 903 | |
| 904 | const layers = Layer.mergeAll( |
| 905 | Layer.succeed(Console.Console, _console), |
| 906 | CliConfigLive, |
| 907 | // Mirror `InvocationLive`: no custom `CliOutput.Formatter` is provided here either |
| 908 | // — `CliOutput.Formatter` is a `Context.Reference` that falls back to v4's |
| 909 | // own `CliOutput.defaultFormatter()`, so `Command.runWith` renders help, |
| 910 | // errors, and `--version` identically to production. |
| 911 | NodeProcessTest, |
| 912 | UpgradeBinaryTest, |
| 913 | ComposioCliUserConfigTest, |
| 914 | ComposioUserContextTest, |
| 915 | ComposioClientSingletonTest, |
| 916 | ComposioSessionRepositoryTest, |
| 917 | TriggersRealtimeTest, |
| 918 | // No runner signals tests; a suite that needs one provides its own controller's service. |
| 919 | ShutdownSignal.Default, |
| 920 | ComposioToolkitsRepositoryTest, |
| 921 | ToolkitSlugCatalogTest, |
| 922 | JsPackageManagerDetector.Default, |
| 923 | ProjectEnvironmentDetector.Default, |
| 924 | CommandRunnerTest(input?.commandRunner), |
| 925 | SetupSkillInstallerTest(input?.setupSkillInstaller), |
| 926 | ToolsExecutorTest, |
| 927 | BunFileSystem.layer, |
| 928 | BunServices.layer, |
| 929 | MockTerminal.layer, |
| 930 | BunPath.layer, |
| 931 | FetchHttpClient.layer, |
| 932 | StdinTest, |
| 933 | TerminalUILayer, |
| 934 | // Recording no-op doubles of the hooks and telemetry sink the invocation runs around a |
| 935 | // command; read their calls with `recordedInvocationCalls`. |
| 936 | InvocationHooksTest, |
| 937 | // `src/commands/index.ts` provides these for real invocations; direct-effect tests that |
| 938 | // never route through the root command still need the "no CLI flag override" default. |
| 939 | cliDebugFlagsLayer(), |
| 940 | Layer.provide( |
| 941 | PendingLoginSession.Default, |
| 942 | Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest) |
| 943 | ), |
| 944 | Layer.provide( |
| 945 | ProjectContext.Default, |
| 946 | Layer.mergeAll(BunFileSystem.layer, NodeOsTest, NodeProcessTest) |
| 947 | ) |
| 948 | ) satisfies RequiredLayer; |
| 949 | |
| 950 | return layers; |
| 951 | }).pipe( |
| 952 | Effect.provideService(References.MinimumLogLevel, 'Debug'), |
| 953 | Effect.scoped, |
| 954 | Layer.unwrap, |
| 955 | // `Layer.provide` only feeds `ConfigProvider` to the layers built above and hides it from |
| 956 | // the resulting layer's output; downstream consumers of `TestLayer` (e.g. command handlers |
| 957 | // reading `Config`/`DEBUG_OVERRIDE_*` at runtime) would fall back to the default |
| 958 | // `ConfigProvider` reference instead of the test's `baseConfigProvider`. `Layer.provideMerge` |
| 959 | // keeps `ConfigProvider` in the output so it stays visible to everything `TestLayer` provides. |
| 960 | Layer.provideMerge( |
| 961 | ConfigProvider.layer( |
| 962 | input?.baseConfigProvider === undefined |
| 963 | ? hostOnlyEnvConfigProvider |
| 964 | : ConfigProvider.orElse(input.baseConfigProvider, hostOnlyEnvConfigProvider) |
| 965 | ) |
| 966 | ) |
| 967 | ); |
| 968 | |
| 969 | // Run @effect/vitest suite with TestLive layer |
| 970 | export const runEffect = |
| 971 | (input?: TestLiveInput) => |
| 972 | <E, A>(self: Effect.Effect<A, E, CliCommand.Environment>): Promise<A> => |
| 973 | Effect.provide(self, TestLayer(input)).pipe(Effect.scoped, Effect.runPromise); |
| 974 | |
| 975 | function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: string }) { |
| 976 | return Effect.gen(function* () { |
| 977 | if (fixture === undefined) { |
| 978 | return; |
| 979 | } |
| 980 | |
| 981 | const fs = yield* FileSystem.FileSystem; |
| 982 | const path = yield* Path.Path; |
| 983 | |
| 984 | const fixtureRoot = yield* path.fromFileUrl(new URL('.', import.meta.url)); |
| 985 | const realFixturePath = path.resolve(fixtureRoot, '..', '..', '__fixtures__', fixture); |
| 986 | const tmpFixturesPath = path.join(tempDir, 'test', '__fixtures__', fixture); |
| 987 | |
| 988 | yield* Effect.logDebug(`Using fixture at: ${tmpFixturesPath}`); |
| 989 | |
| 990 | // Retry the task with a delay between retries and a maximum of 3 retries |
| 991 | const policy = Schedule.addDelay(Schedule.recurs(3), () => Effect.succeed('100 millis')); |
| 992 | |
| 993 | // If all retries fail, run the fallback effect. |
| 994 | // Use tar to skip heavy directories (.venv) that the global setup may have created. |
| 995 | // tar --exclude is POSIX and available on any Linux/macOS without extra packages. |
| 996 | const task = Effect.gen(function* () { |
| 997 | yield* fs.makeDirectory(tmpFixturesPath, { recursive: true }); |
| 998 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 999 | const tarCmd = ChildProcess.make('tar', [ |
| 1000 | '-cf', |
| 1001 | '-', |
| 1002 | '--exclude', |
| 1003 | '.venv', |
| 1004 | '-C', |
| 1005 | realFixturePath, |
| 1006 | '.', |
| 1007 | ]).pipe(ChildProcess.pipeTo(ChildProcess.make('tar', ['-xf', '-', '-C', tmpFixturesPath]))); |
| 1008 | yield* spawner.exitCode(tarCmd); |
| 1009 | }); |
| 1010 | |
| 1011 | const repeated = Effect.retryOrElse(policy, () => |
| 1012 | Effect.die(`Failed to copy fixture to: ${tmpFixturesPath}`) |
| 1013 | ); |
| 1014 | |
| 1015 | yield* repeated(task); |
| 1016 | |
| 1017 | yield* Effect.logDebug(`Copied fixture to: ${tmpFixturesPath}`); |
| 1018 | |
| 1019 | // Break symlinks in node_modules to isolate test from real packages |
| 1020 | const nodeModulesPath = path.join(tmpFixturesPath, 'node_modules'); |
| 1021 | yield* breakSymlinksInNodeModules(fs, path, nodeModulesPath); |
| 1022 | |
| 1023 | return tmpFixturesPath; |
| 1024 | }).pipe(Effect.provide(BunServices.layer)); |
| 1025 | } |
| 1026 | |
| 1027 | /** |
| 1028 | * Breaks symlinks in node_modules to ensure test isolation. |
| 1029 | * - On Unix: Uses `find -type l` for O(1) shell call to detect all symlinks |
| 1030 | * - On Windows: Uses O(n) readLink approach for compatibility |
| 1031 | */ |
| 1032 | function breakSymlinksInNodeModules( |
| 1033 | fs: FileSystem.FileSystem, |
| 1034 | path: Path.Path, |
| 1035 | nodeModulesPath: string |
| 1036 | ): Effect.Effect<void, never, never> { |
| 1037 | // Helper: break a symlink by replacing it with a copy of its target |
| 1038 | const breakSymlink = (symlinkPath: string) => |
| 1039 | Effect.gen(function* () { |
| 1040 | const realPath = yield* fs.realPath(symlinkPath); |
| 1041 | yield* Effect.logDebug(`Breaking symlink: ${symlinkPath} -> ${realPath}`); |
| 1042 | yield* fs.remove(symlinkPath, { recursive: true }); |
| 1043 | yield* fs.copy(realPath, symlinkPath); |
| 1044 | }); |
| 1045 | |
| 1046 | // Unix: Use `find` command for fast symlink detection |
| 1047 | const breakSymlinksUnix = Effect.gen(function* () { |
| 1048 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1049 | const findCmd = ChildProcess.make('find', [ |
| 1050 | nodeModulesPath, |
| 1051 | '-maxdepth', |
| 1052 | '2', |
| 1053 | '-type', |
| 1054 | 'l', |
| 1055 | '-not', |
| 1056 | '-path', |
| 1057 | '*/.*', |
| 1058 | ]); |
| 1059 | const output = yield* spawner.string(findCmd); |
| 1060 | const symlinks = output.trim().split('\n').filter(Boolean); |
| 1061 | |
| 1062 | if (symlinks.length === 0) { |
| 1063 | return; |
| 1064 | } |
| 1065 | |
| 1066 | yield* Effect.logDebug(`Found ${symlinks.length} symlinks to break`); |
| 1067 | yield* Effect.all(symlinks.map(breakSymlink), { concurrency: 'unbounded' }); |
| 1068 | }).pipe(Effect.provide(BunServices.layer)); |
| 1069 | |
| 1070 | // Windows: Use readLink to detect symlinks (O(n) but compatible) |
| 1071 | const breakSymlinksWindows = Effect.gen(function* () { |
| 1072 | const isSymlink = (p: string) => |
| 1073 | fs.readLink(p).pipe( |
| 1074 | Effect.map(() => true), |
| 1075 | Effect.catch(() => Effect.succeed(false)) |
| 1076 | ); |
| 1077 | |
| 1078 | const entries = yield* fs.readDirectory(nodeModulesPath); |
| 1079 | |
| 1080 | yield* Effect.all( |
| 1081 | entries.map(entry => { |
| 1082 | if (entry.startsWith('.')) { |
| 1083 | return Effect.void; |
| 1084 | } |
| 1085 | |
| 1086 | const entryPath = path.join(nodeModulesPath, entry); |
| 1087 | return Effect.gen(function* () { |
| 1088 | const isLink = yield* isSymlink(entryPath); |
| 1089 | |
| 1090 | if (isLink) { |
| 1091 | yield* breakSymlink(entryPath); |
| 1092 | } else if (entry.startsWith('@')) { |
| 1093 | const scopedEntries = yield* fs.readDirectory(entryPath); |
| 1094 | yield* Effect.all( |
| 1095 | scopedEntries.map(scopedEntry => { |
| 1096 | const scopedPath = path.join(entryPath, scopedEntry); |
| 1097 | return Effect.gen(function* () { |
| 1098 | const isScopedLink = yield* isSymlink(scopedPath); |
| 1099 | if (isScopedLink) { |
| 1100 | yield* breakSymlink(scopedPath); |
| 1101 | } |
| 1102 | }); |
| 1103 | }), |
| 1104 | { concurrency: 'unbounded' } |
| 1105 | ); |
| 1106 | } |
| 1107 | }); |
| 1108 | }), |
| 1109 | { concurrency: 'unbounded' } |
| 1110 | ); |
| 1111 | }); |
| 1112 | |
| 1113 | return Effect.gen(function* () { |
| 1114 | const exists = yield* fs.exists(nodeModulesPath); |
| 1115 | if (!exists) { |
| 1116 | return; |
| 1117 | } |
| 1118 | |
| 1119 | // Some fixtures can contain node_modules as a symlink (often broken in temp copies). |
| 1120 | // Normalize it first so tests can safely create nested paths like node_modules/@scope/pkg. |
| 1121 | const nodeModulesLink = yield* fs.readLink(nodeModulesPath).pipe( |
| 1122 | Effect.map(() => true), |
| 1123 | Effect.catch(() => Effect.succeed(false)) |
| 1124 | ); |
| 1125 | |
| 1126 | if (nodeModulesLink) { |
| 1127 | yield* fs.remove(nodeModulesPath, { recursive: true }).pipe(Effect.catch(() => Effect.void)); |
| 1128 | yield* fs |
| 1129 | .makeDirectory(nodeModulesPath, { recursive: true }) |
| 1130 | .pipe(Effect.catch(() => Effect.void)); |
| 1131 | } |
| 1132 | |
| 1133 | const isWindows = process.platform === 'win32'; |
| 1134 | |
| 1135 | if (isWindows) { |
| 1136 | yield* breakSymlinksWindows; |
| 1137 | } else { |
| 1138 | yield* breakSymlinksUnix; |
| 1139 | } |
| 1140 | }).pipe(Effect.catch(() => Effect.void)); |
| 1141 | } |
| 1142 | |
| 1143 | function setupComposioSessionRepository() { |
| 1144 | return Effect.gen(function* () { |
| 1145 | const now = yield* DateTime.now; |
| 1146 | const sessionId = 'te00st11-d0c4-4efa-8117-c638886063e0'; |
| 1147 | const sessionCode = '001122'; |
| 1148 | const expiresAt = DateTime.add(now, { minutes: 10 }); |
| 1149 | |
| 1150 | const accountName = 'test-name'; |
| 1151 | const accountId = 'test-id'; |
| 1152 | const accountEmail = 'test.name@gmail.com'; |
| 1153 | |
| 1154 | const account = { |
| 1155 | name: accountName, |
| 1156 | id: accountId, |
| 1157 | email: accountEmail, |
| 1158 | }; |
| 1159 | |
| 1160 | const composioSessionRepositoryTest = ComposioSessionRepository.of({ |
| 1161 | createSession: () => |
| 1162 | Effect.succeed({ |
| 1163 | id: sessionId, |
| 1164 | code: sessionCode, |
| 1165 | expiresAt, |
| 1166 | status: 'pending', |
| 1167 | }), |
| 1168 | getSession: () => |
| 1169 | Effect.succeed({ |
| 1170 | id: sessionId, |
| 1171 | code: sessionCode, |
| 1172 | expiresAt, |
| 1173 | status: 'pending', |
| 1174 | api_key: null, |
| 1175 | }), |
| 1176 | getRealtimeCredentials: () => |
| 1177 | Effect.succeed({ |
| 1178 | project_id: 'proj_test', |
| 1179 | pusher_key: 'pusher_test_key', |
| 1180 | pusher_cluster: 'mt1', |
| 1181 | }), |
| 1182 | authRealtimeChannel: () => |
| 1183 | Effect.succeed({ |
| 1184 | auth: 'mock:auth', |
| 1185 | channel_data: undefined, |
| 1186 | }), |
| 1187 | }); |
| 1188 | const ComposioSessionRepositoryTest = Layer.succeed( |
| 1189 | ComposioSessionRepository, |
| 1190 | composioSessionRepositoryTest |
| 1191 | ); |
| 1192 | |
| 1193 | return ComposioSessionRepositoryTest; |
| 1194 | }); |
| 1195 | } |