diff --git a/CHANGELOG.md b/CHANGELOG.md index 025177c..e7bbd35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added +- `planecli attachment` command group: `attach` uploads a file to a work item and confirms the upload by reading it back; `ls` lists a work item's attachments. If a file with the same name is already attached, `attach` asks on stderr when run in a terminal and refuses with exit 5 otherwise; `--force` uploads anyway. Thanks to Liewzheng (#11) +- Repeatable `-i/--image` on `wi create` and `wi update` uploads images and appends them to the description. Uploads use the app's description-asset endpoint and fall back to a v1 attachment when the server rejects API tokens there. All paths are checked before anything is written, and `wi update` uploads only after its other options resolved (#11) + +### Fixed +- `wi create --module` resolves the module before creating the work item, so a mistyped module name no longer leaves an item behind that a retry would duplicate + ## [0.6.0] - 2026-11-06 ### Added diff --git a/README.md b/README.md index 6401b4b..780b82a 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ The main differentiator is **intelligent fuzzy search**: reference any resource - **Documents**: Create, read, update, and delete project documents - **Intake**: Manage a project's intake queue — list, create, triage (accept/decline), and delete items - **Comments**: Add, update, and delete comments on work items +- **Attachments**: Upload files to work items, list them, and embed images in descriptions - **Users**: List workspace members and identify the authenticated user - **Fuzzy Search**: Intelligent resource resolution — `--project "Front"` finds "Frontend" - **Dual Output**: Rich tables (default) or JSON with `--json` for scripting @@ -101,6 +102,10 @@ planecli wi create "Review PR #345" --parent ABC-234 --assign "Luiz" --state "In # Update a work item planecli wi update ABC-123 --state "Done" --priority none +# Embed images in the description (repeatable -i/--image; uploaded, then appended as ) +planecli wi create "Login screen glitch" -p "Frontend" -d "See screenshot" -i ./shot.png +planecli wi update ABC-123 -i ./before.png -i ./after.png + # Quick-assign a work item (defaults to yourself) planecli wi assign ABC-123 planecli wi assign ABC-123 --assign "Patrick" @@ -246,6 +251,21 @@ planecli intake delete -p Frontend planecli intake enabled Frontend --json ``` +### Attachments + +```bash +# Upload a file to a work item +planecli attachment attach ABC-123 -f ./server.log + +# List a work item's attachments +planecli attachment ls ABC-123 +``` + +If a file with the same name is already attached, `attach` asks before uploading when it runs in a +terminal (the question goes to stderr). Without a terminal it refuses with exit code 5; pass +`--force` to upload anyway. `wi update -i --force` does the same, but only when the server falls +back to v1 attachments for the image (see the command reference). + ### Comments ```bash diff --git a/docs/adr/0003-sdk-escape-hatches.md b/docs/adr/0003-sdk-escape-hatches.md index e35b310..01e28ef 100644 --- a/docs/adr/0003-sdk-escape-hatches.md +++ b/docs/adr/0003-sdk-escape-hatches.md @@ -32,6 +32,17 @@ The three escape hatches: 2. **Documents (Pages) — direct HTTP.** For `list`, `update`, and `delete`, `commands/documents.py` calls the Plane HTTP API directly with `requests` and an `X-Api-Key` header through `asyncio.to_thread`. These calls run in a thread but deliberately skip `run_sdk`, so they get no concurrency semaphore and no retries from [ADR-0001](0001-async-wrapper-over-sync-sdk.md). `show` and `create` use the SDK through `run_sdk`. 3. **Estimate points — derive from work items.** `cached_list_estimate_points` fetches work items with `expand=estimate_point` (again via raw `_get()`, since expansion turns `estimate_point` from a string into a dict and breaks SDK validation) and collects the unique `{id, value}` pairs. `resolve_estimate_point_async` then maps a requested value to its UUID. +### Amendment (2026-11-06): attachments and description assets + +A fourth escape hatch arrived with `commands/attachments.py`: + +4. **Attachments and description assets — raw resource methods and direct HTTP.** + - Listing, registering, marking and reading back v1 attachments uses `client.work_items.attachments._get`/`_post`/`_patch`. The typed `attachments.list` returns `[]` when the API answers with a paginated `{"results": [...]}` dict, which would hide attachments, and the typed create drops `upload_data`, the presigned form the upload needs. + - Description images go through the app endpoint `/api/assets/v2/workspaces//projects//` (entity type `ISSUE_DESCRIPTION`) and are read back through `/api/v1/workspaces//assets//`, with `requests` and an `X-Api-Key` header. The SDK covers neither. Servers whose app endpoints accept only a browser session answer 401/403/404 to an API token; the command then falls back to a v1 attachment upload, and the asset UUID works the same in the description. + - The file bytes are POSTed to the presigned storage URL directly, with the signature in the form fields, no API key, and a 300-second timeout. + + All of these run through `run_sdk`, so they get the concurrency limit and retries of [ADR-0001](0001-async-wrapper-over-sync-sdk.md). Each call site carries a `NOTE:`. + ## Consequences **Positive:** @@ -47,4 +58,4 @@ The three escape hatches: ## Confirmation -Work item bypasses are marked with a `NOTE:` comment at their call sites. To list every bypass, grep for `_get(` in `utils/resolve.py` and `cache.py`, and for the `X-Api-Key` header in `commands/documents.py`. If a future `plane-sdk` release fixes `WorkItemDetail` validation or adds Pages/estimate-point endpoints, those call sites are the checklist for removing the workarounds. +Work item bypasses are marked with a `NOTE:` comment at their call sites. To list every bypass, grep for `_get(` in `utils/resolve.py` and `cache.py`, for the `X-Api-Key` header in `commands/documents.py`, and for `NOTE:` in `commands/attachments.py`. If a future `plane-sdk` release fixes `WorkItemDetail` validation or adds Pages/estimate-point endpoints, those call sites are the checklist for removing the workarounds. diff --git a/docs/adr/0008-destructive-deletes-are-documented-not-prompted.md b/docs/adr/0008-destructive-deletes-are-documented-not-prompted.md index c0ceda9..2458364 100644 --- a/docs/adr/0008-destructive-deletes-are-documented-not-prompted.md +++ b/docs/adr/0008-destructive-deletes-are-documented-not-prompted.md @@ -68,3 +68,22 @@ command with a cascade is expected to follow the same pattern in code review. **Neutral:** - Revisit if the CLI ever adopts a uniform confirmation model; this ADR would then be superseded rather than amended per command. + +## Amendment (2026-11-06): duplicate-name confirmation on uploads + +`attachment attach` and `wi update -i` (when the image upload falls back to v1 attachments) ask +before uploading a file whose name is already attached to the work item. Same-named attachments +are easy to create by accident and hard to tell apart in the web UI, and deleting the wrong one +breaks an image embedded in the description. This is the one exception to "no `planecli` command +blocks on stdin", and it is bounded so that it keeps the reason behind the rule (never hang an +automated caller): + +- A command may confirm only when `sys.stdin.isatty()` is true. +- The prompt goes to stderr, never stdout, so `--json` output stays clean ([ADR-0005](0005-dual-output-contract.md)). +- Without a TTY the command does not wait: it refuses with exit 5 and a message that names + `--force`. An answer other than `y`/`yes`, or EOF, also refuses. +- `--force` skips the check. It is documented in `--help`, the README and the skill's command + reference. + +The prompt guards against a duplicate, not against data loss, so it does not change the decision +above for deletes: they stay unprompted and documented. diff --git a/docs/caching.md b/docs/caching.md index 04e9a49..2826dbd 100644 --- a/docs/caching.md +++ b/docs/caching.md @@ -51,6 +51,7 @@ Comments are cached **per work item** (keyed by `item_id`, not just the project) |----------|--------| | Documents / Pages | Change frequently | | Individual resource lookups (by UUID/identifier) | Single-resource fetches should always be fresh | +| Attachments (`attachment ls`, uploads) | Read and written straight through the API; an upload is verified by reading the list back, which a cache would defeat | | Intake queue (`intake ls`) | Goes straight to the API (there is no `cached_list_intake`), so the queue always reflects the current state | **Important distinction**: What's cached is the *list of state definitions* — the lookup table that maps state UUIDs to display names and colors — not the association between a work item and its state. A work item's own fields are only ever as stale as its 2-minute TTL. diff --git a/skills/SKILL.md b/skills/SKILL.md index eff547e..ef63491 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -1,10 +1,10 @@ --- name: planecli -description: "Manage Plane.so through the planecli CLI — work items, projects, cycles/sprints, modules, labels, states, documents, intake queue, comments. Use when the user mentions Plane, planecli, or a work-item identifier like ABC-123, or asks about tasks, sprints, or backlogs in a project where Plane is the tracker." +description: "Manage Plane.so through the planecli CLI — work items, projects, cycles/sprints, modules, labels, states, documents, intake queue, comments, attachments. Use when the user mentions Plane, planecli, or a work-item identifier like ABC-123, or asks about tasks, sprints, or backlogs in a project where Plane is the tracker." allowed-tools: Bash(planecli *) metadata: author: Patrick Alves - version: "1.8.0" + version: "1.9.2" --- # PlaneCLI @@ -126,6 +126,12 @@ planecli doc create --title "Spec" --content "$(cat spec.txt)" -p "Project" --js # Comments planecli comment ls ABC-123 --json planecli comment create ABC-123 --body "Fixed in PR #456" --json + +# Attachments (a duplicate name refuses with exit 5 without a TTY; --force uploads anyway) +planecli attachment attach ABC-123 -f ./server.log --json +planecli attachment ls ABC-123 --json +# Embed images in a description (repeatable; paths are checked before anything is written) +planecli wi update ABC-123 -i ./shot.png --json ``` ## Gotchas diff --git a/skills/references/command-reference.md b/skills/references/command-reference.md index adab9be..4159c1c 100644 --- a/skills/references/command-reference.md +++ b/skills/references/command-reference.md @@ -10,6 +10,7 @@ - [States](#states) - [Documents](#documents) - [Comments](#comments) +- [Attachments](#attachments) - [Intake](#intake) - [Users](#users) - [Cache](#cache) @@ -34,6 +35,7 @@ Environment variable `PLANECLI_NO_CACHE=1` disables cache globally. | `project` | `projects` | | `document` | `doc`, `docs`, `documents` | | `comment` | `comments` | +| `attachment` | `attachments` | | `module` | `modules` | | `label` | `labels` | | `state` | `states` | @@ -42,6 +44,7 @@ Environment variable `PLANECLI_NO_CACHE=1` disables cache globally. | `list` | `ls` | | `show` | `read` | | `create` | `new` | +| `attachment attach` | `upload`, `new` | ## Work Items @@ -102,6 +105,7 @@ planecli wi create TITLE [OPTIONS] | `--parent` | Parent work item identifier (ABC-123) for sub-issues | | `--estimate` / `-e` | Story point estimate | | `--description` / `-d` | Description. Stored as raw HTML, not markdown — see the Gotchas in SKILL.md | +| `--image` / `-i` | Image file to embed in the description (repeatable). Every path is checked before the item is created; the images are uploaded after the create and appended to the `-d` text as `

` | | `--json` | JSON output | ### wi update @@ -121,6 +125,8 @@ planecli wi update ISSUE [OPTIONS] | `--clear-labels` | Remove all labels | | `--name` | New title | | `--description` / `-d` | New description. Stored as raw HTML, not markdown | +| `--image` / `-i` | Image file to embed (repeatable). Appended to the new `-d` text, or to the existing description. Uploaded only after every other option resolved, so a typo in `--state` uploads nothing | +| `--force` | Upload an image even if an attachment with the same name exists. Applies only when the server falls back to v1 attachments | | `--json` | JSON output | ### wi delete @@ -296,6 +302,36 @@ oldest → newest — not the first N chronologically. A limit of `0` or a negat value returns no comments (consistent with the `[:limit]` semantics used elsewhere, where `0` means "none"). +## Attachments + +Command group: `planecli attachment` (alias: `attachments`) + +``` +planecli attachment attach ISSUE -f FILE [--project/-p PROJECT] [--force] [--json] +planecli attachment ls ISSUE [--project/-p PROJECT] [--json] +``` + +- `attach` checks that `FILE` exists before any API call (exit 5 if not), uploads it in three + steps (register, push to the presigned storage URL, mark uploaded), and reads it back: exit 4 + if the server does not confirm the upload, or if storage times out (300 s) or refuses the + connection. +- **Duplicate names.** If a file with the same name is already attached, `attach` asks + `Upload anyway? [y/N]` on stderr when stdin is a terminal. Without a terminal it refuses with + exit 5 and names `--force`, so a script never blocks on stdin + ([ADR-0008](../../docs/adr/0008-destructive-deletes-are-documented-not-prompted.md)). + `--force` uploads without asking. +- `ls` shows `ID`, `Name`, `Type`, `Size`, `Uploaded`, `Created`. In `--json`, `name`, `type` and + `size` are copied to the top level from the API's `attributes`. +- **Images in descriptions** (`wi create/update -i`) first try the app endpoint + `/api/assets/v2/` (entity type `ISSUE_DESCRIPTION`, not listed by `attachment ls`). Servers that + answer 401/403/404 to an API token there fall back to a v1 attachment, which `attachment ls` + shows and which the duplicate-name check covers. The `img` tag stores only the asset UUID; the + web editor resolves it. +- MIME types come from the file extension. `.md`, `.markdown` and `.log` always upload as + `text/plain`, because some Plane servers reject `text/markdown` with `400 Invalid file type.` + Unknown types upload as `application/octet-stream`. Other types a server's allow list + rejects fail with exit 4. + ## Intake Command group: `planecli intake` (no alias) diff --git a/src/planecli/app.py b/src/planecli/app.py index 9dd5c28..04a9ce1 100644 --- a/src/planecli/app.py +++ b/src/planecli/app.py @@ -18,6 +18,7 @@ ) # Import and register sub-apps +from planecli.commands.attachments import attachment_app # noqa: E402 from planecli.commands.cache_cmd import cache_app # noqa: E402 from planecli.commands.comments import comment_app # noqa: E402 from planecli.commands.cycles import cycle_app # noqa: E402 @@ -32,6 +33,7 @@ app.command(project_app) app.command(wi_app) +app.command(attachment_app) app.command(comment_app) app.command(doc_app) app.command(intake_app) diff --git a/src/planecli/commands/attachments.py b/src/planecli/commands/attachments.py new file mode 100644 index 0000000..c7618c9 --- /dev/null +++ b/src/planecli/commands/attachments.py @@ -0,0 +1,401 @@ +"""Work item attachment commands (file upload).""" + +from __future__ import annotations + +import mimetypes +import os +from typing import Annotated + +import cyclopts +from cyclopts import Parameter +from plane.errors import PlaneError + +from planecli.api.async_sdk import run_sdk +from planecli.api.client import get_client, get_workspace, handle_api_error +from planecli.exceptions import APIError, ValidationError +from planecli.formatters import output, output_single +from planecli.utils.resolve import ( + resolve_work_item_across_projects_async, + resolve_work_item_async, +) + +attachment_app = cyclopts.App( + name=["attachment", "attachments"], + help="Manage work item file attachments.", +) + +ATTACHMENT_COLUMNS = [ + ("id", "ID"), + ("name", "Name"), + ("type", "Type"), + ("size", "Size"), + ("is_uploaded", "Uploaded"), + ("created_at", "Created"), +] + + +def _enrich_attachment(data: dict) -> dict: + """Flatten the nested `attributes` dict into top-level display fields. + + The attachment API stores the original filename/MIME under `attributes` + and the byte count at the top level; flatten both so formatters and + `--json` consumers see one consistent shape. + """ + data = {**data} + attrs = data.get("attributes") or {} + data["name"] = attrs.get("name") or data.get("name") or "" + data["type"] = attrs.get("type") or data.get("type") or "" + data["size"] = data.get("size") if data.get("size") is not None else attrs.get("size") + return data + + +# Checked before the platform MIME table: some Plane servers reject +# text/markdown with 400 "Invalid file type.", and platforms without +# /etc/mime.types know none of these (recorded in the attachments section of +# skills/references/command-reference.md). +_TEXT_EXTENSIONS = (".md", ".markdown", ".log") + + +def _guess_mime(filename: str) -> str: + """Guess a MIME type, defaulting to application/octet-stream.""" + if filename.lower().endswith(_TEXT_EXTENSIONS): + return "text/plain" + mime, _ = mimetypes.guess_type(filename) + return mime or "application/octet-stream" + + +async def _raw_http(fn, *args, **kwargs): + """Run a direct `requests` call through run_sdk. + + A timeout or connection error becomes APIError (exit 4) instead of a + traceback; the SDK does the same for its own calls through PlaneError. + """ + import requests + + try: + return await run_sdk(fn, *args, **kwargs) + except requests.RequestException as e: + raise APIError(f"Upload request failed: {e}") from e + + +def require_file(path: str) -> str: + """Expand `~` and return the path, or raise ValidationError if it is not a file. + + Run before any resolver or API call, so bad input writes nothing to Plane. + """ + expanded = os.path.expanduser(path) + if not os.path.isfile(expanded): + raise ValidationError(f"File not found: {expanded}") + return expanded + + +async def _resolve_item(issue: str, project: str | None): + """Resolve a work item to (item_dict, project_id), with or without -p.""" + client = get_client() + workspace = get_workspace() + if project: + from planecli.utils.resolve import resolve_project_async + + proj = await resolve_project_async(project, client, workspace) + project_id = proj["id"] + item = await resolve_work_item_async(issue, client, workspace, project_id) + else: + item, project_id = await resolve_work_item_across_projects_async(issue, client, workspace) + return item, project_id + + +def embed_html(asset_id: str) -> str: + """Build an paragraph embedding an uploaded asset into a description. + + The editor's image node stores the asset UUID in src — not a URL. The web + app resolves it at render time (getEditorAssetSrc); a full path here is + mistaken for an asset id and the image fails to load. + """ + return f'

' + + +# Storage servers can be slow for large files; a stalled one must not hang the +# CLI or hold a run_sdk slot forever (ADR-0001). +_UPLOAD_TIMEOUT = 300 # seconds + + +# NOTE: the _app_* helpers call /api/assets/v2/ and /api/v1/.../assets/ with +# raw requests + X-Api-Key, because the SDK covers neither (ADR-0003). +def _app_post_json(url: str, api_key: str, payload: dict): + """POST JSON to a session-only app endpoint, authenticating with an API token.""" + import requests + + return requests.post( + url, + headers={"X-Api-Key": api_key, "Content-Type": "application/json"}, + json=payload, + timeout=60, + ) + + +def _app_patch_json(url: str, api_key: str, payload: dict | None = None): + # NOTE: raw requests, see the _app_* NOTE above (ADR-0003). + import requests + + return requests.patch( + url, + headers={"X-Api-Key": api_key, "Content-Type": "application/json"}, + json=payload or {}, + timeout=60, + ) + + +def _app_get(url: str, api_key: str): + # NOTE: raw requests, see the _app_* NOTE above (ADR-0003). + import requests + + return requests.get(url, headers={"X-Api-Key": api_key}, timeout=60) + + +async def upload_embed_image( + client, workspace: str, project_id: str, item_id: str, path: str, force: bool = False +) -> str: + """Upload an image for description embedding; return the asset UUID. + + Prefers the native app asset endpoint (entity_type=ISSUE_DESCRIPTION — the + image renders inline and does not clutter the attachment list). Servers + whose app endpoints accept only a browser session answer 401/403/404 to an + API token, in which case we fall back to a v1 ISSUE_ATTACHMENT upload + (recorded in ADR-0003). + """ + from planecli.api.client import get_config + + cfg = get_config() + path = require_file(path) + name = os.path.basename(path) + size = os.path.getsize(path) + mime = _guess_mime(name) + + v2_url = f"{cfg.base_url}/api/assets/v2/workspaces/{workspace}/projects/{project_id}/" + # NOTE: raw requests + X-Api-Key, same pattern as documents.py — the SDK + # only covers /api/v1/ endpoints (see ADR-0003). + resp = await _raw_http( + _app_post_json, + v2_url, + cfg.api_key, + { + "name": name, + "type": mime, + "size": size, + "entity_type": "ISSUE_DESCRIPTION", + "entity_identifier": item_id, + }, + ) + if resp.status_code in (401, 403, 404): + att = await upload_attachment(client, workspace, project_id, item_id, path, force=force) + return att["id"] + if resp.status_code != 200: + raise APIError(f"Asset upload failed: HTTP {resp.status_code}") + + created = resp.json() + upload = created["upload_data"] + import requests + + # NOTE: direct POST to the presigned storage URL; the signature is in the + # form fields, so no SDK call and no X-Api-Key (ADR-0003). + with open(path, "rb") as fh: + up = await _raw_http( + requests.post, + upload["url"], + data=upload["fields"], + files={"file": (name, fh, mime)}, + timeout=_UPLOAD_TIMEOUT, + ) + if up.status_code not in (200, 201, 204): + raise APIError(f"File upload failed: HTTP {up.status_code}") + + asset_id = created["asset_id"] + mark = await _raw_http( + _app_patch_json, f"{v2_url}{asset_id}/", cfg.api_key, {"is_uploaded": True} + ) + if mark.status_code not in (200, 204): + raise APIError(f"Asset confirm failed: HTTP {mark.status_code}") + + # Read back through the v1 generic-asset endpoint (workspace-scoped, works + # for any entity type) — a 2xx on the PATCH is not proof of the write + # (see ADR-0007). + check = await _raw_http( + _app_get, + f"{cfg.base_url}/api/v1/workspaces/{workspace}/assets/{asset_id}/", + cfg.api_key, + ) + if check.status_code != 200: + raise APIError("Image asset was not confirmed by the server after upload.") + return asset_id + + +def _confirm_duplicate(name: str, existing: list[dict]) -> bool: + """Ask before uploading a file whose name is already attached. + + Interactive (TTY): prompt y/N on stderr, so stdout keeps only the --json + payload (ADR-0005). Non-interactive: refuse, so scripts and agents never + block on stdin and must pass --force explicitly (ADR-0008). + """ + import sys + + if not sys.stdin.isatty(): + return False + sys.stderr.write( + f"An attachment named '{name}' already exists ({len(existing)}x). Upload anyway? [y/N] " + ) + sys.stderr.flush() + answer = sys.stdin.readline() # "" on EOF -> refuse + return answer.strip().lower() in ("y", "yes") + + +async def upload_attachment( + client, workspace: str, project_id: str, item_id: str, path: str, force: bool = False +) -> dict: + """Upload a file to a work item (dup-check -> register -> push -> mark -> verify). + + Returns the raw attachment dict with is_uploaded=True. Raises + ValidationError if the file does not exist (or the upload is cancelled at + the duplicate-name prompt), APIError if the server does not confirm the + upload (see ADR-0007). + """ + path = require_file(path) + name = os.path.basename(path) + size = os.path.getsize(path) + endpoint = f"{workspace}/projects/{project_id}/work-items/{item_id}/attachments" + + # Guard against duplicate uploads: same-named attachments are easy to + # create by accident and hard to tell apart in the web UI (deleting the + # wrong one breaks embedded images). Confirm before adding another. + # NOTE: raw _get, because the typed attachments.list returns [] when the + # API answers with a paginated {"results": [...]} dict (ADR-0003). + listed = await run_sdk(client.work_items.attachments._get, endpoint) + items = listed if isinstance(listed, list) else listed.get("results", []) + existing = [ + a + for a in items + if not a.get("is_deleted") and (a.get("attributes") or {}).get("name") == name + ] + if existing and not force and not _confirm_duplicate(name, existing): + raise ValidationError( + f"Upload cancelled: '{name}' is already attached " + f"({len(existing)}x). Re-run with --force to upload anyway." + ) + + mime = _guess_mime(name) + + # Three-step upload, mirroring what the Plane web app does: + # NOTE: the SDK's typed attachment methods drop `upload_data` (the + # presigned form), so the raw resource methods are used throughout — + # same escape hatch as the resolvers (see ADR-0003). + # 1. Register the attachment -> get a presigned upload target. + created = await run_sdk( + client.work_items.attachments._post, + endpoint, + {"name": name, "type": mime, "size": size}, + ) + asset_id = created["asset_id"] + upload = created["upload_data"] + + # 2. Push the bytes to the presigned URL. + # NOTE: direct POST to storage; the signature lives in the form fields, so + # no X-Api-Key header here (ADR-0003). + import requests + + with open(path, "rb") as fh: + resp = await _raw_http( + requests.post, + upload["url"], + data=upload["fields"], + files={"file": (name, fh, mime)}, + timeout=_UPLOAD_TIMEOUT, + ) + if resp.status_code not in (200, 201, 204): + raise APIError(f"File upload failed: HTTP {resp.status_code}") + + # 3. Mark the attachment uploaded, then read it back — a 2xx on the + # PATCH is not proof the write landed (see ADR-0007). + # NOTE: raw _patch and _get, as above (ADR-0003). + await run_sdk( + client.work_items.attachments._patch, + f"{endpoint}/{asset_id}", + {"is_uploaded": True}, + ) + listed = await run_sdk(client.work_items.attachments._get, endpoint) + items = listed if isinstance(listed, list) else listed.get("results", []) + mine = next((a for a in items if a.get("id") == asset_id), None) + if not mine or not mine.get("is_uploaded"): + raise APIError("Attachment was not confirmed by the server after upload.") + return mine + + +@attachment_app.command(alias=["upload", "new"]) +async def attach( + issue: str, + file: Annotated[str, Parameter(alias="-f")], + *, + project: Annotated[str | None, Parameter(alias="-p")] = None, + force: bool = False, + json: bool = False, +) -> None: + """Upload a file attachment to a work item. + + Parameters + ---------- + issue + Work item identifier (ABC-123) or UUID. + file + Path to the file to upload. + project + Project name/ID (required for name-based lookup). + force + Upload even if an attachment with the same file name already exists. + """ + from planecli.formatters import console + + path = require_file(file) + + try: + item, project_id = await _resolve_item(issue, project) + client = get_client() + workspace = get_workspace() + mine = await upload_attachment(client, workspace, project_id, item["id"], path, force=force) + except PlaneError as e: + raise handle_api_error(e) + + data = _enrich_attachment(mine) + if json: + output_single(data, [], as_json=True) + else: + console.print(f"[green]Attached {data['name']} ({data['size']} bytes) to {issue}.[/]") + + +@attachment_app.command(name="list", alias="ls") +async def list_( + issue: str, + *, + project: Annotated[str | None, Parameter(alias="-p")] = None, + json: bool = False, +) -> None: + """List attachments on a work item. + + Parameters + ---------- + issue + Work item identifier (ABC-123) or UUID. + project + Project name/ID (required for name-based lookup). + """ + try: + item, project_id = await _resolve_item(issue, project) + client = get_client() + workspace = get_workspace() + endpoint = f"{workspace}/projects/{project_id}/work-items/{item['id']}/attachments" + # NOTE: raw _get, because the typed attachments.list returns [] for a + # paginated {"results": [...]} response (ADR-0003). + listed = await run_sdk(client.work_items.attachments._get, endpoint) + except PlaneError as e: + raise handle_api_error(e) + + items = listed if isinstance(listed, list) else listed.get("results", []) + data = [_enrich_attachment(a) for a in items if not a.get("is_deleted")] + output(data, ATTACHMENT_COLUMNS, title=f"Attachments on {issue}", as_json=json) diff --git a/src/planecli/commands/work_items.py b/src/planecli/commands/work_items.py index 84abeec..bdbbdb2 100644 --- a/src/planecli/commands/work_items.py +++ b/src/planecli/commands/work_items.py @@ -480,6 +480,7 @@ async def create( parent: str | None = None, estimate: Annotated[int | None, Parameter(alias="-e")] = None, description: Annotated[str | None, Parameter(alias="-d")] = None, + image: Annotated[list[str] | None, Parameter(alias="-i")] = None, json: bool = False, ) -> None: """Create a new work item. @@ -506,9 +507,16 @@ async def create( Story point estimate. description Work item description (plain text). + image + Image file path to embed in the description (repeatable). The image is + uploaded as an attachment and an img tag is appended to the description. """ from plane.models.work_items import CreateWorkItem + from planecli.commands.attachments import require_file + + image_paths = [require_file(p) for p in image or []] + try: client = get_client() workspace = get_workspace() @@ -576,8 +584,14 @@ async def create( if label_ids: create_data.labels = label_ids + # Resolve the module before creating, so a typo in --module leaves no + # item behind for a retry to duplicate. + module_data = ( + await resolve_module_async(module, client, workspace, project_id) if module else None + ) + item = await run_sdk(client.work_items.create, workspace, project_id, create_data) - data = _enrich_work_item(item.model_dump()) + raw = item.model_dump() # Invalidate work items cache for this project from planecli.cache import invalidate_resource @@ -585,16 +599,37 @@ async def create( await invalidate_resource("work_items", workspace, project_id) # Add to module if specified - if module: - module_data = await resolve_module_async(module, client, workspace, project_id) + if module_data: await run_sdk( client.modules.add_work_items, workspace, project_id, module_data["id"], - [data["id"]], + [raw["id"]], ) + # Embed images: upload each, then append tags to the description + # (set here, not in create, because uploads need the issue to exist). + if image_paths: + from plane.models.work_items import UpdateWorkItem + + from planecli.commands.attachments import embed_html, upload_embed_image + + parts = [create_data.description_html or ""] + for path in image_paths: + asset_id = await upload_embed_image(client, workspace, project_id, raw["id"], path) + parts.append(embed_html(asset_id)) + raw["description_html"] = "".join(parts) + await run_sdk( + client.work_items.update, + workspace, + project_id, + raw["id"], + UpdateWorkItem(description_html=raw["description_html"]), + ) + + data = _enrich_work_item(raw) + except PlaneError as e: raise handle_api_error(e) @@ -614,6 +649,8 @@ async def update( name: str | None = None, estimate: Annotated[int | None, Parameter(alias="-e")] = None, description: Annotated[str | None, Parameter(alias="-d")] = None, + image: Annotated[list[str] | None, Parameter(alias="-i")] = None, + force: bool = False, json: bool = False, ) -> None: """Update a work item. @@ -640,9 +677,20 @@ async def update( Story point estimate. description New description (plain text). + image + Image file path to embed in the description (repeatable). Uploaded as + an attachment and appended to the existing description, or to the new + --description if one is given. + force + Upload images even if an attachment with the same file name already exists. + Applies only when the server falls back to v1 attachments for the upload. """ from plane.models.work_items import UpdateWorkItem + from planecli.commands.attachments import require_file + + image_paths = [require_file(p) for p in image or []] + try: client = get_client() workspace = get_workspace() @@ -708,6 +756,20 @@ async def update( if clear_labels: update_data.labels = [] + # Upload last, once every resolver has succeeded, so a typo in + # --state or --labels leaves no orphaned upload behind. Images are + # appended to the new --description, or to the existing one. + if image_paths: + from planecli.commands.attachments import embed_html, upload_embed_image + + parts = [update_data.description_html or item_data.get("description_html") or ""] + for path in image_paths: + asset_id = await upload_embed_image( + client, workspace, project_id, item_id, path, force=force + ) + parts.append(embed_html(asset_id)) + update_data.description_html = "".join(parts) + updated = await run_sdk( client.work_items.update, workspace, project_id, item_id, update_data ) diff --git a/tests/test_commands/test_attachments.py b/tests/test_commands/test_attachments.py new file mode 100644 index 0000000..57a54a1 --- /dev/null +++ b/tests/test_commands/test_attachments.py @@ -0,0 +1,773 @@ +"""Tests for work item attachment commands.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from planecli.commands.attachments import _enrich_attachment, _guess_mime, embed_html + + +@pytest.fixture(autouse=True) +def _load_mime_table(): + # Load the platform MIME table before a test patches os.path.isfile or + # open; loading it under those patches fails or loops forever. + import mimetypes + + mimetypes.init() + + +def test_embed_html_uses_asset_id_as_src(): + # The web editor stores the asset UUID in src and resolves it at render + # time — a full URL here breaks image loading. + assert embed_html("a1") == '

' + + +def test_guess_mime_known_extension(): + assert _guess_mime("shot.png") == "image/png" + assert _guess_mime("notes.MD") == "text/plain" + + +def test_guess_mime_unknown_extension_defaults_to_octet_stream(): + assert _guess_mime("data.unknownext") == "application/octet-stream" + assert _guess_mime("noext") == "application/octet-stream" + + +def test_enrich_attachment_flattens_attributes(): + data = { + "id": "a1", + "attributes": {"name": "shot.png", "type": "image/png"}, + "size": 191318.0, + "is_uploaded": True, + } + result = _enrich_attachment(data) + assert result["name"] == "shot.png" + assert result["type"] == "image/png" + assert result["size"] == 191318.0 + + +def test_enrich_attachment_tolerates_missing_attributes(): + result = _enrich_attachment({"id": "a1"}) + assert result["name"] == "" + assert result["type"] == "" + assert result["size"] is None + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_rejects_missing_file(mock_resolve, mock_client, mock_run): + # The file is checked before anything touches config or the API, so a + # missing file is exit 5 even with no Plane config (as in CI). + from planecli.exceptions import ValidationError + + with pytest.raises(ValidationError, match="File not found: /definitely/not/here.png") as exc: + await _run_attach("/definitely/not/here.png") + + assert exc.value.exit_code == 5 + mock_resolve.assert_not_called() + mock_client.assert_not_called() + mock_run.assert_not_called() + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_rejects_directory_path(mock_resolve, mock_client, mock_run, tmp_path): + from planecli.exceptions import ValidationError + + with pytest.raises(ValidationError, match=f"File not found: {tmp_path}"): + await _run_attach(str(tmp_path)) + + mock_resolve.assert_not_called() + mock_client.assert_not_called() + mock_run.assert_not_called() + + +@patch("planecli.commands.attachments.upload_attachment", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_expands_tilde_before_checking( + mock_resolve, _client, _ws, mock_upload, tmp_path, monkeypatch +): + monkeypatch.setenv("HOME", str(tmp_path)) + (tmp_path / "shot.png").write_bytes(b"png") + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_upload.return_value = {"id": "a1", "attributes": {"name": "shot.png"}, "size": 3} + + await _run_attach("~/shot.png") + + mock_resolve.assert_awaited_once() + mock_upload.assert_awaited_once() + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_maps_api_401_to_exit_2(mock_resolve, _client, _ws, mock_run, tmp_path): + from plane.errors import HttpError + + from planecli.exceptions import AuthenticationError + + f = tmp_path / "x.png" + f.write_bytes(b"png") + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = HttpError("Unauthorized", status_code=401) + + with pytest.raises(AuthenticationError) as exc: + await _run_attach(str(f)) + assert exc.value.exit_code == 2 + + +def test_guess_mime_fallback_without_platform_table(): + # Some platforms ship no /etc/mime.types, so mimetypes knows no .md/.log. + with patch("planecli.commands.attachments.mimetypes.guess_type", return_value=(None, None)): + assert _guess_mime("notes.md") == "text/plain" + assert _guess_mime("notes.MD") == "text/plain" + assert _guess_mime("README.markdown") == "text/plain" + assert _guess_mime("server.LOG") == "text/plain" + assert _guess_mime("data.unknownext") == "application/octet-stream" + assert _guess_mime("noext") == "application/octet-stream" + + +def test_guess_mime_markdown_overrides_platform_table(): + # Plane servers can reject text/markdown with 400 "Invalid file type.", + # so markdown goes up as text/plain even when the platform table knows it. + with patch( + "planecli.commands.attachments.mimetypes.guess_type", return_value=("text/markdown", None) + ): + assert _guess_mime("notes.md") == "text/plain" + assert _guess_mime("notes.markdown") == "text/plain" + + +def test_enrich_attachment_does_not_mutate_input(): + data = {"id": "a1", "attributes": {"name": "shot.png", "type": "image/png"}, "size": 5} + before = {"id": "a1", "attributes": {"name": "shot.png", "type": "image/png"}, "size": 5} + + result = _enrich_attachment(data) + + assert data == before + assert result["name"] == "shot.png" + + +def _ls_patches(): + return ( + patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock), + patch("planecli.commands.attachments.get_client"), + patch("planecli.commands.attachments.get_workspace", return_value="ws"), + patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock), + ) + + +def _att(i, name, mime, size): + return {"id": i, "attributes": {"name": name, "type": mime, "size": size}, "is_uploaded": True} + + +async def _run_ls(listed, capsys, *, as_json=True): + from planecli.commands.attachments import list_ + + p_resolve, p_client, p_ws, p_run = _ls_patches() + with p_resolve as mock_resolve, p_client, p_ws, p_run as mock_run: + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.return_value = listed + await list_("ABC-1", json=as_json) + return capsys.readouterr() + + +async def test_ls_lists_paginated_results(capsys): + import json + + out = await _run_ls( + {"results": [_att("a1", "a.png", "image/png", 10), _att("a2", "b.md", "text/markdown", 3)]}, + capsys, + ) + rows = json.loads(out.out) + assert [(r["name"], r["type"], r["size"]) for r in rows] == [ + ("a.png", "image/png", 10), + ("b.md", "text/markdown", 3), + ] + + +async def test_ls_lists_plain_list(capsys): + import json + + out = await _run_ls([{"id": "a1", "attributes": {"name": "a.log"}, "size": 7}], capsys) + rows = json.loads(out.out) + assert len(rows) == 1 + assert (rows[0]["name"], rows[0]["size"]) == ("a.log", 7) + + +async def test_ls_empty(capsys): + import json + + out = await _run_ls([], capsys) + assert json.loads(out.out) == [] + await _run_ls([], capsys, as_json=False) # table path: no error on an empty list + + +async def test_ls_maps_api_403_to_exit_4(): + from plane.errors import HttpError + + from planecli.commands.attachments import list_ + from planecli.exceptions import APIError + + p_resolve, p_client, p_ws, p_run = _ls_patches() + with p_resolve as mock_resolve, p_client, p_ws, p_run as mock_run: + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = HttpError("Forbidden", status_code=403) + with pytest.raises(APIError) as exc: + await list_("ABC-1") + assert exc.value.exit_code == 4 + + +async def test_ls_unresolved_item_exits_3(): + from planecli.commands.attachments import list_ + from planecli.exceptions import ResourceNotFoundError + + p_resolve, p_client, p_ws, p_run = _ls_patches() + with p_resolve as mock_resolve, p_client, p_ws, p_run as mock_run: + mock_resolve.side_effect = ResourceNotFoundError("Work item", "ABC-999") + with pytest.raises(ResourceNotFoundError) as exc: + await list_("ABC-999") + assert exc.value.exit_code == 3 + mock_run.assert_not_called() + + +def _upload_side_effects(verify_list): + return [ + [], # 0. dup-check: no existing attachments + { # 1. register -> presigned target + "asset_id": "asset-1", + "upload_data": {"url": "http://uploads.local", "fields": {"key": "k"}}, + }, + MagicMock(status_code=204), # 2. binary upload + None, # 3. PATCH is_uploaded + verify_list, # 4. verify + ] + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch( + "planecli.commands.attachments.resolve_work_item_across_projects_async", + new_callable=AsyncMock, +) +async def test_attach_uploads_then_marks_uploaded(mock_resolve, mock_client, _ws, mock_run): + from planecli.commands.attachments import attach + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = _upload_side_effects( + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}] + ) + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + await attach("ABC-1", "x.png", json=True) + + client = mock_client.return_value + register = mock_run.call_args_list[1] + assert register.args[0] is client.work_items.attachments._post + assert register.args[2] == {"name": "x.png", "type": "image/png", "size": 10} + # binary push went to the presigned URL with form fields, not the API + post_call = mock_run.call_args_list[2] + assert post_call.args[1] == "http://uploads.local" + assert post_call.kwargs["data"] == {"key": "k"} + mark = mock_run.call_args_list[3] + assert mark.args[0] is client.work_items.attachments._patch + assert mark.args[1].endswith("/attachments/asset-1") + assert mark.args[2] == {"is_uploaded": True} + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch( + "planecli.commands.attachments.resolve_work_item_across_projects_async", + new_callable=AsyncMock, +) +async def test_attach_raises_when_server_does_not_confirm(mock_resolve, _client, _ws, mock_run): + from planecli.exceptions import APIError + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = _upload_side_effects( + [{"id": "asset-1", "is_uploaded": False}] # PATCH accepted but not applied + ) + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + pytest.raises( + APIError, match="Attachment was not confirmed by the server after upload." + ) as exc, + ): + from planecli.commands.attachments import attach + + await attach("ABC-1", "x.png") + assert exc.value.exit_code == 4 + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_cancels_on_duplicate_name(mock_run, _mime): + from planecli.commands.attachments import upload_attachment + from planecli.exceptions import ValidationError + + mock_run.side_effect = [ + [{"id": "old-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + ] + + import re + + msg = ( + "Upload cancelled: 'x.png' is already attached (1x). Re-run with --force to upload anyway." + ) + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("sys.stdin", MagicMock(isatty=MagicMock(return_value=False))), + pytest.raises(ValidationError, match=re.escape(msg)) as exc, + ): + await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + assert exc.value.exit_code == 5 + assert mock_run.call_count == 1 # only the duplicate check; nothing registered + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_force_skips_duplicate_check(mock_run, _mime): + from planecli.commands.attachments import upload_attachment + + mock_run.side_effect = [ + [{"id": "old-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + {"asset_id": "asset-1", "upload_data": {"url": "u", "fields": {}}}, + MagicMock(status_code=204), + None, + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + result = await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png", force=True) + + assert result["id"] == "asset-1" + + +async def _run_attach(path: str) -> None: + from planecli.commands.attachments import attach + + await attach("ABC-1", path) + + +def _resp(status, json_data=None): + m = MagicMock(status_code=status) + m.json.return_value = json_data or {} + return m + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_prefers_v2_endpoint(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [ + _resp( + 200, + { + "asset_id": "a1", + "asset_url": "/api/assets/v2/x/a1/", + "upload_data": {"url": "u", "fields": {}}, + }, + ), + _resp(204), # binary upload + _resp(204), # mark uploaded + _resp(200), # v1 readback confirms + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + asset_id = await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + assert asset_id == "a1" + # first call hits the app (v2) endpoint with the api key, not /api/v1/ + first = mock_run.call_args_list[0] + assert "/api/assets/v2/workspaces/ws/projects/p1/" in first.args[1] + assert first.args[2] == "k" + + +@pytest.mark.parametrize("status", [401, 403, 404]) +@patch("planecli.commands.attachments.upload_attachment", new_callable=AsyncMock) +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_falls_back_to_v1(mock_run, mock_cfg, mock_upload, status): + from planecli.commands.attachments import upload_embed_image + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [_resp(status)] + mock_upload.return_value = {"id": "a9"} + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + ): + asset_id = await upload_embed_image(None, "ws", "p1", "i1", "x.png", force=True) + + assert asset_id == "a9" + mock_upload.assert_awaited_once() + assert mock_upload.call_args.kwargs["force"] is True + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_raises_on_v2_server_error(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + from planecli.exceptions import APIError + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [_resp(500)] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + pytest.raises(APIError), + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_raises_when_not_confirmed(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + from planecli.exceptions import APIError + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [ + _resp( + 200, {"asset_id": "a1", "asset_url": "/u", "upload_data": {"url": "u", "fields": {}}} + ), + _resp(204), + _resp(204), + _resp(404), # readback: asset not visible -> write did not land + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + pytest.raises(APIError), + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + +class _Tty: + """A stdin that is a terminal and answers with the given line.""" + + def __init__(self, line: str): + self._line = line + + def isatty(self) -> bool: + return True + + def readline(self) -> str: + return self._line + + +def test_confirm_duplicate_prompts_on_stderr(monkeypatch, capsys): + from planecli.commands.attachments import _confirm_duplicate + + monkeypatch.setattr("sys.stdin", _Tty("y\n")) + + assert _confirm_duplicate("x.png", [{"id": "old-1"}]) is True + + out = capsys.readouterr() + assert out.out == "" + assert out.err == "An attachment named 'x.png' already exists (1x). Upload anyway? [y/N] " + + +@pytest.mark.parametrize( + ("line", "expected"), + [ + ("y\n", True), + ("YES\n", True), + ("Yes\n", True), + ("n\n", False), + ("\n", False), + ("", False), # EOF + ("maybe\n", False), + ], +) +def test_confirm_duplicate_answers(monkeypatch, capsys, line, expected): + from planecli.commands.attachments import _confirm_duplicate + + monkeypatch.setattr("sys.stdin", _Tty(line)) + + assert _confirm_duplicate("x.png", [{"id": "old-1"}, {"id": "old-2"}]) is expected + assert capsys.readouterr().out == "" + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_presigned_post_has_timeout_v1(mock_run, _mime): + # A stalled storage server must not hang the CLI (or hold a run_sdk slot). + from planecli.commands.attachments import upload_attachment + + mock_run.side_effect = _upload_side_effects( + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}] + ) + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + + post_call = mock_run.call_args_list[2] + assert post_call.args[1] == "http://uploads.local" + assert post_call.kwargs["timeout"] == 300 + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_presigned_post_has_timeout_v2(mock_run, mock_cfg, _mime): + from planecli.commands.attachments import upload_embed_image + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [ + _resp(200, {"asset_id": "a1", "upload_data": {"url": "http://s3.local", "fields": {}}}), + _resp(204), + _resp(204), + _resp(200), + ] + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + post_call = mock_run.call_args_list[1] + assert post_call.args[1] == "http://s3.local" + assert post_call.kwargs["timeout"] == 300 + + +# --- appended after verification ------------------------------------------ + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_request_error_is_api_error(mock_run, _mime): + import requests + + from planecli.commands.attachments import upload_attachment + from planecli.exceptions import APIError + + mock_run.side_effect = [ + [], + {"asset_id": "asset-1", "upload_data": {"url": "u", "fields": {}}}, + requests.exceptions.ReadTimeout("read timed out"), + ] + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + pytest.raises(APIError, match="Upload request failed: read timed out") as exc, + ): + await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + assert exc.value.exit_code == 4 + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_request_error_is_api_error(mock_run, mock_cfg, _mime): + import requests + + from planecli.commands.attachments import upload_embed_image + from planecli.exceptions import APIError + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + ok = [ + _resp(200, {"asset_id": "a1", "upload_data": {"url": "http://s3.local", "fields": {}}}), + _resp(204), # storage POST + _resp(204), # PATCH is_uploaded + _resp(200), # read-back + ] + # Fail each of the four raw calls in turn: register, storage POST, PATCH, read-back. + for failing in range(4): + side = ok[:failing] + [requests.exceptions.ReadTimeout("read timed out")] + mock_run.reset_mock() + mock_run.side_effect = side + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + pytest.raises(APIError, match="Upload request failed: read timed out") as exc, + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + assert exc.value.exit_code == 4 + assert mock_run.call_count == failing + 1 + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch( + "planecli.commands.attachments.resolve_work_item_across_projects_async", + new_callable=AsyncMock, +) +async def test_attach_raises_when_asset_missing_from_read_back(mock_resolve, _c, _w, mock_run): + from planecli.commands.attachments import attach + from planecli.exceptions import APIError + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = _upload_side_effects( + [{"id": "other-asset", "attributes": {"name": "x.png"}, "is_uploaded": True}] + ) + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + pytest.raises(APIError, match="Attachment was not confirmed by the server after upload."), + ): + await attach("ABC-1", "x.png") + + +def _dup_side_effects(): + return [ + [{"id": "old-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + {"asset_id": "asset-1", "upload_data": {"url": "u", "fields": {}}}, + MagicMock(status_code=204), + None, + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + ] + + +@pytest.mark.parametrize(("answer", "uploads"), [("y\n", True), ("\n", False)]) +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_tty_answer(mock_run, _mime, monkeypatch, answer, uploads): + from planecli.commands.attachments import upload_attachment + from planecli.exceptions import ValidationError + + monkeypatch.setattr("sys.stdin", _Tty(answer)) + mock_run.side_effect = _dup_side_effects() + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + ): + if uploads: + result = await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + assert result["id"] == "asset-1" + else: + with pytest.raises(ValidationError, match="Upload cancelled"): + await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + assert mock_run.call_count == 1 # nothing registered + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_ignores_deleted_duplicate(mock_run, _mime): + from planecli.commands.attachments import upload_attachment + + side = _dup_side_effects() + side[0] = {"results": [{"id": "old-1", "attributes": {"name": "x.png"}, "is_deleted": True}]} + mock_run.side_effect = side + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("planecli.commands.attachments.open", MagicMock(), create=True), + patch("sys.stdin", MagicMock(isatty=MagicMock(return_value=False))), + ): + result = await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + assert result["id"] == "asset-1" + + +async def test_ls_hides_deleted(capsys): + import json + + out = await _run_ls( + { + "results": [ + _att("a1", "a.png", "image/png", 1), + {**_att("a2", "b.png", "image/png", 2), "is_deleted": True}, + ] + }, + capsys, + ) + assert [r["id"] for r in json.loads(out.out)] == ["a1"] + + +def test_enrich_attachment_keeps_top_level_name(): + result = _enrich_attachment( + {"id": "a1", "name": "top.png", "type": "image/png", "attributes": {}} + ) + assert (result["name"], result["type"]) == ("top.png", "image/png") + + +def test_guess_mime_bare_extension_name(): + assert _guess_mime(".md") == "text/plain" + assert _guess_mime("build.log") == "text/plain" + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_maps_api_403_to_exit_4(mock_resolve, _client, _ws, mock_run, tmp_path): + from plane.errors import HttpError + + from planecli.exceptions import APIError + + f = tmp_path / "x.png" + f.write_bytes(b"png") + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = HttpError("Forbidden", status_code=403) + with pytest.raises(APIError) as exc: + await _run_attach(str(f)) + assert exc.value.exit_code == 4 + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +async def test_attach_unresolved_item_exits_3(mock_resolve, _client, mock_run, tmp_path): + from planecli.exceptions import ResourceNotFoundError + + f = tmp_path / "x.png" + f.write_bytes(b"png") + mock_resolve.side_effect = ResourceNotFoundError("Work item", "ABC-999") + with pytest.raises(ResourceNotFoundError) as exc: + await _run_attach(str(f)) + assert exc.value.exit_code == 3 + mock_run.assert_not_called() + + +async def test_ls_maps_api_401_to_exit_2(): + from plane.errors import HttpError + + from planecli.commands.attachments import list_ + from planecli.exceptions import AuthenticationError + + p_resolve, p_client, p_ws, p_run = _ls_patches() + with p_resolve as mock_resolve, p_client, p_ws, p_run as mock_run: + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = HttpError("Unauthorized", status_code=401) + with pytest.raises(AuthenticationError) as exc: + await list_("ABC-1") + assert exc.value.exit_code == 2 diff --git a/tests/test_commands/test_work_item_images.py b/tests/test_commands/test_work_item_images.py new file mode 100644 index 0000000..e792fa7 --- /dev/null +++ b/tests/test_commands/test_work_item_images.py @@ -0,0 +1,230 @@ +"""Tests for `wi create -i` / `wi update -i` (description images).""" + +from __future__ import annotations + +import inspect +import json +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from planecli.commands.work_items import create, update +from planecli.exceptions import ResourceNotFoundError, ValidationError + +WI = "planecli.commands.work_items" +UPLOAD = "planecli.commands.attachments.upload_embed_image" + + +def _img(tmp_path, name="shot.png"): + f = tmp_path / name + f.write_bytes(b"png") + return str(f) + + +def _item(**fields): + m = MagicMock() + m.model_dump.return_value = { + "id": "wi-1", + "name": "Bug", + "sequence_id": 5, + "priority": "high", + "project_detail": {"identifier": "ABC"}, + **fields, + } + return m + + +class _Sdk: + """run_sdk stand-in that records create/update payloads by SDK method.""" + + def __init__(self, client, item): + self.client = client + self.item = item + self.created = [] + self.updated = [] + + async def call(self, fn, *args, **_kwargs): + if fn is self.client.work_items.create: + self.created.append(args[-1]) + elif fn is self.client.work_items.update: + self.updated.append(args[-1]) + return self.item + + +@pytest.fixture +def wi_env(): + client = MagicMock() + with ( + patch(f"{WI}.get_client", return_value=client), + patch(f"{WI}.get_workspace", return_value="ws"), + patch(f"{WI}._resolve_project_id_async", new_callable=AsyncMock) as resolve_proj, + patch(f"{WI}.run_sdk", new_callable=AsyncMock) as run_sdk, + patch("planecli.cache.invalidate_resource", new_callable=AsyncMock), + patch(UPLOAD, new_callable=AsyncMock) as upload, + ): + resolve_proj.return_value = "proj-1" + yield {"client": client, "run_sdk": run_sdk, "upload": upload} + + +# --- wi create -i --------------------------------------------------------- + + +async def test_wi_create_image_missing_path_creates_nothing(wi_env, tmp_path): + ok = _img(tmp_path) + missing = str(tmp_path / "missing.png") + + with pytest.raises(ValidationError, match=f"File not found: {missing}") as exc: + await create("Bug", project="Frontend", image=[ok, missing]) + + assert exc.value.exit_code == 5 + wi_env["run_sdk"].assert_not_called() + wi_env["upload"].assert_not_called() + + +async def test_wi_create_image_keeps_description(wi_env, tmp_path): + sdk = _Sdk(wi_env["client"], _item()) + wi_env["run_sdk"].side_effect = sdk.call + wi_env["upload"].side_effect = ["asset-a", "asset-b"] + + await create( + "Bug", + project="Frontend", + description="Steps", + image=[_img(tmp_path, "a.png"), _img(tmp_path, "b.png")], + ) + + assert sdk.created[0].description_html == "

Steps

" + assert sdk.updated[0].description_html == ( + '

Steps

' + ) + + +async def test_wi_create_image_enriches_once(wi_env, tmp_path, capsys): + wi_env["run_sdk"].side_effect = _Sdk(wi_env["client"], _item()).call + wi_env["upload"].return_value = "asset-a" + + await create("Bug", project="Frontend", priority="high", image=[_img(tmp_path)], json=True) + + data = json.loads(capsys.readouterr().out) + assert data["priority"] == "high" + assert data["sequence_id"] == "ABC-5" + + +def test_wi_create_has_no_force_flag(): + from planecli.app import app + + with pytest.raises(Exception): + app.parse_args(["wi", "create", "Bug", "-p", "Frontend", "--force"], exit_on_error=False) + assert "force" not in inspect.signature(create).parameters + + +# --- wi update -i --------------------------------------------------------- + + +@pytest.fixture +def wi_update_env(wi_env): + with patch( + f"{WI}.resolve_work_item_across_projects_async", new_callable=AsyncMock + ) as resolve_wi: + resolve_wi.return_value = ( + {"id": "wi-1", "description_html": "

Old

"}, + "proj-1", + ) + wi_env["resolve_wi"] = resolve_wi + yield wi_env + + +async def test_wi_update_image_missing_path_resolves_nothing(wi_update_env, tmp_path): + missing = str(tmp_path / "missing.png") + + with pytest.raises(ValidationError, match="File not found") as exc: + await update("ABC-5", image=[missing], state="Done") + + assert exc.value.exit_code == 5 + wi_update_env["resolve_wi"].assert_not_called() + wi_update_env["upload"].assert_not_called() + wi_update_env["run_sdk"].assert_not_called() + + +async def test_wi_update_image_not_uploaded_when_state_fails(wi_update_env, tmp_path): + with patch(f"{WI}.resolve_state_async", new_callable=AsyncMock) as resolve_state: + resolve_state.side_effect = ResourceNotFoundError("State", "In Progres") + with pytest.raises(ResourceNotFoundError) as exc: + await update("ABC-5", image=[_img(tmp_path)], state="In Progres") + + assert exc.value.exit_code == 3 + wi_update_env["upload"].assert_not_called() + + +async def test_wi_update_image_not_uploaded_when_labels_fail(wi_update_env, tmp_path): + with patch(f"{WI}.resolve_label_async", new_callable=AsyncMock) as resolve_label: + resolve_label.side_effect = ResourceNotFoundError("Label", "bgu") + with pytest.raises(ResourceNotFoundError): + await update("ABC-5", image=[_img(tmp_path)], labels="bgu") + + wi_update_env["upload"].assert_not_called() + + +async def test_wi_update_image_appends_to_existing_description(wi_update_env, tmp_path): + sdk = _Sdk(wi_update_env["client"], _item()) + wi_update_env["run_sdk"].side_effect = sdk.call + wi_update_env["upload"].return_value = "asset-a" + + await update("ABC-5", image=[_img(tmp_path)]) + + assert sdk.updated[0].description_html == '

Old

' + + +async def test_wi_update_image_with_new_description(wi_update_env, tmp_path): + sdk = _Sdk(wi_update_env["client"], _item()) + wi_update_env["run_sdk"].side_effect = sdk.call + wi_update_env["upload"].return_value = "asset-a" + + await update("ABC-5", description="New", image=[_img(tmp_path)]) + + assert sdk.updated[0].description_html == '

New

' + + +def test_wi_update_force_help_mentions_v1_fallback(): + doc = inspect.getdoc(update) or "" + force_help = doc.split("force\n", 1)[1] + assert "v1" in force_help + assert "fall" in force_help.lower() + + +# --- appended after verification ------------------------------------------ + + +async def test_wi_update_image_passes_force(wi_update_env, tmp_path): + wi_update_env["run_sdk"].side_effect = _Sdk(wi_update_env["client"], _item()).call + wi_update_env["upload"].return_value = "asset-a" + + await update("ABC-5", image=[_img(tmp_path)], force=True) + + assert wi_update_env["upload"].call_args.kwargs["force"] is True + + +async def test_wi_create_unresolved_module_creates_nothing(wi_env, tmp_path): + with patch(f"{WI}.resolve_module_async", new_callable=AsyncMock) as resolve_module: + resolve_module.side_effect = ResourceNotFoundError("Module", "Sprnt") + with pytest.raises(ResourceNotFoundError): + await create("Bug", project="Frontend", module="Sprnt", image=[_img(tmp_path)]) + + wi_env["run_sdk"].assert_not_called() + wi_env["upload"].assert_not_called() + + +async def test_wi_create_image_table_output(wi_env, tmp_path): + from rich.console import Console + + wi_env["run_sdk"].side_effect = _Sdk(wi_env["client"], _item()).call + wi_env["upload"].return_value = "asset-a" + record = Console(record=True, width=120) + + with patch("planecli.formatters.console", record): + await create("Bug", project="Frontend", priority="high", image=[_img(tmp_path)]) + + text = record.export_text() + assert "ABC-5" in text + assert "ABC-ABC" not in text + assert "high" in text