From babed443817f07acf0dd5ad12f4f2ff26bb1abcb Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Mon, 3 Aug 2026 18:34:25 -0700 Subject: [PATCH] feat(sidebar): link Linear issues from Edit Worktree Details MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../handlers/worktree-linear-issue-link.ts | 36 +- src/cli/index.test.ts | 3 + .../src/components/sidebar/WorktreeCard.tsx | 6 +- .../sidebar/WorktreeIssueLinkField.tsx | 256 +++++++++++++ .../sidebar/WorktreeMetaDialog.test.tsx | 341 ++++++++++++++++++ .../components/sidebar/WorktreeMetaDialog.tsx | 269 +++++++++----- .../sidebar/use-worktree-issue-link.ts | 198 ++++++++-- .../sidebar/worktree-issue-displacement.ts | 37 ++ .../sidebar/worktree-meta-updates.test.ts | 253 ++++++++++--- .../sidebar/worktree-meta-updates.ts | 157 ++++++-- src/renderer/src/i18n/locales/en.json | 20 +- .../src/store/slices/worktree-helpers.ts | 4 +- src/renderer/src/store/slices/worktrees.ts | 43 ++- src/shared/issue-link-input.test.ts | 112 ++++++ src/shared/issue-link-input.ts | 75 ++++ src/shared/linear-links.test.ts | 81 +++++ src/shared/linear-links.ts | 52 +++ 17 files changed, 1713 insertions(+), 230 deletions(-) create mode 100644 src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx create mode 100644 src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-issue-displacement.ts create mode 100644 src/shared/issue-link-input.test.ts create mode 100644 src/shared/issue-link-input.ts diff --git a/src/cli/handlers/worktree-linear-issue-link.ts b/src/cli/handlers/worktree-linear-issue-link.ts index 2285da4f01a..c8e1020d847 100644 --- a/src/cli/handlers/worktree-linear-issue-link.ts +++ b/src/cli/handlers/worktree-linear-issue-link.ts @@ -1,17 +1,15 @@ -import { parseLinearIssueInput } from '../../shared/linear-links' +import { + buildLinearIssueLinkUpdates, + LINEAR_ISSUE_LINK_CLEARED, + type LinearIssueLinkUpdates +} from '../../shared/linear-links' import { RuntimeClientError } from '../runtime-client' -type LinearIssueLinkParams = { - linkedLinearIssue: string | null - linkedLinearIssueWorkspaceId: string | null - linkedLinearIssueOrganizationUrlKey: string | null -} - export function getOptionalLinearIssueLinkFlag( flags: Map, name: string, options: { allowNull?: boolean } = {} -): LinearIssueLinkParams | undefined { +): LinearIssueLinkUpdates | undefined { const value = getPresentStringFlag(flags, name) if (value === undefined) { return undefined @@ -24,28 +22,22 @@ export function getOptionalLinearIssueLinkFlag( 'Omit --linear-issue on create, or pass a Linear issue identifier or URL.' ) } - return { - linkedLinearIssue: null, - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: null - } + return { ...LINEAR_ISSUE_LINK_CLEARED } } - const parsed = parseLinearIssueInput(value) - if (!parsed) { + // Why: the shared builder treats empty input as "clear", which is right for a + // text field the user can blank but wrong for a flag — `--linear-issue " "` + // is a mistyped argument, not a request to unlink. Only the literal `null` + // clears, and that is handled above. + const updates = value.trim() === '' ? null : buildLinearIssueLinkUpdates(value) + if (!updates) { throw new RuntimeClientError( 'invalid_argument', 'Pass a Linear issue identifier like STA-335, a Linear issue URL, or null to clear.' ) } - return { - linkedLinearIssue: parsed.identifier, - // Why: changing a link must not keep a workspace id from a previous issue. - // The org key from URLs is enough for current-resolution to safely rehydrate it. - linkedLinearIssueWorkspaceId: null, - linkedLinearIssueOrganizationUrlKey: parsed.organizationUrlKey ?? null - } + return updates } function getPresentStringFlag( diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 6eb064bee28..b9429cb9d69 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1236,6 +1236,9 @@ describe('orca cli worktree awareness', () => { linkedIssue: undefined, linkedLinearIssue: 'STA-335', linkedLinearIssueWorkspaceId: null, + // Why: a bare identifier carries no org, and the two scoping fields + // describe the issue being replaced. Inheriting a stale org key would + // pin the lookup to a workspace this issue does not live in. linkedLinearIssueOrganizationUrlKey: null, comment: undefined, runHooks: false, diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 9cc437fc513..ac6417ef8a3 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -901,7 +901,11 @@ const WorktreeCard = React.memo(function WorktreeCard({ ) const handleRenameTitle = useCallback( - (displayName: string) => updateWorktreeMeta(worktree.id, { displayName }), + // Inline rename has no surface for the failure; the store already logs and + // refetches, which reverts the optimistic title in place. + async (displayName: string): Promise => { + await updateWorktreeMeta(worktree.id, { displayName }) + }, [updateWorktreeMeta, worktree.id] ) diff --git a/src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx b/src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx new file mode 100644 index 00000000000..501ef1bc607 --- /dev/null +++ b/src/renderer/src/components/sidebar/WorktreeIssueLinkField.tsx @@ -0,0 +1,256 @@ +import React, { useCallback, useId, useMemo } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { LinearIcon } from '@/components/icons/LinearIcon' +import { ChevronDown, ExternalLink, Github, LoaderCircle } from 'lucide-react' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { + ISSUE_LINK_PROVIDERS, + isIssueLinkProvider, + type IssueLinkProvider +} from '../../../../shared/issue-link-input' + +// Why: the value must clear the chip and the open-issue button that float over +// the input's right edge. Provider labels are localized, so the text share is +// measured in `ch` rather than baked into a Tailwind `pr-*` step that a longer +// translation would overlap. +const ADORNMENT_RESERVE_PX = 70 +const MAX_RESERVE = '55%' + +/** Exported for test: happy-dom drops `min()`, so this cannot be read back off a style. */ +export function issueAdornmentReserve(providerLabel: string): string { + return `min(calc(${ADORNMENT_RESERVE_PX}px + ${providerLabel.length}ch), ${MAX_RESERVE})` +} + +function providerLabel(provider: IssueLinkProvider): string { + return provider === 'linear' + ? translate('auto.components.sidebar.WorktreeIssueLinkField.25852bfc59', 'Linear') + : translate('auto.components.sidebar.WorktreeIssueLinkField.5b440069e6', 'GitHub') +} + +function ProviderIcon({ + provider, + className +}: { + provider: IssueLinkProvider + className?: string +}): React.JSX.Element { + return provider === 'linear' ? ( + + ) : ( + + ) +} + +export type WorktreeIssueLinkFieldProps = { + inputRef: React.RefObject + value: string + provider: IssueLinkProvider + /** Set when the current value cannot be saved, so the row can explain why. */ + isInvalid: boolean + /** Names the links this save would drop; both slots can be filled at once. */ + displacedLinkLabels: string[] | null + /** Folder workspaces have no persisted link slots — see the design doc. */ + isReadOnly: boolean + canOpenIssue: boolean + openingIssue: boolean + /** The last open attempt resolved to nothing — see useWorktreeIssueLink. */ + openIssueFailed: boolean + onValueChange: (value: string) => void + onProviderChange: (provider: IssueLinkProvider) => void + onOpenIssue: () => void + onKeyDown: (event: React.KeyboardEvent) => void +} + +export function WorktreeIssueLinkField(props: WorktreeIssueLinkFieldProps): React.JSX.Element { + const { + inputRef, + value, + provider, + isInvalid, + displacedLinkLabels, + isReadOnly, + canOpenIssue, + openingIssue, + openIssueFailed, + onValueChange, + onProviderChange, + onOpenIssue, + onKeyDown + } = props + + // Why: the helper `

` is the only surface for the invalid and displacement + // states, so it has to be announced with the field rather than just seen. + const helperId = useId() + const inputId = useId() + const label = providerLabel(provider) + const openIssueLabel = translate( + 'auto.components.sidebar.WorktreeIssueLinkField.161b2d053a', + 'Open linked issue' + ) + + const handleProviderChange = useCallback( + (next: string) => { + if (isIssueLinkProvider(next)) { + onProviderChange(next) + } + }, + [onProviderChange] + ) + + const helperText = useMemo(() => { + if (isReadOnly) { + return translate( + 'auto.components.sidebar.WorktreeIssueLinkField.d4785f9954', + "Issue links are set when a folder workspace is created and can't be changed here yet." + ) + } + if (isInvalid) { + return provider === 'linear' + ? translate( + 'auto.components.sidebar.WorktreeIssueLinkField.964d9bc00a', + 'Not a Linear issue key or linear.app issue URL.' + ) + : translate( + 'auto.components.sidebar.WorktreeIssueLinkField.0a7a2c6efd', + 'Not a GitHub issue number or issue URL.' + ) + } + // Why: ranked above displacement because it answers the click the user just + // made, and it clears as soon as they edit the value that caused it. + if (openIssueFailed) { + return provider === 'linear' + ? translate( + 'auto.components.sidebar.WorktreeIssueLinkField.d8c8a30d1f', + "Couldn't open that issue. Check the identifier and your Linear connection." + ) + : translate( + 'auto.components.sidebar.WorktreeIssueLinkField.269198eeda', + "Couldn't open that issue. Check the number and your GitHub connection." + ) + } + // Whole sentences per arity rather than a joined list: a translated " and " + // fragment would not survive languages that order or punctuate lists differently. + if (displacedLinkLabels && displacedLinkLabels.length > 1) { + return translate( + 'auto.components.sidebar.WorktreeIssueLinkField.72486800ff', + 'Saving unlinks {{first}} and {{second}} — a workspace tracks one issue.', + { first: displacedLinkLabels[0], second: displacedLinkLabels[1] } + ) + } + if (displacedLinkLabels?.length) { + return translate( + 'auto.components.sidebar.WorktreeIssueLinkField.2c245ac134', + 'Saving unlinks {{link}} — a workspace tracks one issue.', + { link: displacedLinkLabels[0] } + ) + } + return translate( + 'auto.components.sidebar.WorktreeIssueLinkField.f047887705', + 'Paste a GitHub or Linear URL, or enter a number. Leave blank to remove the link.' + ) + }, [displacedLinkLabels, isInvalid, isReadOnly, openIssueFailed, provider]) + + return ( +

+ +
+ onValueChange(e.target.value)} + onKeyDown={onKeyDown} + disabled={isReadOnly} + aria-invalid={isInvalid || undefined} + placeholder={translate( + 'auto.components.sidebar.WorktreeIssueLinkField.662ae142f8', + 'Issue #, or a GitHub or Linear URL' + )} + className="h-8 text-xs" + style={{ paddingRight: issueAdornmentReserve(label) }} + /> +
+ {/* Why: `modal` would stack a second scroll-lock layer over the + Dialog's, whose nested teardown strands pointer-events on body. */} + + + + + + + {ISSUE_LINK_PROVIDERS.map((item) => ( + + + {providerLabel(item)} + + ))} + + + + + + + + + {openIssueLabel} + + +
+
+ {/* Why: two lines are reserved up front. The dialog is centered by + transform, so a wrap-count change would shift the field being typed in. */} +

+ {helperText} +

+
+ ) +} diff --git a/src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx b/src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx new file mode 100644 index 00000000000..7c16a086220 --- /dev/null +++ b/src/renderer/src/components/sidebar/WorktreeMetaDialog.test.tsx @@ -0,0 +1,341 @@ +// @vitest-environment happy-dom + +import { act, type ReactNode } from 'react' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import type { FolderWorkspace, Repo, Worktree, WorktreeMeta } from '../../../../shared/types' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' + +// Why: Radix tooltips need a provider the dialog does not own, and the menu's +// portal needs real layout. Stand-ins keep these tests on provider selection. +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children?: ReactNode }) => <>{children}, + TooltipContent: () => null, + TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children} +})) + +vi.mock('@/components/ui/dropdown-menu', async () => { + const React = await import('react') + const SelectContext = React.createContext<(value: string) => void>(() => {}) + const Passthrough = ({ children }: { children?: ReactNode }) => <>{children} + return { + DropdownMenu: Passthrough, + DropdownMenuTrigger: Passthrough, + DropdownMenuContent: Passthrough, + DropdownMenuRadioGroup: ({ + value, + onValueChange, + children + }: { + value: string + onValueChange: (value: string) => void + children?: ReactNode + }) => ( + +
{children}
+
+ ), + DropdownMenuRadioItem: ({ value, children }: { value: string; children?: ReactNode }) => { + const onSelect = React.useContext(SelectContext) + return ( + + ) + } + } +}) + +import WorktreeMetaDialog from './WorktreeMetaDialog' + +const REPO_ID = 'repo-1' +const WORKTREE_ID = 'repo-1::/repo/worktrees/feature' + +const initialState = useAppStore.getInitialState() +const updateWorktreeMeta = + vi.fn< + ( + id: string, + updates: Partial + ) => Promise<{ ok: true } | { ok: false; error: string }> + >() + +function makeRepo(): Repo { + return { id: REPO_ID, path: '/repo', displayName: 'orca', badgeColor: '#999999', addedAt: 1 } +} + +function makeWorktree(overrides: Partial = {}): Worktree { + return { + id: WORKTREE_ID, + repoId: REPO_ID, + path: '/repo/worktrees/feature', + displayName: 'Feature work', + branch: 'feature', + head: 'abc123', + isBare: false, + isMainWorktree: false, + comment: 'existing note', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + ...overrides + } +} + +function makeFolderWorkspace(overrides: Partial = {}): FolderWorkspace { + return { + id: 'fw-1', + projectGroupId: 'pg-1', + name: 'Docs folder', + folderPath: '/repo/docs', + linkedTask: { + provider: 'linear', + type: 'issue', + number: 901, + title: 'Fix auth', + url: 'https://linear.app/acme/issue/STA-901', + linearIdentifier: 'STA-901' + }, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + createdAt: 1, + updatedAt: 1, + ...overrides + } +} + +function openDialog( + options: { + worktree?: Partial + worktreeId?: string + folderWorkspace?: Partial + } = {} +): void { + const worktree = makeWorktree(options.worktree) + useAppStore.setState({ + repos: [makeRepo()], + worktreesByRepo: { [REPO_ID]: [worktree] }, + ...(options.folderWorkspace + ? { folderWorkspaces: [makeFolderWorkspace(options.folderWorkspace)] } + : {}), + activeModal: 'edit-meta', + modalData: { + worktreeId: options.worktreeId ?? worktree.id, + currentDisplayName: worktree.displayName, + currentComment: worktree.comment, + focus: 'comment' + }, + updateWorktreeMeta + }) + render() +} + +function issueInput(): HTMLInputElement { + return screen.getByPlaceholderText('Issue #, or a GitHub or Linear URL') +} + +function providerChip(): HTMLButtonElement { + return screen.getByRole('button', { name: 'Issue provider' }) +} + +function saveButton(): HTMLButtonElement { + return screen.getByRole('button', { name: 'Save' }) +} + +describe('WorktreeMetaDialog issue link row', () => { + beforeEach(() => { + useAppStore.setState(initialState, true) + updateWorktreeMeta.mockReset() + updateWorktreeMeta.mockResolvedValue({ ok: true }) + Object.defineProperty(window, 'api', { + configurable: true, + value: { shell: { openUrl: vi.fn() } } + }) + }) + + afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + }) + + it('seeds the chip and value from a GitHub link', () => { + openDialog({ worktree: { linkedIssue: 42 } }) + + expect(providerChip().textContent).toContain('GitHub') + expect(issueInput().value).toBe('42') + }) + + it('seeds the chip and value from a Linear link', () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + expect(providerChip().textContent).toContain('Linear') + expect(issueInput().value).toBe('STA-335') + }) + + it('flips to Linear when a linear.app issue URL is pasted', () => { + openDialog({ worktree: { linkedIssue: 42 } }) + + fireEvent.change(issueInput(), { + target: { value: 'https://linear.app/acme/issue/STA-335/fix-the-thing' } + }) + + expect(providerChip().textContent).toContain('Linear') + }) + + // Why: Linear and Jira issue keys are the same shape, so only a URL may steer + // the provider — a bare key must never override the user's explicit choice. + it('keeps the chip on GitHub when a bare issue key is typed', () => { + openDialog({ worktree: { linkedIssue: 42 } }) + + fireEvent.change(issueInput(), { target: { value: 'GH-1234' } }) + + expect(providerChip().textContent).toContain('GitHub') + expect(providerChip().textContent).not.toContain('Linear') + }) + + it('flips to GitHub when a GitHub issue URL is pasted over a Linear link', () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + fireEvent.change(issueInput(), { + target: { value: 'https://github.com/acme/orca/issues/77' } + }) + + expect(providerChip().textContent).toContain('GitHub') + }) + + it('names the Linear issue that switching to GitHub would unlink', () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + fireEvent.click(screen.getByRole('menuitemradio', { name: 'GitHub' })) + fireEvent.change(issueInput(), { target: { value: '99' } }) + + expect( + screen.getByText('Saving unlinks Linear STA-335 — a workspace tracks one issue.') + ).toBeTruthy() + }) + + // Both slots can hold a link at once — naming only one understates the save. + it('names both links when clearing the field would drop both', () => { + openDialog({ worktree: { linkedIssue: 42, linkedLinearIssue: 'STA-335' } }) + + fireEvent.change(issueInput(), { target: { value: '' } }) + + expect( + screen.getByText( + 'Saving unlinks Linear STA-335 and GitHub #42 — a workspace tracks one issue.' + ) + ).toBeTruthy() + }) + + // A failed save refetches and reverts the optimistic write, so closing here + // would report success for an edit that silently undid itself. + it('keeps the dialog open and reports why when the save fails', async () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + updateWorktreeMeta.mockResolvedValue({ ok: false, error: 'Runtime is offline' }) + + fireEvent.change(issueInput(), { target: { value: 'STA-999' } }) + await act(async () => { + fireEvent.click(saveButton()) + }) + + expect(screen.getByRole('alert').textContent).toBe('Runtime is offline') + expect(useAppStore.getState().activeModal).toBe('edit-meta') + }) + + it('leaves the Linear link alone when only the comment is edited', async () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + fireEvent.change(screen.getByPlaceholderText('Notes about this worktree...'), { + target: { value: 'updated note' } + }) + + expect(screen.queryByText(/Saving unlinks/)).toBeNull() + + await act(async () => { + fireEvent.click(saveButton()) + }) + + await waitFor(() => expect(updateWorktreeMeta).toHaveBeenCalledTimes(1)) + const updates = updateWorktreeMeta.mock.calls[0]?.[1] ?? {} + expect(Object.keys(updates)).not.toContain('linkedLinearIssue') + expect(Object.keys(updates)).not.toContain('linkedIssue') + expect(updates.comment).toBe('updated note') + }) + + it('blocks saving an unparseable Linear value', () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + fireEvent.change(issueInput(), { target: { value: 'not an issue' } }) + + expect(screen.getByText('Not a Linear issue key or linear.app issue URL.')).toBeTruthy() + expect(saveButton().disabled).toBe(true) + }) + + it('is read-only for a folder workspace', () => { + openDialog({ worktreeId: folderWorkspaceKey('fw-1') }) + + expect(issueInput().disabled).toBe(true) + expect(providerChip().disabled).toBe(true) + expect( + screen.getByText( + "Issue links are set when a folder workspace is created and can't be changed here yet." + ) + ).toBeTruthy() + }) + + // Folder workspaces live outside worktreesByRepo, so the indexed lookup alone + // leaves the row blank and the link it does hold looks lost. + it('shows a folder workspace its own linked issue', () => { + openDialog({ worktreeId: folderWorkspaceKey('fw-1'), folderWorkspace: {} }) + + expect(issueInput().value).toBe('STA-901') + expect(providerChip().textContent).toContain('Linear') + }) + + // A background `orca worktree set` must not move the baseline mid-edit: the + // field would read as dirty and a comment-only save would write the stale seed. + it('keeps the baseline frozen when the store changes while open', async () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + act(() => { + useAppStore.setState({ + worktreesByRepo: { + [REPO_ID]: [makeWorktree({ linkedLinearIssue: 'STA-999' })] + } + }) + }) + fireEvent.change(screen.getByPlaceholderText('Notes about this worktree...'), { + target: { value: 'still working' } + }) + await act(async () => { + fireEvent.click(saveButton()) + }) + + const updates = updateWorktreeMeta.mock.calls[0]?.[1] ?? {} + expect(updates.comment).toBe('still working') + expect(updates).not.toHaveProperty('linkedLinearIssue') + expect(updates).not.toHaveProperty('linkedIssue') + }) + + it('dispatches nothing when the dialog is cancelled', async () => { + openDialog({ worktree: { linkedLinearIssue: 'STA-335' } }) + + fireEvent.change(issueInput(), { target: { value: '99' } }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(useAppStore.getState().activeModal).toBe('none') + }) +}) diff --git a/src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx b/src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx index 5163a839ebf..b5c1d059c57 100644 --- a/src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx +++ b/src/renderer/src/components/sidebar/WorktreeMetaDialog.tsx @@ -10,23 +10,41 @@ import { } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { getDisplacedLinkLabels } from './worktree-issue-displacement' import { buildWorktreeMetaUpdates, parseGitHubWorkItemNumberForMetaField, - type WorktreeMetaSavedPayload + type WorktreeMetaDraft, + type WorktreeMetaSavedPayload, + type WorktreeMetaSnapshot } from './worktree-meta-updates' import { useWorktreeIssueLink } from './use-worktree-issue-link' +import { WorktreeIssueLinkField } from './WorktreeIssueLinkField' import { getScreenSubmitShortcutLabel, isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' -import { ExternalLink, LoaderCircle } from 'lucide-react' import { useMountedRef } from '@/hooks/useMountedRef' import { translate } from '@/i18n/i18n' +import { findIndexedWorktreeOwner } from '@/lib/worktree-runtime-owner-index' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { folderWorkspaceToWorktree } from '../../../../shared/folder-workspace-worktree' +import { isWorkItemLinkQueryTooLarge } from '../../../../shared/new-workspace/work-item-link-query-bounds' +import { + getIssueLinkProviderFromUrl, + parseIssueLinkInput, + type IssueLinkProvider +} from '../../../../shared/issue-link-input' function resizeCommentTextarea(textarea: HTMLTextAreaElement): void { textarea.style.height = 'auto' textarea.style.height = `${textarea.scrollHeight}px` } +/** Only read before the first open, when nothing can be saved yet. */ +const EMPTY_SNAPSHOT: WorktreeMetaSnapshot = { + displayName: '', + issueInput: '', + issueProvider: 'github' +} + const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { const activeModal = useAppStore((s) => s.activeModal) const modalData = useAppStore((s) => s.modalData) @@ -40,9 +58,6 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { const worktreeId = typeof modalData.worktreeId === 'string' ? modalData.worktreeId : '' const currentDisplayName = typeof modalData.currentDisplayName === 'string' ? modalData.currentDisplayName : '' - const currentIssue = - typeof modalData.currentIssue === 'number' ? String(modalData.currentIssue) : '' - const currentPR = typeof modalData.currentPR === 'number' ? String(modalData.currentPR) : '' const currentComment = typeof modalData.currentComment === 'string' ? modalData.currentComment : '' const focusField = typeof modalData.focus === 'string' ? modalData.focus : 'comment' @@ -51,15 +66,73 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { ? (modalData.afterSave as (payload: WorktreeMetaSavedPayload) => void | Promise) : null + const workspaceScope = useMemo(() => parseWorkspaceKey(worktreeId), [worktreeId]) + // Why: link state is read from the store rather than threaded through the + // untyped modalData bag — a call site that forgot a key would otherwise seed + // an empty field and silently destroy the link on save. + const indexedWorktree = useAppStore((s) => { + const owner = findIndexedWorktreeOwner(s.worktreesByRepo, worktreeId) + return owner + ? s.worktreesByRepo[owner.repoId]?.find((item) => item.id === worktreeId) + : undefined + }) + // Why: folder workspaces are absent from worktreesByRepo, so the lookup above + // returns undefined and the row renders blank for them. The selector returns + // the stored record — a stable reference — and the projection happens outside + // it, because a selector that built the object would return a fresh identity + // on every store write and re-render the dialog continuously. + const folderWorkspace = useAppStore((s) => + workspaceScope?.type === 'folder' + ? (s.folderWorkspaces.find((item) => item.id === workspaceScope.folderWorkspaceId) ?? null) + : null + ) + const worktree = useMemo( + () => (folderWorkspace ? folderWorkspaceToWorktree(folderWorkspace) : indexedWorktree), + [folderWorkspace, indexedWorktree] + ) + const linkedIssue = worktree?.linkedIssue ?? null + const linkedLinearIssue = worktree?.linkedLinearIssue ?? null + // Why: ChecksPanel seeds the PR it is looking at, which may not be linked yet. + const currentPR = + typeof modalData.currentPR === 'number' + ? String(modalData.currentPR) + : worktree?.linkedPR != null + ? String(worktree.linkedPR) + : '' + // Why: `typeof` rather than a null check — an unhydrated projection can leave + // linkedIssue undefined, which `!== null` would read as a GitHub link. + const currentProvider: IssueLinkProvider = + typeof linkedIssue === 'number' ? 'github' : linkedLinearIssue ? 'linear' : 'github' + // Why: the value and its provider must come from one source. Every call site + // passed `currentIssue: worktree.linkedIssue`, so the modalData seed was pure + // duplication that could only ever drift from the chip. + const currentIssue = + currentProvider === 'linear' + ? (linkedLinearIssue ?? '') + : typeof linkedIssue === 'number' + ? String(linkedIssue) + : '' + // Why: folder workspaces persist links only through their creation-time + // linkedTask; updateWorktreeMeta drops link keys for them entirely. + const isFolderWorkspace = workspaceScope?.type === 'folder' + const [displayNameInput, setDisplayNameInput] = useState('') const [issueInput, setIssueInput] = useState('') + const [issueProvider, setIssueProvider] = useState('github') const [prInput, setPrInput] = useState('') const [commentInput, setCommentInput] = useState('') const [saving, setSaving] = useState(false) - const { canOpenIssue, openingIssue, handleOpenIssue, resetOpeningIssue } = useWorktreeIssueLink({ - worktreeId, - issueInput - }) + const [saveError, setSaveError] = useState(null) + const [snapshot, setSnapshot] = useState(EMPTY_SNAPSHOT) + const { canOpenIssue, openingIssue, openIssueFailed, handleOpenIssue, resetOpeningIssue } = + useWorktreeIssueLink({ + worktreeId, + issueInput, + issueProvider, + linearOrganizationUrlKey: worktree?.linkedLinearIssueOrganizationUrlKey ?? null, + linkedLinearIssue: worktree?.linkedLinearIssue ?? null, + linearSourceContext: worktree?.linkedTaskSourceContext ?? null + }) const issueInputRef = useRef(null) const prInputRef = useRef(null) @@ -70,12 +143,42 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { if (isOpen && !prevIsOpenRef.current) { setDisplayNameInput(currentDisplayName) setIssueInput(currentIssue) + setIssueProvider(currentProvider) setPrInput(currentPR) setCommentInput(currentComment) + // Why: the baseline is frozen with the seed instead of tracking the store. + // A background `orca worktree set --linear-issue` while the dialog is open + // would otherwise move it, making the untouched field read as dirty — and + // the next comment-only save would write the stale seed back over the new link. + setSnapshot({ + displayName: currentDisplayName, + issueInput: currentIssue, + issueProvider: currentProvider, + linkedWorkItemProvider: worktree?.linkedWorkItem?.provider ?? null, + linkedWorkItemType: worktree?.linkedWorkItem?.type ?? null + }) + setSaveError(null) resetOpeningIssue() } prevIsOpenRef.current = isOpen + const draft = useMemo( + () => ({ displayNameInput, issueInput, issueProvider, prInput, commentInput }), + [displayNameInput, issueInput, issueProvider, prInput, commentInput] + ) + + // Why: a URL names its provider unambiguously. A bare key does not — Linear + // and Jira identifiers are the same shape — so typing never steers the chip. + const handleIssueInputChange = useCallback((next: string) => { + setIssueInput(next) + // Why: the same bound the save gate applies. Detection parses on every + // keystroke, and the field accepts pasted URLs of any length. + const detected = isWorkItemLinkQueryTooLarge(next) ? null : getIssueLinkProviderFromUrl(next) + if (detected) { + setIssueProvider(detected) + } + }, []) + const setCommentTextareaRef = useCallback( (textarea: HTMLTextAreaElement | null) => { textareaRef.current = textarea @@ -92,18 +195,42 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { resizeCommentTextarea(event.currentTarget) }, []) + // Why: bound the parse before it runs on every keystroke — the field accepts + // pasted URLs and has no length cap of its own. + const issueInvalid = useMemo(() => { + const trimmed = issueInput.trim() + if (trimmed === '' || isFolderWorkspace) { + return false + } + return ( + isWorkItemLinkQueryTooLarge(trimmed) || parseIssueLinkInput(trimmed, issueProvider) === null + ) + }, [isFolderWorkspace, issueInput, issueProvider]) + const canSave = useMemo(() => { if (!worktreeId) { return false } - const trimmedIssue = issueInput.trim() const trimmedPR = prInput.trim() - const issueValid = - trimmedIssue === '' || parseGitHubWorkItemNumberForMetaField(trimmedIssue, 'issue') !== null + // Same quadratic-parse bound as the issue field — this runs on every keystroke. const prValid = - trimmedPR === '' || parseGitHubWorkItemNumberForMetaField(trimmedPR, 'pr') !== null - return issueValid && prValid - }, [worktreeId, issueInput, prInput]) + trimmedPR === '' || + (!isWorkItemLinkQueryTooLarge(trimmedPR) && + parseGitHubWorkItemNumberForMetaField(trimmedPR, 'pr') !== null) + return !issueInvalid && prValid + }, [worktreeId, issueInvalid, prInput]) + + const displacedLinkLabels = useMemo( + () => + getDisplacedLinkLabels({ + draft, + snapshot, + isFolderWorkspace, + linkedIssue, + linkedLinearIssue + }), + [draft, snapshot, isFolderWorkspace, linkedIssue, linkedLinearIssue] + ) const handleOpenChange = useCallback( (open: boolean) => { @@ -120,15 +247,18 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { } setSaving(true) try { - const updates = buildWorktreeMetaUpdates({ - displayNameInput, - currentDisplayName, - issueInput, - prInput, - commentInput - }) + const updates = buildWorktreeMetaUpdates(draft, snapshot) - await updateWorktreeMeta(worktreeId, updates) + const result = await updateWorktreeMeta(worktreeId, updates) + // Why: a failed save refetches and reverts the optimistic write. Closing + // here would report success for an edit that silently undid itself, and + // would discard the name, comment and PR changes in the same payload. + if (!result.ok) { + if (mountedRef.current) { + setSaveError(result.error) + } + return + } closeModal() // Why: follow-up refreshes should not turn a successful metadata save // into a failed dialog. @@ -142,19 +272,7 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { setSaving(false) } } - }, [ - worktreeId, - canSave, - displayNameInput, - currentDisplayName, - issueInput, - prInput, - commentInput, - updateWorktreeMeta, - closeModal, - afterSave, - mountedRef - ]) + }, [worktreeId, canSave, draft, snapshot, updateWorktreeMeta, closeModal, afterSave, mountedRef]) const handleCommentKeyDown = useCallback( (e: React.KeyboardEvent) => { @@ -204,8 +322,8 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() { {translate( - 'auto.components.sidebar.WorktreeMetaDialog.65770ad0f0', - 'Edit GitHub links and notes for this workspace.' + 'auto.components.sidebar.WorktreeMetaDialog.a0d191b7a7', + 'Edit issue links, pull request links, and notes for this workspace.' )} @@ -234,58 +352,21 @@ const WorktreeMetaDialog = React.memo(function WorktreeMetaDialog() {

-
- -
- setIssueInput(e.target.value)} - onKeyDown={handleIssueKeyDown} - placeholder={translate( - 'auto.components.sidebar.WorktreeMetaDialog.741279e7b7', - 'Issue # or GitHub URL' - )} - className="h-8 pr-9 text-xs" - /> - - - - - - {translate( - 'auto.components.sidebar.WorktreeMetaDialog.029ea5ec57', - 'Open GitHub issue' - )} - - -
-

- {translate( - 'auto.components.sidebar.WorktreeMetaDialog.7c454be4c5', - 'Paste an issue URL, or enter a number. Leave blank to remove the link.' - )} -

-
+
+ {saveError ? ( +

+ {saveError} +

+ ) : null} +