Skip to content

feat(sidebar): link Linear issues from Edit Worktree Details - #12380

Merged
AmethystLiang merged 4 commits into
mainfrom
no-way-to-attach-linear-issue
Aug 4, 2026
Merged

AmethystLiang merged 4 commits into
mainfrom
no-way-to-attach-linear-issue

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The Edit Worktree Details dialog has a single GH Issue field. A workspace whose work is tracked in Linear had no way to say so from the UI — the link could only be set when the workspace was created, or out-of-band via orca worktree set --linear-issue. The data model already had the slots; the editor didn't.

What changed

One provider-aware Issue row replaces the GitHub-only field. No extra rows, no extra dialog height:

  • A chip suffix inside the input selects GitHub or Linear.
  • Pasting a URL auto-detects the provider and flips the chip.
  • A bare key never steers the provider. LINEAR_IDENTIFIER_PATTERN and Jira's issue-key pattern are byte-identical, so shape alone cannot decide one — letting it try would silently override an explicit choice.
  • A GitHub pull URL is not decisive either: it's a valid GitHub link but not an issue, and must not flip the chip into a state where the field then refuses to save it.

One issue per workspace

A changed field displaces the other provider's slot, and the helper line names what Save is about to unlink (both, when clearing the field drops both). Only a dirty field displaces anything — the dialog opens focused on Comment, and an untouched row leaves every link alone.

GitLab and Jira links are deliberately left alone. The row cannot render them, displacedLinkLabels has no branch to name one, and there is no CLI flag or card property to restore one from. Displacing what it cannot display would destroy a link the user was never shown.

Correctness notes

  • Present-but-undefined keys erase fields. setWorktreeMeta raw-spreads {...existing, ...meta}, so a key that must not be written has to be structurally absent, not undefined. Every build in worktree-meta-updates.test.ts asserts this invariant.
  • Frozen baseline. Dirtiness compares against a snapshot captured in the open transition, not live store state. A background orca worktree set --linear-issue while the dialog is open would otherwise make the untouched field read as dirty, and the next comment-only save would write the stale seed back over the new link.
  • Remote runtimes are gated on key presence, not value. worktree.set parses in strip mode, so an older runtime drops an unknown key and applies the rest of the payload. A dropped clear is as damaging as a dropped write: the stale link it strands is one the Issue row then hides while the card still badges it. Two capabilities are asserted, because linkedWorkItem/linkedTaskSourceContext entered the schema six weeks after task-source-context.v1.
  • Save failures are now visible. updateWorktreeMeta returns a result instead of swallowing. A failed save refetches, which reverts the optimistic write — closing the dialog there reported success for an edit that undid itself, and discarded the name, comment and PR changes in the same payload. The dialog now stays open with a role="alert" line. (Result-return rather than rethrow: ~20 void updateWorktreeMeta(...) call sites would otherwise produce unhandled rejections.)
  • Parses are length-bounded. matchGitHubItemPath strips trailing slashes with an unanchored /\/+$/, which is quadratic — a 160 KB paste of slashes froze the renderer for ~19s. These parses run on every keystroke, so the field, the hook, and the PR gate all take the same bound; the check short-circuits on length, so it stays O(1) on a huge paste.
  • Stale org key. The workspace's stored Linear org key describes the persisted issue, so it only applies while the typed identifier still is that issue. Reusing it for a newly typed one built a URL in the wrong org and short-circuited the lookup that would have reported the miss.
  • Folder workspaces are read-only here — their link is creation-time only, and updateWorktreeMeta drops link keys for them entirely. The row still shows the link (they live outside worktreesByRepo, so the indexed lookup alone left it blank).
  • Protocol gate on Linear URLs. A hostname-only check accepts file://linear.app/...; the parsed value is later handed to shell.openUrl.

Also fixed while here: a bare identifier now clears linkedLinearIssueWorkspaceId/OrganizationUrlKey instead of inheriting them. A stale org key pins resolveLegacyLinearLinkWorkspace to the wrong org — not-found, or a silently wrong issue on a team-prefix collision.

Performance

The dialog's worktree lookup goes through the existing owner index. The code it replaced was Object.values().flat().find() — an N-element allocation on every store notification, not a plain Array.find.

Testing

  • npm run typecheck — clean
  • npx oxlint <changed files> — clean
  • npx oxfmt --check — clean
  • npx vitest run --config config/vitest.config.ts src/shared src/renderer/src/components/sidebar src/renderer/src/store src/cli — 811 files / 8592 tests passed
  • All three localization gates pass

