From a3303536fcc3dc38d1b4a4c94235d25fea44c2a5 Mon Sep 17 00:00:00 2001 From: Evan Sosenko Date: Thu, 19 Nov 2026 10:53:34 -0800 Subject: [PATCH 1/4] Wait for CLI action attempts by default --- README.md | 39 ++++ src/lib/args/parse.test.ts | 82 +++++++ src/lib/args/parse.ts | 63 +++++- src/lib/commands/api-command.ts | 18 +- src/lib/commands/spec.ts | 36 ++++ src/lib/http/api.ts | 61 ++++-- src/lib/http/follow-ups.ts | 8 +- src/lib/http/memory-seam-api.ts | 62 ++++-- src/lib/http/request.ts | 9 +- src/lib/interactions/action-attempt-poll.ts | 34 --- src/lib/interactions/index.ts | 1 - test/cli.test.ts | 200 ++++++++++++++++- test/commands/api-command.test.ts | 160 ++++++++++++++ test/fixtures/action-attempt.ts | 20 ++ test/fixtures/blueprint.ts | 42 ++++ test/http/request.test.ts | 225 +++++++++++++++++++- test/render/completion.test.ts | 16 ++ test/render/help.test.ts | 15 ++ 18 files changed, 1000 insertions(+), 91 deletions(-) delete mode 100644 src/lib/interactions/action-attempt-poll.ts create mode 100644 test/commands/api-command.test.ts create mode 100644 test/fixtures/action-attempt.ts diff --git a/README.md b/README.md index f66e1089..54fbbafa 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,45 @@ seam devices list > devices.json seam devices list | jq '.devices[].device_id' ``` +### Action attempts + +Commands returning a single `action_attempt` wait automatically until it +succeeds or fails, in both interactive and non-interactive modes. This also +applies to `seam action-attempts get`, but not to lists of action attempts. +`--non-interactive` controls prompts only. + +```bash +# Wait, then print one full action attempt, including its result +seam locks unlock-door --device-id "$MY_DOOR" + +# Return the initial action attempt immediately, without polling +seam locks unlock-door --device-id "$MY_DOOR" --no-wait-for-action-attempt +``` + +`--wait-for-action-attempt` explicitly selects the default; +`--no-wait-for-action-attempt` opts out. If repeated, the last form wins. +The wait timeout is **10 seconds**, with a **1 second** polling interval, +matching native SDK defaults. Override these with +`--action-attempt-timeout ` and +`--action-attempt-polling-interval `. Both accept finite positive +numbers; fractional seconds are supported. Timing flags have no effect when +waiting is disabled, but their values must still be valid. + +Successful waiting prints exactly one response: +`{ "action_attempt": }`, not just its +`result`. An action failure or wait timeout exits **1**, with diagnostics on +stderr and no result on stdout. HTTP errors (including polling errors) retain +the usual `{ "error": ... }` stdout payload and exit **1**. With opt-out, an +HTTP-successful request exits **0** and prints its initial action attempt, +even if it is pending or already errored. + +Waiting adds latency compared with older CLI versions that returned pending +attempts immediately; use the opt-out to retain that behavior in scripts. +The timeout is a polling budget, not a strict end-to-end HTTP deadline. +A timeout or Ctrl-C stops local waiting, not the server-side action: its +outcome may still be unknown, so do not blindly retry a physical action. +Raw HTTP callers must still poll for themselves. + ### Pagination Every command that paginates accepts `--page-cursor` to select a page of diff --git a/src/lib/args/parse.test.ts b/src/lib/args/parse.test.ts index 17007b5f..8f5794cf 100644 --- a/src/lib/args/parse.test.ts +++ b/src/lib/args/parse.test.ts @@ -2,9 +2,11 @@ import type { ParsedArgs } from 'minimist' import { expect, test } from 'vitest' import { + getActionAttemptWaitOptions, getInteractivity, parseCliArgs, toArgName, + toArgParams, toGivenArgName, toParameterName, } from './parse.js' @@ -73,6 +75,86 @@ test('parseCliArgs: reads a page cursor exactly as given', () => { ).toBe('0755') }) +test.each([ + [[], undefined], + [['--wait-for-action-attempt'], true], + [['--no-wait-for-action-attempt'], false], + [['--wait-for-action-attempt', '--no-wait-for-action-attempt'], false], + [['--no-wait-for-action-attempt', '--wait-for-action-attempt'], true], +])( + 'parseCliArgs: preserves absent/explicit wait and last-wins order %j', + (flags, expected) => { + // Both the first parse and the endpoint-aware parse use the same CLI controls. + for (const options of [{}, { stringKeys: ['device-id'] }]) { + const args = parseCliArgs( + [...flags, 'locks', 'unlock-door', '--device-id', 'device1'], + options, + ) + expect(args._).toEqual(['locks', 'unlock-door']) + expect(args['wait-for-action-attempt']).toBe(expected) + expect(toArgParams(args)).toEqual({ device_id: 'device1' }) + expect(getActionAttemptWaitOptions(args)).toEqual( + expected === undefined ? {} : { waitForActionAttempt: expected }, + ) + } + }, +) + +test('getActionAttemptWaitOptions: converts seconds once, retaining SDK defaults when absent', () => { + expect(getActionAttemptWaitOptions(parseCliArgs([]))).toEqual({}) + expect( + getActionAttemptWaitOptions( + parseCliArgs([ + '--action-attempt-timeout', + '2.5', + '--action-attempt-polling-interval', + '0.05', + ]), + ), + ).toEqual({ waitForActionAttempt: { timeout: 2500, pollingInterval: 50 } }) + expect( + getActionAttemptWaitOptions( + parseCliArgs([ + '--action-attempt-timeout', + '1', + '--action-attempt-timeout', + '3', + ]), + ), + ).toEqual({ waitForActionAttempt: { timeout: 3000 } }) +}) + +test.each(['action-attempt-timeout', 'action-attempt-polling-interval'])( + 'getActionAttemptWaitOptions: rejects invalid --%s even with opt-out', + (flag) => { + for (const value of ['', '0', '-1', 'NaN', 'Infinity', 'abc', '1e308']) { + expect(() => + getActionAttemptWaitOptions( + parseCliArgs(['--no-wait-for-action-attempt', `--${flag}=${value}`]), + ), + ).toThrow(`--${flag} expects a finite positive number of seconds`) + } + expect(() => + getActionAttemptWaitOptions(parseCliArgs([`--${flag}`])), + ).toThrow() + }, +) + +test('getActionAttemptWaitOptions: opt-out takes precedence over valid timing controls', () => { + const args = parseCliArgs([ + '--wait-for-action-attempt', + '--action-attempt-timeout', + '4', + '--action-attempt-polling-interval', + '.1', + '--no-wait-for-action-attempt', + ]) + expect(getActionAttemptWaitOptions(args)).toEqual({ + waitForActionAttempt: false, + }) + expect(toArgParams(args)).toEqual({}) +}) + test('toArgName: renders a parameter as its argument', () => { expect(toArgName('device_id')).toBe('--device-id') expect(toArgName('code')).toBe('--code') diff --git a/src/lib/args/parse.ts b/src/lib/args/parse.ts index abbbe697..d46aeeb4 100644 --- a/src/lib/args/parse.ts +++ b/src/lib/args/parse.ts @@ -1,5 +1,7 @@ +import type { SeamHttpRequestOptions } from '@seamapi/http' import parseArgs, { type ParsedArgs } from 'minimist' +import { UsageError } from 'lib/errors.js' import type { AuthOverrides } from 'lib/overrides.js' /** @@ -31,6 +33,9 @@ export const interactivityFlags: string[] = [ */ export const cliFlags: string[] = [ ...interactivityFlags, + 'wait_for_action_attempt', + 'action_attempt_timeout', + 'action_attempt_polling_interval', 'endpoint', 'h', 'help', @@ -57,13 +62,15 @@ export interface ParseCliArgsOptions { export const parseCliArgs = ( argv: string[], { stringKeys = [], booleanKeys = [] }: ParseCliArgsOptions = {}, -): ParsedArgs => - parseArgs(argv, { +): ParsedArgs => { + const args = parseArgs(argv, { // A page cursor and a code are opaque even before the endpoint's own // parameter types are known, so always keep them exactly as given. The // overrides are read as given for the same reason: a URL or an id is // never a number, however it happens to be spelled. string: [ + 'action-attempt-timeout', + 'action-attempt-polling-interval', 'code', 'endpoint', 'page-cursor', @@ -72,11 +79,61 @@ export const parseCliArgs = ( 'workspace_id', ...stringKeys, ], - boolean: ['non-interactive', 'interactive', 'json', ...booleanKeys], + boolean: [ + 'non-interactive', + 'interactive', + 'json', + 'wait-for-action-attempt', + ...booleanKeys, + ], + // Do not confuse minimist's implicit false with an explicit opt-out. + default: { 'wait-for-action-attempt': null }, // Deliberately not aliased to -n, which is reserved for a future // --dry-run flag. alias: { 'non-interactive': 'y', interactive: 'i' }, }) + if (args['wait-for-action-attempt'] === null) { + delete args['wait-for-action-attempt'] + } + return args +} + +/** Validate seconds at the CLI boundary and convert to SDK milliseconds once. */ +export const getActionAttemptWaitOptions = ( + args: ParsedArgs, +): Pick => { + const timeout = readDuration( + args['action-attempt-timeout'], + 'action-attempt-timeout', + ) + const pollingInterval = readDuration( + args['action-attempt-polling-interval'], + 'action-attempt-polling-interval', + ) + const wait = args['wait-for-action-attempt'] as boolean | undefined + if (wait === false) return { waitForActionAttempt: false } + if (timeout === undefined && pollingInterval === undefined) { + return wait === undefined ? {} : { waitForActionAttempt: wait } + } + return { + waitForActionAttempt: { + ...(timeout === undefined ? {} : { timeout }), + ...(pollingInterval === undefined ? {} : { pollingInterval }), + }, + } +} + +const readDuration = (value: unknown, flag: string): number | undefined => { + if (value === undefined) return undefined + const seconds = Number(Array.isArray(value) ? value.at(-1) : value) + const milliseconds = seconds * 1_000 + if (!Number.isFinite(milliseconds) || milliseconds <= 0) { + throw new UsageError( + `--${flag} expects a finite positive number of seconds`, + ) + } + return milliseconds +} /** * The request params among the parsed arguments: every key normalized to diff --git a/src/lib/commands/api-command.ts b/src/lib/commands/api-command.ts index 51b0633d..8290c079 100644 --- a/src/lib/commands/api-command.ts +++ b/src/lib/commands/api-command.ts @@ -1,7 +1,12 @@ import { isDeepStrictEqual as isEqual } from 'node:util' import { coerceArgParams } from 'lib/args/coerce.js' -import { parseCliArgs, toArgName, toArgParams } from 'lib/args/parse.js' +import { + getActionAttemptWaitOptions, + parseCliArgs, + toArgName, + toArgParams, +} from 'lib/args/parse.js' import { assertRequiredParams } from 'lib/args/validate.js' import { getCommandBlueprintDef, @@ -36,9 +41,11 @@ export const executeApiCommand = async ( const stringKeys = parameters .filter(({ format }) => format !== 'boolean' && format !== 'number') .flatMap(({ name }) => [name, name.replace(/_/g, '-')]) + const args = parseCliArgs(invocation.argv, { stringKeys }) + const waitOptions = getActionAttemptWaitOptions(args) const { params: argParams, issues } = coerceArgParams( parameters, - toArgParams(parseCliArgs(invocation.argv, { stringKeys })), + toArgParams(args), ) if (issues.length > 0) { @@ -83,7 +90,12 @@ export const executeApiCommand = async ( const api = await ctx.api() const body = await requestSeamApi( - { path: apiPath, params, responseKey: getResponseKey(path, ctx) }, + { + path: apiPath, + params, + responseKey: getResponseKey(path, ctx), + ...waitOptions, + }, { api, output: ctx.output }, ) diff --git a/src/lib/commands/spec.ts b/src/lib/commands/spec.ts index 49a88629..1a851a9a 100644 --- a/src/lib/commands/spec.ts +++ b/src/lib/commands/spec.ts @@ -69,6 +69,42 @@ export interface CommandSpec { } export const globalFlags: CommandFlag[] = [ + { + long: 'wait-for-action-attempt', + short: null, + description: + 'Wait for action attempts to succeed or fail (default in all modes).', + values: [], + takesValue: false, + isRequired: false, + }, + { + long: 'no-wait-for-action-attempt', + short: null, + description: + 'Return the initial action attempt without waiting or polling.', + values: [], + takesValue: false, + isRequired: false, + }, + { + long: 'action-attempt-timeout', + short: null, + description: + 'Action-attempt wait timeout in seconds (positive number, default 10).', + values: [], + takesValue: true, + isRequired: false, + }, + { + long: 'action-attempt-polling-interval', + short: null, + description: + 'Action-attempt polling interval in seconds (positive number, default 1; fractions allowed).', + values: [], + takesValue: true, + isRequired: false, + }, { long: 'endpoint', short: null, diff --git a/src/lib/http/api.ts b/src/lib/http/api.ts index 9381e663..1c3a9675 100644 --- a/src/lib/http/api.ts +++ b/src/lib/http/api.ts @@ -1,10 +1,17 @@ -import { type SeamHttp, SeamHttpRequest } from '@seamapi/http' +import { + type SeamHttp, + SeamHttpRequest, + type SeamHttpRequestOptions, +} from '@seamapi/http' import type { AuthContext } from 'lib/context.js' import { getSeam } from './client.js' -export interface ApiRequestOptions { +export interface ApiRequestOptions extends Pick< + SeamHttpRequestOptions, + 'waitForActionAttempt' +> { path: string params: Record /** Response key documented for the endpoint, e.g., `devices`. */ @@ -15,14 +22,15 @@ export interface ApiRequestOptions { * A prepared call to the Seam API: inspectable before it is sent, e.g., to * report the URL, then sent with {@link SeamApiRequest.fetchResponse}. * - * The real implementation is the SDK's own `SeamHttpRequest`; sending one - * rejects with a `SeamHttpApiError` when the API reports an error. + * Uses the SDK's cached request and resolver, retaining the response wrapper. + * HTTP failures reject with `SeamHttpApiError`; action failures and timeouts + * reject with the SDK's action-attempt errors before returning any payload. */ export interface SeamApiRequest { readonly url: URL readonly method: string readonly body: unknown - /** Send the request and return the full response body. */ + /** Send once, wait if applicable, and return the full response body. */ fetchResponse: () => Promise } @@ -43,16 +51,41 @@ export class HttpSeamApi implements SeamApi { path, params, responseKey, - }: ApiRequestOptions): SeamApiRequest => - new SeamHttpRequest, string | undefined>( - this.seam, - { - pathname: path, - method: 'POST', - body: params, - responseKey: responseKey ?? undefined, + waitForActionAttempt, + }: ApiRequestOptions): SeamApiRequest => { + const request = new SeamHttpRequest< + Record, + string | undefined + >(this.seam, { + pathname: path, + method: 'POST', + body: params, + responseKey: responseKey ?? undefined, + options: + waitForActionAttempt === undefined ? {} : { waitForActionAttempt }, + actionAttempts: { + get: (params) => + this.seam.actionAttempts.get(params, { waitForActionAttempt: false }), }, - ) + }) + + return { + url: request.url, + method: request.method, + body: request.body, + fetchResponse: async () => { + const response = await request.fetchResponse() + if ( + responseKey !== 'action_attempt' || + waitForActionAttempt === false + ) { + return response + } + // execute() reuses the cached submission and runs the SDK resolver. + return { ...response, action_attempt: await request.execute() } + }, + } + } } export const createSeamApi = async (auth?: AuthContext): Promise => { diff --git a/src/lib/http/follow-ups.ts b/src/lib/http/follow-ups.ts index a262a98f..601137f2 100644 --- a/src/lib/http/follow-ups.ts +++ b/src/lib/http/follow-ups.ts @@ -1,11 +1,9 @@ import type { CliContext } from 'lib/context.js' import { isInsideWebBrowser } from 'lib/env.js' -import { interactForActionAttemptPoll } from 'lib/interactions/index.js' import { promptConfirm } from 'lib/prompt.js' /** - * Follow-ups a response may call for: opening a connect webview in the - * browser, and offering to poll a pending action attempt. + * Follow-ups a response may call for: opening a connect webview in the browser. */ export const runResponseFollowUps = async ( data: any, @@ -16,10 +14,6 @@ export const runResponseFollowUps = async ( if (data?.connect_webview) { await handleConnectWebview(data.connect_webview, isNonInteractive) } - - if (data?.action_attempt && !isNonInteractive) { - await interactForActionAttemptPoll(data.action_attempt) - } } const handleConnectWebview = async ( diff --git a/src/lib/http/memory-seam-api.ts b/src/lib/http/memory-seam-api.ts index 99b74a68..e63e85e9 100644 --- a/src/lib/http/memory-seam-api.ts +++ b/src/lib/http/memory-seam-api.ts @@ -1,43 +1,65 @@ -import { SeamHttpApiError, SeamHttpInvalidInputError } from '@seamapi/http' +import { + SeamHttp, + SeamHttpApiError, + SeamHttpInvalidInputError, +} from '@seamapi/http' -import type { ApiRequestOptions, SeamApi, SeamApiRequest } from './api.js' +import { HttpSeamApi } from './api.js' export interface MemorySeamApiResponse { status: number data: unknown } +type MemoryRoute = MemorySeamApiResponse | MemorySeamApiResponse[] | Error + /** - * A real {@link SeamApi} answering from a routes table and recording every - * request, for tests: the in-process mirror of the e2e suite's HTTP server. - * Error statuses reject with the SDK's own error classes, exactly as the - * real transport does. + * The real API adapter over an in-memory wire: exercises the SDK's request + * cache and action-attempt resolver without HTTP or a second polling loop. */ -export class MemorySeamApi implements SeamApi { +export class MemorySeamApi extends HttpSeamApi { /** Every request sent, in order — assert on the outbound messages. */ readonly requests: Array<{ path: string; params: Record }> = [] - constructor(private readonly routes: Record) {} + constructor(routes: Record) { + const seam = new SeamHttp({ + endpoint: 'https://memory.seam.example', + apiKey: 'seam_memory', + }) + super(seam) - createRequest = ({ path, params }: ApiRequestOptions): SeamApiRequest => ({ - url: new URL(`https://memory.seam.example${path}`), - method: 'POST', - body: params, - fetchResponse: async () => { + seam.client.defaults.adapter = async (config) => { + const path = config.url ?? '' + const params = + config.params ?? + (typeof config.data === 'string' + ? JSON.parse(config.data) + : config.data) ?? + {} this.requests.push({ path, params }) - const route = this.routes[path] ?? { + const configured = routes[path] + const route = (Array.isArray(configured) + ? configured.length > 1 + ? configured.shift() + : configured[0] + : configured) ?? { status: 404, data: { error: { type: 'not_found', message: 'Not Found' } }, } - if (route.status >= 400) { - throw toSeamHttpError(route) + if (route instanceof Error) throw route + if (route.status >= 400) throw toSeamHttpError(route) + return { + data: route.data, + status: route.status, + statusText: 'OK', + headers: {}, + config, } - return route.data - }, - }) + } + } } const toSeamHttpError = (route: MemorySeamApiResponse): SeamHttpApiError => { @@ -50,5 +72,5 @@ const toSeamHttpError = (route: MemorySeamApiResponse): SeamHttpApiError => { } export const createMemorySeamApi = ( - routes: Record, + routes: Record, ): MemorySeamApi => new MemorySeamApi(routes) diff --git a/src/lib/http/request.ts b/src/lib/http/request.ts index 95a3ab80..c8eca9ae 100644 --- a/src/lib/http/request.ts +++ b/src/lib/http/request.ts @@ -5,14 +5,9 @@ import type { Output } from 'lib/output/output.js' import { selectResponsePayload } from 'lib/output/select-response-payload.js' import { withLoading } from 'lib/output/with-loading.js' -import type { SeamApi } from './api.js' +import type { ApiRequestOptions, SeamApi } from './api.js' -export interface RequestSeamApiOptions { - path: string - params: Record - /** Response key for the endpoint, used to trim the reported payload. */ - responseKey?: string | null | undefined -} +export type RequestSeamApiOptions = ApiRequestOptions export interface RequestSeamApiDependencies { api: SeamApi diff --git a/src/lib/interactions/action-attempt-poll.ts b/src/lib/interactions/action-attempt-poll.ts deleted file mode 100644 index 7e5734d2..00000000 --- a/src/lib/interactions/action-attempt-poll.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { ActionAttemptsGetResponse } from '@seamapi/http' - -import { getSeam } from 'lib/http/client.js' -import { getOutput } from 'lib/output/get-output.js' -import { withLoading } from 'lib/output/with-loading.js' -import { promptConfirm } from 'lib/prompt.js' - -export const interactForActionAttemptPoll = async ( - actionAttempt: ActionAttemptsGetResponse['action_attempt'], -) => { - if (actionAttempt.status === 'pending') { - const pollForActionAttempt = await promptConfirm({ - message: "Would you like to poll the action attempt until it's ready?", - initialValue: true, - active: 'yes', - inactive: 'no', - }) - - if (pollForActionAttempt) { - const seam = await getSeam() - const { action_attempt_id: actionAttemptId } = actionAttempt - - const updatedActionAttempt = await withLoading( - 'Polling action attempt...', - () => - seam.actionAttempts.get( - { action_attempt_id: actionAttemptId }, - { waitForActionAttempt: { pollingInterval: 240, timeout: 10_000 } }, - ), - ) - getOutput().data({ action_attempt: updatedActionAttempt }) - } - } -} diff --git a/src/lib/interactions/index.ts b/src/lib/interactions/index.ts index cc671f21..97e810af 100644 --- a/src/lib/interactions/index.ts +++ b/src/lib/interactions/index.ts @@ -2,7 +2,6 @@ export * from './access-code.js' export * from './acs-entrance.js' export * from './acs-system.js' export * from './acs-user.js' -export * from './action-attempt-poll.js' export * from './array.js' export * from './blueprint-object.js' export * from './command-params.js' diff --git a/test/cli.test.ts b/test/cli.test.ts index 27e982c0..fa15c463 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -7,6 +7,11 @@ import { fileURLToPath } from 'node:url' import { execa } from 'execa' import { afterAll, beforeAll, expect, test } from 'vitest' +import { + failedActionAttempt, + pendingActionAttempt, + successfulActionAttempt, +} from './fixtures/action-attempt.js' import { testBlueprint } from './fixtures/blueprint.js' const projectRoot = fileURLToPath(new URL('..', import.meta.url)) @@ -36,6 +41,10 @@ let requests: Array<{ headers: Record }> = [] let failNextRequest = false +let initialActionAttempt = pendingActionAttempt +let polledActionAttempt: unknown = successfulActionAttempt +let failActionPoll = false +let onActionPoll: (() => void) | undefined beforeAll(async () => { server = createServer((req, res) => { @@ -55,8 +64,31 @@ beforeAll(async () => { return } + const path = new URL(req.url ?? '', 'http://localhost').pathname + if ( + path === '/action_attempts/get' && + req.method === 'GET' && + failActionPoll + ) { + failActionPoll = false + res.writeHead(400, { 'content-type': 'application/json' }) + res.end(JSON.stringify(errorResponse)) + return + } + const payload = + path === '/locks/unlock_door' || + (path === '/action_attempts/get' && req.method === 'POST') + ? { action_attempt: initialActionAttempt, ok: true } + : path === '/action_attempts/get' + ? { action_attempt: polledActionAttempt, ok: true } + : path === '/action_attempts/list' + ? { action_attempts: [pendingActionAttempt], ok: true } + : devicesListResponse res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify(devicesListResponse)) + res.end(JSON.stringify(payload)) + if (path === '/action_attempts/get' && req.method === 'GET') { + onActionPoll?.() + } }) }) @@ -195,6 +227,172 @@ test('cli: writes only the response to stdout as json', async () => { expect(stderr).not.toContain('device1') }) +test.for([[], ['-y'], ['--wait-for-action-attempt']])( + 'cli: waits by default with %j and reuses resolved auth for polling', + async (flags) => { + requests = [] + initialActionAttempt = pendingActionAttempt + polledActionAttempt = successfulActionAttempt + const { stdout, stderr, exitCode } = await runCli( + [ + ...flags, + 'locks', + 'unlock-door', + '--device-id', + 'device1', + '--action-attempt-timeout', + '1', + '--action-attempt-polling-interval', + '.001', + '--endpoint', + endpoint, + '--workspace-id', + 'workspace_from_flag', + ], + { + configHome: otherEndpointConfigHome, + cacheHome, + env: { + SEAM_CLI_TOKEN: 'seam_at1_from_env', + SEAM_CLI_ENDPOINT: 'http://localhost:1', + SEAM_CLI_WORKSPACE_ID: 'workspace_from_env', + }, + }, + ) + expect(exitCode).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + action_attempt: successfulActionAttempt, + }) + expect(stderr).toBe('') + expect(requests).toHaveLength(2) + expect(requests[0]?.path).toBe('/locks/unlock_door') + expect(requests[0]?.body).toEqual({ device_id: 'device1' }) + const pollUrl = new URL(requests[1]?.path ?? '', endpoint) + expect(pollUrl.pathname).toBe('/action_attempts/get') + expect(pollUrl.searchParams.get('action_attempt_id')).toBe('attempt1') + for (const request of requests) { + expect(request.headers['authorization']).toBe('Bearer seam_at1_from_env') + expect(request.headers['seam-workspace']).toBe('workspace_from_flag') + } + }, +) + +test('cli: explicit opt-out prints pending once without polling or prompts', async () => { + requests = [] + initialActionAttempt = pendingActionAttempt + const { stdout, stderr, exitCode } = await runCli( + [ + '--no-wait-for-action-attempt', + 'locks', + 'unlock-door', + '--device-id', + 'device1', + ], + { cacheHome }, + ) + expect(exitCode).toBe(0) + expect(JSON.parse(stdout)).toEqual({ action_attempt: pendingActionAttempt }) + expect(stderr).toBe('') + expect(requests).toHaveLength(1) + expect(requests[0]?.body).toEqual({ device_id: 'device1' }) +}) + +test('cli: AA failure exits 1 with stderr only; polling HTTP errors keep the error payload', async () => { + requests = [] + polledActionAttempt = failedActionAttempt + const args = [ + 'locks', + 'unlock-door', + '--device-id', + 'device1', + '--action-attempt-polling-interval', + '.001', + ] + const failed = await runCli(args, { cacheHome }) + expect(failed.exitCode).toBe(1) + expect(failed.stdout).toBe('') + expect(failed.stderr).toContain('The device is offline') + expect(requests).toHaveLength(2) + + requests = [] + failActionPoll = true + const httpFailed = await runCli(args, { cacheHome }) + expect(httpFailed.exitCode).toBe(1) + expect(JSON.parse(httpFailed.stdout)).toEqual({ error: errorResponse.error }) + expect(requests).toHaveLength(2) +}) + +test('cli: invalid durations fail before submission even with opt-out', async () => { + requests = [] + const { exitCode, stdout, stderr } = await runCli( + [ + 'locks', + 'unlock-door', + '--device-id', + 'device1', + '--no-wait-for-action-attempt', + '--action-attempt-timeout', + 'Infinity', + ], + { cacheHome }, + ) + expect(exitCode).toBe(1) + expect(stdout).toBe('') + expect(stderr).toContain( + '--action-attempt-timeout expects a finite positive number of seconds', + ) + expect(requests).toEqual([]) +}) + +test('cli: SIGINT during polling stops local waiting without replay or cancellation', async () => { + requests = [] + polledActionAttempt = pendingActionAttempt + const child = execa( + 'node', + [ + '--import', + 'tsx', + entrypoint, + 'locks', + 'unlock-door', + '--device-id', + 'device1', + '--action-attempt-polling-interval', + '.001', + ], + { + cwd: projectRoot, + env: { + XDG_CONFIG_HOME: configHome, + XDG_STATE_HOME: stateHome, + XDG_CACHE_HOME: cacheHome, + SEAM_CLI_ENDPOINT: endpoint, + SEAM_CLI_TOKEN: 'seam_apikey1_token', + SEAM_CLI_WORKSPACE_ID: undefined, + FORCE_COLOR: '0', + }, + input: '', + reject: false, + }, + ) + onActionPoll = () => { + child.kill('SIGINT') + } + try { + const result = await child + expect(result.signal).toBe('SIGINT') + expect(result.stdout).toBe('') + expect(requests).toHaveLength(2) + expect(requests[0]?.path).toBe('/locks/unlock_door') + expect(new URL(requests[1]?.path ?? '', endpoint).pathname).toBe( + '/action_attempts/get', + ) + } finally { + onActionPoll = undefined + child.kill('SIGKILL') + } +}) + test('cli: reads request params piped in as json', async () => { requests = [] const { stdout, exitCode } = await runCli(['devices', 'list'], { diff --git a/test/commands/api-command.test.ts b/test/commands/api-command.test.ts new file mode 100644 index 00000000..ee047246 --- /dev/null +++ b/test/commands/api-command.test.ts @@ -0,0 +1,160 @@ +import { afterEach, expect, test, vi } from 'vitest' + +import { getInteractivity, parseCliArgs } from 'lib/args/parse.js' +import { executeApiCommand } from 'lib/commands/api-command.js' +import { createMemoryConfig } from 'lib/config/memory-config-store.js' +import { type CliContext, resolveAuth } from 'lib/context.js' +import { createMemorySeamApi } from 'lib/http/memory-seam-api.js' +import { createMemoryPrompt } from 'lib/memory-prompt.js' +import { resetOutput, setOutput } from 'lib/output/get-output.js' +import { createMemoryOutput } from 'lib/output/memory-output.js' +import { resetPromptClient, setPromptClient } from 'lib/prompt.js' +import { + pendingActionAttempt, + successfulActionAttempt, +} from 'test/fixtures/action-attempt.js' +import { testBlueprint } from 'test/fixtures/blueprint.js' + +afterEach(() => { + vi.useRealTimers() + resetPromptClient() + resetOutput() +}) + +test.each([ + [[], true, 'json'], + [['--interactive'], true, 'text'], + [['-y'], true, 'json'], + [[], false, 'json'], +] as const)( + 'API commands wait without AA confirmation: flags=%j canPrompt=%s format=%s', + async (flags, canPrompt, format) => { + vi.useFakeTimers() + const memory = createMemoryOutput({ format }) + setOutput(memory.output) + const prompt = createMemoryPrompt(['done']) + setPromptClient(prompt) + const api = createMemorySeamApi({ + '/locks/unlock_door': { + status: 200, + data: { action_attempt: pendingActionAttempt, ok: true }, + }, + '/action_attempts/get': { + status: 200, + data: { action_attempt: successfulActionAttempt, ok: true }, + }, + }) + const argv = ['locks', 'unlock-door', '--device-id', 'device1', ...flags] + const args = parseCliArgs(argv) + const config = createMemoryConfig() + const ctx: CliContext = { + config, + auth: resolveAuth(config), + output: memory.output, + blueprint: testBlueprint, + interactivity: getInteractivity( + { + ...args, + interactive: args['interactive'], + non_interactive: args['non-interactive'], + }, + { canPrompt }, + ), + api: async () => api, + } + const result = executeApiCommand( + { + path: ['locks', 'unlock-door'], + argv, + args, + argParams: {}, + stdinParams: {}, + }, + ctx, + ) + await vi.advanceTimersByTimeAsync(0) + expect(memory.stdout()).toBe('') + await vi.advanceTimersByTimeAsync(1000) + expect(await result).toEqual({ kind: 'done' }) + expect(prompt.questions.map(({ kind }) => kind)).toEqual( + ctx.interactivity === 'interactive' ? ['autocomplete'] : [], + ) + expect(memory.stdout()).toContain('success') + if (format === 'json') { + expect(JSON.parse(memory.stdout())).toEqual({ + action_attempt: successfulActionAttempt, + }) + } else { + expect(memory.stdout()).toContain('result') + expect(memory.stdout()).not.toContain('pending') + } + expect(api.requests).toEqual([ + { path: '/locks/unlock_door', params: { device_id: 'device1' } }, + { + path: '/action_attempts/get', + params: { action_attempt_id: 'attempt1' }, + }, + ]) + }, +) + +test('action-attempts get waits just like SDK reads; opt-out skips follow-ups even in interactive mode', async () => { + vi.useFakeTimers() + const api = createMemorySeamApi({ + '/action_attempts/get': [ + { status: 200, data: { action_attempt: pendingActionAttempt } }, + { status: 200, data: { action_attempt: successfulActionAttempt } }, + ], + }) + const memory = createMemoryOutput({ format: 'json' }) + setOutput(memory.output) + const prompt = createMemoryPrompt() + setPromptClient(prompt) + const config = createMemoryConfig() + const ctx: CliContext = { + config, + auth: resolveAuth(config), + output: memory.output, + blueprint: testBlueprint, + interactivity: 'auto', + api: async () => api, + } + const argv = ['action-attempts', 'get', '--action-attempt-id', 'attempt1'] + const result = executeApiCommand( + { + path: ['action-attempts', 'get'], + argv, + args: parseCliArgs(argv), + argParams: {}, + stdinParams: {}, + }, + ctx, + ) + await vi.runAllTimersAsync() + await result + expect(JSON.parse(memory.stdout())).toEqual({ + action_attempt: successfulActionAttempt, + }) + expect(api.requests).toHaveLength(2) + expect(prompt.questions).toEqual([]) + + const optedOut = [...argv, '--no-wait-for-action-attempt'] + const pendingApi = createMemorySeamApi({ + '/action_attempts/get': { + status: 200, + data: { action_attempt: pendingActionAttempt }, + }, + }) + await executeApiCommand( + { + path: ['action-attempts', 'get'], + argv: optedOut, + args: parseCliArgs(optedOut), + argParams: {}, + stdinParams: {}, + }, + { ...ctx, api: async () => pendingApi }, + ) + expect(pendingApi.requests).toHaveLength(1) + expect(prompt.questions).toEqual([]) +}) diff --git a/test/fixtures/action-attempt.ts b/test/fixtures/action-attempt.ts new file mode 100644 index 00000000..2d8b814e --- /dev/null +++ b/test/fixtures/action-attempt.ts @@ -0,0 +1,20 @@ +export const pendingActionAttempt = { + action_attempt_id: 'attempt1', + action_type: 'UNLOCK_DOOR', + status: 'pending', + result: null, + error: null, +} + +export const successfulActionAttempt = { + ...pendingActionAttempt, + status: 'success', + result: { device_id: 'device1' }, + completed_at: '2026-01-01T00:00:00Z', +} + +export const failedActionAttempt = { + ...pendingActionAttempt, + status: 'error', + error: { type: 'device_offline', message: 'The device is offline' }, +} diff --git a/test/fixtures/blueprint.ts b/test/fixtures/blueprint.ts index 24c44f10..b4f5bccb 100644 --- a/test/fixtures/blueprint.ts +++ b/test/fixtures/blueprint.ts @@ -83,6 +83,48 @@ export const testBlueprint = { }, response: { responseType: 'resource', responseKey: 'access_code' }, }, + { + path: '/locks/unlock_door', + title: 'Unlock Door', + description: 'Unlocks a door.', + request: { + parameters: [ + { + name: 'device_id', + description: 'ID of the device.', + format: 'id', + isRequired: true, + }, + ], + }, + response: { responseType: 'resource', responseKey: 'action_attempt' }, + }, + { + path: '/action_attempts/get', + title: 'Get Action Attempt', + description: 'Gets an action attempt.', + request: { + parameters: [ + { + name: 'action_attempt_id', + description: 'ID of the action attempt.', + format: 'id', + isRequired: true, + }, + ], + }, + response: { responseType: 'resource', responseKey: 'action_attempt' }, + }, + { + path: '/action_attempts/list', + title: 'List Action Attempts', + description: 'Lists action attempts.', + request: { parameters: [] }, + response: { + responseType: 'resource_list', + responseKey: 'action_attempts', + }, + }, ], }, ], diff --git a/test/http/request.test.ts b/test/http/request.test.ts index e74ac2bd..c7e00266 100644 --- a/test/http/request.test.ts +++ b/test/http/request.test.ts @@ -1,8 +1,15 @@ -import { afterEach, beforeEach, expect, test } from 'vitest' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { getActionAttemptWaitOptions, parseCliArgs } from 'lib/args/parse.js' +import { reportErrorAndExit } from 'lib/errors.js' import { createMemorySeamApi } from 'lib/http/memory-seam-api.js' import { requestSeamApi } from 'lib/http/request.js' import { createMemoryOutput } from 'lib/output/memory-output.js' +import { + failedActionAttempt as failed, + pendingActionAttempt as pending, + successfulActionAttempt as success, +} from 'test/fixtures/action-attempt.js' let exitCodeBefore: number | string | undefined @@ -12,8 +19,224 @@ beforeEach(() => { afterEach(() => { process.exitCode = exitCodeBefore + vi.useRealTimers() }) +const response = (actionAttempt: unknown) => ({ + status: 200, + data: { action_attempt: actionAttempt, ok: true }, +}) +const actionOptions = { + path: '/locks/unlock_door', + params: { device_id: 'device1' }, + responseKey: 'action_attempt', +} + +test.each([undefined, true])( + 'requestSeamApi: waits before its sole output with wait=%s, SDK 1s polling', + async (waitForActionAttempt) => { + vi.useFakeTimers() + const api = createMemorySeamApi({ + '/locks/unlock_door': response(pending), + '/action_attempts/get': [response(pending), response(success)], + }) + const memory = createMemoryOutput({ format: 'json' }) + const result = requestSeamApi( + { + ...actionOptions, + ...(waitForActionAttempt === undefined ? {} : { waitForActionAttempt }), + }, + { api, output: memory.output }, + ) + + await vi.advanceTimersByTimeAsync(0) + expect(memory.stdout()).toBe('') + expect(api.requests).toEqual([ + { path: '/locks/unlock_door', params: { device_id: 'device1' } }, + ]) + await vi.advanceTimersByTimeAsync(999) + expect(api.requests).toHaveLength(1) + await vi.advanceTimersByTimeAsync(1) + expect(memory.stdout()).toBe('') + await vi.advanceTimersByTimeAsync(1000) + expect(await result).toEqual({ action_attempt: success, ok: true }) + expect(JSON.parse(memory.stdout())).toEqual({ action_attempt: success }) + expect(memory.stderr()).toBe('') + expect(api.requests).toEqual([ + { path: '/locks/unlock_door', params: { device_id: 'device1' } }, + { + path: '/action_attempts/get', + params: { action_attempt_id: 'attempt1' }, + }, + { + path: '/action_attempts/get', + params: { action_attempt_id: 'attempt1' }, + }, + ]) + }, +) + +test('requestSeamApi: immediate success preserves the full AA and wrapper without polling', async () => { + const api = createMemorySeamApi({ '/locks/unlock_door': response(success) }) + const memory = createMemoryOutput({ format: 'json' }) + await requestSeamApi(actionOptions, { api, output: memory.output }) + expect(JSON.parse(memory.stdout())).toEqual({ action_attempt: success }) + expect(api.requests).toHaveLength(1) +}) + +test.each([pending, failed])( + 'requestSeamApi: opt-out returns HTTP-successful $status AA without polling', + async (initial) => { + const api = createMemorySeamApi({ '/locks/unlock_door': response(initial) }) + const memory = createMemoryOutput({ format: 'json' }) + await requestSeamApi( + { ...actionOptions, waitForActionAttempt: false }, + { api, output: memory.output }, + ) + expect(JSON.parse(memory.stdout())).toEqual({ action_attempt: initial }) + expect(api.requests).toHaveLength(1) + expect(process.exitCode).toBe(exitCodeBefore) + }, +) + +test.each([false, true])( + 'requestSeamApi: terminal AA error has stderr only/exit1 (polled=%s)', + async (polled) => { + vi.useFakeTimers() + const api = createMemorySeamApi({ + '/locks/unlock_door': response(polled ? pending : failed), + '/action_attempts/get': response(failed), + }) + const memory = createMemoryOutput({ format: 'json' }) + const result = requestSeamApi(actionOptions, { + api, + output: memory.output, + }).catch((error) => reportErrorAndExit(error, memory.output)) + await vi.runAllTimersAsync() + await result + expect(memory.stdout()).toBe('') + expect(memory.stderr()).toContain('The device is offline') + expect(process.exitCode).toBe(1) + expect( + api.requests.filter(({ path }) => path === '/locks/unlock_door'), + ).toHaveLength(1) + }, +) + +test.each([ + [[], 10_000, 1000], + [ + [ + '--action-attempt-timeout', + '.1', + '--action-attempt-polling-interval', + '.04', + ], + 100, + 40, + ], +])( + 'requestSeamApi: timeout budget %j uses one resolver and never resubmits', + async (flags, timeout, interval) => { + vi.useFakeTimers() + const api = createMemorySeamApi({ + '/locks/unlock_door': response(pending), + '/action_attempts/get': response(pending), + }) + const memory = createMemoryOutput({ format: 'json' }) + const result = requestSeamApi( + { ...actionOptions, ...getActionAttemptWaitOptions(parseCliArgs(flags)) }, + { api, output: memory.output }, + ).catch((error) => reportErrorAndExit(error, memory.output)) + await vi.advanceTimersByTimeAsync(timeout - 1) + expect(memory.stdout()).toBe('') + expect(memory.stderr()).toBe('') + await vi.advanceTimersByTimeAsync(1) + await result + expect(memory.stdout()).toBe('') + expect(memory.stderr()).toContain( + `Timed out waiting for action attempt after ${timeout}ms`, + ) + expect(process.exitCode).toBe(1) + expect( + api.requests.filter(({ path }) => path === '/locks/unlock_door'), + ).toHaveLength(1) + expect( + api.requests.filter(({ path }) => path === '/action_attempts/get'), + ).toHaveLength(Math.ceil(timeout / interval)) + }, +) + +test.each(['submission', 'poll'])( + 'requestSeamApi: %s HTTP errors keep one structured error payload', + async (stage) => { + vi.useFakeTimers() + const httpError = { + status: 400, + data: { error: { type: 'invalid_input', message: 'Bad request' } }, + } + const api = createMemorySeamApi({ + '/locks/unlock_door': + stage === 'submission' ? httpError : response(pending), + '/action_attempts/get': httpError, + }) + const memory = createMemoryOutput({ format: 'json' }) + const result = requestSeamApi(actionOptions, { api, output: memory.output }) + await vi.runAllTimersAsync() + expect(await result).toBe(null) + expect(JSON.parse(memory.stdout())).toEqual({ error: httpError.data.error }) + expect(process.exitCode).toBe(1) + expect( + api.requests.filter(({ path }) => path === '/locks/unlock_door'), + ).toHaveLength(1) + }, +) + +test('requestSeamApi: polling runtime errors do not emit the pending result or replay', async () => { + vi.useFakeTimers() + const api = createMemorySeamApi({ + '/locks/unlock_door': response(pending), + '/action_attempts/get': new Error('Connection lost'), + }) + const memory = createMemoryOutput({ format: 'json' }) + const result = requestSeamApi(actionOptions, { + api, + output: memory.output, + }).catch((error) => reportErrorAndExit(error, memory.output)) + await vi.runAllTimersAsync() + await result + expect(memory.stdout()).toBe('') + expect(memory.stderr()).toContain('Connection lost') + expect(process.exitCode).toBe(1) + expect(api.requests).toHaveLength(2) +}) + +test.each(['devices', 'action_attempts'])( + 'requestSeamApi: %s lists do not poll nested AAs', + async (responseKey) => { + const api = createMemorySeamApi({ + '/resources/list': { + status: 200, + data: { + [responseKey]: [pending], + pagination: { has_next_page: false }, + ok: true, + }, + }, + }) + const memory = createMemoryOutput({ format: 'json' }) + await requestSeamApi( + { path: '/resources/list', params: {}, responseKey }, + { api, output: memory.output }, + ) + expect(JSON.parse(memory.stdout())).toEqual({ + [responseKey]: [pending], + pagination: { has_next_page: false }, + }) + expect(api.requests).toHaveLength(1) + }, +) + test('requestSeamApi: sends the params and reports the trimmed payload', async () => { const api = createMemorySeamApi({ '/devices/list': { diff --git a/test/render/completion.test.ts b/test/render/completion.test.ts index ed56b7e5..832b67e3 100644 --- a/test/render/completion.test.ts +++ b/test/render/completion.test.ts @@ -65,6 +65,22 @@ test('fish completion: guards each candidate with its command path', () => { expect(script).toContain(`complete -c seam -s h -l help -d`) }) +test.each(completionShells)( + '%s completion: includes only final AA controls', + (shell) => { + const script = renderCompletion(shell, spec) + for (const flag of [ + 'wait-for-action-attempt', + 'no-wait-for-action-attempt', + 'action-attempt-timeout', + 'action-attempt-polling-interval', + ]) { + expect(script).toContain(flag) + } + expect(script).not.toContain('action-attempt-wait-timeout') + }, +) + test.each(completionShells)('%s completion: quotes safely', (shell) => { const script = renderCompletion(shell, spec) // Descriptions are embedded in single-quoted shell strings. diff --git a/test/render/help.test.ts b/test/render/help.test.ts index 3525ec5d..42950040 100644 --- a/test/render/help.test.ts +++ b/test/render/help.test.ts @@ -72,6 +72,21 @@ test('command help: documents the flags of the command', () => { expect(rendered).toContain('-y') }) +test('command help: documents default waiting, opt-out and seconds-based timing controls', () => { + const rendered = helpText('locks', 'unlock-door') + for (const flag of [ + '--wait-for-action-attempt', + '--no-wait-for-action-attempt', + '--action-attempt-timeout', + '--action-attempt-polling-interval', + ]) { + expect(rendered).toContain(flag) + } + expect(rendered).toContain('default in all modes') + expect(rendered).toContain('seconds (positive number, default 10)') + expect(rendered).toContain('default 1; fractions allowed') +}) + test('command help: keeps parameters apart from the CLI options', () => { const rendered = helpText('devices', 'list') From ca6b7765e80a091754a8f2e051e43408336b1616 Mon Sep 17 00:00:00 2001 From: Evan Sosenko Date: Thu, 19 Nov 2026 11:22:47 -0800 Subject: [PATCH 2/4] docs: keep action attempt README guidance concise --- README.md | 34 +++------------------------------- 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 54fbbafa..9608f0cf 100644 --- a/README.md +++ b/README.md @@ -201,42 +201,14 @@ seam devices list | jq '.devices[].device_id' ### Action attempts -Commands returning a single `action_attempt` wait automatically until it -succeeds or fails, in both interactive and non-interactive modes. This also -applies to `seam action-attempts get`, but not to lists of action attempts. -`--non-interactive` controls prompts only. +Action commands wait automatically for the action attempt to succeed or fail, +including in non-interactive mode. To return immediately instead: ```bash -# Wait, then print one full action attempt, including its result -seam locks unlock-door --device-id "$MY_DOOR" - -# Return the initial action attempt immediately, without polling seam locks unlock-door --device-id "$MY_DOOR" --no-wait-for-action-attempt ``` -`--wait-for-action-attempt` explicitly selects the default; -`--no-wait-for-action-attempt` opts out. If repeated, the last form wins. -The wait timeout is **10 seconds**, with a **1 second** polling interval, -matching native SDK defaults. Override these with -`--action-attempt-timeout ` and -`--action-attempt-polling-interval `. Both accept finite positive -numbers; fractional seconds are supported. Timing flags have no effect when -waiting is disabled, but their values must still be valid. - -Successful waiting prints exactly one response: -`{ "action_attempt": }`, not just its -`result`. An action failure or wait timeout exits **1**, with diagnostics on -stderr and no result on stdout. HTTP errors (including polling errors) retain -the usual `{ "error": ... }` stdout payload and exit **1**. With opt-out, an -HTTP-successful request exits **0** and prints its initial action attempt, -even if it is pending or already errored. - -Waiting adds latency compared with older CLI versions that returned pending -attempts immediately; use the opt-out to retain that behavior in scripts. -The timeout is a polling budget, not a strict end-to-end HTTP deadline. -A timeout or Ctrl-C stops local waiting, not the server-side action: its -outcome may still be unknown, so do not blindly retry a physical action. -Raw HTTP callers must still poll for themselves. +Run `seam locks unlock-door --help` for waiting and timing options. ### Pagination From 49cfb3d97e0b868e46716c529168f0ebcdad55b0 Mon Sep 17 00:00:00 2001 From: Evan Sosenko Date: Thu, 19 Nov 2026 11:28:35 -0800 Subject: [PATCH 3/4] no-mistakes(document): Refresh waiting guidance and SDK references --- README.md | 13 +++--------- TESTING.md | 61 +++++++----------------------------------------------- 2 files changed, 11 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index 9608f0cf..f5ad3188 100644 --- a/README.md +++ b/README.md @@ -199,16 +199,9 @@ seam devices list > devices.json seam devices list | jq '.devices[].device_id' ``` -### Action attempts - -Action commands wait automatically for the action attempt to succeed or fail, -including in non-interactive mode. To return immediately instead: - -```bash -seam locks unlock-door --device-id "$MY_DOOR" --no-wait-for-action-attempt -``` - -Run `seam locks unlock-door --help` for waiting and timing options. +Action commands wait automatically, including in non-interactive mode. Pass +`--no-wait-for-action-attempt` to return immediately; run +`seam locks unlock-door --help` for waiting and timing options. ### Pagination diff --git a/TESTING.md b/TESTING.md index be5651e6..8a0734e2 100644 --- a/TESTING.md +++ b/TESTING.md @@ -103,59 +103,14 @@ behavior. The CLI is blueprint-driven and has one chokepoint: preparing a `SeamHttpRequest` for an endpoint path. The port mirrors that — prepare a request, inspect it, send it: -```ts -// src/lib/http/api.ts -export interface SeamApiRequest { - readonly url: URL - readonly method: string - readonly body: unknown - fetchResponse: () => Promise -} - -export interface SeamApi { - createRequest: (options: ApiRequestOptions) => SeamApiRequest -} - -export class HttpSeamApi implements SeamApi { - constructor(private readonly seam: SeamHttp) {} // the only place SeamHttp appears - - createRequest = ({ path, params, responseKey }: ApiRequestOptions) => - new SeamHttpRequest(this.seam, { - pathname: path, - method: 'POST', - body: params, - responseKey: responseKey ?? undefined, - }) -} -``` - -The real request object is the SDK's own `SeamHttpRequest`, so the URL is -inspectable before sending and an error status rejects with the SDK's typed -`SeamHttpApiError`. The fake is the in-process mirror of the e2e server — a -routes table plus a capture — and it rejects with those same SDK error -classes, never an imitation: - -```ts -// src/lib/http/memory-seam-api.ts -export class MemorySeamApi implements SeamApi { - readonly requests: Array<{ path: string; params: Record }> = - [] - - constructor(private readonly routes: Record) {} - - createRequest = ({ path, params }: ApiRequestOptions): SeamApiRequest => ({ - url: new URL(`https://memory.seam.example${path}`), - method: 'POST', - body: params, - fetchResponse: async () => { - this.requests.push({ path, params }) - const route = this.routes[path] - if (route == null || route.status >= 400) throw toSeamHttpError(route) - return route.data - }, - }) -} -``` +See [`SeamApi` and `HttpSeamApi`](src/lib/http/api.ts) for the authoritative +request contract and SDK integration. The adapter keeps the URL inspectable +before sending and uses the SDK resolver for action-attempt waiting. + +[`MemorySeamApi`](src/lib/http/memory-seam-api.ts) runs that same adapter over +an in-memory wire, with a routes table and request capture. SDK request caching, +resolution, and typed errors stay real without an HTTP server or a separate +polling implementation. This keeps transport separate from presentation: the error-status → exit-code behavior is a classical test with zero HTTP: From 632fa6067d18f3fbff8cdc5ac93df391a984d567 Mon Sep 17 00:00:00 2001 From: Evan Sosenko Date: Thu, 19 Nov 2026 11:37:40 -0800 Subject: [PATCH 4/4] Simplify action execution and fixture control flow --- README.md | 5 ++- src/lib/http/api.ts | 60 +++++++++++-------------------- src/lib/http/memory-seam-api.ts | 16 ++++++--- src/lib/http/request.ts | 3 ++ test/cli.test.ts | 18 ++++++---- test/http/memory-seam-api.test.ts | 39 ++++++++++++++++++++ test/http/request.test.ts | 2 +- 7 files changed, 88 insertions(+), 55 deletions(-) create mode 100644 test/http/memory-seam-api.test.ts diff --git a/README.md b/README.md index f5ad3188..10849b28 100644 --- a/README.md +++ b/README.md @@ -199,9 +199,8 @@ seam devices list > devices.json seam devices list | jq '.devices[].device_id' ``` -Action commands wait automatically, including in non-interactive mode. Pass -`--no-wait-for-action-attempt` to return immediately; run -`seam locks unlock-door --help` for waiting and timing options. +The CLI waits for actions to finish by default. To return immediately, pass +`--no-wait-for-action-attempt`. ### Pagination diff --git a/src/lib/http/api.ts b/src/lib/http/api.ts index 1c3a9675..1a60c878 100644 --- a/src/lib/http/api.ts +++ b/src/lib/http/api.ts @@ -20,18 +20,16 @@ export interface ApiRequestOptions extends Pick< /** * A prepared call to the Seam API: inspectable before it is sent, e.g., to - * report the URL, then sent with {@link SeamApiRequest.fetchResponse}. - * - * Uses the SDK's cached request and resolver, retaining the response wrapper. - * HTTP failures reject with `SeamHttpApiError`; action failures and timeouts - * reject with the SDK's action-attempt errors before returning any payload. + * report the URL, then executed through the SDK. */ export interface SeamApiRequest { readonly url: URL readonly method: string readonly body: unknown - /** Send once, wait if applicable, and return the full response body. */ + /** Return the full response body without automatic waiting. */ fetchResponse: () => Promise + /** Return the response resource with SDK automatic action-attempt waiting. */ + execute: () => Promise } /** @@ -52,40 +50,24 @@ export class HttpSeamApi implements SeamApi { params, responseKey, waitForActionAttempt, - }: ApiRequestOptions): SeamApiRequest => { - const request = new SeamHttpRequest< - Record, - string | undefined - >(this.seam, { - pathname: path, - method: 'POST', - body: params, - responseKey: responseKey ?? undefined, - options: - waitForActionAttempt === undefined ? {} : { waitForActionAttempt }, - actionAttempts: { - get: (params) => - this.seam.actionAttempts.get(params, { waitForActionAttempt: false }), + }: ApiRequestOptions): SeamApiRequest => + new SeamHttpRequest, string | undefined>( + this.seam, + { + pathname: path, + method: 'POST', + body: params, + responseKey: responseKey ?? undefined, + options: + waitForActionAttempt === undefined ? {} : { waitForActionAttempt }, + actionAttempts: { + get: (params) => + this.seam.actionAttempts.get(params, { + waitForActionAttempt: false, + }), + }, }, - }) - - return { - url: request.url, - method: request.method, - body: request.body, - fetchResponse: async () => { - const response = await request.fetchResponse() - if ( - responseKey !== 'action_attempt' || - waitForActionAttempt === false - ) { - return response - } - // execute() reuses the cached submission and runs the SDK resolver. - return { ...response, action_attempt: await request.execute() } - }, - } - } + ) } export const createSeamApi = async (auth?: AuthContext): Promise => { diff --git a/src/lib/http/memory-seam-api.ts b/src/lib/http/memory-seam-api.ts index e63e85e9..77e181c7 100644 --- a/src/lib/http/memory-seam-api.ts +++ b/src/lib/http/memory-seam-api.ts @@ -40,11 +40,17 @@ export class MemorySeamApi extends HttpSeamApi { this.requests.push({ path, params }) const configured = routes[path] - const route = (Array.isArray(configured) - ? configured.length > 1 - ? configured.shift() - : configured[0] - : configured) ?? { + let route: MemorySeamApiResponse | Error | undefined + if (Array.isArray(configured)) { + if (configured.length > 1) { + route = configured.shift() + } else { + route = configured[0] + } + } else { + route = configured + } + route ??= { status: 404, data: { error: { type: 'not_found', message: 'Not Found' } }, } diff --git a/src/lib/http/request.ts b/src/lib/http/request.ts index c8eca9ae..d0033af4 100644 --- a/src/lib/http/request.ts +++ b/src/lib/http/request.ts @@ -33,6 +33,9 @@ export const requestSeamApi = async ( let body: unknown try { body = await withLoading('Making request...', async () => { + if (options.responseKey === 'action_attempt') { + return { action_attempt: await request.execute() } + } return await request.fetchResponse() }) } catch (error) { diff --git a/test/cli.test.ts b/test/cli.test.ts index fa15c463..1cdbce30 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -75,15 +75,19 @@ beforeAll(async () => { res.end(JSON.stringify(errorResponse)) return } - const payload = + let payload: unknown + if ( path === '/locks/unlock_door' || (path === '/action_attempts/get' && req.method === 'POST') - ? { action_attempt: initialActionAttempt, ok: true } - : path === '/action_attempts/get' - ? { action_attempt: polledActionAttempt, ok: true } - : path === '/action_attempts/list' - ? { action_attempts: [pendingActionAttempt], ok: true } - : devicesListResponse + ) { + payload = { action_attempt: initialActionAttempt, ok: true } + } else if (path === '/action_attempts/get') { + payload = { action_attempt: polledActionAttempt, ok: true } + } else if (path === '/action_attempts/list') { + payload = { action_attempts: [pendingActionAttempt], ok: true } + } else { + payload = devicesListResponse + } res.writeHead(200, { 'content-type': 'application/json' }) res.end(JSON.stringify(payload)) if (path === '/action_attempts/get' && req.method === 'GET') { diff --git a/test/http/memory-seam-api.test.ts b/test/http/memory-seam-api.test.ts new file mode 100644 index 00000000..6214cd59 --- /dev/null +++ b/test/http/memory-seam-api.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from 'vitest' + +import { createMemorySeamApi } from 'lib/http/memory-seam-api.js' + +test('memory wire consumes responses in order and repeats the last response', async () => { + const first = { devices: [{ device_id: 'first' }], ok: true } + const last = { devices: [{ device_id: 'last' }], ok: true } + const api = createMemorySeamApi({ + '/devices/list': [ + { status: 200, data: first }, + { status: 200, data: last }, + ], + }) + + const responses = [] + for (let index = 0; index < 3; index++) { + responses.push( + await api + .createRequest({ path: '/devices/list', params: {} }) + .fetchResponse(), + ) + } + expect(responses).toEqual([first, last, last]) + expect(api.requests).toHaveLength(3) +}) + +test.each([{}, { '/devices/list': [] }])( + 'memory wire retains missing/empty-route 404 fallback: %j', + async (routes) => { + const api = createMemorySeamApi(routes) + await expect( + api.createRequest({ path: '/devices/list', params: {} }).fetchResponse(), + ).rejects.toMatchObject({ + statusCode: 404, + code: 'not_found', + message: 'Not Found', + }) + }, +) diff --git a/test/http/request.test.ts b/test/http/request.test.ts index c7e00266..489d9179 100644 --- a/test/http/request.test.ts +++ b/test/http/request.test.ts @@ -59,7 +59,7 @@ test.each([undefined, true])( await vi.advanceTimersByTimeAsync(1) expect(memory.stdout()).toBe('') await vi.advanceTimersByTimeAsync(1000) - expect(await result).toEqual({ action_attempt: success, ok: true }) + expect(await result).toEqual({ action_attempt: success }) expect(JSON.parse(memory.stdout())).toEqual({ action_attempt: success }) expect(memory.stderr()).toBe('') expect(api.requests).toEqual([