Repository navigation
Blitzy: Add work item duplicate endpoint to public REST API v1 - #1
Open
blitzy[bot] wants to merge 12 commits into
Open
blitzy[bot] wants to merge 12 commits into
blitzy[bot] wants to merge 12 commits into
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 existingIssueSerializer.Change set — 4 files, 271 insertions, 0 deletions, 11 commits
plane/api/views/issue.pyIssueDuplicateAPIEndpoint(L846–947) + 2 model importsplane/api/views/__init__.pyplane/api/urls/work_item.pypath()innew_url_patternsonlyplane/tests/contract/api/test_work_item_duplicate.pygit log --name-only 4ca6d6c7b8..HEAD | sort -ulists only those 4 paths.Behaviour
workspace__slugandproject_id→ foreign-project/mismatched-slug addressing returns 404 with{"error": "The requested resource does not exist."}name(+" (Copy)", clamped to the column limit), both description columns,priority,state,point,estimate_point, dates,parent,type, assignees and labelscompleted_at→ null (post-write queryset update, since_sync_completed_athas no escape hatch),archived_at→ null,is_draft→ false; nullsexternal_source,external_id,description_binaryid/sequence_idfromIssue.save()under the project advisory lockduplicaterelationProjectEntityPermission): GUEST 403 · MEMBER/ADMIN 201 · no key 401 · non-POST 405 withAllow: POSTDirectives honoured (verified)
makemigrations --check --dry-run→ "No changes detected"pip checkcleanplane/app/middleware/settings/throttle/frontend/.githubdiffs all empty; OpenAPI 64 → 65 paths with zero existing paths changed and 86 → 86 schemas unchangedValidation
contract/api6 failed / 26 passed; full suite 35 failed / 180 passed4ca6d6c7b8: 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/formatclean on all 4 files; SPDX header byte-matchesCOPYRIGHT.txt(488/488 files)IntegrityError; Swagger UI browser-verifiedReviewer notes
pull-request-build-lint-api.ymlis gated onrequested_reviewers != null, so the backend lint job is otherwise skipped. CODEOWNERSapps/api/→ @dheeru0198 @pablohashescobar.IssueActivityrow and noissuewebhook event. Please confirm before external clients adopt the endpoint.