Skip to content

Make due dates, sub issues, relations and comment files writable - #150

Merged
imshashank merged 23 commits into
mainfrom
issues/writable-fields
Aug 8, 2026
Merged

imshashank merged 23 commits into
mainfrom
issues/writable-fields

Conversation

@imshashank

@imshashank imshashank commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Four issue fields were readable and filterable but had no write path anywhere in the product: due dates, sub issues, issue relations, and attachments on a comment. This closes all four, in the service layer first, then the route, then the UI, and adds the MCP tools so an agent reaches the same behaviour through the same functions.

No migration is needed. There is no schema change: due_date, parent_id, issue_relation and attachment.parent_type all already exist in production.

What was missing, and where

Field Service Route UI MCP
Due date already accepted by issueUpdateSchema already accepted by PATCH /api/issues/[id] absent from the properties panel, and IssuePatch could not even carry it already on update_issue
Parent, sub issues already accepted already accepted no control at all on create_issue, absent from update_issue
Relations setRelation, removeRelation, listRelations existed no route at all nothing set_relation only
Comment attachments assertUploadParent already allowed a comment parent presign already accepted it the composer never passed onUpload nothing

Server

  • packages/core/src/work/issue-service.ts
    • assertParentAllowed now loads the parent through the same visibility check every other read uses. Before this, a member could set an issue in a team they cannot see as the parent of their own issue, which both leaks that the issue exists and drags it into a tree they can read.
    • listRelations now refuses an issue the caller cannot see. It was reachable for any issue id in the workspace.
    • New listRelatedIssues returns the link plus the related issue row, and drops a related issue in a team the caller is not in. Used by both the route and the MCP get_issue, so the two cannot drift.
    • New getParentIssue returns the parent the caller may actually see, or null. The issue detail payload carries it so the client never has to turn an id into an identifier.
  • packages/core/src/content/attachment-service.ts
    • registerUpload, finishUpload and attachFile now hold what the presign and complete routes used to: the scope an upload publishes on, the comment to issue lookup, the size check, and who may finish an upload. Only the person who registered an upload can complete it; before, any member of the workspace could.
    • A comment attachment publishes on issue:<id>, not on the uploader, so the people watching the issue see it.
  • apps/web/src/app/api/issues/[id]/relations/route.ts is new: GET, POST, DELETE, each parsing with issueRelationSchema and calling a service.
  • The presign and complete routes are now four lines each.

UI

  • Properties panel gains Due date (shift+d) and Parent, next to the seven that were already there.
  • Issue detail gains a Sub issues section that creates a child or adopts an existing issue, and a Links section that adds and removes blocks, blocked by, relates to, duplicate of and duplicated by.
  • Comment composers accept files. A new comment holds them behind a local blob placeholder and uploads them against the comment once the server has created it, then patches the body, reusing the pending-attachment machinery quick create already had. Editing an existing comment uploads straight away.
  • Relation deltas arrive on the issue scope and invalidate the links the reader is looking at.

MCP

  • update_issue takes parent (nullable, so an agent can detach).
  • remove_relation is new.
  • attach_file is new: base64 bytes against an issue, comment, doc or project, returning a url and ready-made markdown. It calls attachFile, which calls assertUploadParent, the same gate the web presign route goes through.
  • get_issue lists relations through listRelatedIssues, so it no longer names an issue in a team the caller cannot see.

Tests, and the mutation that makes each one bite

Every test below was watched failing first, then the production code was deliberately broken and confirmed RED, then restored.

Test Mutation that turns it red
core: refuses a parent in a team the caller cannot see assertParentAllowed reverts to the workspace-only lookup → resolves instead of 404
core: refuses to list the relations of an issue the caller cannot see drop loadIssue from listRelations → resolves instead of 404
core: leaves out a related issue in a team the caller cannot see drop the isInTeam filter in listRelatedIssues → the hidden issue comes back
core: stores a due date and clears it drop track('dueDate', ...) → stays null
core: comment upload publishes on the issue of that comment resolveAttachmentScopes always returns attachmentScopes → user: instead of issue:
core: refuses to finish an upload someone else registered drop the uploader check → resolves
core: attachFile refuses a workspace the caller does not belong to drop assertUploadParent → resolves and writes bytes
web route: GET relations refuses a hidden issue route queries the db directly instead of listRelatedIssues → 200
web route: DELETE relations route reads the body instead of the query string → 422
MCP: makes an issue a sub issue and detaches it drop parent from buildIssuePatch → parentId stays null
MCP: unlinks two issues from either end drop registerRemoveRelation → tool not found
UI: due date sends the day the person picked onChange becomes a no-op → nothing is patched
UI: sub issue carries the parent id drop parentId from the create input → missing
UI: unlink names the pair and the type drop type from the query string → server would delete the wrong link
UI: comment composer is wired for uploads drop onUpload from the thread composer → no file input
UI: held files upload against the comment upload with parentType: 'issue' → wrong parent

Authorization is proved against the route, not the component: a guest is refused 403 on POST and DELETE relations and on presign, and a member outside the team is refused 404 on the same routes and on setting a hidden parent. The same four refusals are proved over MCP.

bun run verify exits 0: 2675 tests across every package.

Test isolation

apps/web/tests/app/api/docs/home.test.ts mocks @/lib/auth/principal.ts at module scope and never restores it. Bun evaluates every test file before running any of them, so that mock wins for the whole run. The new route test therefore installs its own session and membership mocks in beforeEach, and builds the membership from a principal resolvePrincipal really resolved out of the database, so the service still decides every authorization question. Nothing existing was changed to make this work.

Greptile Summary

The PR adds write paths for issue due dates, hierarchy, relations, and comment attachments across the service, HTTP, UI, and MCP layers.

  • Centralizes attachment registration and completion in the core service.
  • Adds relation and hierarchy APIs and issue-detail controls.
  • Adds comment attachment staging, upload, and body rewriting.
  • Extends MCP issue and attachment tools.

Confidence Score: 4/5

The PR is not yet safe to merge because a failed comment rewrite still leaves successfully uploaded attachments stored and registered without links from the comment.

Comment attachment uploads complete before the comment-body patch, but failure of that patch has no rollback or cleanup path, leaving attachment records and stored objects unreferenced.

Files Needing Attention: apps/web/src/features/comments/comment-thread.tsx

Important Files Changed

Filename Overview
apps/web/src/features/comments/comment-thread.tsx Integrates per-composer attachment queues and post-creation uploads; the previously reported failed-rewrite lifecycle remains unresolved.
apps/web/src/features/comments/comment-uploads.ts Implements isolated pending-file ownership, placeholder stripping, settlement, and object-URL release.
packages/core/src/content/attachment-service.ts Centralizes upload authorization, registration, completion, and inline attachment storage.
packages/core/src/work/issue-service.ts Adds visibility-aware parent and relation operations shared by HTTP and MCP callers.
apps/web/src/app/api/issues/[id]/relations/route.ts Adds HTTP handlers for listing, creating, and removing issue relations through core services.
packages/mcp-server/src/tools/issues.ts Extends issue tools with parent updates, relation removal, and attachment operations.

Sequence Diagram

sequenceDiagram
  participant UI as Comment composer
  participant API as Comment API
  participant Upload as Attachment service
  participant Store as Object storage
  UI->>API: Create comment with stripped attachment names
  API-->>UI: Created comment ID
  UI->>Upload: Upload files against comment ID
  Upload->>Store: Store bytes
  Upload-->>UI: Attachment URLs
  UI->>API: Patch comment with attachment markdown
Loading

Reviews (11): Last reviewed commit: "test(issues): mirror the route tree in t..." | Re-trigger Greptile

Context used:

  • Context used - CLAUDE.md (source)

assertParentAllowed only checked the workspace, so a member could hang
an issue under a parent in a team they cannot see. listRelations and the
new listRelatedIssues now load the issue through the same visibility
check every other read uses, and a related issue outside the caller
teams is dropped from the result.
…rents included

The presign and complete routes carried the business rules: which scope
an upload publishes on, what a comment attachment belongs to, and who may
finish an upload. That now lives in registerUpload, finishUpload and
attachFile, so the web app and MCP take the same path. A comment upload
publishes on the issue of that comment rather than on the uploader, and
only the person who registered an upload can finish it.
Adds GET, POST and DELETE on /api/issues/[id]/relations, each a thin
handler over setRelation, removeRelation and listRelatedIssues. The issue
detail payload now carries the parent the server resolved, so the client
never has to turn a parent id into an identifier itself.
update_issue takes a parent so an agent can build a sub issue tree,
remove_relation undoes what set_relation wrote, and attach_file uploads
bytes against an issue, comment, doc or project through the same
registerUpload path the web app uses. get_issue now lists relations
through listRelatedIssues, which hides an issue in a team the caller
cannot see.
… files

The properties panel gains a due date and a parent, the detail page gains
a sub issue list that can create or adopt a child, and a links section
that adds and removes every relation type. Comment composers now take
files: a new comment holds them behind a local placeholder and uploads
them against the comment once the server has one, an edit uploads
straight away. Every value goes to the server as it stands, and the
relation deltas invalidate the links the reader is looking at.
@vercel

vercel Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
orbit Error Error Aug 8, 2026 5:40am

Request Review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds issue parent and relation workflows, calendar-date validation, centralized attachment upload services, comment attachment uploads, and MCP tools. It also adds web UI components, query integration, realtime invalidation, authorization checks, and tests.

Changes

Issue and attachment workflows

