Skip to content

Blitzy: Add work item duplicate endpoint to public REST API v1 - #1

Open
blitzy[bot] wants to merge 12 commits into
previewfrom
blitzy-bc580970-4984-4080-9d85-5a6fdc4c18d6
Open

blitzy[bot] wants to merge 12 commits into
previewfrom
blitzy-bc580970-4984-4080-9d85-5a6fdc4c18d6

Conversation

@blitzy

@blitzy blitzy Bot commented Jul 31, 2026

Copy link
Copy Markdown

Summary

Adds one additive, write-only action to Plane's external REST API v1:

POST /api/v1/workspaces/{slug}/projects/{project_id}/work-items/{pk}/duplicate/

Clones a work item into a new work item in the same project — Jira "Clone issue" / Linear "Duplicate issue" parity — copying editable content plus assignees and labels, assigning a fresh per-project sequence_id, and starting the clone with a clean history. Responds HTTP 201 via the existing IssueSerializer.

Change set — 4 files, 271 insertions, 0 deletions, 11 commits

Mode File +
M plane/api/views/issue.py +104 — IssueDuplicateAPIEndpoint (L846–947) + 2 model imports
M plane/api/views/__init__.py +1 — barrel re-export
M plane/api/urls/work_item.py +6 — import + one path() in new_url_patterns only
A plane/tests/contract/api/test_work_item_duplicate.py +160 — 2 contract cases

git log --name-only 4ca6d6c7b8..HEAD | sort -u lists only those 4 paths.

Behaviour

  • Scoped load on workspace__slug and project_id → foreign-project/mismatched-slug addressing returns 404 with {"error": "The requested resource does not exist."}
  • Copies name (+ " (Copy)", clamped to the column limit), both description columns, priority, state, point, estimate_point, dates, parent, type, assignees and labels
  • Normalizes completed_at → null (post-write queryset update, since _sync_completed_at has no escape hatch), archived_at → null, is_draft → false; nulls external_source, external_id, description_binary
  • Fresh id/sequence_id from Issue.save() under the project advisory lock
  • Zero rows written to any history table (comments, activities, links, reactions, subscribers, votes, versions, attachments, cycle/module memberships, relations); no duplicate relation
  • Authorization byte-identical to work-item create (ProjectEntityPermission): GUEST 403 · MEMBER/ADMIN 201 · no key 401 · non-POST 405 with Allow: POST
  • No async dispatch, so it returns 201 even with the broker down and no base URL configured

Directives honoured (verified)

  • Zero migrations — makemigrations --check --dry-run → "No changes detected"
  • Zero dependency changes — manifest/lockfile diffs empty; pip check clean
  • No existing contract altered — serializer/model/plane/app/middleware/settings/throttle/frontend/.github diffs all empty; OpenAPI 64 → 65 paths with zero existing paths changed and 86 → 86 schemas unchanged

Validation

  • New module 2 passed / 0 failed; contract/api 6 failed / 26 passed; full suite 35 failed / 180 passed
  • Baseline at 4ca6d6c7b8: 35 failed / 178 passed — sorted failed-node-id lists identical, so 0 failures added and 0 accidentally fixed (pre-existing failures out of scope)
  • ruff check/format clean on all 4 files; SPDX header byte-matches COPYRIGHT.txt (488/488 files)
  • 72-check HTTP + DB matrix 72/72 in both server arms; 10-way burst → 10 × 201, 0 IntegrityError; Swagger UI browser-verified

Reviewer notes

⚠️ Request reviewers — pull-request-build-lint-api.yml is gated on requested_reviewers != null, so the backend lint job is otherwise skipped. CODEOWNERS apps/api/ → @dheeru0198 @pablohashescobar.

⚠️ Open product decision: by AAP mandate (D-3) duplicates emit no IssueActivity row and no issue webhook event. Please confirm before external clients adopt the endpoint.

blitzyai added 12 commits July 30, 2026 21:36
Add IssueDuplicateAPIEndpoint to the public REST API v1 issue views module. The
endpoint clones an existing work item into a brand new work item in the same
project, so API clients can perform the equivalent of Jira's "Clone issue" or
Linear's "Duplicate issue".