New coverage: provider detection and parse (issue-link-input.test.ts), payload shape and the erasure invariant (worktree-meta-updates.test.ts), dialog behavior incl. seeding, chip flips, displacement notices, the frozen baseline, folder workspaces, and the save-failure surface (WorktreeMetaDialog.test.tsx), and the Linear protocol gate (linear-links.test.ts).

Two rounds of /readiness-checklist were run with sub-agents across functional, performance, security, back-compat and cross-platform seats; round 2 caught three defects introduced by round 1's own fixes.

Not in scope

Jira. The chip menu lists only GitHub and Linear — no disabled "coming soon" item. ISSUE_LINK_PROVIDERS narrows the canonical provider union rather than minting a parallel one, so adding Jira later is a one-entry change.

Made with Orca 🐋

The Issue field only accepted GitHub numbers, so a workspace tracking a
Linear issue had no way to say so from the dialog — the link could only be
set at creation time or through `orca worktree set --linear-issue`.

Replaces the field with one provider-aware row: a chip suffix inside the
input selects GitHub or Linear, and pasting a URL flips the chip to match.
A bare key never steers the provider — Linear and Jira issue keys are
byte-identical in shape, so shape alone cannot decide one.

One issue per workspace. A changed field displaces the other provider's
slot and the row names what Save is about to unlink. GitLab and Jira links
are left alone: the row cannot display them, and nothing else in the UI
could restore one it dropped.

- Folder workspaces read-only (their link is creation-time only)
- Remote runtimes assert the capability before writing or clearing, since
  `worktree.set` parses in strip mode and would silently drop the keys
- `updateWorktreeMeta` now reports failure so the dialog can stay open
  instead of closing over a save that refetch reverted
- Parses are length-bounded — `matchGitHubItemPath` strips trailing
  slashes with an unanchored regex that is quadratic on a large paste
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8353406b-b009-493a-8ebf-91bfaa38edab

📥 Commits

Reviewing files that changed from the base of the PR and between cacd88e and d1e966d.

📒 Files selected for processing (1)
  • src/cli/index.test.ts

📝 Walkthrough

Walkthrough

The change adds shared GitHub and Linear issue-link parsing and update builders. Worktree metadata updates now use draft and snapshot state, preserve unrelated links, and return structured results. The issue-link hook and controlled field support provider selection, validation, opening, and failure states. The metadata dialog supports indexed and folder workspaces, displaced-link warnings, read-only behavior, and failed-save handling. Tests cover parsing, update construction, dialog behavior, and persistence outcomes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.72% 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
Title check ✅ Passed The title clearly identifies the main change: adding Linear issue links to the Edit Worktree Details sidebar.
Description check ✅ Passed The description clearly covers the change, testing, security considerations, risks, and scope, so it is mostly complete despite missing some template headings.
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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (7)
src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx (2)

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

Announce the helper text when it changes without focus movement.

openIssueFailed is set after a button click. The input keeps focus elsewhere or the click target is the open-issue button, so a change in aria-describedby content is not reliably announced. Add a live region role so screen-reader users receive the failure and displacement messages.

♿ Proposed fix
       <p
         id={helperId}
