Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/skills/verify-putio-cli/features/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ Each feature file starts with an H1 and one paragraph of user-visible behavior,
- [Auth login](./auth-login.md): token from stdin, hidden prompt, device link, profiles, rejected tokens.
- [Account reads](./account-reads.md): `whoami`, `auth status`, and `files list` with saved or missing auth.
- [SDK call](./sdk-call.md): `sdk call` argument validation, dry run, and execution.
- [Transfers watch](./transfers-watch.md): `transfers watch` until a transfer finishes or the deadline passes.
26 changes: 26 additions & 0 deletions .agents/skills/verify-putio-cli/features/transfers-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Transfers watch

`putio transfers watch` polls one transfer until it reaches a finished status or the deadline passes, then prints the last transfer it saw and whether it timed out.

## Sub-features

- `watch-finished` returns at once for a finished transfer.
- `watch-deadline` stops at `--timeout-seconds`, even when `--interval-seconds` is longer.
- `watch-ndjson` streams one line per poll.

## How to get to it (user POV)

- `putio transfers watch --id <id>`, optionally `--timeout-seconds` and `--interval-seconds`.

## Driving it with verify.sh

Preconditions: a fresh run, signed in with `printf fixture-token | verify.sh cli login-stdin -- auth login --token-stdin --output json`. The fixture serves transfer `7` as always `DOWNLOADING` and transfer `8` as `COMPLETED`.

- **Finished.** `verify.sh cli watch-finished -- transfers watch --id 8 --output json`. Exit `0`; stdout has `"timedOut": false` and status `COMPLETED`; `verify.sh requests` shows one `GET /v2/transfers/8`.
- **Deadline.** `time verify.sh cli watch-deadline -- transfers watch --id 7 --timeout-seconds 3 --interval-seconds 60 --output json`. Exit `0` after about 3 seconds; stdout has `"timedOut": true`; `verify.sh requests` shows two `GET /v2/transfers/7`, about 3 seconds apart.
- **Stream.** `verify.sh cli watch-ndjson -- transfers watch --id 7 --timeout-seconds 2 --interval-seconds 1 --output ndjson`. Stdout has one JSON line per poll; only the last has `"timedOut": true`.

## Gotchas

- The request timestamps in `requests.jsonl` are the proof of the deadline; the wall time of `verify.sh` includes Node startup.
- Transfer `7` never finishes; a watch without `--timeout-seconds` runs for the default 300 seconds.
47 changes: 47 additions & 0 deletions .agents/skills/verify-putio-cli/scripts/fixture-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,45 @@ const accountInfo = {
warnings: {},
};

const transfer = (id, name, status) => ({
availability: null,
callback_url: null,
client_ip: null,
completion_percent: null,
created_at: TIMESTAMP,
created_torrent: false,
current_ratio: null,
down_speed: null,
download_id: null,
downloaded: null,
error_message: null,
estimated_time: null,
file_id: null,
finished_at: null,
hash: null,
id,
is_private: false,
name,
peers_connected: null,
peers_getting_from_us: null,
peers_sending_to_us: null,
percent_done: status === "COMPLETED" ? 100 : 50,
save_parent_id: 0,
seconds_seeding: null,
simulated: false,
size: null,
source: `https://example.invalid/${name}.torrent`,
started_at: null,
status,
subscription_id: null,
torrent_link: null,
tracker: null,
tracker_message: null,
type: "URL",
up_speed: null,
uploaded: null,
});

const ok = (body = {}) => ({ status: 200, body: { status: "OK", ...body } });

const error = (status, errorType, message) => ({
Expand Down Expand Up @@ -119,6 +158,14 @@ const routes = {
authorized(request)
? ok({ cursor: null, files: [file(1, "Movies")], parent: file(0, "Your Files"), total: 1 })
: error(401, "invalid_grant", "Invalid token"),
"GET /v2/transfers/7": (request) =>
authorized(request)
? ok({ transfer: transfer(7, "stuck.iso", "DOWNLOADING") })
: error(401, "invalid_grant", "Invalid token"),
"GET /v2/transfers/8": (request) =>
authorized(request)
? ok({ transfer: transfer(8, "done.iso", "COMPLETED") })
: error(401, "invalid_grant", "Invalid token"),
};

const readBody = async (request) => {
Expand Down
1 change: 1 addition & 0 deletions skills/putio-cli/references/writes.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ putio sdk call --json '{"operation":"files.get","args":[{"id":42}]}' --execute -
Rules:

- Take required keys from `describe`; never guess names.
- A `--json` payload that fails its schema exits 1; `error.message` names the failing path.
- Treat every `sdk call` operation as potentially mutating and inspect its dry-run before `--execute`.
- `sdk call` args are the SDK function's positional parameters and must match its input schema. A mismatch fails with title `Invalid SDK arguments` before any request; `error.details` names the `operation` and the schema `issue` with its path.
- Bulk selections (`downloadLinks.create`, `sharing.clone`, `sharing.shareFiles`, `zips.create`) need `ids` or a `cursor`; `zips.create` names them `file_ids`.
Expand Down
39 changes: 38 additions & 1 deletion src/command-paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,43 @@ describe("auth", () => {
env: { PUTIO_CLI_TOKEN: undefined },
});

const rateLimited = {
body: {
error_message: "Too many requests",
error_type: "RATE_LIMIT_ERROR",
status: "ERROR",
status_code: 429,
},
status: 429,
};

it("reports a rate limit while validating a token", async () => {
api.route("GET /v2/oauth2/validate", rateLimited);

const run = await anonymousLogin(["--token-stdin", "--output", "json"], {
stdin: "existing-token\n",
});

expect(run.exitCode).toBe(1);
expect(stderrJson(run).error).toMatchObject({ httpStatusCode: 429, title: "Rate limited" });
expect(run.config).toBeUndefined();
});

it("reports a rate limit while polling the device link", async () => {
api.route(
"GET /v2/oauth2/oob/code",
ok({ code: "PUTIO1", qr_code_url: "https://example.invalid/qr" }),
);
api.route("GET /v2/oauth2/oob/code/PUTIO1", rateLimited);

const run = await anonymousLogin(["--output", "json", "--timeout-seconds", "1"], {});

expect(run.exitCode).toBe(1);
expect(run.stderr).toContain('"title": "Rate limited"');
expect(run.stderr).not.toContain("Device login failed");
expect(run.config).toBeUndefined();
});

it("validates a token from stdin and saves it as a token-sourced profile", async () => {
routeTokenValidation("existing-token");

Expand Down Expand Up @@ -1169,7 +1206,7 @@ describe("files upload", () => {
],
[
["--json", '{"path":"/missing/upload-fixture","parent_id":-1}'],
"Expected `--json` to match the command input schema.",
/^Expected `--json` to match the command input schema: .*\["parent_id"\]$/u,
],
])("rejects invalid upload options before filesystem work: %j", async (args, message) => {
expectFailure(await putio("files", "upload", ...args, "--output", "json"), message);
Expand Down
12 changes: 7 additions & 5 deletions src/commands/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Argument, Command, Prompt } from "effect/cli";
import { isPutioRateLimitError } from "@putdotio/sdk";
import * as Stdio from "effect/Stdio";
import * as Terminal from "effect/Terminal";
import { Cause, Console, Effect, Fiber, Option, Queue, Redacted, Schema, Stream } from "effect";
Expand Down Expand Up @@ -201,11 +202,12 @@ const promptForToken = Effect.gen(function* () {

const validateExistingToken = (apiBaseUrl: string, token: string) =>
provideSdk({ apiBaseUrl }, sdk.auth.validateToken(token)).pipe(
Effect.mapError(
() =>
new AuthStateError({
message: "Unable to validate the token with put.io. Check your connection and retry.",
}),
Effect.mapError((error) =>
isPutioRateLimitError(error)
? error
: new AuthStateError({
message: "Unable to validate the token with put.io. Check your connection and retry.",
}),
),
Effect.flatMap((result) =>
result.result
Expand Down
140 changes: 30 additions & 110 deletions src/commands/transfers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Command, Flag } from "effect/cli";
import { TransferAddInputSchema } from "@putdotio/sdk";
import { Clock, Duration, Effect, Option, Schema } from "effect";
import { TransferAddInputSchema, type Transfer } from "@putdotio/sdk";
import { Effect, Option, Schema } from "effect";

import {
CliCommandInputError,
Expand Down Expand Up @@ -34,6 +34,7 @@ import { translate } from "../i18n/index.js";
import { withTerminalLoader } from "../internal/loader-service.js";
import { writeOutput } from "../internal/output-service.js";
import { renderTransfersTerminal } from "../internal/terminal/transfers-terminal.js";
import { type TransferWatchResult, watchTransfer } from "../internal/transfer-watch.js";

const perPageConfig = defineIntegerOption("per-page", { optional: true });
const callbackUrlConfig = defineTextOption("callback-url", { optional: true });
Expand Down Expand Up @@ -413,124 +414,43 @@ const transfersWatch = Command.make(
Option.getOrElse(timeoutSeconds, () => 300),
) * 1_000;

const startedAt = yield* Clock.currentTimeMillis;
const writeWatchOutput = (value: TransferWatchResult<Transfer>) =>
writeReadOutput({
command: "transfers watch",
output: controls.output,
outputMode: controls.outputMode,
renderTerminalValue: (terminalValue) =>
[
renderTransferWatchFinishedTerminal({
id: terminalValue.transfer.id,
status: terminalValue.transfer.status,
timedOut: terminalValue.timedOut,
}),
"",
renderTransfersTerminal({ transfers: [terminalValue.transfer] }),
].join("\n"),
requestedFields: controls.requestedFields,
value,
});

const result = yield* withTerminalLoader(
{
message: translate("cli.transfers.command.watching", { id }),
output: controls.output,
},
Effect.gen(function* () {
while (true) {
const current = yield* withAuthedSdk(({ sdk }) => sdk.transfers.get(id));

if (isTerminalTransferStatus(current.status)) {
const value = {
timedOut: false,
transfer: current,
} as const;

if (controls.outputMode === "ndjson") {
yield* writeReadOutput({
command: "transfers watch",
output: controls.output,
outputMode: controls.outputMode,
renderTerminalValue: (terminalValue) =>
[
renderTransferWatchFinishedTerminal({
id: terminalValue.transfer.id,
status: terminalValue.transfer.status,
timedOut: terminalValue.timedOut,
}),
"",
renderTransfersTerminal({ transfers: [terminalValue.transfer] }),
].join("\n"),
requestedFields: controls.requestedFields,
value,
});
}

return value;
}

if ((yield* Clock.currentTimeMillis) - startedAt >= timeoutMs) {
const value = {
timedOut: true,
transfer: current,
} as const;

if (controls.outputMode === "ndjson") {
yield* writeReadOutput({
command: "transfers watch",
output: controls.output,
outputMode: controls.outputMode,
renderTerminalValue: (terminalValue) =>
[
renderTransferWatchFinishedTerminal({
id: terminalValue.transfer.id,
status: terminalValue.transfer.status,
timedOut: terminalValue.timedOut,
}),
"",
renderTransfersTerminal({ transfers: [terminalValue.transfer] }),
].join("\n"),
requestedFields: controls.requestedFields,
value,
});
}

return value;
}

if (controls.outputMode === "ndjson") {
yield* writeReadOutput({
command: "transfers watch",
output: controls.output,
outputMode: controls.outputMode,
renderTerminalValue: (terminalValue) =>
[
renderTransferWatchFinishedTerminal({
id: terminalValue.transfer.id,
status: terminalValue.transfer.status,
timedOut: terminalValue.timedOut,
}),
"",
renderTransfersTerminal({ transfers: [terminalValue.transfer] }),
].join("\n"),
requestedFields: controls.requestedFields,
value: {
timedOut: false,
transfer: current,
},
});
}

yield* Effect.sleep(Duration.millis(intervalMs));
}
watchTransfer({
intervalMs,
isTerminal: (transfer: Transfer) => isTerminalTransferStatus(transfer.status),
onUpdate: (update) =>
controls.outputMode === "ndjson" ? writeWatchOutput(update) : Effect.void,
Comment thread
altaywtf marked this conversation as resolved.
Resolved
poll: withAuthedSdk(({ sdk }) => sdk.transfers.get(id)),
timeoutMs,
}),
);

if (controls.outputMode === "ndjson") {
return;
if (controls.outputMode !== "ndjson") {
yield* writeWatchOutput(result);
}

yield* writeReadOutput({
command: "transfers watch",
output: controls.output,
outputMode: controls.outputMode,
renderTerminalValue: (value) =>
[
renderTransferWatchFinishedTerminal({
id: value.transfer.id,
status: value.transfer.status,
timedOut: value.timedOut,
}),
"",
renderTransfersTerminal({ transfers: [value.transfer] }),
].join("\n"),
requestedFields: controls.requestedFields,
value: result,
});
}),
);

Expand Down
6 changes: 4 additions & 2 deletions src/internal/auth-flow.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { ConfigProvider, Effect, Fiber, Result } from "effect";
import { ConfigProvider, Data, Effect, Fiber, Result } from "effect";
import { TestClock } from "effect/testing";

import { makeCliAppLayer } from "./app-layer.js";
Expand Down Expand Up @@ -30,6 +30,8 @@ const mockRuntime: CliRuntimeService = {
}),
};

class PollFailure extends Data.TaggedError("PollFailure") {}

describe("resolveAuthFlowConfig", () => {
it.effect("uses the built-in CLI app id and sensible defaults", () =>
Effect.gen(function* () {
Expand Down Expand Up @@ -204,7 +206,7 @@ describe("waitForDeviceToken", () => {
const result = yield* Effect.result(
waitForDeviceToken({
code: "ABCD1234",
checkCodeMatch: () => Effect.fail("boom"),
checkCodeMatch: () => Effect.fail(new PollFailure()),
}),
);

Expand Down
Loading