Layer / File(s) Summary
Shared contracts and core services
packages/shared/src/**, packages/services/src/storage/*, packages/core/src/content/attachment-service.ts, packages/core/src/work/issue-service.ts, packages/core/tests/**
Adds calendar-date and inline-upload validation. Centralizes attachment registration, completion, inline storage, scope resolution, and cleanup. Strengthens parent and relation authorization.
Web API and query wiring
apps/web/src/app/api/**, apps/web/src/lib/query/**, apps/web/src/lib/realtime/**, apps/web/tests/app/api/issues/writable-fields.test.ts
Adds issue relation API handlers, parent data to issue responses, attachment-service delegation, relation query hooks, cache updates, realtime invalidation, and API tests.
Issue detail and writable fields
apps/web/src/features/issues/**, apps/web/tests/features/issues/**
Adds due-date editing, parent selection, sub-issue management, relation linking, issue search, and related test coverage.
Comment attachment lifecycle
apps/web/src/features/comments/**, apps/web/tests/features/comments/**
Adds pending attachment placeholders, deferred upload settlement, cleanup on failure, and uploads for new, reply, edited, and existing comments.
MCP issue and attachment tools
packages/mcp-server/**
Adds parent updates, relation removal, inline file attachment, related issue responses, registration, and authorization tests.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Noveum/orbit#5: Provides storage services used by the attachment lifecycle.
  • Noveum/orbit#23: Shares the attachment routes and attachment-service flow.
  • Noveum/orbit#139: Overlaps with issue parent-child handling and cache synchronization.

Suggested reviewers: pulkitxm

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main changes: making due dates, sub-issues, relations, and comment files writable.
Description check ✅ Passed The description directly explains the writable issue fields, implementation layers, authorization changes, tests, and known review concerns.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issues/writable-fields

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added tests Test coverage and test infrastructure area: web The Next.js app and its UI area: mcp The MCP server, its tools and its OAuth area: issues Issues, lists and boards dependencies Dependency updates labels Aug 7, 2026
Comment thread apps/web/src/lib/query/use-issues.ts Resolved
removeRelation loaded only the issue in the path, so a member of one team
could delete a relation whose far end sits in a team they cannot see, even
though listRelatedIssues already refuses to show them that link. The new
DELETE route made it reachable over HTTP, and the MCP tool was stricter
than the route because it resolved both issues itself. Load both ends in
the service, the way setRelation does, so every caller gets the same gate.
z.coerce.date() took anything Date can swallow. true became 1970-01-01,
and a year outside four digits survived the parse and then lost its tail
to toISOString().slice(0, 10), so PATCH /api/issues/[id] handed postgres
'+275760-09' and answered 500 instead of 422. A string the ISO parser
rejects also fell through to the host timezone, so '10000-01-01' landed
on a different day depending on where the server ran.

calendarDateSchema takes YYYY-MM-DD, reads it as that day in UTC, and
refuses anything a date column cannot hold. Project and milestone dates
go through the same helper for the same reason.
…rded

attachFile put the bytes and then wrote the row. A failed insert left an
object nothing in the database points at. Take it back out. The comment
lookup behind a scope now names the workspace, and attach_file declares
the same size bound the service enforces, so an agent sees the limit in
the tool schema rather than in a rejection.
One usePendingCommentFiles served the thread composer and every reply
composer, so the first submit drained the queue for all of them: one
comment took another one's files and the other kept revoked blob urls.
Each composer now owns its own queue.

The body that creates the comment no longer carries blob urls either. It
goes out with the placeholders reduced to file names, and the upload
rewrites it afterwards, so a rewrite that never lands leaves a readable
comment instead of links only the author's browser could ever resolve.
The new button hand rolled transition-colors, which skips the easing and
the prefers-reduced-motion opt out every other hover in the app carries.
A filtered list can be parent sensitive through the relation filter, and
the detail carries both the parent and the sub issues. Mount an observer
on each and prove the update refetches them, so the next change to
settleFilteredLists or to the detail invalidation cannot go quiet.
@imshashank

Copy link
Copy Markdown
Contributor Author

Second adversarial pass, with main merged in

Merged main (#148, #139, #133) into the branch and resolved the conflicts in issue-properties.tsx, issue-detail.tsx, use-issues.ts, delta-bridge.tsx and the MCP issue tools, so due date and parent sit next to milestone rather than instead of it, and roots.relations and roots.milestones both flush.

Then I called every new and changed route directly with a hostile payload, walked the parent and relation graphs looking for a shape that should not exist, and broke the production code behind every test this branch added.

The branch holds where it claims to

Everything I tried through the service and through the route was refused, and I watched each refusal rather than reading for it:

  • Parent cycles. An issue cannot be its own parent, cannot close a two node loop, and cannot close a longer one: the chain guard caps depth at ten and assertParentAllowed walks up from the parent looking for the child, so the walk either finds the child (409) or runs out of depth (409). The walk reads parentId on an org scoped query rather than through loadIssue, which is right: it has to see ancestors in teams the caller cannot in order to detect the cycle, and it reads nothing but the id.
  • Cross workspace. A parent, a relation and an upload parent in another organization are all 404. bulkUpdateIssues shares applyIssueUpdates, so the parent check covers it too, and issueMoveSchema carries no parentId, so there is no third way in.
  • Hidden teams. Setting a hidden issue as a parent is 404 on both create and update, relating to one is 404 from either end, and reparenting a hidden child is refused.
  • Comment attachments. Presign, complete and the MCP attach_file all go through assertUploadParent, which joins the comment to its issue and checks the team. A guest is 403, a member outside the team is 404, and nothing reaches storage in either case.
  • Scopes. Relations publish on issue:<source> and issue:<target>, a comment upload publishes on the issue of that comment, and issue: is team gated in authorizeScope. Nothing new rides the org scope.
  • MCP parity. update_issue reaches updateIssue, remove_relation reaches removeRelation, attach_file reaches attachFile. No parallel path.

All fifteen tests the branch added bite. I broke the code each one covers, one at a time, and watched it go red with a real assertion failure rather than a load error, then restored it. That includes the four route level refusals and the two MCP ones.

What was wrong

1. A member could unlink an issue they cannot see. Fixed in 030ba49.

removeRelation called loadIssue on the issue in the path and not on the far end, then deleted both directions. So a member of team A, given a relation between a visible issue and one in team B, could delete the row hanging off the team B issue, which they cannot read and which listRelatedIssues correctly refuses to show them. Proved through the route:

DELETE /api/issues/<visible>/relations?relatedIssueId=<hidden>&type=blocks  ->  200, both rows gone

The MCP remove_relation tool happened to be safe, because it resolves both issues with getIssue before calling the service. That is the wrong place for the gate: the tool was stricter than the route, and the service, which both share, was the weak one. removeRelation now loads both ends, the way setRelation already does, so the route and the tool answer the same and the check cannot be skipped by a future caller.

Covered at both layers: packages/core/tests/work/issue-service.test.ts, "refuses to unlink an issue that sits in a team the caller cannot see", and apps/web/tests/app/api/issues/writable-fields.test.ts, "refuses to unlink an issue the caller cannot see from the end they can", which also asserts the relation survives. Dropping the second loadIssue turns both red.

2. A due date was whatever Date could swallow. Fixed in c980b2d.

dueDate was z.coerce.date(). Three separate problems, all reachable from PATCH /api/issues/[id]:

  • {"dueDate": true} returned 200 and stored 1970-01-01. So did 0, and so did any number, read as epoch milliseconds.
  • {"dueDate": "+275760-09-13"} survived the parse, then toISOString().slice(0, 10) cut it to +275760-09 and postgres rejected it, so the route answered 500 with a stack trace in the log instead of 422. -000001-01-01 did the same.
  • {"dueDate": "10000-01-01"} is not a string the ISO parser accepts, so it fell through to the implementation defined parser, which reads it in the host timezone. On a machine at +05:30 it became 9999-12-31. The day a due date landed on depended on where the server ran.

calendarDateSchema in @orbit/shared now takes YYYY-MM-DD, reads it as that day in UTC with no fallback parsing, rejects a day that does not exist (2026-02-30), and refuses a year a date column cannot hold. 0001-01-01 and 9999-12-31 still round trip. Project startDate and targetDate and milestone targetDate go through the same schema, because they share toDateString and had the identical 500.

This narrows the contract: a full ISO datetime is now a 422 rather than a silent truncation to its UTC day. Nothing sends one. The web sends <input type="date"> output, MCP declares z.iso.date(), and no importer or seed writes these fields.

Covered in packages/shared/tests/validators/validators.test.ts and at the route in writable-fields.test.ts, "answers 422 for a due date the client made up, never 500".

3. One held file queue for the whole comment thread. Fixed in 1e07fec.

Greptile flagged the race; the reality was simpler and always broken. CommentThread called usePendingCommentFiles() once and passed the same object to the root composer, every reply composer and every edit composer, so held.current was one queue for the page. Hold a file in a reply, submit the root composer, and the file moved to the root comment while the reply kept a revoked blob. Each composer now owns its hook instance.

The same commit stops a blob: url ever reaching the server. The create goes out with the placeholders reduced to file names and the real urls arrive in the patch, so a rewrite that never lands leaves a readable comment instead of a permanently dead link, and other readers never see one either.

4. An inline upload could orphan its bytes. Fixed in 94cfef9.

attachFile put the object and then wrote the row; a failed insert left bytes nothing points at. It now deletes the key before rethrowing, driven in the test by a real foreign key violation rather than a mock. Two smaller things rode along: the comment lookup behind a scope now names the organization, and attach_file declares the size bound the service enforces.

5. A hand rolled hover on the new clear parent button. Fixed in 2192ca4.

transition-colors duration-[var(--duration-fast)] written at the call site, so no easing token and no motion-reduce:transition-none. Routed through rowHover.

Greptile

Five threads, all answered and resolved. Four were real and are fixed above.

The fifth, parent changes leaving lists stale, does not hold, and I resolved it with the reasoning plus a new test rather than a shrug: no list query the client issues carries parentId or includeSubIssues, and the one way a list can be parent sensitive, the relation filter, is settled by invalidation because belongsInList is deliberately filter blind. apps/web/tests/lib/query/use-issues.test.tsx now mounts a real observer on a relation is sub_issue list and on the detail and proves both refetch on a reparent. Two different mutations turn it red.

I disagreed with the route boundary validation finding and said why on the thread: handing the raw body to the service is the shape every issue route in this repo already uses, and the service is the shared gate precisely because MCP calls it without passing a route handler at all.

Considered and left alone

  • The issue payload still carries parentId even when getParentIssue refuses to resolve that parent, so a member learns an opaque id for an issue in a team they cannot see. parentId predates this branch, an admin can legitimately set a cross team parent, and the id resolves to nothing for that caller. Worth a separate look, not a change here.
  • applyIssueUpdates answers 403 rather than 404 for an issue in a team the caller cannot see, which distinguishes "exists" from "does not exist" on the update path. Pre-existing and outside this branch.

bun run verify exits 0.

Three renderHook roots racing against a 1s waitFor was tight enough to
time out on a loaded runner. One hook mounts the filtered list, the
detail and the mutation together, the mutate goes through act, and the
waits carry a deadline that fits a slow machine. Both mutations that
matter still turn it red.
Six web test files call mock.module on @/lib/query/use-issues.ts and none
put it back, so by the time this file runs useUpdateIssue is a stub with
no isSuccess and no request behind mutate. The test passed alone and was
inert in the suite, which is worse than not having it. The claim it was
answering is argued on the thread from issue-search.ts and
settleFilteredLists instead, and the module mock leak is worth its own
change rather than a workaround here.
@imshashank

Copy link
Copy Markdown
Contributor Author

Correction on the reparent cache test

I added a test in 8f73aad asserting that a reparent refetches the filtered list and the detail. CI failed on it, and the reason is worth reporting rather than burying.

Six web test files call mock.module('@/lib/query/use-issues.ts', ...) and none of them restore it. Five install it at module scope, and Bun evaluates every test file before running any test, so those mocks are live for the whole run. apps/web/tests/features/issues/issue-properties.test.tsx replaces the module with a single useUpdateIssue stub; this PR's own apps/web/tests/features/issues/writable-fields.test.tsx reinstalls a similar stub in beforeEach. By the time tests/lib/query/use-issues.test.tsx runs, useUpdateIssue has no isSuccess and nothing behind mutate.

So the test passed when I ran the file alone and was inert in the suite. That is exactly the failure mode worth avoiding, so I removed it in c7ced7d rather than pad its timeouts into passing. The Greptile finding it was answering is argued on the thread from issue-search.ts and settleFilteredLists, which is checkable by reading.

The leak itself is a real and pre-existing trap, and it is not confined to this module: the PR description already documents the same shape for @/lib/auth/principal.ts in tests/app/api/docs/home.test.ts. Any test that reaches for a real hook out of a module some other file has stubbed gets the stub, silently. It wants its own change: capture the real module, spread it in the factory, and restore it in afterAll, in each of the six files. I have deliberately not done that here, because rewriting six unrelated test files inside a review pass on this PR is the wrong place for it.

Nothing about the shipped behaviour changed with that removal. The five defects this pass found are still fixed and still covered:

Fix Test that turns red without it
removeRelation loads both ends core "refuses to unlink an issue that sits in a team the caller cannot see", web route "refuses to unlink an issue the caller cannot see from the end they can"
calendarDateSchema shared "refuses a year a date column cannot hold", web route "answers 422 for a due date the client made up, never 500"
per composer held files "keeps the files of one composer out of the draft of another"
no blob url in the created body "never hands the created comment a body that points at browser local bytes"
attachFile cleans up its object "takes the stored bytes back out when the row cannot be written"

@imshashank

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@imshashank

Copy link
Copy Markdown
Contributor Author

CI is red on main, not on this branch

Unit and integration tests fails on this PR, and it fails on main too, on the same tests, for the same reason. This is not something the branch introduced.

The visible failure is a Zod error on the response shape (expected object, received undefined at project or milestone), but that is the test parsing an error envelope. The real error is above it in the log:

PostgresError: insert or update on table "project" violates foreign key constraint
  "project_organization_id_organization_id_fk"
detail: Key (organization_id)=(05f2d663-...) is not present in table "organization".

The workspace those two files create in beforeAll is gone by the time their tests run. That is test database isolation between files, not route behaviour, and it has nothing to do with anything in this PR: no date validation, no relation, no attachment code is on that path.

It does not reproduce on macOS. I ran the two files alone, the whole tests/app tree, and three full bun run verify passes, all green, and I tried forcing several file orders against the other files that mock @/lib/auth/session.ts. Bun's file discovery order differs between the two platforms, so this shows up on the Linux runner and not here.

I am not patching it in this PR. I cannot watch a fix go from red to green locally, and guessing at a test isolation fix I cannot reproduce is how a test ends up passing for the wrong reason. It wants its own change, with a reproduction first: either run the web suite with the CI file order, or make milestones.test.ts and projects/route.test.ts build their fixtures per test rather than in beforeAll and confirm that is what does it.

It is worth saying that this is the second isolation trap in the web suite today. The other one is the mock.module leak on @/lib/query/use-issues.ts I described above, and the PR description already documents a third on @/lib/auth/principal.ts. Three separate landmines in one suite is a pattern rather than bad luck.

Locally, bun run verify on this branch exits 0: 2900 tests across every package, on main merged in.

draft() drains the queue at submit, so a create that fails left the blob
urls alive for the page's lifetime. The mutation now releases them on
error. It already toasts, and the composer clearing its box before the
server answers is how every comment has always behaved, so that part is
not this change to make.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (4)
apps/web/src/features/issues/issue-relations.tsx (1)

18-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the shared hover helper for the unlink control.

Replace the raw hover:bg-surface-2 hover:text-text utilities with surfaceHover. This keeps the control consistent with the shared interaction policy.

Proposed change
-import { revealOnHover, rowHover } from '`@/lib/interaction.ts`';
+import { revealOnHover, rowHover, surfaceHover } from '`@/lib/interaction.ts`';
@@
-                    'mr-1.5 flex size-6 shrink-0 items-center justify-center rounded-md text-faint hover:bg-surface-2 hover:text-text',
+                    'mr-1.5 flex size-6 shrink-0 items-center justify-center rounded-md text-faint',
+                    surfaceHover,
                     revealOnHover,

As per coding guidelines: "Use shared interaction tokens for color transitions." Based on learnings: use rowHover, cardHover, or surfaceHover instead of raw hover color classes.

Also applies to: 135-138

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/features/issues/issue-relations.tsx` at line 18, Replace the raw
hover color utilities on the unlink control with the shared surfaceHover helper,
using the existing interaction import in issue-relations.tsx. Update the
corresponding unlink-control usage near the additional referenced lines while
preserving its other classes and behavior.

Sources: Coding guidelines, Learnings

packages/core/tests/content/attachment-service.test.ts (1)

42-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the double assertion on the fake storage driver.

as unknown as StorageDriver disables structural checking of the fake. If StorageDriver changes, this fake keeps compiling and the tests silently exercise a stale contract. Annotate the constant instead. Promise.reject(...) returns Promise<never>, which is assignable to Promise<string>, and a callback that declares fewer parameters is assignable, so the direct annotation should compile.

♻️ Proposed typing change
-  const driver = {
-    name: 's3',
+  const driver: StorageDriver = {
+    name: 's3',
     createUploadTarget: (key: string, contentType: string, contentLength: number) =>
       Promise.resolve({
         key,
         url: `https://storage.test/${key}`,
-        method: 'PUT',
+        method: 'PUT' as const,
         headers: { 'content-type': contentType },
         maxBytes: contentLength,
         expiresAt: new Date(Date.now() + 60_000).toISOString(),
       }),
@@
     stat: (key: string) => Promise.resolve(objects.get(key) ?? null),
-  } as unknown as StorageDriver;
+  };

As per coding guidelines: "Maintain strict types: do not use any or non-null assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/content/attachment-service.test.ts` around lines 42 - 65,
Replace the `as unknown as StorageDriver` assertion on the `driver` fake with a
direct `StorageDriver` type annotation, preserving the existing methods and
behavior while enabling structural contract checking.

Source: Coding guidelines

packages/core/tests/work/issue-service.test.ts (1)

859-867: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the error type for non-calendar due dates.

This test uses rejects.toThrow(), while the neighbouring boundary test uses rejects.toBeInstanceOf(ZodError). A bare toThrow() also passes if the value reaches the database and Postgres raises an error. That would hide a regression back to coercion. Assert ZodError here as well so the test fails when schema validation stops rejecting these values.

♻️ Proposed test change
     for (const nonsense of [true, false, 0, 1_700_000_000_000, 'banana', {}, []]) {
-      await expect(updateIssue(workspace.admin, issue.id, { dueDate: nonsense })).rejects.toThrow();
+      await expect(
+        updateIssue(workspace.admin, issue.id, { dueDate: nonsense }),
+      ).rejects.toBeInstanceOf(ZodError);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/work/issue-service.test.ts` around lines 859 - 867,
Update the non-calendar due-date assertions in the “refuses a due date that is
not a calendar day” test to require each updateIssue rejection to be an instance
of ZodError, matching the neighboring boundary test; keep the existing
invalid-value coverage and final null dueDate assertion.
packages/core/src/content/attachment-service.ts (1)

106-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Type parentType with the shared attachment parent union.

AttachmentDraft.parentType is string. resolveAttachmentScopes and attachmentScopes branch on the literals 'doc', 'issue', 'project', and 'comment'. A widened string removes the compile-time guarantee that only those values reach the draft, and it also weakens the type passed to assertUploadParent, which expects AttachmentParentType. Use the union type instead.

♻️ Proposed typing change
 interface AttachmentDraft {
-  readonly parentType: string;
+  readonly parentType: AttachmentParentType;
   readonly parentId: string;

Import the type from the storage package:

 import {
   assertUploadParent,
+  type AttachmentParentType,
   fileUrlFor,

Verify the exported name before applying:

#!/bin/bash
rg -nP 'AttachmentParentType' --type=ts -C2

As per coding guidelines: "Use strict types: do not use any or non-null assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/content/attachment-service.ts` around lines 106 - 114,
Update AttachmentDraft.parentType to use the shared AttachmentParentType union
imported from the storage package, rather than string. Verify and reuse the
existing exported type so resolveAttachmentScopes, attachmentScopes, and
assertUploadParent retain literal-type safety without introducing any or
non-null assertions.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/src/features/comments/comment-thread.tsx`:
- Around line 86-93: Update the comment creation/edit flow around the create
mutation’s onSuccess callback and draft.settle so subsequent edit submissions
cannot run until attachment settlement completes; serialize or gate edits
against the pending settlement, preserving the settled body as the authoritative
result, and add a regression test covering create, settlement, and a later user
edit.

In `@apps/web/src/features/comments/comment-uploads.ts`:
- Around line 41-95: Add a discard operation alongside hold, upload, and draft
that releases all entries in held.current and clears the collection; invoke it
when comment edit/reply drafts are canceled, removed, or the owning component
unmounts. Update draft to discard stale pending placeholders before
attachPending uploads, while preserving normal settlement behavior, and add
coverage for canceled edits and removals.

In `@apps/web/src/features/issues/issue-properties.tsx`:
- Around line 34-35: Update the rowClassName constant to remove its custom hover
and transition utility classes and compose the base layout classes with the
shared rowHover helper. Preserve the existing spacing, typography, and layout
classes while ensuring property buttons use rowHover for interaction behavior.

In `@apps/web/tests/app/api/issues/writable-fields.test.ts`:
- Around line 1-2: Split the suites in writable-fields.test.ts by endpoint and
move them into test files mirroring each source route: issues/[id]/route.ts,
issues/[id]/relations/route.ts, and attachments/presign/route.ts. Preserve each
suite’s behavior and imports, and extract shared fixture setup into a nearby
test helper only if it is reused across the new files.

In `@apps/web/tests/features/comments/comment-uploads.test.tsx`:
- Around line 75-77: Update the test setup around the existing fetch
preservation to also save the original globalThis.XMLHttpRequest, then restore
it in afterEach(). Ensure tests that replace XMLHttpRequest with FakeUpload do
not leak that mock into subsequent tests.

In `@apps/web/tests/features/issues/writable-fields.test.tsx`:
- Around line 206-245: The IssueProperties tests only cover existing parent
display and detachment, not picker selection mutations. Add interaction tests
for both the parent picker and sub-issue picker that select an issue through
each picker’s UI and assert patched contains { parentId: selected.id }, so
removing either onPick callback causes failure.

In `@packages/mcp-server/tests/tools.test.ts`:
- Around line 25-35: Move the issue-tool test coverage from
packages/mcp-server/tests/tools.test.ts lines 25-35 into
packages/mcp-server/tests/tools/issues.test.ts, including relation, parent,
due-date, and authorization cases. Move the attachment-tool cases from
packages/mcp-server/tests/tools/attachments.test.ts lines 1-193 into
packages/mcp-server/tests/tools/issues.test.ts, or into a focused helper
imported by that mirrored test file; preserve coverage while making the tests
mirror src/tools/issues.ts.
- Around line 291-308: Add coverage in the “unlinks two issues from either end”
test by creating a fresh blocks relation after the inverse-removal assertion,
then call remove_relation with first.identifier, second.identifier, and type
'blocks'. Assert the relation is removed so the direct deletion branch is
exercised independently of the inverse blocked_by path.

In `@packages/mcp-server/tests/tools/attachments.test.ts`:
- Around line 56-81: Update the attachment test setup around beforeAll and the
individual test cases to execute each case, including its required workspace,
members, issue, comment, and attachment fixtures, inside a real Postgres
transaction that is rolled back afterward. Remove reliance on shared persisted
fixtures from beforeAll while preserving the existing admin and guest behavior,
and ensure cleanup in afterAll remains safe for connections created per test.

In `@packages/shared/tests/validators/validators.test.ts`:
- Around line 113-116: Update the extreme-year cases in the dayOf validation
test to also assert that safeParse(...).success is false for each unsupported
date, while retaining the existing dayOf null assertion. Use the validator
symbol already exercised by this test so the test fails when invalid years are
coerced into a null date.

---

Nitpick comments:
In `@apps/web/src/features/issues/issue-relations.tsx`:
- Line 18: Replace the raw hover color utilities on the unlink control with the
shared surfaceHover helper, using the existing interaction import in
issue-relations.tsx. Update the corresponding unlink-control usage near the
additional referenced lines while preserving its other classes and behavior.

In `@packages/core/src/content/attachment-service.ts`:
- Around line 106-114: Update AttachmentDraft.parentType to use the shared
AttachmentParentType union imported from the storage package, rather than
string. Verify and reuse the existing exported type so resolveAttachmentScopes,
attachmentScopes, and assertUploadParent retain literal-type safety without
introducing any or non-null assertions.

In `@packages/core/tests/content/attachment-service.test.ts`:
- Around line 42-65: Replace the `as unknown as StorageDriver` assertion on the
`driver` fake with a direct `StorageDriver` type annotation, preserving the
existing methods and behavior while enabling structural contract checking.

In `@packages/core/tests/work/issue-service.test.ts`:
- Around line 859-867: Update the non-calendar due-date assertions in the
“refuses a due date that is not a calendar day” test to require each updateIssue
rejection to be an instance of ZodError, matching the neighboring boundary test;
keep the existing invalid-value coverage and final null dueDate assertion.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: dd13f3cc-e752-4d57-88a6-f2edee4f2fe8

📥 Commits

Reviewing files that changed from the base of the PR and between 5ddbb49 and fcbf047.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (42)
  • apps/web/src/app/api/attachments/[id]/complete/route.ts
  • apps/web/src/app/api/attachments/presign/route.ts
  • apps/web/src/app/api/issues/[id]/relations/route.ts
  • apps/web/src/app/api/issues/[id]/route.ts
  • apps/web/src/features/comments/comment-composer.tsx
  • apps/web/src/features/comments/comment-thread.tsx
  • apps/web/src/features/comments/comment-uploads.ts
  • apps/web/src/features/issues/due-date-field.tsx
  • apps/web/src/features/issues/issue-detail.tsx
  • apps/web/src/features/issues/issue-picker.tsx
  • apps/web/src/features/issues/issue-properties.tsx
  • apps/web/src/features/issues/issue-relations.tsx
  • apps/web/src/features/issues/pending-attachments.ts
  • apps/web/src/features/issues/sub-issues.tsx
  • apps/web/src/lib/query/keys.ts
  • apps/web/src/lib/query/schemas.ts
  • apps/web/src/lib/query/use-issues.ts
  • apps/web/src/lib/query/use-relations.ts
  • apps/web/src/lib/realtime/delta-bridge.tsx
  • apps/web/tests/app/api/issues/writable-fields.test.ts
  • apps/web/tests/features/comments/comment-composer.test.tsx
  • apps/web/tests/features/comments/comment-uploads.test.tsx
  • apps/web/tests/features/issues/issue-detail-delete.test.tsx
  • apps/web/tests/features/issues/issue-relations.test.tsx
  • apps/web/tests/features/issues/writable-fields.test.tsx
  • packages/core/src/content/attachment-service.ts
  • packages/core/src/work/issue-service.ts
  • packages/core/tests/content/attachment-service.test.ts
  • packages/core/tests/work/issue-service.test.ts
  • packages/mcp-server/package.json
  • packages/mcp-server/src/tools/issues.ts
  • packages/mcp-server/tests/tools.test.ts
  • packages/mcp-server/tests/tools/attachments.test.ts
  • packages/services/src/storage/index.ts
  • packages/services/src/storage/key.ts
  • packages/shared/src/constants/upload.ts
  • packages/shared/src/validators/common.ts
  • packages/shared/src/validators/issue.ts
  • packages/shared/src/validators/milestone.ts
  • packages/shared/src/validators/project.ts
  • packages/shared/src/validators/upload.ts
  • packages/shared/tests/validators/validators.test.ts

Comment thread packages/mcp-server/tests/tools.test.ts Resolved
Comment thread packages/mcp-server/tests/tools.test.ts Resolved
hold() kept every attached file in a ref and only draft() ever cleared
it, so attaching files to a new comment and then navigating away or
cancelling left the object URLs alive for the life of the page. The
hook now exposes discard(), and the composer calls it on unmount.

Also restores XMLHttpRequest between tests, which afterEach left
replaced, so a fake upload leaked into every test that ran after it.

Property rows compose the shared rowHover token instead of hand rolling
transition-colors and a hover colour, which had lost
motion-reduce:transition-none along the way.
…inned

remove_relation deletes through an OR of two shapes, the relation as it
was written and its mirror. Only the mirror end was exercised, so the
direct branch could be deleted without a test noticing. Removing it now
fails two tests rather than none.

The calendar year test read a rejected parse and a parse that yielded
no date as the same thing, because its helper returns null for both. A
schema that accepted year 10000 and stored nothing would have passed.
It now asserts safeParse fails.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/features/comments/comment-thread.tsx (1)

90-96: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Do not silently discard settlement failures.

When draft.settle() rejects, Line 96 hides the error. Report the failure to the user and release any remaining pending resources.

As per coding guidelines, "Throw typed domain errors from @orbit/shared/errors, map them to responses in route handlers, and never silently swallow errors."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/features/comments/comment-thread.tsx` around lines 90 - 96,
Update the draft.settle chain in the comment creation flow so rejection is not
swallowed by catch(() => undefined). Surface the settlement failure to the user
and release any remaining pending resources, using the existing typed
domain-error and error-reporting conventions rather than silently ignoring the
error.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/tests/features/comments/comment-uploads.test.tsx`:
- Around line 229-242: Update the test around usePendingCommentFiles to exercise
the real settlement flow: configure the upload mock for success, call await
draft.settle(commentId) instead of draft.release(), then call discard(). Keep
the existing revoked URL assertion so the test fails if settlement no longer
releases the held URL.

---

Outside diff comments:
In `@apps/web/src/features/comments/comment-thread.tsx`:
- Around line 90-96: Update the draft.settle chain in the comment creation flow
so rejection is not swallowed by catch(() => undefined). Surface the settlement
failure to the user and release any remaining pending resources, using the
existing typed domain-error and error-reporting conventions rather than silently
ignoring the error.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e9f02bee-99dd-4e61-8cdf-5824016641e8

📥 Commits

Reviewing files that changed from the base of the PR and between fcbf047 and 441d567.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • apps/web/src/features/comments/comment-thread.tsx
  • apps/web/src/features/comments/comment-uploads.ts
  • apps/web/src/features/issues/issue-properties.tsx
  • apps/web/src/lib/query/keys.ts
  • apps/web/src/lib/query/schemas.ts
  • apps/web/src/lib/realtime/delta-bridge.tsx
  • apps/web/tests/app/api/issues/writable-fields.test.ts
  • apps/web/tests/features/comments/comment-uploads.test.tsx
  • packages/core/src/work/issue-service.ts
  • packages/mcp-server/tests/tools.test.ts
  • packages/shared/tests/validators/validators.test.ts
💤 Files with no reviewable changes (2)
  • apps/web/src/lib/query/keys.ts
  • apps/web/src/lib/realtime/delta-bridge.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/web/src/lib/query/schemas.ts
  • apps/web/src/features/issues/issue-properties.tsx
  • packages/mcp-server/tests/tools.test.ts
  • packages/core/src/work/issue-service.ts
  • packages/shared/tests/validators/validators.test.ts
  • apps/web/src/features/comments/comment-uploads.ts

Settlement rewrites the body it created, so anything typed between the create and the upload finishing was overwritten. Apply the rewritten body only when the cached comment still reads exactly as it was created.
writable-fields.test.ts covered three routes at a path that mirrored none of them. Split it per route and move the shared world, mocks and fixtures into a package root support module, which the auth mock isolation guard now reads too.

This branch had an error being deployed

1 failed deployment
Preview — 4977f8fb Deployed Aug 8, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: issues Issues, lists and boards area: mcp The MCP server, its tools and its OAuth area: web The Next.js app and its UI dependencies Dependency updates tests Test coverage and test infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant