Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 06:00 UTC
| 1 | import { Auth, make, type ComposioClientShape } from '@composio/client/effect'; |
| 2 | import * as BunFileSystem from '@effect/platform-bun/BunFileSystem'; |
| 3 | import * as BunPath from '@effect/platform-bun/BunPath'; |
| 4 | import { describe, expect, it } from '@effect/vitest'; |
| 5 | import { ConfigProvider, Console, Effect, Fiber, Layer, Option, Stream } from 'effect'; |
| 6 | import { HttpClient } from 'effect/http'; |
| 7 | import { TestClock } from 'effect/testing'; |
| 8 | import * as tempy from 'tempy'; |
| 9 | import { |
| 10 | handleLegacyAuthConfigLink, |
| 11 | handleListConnectedAccounts, |
| 12 | handleToolRouterLink, |
| 13 | runConnectedAccountsLink, |
| 14 | type ConnectedAccountsLinkParams, |
| 15 | } from 'src/commands/connected-accounts/link/connected-accounts.link.handler'; |
| 16 | import { |
| 17 | AUTH_CONFIG_SCOPE_MESSAGE, |
| 18 | BROWSE_AUTH_CONFIGS_HINT, |
| 19 | BROWSE_TOOLKITS_HINT, |
| 20 | INCOMPLETE_LINK_RESPONSE_MESSAGE, |
| 21 | LIST_REQUIRES_TOOLKIT_MESSAGE, |
| 22 | LIST_WITH_AUTH_CONFIG_MESSAGE, |
| 23 | ROOT_AUTH_CONFIG_MESSAGE, |
| 24 | TOOLKIT_AND_AUTH_CONFIG_MESSAGE, |
| 25 | formatNonInteractiveAuthorizationInstructions, |
| 26 | missingArgumentMessage, |
| 27 | } from 'src/commands/connected-accounts/link/connected-accounts.link.format'; |
| 28 | import { CommandSurface, MissingActingUserError } from 'src/commands/surface'; |
| 29 | import { CliUserConfig } from 'src/models/cli-user-config'; |
| 30 | import type { ConnectedAccountItem } from 'src/models/connected-accounts'; |
| 31 | import type { ProjectKeys } from 'src/models/project-keys'; |
| 32 | import { ComposioCliUserConfig } from 'src/services/cli-user-config'; |
| 33 | import { ComposioClientSingleton } from 'src/services/composio-clients'; |
| 34 | import { NodeOs } from 'src/services/node-os'; |
| 35 | import { NodeProcess } from 'src/services/node-process'; |
| 36 | import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui'; |
| 37 | import { ProjectContext } from 'src/services/project-context'; |
| 38 | import { ComposioUserContext } from 'src/services/user-context'; |
| 39 | import { ConnectedAccountsTest, MockConsole } from 'test/__utils__'; |
| 40 | import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts'; |
| 41 | import { |
| 42 | mockConnectedAccountResources, |
| 43 | resolveConnectedAccountsTestData, |
| 44 | } from 'test/__utils__/layers/connected-accounts'; |
| 45 | import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider'; |
| 46 | import { makeOrgProject } from 'test/__utils__/models/account'; |
| 47 | import { exitCodeOf } from 'test/__utils__/exit-code'; |
| 48 | import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui'; |
| 49 | import { TerminalUITest, terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test'; |
| 50 | import open from 'open'; |
| 51 | import { afterEach, vi } from 'vitest'; |
| 52 | |
| 53 | vi.mock('open', () => ({ |
| 54 | default: vi.fn(async () => undefined), |
| 55 | })); |
| 56 | |
| 57 | afterEach(() => { |
| 58 | vi.clearAllMocks(); |
| 59 | }); |
| 60 | |
| 61 | // The consumer project the mock client resolves for `org_test`, and its user. |
| 62 | const CONSUMER_USER_ID = 'consumer-user-org_test'; |
| 63 | const DEVELOPER_PROJECT = makeOrgProject({ id: 'proj_named', name: 'named', orgId: 'org_test' }); |
| 64 | |
| 65 | const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({ |
| 66 | id: 'con_existing', |
| 67 | // `word_id` precedes `alias` to match the model's field order, which is the order the |
| 68 | // decoded items carry into the `--list` payload asserted as a raw string below. |
| 69 | word_id: 'castle', |
| 70 | alias: null, |
| 71 | status: 'ACTIVE', |
| 72 | status_reason: null, |
| 73 | is_disabled: false, |
| 74 | user_id: CONSUMER_USER_ID, |
| 75 | toolkit: { slug: 'gmail' }, |
| 76 | auth_config: { |
| 77 | id: 'ac_gmail', |
| 78 | auth_scheme: 'OAUTH2', |
| 79 | is_composio_managed: true, |
| 80 | is_disabled: false, |
| 81 | }, |
| 82 | created_at: '2026-01-01T00:00:00Z', |
| 83 | updated_at: '2026-01-01T00:00:00Z', |
| 84 | test_request_endpoint: '', |
| 85 | ...overrides, |
| 86 | }); |
| 87 | |
| 88 | const directory = (testUserId: Option.Option<string>): Option.Option<ProjectKeys> => |
| 89 | Option.some({ |
| 90 | orgId: 'org_test', |
| 91 | projectId: 'proj_directory', |
| 92 | projectName: Option.some('directory'), |
| 93 | orgName: Option.none(), |
| 94 | email: Option.none(), |
| 95 | testUserId, |
| 96 | }); |
| 97 | |
| 98 | const params = ( |
| 99 | overrides: Partial<ConnectedAccountsLinkParams> = {} |
| 100 | ): ConnectedAccountsLinkParams => ({ |
| 101 | toolkit: Option.none(), |
| 102 | authConfig: Option.none(), |
| 103 | noWait: true, |
| 104 | noBrowser: true, |
| 105 | alias: Option.none(), |
| 106 | list: false, |
| 107 | ...overrides, |
| 108 | }); |
| 109 | |
| 110 | interface LinkFixture { |
| 111 | readonly surface?: Layer.Layer<CommandSurface>; |
| 112 | readonly accounts?: ReadonlyArray<ConnectedAccountItem>; |
| 113 | /** The `consumer_user_id` the consumer project resolves with; see `AccountTestData`. */ |
| 114 | readonly consumerUserId?: string | null; |
| 115 | readonly directoryProject?: Option.Option<ProjectKeys>; |
| 116 | readonly globalTestUserId?: Option.Option<string>; |
| 117 | /** Replaces the `link.create` answer, e.g. to fail it. */ |
| 118 | readonly legacyLinkCreate?: () => Effect.Effect<unknown, unknown>; |
| 119 | /** Replaces the `toolRouter.session.link` answer, e.g. to fail it or drop a field. */ |
| 120 | readonly toolRouterLink?: () => Effect.Effect<unknown, unknown>; |
| 121 | /** Makes `connectedAccounts.list` fail, to prove the alias-hints fetch is auxiliary. */ |
| 122 | readonly connectedAccountsListFails?: boolean; |
| 123 | /** Makes the first N `connectedAccounts.retrieve` calls fail, for the polling retries. */ |
| 124 | readonly retrieveFailsFirst?: number; |
| 125 | /** Runs before every `connectedAccounts.retrieve`, i.e. at every poll while the link waits. */ |
| 126 | readonly onRetrieve?: () => void; |
| 127 | /** Replaces the headless test terminal, e.g. with `redirectedTerminalUI`. */ |
| 128 | readonly terminal?: Layer.Layer<TerminalUI>; |
| 129 | } |
| 130 | |
| 131 | /** A request that creates a link, as the mock client saw it. */ |
| 132 | interface LinkRequest { |
| 133 | readonly operation: 'link.create' | 'toolRouter.session.link'; |
| 134 | readonly params: unknown; |
| 135 | } |
| 136 | |
| 137 | // A resource neither layer below shadows reaches this transport and dies with its URL. |
| 138 | const baseClient = make( |
| 139 | { |
| 140 | auth: Auth.project('test'), |
| 141 | baseURL: 'https://mock.invalid', |
| 142 | }, |
| 143 | HttpClient.make(request => |
| 144 | Effect.die(new Error(`unexpected network call from the link handler test: ${request.url}`)) |
| 145 | ) |
| 146 | ); |
| 147 | |
| 148 | const cliUserConfig = ComposioCliUserConfig.of({ |
| 149 | data: { |
| 150 | channel: 'beta', |
| 151 | developerModeEnabled: true, |
| 152 | developerDangerousCommandsEnabled: false, |
| 153 | experimentalFeatures: {}, |
| 154 | artifactDirectory: undefined, |
| 155 | security: 'auto', |
| 156 | }, |
| 157 | raw: CliUserConfig.make({ |
| 158 | developer: { enabled: true, destructiveActions: false }, |
| 159 | experimentalFeatures: {}, |
| 160 | artifactDirectory: Option.none(), |
| 161 | security: 'auto', |
| 162 | }), |
| 163 | channel: 'beta', |
| 164 | isDevModeEnabled: () => true, |
| 165 | areDeveloperDangerousCommandsEnabled: () => false, |
| 166 | isExperimentalFeatureEnabled: () => true, |
| 167 | update: () => Effect.void, |
| 168 | }); |
| 169 | |
| 170 | /** |
| 171 | * What a link handler needs and nothing more: the account and connected-account families of |
| 172 | * the mock client (`test/__utils__/layers`), a Tool Router session that answers, and doubles |
| 173 | * for the user, the directory, and the platform. `requests` records every link request. |
| 174 | */ |
| 175 | const linkHandlerTest = (fixture: LinkFixture = {}) => { |
| 176 | const requests: Array<LinkRequest> = []; |
| 177 | /** The `user_id` of every Tool Router session the handler created. */ |
| 178 | const sessionUsers: Array<string> = []; |
| 179 | const connectedAccounts = mockConnectedAccountResources( |
| 180 | resolveConnectedAccountsTestData({ items: [...(fixture.accounts ?? [])] }) |
| 181 | ); |
| 182 | let retrieveAttempts = 0; |
| 183 | const connectedAccountsResources = { |
| 184 | ...connectedAccounts, |
| 185 | connectedAccounts: { |
| 186 | ...connectedAccounts.connectedAccounts, |
| 187 | list: fixture.connectedAccountsListFails |
| 188 | ? () => Effect.fail(new Error('connectedAccounts.list is down')) |
| 189 | : connectedAccounts.connectedAccounts.list, |
| 190 | listStream: fixture.connectedAccountsListFails |
| 191 | ? () => Stream.fail(new Error('connectedAccounts.list is down')) |
| 192 | : connectedAccounts.connectedAccounts.listStream, |
| 193 | retrieve: (nanoid: string) => { |
| 194 | fixture.onRetrieve?.(); |
| 195 | retrieveAttempts += 1; |
| 196 | return retrieveAttempts <= (fixture.retrieveFailsFirst ?? 0) |
| 197 | ? Effect.fail(new Error(`transient retrieve failure ${retrieveAttempts}`)) |
| 198 | : connectedAccounts.connectedAccounts.retrieve(nanoid); |
| 199 | }, |
| 200 | }, |
| 201 | }; |
| 202 | const record = (operation: LinkRequest['operation'], requestParams: unknown) => |
| 203 | Effect.sync(() => requests.push({ operation, params: requestParams })); |
| 204 | const clientFor = (scope: MockRequestScope): ComposioClientShape => |
| 205 | // The shadows answer only the fields the handlers read, so they do not satisfy the |
| 206 | // client's full response types; `test-layer.ts` shadows its mock client the same way. |
| 207 | ({ |
| 208 | ...baseClient, |
| 209 | ...mockAccountResources( |
| 210 | { projects: [DEVELOPER_PROJECT], consumerUserId: fixture.consumerUserId }, |
| 211 | scope |
| 212 | ), |
| 213 | ...connectedAccountsResources, |
| 214 | link: { |
| 215 | create: (linkParams: { auth_config_id: string; user_id: string }) => |
| 216 | record('link.create', linkParams).pipe( |
| 217 | Effect.andThen( |
| 218 | fixture.legacyLinkCreate |
| 219 | ? fixture.legacyLinkCreate() |
| 220 | : connectedAccounts.link.create(linkParams) |
| 221 | ) |
| 222 | ), |
| 223 | }, |
| 224 | toolRouter: { |
| 225 | ...baseClient.toolRouter, |
| 226 | session: { |
| 227 | ...baseClient.toolRouter.session, |
| 228 | create: (sessionParams: { user_id: string }) => |
| 229 | Effect.sync(() => sessionUsers.push(sessionParams.user_id)).pipe( |
| 230 | Effect.as({ session_id: 'trs_handler_test' }) |
| 231 | ), |
| 232 | link: (sessionId: string, linkParams: { toolkit: string; alias?: string }) => |
| 233 | record('toolRouter.session.link', { sessionId, ...linkParams }).pipe( |
| 234 | Effect.andThen( |
| 235 | fixture.toolRouterLink |
| 236 | ? fixture.toolRouterLink() |
| 237 | : Effect.succeed({ |
| 238 | connected_account_id: 'con_new', |
| 239 | link_token: 'lt_test', |
| 240 | redirect_url: 'https://app.composio.dev/link?token=lt_test', |
| 241 | }) |
| 242 | ) |
| 243 | ), |
| 244 | }, |
| 245 | }, |
| 246 | }) as unknown as ComposioClientShape; |
| 247 | |
| 248 | const dir = tempy.temporaryDirectory({ prefix: 'link-handler' }); |
| 249 | const layer = Layer.mergeAll( |
| 250 | Layer.effect(Console.Console, MockConsole.make), |
| 251 | fixture.terminal ?? TerminalUITest, |
| 252 | fixture.surface ?? CommandSurface.root, |
| 253 | Layer.succeed( |
| 254 | ComposioUserContext, |
| 255 | ComposioUserContext.of({ |
| 256 | data: { |
| 257 | apiKey: Option.some('uak_test'), |
| 258 | baseURL: 'https://mock.invalid', |
| 259 | webURL: 'https://platform.mock.invalid', |
| 260 | orgId: Option.some('org_test'), |
| 261 | projectId: Option.none(), |
| 262 | testUserId: fixture.globalTestUserId ?? Option.none(), |
| 263 | }, |
| 264 | backendMismatch: Option.none(), |
| 265 | isLoggedIn: () => true, |
| 266 | logout: Effect.void, |
| 267 | login: () => Effect.void, |
| 268 | update: () => Effect.void, |
| 269 | }) |
| 270 | ), |
| 271 | Layer.succeed( |
| 272 | ProjectContext, |
| 273 | ProjectContext.of({ resolve: Effect.succeed(fixture.directoryProject ?? Option.none()) }) |
| 274 | ), |
| 275 | Layer.succeed( |
| 276 | ComposioClientSingleton, |
| 277 | ComposioClientSingleton.of({ |
| 278 | get: () => Effect.succeed(clientFor({})), |
| 279 | getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)), |
| 280 | getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }), |
| 281 | }) |
| 282 | ), |
| 283 | ConnectedAccountsTest(), |
| 284 | BunFileSystem.layer, |
| 285 | BunPath.layer, |
| 286 | Layer.succeed( |
| 287 | NodeOs, |
| 288 | NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' }) |
| 289 | ), |
| 290 | Layer.succeed( |
| 291 | NodeProcess, |
| 292 | NodeProcess.of({ cwd: dir, execPath: `${dir}/composio`, platform: 'darwin', arch: 'arm64' }) |
| 293 | ), |
| 294 | Layer.succeed(ComposioCliUserConfig, cliUserConfig), |
| 295 | ConfigProvider.layer(hostOnlyEnvConfigProvider) |
| 296 | ); |
| 297 | return { layer, requests, sessionUsers }; |
| 298 | }; |
| 299 | |
| 300 | const lines = MockConsole.getLines({ stripAnsi: true }); |
| 301 | |
| 302 | /** Runs `handler` to its exit, then reads the lines it printed. */ |
| 303 | const exitAndLines = <A, E, R>(handler: Effect.Effect<A, E, R>) => |
| 304 | Effect.gen(function* () { |
| 305 | const exit = yield* Effect.exit(handler); |
| 306 | return { exit, output: yield* lines }; |
| 307 | }); |
| 308 | |
| 309 | /** The command's JSON result: `ui.output` prints it as the last console line. */ |
| 310 | const lastJson = lines.pipe(Effect.map(all => JSON.parse(String(all.at(-1))) as unknown)); |
| 311 | |
| 312 | /** The payload as `link` prints it: a `toStdoutJson` string, key order included. */ |
| 313 | const toJson = (payload: object) => JSON.stringify(payload, null, 2); |
| 314 | |
| 315 | /** The `link.create` answer of the mock connected-account resources. */ |
| 316 | const LEGACY_LINK_TARGET = { |
| 317 | connected_account_id: 'con_test_link', |
| 318 | redirect_url: 'https://app.composio.dev/link?token=lt_test_token', |
| 319 | } as const; |
| 320 | |
| 321 | /** The `toolRouter.session.link` answer of the handler test's client double. */ |
| 322 | const TOOL_ROUTER_LINK_TARGET = { |
| 323 | connected_account_id: 'con_new', |
| 324 | redirect_url: 'https://app.composio.dev/link?token=lt_test', |
| 325 | } as const; |
| 326 | |
| 327 | /** The pending payload of a legacy link, byte for byte. */ |
| 328 | const legacyPendingJson = () => |
| 329 | toJson({ |
| 330 | status: 'pending', |
| 331 | message: 'Complete authorization by opening the URL', |
| 332 | connected_account_id: LEGACY_LINK_TARGET.connected_account_id, |
| 333 | redirect_url: LEGACY_LINK_TARGET.redirect_url, |
| 334 | project_type: 'DEVELOPER', |
| 335 | }); |
| 336 | |
| 337 | /** The pending payload of a Tool Router link, byte for byte. */ |
| 338 | const toolRouterPendingJson = (projectType: 'CONSUMER' | 'DEVELOPER' = 'CONSUMER') => |
| 339 | toJson({ |
| 340 | status: 'pending', |
| 341 | message: 'Complete authorization by opening the URL', |
| 342 | connected_account_id: TOOL_ROUTER_LINK_TARGET.connected_account_id, |
| 343 | redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url, |
| 344 | toolkit: 'gmail', |
| 345 | project_type: projectType, |
| 346 | }); |
| 347 | |
| 348 | /** The payload once polling saw `con_new` ACTIVE, byte for byte. */ |
| 349 | const toolRouterActiveJson = () => |
| 350 | toJson({ |
| 351 | status: 'success', |
| 352 | message: 'Connected account "con_new" is now ACTIVE (toolkit: gmail).', |
| 353 | connected_account_id: 'con_new', |
| 354 | toolkit: 'gmail', |
| 355 | redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url, |
| 356 | }); |
| 357 | |
| 358 | /** |
| 359 | * Runs an effect whose context is already provided on the test clock, with a pump fiber that |
| 360 | * keeps advancing the clock while it runs: every pump iteration lets the effect reach its next |
| 361 | * scheduled sleep, then moves the clock past it. Answers what the effect answered once done. |
| 362 | */ |
| 363 | const runWithAdvancingClock = <A, E>(effect: Effect.Effect<A, E>) => |
| 364 | Effect.gen(function* () { |
| 365 | const run = yield* Effect.forkChild(effect); |
| 366 | const pump = yield* Effect.forkChild( |
| 367 | Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('10 seconds'))) |
| 368 | ); |
| 369 | const result = yield* Fiber.join(run); |
| 370 | yield* Fiber.interrupt(pump); |
| 371 | return result; |
| 372 | }); |
| 373 | |
| 374 | /** The headless test terminal with stderr a TTY, so the link's decoration renders. */ |
| 375 | const decoratingTerminal = Layer.succeed( |
| 376 | TerminalUI, |
| 377 | TerminalUI.of({ |
| 378 | ...terminalUITestImpl, |
| 379 | capabilities: Effect.succeed( |
| 380 | getTerminalCapabilities({ |
| 381 | stdin: { isTTY: false }, |
| 382 | stdout: { isTTY: false }, |
| 383 | stderr: { isTTY: true }, |
| 384 | }) |
| 385 | ), |
| 386 | }) |
| 387 | ); |
| 388 | |
| 389 | const devSurface = (flags: { userId?: string; projectName?: string } = {}) => |
| 390 | CommandSurface.dev({ |
| 391 | userId: Option.fromUndefinedOr(flags.userId), |
| 392 | projectName: Option.fromUndefinedOr(flags.projectName), |
| 393 | }); |
| 394 | |
| 395 | describe('connected-accounts link handler: runConnectedAccountsLink', () => { |
| 396 | it.effect.each([ |
| 397 | { |
| 398 | name: 'a blank --alias, before any other check', |
| 399 | surface: CommandSurface.root, |
| 400 | input: { alias: Option.some(' '), authConfig: Option.some('ac_1') }, |
| 401 | option: '--alias', |
| 402 | message: '`--alias` cannot be empty.', |
| 403 | command: 'link', |
| 404 | }, |
| 405 | { |
| 406 | name: '--auth-config on the root tree, which is consumer-only', |
| 407 | surface: CommandSurface.root, |
| 408 | input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') }, |
| 409 | option: '--auth-config', |
| 410 | message: ROOT_AUTH_CONFIG_MESSAGE, |
| 411 | command: 'link', |
| 412 | }, |
| 413 | { |
| 414 | name: 'a toolkit and --auth-config under dev', |
| 415 | surface: devSurface(), |
| 416 | input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') }, |
| 417 | option: '--auth-config', |
| 418 | message: TOOLKIT_AND_AUTH_CONFIG_MESSAGE, |
| 419 | command: 'dev connected-accounts link', |
| 420 | }, |
| 421 | { |
| 422 | name: 'neither a toolkit nor --auth-config on the root tree', |
| 423 | surface: CommandSurface.root, |
| 424 | input: {}, |
| 425 | option: '<toolkit>', |
| 426 | message: missingArgumentMessage('root'), |
| 427 | command: 'link', |
| 428 | }, |
| 429 | { |
| 430 | name: 'neither a toolkit nor --auth-config under dev', |
| 431 | surface: devSurface(), |
| 432 | input: {}, |
| 433 | option: '<toolkit>', |
| 434 | message: missingArgumentMessage('dev'), |
| 435 | command: 'dev connected-accounts link', |
| 436 | }, |
| 437 | ])('[Given] $name [Then] fails with a CommandInputError and sends nothing', c => |
| 438 | Effect.gen(function* () { |
| 439 | const { layer, requests } = linkHandlerTest({ surface: c.surface }); |
| 440 | const error = yield* runConnectedAccountsLink(params(c.input)).pipe( |
| 441 | Effect.flip, |
| 442 | Effect.provide(layer) |
| 443 | ); |
| 444 | |
| 445 | expect(error).toMatchObject({ |
| 446 | _tag: 'commands/CommandInputError', |
| 447 | command: c.command, |
| 448 | option: c.option, |
| 449 | message: c.message, |
| 450 | }); |
| 451 | expect(requests).toEqual([]); |
| 452 | }) |
| 453 | ); |
| 454 | |
| 455 | it.effect.each([ |
| 456 | { flow: 'list', input: { toolkit: Option.some('gmail'), list: true } }, |
| 457 | { flow: 'legacy', input: { authConfig: Option.some('ac_gmail') } }, |
| 458 | { flow: 'tool-router', input: { toolkit: Option.some('gmail') } }, |
| 459 | ])('[Given] the flags select the $flow flow [Then] it runs that flow', c => |
| 460 | Effect.gen(function* () { |
| 461 | // On the dev tree every flow acts as --user-id on the directory's developer project. |
| 462 | const fixtureAccount = account({ alias: 'work', user_id: 'user_1' }); |
| 463 | const { layer } = linkHandlerTest({ |
| 464 | surface: devSurface({ userId: 'user_1' }), |
| 465 | accounts: [fixtureAccount], |
| 466 | directoryProject: directory(Option.none()), |
| 467 | }); |
| 468 | const lastLine = yield* runConnectedAccountsLink( |
| 469 | params({ ...c.input, alias: Option.some('second') }) |
| 470 | ).pipe( |
| 471 | Effect.andThen(lines), |
| 472 | Effect.map(all => String(all.at(-1))), |
| 473 | Effect.provide(layer) |
| 474 | ); |
| 475 | |
| 476 | // The raw string, not JSON.parse, so a key reorder fails here. |
| 477 | expect(lastLine).toBe( |
| 478 | c.flow === 'list' |
| 479 | ? toJson({ toolkit: 'gmail', total: 1, items: [fixtureAccount] }) |
| 480 | : c.flow === 'legacy' |
| 481 | ? legacyPendingJson() |
| 482 | : toolRouterPendingJson('DEVELOPER') |
| 483 | ); |
| 484 | }) |
| 485 | ); |
| 486 | }); |
| 487 | |
| 488 | describe('connected-accounts link handler: handleListConnectedAccounts', () => { |
| 489 | it.effect.each([ |
| 490 | { |
| 491 | name: 'no toolkit', |
| 492 | input: { list: true, authConfig: Option.some('ac_1') }, |
| 493 | message: LIST_REQUIRES_TOOLKIT_MESSAGE, |
| 494 | }, |
| 495 | { |
| 496 | name: '--auth-config', |
| 497 | input: { list: true, toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') }, |
| 498 | message: LIST_WITH_AUTH_CONFIG_MESSAGE, |
| 499 | }, |
| 500 | ])('[Given] $name [Then] fails with a CommandInputError saying why --list cannot run', c => |
| 501 | Effect.gen(function* () { |
| 502 | const { layer, requests } = linkHandlerTest(); |
| 503 | const error = yield* handleListConnectedAccounts(params(c.input)).pipe( |
| 504 | Effect.flip, |
| 505 | Effect.provide(layer) |
| 506 | ); |
| 507 | |
| 508 | expect(error).toMatchObject({ |
| 509 | _tag: 'commands/CommandInputError', |
| 510 | command: 'link', |
| 511 | option: '--list', |
| 512 | message: c.message, |
| 513 | }); |
| 514 | expect(requests).toEqual([]); |
| 515 | }) |
| 516 | ); |
| 517 | |
| 518 | it.effect('[Given] the consumer project [Then] lists only its user’s active accounts', () => |
| 519 | Effect.gen(function* () { |
| 520 | const mine = account(); |
| 521 | const { layer } = linkHandlerTest({ |
| 522 | accounts: [ |
| 523 | mine, |
| 524 | account({ id: 'con_other_user', user_id: 'someone-else' }), |
| 525 | account({ id: 'con_inactive', status: 'INITIATED' }), |
| 526 | account({ id: 'con_other_toolkit', toolkit: { slug: 'slack' } }), |
| 527 | ], |
| 528 | }); |
| 529 | const result = yield* handleListConnectedAccounts( |
| 530 | params({ toolkit: Option.some('gmail'), list: true }) |
| 531 | ).pipe(Effect.andThen(lastJson), Effect.provide(layer)); |
| 532 | |
| 533 | expect(result).toStrictEqual({ toolkit: 'gmail', total: 1, items: [mine] }); |
| 534 | }) |
| 535 | ); |
| 536 | |
| 537 | it.effect('[Given] no active account [Then] warns and prints an empty list', () => |
| 538 | Effect.gen(function* () { |
| 539 | const { layer } = linkHandlerTest(); |
| 540 | const output = yield* handleListConnectedAccounts( |
| 541 | params({ toolkit: Option.some('gmail'), list: true }) |
| 542 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 543 | |
| 544 | expect(output.at(-2)).toBe('No active connected accounts found for "gmail".'); |
| 545 | // The empty case lists `items` before `total`; this pins that order. |
| 546 | expect(String(output.at(-1))).toBe(toJson({ toolkit: 'gmail', items: [], total: 0 })); |
| 547 | }) |
| 548 | ); |
| 549 | |
| 550 | it.effect.each([ |
| 551 | { |
| 552 | name: '--user-id', |
| 553 | surface: devSurface({ projectName: 'named', userId: 'user_flag' }), |
| 554 | directoryProject: directory(Option.some('user_directory')), |
| 555 | expectedUser: 'user_flag', |
| 556 | }, |
| 557 | { |
| 558 | name: 'the directory’s test user, for the directory’s own project', |
| 559 | surface: devSurface({ projectName: 'named' }), |
| 560 | directoryProject: Option.map(directory(Option.some('user_directory')), keys => ({ |
| 561 | ...keys, |
| 562 | projectId: DEVELOPER_PROJECT.id, |
| 563 | })), |
| 564 | expectedUser: 'user_directory', |
| 565 | }, |
| 566 | { |
| 567 | name: 'the global test user, for a project other than the directory’s', |
| 568 | surface: devSurface({ projectName: 'named' }), |
| 569 | directoryProject: directory(Option.some('user_directory')), |
| 570 | expectedUser: 'user_global', |
| 571 | }, |
| 572 | ])('[Given] dev --project-name and $name [Then] lists that user’s accounts', c => |
| 573 | Effect.gen(function* () { |
| 574 | const { layer } = linkHandlerTest({ |
| 575 | surface: c.surface, |
| 576 | directoryProject: c.directoryProject, |
| 577 | globalTestUserId: Option.some('user_global'), |
| 578 | accounts: ['user_flag', 'user_directory', 'user_global'].map(userId => |
| 579 | account({ id: `con_${userId}`, user_id: userId }) |
| 580 | ), |
| 581 | }); |
| 582 | const result = yield* handleListConnectedAccounts( |
| 583 | params({ toolkit: Option.some('gmail'), list: true }) |
| 584 | ).pipe(Effect.andThen(lastJson), Effect.provide(layer)); |
| 585 | |
| 586 | expect(result).toMatchObject({ total: 1, items: [{ user_id: c.expectedUser }] }); |
| 587 | }) |
| 588 | ); |
| 589 | |
| 590 | it.effect.each([ |
| 591 | { name: '--user-id', userId: 'user_flag', expectedUser: 'user_flag' }, |
| 592 | { name: 'the directory’s test user', userId: undefined, expectedUser: 'user_directory' }, |
| 593 | ])( |
| 594 | '[Given] dev without --project-name and $name [Then] lists that user’s accounts in the directory’s project', |
| 595 | c => |
| 596 | Effect.gen(function* () { |
| 597 | const { layer } = linkHandlerTest({ |
| 598 | surface: devSurface({ userId: c.userId }), |
| 599 | directoryProject: directory(Option.some('user_directory')), |
| 600 | accounts: [CONSUMER_USER_ID, 'user_flag', 'user_directory'].map(userId => |
| 601 | account({ id: `con_${userId}`, user_id: userId }) |
| 602 | ), |
| 603 | }); |
| 604 | const result = yield* handleListConnectedAccounts( |
| 605 | params({ toolkit: Option.some('gmail'), list: true }) |
| 606 | ).pipe(Effect.andThen(lastJson), Effect.provide(layer)); |
| 607 | |
| 608 | expect(result).toMatchObject({ total: 1, items: [{ user_id: c.expectedUser }] }); |
| 609 | }) |
| 610 | ); |
| 611 | |
| 612 | it.effect( |
| 613 | '[Given] dev without --project-name outside a developer project [Then] fails with ProjectResolutionError', |
| 614 | () => |
| 615 | Effect.gen(function* () { |
| 616 | const { layer, requests } = linkHandlerTest({ |
| 617 | surface: devSurface({ userId: 'user_flag' }), |
| 618 | }); |
| 619 | const error = yield* handleListConnectedAccounts( |
| 620 | params({ toolkit: Option.some('gmail'), list: true }) |
| 621 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 622 | |
| 623 | expect(error).toMatchObject({ |
| 624 | _tag: 'services/ProjectResolutionError', |
| 625 | reason: 'missing_developer_project', |
| 626 | }); |
| 627 | expect(requests).toEqual([]); |
| 628 | }) |
| 629 | ); |
| 630 | |
| 631 | it.effect('[Given] the list request fails [Then] fails with the request error', () => |
| 632 | Effect.gen(function* () { |
| 633 | const { layer } = linkHandlerTest({ connectedAccountsListFails: true }); |
| 634 | const error = yield* handleListConnectedAccounts( |
| 635 | params({ toolkit: Option.some('gmail'), list: true }) |
| 636 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 637 | |
| 638 | expect(error).toMatchObject({ |
| 639 | _tag: 'commands/ConnectedAccountsRequestError', |
| 640 | message: 'Failed to list connected accounts for "gmail".', |
| 641 | }); |
| 642 | }) |
| 643 | ); |
| 644 | |
| 645 | it.effect.each([ |
| 646 | { |
| 647 | tree: 'root', |
| 648 | surface: CommandSurface.root, |
| 649 | message: 'Missing consumer user id. Run `composio login` and try again.', |
| 650 | }, |
| 651 | { |
| 652 | tree: 'dev', |
| 653 | surface: devSurface(), |
| 654 | message: |
| 655 | 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.', |
| 656 | }, |
| 657 | ])('[Given] no user on the $tree tree [Then] fails with that tree’s message', c => |
| 658 | Effect.gen(function* () { |
| 659 | const { layer } = linkHandlerTest({ |
| 660 | surface: c.surface, |
| 661 | directoryProject: directory(Option.none()), |
| 662 | consumerUserId: '', |
| 663 | }); |
| 664 | const error = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe( |
| 665 | Effect.flip, |
| 666 | Effect.provide(layer) |
| 667 | ); |
| 668 | |
| 669 | expect(error).toMatchObject({ message: c.message }); |
| 670 | }) |
| 671 | ); |
| 672 | |
| 673 | it.effect( |
| 674 | '[Given] dev --project-name and no user anywhere [Then] fails pointing at --user-id', |
| 675 | () => |
| 676 | Effect.gen(function* () { |
| 677 | const { layer } = linkHandlerTest({ surface: devSurface({ projectName: 'named' }) }); |
| 678 | const error = yield* handleListConnectedAccounts( |
| 679 | params({ toolkit: Option.some('gmail'), list: true }) |
| 680 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 681 | |
| 682 | expect(error).toMatchObject({ |
| 683 | _tag: 'commands/MissingActingUserError', |
| 684 | message: |
| 685 | 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.', |
| 686 | }); |
| 687 | }) |
| 688 | ); |
| 689 | }); |
| 690 | |
| 691 | describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => { |
| 692 | it.effect( |
| 693 | '[Given] the directory’s test user [Then] links it in the directory’s project and prints the pending link', |
| 694 | () => |
| 695 | Effect.gen(function* () { |
| 696 | const { layer, requests } = linkHandlerTest({ |
| 697 | surface: devSurface(), |
| 698 | directoryProject: directory(Option.some('user_directory')), |
| 699 | }); |
| 700 | const output = yield* handleLegacyAuthConfigLink( |
| 701 | params({ authConfig: Option.some('ac_gmail') }) |
| 702 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 703 | |
| 704 | expect(output[0]).toBe('Using test user id "user_directory"'); |
| 705 | expect(requests).toEqual([ |
| 706 | { |
| 707 | operation: 'link.create', |
| 708 | params: { auth_config_id: 'ac_gmail', user_id: 'user_directory' }, |
| 709 | }, |
| 710 | ]); |
| 711 | expect(String(output.at(-1))).toBe(legacyPendingJson()); |
| 712 | }) |
| 713 | ); |
| 714 | |
| 715 | it.effect('[Given] no --auth-config [Then] fails with a usage error and sends nothing', () => |
| 716 | Effect.gen(function* () { |
| 717 | const { layer, requests } = linkHandlerTest({ surface: devSurface() }); |
| 718 | const error = yield* handleLegacyAuthConfigLink(params()).pipe( |
| 719 | Effect.flip, |
| 720 | Effect.provide(layer) |
| 721 | ); |
| 722 | |
| 723 | expect(error).toMatchObject({ |
| 724 | _tag: 'commands/CommandInputError', |
| 725 | command: 'dev connected-accounts link', |
| 726 | option: '--auth-config', |
| 727 | message: missingArgumentMessage('dev'), |
| 728 | }); |
| 729 | expect(requests).toEqual([]); |
| 730 | }) |
| 731 | ); |
| 732 | |
| 733 | it.effect('[Given] no user anywhere [Then] fails pointing at dev init', () => |
| 734 | Effect.gen(function* () { |
| 735 | const { layer } = linkHandlerTest({ |
| 736 | surface: devSurface(), |
| 737 | directoryProject: directory(Option.none()), |
| 738 | }); |
| 739 | const error = yield* handleLegacyAuthConfigLink( |
| 740 | params({ authConfig: Option.some('ac_gmail') }) |
| 741 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 742 | |
| 743 | expect(error).toMatchObject({ |
| 744 | _tag: 'commands/MissingActingUserError', |
| 745 | message: |
| 746 | 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.', |
| 747 | }); |
| 748 | }) |
| 749 | ); |
| 750 | |
| 751 | it.effect( |
| 752 | '[Given] no developer project and no user [Then] reports the missing project first', |
| 753 | () => |
| 754 | Effect.gen(function* () { |
| 755 | const { layer, requests } = linkHandlerTest({ surface: devSurface() }); |
| 756 | const error = yield* handleLegacyAuthConfigLink( |
| 757 | params({ authConfig: Option.some('ac_gmail') }) |
| 758 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 759 | |
| 760 | expect(error).toMatchObject({ |
| 761 | _tag: 'commands/CommandInputError', |
| 762 | option: '--auth-config', |
| 763 | message: AUTH_CONFIG_SCOPE_MESSAGE, |
| 764 | }); |
| 765 | expect(requests).toEqual([]); |
| 766 | }) |
| 767 | ); |
| 768 | |
| 769 | it.effect( |
| 770 | '[Given] no developer project [Then] fails with a CommandInputError explaining the scope and sends nothing', |
| 771 | () => |
| 772 | Effect.gen(function* () { |
| 773 | const { layer, requests } = linkHandlerTest({ surface: devSurface({ userId: 'user_1' }) }); |
| 774 | const error = yield* handleLegacyAuthConfigLink( |
| 775 | params({ authConfig: Option.some('ac_gmail') }) |
| 776 | ).pipe(Effect.flip, Effect.provide(layer)); |
| 777 | |
| 778 | expect(error).toMatchObject({ |
| 779 | _tag: 'commands/CommandInputError', |
| 780 | command: 'dev connected-accounts link', |
| 781 | option: '--auth-config', |
| 782 | message: AUTH_CONFIG_SCOPE_MESSAGE, |
| 783 | }); |
| 784 | expect(requests).toEqual([]); |
| 785 | }) |
| 786 | ); |
| 787 | |
| 788 | it.effect( |
| 789 | '[Given] the link request fails [Then] reports the message and the auth-config hint, and exits 1', |
| 790 | () => |
| 791 | Effect.gen(function* () { |
| 792 | const { layer, requests } = linkHandlerTest({ |
| 793 | surface: devSurface({ userId: 'user_1' }), |
| 794 | directoryProject: directory(Option.none()), |
| 795 | legacyLinkCreate: () => Effect.fail(new Error('quota exhausted')), |
| 796 | }); |
| 797 | const { exit, output } = yield* exitAndLines( |
| 798 | handleLegacyAuthConfigLink(params({ authConfig: Option.some('ac_gmail') })) |
| 799 | ).pipe(Effect.provide(layer)); |
| 800 | |
| 801 | expect(output).toEqual(['quota exhausted', BROWSE_AUTH_CONFIGS_HINT]); |
| 802 | expect(exitCodeOf(exit)).toBe(1); |
| 803 | expect(requests).toEqual([ |
| 804 | { |
| 805 | operation: 'link.create', |
| 806 | params: { auth_config_id: 'ac_gmail', user_id: 'user_1' }, |
| 807 | }, |
| 808 | ]); |
| 809 | }) |
| 810 | ); |
| 811 | |
| 812 | it.effect( |
| 813 | '[Given] an alias already in use [Then] points at the dev commands, sends nothing, and exits 1', |
| 814 | () => |
| 815 | Effect.gen(function* () { |
| 816 | const { layer, requests } = linkHandlerTest({ |
| 817 | surface: devSurface({ userId: 'user_1' }), |
| 818 | directoryProject: directory(Option.none()), |
| 819 | accounts: [account({ user_id: 'user_1', alias: 'Work' })], |
| 820 | }); |
| 821 | const { exit, output } = yield* exitAndLines( |
| 822 | handleLegacyAuthConfigLink( |
| 823 | params({ authConfig: Option.some('ac_gmail'), alias: Option.some(' work ') }) |
| 824 | ) |
| 825 | ).pipe(Effect.provide(layer)); |
| 826 | |
| 827 | expect(output).toEqual([ |
| 828 | 'Alias "work" is already in use by connected account "con_existing".', |
| 829 | "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list", |
| 830 | ]); |
| 831 | expect(exitCodeOf(exit)).toBe(1); |
| 832 | expect(requests).toEqual([]); |
| 833 | }) |
| 834 | ); |
| 835 | }); |
| 836 | |
| 837 | describe('connected-accounts link handler: handleToolRouterLink', () => { |
| 838 | it.effect.each([ |
| 839 | { name: '--user-id', userId: 'user_flag', expectedUser: 'user_flag' }, |
| 840 | { name: 'the directory’s test user', userId: undefined, expectedUser: 'user_directory' }, |
| 841 | ])( |
| 842 | '[Given] dev without --project-name and $name [Then] links that user in the directory’s project', |
| 843 | c => |
| 844 | Effect.gen(function* () { |
| 845 | const { layer, sessionUsers } = linkHandlerTest({ |
| 846 | surface: devSurface({ userId: c.userId }), |
| 847 | directoryProject: directory(Option.some('user_directory')), |
| 848 | globalTestUserId: Option.some('user_global'), |
| 849 | }); |
| 850 | const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe( |
| 851 | Effect.andThen(lines), |
| 852 | Effect.provide(layer) |
| 853 | ); |
| 854 | |
| 855 | expect(sessionUsers).toEqual([c.expectedUser]); |
| 856 | expect(String(output.at(-1))).toBe(toolRouterPendingJson('DEVELOPER')); |
| 857 | }) |
| 858 | ); |
| 859 | |
| 860 | it.effect( |
| 861 | '[Given] dev and an alias already in use [Then] points at the dev commands, sends nothing, and exits 1', |
| 862 | () => |
| 863 | Effect.gen(function* () { |
| 864 | const { layer, requests } = linkHandlerTest({ |
| 865 | surface: devSurface({ userId: 'user_1' }), |
| 866 | directoryProject: directory(Option.none()), |
| 867 | accounts: [account({ user_id: 'user_1', alias: 'Work' })], |
| 868 | }); |
| 869 | const { exit, output } = yield* exitAndLines( |
| 870 | handleToolRouterLink( |
| 871 | params({ toolkit: Option.some('gmail'), alias: Option.some('work') }) |
| 872 | ) |
| 873 | ).pipe(Effect.provide(layer)); |
| 874 | |
| 875 | expect(output).toEqual([ |
| 876 | 'Alias "work" is already in use by connected account "con_existing".', |
| 877 | "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list --toolkits gmail", |
| 878 | ]); |
| 879 | expect(exitCodeOf(exit)).toBe(1); |
| 880 | expect(requests).toEqual([]); |
| 881 | }) |
| 882 | ); |
| 883 | |
| 884 | it.effect( |
| 885 | '[Given] the consumer project and --alias [Then] links with the alias and prints the pending link', |
| 886 | () => |
| 887 | Effect.gen(function* () { |
| 888 | const { layer, requests } = linkHandlerTest({ accounts: [account()] }); |
| 889 | const output = yield* handleToolRouterLink( |
| 890 | params({ toolkit: Option.some('gmail'), alias: Option.some(' work ') }) |
| 891 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 892 | |
| 893 | expect(requests).toEqual([ |
| 894 | { |
| 895 | operation: 'toolRouter.session.link', |
| 896 | params: { sessionId: 'trs_handler_test', toolkit: 'gmail', alias: 'work' }, |
| 897 | }, |
| 898 | ]); |
| 899 | expect(String(output.at(-1))).toBe(toolRouterPendingJson()); |
| 900 | }) |
| 901 | ); |
| 902 | |
| 903 | it.effect( |
| 904 | '[Given] no --no-wait [Then] polls the account to ACTIVE and prints the active payload', |
| 905 | () => |
| 906 | Effect.gen(function* () { |
| 907 | // `retrieve('con_new')` answers from the fixture, so polling succeeds on its first try. |
| 908 | const { layer } = linkHandlerTest({ |
| 909 | accounts: [ |
| 910 | account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null }), |
| 911 | ], |
| 912 | }); |
| 913 | const output = yield* handleToolRouterLink( |
| 914 | params({ toolkit: Option.some('gmail'), noWait: false }) |
| 915 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 916 | |
| 917 | expect(output).toContain('Connection successful'); |
| 918 | expect(String(output.at(-1))).toBe(toolRouterActiveJson()); |
| 919 | }) |
| 920 | ); |
| 921 | |
| 922 | it.effect( |
| 923 | '[Given] the link returns the existing account [Then] no --alias is needed to reuse it', |
| 924 | () => |
| 925 | Effect.gen(function* () { |
| 926 | // The fixture account is both the hints entry and the link answer, so the |
| 927 | // additional-account guard lets the same account through. |
| 928 | const { layer } = linkHandlerTest({ accounts: [account({ id: 'con_new' })] }); |
| 929 | const lastLine = yield* handleToolRouterLink( |
| 930 | params({ toolkit: Option.some('gmail') }) |
| 931 | ).pipe( |
| 932 | Effect.andThen(lines), |
| 933 | Effect.map(all => String(all.at(-1))), |
| 934 | Effect.provide(layer) |
| 935 | ); |
| 936 | |
| 937 | expect(lastLine).toBe(toolRouterPendingJson()); |
| 938 | }) |
| 939 | ); |
| 940 | |
| 941 | it.effect('[Given] the alias-hints list request fails [Then] the link still runs', () => |
| 942 | Effect.gen(function* () { |
| 943 | const { layer, requests } = linkHandlerTest({ connectedAccountsListFails: true }); |
| 944 | const lastLine = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe( |
| 945 | Effect.andThen(lines), |
| 946 | Effect.map(all => String(all.at(-1))), |
| 947 | Effect.provide(layer) |
| 948 | ); |
| 949 | |
| 950 | expect(requests).toEqual([ |
| 951 | { |
| 952 | operation: 'toolRouter.session.link', |
| 953 | params: { sessionId: 'trs_handler_test', toolkit: 'gmail' }, |
| 954 | }, |
| 955 | ]); |
| 956 | expect(lastLine).toBe(toolRouterPendingJson()); |
| 957 | }) |
| 958 | ); |
| 959 | |
| 960 | it.effect('[Given] the link request fails [Then] reports the cause and the browse hint', () => |
| 961 | Effect.gen(function* () { |
| 962 | const terminal = redirectedTerminalUI(); |
| 963 | const { layer } = linkHandlerTest({ |
| 964 | toolRouterLink: () => Effect.fail(new Error('offline')), |
| 965 | terminal: terminal.layer, |
| 966 | }); |
| 967 | const exit = yield* Effect.exit( |
| 968 | handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(Effect.provide(layer)) |
| 969 | ); |
| 970 | |
| 971 | // `failedWith` keeps the client error in `.cause`, and the message prefers it. Plain |
| 972 | // lines, so a script, CI or an agent reading a redirected stderr sees them. |
| 973 | expect(terminal.stderr()).toBe(`offline\n${BROWSE_TOOLKITS_HINT}\n`); |
| 974 | expect(terminal.stdout()).toBe(''); |
| 975 | expect(exitCodeOf(exit)).toBe(1); |
| 976 | }) |
| 977 | ); |
| 978 | |
| 979 | it.effect('[Given] an incomplete link response [Then] reports it and exits 1', () => |
| 980 | Effect.gen(function* () { |
| 981 | const { layer } = linkHandlerTest({ |
| 982 | toolRouterLink: () => |
| 983 | Effect.succeed({ connected_account_id: 'con_new', link_token: 'lt', redirect_url: '' }), |
| 984 | }); |
| 985 | const { exit, output } = yield* exitAndLines( |
| 986 | handleToolRouterLink(params({ toolkit: Option.some('gmail') })) |
| 987 | ).pipe(Effect.provide(layer)); |
| 988 | |
| 989 | expect(output).toEqual(['Linking gmail...', INCOMPLETE_LINK_RESPONSE_MESSAGE]); |
| 990 | expect(exitCodeOf(exit)).toBe(1); |
| 991 | }) |
| 992 | ); |
| 993 | |
| 994 | it.effect('[Given] no toolkit [Then] fails with a usage error and sends nothing', () => |
| 995 | Effect.gen(function* () { |
| 996 | const { layer, requests } = linkHandlerTest(); |
| 997 | const error = yield* handleToolRouterLink(params()).pipe(Effect.flip, Effect.provide(layer)); |
| 998 | |
| 999 | expect(error).toMatchObject({ |
| 1000 | _tag: 'commands/CommandInputError', |
| 1001 | command: 'link', |
| 1002 | option: '<toolkit>', |
| 1003 | message: missingArgumentMessage('root'), |
| 1004 | }); |
| 1005 | expect(requests).toEqual([]); |
| 1006 | }) |
| 1007 | ); |
| 1008 | |
| 1009 | it.effect.each([ |
| 1010 | { case: 'no consumer user id at all', consumerUserId: null }, |
| 1011 | { case: 'an empty consumer user id', consumerUserId: '' }, |
| 1012 | ])('[Given] $case and no test user [Then] fails before any link request', c => |
| 1013 | Effect.gen(function* () { |
| 1014 | const { layer, requests } = linkHandlerTest({ consumerUserId: c.consumerUserId }); |
| 1015 | const failure = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe( |
| 1016 | Effect.flip, |
| 1017 | Effect.provide(layer) |
| 1018 | ); |
| 1019 | |
| 1020 | // An empty id counts as no user, so both shapes fail with the shared missing-user error. |
| 1021 | expect(failure).toBeInstanceOf(MissingActingUserError); |
| 1022 | expect(failure).toMatchObject({ |
| 1023 | message: 'Missing consumer user id. Run `composio login` and try again.', |
| 1024 | }); |
| 1025 | expect(requests).toEqual([]); |
| 1026 | }) |
| 1027 | ); |
| 1028 | |
| 1029 | it.effect('[Given] a redirect URL without an http scheme [Then] warns and still waits', () => |
| 1030 | Effect.gen(function* () { |
| 1031 | const { layer } = linkHandlerTest({ |
| 1032 | accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })], |
| 1033 | toolRouterLink: () => |
| 1034 | Effect.succeed({ connected_account_id: 'con_new', redirect_url: 'notaurl' }), |
| 1035 | terminal: decoratingTerminal, |
| 1036 | }); |
| 1037 | const output = yield* handleToolRouterLink( |
| 1038 | params({ toolkit: Option.some('gmail'), noWait: false }) |
| 1039 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 1040 | |
| 1041 | expect(output).toEqual([ |
| 1042 | 'Linking gmail...', |
| 1043 | 'Open this URL in your browser to authorize', |
| 1044 | '[Redirect URL] notaurl', |
| 1045 | 'Redirect URL has an unexpected scheme: notaurl', |
| 1046 | 'Open the URL manually if you trust the source.', |
| 1047 | 'Connection successful', |
| 1048 | 'Connected account "con_new" is now ACTIVE (toolkit: gmail).', |
| 1049 | toJson({ |
| 1050 | status: 'success', |
| 1051 | message: 'Connected account "con_new" is now ACTIVE (toolkit: gmail).', |
| 1052 | connected_account_id: 'con_new', |
| 1053 | toolkit: 'gmail', |
| 1054 | redirect_url: 'notaurl', |
| 1055 | }), |
| 1056 | ]); |
| 1057 | expect(vi.mocked(open)).not.toHaveBeenCalled(); |
| 1058 | }) |
| 1059 | ); |
| 1060 | |
| 1061 | it.effect('[Given] the browser fails to open [Then] points at the URL and still waits', () => |
| 1062 | Effect.gen(function* () { |
| 1063 | vi.mocked(open).mockRejectedValueOnce(new Error('no browser')); |
| 1064 | const { layer } = linkHandlerTest({ |
| 1065 | accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })], |
| 1066 | terminal: decoratingTerminal, |
| 1067 | }); |
| 1068 | const output = yield* handleToolRouterLink( |
| 1069 | params({ toolkit: Option.some('gmail'), noWait: false, noBrowser: false }) |
| 1070 | ).pipe(Effect.andThen(lines), Effect.provide(layer)); |
| 1071 | |
| 1072 | expect(vi.mocked(open)).toHaveBeenCalledWith(TOOL_ROUTER_LINK_TARGET.redirect_url, { |
| 1073 | wait: false, |
| 1074 | }); |
| 1075 | expect(output).toEqual([ |
| 1076 | 'Linking gmail...', |
| 1077 | 'Redirecting you to the authorization page', |
| 1078 | `[Redirect URL] ${TOOL_ROUTER_LINK_TARGET.redirect_url}`, |
| 1079 | 'Could not open the browser automatically.', |
| 1080 | 'Open the URL above manually.', |
| 1081 | 'Connection successful', |
| 1082 | 'Connected account "con_new" is now ACTIVE (toolkit: gmail).', |
| 1083 | toolRouterActiveJson(), |
| 1084 | ]); |
| 1085 | }) |
| 1086 | ); |
| 1087 | |
| 1088 | it.effect('[Given] one failed poll [Then] retries and still reaches ACTIVE', () => |
| 1089 | Effect.gen(function* () { |
| 1090 | const { layer } = linkHandlerTest({ |
| 1091 | accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })], |
| 1092 | retrieveFailsFirst: 1, |
| 1093 | }); |
| 1094 | const lastLine = yield* runWithAdvancingClock( |
| 1095 | handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false })).pipe( |
| 1096 | Effect.andThen(lines), |
| 1097 | Effect.map(all => String(all.at(-1))), |
| 1098 | Effect.provide(layer) |
| 1099 | ) |
| 1100 | ); |
| 1101 | |
| 1102 | expect(lastLine).toBe(toolRouterActiveJson()); |
| 1103 | }) |
| 1104 | ); |
| 1105 | |
| 1106 | it.effect('[Given] the account never turns ACTIVE [Then] gives up and reports the timeout', () => |
| 1107 | Effect.gen(function* () { |
| 1108 | const { layer } = linkHandlerTest({ |
| 1109 | accounts: [account({ id: 'con_new', user_id: 'poll-source', status: 'INITIATED' })], |
| 1110 | }); |
| 1111 | const error = yield* runWithAdvancingClock( |
| 1112 | Effect.gen(function* () { |
| 1113 | const error = yield* Effect.flip( |
| 1114 | handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false })) |
| 1115 | ); |
| 1116 | const output = yield* lines; |
| 1117 | return { error, output }; |
| 1118 | }).pipe(Effect.provide(layer)) |
| 1119 | ); |
| 1120 | |
| 1121 | expect(error.error).toMatchObject({ |
| 1122 | _tag: 'commands/ConnectionPollingError', |
| 1123 | connectedAccountId: 'con_new', |
| 1124 | status: 'INITIATED', |
| 1125 | }); |
| 1126 | expect(error.output).not.toContain('Connection successful'); |
| 1127 | expect(String(error.output.at(-1))).toBe( |
| 1128 | 'Timed out waiting for authorization. Run the command again.' |
| 1129 | ); |
| 1130 | }) |
| 1131 | ); |
| 1132 | |
| 1133 | it.effect( |
| 1134 | '[Given] an active account and no --alias [Then] lists it, prints no link, and exits 1', |
| 1135 | () => |
| 1136 | Effect.gen(function* () { |
| 1137 | const { layer } = linkHandlerTest({ accounts: [account({ alias: 'default' })] }); |
| 1138 | const { exit, output } = yield* exitAndLines( |
| 1139 | handleToolRouterLink(params({ toolkit: Option.some('gmail') })) |
| 1140 | ).pipe(Effect.provide(layer)); |
| 1141 | |
| 1142 | expect(output.slice(-2)).toEqual([ |
| 1143 | `A connected account already exists for user "${CONSUMER_USER_ID}" in toolkit "gmail". Pass --alias to create another one.`, |
| 1144 | '[Existing accounts] con_existing (default, castle)', |
| 1145 | ]); |
| 1146 | expect(exitCodeOf(exit)).toBe(1); |
| 1147 | }) |
| 1148 | ); |
| 1149 | }); |
| 1150 | |
| 1151 | describe('connected-accounts link handler: waiting off a terminal', () => { |
| 1152 | // Every stream redirected, as an agent's shell runs the command. The first two polls find |
| 1153 | // nothing, so the link is still waiting when `stderrWhileWaiting` is read, at the first one. |
| 1154 | it.effect.each([ |
| 1155 | { |
| 1156 | flow: 'a toolkit', |
| 1157 | account: 'con_new', |
| 1158 | redirectUrl: TOOL_ROUTER_LINK_TARGET.redirect_url, |
| 1159 | surface: undefined, |
| 1160 | directoryProject: undefined, |
| 1161 | link: () => handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false })), |
| 1162 | }, |
| 1163 | { |
| 1164 | flow: 'an auth config', |
| 1165 | account: LEGACY_LINK_TARGET.connected_account_id, |
| 1166 | redirectUrl: LEGACY_LINK_TARGET.redirect_url, |
| 1167 | surface: devSurface(), |
| 1168 | directoryProject: directory(Option.some('user_directory')), |
| 1169 | link: () => |
| 1170 | handleLegacyAuthConfigLink(params({ authConfig: Option.some('ac_gmail'), noWait: false })), |
| 1171 | }, |
| 1172 | ])( |
| 1173 | '[Given] --no-browser and $flow [Then] stderr has the URL before the wait, stdout the JSON after', |
| 1174 | ({ account: accountId, redirectUrl, surface, directoryProject, link }) => |
| 1175 | Effect.gen(function* () { |
| 1176 | const terminal = redirectedTerminalUI(); |
| 1177 | let stderrWhileWaiting: string | undefined; |
| 1178 | const { layer } = linkHandlerTest({ |
| 1179 | ...(surface ? { surface } : {}), |
| 1180 | ...(directoryProject ? { directoryProject } : {}), |
| 1181 | accounts: [ |
| 1182 | account({ id: accountId, user_id: 'poll-source', alias: null, word_id: null }), |
| 1183 | ], |
| 1184 | retrieveFailsFirst: 2, |
| 1185 | onRetrieve: () => { |
| 1186 | stderrWhileWaiting ??= terminal.stderr(); |
| 1187 | }, |
| 1188 | terminal: terminal.layer, |
| 1189 | }); |
| 1190 | |
| 1191 | yield* runWithAdvancingClock(link().pipe(Effect.provide(layer))); |
| 1192 | |
| 1193 | expect(stderrWhileWaiting).toBe( |
| 1194 | `${formatNonInteractiveAuthorizationInstructions(redirectUrl)}\n` |
| 1195 | ); |
| 1196 | const stdout = terminal.stdout(); |
| 1197 | expect(JSON.parse(stdout)).toMatchObject({ status: 'success', redirect_url: redirectUrl }); |
| 1198 | expect(vi.mocked(open)).not.toHaveBeenCalled(); |
| 1199 | }) |
| 1200 | ); |
| 1201 | |
| 1202 | it.effect('[Given] --no-wait [Then] stderr stays empty: the URL is in the stdout JSON', () => |
| 1203 | Effect.gen(function* () { |
| 1204 | const terminal = redirectedTerminalUI(); |
| 1205 | const { layer } = linkHandlerTest({ terminal: terminal.layer }); |
| 1206 | |
| 1207 | yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe( |
| 1208 | Effect.provide(layer) |
| 1209 | ); |
| 1210 | |
| 1211 | expect(terminal.stderr()).toBe(''); |
| 1212 | expect(JSON.parse(terminal.stdout())).toMatchObject({ |
| 1213 | status: 'pending', |
| 1214 | redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url, |
| 1215 | }); |
| 1216 | }) |
| 1217 | ); |
| 1218 | }); |