+        role="status"
+        aria-live="polite"
         className={cn(

246-250: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the existing warning color token for this field.

main.css defines var(--warning, #f59e0b) and no light/dark text color mapping exists. Add a --color-warning mapping to main.css, then replace both text-amber-* classes here with the token-based style.

Source: Coding guidelines

src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx (1)

244-261: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Clear saveError when a new save starts.

A failed save keeps saveError visible. If the user edits a field and clicks Save again, the previous error stays on screen for the whole in-flight request. Reset it with setSaving(true).

♻️ Proposed fix
     setSaving(true)
+    setSaveError(null)
     try {
src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx (1)

216-238: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a test for the displaced-link payload, not only the warning text.

These tests assert the warning copy. No test asserts the update payload that the displacement produces. The one-issue-per-workspace rule is enforced by buildWorktreeMetaUpdates, so a regression there would clear the wrong slot without failing any test here.

💚 Proposed test
+  it('clears the displaced GitHub link when a Linear value is saved', async () => {
+    openDialog({ worktree: { linkedIssue: 42 } })
+
+    fireEvent.click(screen.getByRole('menuitemradio', { name: 'Linear' }))
+    fireEvent.change(issueInput(), { target: { value: 'STA-335' } })
+    await act(async () => {
+      fireEvent.click(saveButton())
+    })
+
+    await waitFor(() => expect(updateWorktreeMeta).toHaveBeenCalledTimes(1))
+    const updates = updateWorktreeMeta.mock.calls[0]?.[1] ?? {}
+    expect(updates.linkedLinearIssue).toBe('STA-335')
+    expect(updates.linkedIssue).toBeNull()
+  })
src/shared/issue-link-input.test.ts (1)

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

Add a test for the safe-integer bound.

parseIssueLinkInput rejects digit strings that exceed Number.MAX_SAFE_INTEGER, and the source comment states this guard is load-bearing. No test covers it, so a regression would pass CI.

💚 Proposed test addition
     it('rejects non-positive numbers and junk', () => {
       expect(parseIssueLinkInput('0', 'github')).toBeNull()
       expect(parseIssueLinkInput('-1', 'github')).toBeNull()
       expect(parseIssueLinkInput('not an issue', 'github')).toBeNull()
       expect(parseIssueLinkInput('   ', 'github')).toBeNull()
     })
+
+    it('rejects numbers beyond the safe-integer range', () => {
+      expect(parseIssueLinkInput('9'.repeat(400), 'github')).toBeNull()
+    })
src/renderer/src/components/sidebar/worktree-meta-updates.ts (1)

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

Document or guard the PR field's unconditional write.

buildPrLinkUpdate always emits linkedPR, including null for a blank input. This is safe only while the dialog seeds prInput from the persisted linkedPR on open. The issue field received a snapshot-based dirty guard to defend against exactly this failure mode. Add the seeding requirement as a comment here, or gate the write on a snapshot comparison as the issue field does.

♻️ Proposed comment
+// Requires the dialog to seed `prInput` from the persisted `linkedPR`. An
+// unseeded field would clear the link on an untouched save.
 function buildPrLinkUpdate(draft: WorktreeMetaDraft): Partial<WorktreeMeta> {
src/renderer/src/components/sidebar/worktree-meta-updates.test.ts (1)

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

This test cannot fail.

buildWorktreeMetaUpdates never writes linkedGitLabIssue on any branch, so both assertions hold regardless of the displacement logic. The comment states the intent correctly, but the test does not protect it.

Assert on the fields the builder can actually write for a GitLab-owned work item — linkedWorkItem and linkedTaskSourceContext — which is what the displacement gate decides. Note that lines 147-157 already cover that case, so this test may be redundant.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 78101784-f91a-456a-abd0-b7158a7adc59

📥 Commits

Reviewing files that changed from the base of the PR and between ce8b778 and babed44.

📒 Files selected for processing (17)
  • src/cli/handlers/worktree-linear-issue-link.ts
  • src/cli/index.test.ts
  • src/renderer/src/components/sidebar/WorktreeCard.tsx
  • src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx
  • src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx
  • src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx
  • src/renderer/src/components/sidebar/use-worktree-issue-link.ts
  • src/renderer/src/components/sidebar/worktree-issue-displacement.ts
  • src/renderer/src/components/sidebar/worktree-meta-updates.test.ts
  • src/renderer/src/components/sidebar/worktree-meta-updates.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/shared/issue-link-input.test.ts
  • src/shared/issue-link-input.ts
  • src/shared/linear-links.test.ts
  • src/shared/linear-links.ts

Only clear displaced issue links when they actually existed, preventing
unnecessary Linear keys in GitHub-only workspaces. Skip comment updates
when unchanged to avoid workspace reordering. Add accessibility to
displacement messages and improve folder workspace error handling.
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] fixed

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Confirmed. Thank you for the fix.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

The same workspace ID can exist under multiple hosts — the owner index reports
this as ambiguous rather than guessing. Dialog callers now pass their repoId so
lookups are unambiguous. Linear identifiers without an org key are resolved
across all workspaces (not just the active organization). Added race-condition
protection for async issue lookups and better change detection to avoid clearing
work-item titles when re-saving an identifier in different spelling.
@AmethystLiang
AmethystLiang merged commit 999e3a3 into main Aug 4, 2026
45 of 46 checks passed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
src/renderer/src/components/sidebar/use-worktree-issue-link.ts (2)

201-204: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Scope openingIssue cleanup to the request generation.

If resetOpeningIssue() retires request A and request B starts before A settles, A clears openingIssue in either finally block. The hook then reports B as idle and can accept duplicate opens. Clear loading state only when openRequestRef.current === generation. Apply the change in both branches.

Proposed fix
     const isCurrentRequest = (): boolean =>
       mountedRef.current &&
       openRequestRef.current === generation &&
       latestRequestKeyRef.current === requestKey
+    const isActiveGeneration = (): boolean =>
+      mountedRef.current && openRequestRef.current === generation
...
     } finally {
-      if (mountedRef.current) {
+      if (isActiveGeneration()) {
         setOpeningIssue(false)
       }
     }

Also applies to: 240-243, 263-265


273-276: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Associate an open failure with the selected provider.

If a Linear lookup for ENG-123 fails and the user selects GitHub without changing the text, openIssueFailed remains true. Store the provider-plus-input request key when a lookup fails, then compare that key here. Add a provider-switch regression test.

Based on the PR objective, provider selection can change without changing a bare identifier.

🧹 Nitpick comments (1)
src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx (1)

430-444: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert the full argument list for the cross-workspace lookup.

slice(0, 2) ignores any further arguments, so a wrong third argument such as a workspace scope or organization key still passes. Assert the whole call instead.

♻️ Proposed tightening
-    expect(fetchLinearIssue.mock.calls[0]?.slice(0, 2)).toEqual(['STA-999', 'all'])
+    expect(fetchLinearIssue).toHaveBeenCalledWith('STA-999', 'all')

If the caller intentionally passes extra arguments, keep the current form and ignore this suggestion.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: acdaf834-ca7e-4dae-ac02-dc3440586c42

📥 Commits

Reviewing files that changed from the base of the PR and between 9e2c735 and cacd88e.

📒 Files selected for processing (9)
  • src/renderer/src/components/right-sidebar/ChecksPanel.tsx
  • src/renderer/src/components/sidebar/WorktreeCard.tsx
  • src/renderer/src/components/sidebar/WorktreeContextMenu.tsx
  • src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx
  • src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx
  • src/renderer/src/components/sidebar/use-worktree-issue-link.ts
  • src/renderer/src/components/sidebar/use-worktree-meta-workspace.ts
  • src/renderer/src/components/sidebar/worktree-meta-updates.test.ts
  • src/renderer/src/components/sidebar/worktree-meta-updates.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx
  • src/renderer/src/components/sidebar/worktree-meta-updates.test.ts
  • src/renderer/src/components/sidebar/WorktreeCard.tsx

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#12380)

* feat(sidebar): link Linear issues from Edit Worktree Details

The Issue field only accepted GitHub numbers, so a workspace tracking a
Linear issue had no way to say so from the dialog — the link could only be
set at creation time or through `orca worktree set --linear-issue`.

Replaces the field with one provider-aware row: a chip suffix inside the
input selects GitHub or Linear, and pasting a URL flips the chip to match.
A bare key never steers the provider — Linear and Jira issue keys are
byte-identical in shape, so shape alone cannot decide one.

One issue per workspace. A changed field displaces the other provider's
slot and the row names what Save is about to unlink. GitLab and Jira links
are left alone: the row cannot display them, and nothing else in the UI
could restore one it dropped.

- Folder workspaces read-only (their link is creation-time only)
- Remote runtimes assert the capability before writing or clearing, since
  `worktree.set` parses in strip mode and would silently drop the keys
- `updateWorktreeMeta` now reports failure so the dialog can stay open
  instead of closing over a save that refetch reverted
- Parses are length-bounded — `matchGitHubItemPath` strips trailing
  slashes with an unanchored regex that is quadratic on a large paste

* fix(sidebar): respect one-issue-per-workspace rule conditionally

Only clear displaced issue links when they actually existed, preventing
unnecessary Linear keys in GitHub-only workspaces. Skip comment updates
when unchanged to avoid workspace reordering. Add accessibility to
displacement messages and improve folder workspace error handling.

* fix(sidebar): resolve workspace ambiguity and improve Linear issue linki

The same workspace ID can exist under multiple hosts — the owner index reports
this as ambiguous rather than guessing. Dialog callers now pass their repoId so
lookups are unambiguous. Linear identifiers without an org key are resolved
across all workspaces (not just the active organization). Added race-condition
protection for async issue lookups and better change detection to avoid clearing
work-item titles when re-saving an identifier in different spelling.
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