The handler resolves the source scoped to both the workspace slug and the
project, clones the loaded instance in place so every editable column carries
over verbatim, re-creates the assignee and label through-rows explicitly, and
returns HTTP 201 rendered by the existing IssueSerializer. Authorization is
identical to work item create (ProjectEntityPermission), and API key
authentication plus per-key throttling are inherited from BaseAPIView.

The clone receives a fresh id and sequence id from the issue model's own save
path, appends a " (Copy)" suffix to the name, and starts with a clean history:
no comment, attachment, activity, relation, reaction, subscriber, vote or
cycle/module membership row is written, and no asynchronous activity dispatch
occurs. The collaborative editor binary state and the external identity columns
are dropped so the clone is a new native work item, archived_at and is_draft are
normalized, and completed_at is cleared after the write because the model
synchronizes it with the state group on every insert.

Purely additive: two model imports (IssueAssignee, IssueLabel) and one new view
class. No migration, and no change to any existing endpoint, serializer, model,
route, permission or middleware.
Append IssueDuplicateAPIEndpoint to the 'from .issue import (...)' block of the
public API views package initializer so the class defined in
plane/api/views/issue.py is reachable as plane.api.views.IssueDuplicateAPIEndpoint.

plane/api/urls/work_item.py imports its views from the package rather than the
submodule, so this re-export is the wiring that lets the new
POST /api/v1/workspaces/{slug}/projects/{project_id}/work-items/{pk}/duplicate/
route resolve its view; without it the URL module cannot import the class and the
application fails at import time.

The change is a single added line: no existing export is renamed, reordered or
aliased, no __all__ is introduced, and no other module is touched. Ruff's
per-file F401 ignore for __init__.py already covers the re-export, so no noqa is
needed.
Addresses the three code review findings on IssueDuplicateAPIEndpoint:

- CRITICAL (data integrity): capture the source assignees and labels from
  IssueAssignee/IssueLabel through rows instead of the assignees/labels
  many-to-many managers. The managers join the through tables without
  filtering deleted_at, so removed associations were resurrected on the
  clone and a removed-then-re-added assignee produced duplicate ids that
  violated the active-row unique index after the clone had been inserted,
  leaving a partial clone. Reading the through tables matches what the
  issue serializer renders for the source.

- MAJOR (functional edge): trim the copied name against the name column
  max length before appending the " (Copy)" suffix, so sources whose name
  sits on the 255 character boundary are duplicated with 201 instead of
  overflowing the column and returning a server error.

- MINOR (performance): select the state, project and project workspace
  with the source work item, removing the three lazy relation fetches that
  Issue.save() triggered on every call.
Addresses the outstanding code review finding on IssueDuplicateAPIEndpoint.

MAJOR (AAP compliance / completeness): the clone name was built through two
unplanned helper assignments and a truncated expression. The Agent Action Plan
and this file's frozen prompt both prescribe the exact statement

    issue.name = f"{issue.name} (Copy)"

so the helpers are removed and the mandated single statement is restored. This
also honours the Minimal Change Clause tie-breaker, which selects the option
that adds the least code and mirrors the Page duplicate endpoint, whose name
mutation is byte-identical.

The earlier suggestion to trim the copied name against the name column length
is therefore not applied: it contradicts an explicit, verbatim plan instruction
and the only alternative mitigation, catching the database error, is forbidden
by the same plan. Measured behaviour of the restored code: a source name of up
to 248 characters duplicates with 201, and a longer one fails the request with
no partial write at all - the insert is rolled back inside the model's own
atomic block, so no work item and no sequence row is left behind.

The two previously hardened behaviours are retained and re-verified, since no
review finding objects to either and both resolve reported defects: the source
assignees and labels are still captured from the IssueAssignee/IssueLabel
through tables, so soft deleted associations are neither resurrected nor
duplicated on the clone, and the source is still loaded with its state, project
and project workspace selected, so Issue.save() triggers no lazy relation fetch.

Verified: ruff clean on the changed file, no new formatting drift, Django system
check clean, the OpenAPI operation still renders as duplicate_work_item with no
spurious path parameter, and the whole backend suite matches its recorded
baseline of 35 failed / 178 passed with contract/api at 6 failed / 24 passed.
…point

Resolves the outstanding findings from the six code review reports covering
apps/api/plane/api/views/issue.py and apps/api/plane/api/views/__init__.py.

Comment remediation (COMMENTS review, 6 MINOR findings) — the inline commentary
in IssueDuplicateAPIEndpoint read as implementation-plan narration (38 comment
lines across 123, ~31%, versus 3-7% in the sibling work item endpoints). Each
block is now reduced to the non-obvious invariant it exists to protect:

- source lookup: keep only the default-manager rationale (archived and draft
  sources stay duplicable, soft-deleted ones still 404) plus the reason the
  state, project and project workspace are selected alongside the source
- membership capture: keep the capture-before-pk-reset ordering and the
  through-model soft-delete semantics, in version-neutral wording
- instance clone: keep only the insert-path invariant that yields a fresh
  sequence id and IssueSequence row
- archive/draft normalisation: comment removed, the assignments say it already
- through-row recreation: keep that bulk_create bypasses ProjectBaseModel.save()
  and that project and workspace must be set before serialization re-queries
- completed_at: keep the save-time sync and queryset-bypass rationale without
  the overly absolute claim

The public documentation is untouched: the class docstring, the work_item_docs
operation metadata, the 201 response description, the handler docstring and the
collaborative-editor and external-identity rationales are all preserved. The
edit is provably comment-only — the module AST is identical before and after.

Data-integrity and performance findings (BACKEND/DATABASE/PERFORMANCE review)
are re-verified against live PostgreSQL: the active through rows are read from
IssueAssignee and IssueLabel so soft-deleted associations are never resurrected,
and the source is loaded with select_related("state", "project__workspace") so
Issue.save() re-fetches none of them.

The clone name mutation stays exactly as the plan mandates,
issue.name = f"{issue.name} (Copy)", per the completeness review.
Wire the additive POST work-item duplicate action into the public REST
API v1 URLconf:

    POST /api/v1/workspaces/{slug}/projects/{project_id}
         /work-items/{pk}/duplicate/

Two purely additive edits to plane/api/urls/work_item.py:

- Append IssueDuplicateAPIEndpoint to the plane.api.views import block,
  resolving through the views package barrel.
- Insert one path() entry into new_url_patterns immediately after the
  work-item detail route, so the new action sits with its siblings.

The <uuid:pk> converter is used rather than <uuid:issue_id> because
duplicate/ is an action on the work item itself, not a sub-resource;
this makes the captured kwargs exactly slug/project_id/pk, matching the
handler signature, and lets drf-spectacular publish the operation with a
pk path parameter. The entry is registered in the modern work-items/
list only: no alias is added under the deprecated issues/ prefix, since
a brand-new capability must not create an obligation to support a
deprecated prefix. An explicit http_method_names=["post"] allowlist
follows the convention of every sibling entry and keeps the operation
visible to the schema preprocessing hook, which drops PUT.

No existing route entry, section comment, or the trailing urlpatterns
concatenation is altered, and no authentication, permission, or throttle
configuration is introduced here - all of it is inherited from
BaseAPIView on the view side. No migration and no dependency change.

Validated: ruff clean; Django system check clean; work_item patterns
12 legacy + 14 modern = 26 and the api aggregator 64 -> 65; reverse and
resolve bind IssueDuplicateAPIEndpoint with kwargs {slug, project_id,
pk}; live POST returns 201 with a fresh sequence id while non-POST
methods return 405, an unknown id returns 404 and a guest returns 403;
the operation publishes once under the curated Work Items tag with no
operationId collision; the full test suite is unchanged at 35 failed /
178 passed with an identical failure set before and after.
Duplicating a work item whose name was 249-255 characters returned HTTP 500
(psycopg StringDataRightTruncation -> django.db.utils.DataError) because the
handler appended the mandated " (Copy)" suffix without accounting for
Issue.name being a CharField(max_length=255); the mirrored page duplicate
precedent operates on an unbounded TextField, so the idiom was not length
safe when transplanted.

The copied base name is now trimmed against the field's own max_length before
the insert, so the mandated suffix always survives and the insert can never
overflow the column. Sources at or below the threshold are unaffected: their
clone name is still exactly name + " (Copy)".

Addresses QA finding #1 (MAJOR, functional) on the work item duplicate
endpoint. Re-verified at runtime: 249 and 255 character sources now return
201 with a 255 character clone name ending in " (Copy)", persisted to the
row; the short name control, the fresh id/sequence_id, completed_at,
archived_at, is_draft, external identity, description fidelity, assignee and
label re-creation, clean history, 404/403/405 contract and the pytest
baselines are all unchanged.
Cover POST /api/v1/workspaces/{slug}/projects/{project_id}/work-items/{pk}/duplicate/
with a pytest contract module holding two cases.

The success case asserts the full response contract and the persisted state:
a 201 status, a fresh id and sequence id, the " (Copy)" name suffix, the
preserved priority, and the assignee and label sets copied from the source.
It also asserts that completed_at is null both in the payload and on the
re-fetched row, which is the check that proves the endpoint normalizes the
column after the write even though the clone copies a completed state, and
that the clone's comment and activity counts are zero so the duplicate
starts with a clean history.

The not found case posts a random identifier and asserts a 404.

The source fixture derives completed_at organically by attaching a state
whose group is completed, so the model's own synchronizer populates the
column rather than the test writing a value no real work item could hold.
Project, state, label and through rows are created through the ORM with
both project and workspace supplied, and the project fixture is duplicated
per module following the convention of the sibling contract modules.
…gful

Resolves code review finding TST-001 (MAJOR) on the work item duplicate
contract test.

The source_issue fixture created no IssueComment and no IssueActivity, so
the two clone-zero assertions could false-pass: an endpoint that copied
every source history row would still leave the clone with zero rows and
satisfy both assertions. Creating a work item through the ORM triggers no
signal that seeds either history table, so the source was provably empty.

The fixture now seeds one IssueComment and one IssueActivity on the source,
following the repository's own construction patterns (the comment mirrors
the IssueComment model unit test, the activity mirrors the created-verb row
written by the issue activity task). The activity epoch is derived from the
work item's own creation stamp so no new import is required.

No new import, mock, broker, settings override, test method or assertion was
added, and both clean-history assertion lines are unchanged. Verified with a
throwaway mutation probe: the contract test now fails against a
history-copying endpoint and would have passed before this change.

Validation: isolated module 2 passed/0 failed; plane/tests/contract/api
6 failed/26 passed; whole plane/tests 35 failed/180 passed - all matching the
documented differential baseline with zero new warnings. ruff check clean on
all four in-scope files; Django system check reports no issues.
Addresses the 10 COMMENTS-gate findings on the work item duplicate
endpoint and its contract test. Comment and docstring changes only; no
behavioural token was modified (8 prose lines added, 38 removed).

apps/api/plane/api/views/issue.py
- Replace the name-restatement class docstring with a one-line
  description of the action, keeping the docstring the AAP mandates.
- Reduce the three-line name-limit narration to a single timeless
  invariant, removing the implementation-history reference.

apps/api/plane/tests/contract/api/test_work_item_duplicate.py
- Condense the source fixture docstring to its contract and the
  non-vacuous-assertion rationale.
- Delete the paired-Description comment and the inaccurate
  activity-task comment.
- Correct the reload and clean-history rationales so they describe only
  what the code and assertions actually establish.
- Drop four docstrings that restated their identifiers and collapse the
  many-to-many and identifier comments to one line each.

Prose density is now 78 words per 100 lines, in line with the label
(82) and cycle (75) contract precedents. Validation: ruff clean on all
four in-scope files, SPDX headers intact, published OpenAPI operation
byte-unchanged, new module 2 passed, contract/api 6 failed 26 passed,
full backend suite 35 failed 180 passed - the documented pre-existing
baseline with no regressions.
…test

Addresses QA finding R3 INFO-3: test_duplicate_work_item_not_found asserted only the 404 status code, leaving the response body unverified even though AAP section 0.6.1 specifies the not-found contract as {"error": "The requested resource does not exist."} produced by BaseAPIView.handle_exception.

- assert response.data["error"] equals the documented envelope, following the existing contract-suite convention in test_labels.py
- runtime verified: the live 404 body is byte-exact, the module reports 2 passed / 0 failed, and mutating the expected string fails the assertion (non-vacuous)
- ruff check and ruff format clean, SPDX header intact, differential baselines unchanged (contract/api 6 failed / 26 passed, plane/tests 35 failed / 180 passed)

All 28 remaining findings across the four QA reports are pre-existing platform behaviour or AAP-mandated design located in files the AAP declares UNTOUCHED, so no other file is modified.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant