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, 04:45 UTC
| 1 | import { describe, it, expect, vi, beforeEach, afterEach } from '@effect/vitest'; |
| 2 | import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'; |
| 3 | import { dirname, join } from 'node:path'; |
| 4 | import { tmpdir } from 'node:os'; |
| 5 | import * as BunFileSystem from '@effect/platform-bun/BunFileSystem'; |
| 6 | import * as BunPath from '@effect/platform-bun/BunPath'; |
| 7 | import { Effect, Fiber, Layer } from 'effect'; |
| 8 | import { withHttpServerEffect } from 'test/__utils__/http-server'; |
| 9 | import { defaultNodeOs, NodeOs } from 'src/services/node-os'; |
| 10 | import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui'; |
| 11 | import { commandIdentity } from 'test/__utils__/command-identity'; |
| 12 | import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test'; |
| 13 | import { |
| 14 | createUpdateChecker, |
| 15 | UpdateNotice, |
| 16 | parseLatestVersionFromReleases, |
| 17 | type UpdateCheckConfig, |
| 18 | type UpdateCheckState, |
| 19 | } from 'src/services/update-check'; |
| 20 | |
| 21 | // ── Helpers ───────────────────────────────────────────────────────────── |
| 22 | |
| 23 | /** Platform services required by the update checker's Effects. */ |
| 24 | const PlatformLayers = Layer.mergeAll(BunFileSystem.layer, BunPath.layer); |
| 25 | |
| 26 | /** Create a temp directory that is cleaned up after each test. */ |
| 27 | let tempDir: string; |
| 28 | beforeEach(() => { |
| 29 | tempDir = mkdtempSync(join(tmpdir(), 'update-check-test-')); |
| 30 | }); |
| 31 | afterEach(() => { |
| 32 | rmSync(tempDir, { recursive: true, force: true }); |
| 33 | }); |
| 34 | |
| 35 | /** Build a test config pointing at a temp directory with optional overrides. */ |
| 36 | function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig { |
| 37 | return { |
| 38 | stateFile: join(tempDir, '.composio', 'update-check.json'), |
| 39 | currentVersion: '0.2.0', |
| 40 | checkIntervalMs: 24 * 60 * 60 * 1000, |
| 41 | releasesUrl: 'http://unused.test', |
| 42 | binaryAssetName: 'composio-darwin-aarch64.zip', |
| 43 | accessToken: undefined, |
| 44 | fetchFn: () => Promise.reject(new Error('fetch not configured')), |
| 45 | ...overrides, |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | const makeTerminal = ( |
| 50 | output: string[], |
| 51 | tty: { stdin: boolean; stdout: boolean; stderr: boolean } = { |
| 52 | stdin: true, |
| 53 | stdout: true, |
| 54 | stderr: true, |
| 55 | } |
| 56 | ): Pick<TerminalUI, 'capabilities' | 'error'> => ({ |
| 57 | capabilities: Effect.succeed( |
| 58 | getTerminalCapabilities({ |
| 59 | stdin: { isTTY: tty.stdin }, |
| 60 | stdout: { isTTY: tty.stdout }, |
| 61 | stderr: { isTTY: tty.stderr }, |
| 62 | }) |
| 63 | ), |
| 64 | error: line => Effect.sync(() => output.push(line)), |
| 65 | }); |
| 66 | |
| 67 | /** Write a state file to the test config's stateFile path. */ |
| 68 | function writeState(config: UpdateCheckConfig, state: UpdateCheckState): void { |
| 69 | mkdirSync(dirname(config.stateFile), { recursive: true }); |
| 70 | writeFileSync(config.stateFile, JSON.stringify(state)); |
| 71 | } |
| 72 | |
| 73 | /** Create a GitHub releases response body. */ |
| 74 | function makeReleasesPayload(versions: string[], assetName = 'composio-darwin-aarch64.zip') { |
| 75 | return versions.map(v => ({ |
| 76 | tag_name: `@composio/cli@${v}`, |
| 77 | prerelease: v.includes('-'), |
| 78 | draft: false, |
| 79 | assets: [{ name: assetName, browser_download_url: 'unused' }], |
| 80 | })); |
| 81 | } |
| 82 | |
| 83 | function makeDeferred<T>() { |
| 84 | let resolve!: (value: T | PromiseLike<T>) => void; |
| 85 | let reject!: (reason?: unknown) => void; |
| 86 | const promise = new Promise<T>((resolvePromise, rejectPromise) => { |
| 87 | resolve = resolvePromise; |
| 88 | reject = rejectPromise; |
| 89 | }); |
| 90 | return { promise, resolve, reject }; |
| 91 | } |
| 92 | |
| 93 | // ── parseLatestVersionFromReleases (pure) ─────────────────────────────── |
| 94 | |
| 95 | describe('parseLatestVersionFromReleases', () => { |
| 96 | const binaryAssetName = 'composio-darwin-aarch64.zip'; |
| 97 | |
| 98 | it('returns undefined for non-array input', () => { |
| 99 | expect(parseLatestVersionFromReleases(null, binaryAssetName)).toBeUndefined(); |
| 100 | expect(parseLatestVersionFromReleases('string', binaryAssetName)).toBeUndefined(); |
| 101 | expect(parseLatestVersionFromReleases(42, binaryAssetName)).toBeUndefined(); |
| 102 | }); |
| 103 | |
| 104 | it('returns undefined when no releases match the CLI pattern', () => { |
| 105 | const releases = [ |
| 106 | { tag_name: '@composio/core@1.0.0', assets: [{ name: binaryAssetName }] }, |
| 107 | { tag_name: 'v1.0.0', assets: [{ name: binaryAssetName }] }, |
| 108 | { tag_name: '@composio/cli@0.2.0-beta.1', assets: [{ name: binaryAssetName }] }, |
| 109 | ]; |
| 110 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBeUndefined(); |
| 111 | }); |
| 112 | |
| 113 | it('returns the single matching version', () => { |
| 114 | const releases = makeReleasesPayload(['0.2.1']); |
| 115 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBe('0.2.1'); |
| 116 | }); |
| 117 | |
| 118 | it('returns the highest semver, not the first element', () => { |
| 119 | const releases = makeReleasesPayload(['0.1.0', '0.10.0', '0.9.0', '0.2.0']); |
| 120 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBe('0.10.0'); |
| 121 | }); |
| 122 | |
| 123 | it('excludes prerelease and draft releases', () => { |
| 124 | const releases = [ |
| 125 | ...makeReleasesPayload(['0.2.0']), |
| 126 | { |
| 127 | tag_name: '@composio/cli@0.3.0', |
| 128 | prerelease: true, |
| 129 | draft: false, |
| 130 | assets: [{ name: binaryAssetName }], |
| 131 | }, |
| 132 | { |
| 133 | tag_name: '@composio/cli@0.4.0', |
| 134 | prerelease: false, |
| 135 | draft: true, |
| 136 | assets: [{ name: binaryAssetName }], |
| 137 | }, |
| 138 | ]; |
| 139 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBe('0.2.0'); |
| 140 | }); |
| 141 | |
| 142 | it('requires the platform binary asset', () => { |
| 143 | const releases = [ |
| 144 | ...makeReleasesPayload(['0.4.0'], 'composio-linux-x64.zip'), |
| 145 | ...makeReleasesPayload(['0.3.0']), |
| 146 | ]; |
| 147 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBe('0.3.0'); |
| 148 | }); |
| 149 | |
| 150 | it('returns undefined when no binary asset name is known', () => { |
| 151 | expect( |
| 152 | parseLatestVersionFromReleases(makeReleasesPayload(['0.2.1']), undefined) |
| 153 | ).toBeUndefined(); |
| 154 | }); |
| 155 | |
| 156 | it('skips malformed release objects', () => { |
| 157 | const releases = [ |
| 158 | null, |
| 159 | 42, |
| 160 | { noTagName: true }, |
| 161 | { tag_name: 123 }, |
| 162 | { tag_name: '@composio/cli@0.5.0' }, |
| 163 | { tag_name: '@composio/cli@0.6.0', assets: [{ noName: true }] }, |
| 164 | { tag_name: '@composio/cli@0.7.0', assets: [{ name: binaryAssetName }] }, |
| 165 | ]; |
| 166 | expect(parseLatestVersionFromReleases(releases, binaryAssetName)).toBe('0.7.0'); |
| 167 | }); |
| 168 | }); |
| 169 | |
| 170 | // ── showUpdateNotice ──────────────────────────────────────────────────── |
| 171 | |
| 172 | describe('showUpdateNotice', () => { |
| 173 | let output: string[]; |
| 174 | |
| 175 | beforeEach(() => { |
| 176 | output = []; |
| 177 | }); |
| 178 | |
| 179 | it.effect('does nothing when no state file exists', () => |
| 180 | Effect.gen(function* () { |
| 181 | const { showUpdateNotice } = createUpdateChecker(makeConfig()); |
| 182 | |
| 183 | yield* showUpdateNotice(makeTerminal(output)); |
| 184 | |
| 185 | expect(output).toEqual([]); |
| 186 | }).pipe(Effect.provide(PlatformLayers)) |
| 187 | ); |
| 188 | |
| 189 | it.effect('does nothing when cached version equals current version', () => |
| 190 | Effect.gen(function* () { |
| 191 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 192 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' }); |
| 193 | const { showUpdateNotice } = createUpdateChecker(config); |
| 194 | |
| 195 | yield* showUpdateNotice(makeTerminal(output)); |
| 196 | |
| 197 | expect(output).toEqual([]); |
| 198 | }).pipe(Effect.provide(PlatformLayers)) |
| 199 | ); |
| 200 | |
| 201 | it.effect('does nothing when cached version is older than current', () => |
| 202 | Effect.gen(function* () { |
| 203 | const config = makeConfig({ currentVersion: '0.3.0' }); |
| 204 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' }); |
| 205 | const { showUpdateNotice } = createUpdateChecker(config); |
| 206 | |
| 207 | yield* showUpdateNotice(makeTerminal(output)); |
| 208 | |
| 209 | expect(output).toEqual([]); |
| 210 | }).pipe(Effect.provide(PlatformLayers)) |
| 211 | ); |
| 212 | |
| 213 | it.effect('prints upgrade hint when cached version is newer', () => |
| 214 | Effect.gen(function* () { |
| 215 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 216 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' }); |
| 217 | const { showUpdateNotice } = createUpdateChecker(config); |
| 218 | |
| 219 | yield* showUpdateNotice(makeTerminal(output)); |
| 220 | |
| 221 | expect(output).toHaveLength(1); |
| 222 | expect(output[0]).toContain('Update available'); |
| 223 | expect(output[0]).toContain('0.3.0'); |
| 224 | expect(output[0]).toContain('composio upgrade'); |
| 225 | }).pipe(Effect.provide(PlatformLayers)) |
| 226 | ); |
| 227 | |
| 228 | it.effect('does not print upgrade hint when stderr is captured', () => |
| 229 | Effect.gen(function* () { |
| 230 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 231 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' }); |
| 232 | const { showUpdateNotice } = createUpdateChecker(config); |
| 233 | |
| 234 | yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: true, stderr: false })); |
| 235 | |
| 236 | expect(output).toEqual([]); |
| 237 | }).pipe(Effect.provide(PlatformLayers)) |
| 238 | ); |
| 239 | |
| 240 | it.effect('still prints upgrade hint when stdout is piped but stderr is a terminal', () => |
| 241 | Effect.gen(function* () { |
| 242 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 243 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' }); |
| 244 | const { showUpdateNotice } = createUpdateChecker(config); |
| 245 | |
| 246 | yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: false, stderr: true })); |
| 247 | |
| 248 | expect(output).toHaveLength(1); |
| 249 | expect(output[0]).toContain('Update available'); |
| 250 | }).pipe(Effect.provide(PlatformLayers)) |
| 251 | ); |
| 252 | |
| 253 | it.effect('still prints upgrade hint when stdin is redirected', () => |
| 254 | Effect.gen(function* () { |
| 255 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 256 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' }); |
| 257 | const { showUpdateNotice } = createUpdateChecker(config); |
| 258 | |
| 259 | yield* showUpdateNotice(makeTerminal(output, { stdin: false, stdout: true, stderr: true })); |
| 260 | |
| 261 | expect(output).toHaveLength(1); |
| 262 | expect(output[0]).toContain('Update available'); |
| 263 | }).pipe(Effect.provide(PlatformLayers)) |
| 264 | ); |
| 265 | |
| 266 | it.effect('silently ignores corrupt state file', () => |
| 267 | Effect.gen(function* () { |
| 268 | const config = makeConfig(); |
| 269 | mkdirSync(dirname(config.stateFile), { recursive: true }); |
| 270 | writeFileSync(config.stateFile, 'not-json!!!'); |
| 271 | const { showUpdateNotice } = createUpdateChecker(config); |
| 272 | |
| 273 | yield* showUpdateNotice(makeTerminal(output)); |
| 274 | |
| 275 | expect(output).toEqual([]); |
| 276 | }).pipe(Effect.provide(PlatformLayers)) |
| 277 | ); |
| 278 | |
| 279 | it.effect('does nothing when cached version is not valid semver', () => |
| 280 | Effect.gen(function* () { |
| 281 | const config = makeConfig({ currentVersion: '0.2.0' }); |
| 282 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' }); |
| 283 | const { showUpdateNotice } = createUpdateChecker(config); |
| 284 | |
| 285 | yield* showUpdateNotice(makeTerminal(output)); |
| 286 | |
| 287 | expect(output).toEqual([]); |
| 288 | }).pipe(Effect.provide(PlatformLayers)) |
| 289 | ); |
| 290 | }); |
| 291 | |
| 292 | // ── UpdateNotice (the service the invocation runs) ──────────────────────────── |
| 293 | |
| 294 | describe('UpdateNotice', () => { |
| 295 | /** `UpdateNotice.Default` over a home directory in `tempDir` and a recording, decorating stderr. */ |
| 296 | const noticeLayer = (output: string[]) => |
| 297 | Layer.provide( |
| 298 | UpdateNotice.Default, |
| 299 | Layer.mergeAll( |
| 300 | PlatformLayers, |
| 301 | Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })), |
| 302 | Layer.succeed(TerminalUI, TerminalUI.of({ ...terminalUITestImpl, ...makeTerminal(output) })) |
| 303 | ) |
| 304 | ); |
| 305 | |
| 306 | // `makeConfig()`'s state file is where the service looks under that home directory. |
| 307 | const writeCachedLatest = (latestVersion: string) => |
| 308 | writeState(makeConfig(), { lastChecked: new Date().toISOString(), latestVersion }); |
| 309 | |
| 310 | // Which commands run it is their `CommandMeta`'s business: see |
| 311 | // `test/src/invocation/invocation-hooks.test.ts`. |
| 312 | it.effect('[Given] a newer cached release [Then] prints the notice', () => { |
| 313 | const output: string[] = []; |
| 314 | writeCachedLatest('999.0.0'); |
| 315 | return Effect.gen(function* () { |
| 316 | const notice = yield* UpdateNotice; |
| 317 | yield* notice.run({ identity: commandIdentity(['tools', 'list']) }); |
| 318 | expect(output.some(line => line.includes('999.0.0'))).toBe(true); |
| 319 | }).pipe(Effect.provide(noticeLayer(output))); |
| 320 | }); |
| 321 | |
| 322 | it.effect('[Given] no cached release [Then] prints nothing', () => { |
| 323 | const output: string[] = []; |
| 324 | return Effect.gen(function* () { |
| 325 | const notice = yield* UpdateNotice; |
| 326 | yield* notice.run({ identity: commandIdentity(['tools', 'list']) }); |
| 327 | expect(output).toEqual([]); |
| 328 | }).pipe(Effect.provide(noticeLayer(output))); |
| 329 | }); |
| 330 | }); |
| 331 | |
| 332 | // ── getUpdateStatus ───────────────────────────────────────────────────── |
| 333 | |
| 334 | describe('getUpdateStatus', () => { |
| 335 | it.effect('reports an available update for a stale stable install', () => |
| 336 | Effect.gen(function* () { |
| 337 | const config = makeConfig({ |
| 338 | currentVersion: '0.2.0', |
| 339 | fetchFn: vi.fn().mockResolvedValue({ |
| 340 | ok: true, |
| 341 | json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])), |
| 342 | }) as unknown as typeof fetch, |
| 343 | }); |
| 344 | const { getUpdateStatus } = createUpdateChecker(config); |
| 345 | |
| 346 | const status = yield* getUpdateStatus; |
| 347 | |
| 348 | expect(status).toEqual({ |
| 349 | current: '0.2.0', |
| 350 | latestStable: '0.3.0', |
| 351 | updateAvailable: true, |
| 352 | checkStatus: 'update-available', |
| 353 | lastChecked: expect.any(String), |
| 354 | }); |
| 355 | }).pipe(Effect.provide(PlatformLayers)) |
| 356 | ); |
| 357 | |
| 358 | it.effect('reports an unknown status when the fetch fails and no cache exists', () => |
| 359 | Effect.gen(function* () { |
| 360 | const config = makeConfig({ |
| 361 | currentVersion: '0.2.0', |
| 362 | fetchFn: vi.fn().mockRejectedValue(new Error('offline')) as unknown as typeof fetch, |
| 363 | }); |
| 364 | const { getUpdateStatus } = createUpdateChecker(config); |
| 365 | |
| 366 | const status = yield* getUpdateStatus; |
| 367 | |
| 368 | expect(status).toEqual({ |
| 369 | current: '0.2.0', |
| 370 | latestStable: null, |
| 371 | updateAvailable: false, |
| 372 | checkStatus: 'unknown', |
| 373 | lastChecked: null, |
| 374 | }); |
| 375 | expect(existsSync(config.stateFile)).toBe(false); |
| 376 | }).pipe(Effect.provide(PlatformLayers)) |
| 377 | ); |
| 378 | |
| 379 | it.effect('does not call a stale cached version up to date after a failed refresh', () => |
| 380 | Effect.gen(function* () { |
| 381 | const config = makeConfig({ |
| 382 | currentVersion: '0.2.0', |
| 383 | fetchFn: vi.fn().mockRejectedValue(new Error('offline')) as unknown as typeof fetch, |
| 384 | }); |
| 385 | const lastChecked = '2020-01-01T00:00:00.000Z'; |
| 386 | writeState(config, { lastChecked, latestVersion: '0.2.0' }); |
| 387 | const { getUpdateStatus } = createUpdateChecker(config); |
| 388 | |
| 389 | const status = yield* getUpdateStatus; |
| 390 | |
| 391 | expect(status).toEqual({ |
| 392 | current: '0.2.0', |
| 393 | latestStable: '0.2.0', |
| 394 | updateAvailable: false, |
| 395 | checkStatus: 'unknown', |
| 396 | lastChecked, |
| 397 | }); |
| 398 | }).pipe(Effect.provide(PlatformLayers)) |
| 399 | ); |
| 400 | |
| 401 | it.effect('does not report a cached prerelease as latestStable', () => |
| 402 | Effect.gen(function* () { |
| 403 | const config = makeConfig({ currentVersion: '0.2.32-beta.289' }); |
| 404 | writeState(config, { |
| 405 | lastChecked: new Date().toISOString(), |
| 406 | latestVersion: '0.2.32-beta.289', |
| 407 | }); |
| 408 | const { getUpdateStatus } = createUpdateChecker(config); |
| 409 | |
| 410 | const status = yield* getUpdateStatus; |
| 411 | |
| 412 | expect(status.latestStable).toBeNull(); |
| 413 | expect(status.updateAvailable).toBe(false); |
| 414 | expect(status.checkStatus).toBe('unknown'); |
| 415 | }).pipe(Effect.provide(PlatformLayers)) |
| 416 | ); |
| 417 | |
| 418 | it.effect('uses the fresh cache without fetching', () => |
| 419 | Effect.gen(function* () { |
| 420 | const fetchFn = vi.fn(); |
| 421 | const config = makeConfig({ |
| 422 | currentVersion: '0.2.0', |
| 423 | fetchFn: fetchFn as unknown as typeof fetch, |
| 424 | }); |
| 425 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.1' }); |
| 426 | const { getUpdateStatus } = createUpdateChecker(config); |
| 427 | |
| 428 | const status = yield* getUpdateStatus; |
| 429 | |
| 430 | expect(fetchFn).not.toHaveBeenCalled(); |
| 431 | expect(status.latestStable).toBe('0.2.1'); |
| 432 | expect(status.updateAvailable).toBe(true); |
| 433 | expect(status.checkStatus).toBe('update-available'); |
| 434 | }).pipe(Effect.provide(PlatformLayers)) |
| 435 | ); |
| 436 | |
| 437 | it.effect('reports an unknown status for an invalid installed version', () => |
| 438 | Effect.gen(function* () { |
| 439 | const config = makeConfig({ currentVersion: 'corrupt-tag' }); |
| 440 | writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' }); |
| 441 | const { getUpdateStatus } = createUpdateChecker(config); |
| 442 | |
| 443 | const status = yield* getUpdateStatus; |
| 444 | |
| 445 | expect(status).toEqual({ |
| 446 | current: 'corrupt-tag', |
| 447 | latestStable: '0.3.0', |
| 448 | updateAvailable: false, |
| 449 | checkStatus: 'unknown', |
| 450 | lastChecked: expect.any(String), |
| 451 | }); |
| 452 | }).pipe(Effect.provide(PlatformLayers)) |
| 453 | ); |
| 454 | }); |
| 455 | |
| 456 | // ── checkForUpdate ────────────────────────────────────────────────────── |
| 457 | |
| 458 | describe('checkForUpdate', () => { |
| 459 | // Pin the wall clock so the throttle math in checkForUpdate is deterministic. |
| 460 | // Only Date is faked: the SUT awaits real fetch promises through |
| 461 | // Effect.tryPromise, which need real timers/microtasks to settle. |
| 462 | const pinnedNow = new Date('2026-01-01T00:00:00.000Z'); |
| 463 | const staleLastChecked = '2025-12-30T23:00:00.000Z'; // 25 hours before pinnedNow |
| 464 | |
| 465 | beforeEach(() => { |
| 466 | vi.useFakeTimers({ toFake: ['Date'] }); |
| 467 | vi.setSystemTime(pinnedNow); |
| 468 | }); |
| 469 | |
| 470 | afterEach(() => { |
| 471 | vi.useRealTimers(); |
| 472 | }); |
| 473 | |
| 474 | it.effect('skips fetch when cache is fresh', () => |
| 475 | Effect.gen(function* () { |
| 476 | const fetchFn = vi.fn(); |
| 477 | const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch }); |
| 478 | writeState(config, { |
| 479 | lastChecked: new Date().toISOString(), |
| 480 | latestVersion: '0.2.0', |
| 481 | }); |
| 482 | const { checkForUpdate } = createUpdateChecker(config); |
| 483 | |
| 484 | yield* checkForUpdate; |
| 485 | |
| 486 | expect(fetchFn).not.toHaveBeenCalled(); |
| 487 | }).pipe(Effect.provide(PlatformLayers)) |
| 488 | ); |
| 489 | |
| 490 | it.effect('fetches when cache is stale', () => |
| 491 | Effect.gen(function* () { |
| 492 | const stale = staleLastChecked; |
| 493 | const config = makeConfig({ |
| 494 | fetchFn: vi.fn().mockResolvedValue({ |
| 495 | ok: true, |
| 496 | json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])), |
| 497 | }) as unknown as typeof fetch, |
| 498 | }); |
| 499 | writeState(config, { lastChecked: stale, latestVersion: '0.2.0' }); |
| 500 | const { checkForUpdate } = createUpdateChecker(config); |
| 501 | |
| 502 | yield* checkForUpdate; |
| 503 | |
| 504 | expect(config.fetchFn).toHaveBeenCalledOnce(); |
| 505 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 506 | expect(state.latestVersion).toBe('0.3.0'); |
| 507 | }).pipe(Effect.provide(PlatformLayers)) |
| 508 | ); |
| 509 | |
| 510 | it.effect('fetches when no cache exists', () => |
| 511 | Effect.gen(function* () { |
| 512 | const config = makeConfig({ |
| 513 | fetchFn: vi.fn().mockResolvedValue({ |
| 514 | ok: true, |
| 515 | json: () => Promise.resolve(makeReleasesPayload(['0.4.0', '0.3.0'])), |
| 516 | }) as unknown as typeof fetch, |
| 517 | }); |
| 518 | const { checkForUpdate } = createUpdateChecker(config); |
| 519 | |
| 520 | yield* checkForUpdate; |
| 521 | |
| 522 | expect(existsSync(config.stateFile)).toBe(true); |
| 523 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 524 | expect(state.latestVersion).toBe('0.4.0'); |
| 525 | }).pipe(Effect.provide(PlatformLayers)) |
| 526 | ); |
| 527 | |
| 528 | it.effect('fetches when cache file is corrupt', () => |
| 529 | Effect.gen(function* () { |
| 530 | const config = makeConfig({ |
| 531 | fetchFn: vi.fn().mockResolvedValue({ |
| 532 | ok: true, |
| 533 | json: () => Promise.resolve(makeReleasesPayload(['0.5.0'])), |
| 534 | }) as unknown as typeof fetch, |
| 535 | }); |
| 536 | mkdirSync(dirname(config.stateFile), { recursive: true }); |
| 537 | writeFileSync(config.stateFile, 'garbage'); |
| 538 | const { checkForUpdate } = createUpdateChecker(config); |
| 539 | |
| 540 | yield* checkForUpdate; |
| 541 | |
| 542 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 543 | expect(state.latestVersion).toBe('0.5.0'); |
| 544 | }).pipe(Effect.provide(PlatformLayers)) |
| 545 | ); |
| 546 | |
| 547 | it.effect( |
| 548 | 'still writes lastChecked when no CLI releases with the required binary are found', |
| 549 | () => |
| 550 | Effect.gen(function* () { |
| 551 | const config = makeConfig({ |
| 552 | fetchFn: vi.fn().mockResolvedValue({ |
| 553 | ok: true, |
| 554 | json: () => |
| 555 | Promise.resolve([ |
| 556 | { |
| 557 | tag_name: '@composio/core@1.0.0', |
| 558 | assets: [{ name: 'composio-darwin-aarch64.zip' }], |
| 559 | }, |
| 560 | ]), |
| 561 | }) as unknown as typeof fetch, |
| 562 | }); |
| 563 | const { checkForUpdate } = createUpdateChecker(config); |
| 564 | |
| 565 | yield* checkForUpdate; |
| 566 | |
| 567 | expect(existsSync(config.stateFile)).toBe(true); |
| 568 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 569 | expect(state.lastChecked).toBeDefined(); |
| 570 | // Falls back to currentVersion since no previous state and no matching releases found |
| 571 | expect(state.latestVersion).toBe(config.currentVersion); |
| 572 | }).pipe(Effect.provide(PlatformLayers)) |
| 573 | ); |
| 574 | |
| 575 | it.effect( |
| 576 | 'preserves previous latestVersion when no CLI releases with the required binary are found', |
| 577 | () => |
| 578 | Effect.gen(function* () { |
| 579 | const config = makeConfig({ |
| 580 | fetchFn: vi.fn().mockResolvedValue({ |
| 581 | ok: true, |
| 582 | json: () => |
| 583 | Promise.resolve([ |
| 584 | { |
| 585 | tag_name: '@composio/core@1.0.0', |
| 586 | assets: [{ name: 'composio-darwin-aarch64.zip' }], |
| 587 | }, |
| 588 | ]), |
| 589 | }) as unknown as typeof fetch, |
| 590 | }); |
| 591 | const stale = staleLastChecked; |
| 592 | writeState(config, { lastChecked: stale, latestVersion: '0.3.0' }); |
| 593 | const { checkForUpdate } = createUpdateChecker(config); |
| 594 | |
| 595 | yield* checkForUpdate; |
| 596 | |
| 597 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 598 | expect(state.latestVersion).toBe('0.3.0'); |
| 599 | expect(new Date(state.lastChecked).getTime()).toBeGreaterThan(new Date(stale).getTime()); |
| 600 | }).pipe(Effect.provide(PlatformLayers)) |
| 601 | ); |
| 602 | |
| 603 | it.effect('does not create authoritative state after an HTTP error', () => |
| 604 | Effect.gen(function* () { |
| 605 | const config = makeConfig({ |
| 606 | fetchFn: vi.fn().mockResolvedValue({ |
| 607 | ok: false, |
| 608 | status: 500, |
| 609 | }) as unknown as typeof fetch, |
| 610 | }); |
| 611 | const { checkForUpdate } = createUpdateChecker(config); |
| 612 | |
| 613 | // Should not fail |
| 614 | yield* checkForUpdate; |
| 615 | |
| 616 | expect(existsSync(config.stateFile)).toBe(false); |
| 617 | }).pipe(Effect.provide(PlatformLayers)) |
| 618 | ); |
| 619 | |
| 620 | it.effect('does not create authoritative state after a network error', () => |
| 621 | Effect.gen(function* () { |
| 622 | const config = makeConfig({ |
| 623 | fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch, |
| 624 | }); |
| 625 | const { checkForUpdate } = createUpdateChecker(config); |
| 626 | |
| 627 | yield* checkForUpdate; |
| 628 | |
| 629 | expect(existsSync(config.stateFile)).toBe(false); |
| 630 | }).pipe(Effect.provide(PlatformLayers)) |
| 631 | ); |
| 632 | |
| 633 | it.effect('throttles repeated network errors without creating authoritative state', () => |
| 634 | Effect.gen(function* () { |
| 635 | const fetchFn = vi.fn().mockRejectedValue(new Error('DNS failed')); |
| 636 | const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch }); |
| 637 | const { checkForUpdate } = createUpdateChecker(config); |
| 638 | |
| 639 | yield* checkForUpdate; |
| 640 | yield* checkForUpdate; |
| 641 | |
| 642 | expect(fetchFn).toHaveBeenCalledOnce(); |
| 643 | expect(existsSync(config.stateFile)).toBe(false); |
| 644 | expect(existsSync(`${config.stateFile}.attempt`)).toBe(true); |
| 645 | }).pipe(Effect.provide(PlatformLayers)) |
| 646 | ); |
| 647 | |
| 648 | it.effect('preserves stale successful state after a network error', () => |
| 649 | Effect.gen(function* () { |
| 650 | const config = makeConfig({ |
| 651 | fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch, |
| 652 | }); |
| 653 | const previousState: UpdateCheckState = { |
| 654 | lastChecked: staleLastChecked, |
| 655 | latestVersion: '0.3.0', |
| 656 | }; |
| 657 | writeState(config, previousState); |
| 658 | const { checkForUpdate } = createUpdateChecker(config); |
| 659 | |
| 660 | yield* checkForUpdate; |
| 661 | |
| 662 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 663 | expect(state).toEqual(previousState); |
| 664 | }).pipe(Effect.provide(PlatformLayers)) |
| 665 | ); |
| 666 | |
| 667 | it.effect('does not let an older failed check supersede successful state', () => |
| 668 | Effect.gen(function* () { |
| 669 | const failedResponse = makeDeferred<Response>(); |
| 670 | const failedRequestStarted = makeDeferred<void>(); |
| 671 | const failingConfig = makeConfig({ |
| 672 | fetchFn: vi.fn(() => { |
| 673 | failedRequestStarted.resolve(); |
| 674 | return failedResponse.promise; |
| 675 | }), |
| 676 | }); |
| 677 | const successfulConfig = makeConfig({ |
| 678 | fetchFn: vi.fn().mockResolvedValue({ |
| 679 | ok: true, |
| 680 | json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])), |
| 681 | }) as unknown as typeof fetch, |
| 682 | }); |
| 683 | const failingFiber = yield* Effect.forkChild( |
| 684 | createUpdateChecker(failingConfig).checkForUpdate |
| 685 | ); |
| 686 | |
| 687 | yield* Effect.promise(() => failedRequestStarted.promise); |
| 688 | const successfulAt = new Date(pinnedNow.getTime() + 60_000); |
| 689 | yield* Effect.sync(() => vi.setSystemTime(successfulAt)); |
| 690 | yield* createUpdateChecker(successfulConfig).checkForUpdate; |
| 691 | yield* Effect.sync(() => vi.setSystemTime(new Date(successfulAt.getTime() + 60_000))); |
| 692 | yield* Effect.sync(() => failedResponse.reject(new Error('transient failure'))); |
| 693 | yield* Fiber.join(failingFiber); |
| 694 | |
| 695 | const state: UpdateCheckState = JSON.parse(readFileSync(failingConfig.stateFile, 'utf-8')); |
| 696 | expect(state).toEqual({ |
| 697 | lastChecked: successfulAt.toISOString(), |
| 698 | latestVersion: '0.3.0', |
| 699 | }); |
| 700 | expect(JSON.parse(readFileSync(`${failingConfig.stateFile}.attempt`, 'utf-8'))).toEqual({ |
| 701 | lastAttempted: pinnedNow.toISOString(), |
| 702 | }); |
| 703 | |
| 704 | const recoveryFetch = vi.fn().mockResolvedValue({ |
| 705 | ok: true, |
| 706 | json: () => Promise.resolve(makeReleasesPayload(['0.4.0'])), |
| 707 | }); |
| 708 | yield* Effect.sync(() => |
| 709 | vi.setSystemTime(new Date(successfulAt.getTime() + failingConfig.checkIntervalMs + 1)) |
| 710 | ); |
| 711 | yield* createUpdateChecker(makeConfig({ fetchFn: recoveryFetch as unknown as typeof fetch })) |
| 712 | .checkForUpdate; |
| 713 | |
| 714 | expect(recoveryFetch).toHaveBeenCalledOnce(); |
| 715 | const refreshedState: UpdateCheckState = JSON.parse( |
| 716 | readFileSync(failingConfig.stateFile, 'utf-8') |
| 717 | ); |
| 718 | expect(refreshedState.latestVersion).toBe('0.4.0'); |
| 719 | expect(existsSync(`${failingConfig.stateFile}.attempt`)).toBe(false); |
| 720 | }).pipe(Effect.provide(PlatformLayers)) |
| 721 | ); |
| 722 | |
| 723 | it.effect('sends Authorization header when accessToken is set', () => |
| 724 | Effect.gen(function* () { |
| 725 | const fetchFn = vi.fn().mockResolvedValue({ |
| 726 | ok: true, |
| 727 | json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])), |
| 728 | }); |
| 729 | const config = makeConfig({ |
| 730 | accessToken: 'ghp_secret123', |
| 731 | fetchFn: fetchFn as unknown as typeof fetch, |
| 732 | }); |
| 733 | const { checkForUpdate } = createUpdateChecker(config); |
| 734 | |
| 735 | yield* checkForUpdate; |
| 736 | |
| 737 | expect(fetchFn).toHaveBeenCalledOnce(); |
| 738 | const [, init] = fetchFn.mock.calls[0]; |
| 739 | expect(init.headers.Authorization).toBe('Bearer ghp_secret123'); |
| 740 | }).pipe(Effect.provide(PlatformLayers)) |
| 741 | ); |
| 742 | |
| 743 | it.effect('does not send Authorization header when accessToken is undefined', () => |
| 744 | Effect.gen(function* () { |
| 745 | const fetchFn = vi.fn().mockResolvedValue({ |
| 746 | ok: true, |
| 747 | json: () => Promise.resolve(makeReleasesPayload(['0.2.1'])), |
| 748 | }); |
| 749 | const config = makeConfig({ |
| 750 | accessToken: undefined, |
| 751 | fetchFn: fetchFn as unknown as typeof fetch, |
| 752 | }); |
| 753 | const { checkForUpdate } = createUpdateChecker(config); |
| 754 | |
| 755 | yield* checkForUpdate; |
| 756 | |
| 757 | const [, init] = fetchFn.mock.calls[0]; |
| 758 | expect(init.headers.Authorization).toBeUndefined(); |
| 759 | }).pipe(Effect.provide(PlatformLayers)) |
| 760 | ); |
| 761 | }); |
| 762 | |
| 763 | // ── Integration: real HTTP server ─────────────────────────────────────── |
| 764 | |
| 765 | describe('checkForUpdate with real HTTP', () => { |
| 766 | it.effect('fetches from a real server and writes state', () => |
| 767 | withHttpServerEffect( |
| 768 | (_req, res) => { |
| 769 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 770 | res.end(JSON.stringify(makeReleasesPayload(['0.1.26', '0.2.0', '0.2.1']))); |
| 771 | }, |
| 772 | baseUrl => |
| 773 | Effect.gen(function* () { |
| 774 | const config = makeConfig({ releasesUrl: baseUrl, fetchFn: fetch }); |
| 775 | const { checkForUpdate } = createUpdateChecker(config); |
| 776 | |
| 777 | yield* checkForUpdate; |
| 778 | |
| 779 | const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8')); |
| 780 | expect(state.latestVersion).toBe('0.2.1'); |
| 781 | }) |
| 782 | ).pipe(Effect.provide(PlatformLayers)) |
| 783 | ); |
| 784 | |
| 785 | it.effect('passes Authorization header to the server', () => { |
| 786 | let receivedAuth: string | undefined; |
| 787 | |
| 788 | return withHttpServerEffect( |
| 789 | (req, res) => { |
| 790 | receivedAuth = req.headers.authorization; |
| 791 | res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 792 | res.end(JSON.stringify(makeReleasesPayload(['0.2.1']))); |
| 793 | }, |
| 794 | baseUrl => |
| 795 | Effect.gen(function* () { |
| 796 | const config = makeConfig({ |
| 797 | releasesUrl: baseUrl, |
| 798 | accessToken: 'ghp_test_token', |
| 799 | fetchFn: fetch, |
| 800 | }); |
| 801 | const { checkForUpdate } = createUpdateChecker(config); |
| 802 | |
| 803 | yield* checkForUpdate; |
| 804 | |
| 805 | expect(receivedAuth).toBe('Bearer ghp_test_token'); |
| 806 | }) |
| 807 | ).pipe(Effect.provide(PlatformLayers)); |
| 808 | }); |
| 809 | }); |