diff --git a/src/renderer/src/components/diff-comments/diff-comment-draft-zone.test.tsx b/src/renderer/src/components/diff-comments/diff-comment-draft-zone.test.tsx index 3ecac725d6e..1ea07325e4e 100644 --- a/src/renderer/src/components/diff-comments/diff-comment-draft-zone.test.tsx +++ b/src/renderer/src/components/diff-comments/diff-comment-draft-zone.test.tsx @@ -310,3 +310,31 @@ describe('useDiffCommentDraftZone teardown', () => { expect(fake.zones.size).toBe(0) }) }) + +it('submits a local draft through the owner callback captured when it opened', async () => { + const fake = createFakeDiffCommentEditor() + const onA = vi.fn().mockResolvedValue(true) + const onB = vi.fn().mockResolvedValue(true) + const hook = renderHook( + ({ onCreateComment }) => + useDiffCommentDraftZone({ + editor: fake.editor, + onCreateComment, + captureCreateComment: true + }), + { initialProps: { onCreateComment: onA } } + ) + act(() => { + hook.result.current.onAddCommentClickRef.current({ lineNumber: DRAFT_LINE, top: 0 }) + }) + hook.rerender({ onCreateComment: onB }) + await act(async () => { + submitDraft(fake, BODY) + }) + expect(onA).toHaveBeenCalledExactlyOnceWith({ + lineNumber: DRAFT_LINE, + startLine: undefined, + body: BODY + }) + expect(onB).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/diff-comments/diff-comment-draft-zone.ts b/src/renderer/src/components/diff-comments/diff-comment-draft-zone.ts index c9f3bd6bda5..a642ba8ea89 100644 --- a/src/renderer/src/components/diff-comments/diff-comment-draft-zone.ts +++ b/src/renderer/src/components/diff-comments/diff-comment-draft-zone.ts @@ -5,6 +5,10 @@ import { installDiffCommentZoneMouseDownStopper } from './diff-comment-zone-mous import { renderDiffCommentDraftCard } from './diff-comment-zone-card' import { resizeDiffCommentZone, + snapshotDiffCommentDraft, + type CarriedDiffCommentDraft, + type OpenDiffCommentDraft, + type RestoreDiffCommentDraft, DRAFT_ZONE_DEFAULT_HEIGHT, type DraftZoneEntry } from './diff-comment-view-zone-entry' @@ -14,12 +18,11 @@ export type DiffCommentDraft = { startLine?: number } -type CarriedDraft = { draft: DiffCommentDraft; body: string } - export type UseDiffCommentDraftZoneArgs = { editor: monacoEditor.ICodeEditor | null monacoModelIdentity?: string canOpenDraft?: boolean + captureCreateComment?: boolean onCreateComment?: (args: { lineNumber: number startLine?: number @@ -42,6 +45,7 @@ export function useDiffCommentDraftZone({ editor, monacoModelIdentity, canOpenDraft = true, + captureCreateComment = false, onCreateComment, draftPlaceholder, draftSubmitLabel, @@ -49,7 +53,7 @@ export function useDiffCommentDraftZone({ }: UseDiffCommentDraftZoneArgs): DiffCommentDraftZoneHandle { const draftZoneRef = useRef(null) // Retain the only draft copy between card teardown and replacement. - const pendingDraftRef = useRef(null) + const pendingDraftRef = useRef(null) const previousModelIdentityRef = useRef(monacoModelIdentity) const reanchorFrameRef = useRef(null) const onAddCommentClickRef = useRef< @@ -100,21 +104,23 @@ export function useDiffCommentDraftZone({ }, []) // Re-anchor frames and settling submits need the latest opener. - const openDraftRef = useRef<(draft: DiffCommentDraft, initialBody?: string) => boolean>( - () => false - ) + const openDraftRef = useRef(() => false) // Restore failed submissions after teardown unless another card now owns the composer; the toast covers displaced failures. - const restoreFailedSubmit = useCallback((draft: DiffCommentDraft, body: string): void => { - if (unmountedRef.current || draftZoneRef.current || openDraftRef.current(draft, body)) { + const restoreFailedSubmit = useCallback((draft, body, createComment) => { + if ( + unmountedRef.current || + draftZoneRef.current || + openDraftRef.current(draft, body, createComment) + ) { return } - pendingDraftRef.current = { draft, body } + pendingDraftRef.current = { draft, body, createComment } }, []) - const openDraft = useCallback( - (draft: DiffCommentDraft, initialBody = ''): boolean => { - if (!editor || !editor.getModel() || !onCreateCommentRef.current || !canOpenDraft) { + const openDraft = useCallback( + (draft, initialBody = '', capturedCreateComment = onCreateCommentRef.current) => { + if (!editor || !editor.getModel() || !capturedCreateComment || !canOpenDraft) { return false } @@ -156,6 +162,7 @@ export function useDiffCommentDraftZone({ root, draft, body: initialBody, + createComment: capturedCreateComment, submitting: false, disposeMouseDownStopper: () => { disposeDomMouseDownStopper() @@ -180,7 +187,9 @@ export function useDiffCommentDraftZone({ }, onCancel: () => disposeDraftZone(true), onSubmit: async (body) => { - const createComment = onCreateCommentRef.current + const createComment = captureCreateComment + ? entry.createComment + : onCreateCommentRef.current if (!createComment) { return false } @@ -202,7 +211,7 @@ export function useDiffCommentDraftZone({ disposeDraftZone(entry.domNode.contains(document.activeElement)) } } else if (draftZoneRef.current !== entry) { - restoreFailedSubmit(draft, body) + restoreFailedSubmit(draft, body, entry.createComment) } } } @@ -213,6 +222,7 @@ export function useDiffCommentDraftZone({ }, [ canOpenDraft, + captureCreateComment, disposeDraftZone, draftPlaceholder, draftSubmitLabel, @@ -233,7 +243,7 @@ export function useDiffCommentDraftZone({ reanchorFrameRef.current = requestAnimationFrame(() => { reanchorFrameRef.current = null const pending = pendingDraftRef.current - if (pending && openDraftRef.current(pending.draft, pending.body)) { + if (pending && openDraftRef.current(pending.draft, pending.body, pending.createComment)) { pendingDraftRef.current = null } }) @@ -256,7 +266,13 @@ export function useDiffCommentDraftZone({ // A new anchor must cancel any frame that would move the card back. cancelReanchorFrame() pendingDraftRef.current = null - if (!openDraft({ lineNumber: args.lineNumber, startLine: args.startLine }, carriedBody)) { + if ( + !openDraft( + { lineNumber: args.lineNumber, startLine: args.startLine }, + carriedBody, + current?.createComment ?? pending?.createComment + ) + ) { pendingDraftRef.current = pending } }, @@ -277,7 +293,7 @@ export function useDiffCommentDraftZone({ if (current) { // In-flight saves restore their own failures; carrying their text would allow duplicate submission. if (!current.submitting) { - pendingDraftRef.current = { draft: current.draft, body: current.body } + pendingDraftRef.current = snapshotDiffCommentDraft(current) } disposeDraftZone() } @@ -304,7 +320,7 @@ export function useDiffCommentDraftZone({ // Runs before the identity effect on a same-render swap, so stash here or the draft is lost. const current = draftZoneRef.current if (!unmountedRef.current && current && !current.submitting) { - pendingDraftRef.current = { draft: current.draft, body: current.body } + pendingDraftRef.current = snapshotDiffCommentDraft(current) } disposeDraftZone(false) } diff --git a/src/renderer/src/components/diff-comments/diff-comment-view-zone-entry.ts b/src/renderer/src/components/diff-comments/diff-comment-view-zone-entry.ts index b4f9072d693..98b62f2a035 100644 --- a/src/renderer/src/components/diff-comments/diff-comment-view-zone-entry.ts +++ b/src/renderer/src/components/diff-comments/diff-comment-view-zone-entry.ts @@ -22,6 +22,11 @@ export type DraftZoneEntry = { root: Root draft: { lineNumber: number; startLine?: number } body: string + createComment: (args: { + lineNumber: number + startLine?: number + body: string + }) => Promise // A save is in flight: the body must not be carried to another card, or the note could post twice. submitting: boolean disposeMouseDownStopper: () => void @@ -63,3 +68,20 @@ export function resizeDiffCommentZone( acc.layoutZone(entry.zoneId) }) } + +export type CarriedDiffCommentDraft = Pick +export type OpenDiffCommentDraft = ( + draft: DraftZoneEntry['draft'], + initialBody?: string, + createComment?: DraftZoneEntry['createComment'] +) => boolean + +export function snapshotDiffCommentDraft(entry: DraftZoneEntry): CarriedDiffCommentDraft { + return { draft: entry.draft, body: entry.body, createComment: entry.createComment } +} + +export type RestoreDiffCommentDraft = ( + draft: DraftZoneEntry['draft'], + body: string, + createComment: DraftZoneEntry['createComment'] +) => void diff --git a/src/renderer/src/components/diff-comments/diff-comment-zone-card.tsx b/src/renderer/src/components/diff-comments/diff-comment-zone-card.tsx index dfb1f44d205..ddd679b483f 100644 --- a/src/renderer/src/components/diff-comments/diff-comment-zone-card.tsx +++ b/src/renderer/src/components/diff-comments/diff-comment-zone-card.tsx @@ -1,3 +1,4 @@ +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import type { RefObject } from 'react' import type { Root } from 'react-dom/client' import { formatDiffComments } from '@/lib/diff-comments-format' @@ -46,6 +47,7 @@ function getSingleCommentSendScopes( // Callbacks arrive as refs so the rendered props keep the decorator's identity semantics. export type DiffCommentZoneCardContext = { + owner: DiffCommentOwner | null worktreeId: string filePath: string activeGroupId: string @@ -54,7 +56,7 @@ export type DiffCommentZoneCardContext = { onDeleteCommentRef: RefObject<(commentId: string) => void> onUpdateCommentRef: RefObject<((commentId: string, body: string) => Promise) | undefined> clearDeliveredDiffComments: ( - worktreeId: string, + owner: DiffCommentOwner, comments: readonly DiffCommentDeliverySnapshot[] ) => Promise } @@ -63,6 +65,7 @@ export function renderDiffCommentZoneCard( root: Root, comment: DecoratedDiffComment, { + owner, worktreeId, filePath, activeGroupId, @@ -103,6 +106,7 @@ export function renderDiffCommentZoneCard( headerActions={ worktreeId && comment.author === undefined ? ( void clearDeliveredDiffComments(worktreeId, notes)} + onDelivered={(notes) => void (owner && clearDeliveredDiffComments(owner, notes))} /> ) : null } diff --git a/src/renderer/src/components/diff-comments/use-diff-comment-owner.test.tsx b/src/renderer/src/components/diff-comments/use-diff-comment-owner.test.tsx new file mode 100644 index 00000000000..efa73cff8f1 --- /dev/null +++ b/src/renderer/src/components/diff-comments/use-diff-comment-owner.test.tsx @@ -0,0 +1,642 @@ +// @vitest-environment happy-dom +import { act, cleanup, render, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import type * as RuntimeRpcClient from '@/runtime/runtime-rpc-client' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import { makeFolderWorkspace, makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' +import { makeProjectGroup } from '@/components/sidebar/folder-workspace-composer-submit-fixtures' +import { resolveSourceFolderHost } from '@/lib/workspace-copy-owner' +import { makeOpenFile } from '@/store/slices/store-session-test-harness' +import { captureWorktreeOperationGenerationSnapshot } from '@/lib/worktree-operation-generation' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { DiffComment } from '../../../../shared/diff-comment-types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { Repo } from '../../../../shared/repo-types' +import { useCombinedDiffNotesActions } from '../editor/combined-diff/review-controls/use-combined-diff-notes-actions' +import { useMarkdownPreviewSourceFoundation } from '../editor/use-markdown-preview-source-foundation' +import { useSourceControlDiffCommentNotes } from '../right-sidebar/source-control/notes/use-diff-comment-notes' +import { useDiffCommentView, useOwnedDiffCommentTarget } from './use-diff-comment-owner' +import { useVisibleWorktreeDiffComments } from './use-visible-worktree-diff-comments' + +vi.mock('sonner', () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } })) +vi.mock('@/runtime/runtime-rpc-client', async (importOriginal) => ({ + ...(await importOriginal()), + callRuntimeRpc: vi.fn().mockResolvedValue({ ok: true }) +})) + +const REPO = 'repo-1' +const WT = `${REPO}::/work/a` +const OTHER = `${REPO}::/work/b` +const initialState = useAppStore.getState() +const SSH_BOX = { kind: 'worktree', authority: { endpoint: { kind: 'self' }, at: 'ssh:box' } } + +function row( + id: string, + hostId: ExecutionHostId, + diffComments: DiffComment[] = [], + runtimeOwnerEnvironmentId?: string +): Worktree { + return makeWorktree({ + id, + repoId: REPO, + path: id.slice(REPO.length + 2), + hostId, + diffComments, + ...(runtimeOwnerEnvironmentId ? { runtimeOwnerEnvironmentId } : {}) + }) +} + +function repoOn(id: string, executionHostId: ExecutionHostId): Repo { + return { + id, + path: `/work/${id}`, + displayName: id, + badgeColor: '#000', + addedAt: 0, + executionHostId + } +} + +function note(id: string, filePath = 'a.ts'): DiffComment { + return { id, worktreeId: WT, filePath, lineNumber: 1, body: id, createdAt: 1, side: 'modified' } +} + +// Same worktree on this computer and on an SSH host, plus an unrelated worktree. +function seedTwins(selected: ExecutionHostId, local = [note('l1'), note('l2')]) { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: selected, + worktreesByRepo: { + [REPO]: [row(WT, 'local', local), row(WT, 'ssh:box', [note('s1')]), row(OTHER, 'local')] + } + }) +} + +function replaceRow(hostId: ExecutionHostId, id: string, diffComments: DiffComment[]) { + useAppStore.setState((s) => ({ + worktreesByRepo: { + [REPO]: s.worktreesByRepo[REPO].map((w) => + w.id === id && w.hostId === hostId ? { ...w, diffComments } : w + ) + } + })) +} + +beforeEach(() => { + useAppStore.setState(initialState, true) + vi.mocked(callRuntimeRpc).mockClear() +}) + +afterEach(() => { + cleanup() +}) + +describe('note owner views', () => { + it('re-render only the consumer whose shown copy changed', () => { + seedTwins('ssh:box') + const renders = { open: 0, other: 0 } + function Probe({ id, name }: { id: string; name: keyof typeof renders }) { + useDiffCommentView(id, 'selection') + renders[name] += 1 + return null + } + render( + <> + + + + ) + renders.open = 0 + renders.other = 0 + + act(() => useAppStore.setState({ editorFontZoomLevel: 3 })) + expect(renders).toEqual({ open: 0, other: 0 }) + + // The unselected host's copy of the open worktree changes. + act(() => replaceRow('local', WT, [note('l3')])) + expect(renders).toEqual({ open: 0, other: 0 }) + + act(() => replaceRow('ssh:box', WT, [note('s2')])) + expect(renders).toEqual({ open: 1, other: 0 }) + }) + + it('do no row work for open Clear confirmations on unrelated writes', () => { + let idReads = 0 + const rows = Array.from({ length: 1000 }, (_, index) => { + const id = index === 0 ? WT : `${REPO}::/work/${index}` + const counted = row(id, 'local', index === 0 ? [note('l1')] : []) + Object.defineProperty(counted, 'id', { + enumerable: true, + get: () => { + idReads += 1 + return id + } + }) + return counted + }) + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'local', + worktreesByRepo: { [REPO]: rows } + }) + const { result } = renderHook(() => { + const { owner, comments } = useVisibleWorktreeDiffComments(WT, 'selection') + return { + combined: useCombinedDiffNotesActions({ + owner, + clearDiffComments: vi.fn(async () => true), + diffCommentsForWorktree: comments, + markdownReviewNotesEnabled: true + }), + sourceControl: useSourceControlDiffCommentNotes({ + activeWorktreeId: WT, + clearDiffComments: vi.fn(async () => true), + clearDiffCommentsForFile: vi.fn(async () => true) + }), + owner + } + }) + const owner = result.current.owner + if (!owner) { + throw new Error('no owner') + } + act(() => result.current.combined.setClearNotesDialogOpen(true)) + act(() => + result.current.sourceControl.setPendingDiffCommentsClear({ + kind: 'all', + worktreeId: WT, + owner, + count: 1 + }) + ) + expect(result.current.combined.clearNotesDialogVisible).toBe(true) + expect(result.current.sourceControl.resolvedPendingDiffCommentsClear).not.toBeNull() + + idReads = 0 + for (let write = 0; write < 20; write += 1) { + act(() => useAppStore.setState({ editorFontZoomLevel: write })) + } + expect(idReads).toBe(0) + }) + + it('do work linear in the catalog on listing and repo updates, none on unrelated writes', () => { + function cost(size: number) { + let reads = 0 + const counted = (record: T): T => { + const { id } = record + return Object.defineProperty(record, 'id', { + enumerable: true, + get: () => { + reads += 1 + return id + } + }) + } + const repos = [ + repoOn(REPO, 'local'), + repoOn(REPO, 'runtime:hub'), + ...Array.from({ length: size }, (_, index) => repoOn(`unrelated-${index}`, 'local')) + ].map(counted) + const rows = Array.from({ length: size }, (_, index) => + counted( + makeWorktree({ id: `${REPO}::/work/${index}`, repoId: REPO, diffComments: [note('n')] }) + ) + ) + useAppStore.setState({ repos, worktreesByRepo: { [REPO]: rows } }) + const ids = rows.map((row) => row.id) + const { result, unmount } = renderHook(() => + ids.map((id) => useDiffCommentView(id, { runtimeEnvironmentId: null })) + ) + expect(result.current.every((view) => view.comments?.length === 1)).toBe(true) + + reads = 0 + act(() => useAppStore.setState({ worktreesByRepo: { [REPO]: [...rows] } })) + act(() => useAppStore.setState({ repos: [...repos] })) + const updateReads = reads + reads = 0 + act(() => useAppStore.setState({ editorFontZoomLevel: size })) + expect(reads).toBe(0) + act(() => + useAppStore.setState({ + worktreesByRepo: { + [REPO]: [{ ...rows[0], id: ids[0], diffComments: [] }, ...rows.slice(1)] + } + }) + ) + expect(result.current[0].comments).toEqual([]) + unmount() + return updateReads + } + + // N views over N rows and N repos: linear growth is 10x, per-reader catalog scans 100x. + expect(cost(100)).toBeLessThanOrEqual(cost(10) * 20) + }) + + it('share folder qualification across readers: linear on catalog and server updates, none on unrelated writes', () => { + function cost(size: number) { + let reads = 0 + const folders = Array.from({ length: size }, (_, index) => { + const id = `folder-${index}` + return Object.defineProperty( + makeFolderWorkspace({ + id, + folderPath: `/f/${index}`, + executionHostId: 'local', + diffComments: [note('n')] + }), + 'id', + { + enumerable: true, + get: () => { + reads += 1 + return id + } + } + ) + }) + useAppStore.setState({ + folderWorkspaces: folders, + projectGroups: [{ ...makeProjectGroup(), executionHostId: 'local' }] + }) + // Every folder has a reader, and the first has five more. + const keys = [ + ...folders.map((folder) => `folder:${folder.id}`), + ...Array(5).fill('folder:folder-0') + ] + const { result, unmount } = renderHook(() => + keys.map((key) => useDiffCommentView(key, { runtimeEnvironmentId: null })) + ) + expect(result.current.every((view) => view.comments?.length === 1)).toBe(true) + + reads = 0 + act(() => useAppStore.setState({ folderWorkspaces: [...folders] })) + act(() => useAppStore.setState({ runtimeEnvironments: [] })) + const updateReads = reads + reads = 0 + act(() => useAppStore.setState({ editorFontZoomLevel: size })) + expect(reads).toBe(0) + act(() => + useAppStore.setState({ + folderWorkspaces: [ + makeFolderWorkspace({ ...folders[0], id: 'folder-0', diffComments: [] }), + ...folders.slice(1) + ] + }) + ) + expect(result.current.at(-1)?.comments).toEqual([]) + unmount() + return updateReads + } + + expect(cost(100)).toBeLessThanOrEqual(cost(10) * 20) + }) + + it('share one SSH qualification across same-id publications and readers on a listing update', () => { + function cost(copies: number) { + let hostReads = 0 + const rows = Array.from({ length: copies }, () => + Object.defineProperty( + makeWorktree({ id: WT, repoId: REPO, diffComments: [note('n')] }), + 'hostId', + { + enumerable: true, + get: () => { + hostReads += 1 + return 'ssh:box' + } + } + ) + ) + useAppStore.setState({ + repos: [{ ...repoOn(REPO, 'ssh:box'), connectionId: 'box' }], + worktreesByRepo: { [REPO]: rows } + }) + const { result, unmount } = renderHook(() => + Array.from({ length: 10 }, () => useDiffCommentView(WT, { runtimeEnvironmentId: null })) + ) + expect(result.current[0].owner).toMatchObject({ + authority: { endpoint: { kind: 'self' }, at: 'ssh:box' } + }) + + hostReads = 0 + act(() => useAppStore.setState({ worktreesByRepo: { [REPO]: [...rows] } })) + const updateReads = hostReads + unmount() + return updateReads + } + + // Ten readers over C same-id rows: shared qualification grows 10x, per-row peer scans 100x. + expect(cost(100)).toBeLessThanOrEqual(cost(10) * 20) + }) + + it('keep nothing for folders that are not listed', () => { + const missing = Array.from({ length: 50 }, (_, index) => + resolveSourceFolderHost(useAppStore.getState(), `folder:gone-${index}`, `gone-${index}`, { + runtimeEnvironmentId: null + }) + ) + expect(missing[0]).toEqual({ kind: 'missing' }) + // One shared answer: no per-id result was computed and retained. + expect(new Set(missing).size).toBe(1) + }) + + it('show a sole paired SSH copy selected through its server alias', () => { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'runtime:hub', + repos: [ + { + id: REPO, + path: '/work/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'box', + executionHostId: 'runtime:hub' + } + ], + worktreesByRepo: { [REPO]: [row(WT, 'ssh:box', [note('s1')])] } + }) + const { result } = renderHook(() => useVisibleWorktreeDiffComments(WT, 'selection')) + + expect(result.current.known).toBe(true) + expect(result.current.comments.map((comment) => comment.body)).toEqual(['s1']) + expect(result.current.owner).toEqual({ + kind: 'worktree', + worktreeId: WT, + authority: { endpoint: { kind: 'environment', environmentId: 'hub' }, at: 'ssh:box' } + }) + }) + + it('tell an unlisted copy apart from a listed copy with no notes', () => { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'ssh:box', + worktreesByRepo: { [REPO]: [row(WT, 'local', [note('l1')])] } + }) + const { result } = renderHook(() => useVisibleWorktreeDiffComments(WT, 'selection')) + expect(result.current).toMatchObject({ known: false, comments: [], owner: SSH_BOX }) + + act(() => replaceRow('local', WT, [])) + act(() => + useAppStore.setState((s) => ({ + worktreesByRepo: { [REPO]: [...s.worktreesByRepo[REPO], row(WT, 'ssh:box')] } + })) + ) + expect(result.current).toMatchObject({ known: true, comments: [], owner: SSH_BOX }) + }) + + it('keep the composer opener installed before rows load, capturing the copy it opens on', () => { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'ssh:box', + worktreesByRepo: { [REPO]: [] } + }) + const { result } = renderHook(() => + useOwnedDiffCommentTarget<{ line: number }>(WT, 'selection') + ) + const installedOpener = result.current[1] + seedTwins('ssh:box') + + act(() => installedOpener({ line: 1 })) + expect(result.current[2].current).toMatchObject(SSH_BOX) + + act(() => useAppStore.setState({ activeWorkspaceExecutionHostId: 'local' })) + act(() => installedOpener((target) => target && { line: target.line + 1 })) + expect(result.current[1]).toBe(installedOpener) + expect(result.current[2].current).toMatchObject(SSH_BOX) + }) + + it('read and save a Markdown preview on its source copy, not the selected one', async () => { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'local', + worktreesByRepo: { + [REPO]: [ + row(WT, 'local', [{ ...note('local B', 'a.md'), source: 'markdown' }]), + row(WT, 'runtime:hub', [{ ...note('runtime A', 'a.md'), source: 'markdown' }], 'hub') + ] + } + }) + const { result } = renderHook(() => + useMarkdownPreviewSourceFoundation({ + content: 'runtime A content', + filePath: '/work/a/a.md', + sourceFileId: null, + sourceWorktreeId: WT, + sourceRuntimeEnvironmentId: 'hub', + prewarmImages: false + }) + ) + const owner = result.current.commentOwner + if (!owner) { + throw new Error('no owner') + } + + expect(result.current.imageRuntimeContext?.target).toEqual({ + kind: 'environment', + environmentId: 'hub' + }) + expect(result.current.markdownComments.map((comment) => comment.body)).toEqual(['runtime A']) + await act(() => + useAppStore.getState().addDiffComment(owner, { + worktreeId: WT, + filePath: 'a.md', + source: 'markdown', + lineNumber: 1, + body: 'added', + side: 'modified' + }) + ) + expect(callRuntimeRpc).toHaveBeenCalledExactlyOnceWith( + { kind: 'environment', environmentId: 'hub' }, + 'worktree.set', + expect.objectContaining({ + diffComments: [ + expect.objectContaining({ body: 'runtime A' }), + expect.objectContaining({ body: 'added' }) + ] + }), + expect.anything() + ) + }) +}) + +describe('retained sources', () => { + const markdown = (body: string): DiffComment => ({ ...note(body, 'a.md'), source: 'markdown' }) + const preview = (sourceFileId: string | null) => + renderHook(() => + useMarkdownPreviewSourceFoundation({ + content: 'content', + filePath: '/work/a/a.md', + sourceFileId, + sourceWorktreeId: WT, + sourceRuntimeEnvironmentId: null, + prewarmImages: false + }) + ) + + it('read and save a direct SSH preview on its own copy while the local copy is selected', async () => { + const updateMeta = vi.fn().mockResolvedValue({}) + Object.defineProperty(window, 'api', { + configurable: true, + value: { worktrees: { updateMeta }, ui: { set: vi.fn() } } + }) + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'local', + worktreesByRepo: { + [REPO]: [row(WT, 'local', [markdown('local B')]), row(WT, 'ssh:box', [markdown('SSH A')])] + }, + openFiles: [ + makeOpenFile({ + id: 'source-a', + worktreeId: WT, + filePath: '/work/a/a.md', + relativePath: 'a.md', + runtimeEnvironmentId: null, + operationProvenance: { + generation: captureWorktreeOperationGenerationSnapshot({ + executionHostId: 'ssh:box', + runtimeEnvironmentId: null + }), + ownershipProjection: 'explicit' + } + }) + ] + }) + const { result } = preview('source-a') + const owner = result.current.commentOwner + if (!owner) { + throw new Error('no owner') + } + + expect(result.current.markdownComments.map((comment) => comment.body)).toEqual(['SSH A']) + await act(() => + useAppStore.getState().addDiffComment(owner, { + worktreeId: WT, + filePath: 'a.md', + source: 'markdown', + lineNumber: 1, + body: 'added', + side: 'modified' + }) + ) + expect(updateMeta).toHaveBeenCalledExactlyOnceWith({ + worktreeId: WT, + executionHostId: 'ssh:box', + updates: { + diffComments: [ + expect.objectContaining({ body: 'SSH A' }), + expect.objectContaining({ body: 'added' }) + ] + } + }) + const local = useAppStore.getState().worktreesByRepo[REPO][0] + expect(local.diffComments?.map((comment) => comment.body)).toEqual(['local B']) + }) + + it("keep this app's copy for an app source while a server's copy is selected", () => { + useAppStore.setState({ + activeWorktreeId: WT, + activeWorkspaceExecutionHostId: 'runtime:hub', + worktreesByRepo: { + [REPO]: [ + row(WT, 'local', [markdown('local A')]), + row(WT, 'runtime:hub', [markdown('hub B')], 'hub') + ] + } + }) + const { result } = preview(null) + + expect(result.current.markdownComments.map((comment) => comment.body)).toEqual(['local A']) + expect(result.current.commentOwner).toEqual({ + kind: 'worktree', + worktreeId: WT, + authority: { endpoint: { kind: 'self' }, at: 'local' } + }) + }) + + it('capture through an installed opener the source the surface shows now', () => { + useAppStore.setState({ + worktreesByRepo: { + [REPO]: [row(WT, 'runtime:a', [], 'a'), row(WT, 'runtime:b', [], 'b')] + } + }) + const { result, rerender } = renderHook( + ({ runtimeEnvironmentId }) => + useOwnedDiffCommentTarget<{ line: number }>(WT, { runtimeEnvironmentId }), + { initialProps: { runtimeEnvironmentId: 'a' } } + ) + const installedOpener = result.current[1] + rerender({ runtimeEnvironmentId: 'b' }) + + act(() => installedOpener({ line: 1 })) + expect(result.current[2].current).toMatchObject({ + authority: { endpoint: { kind: 'environment', environmentId: 'b' } } + }) + }) +}) + +describe('captured Clear confirmations', () => { + it('in combined diff keep the copy they opened on after the selected host changes', async () => { + seedTwins('ssh:box') + const clearDiffComments = vi.fn(async () => true) + const { result } = renderHook(() => { + const { owner, comments } = useVisibleWorktreeDiffComments(WT, 'selection') + return useCombinedDiffNotesActions({ + owner, + clearDiffComments, + diffCommentsForWorktree: comments, + markdownReviewNotesEnabled: true + }) + }) + + act(() => result.current.setClearNotesDialogOpen(true)) + act(() => useAppStore.setState({ activeWorkspaceExecutionHostId: 'local' })) + + expect(result.current.clearNotesDialogVisible).toBe(true) + expect(result.current.clearNotesCount).toBe(1) + await act(() => result.current.handleConfirmClearNotes()) + expect(clearDiffComments).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining(SSH_BOX), + expect.anything() + ) + }) + + it('in source control keep the copy they opened on after the selected host changes', async () => { + seedTwins('ssh:box') + const clearDiffComments = vi.fn(async () => true) + const { result } = renderHook(() => ({ + notes: useSourceControlDiffCommentNotes({ + activeWorktreeId: WT, + clearDiffComments, + clearDiffCommentsForFile: vi.fn(async () => true) + }), + owner: useDiffCommentView(WT, 'selection').owner + })) + const owner = result.current.owner + if (!owner) { + throw new Error('no owner') + } + + act(() => + result.current.notes.setPendingDiffCommentsClear({ + kind: 'all', + worktreeId: WT, + owner, + count: 1 + }) + ) + act(() => useAppStore.setState({ activeWorkspaceExecutionHostId: 'local' })) + + expect(result.current.notes.resolvedPendingDiffCommentsClear).not.toBeNull() + expect(result.current.notes.pendingDiffCommentsClearCount).toBe(1) + await act(() => result.current.notes.handleConfirmDiffCommentsClear()) + expect(clearDiffComments).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining(SSH_BOX), + expect.anything() + ) + }) +}) diff --git a/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts b/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts new file mode 100644 index 00000000000..9c4638c770d --- /dev/null +++ b/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts @@ -0,0 +1,68 @@ +import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' +import type { Dispatch, SetStateAction } from 'react' +import { useAppStore } from '@/store' +import { + createDiffCommentViewSelector, + createOwnedDiffCommentsSelector, + selectDiffCommentView, + sourceParts, + type DiffCommentOwner, + type DiffCommentView +} from '@/store/diff-comment-owner' +import type { WorkspaceCopySource } from '@/lib/workspace-copy-owner' +import type { DiffComment } from '../../../../shared/diff-comment-types' + +/** + * The notes a surface shows and the copy they belong to, from one read. A retained surface passes + * its own resource (its tab); only selection-bound views pass `'selection'`. + */ +export function useDiffCommentView( + worktreeId: string | null | undefined, + source: WorkspaceCopySource +): DiffCommentView { + const select = useMemo(() => createDiffCommentViewSelector(), []) + const [selection, runtimeEnvironmentId, externalSshTargetId, operationProvenance] = + sourceParts(source) + return useAppStore((state) => + select( + state, + worktreeId, + selection, + runtimeEnvironmentId, + externalSshTargetId, + operationProvenance + ) + ) +} + +/** The notes of a captured copy (an open confirmation), through the same cached read. */ +export function useOwnedDiffComments(owner: DiffCommentOwner | null): DiffComment[] | undefined { + const select = useMemo(() => createOwnedDiffCommentsSelector(), []) + return useAppStore((state) => select(state, owner)) +} + +/** A composer target whose owner is captured when it opens, so a later submit saves to that copy. */ +export function useOwnedDiffCommentTarget( + worktreeId: string | null | undefined, + source: WorkspaceCopySource +) { + const [target, setTarget] = useState(null) + const capturedOwner = useRef(null) + // Installed keyboard openers keep the first setter they were given, so it reads the current surface. + const current = useRef({ worktreeId, source }) + useLayoutEffect(() => { + current.current = { worktreeId, source } + }) + const setOwnedTarget = useCallback>>((value) => { + // Opening reads the copy this surface shows now; position-only updates keep it. + if (value && typeof value !== 'function') { + capturedOwner.current = selectDiffCommentView( + useAppStore.getState(), + current.current.worktreeId, + current.current.source + ).owner + } + setTarget(value) + }, []) + return [target, setOwnedTarget, capturedOwner] as const +} diff --git a/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts b/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts index 0c5a08eff4f..fe5b30f54f0 100644 --- a/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts +++ b/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts @@ -1,22 +1,33 @@ +import { useDiffCommentView } from './use-diff-comment-owner' +import type { DiffCommentOwner } from '@/store/diff-comment-owner' +import type { WorkspaceCopySource } from '@/lib/workspace-copy-owner' import { useMemo } from 'react' import { useAppStore } from '@/store' -import { selectWorktreeDiffCommentsOrEmpty } from '@/store/worktree-diff-comments-selector' import { isMarkdownReviewNotesEnabled, withoutMarkdownReviewNotes } from '@/lib/markdown-review-notes-setting' import type { DiffComment } from '../../../../shared/diff-comment-types' -export function useVisibleWorktreeDiffComments(worktreeId: string | null | undefined): { +const NO_COMMENTS: DiffComment[] = [] + +export function useVisibleWorktreeDiffComments( + worktreeId: string | null | undefined, + source: WorkspaceCopySource +): { + owner: DiffCommentOwner | null comments: DiffComment[] + /** False while the copy is unknown or not listed: no notes are shown, which is not "none". */ + known: boolean markdownReviewNotesEnabled: boolean } { - // Null owners still need the selector’s stable empty sentinel; inline arrays would churn Zustand subscribers. - const allComments = useAppStore((s) => selectWorktreeDiffCommentsOrEmpty(s, worktreeId)) + const { owner, comments: listed } = useDiffCommentView(worktreeId, source) + // Unknown copies still need a stable empty list; inline arrays would churn memoized consumers. + const allComments = listed ?? NO_COMMENTS const markdownReviewNotesEnabled = useAppStore((s) => isMarkdownReviewNotesEnabled(s.settings)) const comments = useMemo( () => (markdownReviewNotesEnabled ? allComments : withoutMarkdownReviewNotes(allComments)), [allComments, markdownReviewNotesEnabled] ) - return { comments, markdownReviewNotesEnabled } + return { owner, comments, known: listed !== undefined, markdownReviewNotesEnabled } } diff --git a/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx b/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx index 185dc78bc5a..c390bae3352 100644 --- a/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx +++ b/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx @@ -1,3 +1,4 @@ +import { diffCommentOwnerKey, type DiffCommentOwner } from '@/store/diff-comment-owner' import { useCallback, useEffect, useMemo, useRef } from 'react' import type { editor as monacoEditor } from 'monaco-editor' import { createRoot, type Root } from 'react-dom/client' @@ -25,6 +26,8 @@ import { useDiffCommentDraftZone, type DiffCommentDraft } from './diff-comment-d export type { DiffCommentDraft } type DecoratorArgs = { + captureCreateComment?: boolean + commentOwner?: DiffCommentOwner | null editor: monacoEditor.ICodeEditor | null // Monaco destroys model-scoped view zones on model swap, so rebuild even though the editor object is stable. monacoModelIdentity?: string @@ -55,6 +58,8 @@ type DecoratorArgs = { } export function useDiffCommentDecorator({ + captureCreateComment = false, + commentOwner = null, editor, monacoModelIdentity, filePath, @@ -78,6 +83,7 @@ export function useDiffCommentDecorator({ pendingScrollCommentId, onPendingScrollConsumed }: DecoratorArgs): void { + const ownerKey = commentOwner ? diffCommentOwnerKey(commentOwner) : null const clearDeliveredDiffComments = useAppStore((s) => s.clearDeliveredDiffComments) const activeGroupId = useAppStore((s) => worktreeId ? (s.activeGroupIdByWorktree[worktreeId] ?? worktreeId) : worktreeId @@ -106,6 +112,7 @@ export function useDiffCommentDecorator({ onPendingScrollConsumedRef.current = onPendingScrollConsumed const { onAddCommentClickRef, isDraftOpen } = useDiffCommentDraftZone({ + captureCreateComment, editor, monacoModelIdentity, onCreateComment, @@ -241,7 +248,7 @@ export function useDiffCommentDecorator({ pendingScrollRef.current = null scrollToZoneRef.current = null } - }, [cancelScrollToZoneFrame, editor, monacoModelIdentity]) + }, [cancelScrollToZoneFrame, editor, monacoModelIdentity, ownerKey]) useEffect(() => { if (!editor) { @@ -286,6 +293,7 @@ export function useDiffCommentDecorator({ const renderCard = (root: Root, comment: DecoratedDiffComment): void => { renderDiffCommentZoneCard(root, comment, { + owner: commentOwner, worktreeId, filePath, activeGroupId, @@ -386,6 +394,8 @@ export function useDiffCommentDecorator({ activeGroupId, cancelScrollToZoneFrame, clearDeliveredDiffComments, + commentOwner, + ownerKey, comments, editor, filePath, diff --git a/src/renderer/src/components/editor/ChangesModeView.tsx b/src/renderer/src/components/editor/ChangesModeView.tsx index 9bc0bc07dfe..bb0705bc676 100644 --- a/src/renderer/src/components/editor/ChangesModeView.tsx +++ b/src/renderer/src/components/editor/ChangesModeView.tsx @@ -89,6 +89,7 @@ export function ChangesModeView({ sideBySide={sideBySide} editable={true} worktreeId={activeFile.worktreeId} + noteSource={activeFile} onContentChange={onContentChange} onSave={onSave} /> diff --git a/src/renderer/src/components/editor/DiffNotesSendMenu.tsx b/src/renderer/src/components/editor/DiffNotesSendMenu.tsx index 20d192b697f..6bedfcf2c92 100644 --- a/src/renderer/src/components/editor/DiffNotesSendMenu.tsx +++ b/src/renderer/src/components/editor/DiffNotesSendMenu.tsx @@ -1,3 +1,4 @@ +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import React, { useCallback, useMemo } from 'react' import type { DiffComment } from '../../../../shared/diff-comment-types' import { useAppStore } from '@/store' @@ -10,6 +11,7 @@ import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' const OPEN_REQUEST_TTL_MS = 5000 export function DiffNotesSendMenu({ + owner, worktreeId, groupId, comments, @@ -23,6 +25,8 @@ export function DiffNotesSendMenu({ align = 'end', respondToOpenRequest = false }: { + /** The copy `comments` were read from, so delivered notes clear there. */ + owner: DiffCommentOwner | null worktreeId: string groupId: string comments: readonly DiffComment[] @@ -82,6 +86,7 @@ export function DiffNotesSendMenu({ return ( void clearDeliveredDiffComments(worktreeId, notes)} + onDelivered={(notes) => void (owner && clearDeliveredDiffComments(owner, notes))} /> ) } diff --git a/src/renderer/src/components/editor/DiffSectionItem.tsx b/src/renderer/src/components/editor/DiffSectionItem.tsx index 36436bd4285..e4b5c3cc769 100644 --- a/src/renderer/src/components/editor/DiffSectionItem.tsx +++ b/src/renderer/src/components/editor/DiffSectionItem.tsx @@ -1,14 +1,14 @@ +import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace-copy-owner' +import { useDiffCommentView } from '../diff-comments/use-diff-comment-owner' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { DiffOnMount } from '@monaco-editor/react' import type { editor as monacoEditor } from 'monaco-editor' import { detectLanguage } from '@/lib/language-detect' import { useAppStore } from '@/store' import { useEditorTypography } from '@/hooks/use-editor-typography' -import { selectWorktreeDiffComments } from '@/store/worktree-diff-comments-selector' import { useDiffCommentDecorator } from '../diff-comments/useDiffCommentDecorator' import { applyDiffEditorLineNumberOptions } from './diff-editor-line-number-options' import { DiffSectionHeader } from './DiffSectionHeader' -import type { DiffComment } from '../../../../shared/diff-comment-types' import { isDiffComment } from '@/lib/diff-comment-compat' import { installEditorSaveShortcut, installMonacoEditorFindShortcut } from './editor-shortcuts' import { DiffSectionBody } from './DiffSectionBody' @@ -29,6 +29,7 @@ export function DiffSectionItem({ isDark, sectionHeight, worktreeId, + noteSource = NO_RESOURCE_EVIDENCE, loadSection, loadDeferredSection, retrySection, @@ -50,15 +51,16 @@ export function DiffSectionItem({ const diffTypography = useEditorTypography('diff') const diffWordWrap = useAppStore((s) => s.settings?.diffWordWrap) const diffShowWhitespace = useAppStore((s) => s.settings?.diffShowWhitespace) + // One read: the stable notes array and the copy it belongs to; filter below so unrelated writes don't invalidate. + const { owner: commentOwner, comments: allDiffComments } = useDiffCommentView( + worktreeId, + noteSource + ) const addDiffComment = useAppStore((s) => s.addDiffComment) const deleteDiffComment = useAppStore((s) => s.deleteDiffComment) const updateDiffComment = useAppStore((s) => s.updateDiffComment) const scrollToDiffCommentId = useAppStore((s) => s.scrollToDiffCommentId) const setScrollToDiffCommentId = useAppStore((s) => s.setScrollToDiffCommentId) - // Select the stable worktree array and memoize filtering; fresh selector results would rerender this section on unrelated writes. - const allDiffComments = useAppStore((s): DiffComment[] | undefined => - selectWorktreeDiffComments(s, worktreeId) - ) const diffComments = useMemo( () => (allDiffComments ?? []).filter((c) => c.filePath === section.path && isDiffComment(c)), [allDiffComments, section.path] @@ -106,6 +108,7 @@ export function DiffSectionItem({ body: string }): Promise => { return submitDiffSectionComment({ + owner: commentOwner, addDiffComment, body, onAddLineComment, @@ -114,10 +117,12 @@ export function DiffSectionItem({ worktreeId }) }, - [addDiffComment, onAddLineComment, section, worktreeId] + [commentOwner, addDiffComment, onAddLineComment, section, worktreeId] ) useDiffCommentDecorator({ + captureCreateComment: !onAddLineComment, + commentOwner, editor: hasLineCommentAction ? modifiedEditor : null, monacoModelIdentity: `${modelPathBase}:modified`, filePath: section.path, @@ -129,13 +134,16 @@ export function DiffSectionItem({ onCreateComment: handleCreateComment, draftPlaceholder: addLineCommentPlaceholder, draftSubmitLabel: addLineCommentLabel, - canOpenDraft: !isLargeDiffLimited, + canOpenDraft: !isLargeDiffLimited && (commentOwner !== null || Boolean(onAddLineComment)), onDeleteComment: (id) => { if (worktreeId) { - void deleteDiffComment(worktreeId, id) + void (commentOwner && deleteDiffComment(commentOwner, id)) } }, - onUpdateComment: worktreeId ? (id, body) => updateDiffComment(worktreeId, id, body) : undefined, + onUpdateComment: worktreeId + ? (id, body) => + commentOwner ? updateDiffComment(commentOwner, id, body) : Promise.resolve(false) + : undefined, pendingScrollCommentId: pendingScrollForThisSection, onPendingScrollConsumed: () => setScrollToDiffCommentId(null) }) diff --git a/src/renderer/src/components/editor/DiffViewer.tsx b/src/renderer/src/components/editor/DiffViewer.tsx index 23366759dd5..4de8dd12e94 100644 --- a/src/renderer/src/components/editor/DiffViewer.tsx +++ b/src/renderer/src/components/editor/DiffViewer.tsx @@ -1,3 +1,5 @@ +import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace-copy-owner' +import { useDiffCommentView } from '../diff-comments/use-diff-comment-owner' import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { DiffEditor, type DiffOnMount } from '@monaco-editor/react' import type { editor } from 'monaco-editor' @@ -6,12 +8,10 @@ import { diffViewStateCache, setWithLRU } from '@/lib/scroll-cache' import { monacoTypographyOptions } from '@/lib/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { useContextualCopySetup } from './useContextualCopySetup' -import { selectWorktreeDiffComments } from '@/store/worktree-diff-comments-selector' import { useDiffCommentDecorator } from '../diff-comments/useDiffCommentDecorator' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { applyDiffEditorLineNumberOptions } from './diff-editor-line-number-options' -import type { DiffComment } from '../../../../shared/diff-comment-types' import { isDiffComment } from '@/lib/diff-comment-compat' import { installEditorSaveShortcut, installMonacoEditorFindShortcut } from './editor-shortcuts' import { diffEditorScrollbarOptions } from './diff-editor-scrollbar-options' @@ -50,6 +50,7 @@ export default function DiffViewer({ sideBySide, editable, worktreeId, + noteSource = NO_RESOURCE_EVIDENCE, onAddLineComment, commentableLineNumbers, addLineCommentLabel, @@ -64,16 +65,17 @@ export default function DiffViewer({ const diffCollapseUnchangedRegions = useAppStore((s) => s.settings?.diffCollapseUnchangedRegions) const monacoTheme = useMonacoTheme() const diffTypography = useEditorTypography('diff') + // One read: the stable notes array and the copy it belongs to; filter below so unrelated writes don't invalidate. + const { owner: commentOwner, comments: allDiffComments } = useDiffCommentView( + worktreeId, + noteSource + ) const addDiffComment = useAppStore((s) => s.addDiffComment) const deleteDiffComment = useAppStore((s) => s.deleteDiffComment) const language = usePluginSyntaxLanguage(filePath, coreLanguage) const updateDiffComment = useAppStore((s) => s.updateDiffComment) const scrollToDiffCommentId = useAppStore((s) => s.scrollToDiffCommentId) const setScrollToDiffCommentId = useAppStore((s) => s.setScrollToDiffCommentId) - // Select the stable worktree array; filter below so unrelated writes do not invalidate this viewer. - const allDiffComments = useAppStore((s): DiffComment[] | undefined => - selectWorktreeDiffComments(s, worktreeId) - ) const diffComments = useMemo( () => (allDiffComments ?? []).filter((c) => c.filePath === relativePath && isDiffComment(c)), [allDiffComments, relativePath] @@ -108,6 +110,11 @@ export default function DiffViewer({ return diffComments.some((c) => c.id === scrollToDiffCommentId) ? scrollToDiffCommentId : null }, [scrollToDiffCommentId, diffComments, worktreeId]) + // A draft keeps its captured owner across a same-tab rename but saves under the file's current path. + const relativePathRef = useRef(relativePath) + useLayoutEffect(() => { + relativePathRef.current = relativePath + }, [relativePath]) const handleCreateComment = useCallback( async ({ lineNumber, @@ -128,15 +135,17 @@ export default function DiffViewer({ if (!worktreeId) { return false } - const result = await addDiffComment({ - worktreeId, - filePath: relativePath, - source: 'diff', - startLine, - lineNumber, - body, - side: 'modified' - }) + const result = await (commentOwner + ? addDiffComment(commentOwner, { + worktreeId, + filePath: relativePathRef.current, + source: 'diff', + startLine, + lineNumber, + body, + side: 'modified' + }) + : null) if (!result) { toast.error( translate('auto.components.editor.diffCommentSaveFailed', 'Failed to save comment') @@ -144,11 +153,13 @@ export default function DiffViewer({ } return Boolean(result) }, - [addDiffComment, onAddLineComment, relativePath, worktreeId] + [commentOwner, addDiffComment, onAddLineComment, worktreeId] ) // Only local diffs can edit notes; gate the decorator on a valid comment target. useDiffCommentDecorator({ + captureCreateComment: !onAddLineComment, + commentOwner, editor: hasLineCommentAction ? modifiedEditor : null, monacoModelIdentity: modifiedModelKey ?? modelKey, filePath: relativePath, @@ -160,13 +171,17 @@ export default function DiffViewer({ onCreateComment: handleCreateComment, draftPlaceholder: addLineCommentPlaceholder, draftSubmitLabel: addLineCommentLabel, - canOpenDraft: !renderLimit.limited, + // Notes of an unknown copy can't be added to; hosted review comments have no local copy. + canOpenDraft: !renderLimit.limited && (commentOwner !== null || Boolean(onAddLineComment)), onDeleteComment: (id) => { if (worktreeId) { - void deleteDiffComment(worktreeId, id) + void (commentOwner && deleteDiffComment(commentOwner, id)) } }, - onUpdateComment: worktreeId ? (id, body) => updateDiffComment(worktreeId, id, body) : undefined, + onUpdateComment: worktreeId + ? (id, body) => + commentOwner ? updateDiffComment(commentOwner, id, body) : Promise.resolve(false) + : undefined, pendingScrollCommentId: pendingScrollForThisViewer, onPendingScrollConsumed: () => setScrollToDiffCommentId(null) }) diff --git a/src/renderer/src/components/editor/DiffViewer.word-wrap-lifecycle.test.tsx b/src/renderer/src/components/editor/DiffViewer.word-wrap-lifecycle.test.tsx index 02a07e788ed..d29ec25876f 100644 --- a/src/renderer/src/components/editor/DiffViewer.word-wrap-lifecycle.test.tsx +++ b/src/renderer/src/components/editor/DiffViewer.word-wrap-lifecycle.test.tsx @@ -3,6 +3,7 @@ import { act, cleanup, render } from '@testing-library/react' import { useEffect, useRef } from 'react' import { afterEach, describe, expect, it, vi } from 'vitest' import DiffViewer from './DiffViewer' +import { useDiffCommentDecorator } from '../diff-comments/useDiffCommentDecorator' import { DiffNavigationProvider, useDiffNavigation } from './diff-navigation-context' import { getLargeDiffRenderLimitFromCounts } from './large-diff-render-limit' @@ -39,7 +40,10 @@ const fixture = vi.hoisted(() => { scrollToDiffCommentId: null, setScrollToDiffCommentId: vi.fn() } - return { createEditor, editors, state } + const noView: { owner: { kind: 'worktree'; worktreeId: string } | null; comments?: [] } = { + owner: null + } + return { createEditor, editors, state, view: noView } }) vi.mock('@monaco-editor/react', () => ({ @@ -69,8 +73,11 @@ vi.mock('@monaco-editor/react', () => ({ vi.mock('@/store', () => ({ useAppStore: (selector: (state: typeof fixture.state) => T) => selector(fixture.state) })) -vi.mock('@/store/worktree-diff-comments-selector', () => ({ - selectWorktreeDiffComments: () => undefined +vi.mock('@/store/diff-comment-owner', () => ({ + sourceParts: () => [], + createDiffCommentViewSelector: () => () => fixture.view, + selectDiffCommentView: () => ({ owner: null, comments: undefined }), + diffCommentOwnerKey: () => '' })) vi.mock('@/lib/monaco-setup', () => ({ monaco: { Uri: { parse: (path: string) => path }, editor: { getModel: () => null } } @@ -153,3 +160,38 @@ describe('file diff word-wrap lifecycle', () => { expect(mounted?.disposeUpdate).toHaveBeenCalledOnce() }) }) + +describe('file diff review notes', () => { + it('saves a draft opened before a same-tab rename under the renamed path, on the captured copy', async () => { + const owner = { kind: 'worktree' as const, worktreeId: 'wt' } + fixture.view = { owner, comments: [] } + fixture.state.addDiffComment.mockResolvedValue({ id: 'saved' }) + const viewer = (relativePath: string) => ( + + + + ) + const view = render(viewer('a.ts')) + // The open draft keeps the submit callback it captured when it opened. + const captured = vi.mocked(useDiffCommentDecorator).mock.calls.at(-1)?.[0].onCreateComment + view.rerender(viewer('b.ts')) + + await act(async () => { + await captured?.({ lineNumber: 1, body: 'rename draft' }) + }) + expect(fixture.state.addDiffComment).toHaveBeenCalledExactlyOnceWith( + owner, + expect.objectContaining({ filePath: 'b.ts', body: 'rename draft' }) + ) + fixture.view = { owner: null } + }) +}) diff --git a/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx b/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx index 611cf9647c0..6f4fc4aa086 100644 --- a/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx +++ b/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx @@ -224,6 +224,7 @@ export function EditorConflictReviewSurface({ key={`${viewStateScopeId}:${contentFile.id}:${viewStateKeySuffix}`} fileId={contentFile.id} filePath={contentFile.filePath} + noteSource={contentFile} viewStateKey={selectedViewStateKey} viewStateId={editorViewStateId} relativePath={contentFile.relativePath} diff --git a/src/renderer/src/components/editor/EditorDiffFileSurface.tsx b/src/renderer/src/components/editor/EditorDiffFileSurface.tsx index 9158030d96f..dce533d2217 100644 --- a/src/renderer/src/components/editor/EditorDiffFileSurface.tsx +++ b/src/renderer/src/components/editor/EditorDiffFileSurface.tsx @@ -163,6 +163,7 @@ export function EditorDiffFileSurface({ sideBySide={sideBySide} editable={isEditable} worktreeId={activeFile.worktreeId} + noteSource={activeFile} onContentChange={isEditable ? onContentChange : undefined} onSave={isEditable ? (isMarkdown ? markdownDocuments.mdSave : onSave) : undefined} /> diff --git a/src/renderer/src/components/editor/EditorEditFileSurface.tsx b/src/renderer/src/components/editor/EditorEditFileSurface.tsx index 65a6e678c4a..2e14e551da1 100644 --- a/src/renderer/src/components/editor/EditorEditFileSurface.tsx +++ b/src/renderer/src/components/editor/EditorEditFileSurface.tsx @@ -246,6 +246,7 @@ export function EditorEditFileSurface({ key={monacoRemountKey} fileId={activeFile.id} filePath={activeFile.filePath} + noteSource={activeFile} viewStateKey={editorViewStateKey} viewStateId={viewStateScopeId} relativePath={activeFile.relativePath} diff --git a/src/renderer/src/components/editor/EditorMarkdownFileSurface.tsx b/src/renderer/src/components/editor/EditorMarkdownFileSurface.tsx index 4bb4c04d65a..10eefd580f1 100644 --- a/src/renderer/src/components/editor/EditorMarkdownFileSurface.tsx +++ b/src/renderer/src/components/editor/EditorMarkdownFileSurface.tsx @@ -111,6 +111,7 @@ export function EditorMarkdownFileSurface({ worktreeId={activeFile.worktreeId} externalSshTargetId={activeFile.externalSshTargetId} runtimeEnvironmentId={activeFile.runtimeEnvironmentId} + operationProvenance={activeFile.operationProvenance} scrollCacheKey={`${editorViewStateKey}:rich`} onContentChange={onContentChange} onDirtyStateHint={handleDirtyStateHint} diff --git a/src/renderer/src/components/editor/EditorPanelHeader.test.tsx b/src/renderer/src/components/editor/EditorPanelHeader.test.tsx index ad17ea8c387..ca99ce808b7 100644 --- a/src/renderer/src/components/editor/EditorPanelHeader.test.tsx +++ b/src/renderer/src/components/editor/EditorPanelHeader.test.tsx @@ -13,8 +13,11 @@ vi.mock('@/store', () => ({ }) })) -vi.mock('@/store/worktree-diff-comments-selector', () => ({ - selectWorktreeDiffCommentsOrEmpty: () => [] +vi.mock('@/store/diff-comment-owner', () => ({ + sourceParts: () => [], + createDiffCommentViewSelector: () => () => ({ owner: null, comments: [] }), + createOwnedDiffCommentsSelector: () => () => undefined, + diffCommentOwnerKey: () => '' })) vi.mock('@/components/ui/tooltip', () => ({ diff --git a/src/renderer/src/components/editor/EditorPanelHeader.tsx b/src/renderer/src/components/editor/EditorPanelHeader.tsx index f8c677a86d3..0b210144594 100644 --- a/src/renderer/src/components/editor/EditorPanelHeader.tsx +++ b/src/renderer/src/components/editor/EditorPanelHeader.tsx @@ -98,7 +98,10 @@ export function EditorPanelHeader({ onExportMarkdownToPdf, createArtifactRequest }: EditorPanelHeaderProps): React.JSX.Element { - const { comments: diffComments } = useVisibleWorktreeDiffComments(activeFile.worktreeId) + const { owner: commentOwner, comments: diffComments } = useVisibleWorktreeDiffComments( + activeFile.worktreeId, + activeFile + ) const activeGroupId = useAppStore((s) => s.activeGroupIdByWorktree[activeFile.worktreeId]) const diffWordWrap = useAppStore((s) => s.settings?.diffWordWrap === true) const diffShowWhitespace = useAppStore((s) => s.settings?.diffShowWhitespace === true) @@ -184,6 +187,7 @@ export function EditorPanelHeader({ )} {isSingleDiff && fileDiffComments.length > 0 && ( {sourceWorktree ? ( void clearDeliveredDiffComments(sourceWorktree.id, notes)} + onDelivered={(notes) => + void (commentOwner && clearDeliveredDiffComments(commentOwner, notes)) + } /> ) : null} diff --git a/src/renderer/src/components/editor/MonacoEditor.tsx b/src/renderer/src/components/editor/MonacoEditor.tsx index 25afc393a30..a6767d7a508 100644 --- a/src/renderer/src/components/editor/MonacoEditor.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.tsx @@ -14,6 +14,7 @@ import { MAX_TOKENIZATION_LINE_LENGTH } from '@/lib/monaco-languages/monarch-emb import { buildFileEditorWordWrapOptions } from './file-editor-word-wrap-options' import { toEditorModelUri } from './editor-model-uri' import { getEditorModelOwnerKey } from './editor-model-owner' +import { NO_RESOURCE_EVIDENCE, type WorkspaceResource } from '@/lib/workspace-copy-owner' import { getMonacoAutoHeightForContent, isMonacoAutoHeightCapped } from './monaco-auto-height' import { monacoFindOptions } from './monaco-find-options' import { useMonacoRevealScheduler } from './use-monaco-reveal-scheduler' @@ -48,6 +49,8 @@ type MonacoEditorProps = { revealMatchLength?: number markdownDocuments?: MarkdownDocument[] worktreeId?: string + /** The open file's tab; its review notes belong to the copy it names. */ + noteSource?: WorkspaceResource markdownAnnotationsEnabled?: boolean conflictDecorationsEnabled?: boolean readOnly?: boolean @@ -72,6 +75,7 @@ export default function MonacoEditor({ revealMatchLength, markdownDocuments, worktreeId, + noteSource = NO_RESOURCE_EVIDENCE, markdownAnnotationsEnabled = false, conflictDecorationsEnabled = false, readOnly = false, @@ -160,6 +164,7 @@ export default function MonacoEditor({ content, language, worktreeId, + noteSource, markdownAnnotationsEnabled }) diff --git a/src/renderer/src/components/editor/NotesSendMenu.test.tsx b/src/renderer/src/components/editor/NotesSendMenu.test.tsx index 9633fe1f339..e86a25b2955 100644 --- a/src/renderer/src/components/editor/NotesSendMenu.test.tsx +++ b/src/renderer/src/components/editor/NotesSendMenu.test.tsx @@ -234,6 +234,11 @@ function renderMenu( hookRuntime.index = 0 return expand( + owner={{ + kind: 'worktree', + worktreeId: 'wt-1', + authority: { endpoint: { kind: 'self' }, at: 'local' } + }} worktreeId="wt-1" groupId="group-1" modeIdParts={['markdown-notes', 'wt-1', 'README.md', 'rail']} @@ -278,6 +283,17 @@ describe('NotesSendMenu', () => { expect(storeMocks.openAgentSendPopoverTargetMode).not.toHaveBeenCalled() }) + it('disables the trigger without claiming the notes were sent while their copy is unknown', () => { + const tree = renderMenu({ + owner: null, + scopes: [{ id: 'all', label: 'All unsent notes', notes: [note('1')], formatPrompt: () => '' }] + }) + + expect(findByType(tree, 'button').props.disabled).toBe(true) + expect(findByType(tree, 'button').props.title).toBeUndefined() + expect(findAllByType(tree, 'TooltipContent')).toHaveLength(0) + }) + it('opens and closes target mode with the default scope', () => { const onDelivered = vi.fn() const tree = renderMenu({ onDelivered }) diff --git a/src/renderer/src/components/editor/NotesSendMenu.tsx b/src/renderer/src/components/editor/NotesSendMenu.tsx index fa64bdcb215..efcb9a8bc61 100644 --- a/src/renderer/src/components/editor/NotesSendMenu.tsx +++ b/src/renderer/src/components/editor/NotesSendMenu.tsx @@ -1,3 +1,4 @@ +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import React, { useCallback, useEffect, useMemo, useState } from 'react' import { Send, Sparkles } from 'lucide-react' import { useAppStore } from '@/store' @@ -43,6 +44,8 @@ type SendableNotesScope = Omit, 'formatPrompt'> } export type NotesSendMenuProps = { + /** The copy the notes were read from; null while it is unknown, which disables Send without a message. */ + owner: DiffCommentOwner | null worktreeId: string groupId: string modeIdParts: readonly string[] @@ -71,6 +74,7 @@ export function buildNotesSendTargetModeId(modeIdParts: readonly string[]): stri } export function NotesSendMenu({ + owner, worktreeId, groupId, modeIdParts, @@ -99,10 +103,12 @@ export function NotesSendMenu({ const sendableScopes = useMemo[]>(() => { void inFlightVersion return scopes.map(({ formatPrompt, ...scope }) => { - const notes = scope.notes.filter((note) => !isNoteInFlight(diffCommentSendKey(note))) + const notes = owner + ? scope.notes.filter((note) => !isNoteInFlight(diffCommentSendKey(owner, note))) + : [] return { ...scope, notes, prompt: notes.length > 0 ? formatPrompt(notes) : '' } }) - }, [inFlightVersion, scopes]) + }, [inFlightVersion, owner, scopes]) const enabledScopes = useMemo( () => sendableScopes.filter((scope) => scope.notes.length > 0), [sendableScopes] @@ -113,10 +119,12 @@ export function NotesSendMenu({ }, [defaultScopeId, enabledScopes]) const hasDeliverableNotes = enabledScopes.length > 0 // Notes only on their way to an agent are not sent yet. - const disabledTitle = scopes.some((scope) => scope.notes.length > 0) - ? translate('components.native-chat.question.sending', 'Sending…') - : (disabledTooltip ?? - translate('auto.components.editor.NotesSendMenu.allNotesSent', 'All notes sent')) + const disabledTitle = !owner + ? undefined + : scopes.some((scope) => scope.notes.length > 0) + ? translate('components.native-chat.question.sending', 'Sending…') + : (disabledTooltip ?? + translate('auto.components.editor.NotesSendMenu.allNotesSent', 'All notes sent')) const markDelivered = useCallback( (notes: readonly TNote[]) => { @@ -126,8 +134,12 @@ export function NotesSendMenu({ ) const holdInFlight = useCallback( (notes: readonly TNote[]) => (delivered: Promise) => - holdNotesForSend(notes.map(diffCommentSendKey), delivered, () => markDelivered(notes)), - [markDelivered] + holdNotesForSend( + owner ? notes.map((note) => diffCommentSendKey(owner, note)) : [], + delivered, + () => markDelivered(notes) + ), + [markDelivered, owner] ) const openTargetMode = useCallback( @@ -245,9 +257,11 @@ export function NotesSendMenu({ - - {hasDeliverableNotes ? enabledSendTooltip() : disabledTitle} - + {hasDeliverableNotes || disabledTitle ? ( + + {hasDeliverableNotes ? enabledSendTooltip() : disabledTitle} + + ) : null} s.editorFontZoomLevel) const activateMarkdownLink = useAppStore((s) => s.activateMarkdownLink) + // One read: the stable notes array and the copy it belongs to; filter below so unrelated writes don't invalidate. + const noteSource = { runtimeEnvironmentId, externalSshTargetId, operationProvenance } + const { owner: commentOwner, comments: allDiffComments } = useDiffCommentView( + worktreeId, + noteSource + ) const addDiffComment = useAppStore((s) => s.addDiffComment) const deleteDiffComment = useAppStore((s) => s.deleteDiffComment) const updateDiffComment = useAppStore((s) => s.updateDiffComment) const clearDeliveredDiffComments = useAppStore((s) => s.clearDeliveredDiffComments) - const allDiffComments = useAppStore((s): DiffComment[] | undefined => - selectWorktreeDiffComments(s, worktreeId) - ) const { codec, htmlSuperscriptLinkContext, worktreeRoot } = useRichMarkdownSuperscriptLinkSetup({ filePath, runtimeEnvironmentId, @@ -107,11 +110,13 @@ export default function RichMarkdownEditor({ editorRef, filePath, markdownAnnotationFilePath, - markdownAnnotationsEnabled, + // Notes of an unknown copy can't be added to. + markdownAnnotationsEnabled: markdownAnnotationsEnabled && commentOwner !== null, markdownReviewContent, markdownSourceLineOffset, rootRef, scrollContainerRef, + noteSource, worktreeId, worktreeRoot }) @@ -325,6 +330,7 @@ export default function RichMarkdownEditor({ return ( void review.handleCopyMarkdownReviewNotes()} onCopyReviewNote={(note) => void review.handleCopyMarkdownReviewNote(note)} onToggleReviewRail={() => review.setReviewRailOpen((open) => !open)} - onReviewNotesDelivered={(notes) => void clearDeliveredDiffComments(worktreeId, notes)} + onReviewNotesDelivered={(notes) => + void (commentOwner && clearDeliveredDiffComments(commentOwner, notes)) + } onReviewNoteSourceClick={review.scrollRichMarkdownReviewNoteSourceIntoView} - onDeleteReviewComment={(commentId) => void deleteDiffComment(worktreeId, commentId)} + onDeleteReviewComment={(commentId) => + void (commentOwner && deleteDiffComment(commentOwner, commentId)) + } onSubmitReviewCommentEdit={(commentId, body) => - updateDiffComment(worktreeId, commentId, body) + commentOwner ? updateDiffComment(commentOwner, commentId, body) : Promise.resolve(false) } onReviewNoteContentResize={review.syncNotePositions} onNavigateTableOfContentsItem={navigateToTableOfContentsItem} diff --git a/src/renderer/src/components/editor/RichMarkdownEditorSurface.tsx b/src/renderer/src/components/editor/RichMarkdownEditorSurface.tsx index a13c6a5f6cf..e550cc2b76e 100644 --- a/src/renderer/src/components/editor/RichMarkdownEditorSurface.tsx +++ b/src/renderer/src/components/editor/RichMarkdownEditorSurface.tsx @@ -1,3 +1,4 @@ +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import type React from 'react' import { EditorContent } from '@tiptap/react' import type { Editor } from '@tiptap/react' @@ -52,6 +53,7 @@ type RichMarkdownEditorSurfaceProps = { attentionReviewCommentId: string | null copiedReviewNoteId: string | null markdownReviewContent: string + commentOwner: DiffCommentOwner | null worktreeId: string filePath: string markdownCommentsCount: number @@ -144,6 +146,7 @@ export function RichMarkdownEditorSurface({ attentionReviewCommentId, copiedReviewNoteId, markdownReviewContent, + commentOwner, worktreeId, filePath, markdownCommentsCount, @@ -232,6 +235,7 @@ export function RichMarkdownEditorSurface({ {reviewRailVisible && notePositions.length > 0 ? ( {markdownCommentsCount > 0 ? ( void @@ -39,6 +41,7 @@ export function RichMarkdownReviewNoteLayer({ attentionCommentId, copiedCommentId, markdownReviewContent, + owner, worktreeId, filePath, onCopyNote, @@ -58,7 +61,7 @@ export function RichMarkdownReviewNoteLayer({ > {positions.map(({ comment, top }) => (
: } s.openBranchAllDiffs) const updateSettings = useAppStore((s) => s.updateSettings) const clearDiffComments = useAppStore((s) => s.clearDiffComments) - const { comments: diffCommentsForWorktree, markdownReviewNotesEnabled } = - useVisibleWorktreeDiffComments(file.worktreeId) + // The notes of the copy this diff was read from (the file's server when it names one). + const notesView = useVisibleWorktreeDiffComments(file.worktreeId, file) const activeGroupId = useAppStore((s) => s.activeGroupIdByWorktree[file.worktreeId]) const canOpenWorkspaceFileBrowserForPath = useWorkspaceFileBrowserActionPredicate(file.worktreeId) const isDark = useDocumentDarkTheme() @@ -90,10 +90,10 @@ export default function CombinedDiffViewer({ sectionsRef: registry.sectionsRef }) const notes = useCombinedDiffNotesActions({ + owner: notesView.owner, clearDiffComments, - diffCommentsForWorktree, - markdownReviewNotesEnabled, - worktreeId: file.worktreeId + diffCommentsForWorktree: notesView.comments, + markdownReviewNotesEnabled: notesView.markdownReviewNotesEnabled }) const preferences = useCombinedDiffViewPreferences({ combinedDiffFileTreeVisibleByDefault, @@ -338,7 +338,8 @@ export default function CombinedDiffViewer({ branchCompare={entrySet.branchCompare} commitCompare={entrySet.commitCompare} diffCommentCount={notes.diffCommentCount} - diffCommentsForWorktree={diffCommentsForWorktree} + commentOwner={notesView.owner} + diffCommentsForWorktree={notesView.comments} diffShowWhitespace={diffShowWhitespace} diffWordWrap={diffWordWrap} file={file} @@ -377,7 +378,8 @@ export default function CombinedDiffViewer({
void notes.handleConfirmClearNotes()} open={notes.clearNotesDialogVisible} diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-toolbar.tsx b/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-toolbar.tsx index 01cda2a17b8..9ba014b838c 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-toolbar.tsx +++ b/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-toolbar.tsx @@ -6,6 +6,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip import { translate } from '@/i18n/i18n' import type { OpenFile } from '@/store/slices/editor' import type { DiffComment } from '../../../../../../shared/diff-comment-types' +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import { DiffNotesSendMenu } from '../../DiffNotesSendMenu' import { DiffNotesPreviewPopover } from './combined-diff-notes-popover' @@ -40,6 +41,7 @@ export function CombinedDiffToolbar({ allSectionsCollapsed, branchCompare, commitCompare, + commentOwner, diffCommentCount, diffCommentsForWorktree, diffShowWhitespace, @@ -66,6 +68,7 @@ export function CombinedDiffToolbar({ allSectionsCollapsed: boolean branchCompare: NonNullable | null commitCompare: NonNullable | null + commentOwner: DiffCommentOwner | null diffCommentCount: number diffCommentsForWorktree: DiffComment[] diffShowWhitespace: boolean | undefined @@ -152,6 +155,7 @@ export function CombinedDiffToolbar({ Promise @@ -18,15 +22,15 @@ export type CombinedDiffNotesActions = { } export function useCombinedDiffNotesActions({ + owner, clearDiffComments, diffCommentsForWorktree, - markdownReviewNotesEnabled, - worktreeId + markdownReviewNotesEnabled }: { - clearDiffComments: (worktreeId: string, options?: DiffCommentsClearOptions) => Promise + owner: DiffCommentOwner | null + clearDiffComments: AppState['clearDiffComments'] diffCommentsForWorktree: DiffComment[] markdownReviewNotesEnabled: boolean - worktreeId: string }): CombinedDiffNotesActions { const diffCommentCount = diffCommentsForWorktree.length const diffCommentsPrompt = React.useMemo( @@ -41,12 +45,39 @@ export function useCombinedDiffNotesActions({ [diffCommentsForWorktree] ) - const [clearNotesDialogOpen, setClearNotesDialogOpen] = useState(false) + // The confirmation acts on the copy shown when it opened, whatever is selected later. + const [clearTarget, setClearTarget] = useState<{ owner: DiffCommentOwner; count: number } | null>( + null + ) + const clearNotesDialogOpen = clearTarget !== null + const setClearNotesDialogOpen: React.Dispatch> = useCallback( + (value) => { + const next = typeof value === 'function' ? value(clearNotesDialogOpen) : value + if (!next) { + setClearTarget(null) + } else if (!clearNotesDialogOpen && owner) { + setClearTarget({ owner, count: diffCommentCount }) + } + }, + [clearNotesDialogOpen, diffCommentCount, owner] + ) + const ownedComments = useOwnedDiffComments(clearTarget?.owner ?? null) + // A copy gone since opening keeps its count, so confirming reports the failure. + const clearNotesCount = React.useMemo( + () => + !clearTarget + ? 0 + : !ownedComments + ? clearTarget.count + : (markdownReviewNotesEnabled ? ownedComments : withoutMarkdownReviewNotes(ownedComments)) + .length, + [clearTarget, markdownReviewNotesEnabled, ownedComments] + ) const [isClearingNotes, setIsClearingNotes] = useState(false) - const clearNotesDialogVisible = clearNotesDialogOpen && (diffCommentCount > 0 || isClearingNotes) + const clearNotesDialogVisible = clearNotesDialogOpen && (clearNotesCount > 0 || isClearingNotes) if (clearNotesDialogOpen && !clearNotesDialogVisible) { // External note clearing must close the dialog before an empty confirmation can paint. - setClearNotesDialogOpen(false) + setClearTarget(null) } const [notesCopied, setNotesCopied] = useState(false) const mountedRef = useRef(true) @@ -100,12 +131,12 @@ export function useCombinedDiffNotesActions({ }, [clearNotesCopiedResetTimer, diffCommentCount, diffCommentsPrompt]) const handleConfirmClearNotes = useCallback(async (): Promise => { - if (diffCommentCount === 0 || isClearingNotes) { + if (!clearTarget || clearNotesCount === 0 || isClearingNotes) { return } setIsClearingNotes(true) try { - const ok = await clearDiffComments(worktreeId, { + const ok = await clearDiffComments(clearTarget.owner, { keepMarkdownNotes: !markdownReviewNotesEnabled }) if (!mountedRef.current) { @@ -126,9 +157,17 @@ export function useCombinedDiffNotesActions({ setIsClearingNotes(false) } } - }, [clearDiffComments, diffCommentCount, isClearingNotes, markdownReviewNotesEnabled, worktreeId]) + }, [ + clearDiffComments, + clearNotesCount, + clearTarget, + isClearingNotes, + markdownReviewNotesEnabled, + setClearNotesDialogOpen + ]) return { + clearNotesCount, clearNotesDialogVisible, diffCommentCount, handleConfirmClearNotes, diff --git a/src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx b/src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx index 95c79a4d58c..730e1084982 100644 --- a/src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx +++ b/src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx @@ -8,6 +8,7 @@ import type { Virtualizer } from '@tanstack/react-virtual' import { joinPath } from '@/lib/path' import type { OpenFile } from '@/store/slices/editor' import type { DiffComment } from '../../../../../../shared/diff-comment-types' +import type { DiffCommentOwner } from '@/store/diff-comment-owner' import { DiffSectionItem } from '../../DiffSectionItem' import type { DiffSectionItemProps } from '../../diff-section-item-props' import { DiffNotesSendMenu } from '../../DiffNotesSendMenu' @@ -19,6 +20,7 @@ import { translate } from '@/i18n/i18n' export function CombinedDiffSectionList({ activeGroupId, canOpenWorkspaceFileBrowserForPath, + commentOwner, diffCommentsForWorktree, file, handleSectionSaveRef, @@ -47,6 +49,7 @@ export function CombinedDiffSectionList({ }: { activeGroupId: string | undefined canOpenWorkspaceFileBrowserForPath: (path: string) => boolean + commentOwner: DiffCommentOwner | null diffCommentsForWorktree: DiffComment[] file: OpenFile handleSectionSaveRef: DiffSectionItemProps['handleSectionSaveRef'] @@ -117,6 +120,7 @@ export function CombinedDiffSectionList({ isDark={isDark} sectionHeight={sectionHeights[virtualItem.index]} worktreeId={file.worktreeId} + noteSource={file} loadSection={loadSection} loadDeferredSection={loadDeferredSection} retrySection={retrySection} @@ -150,6 +154,7 @@ export function CombinedDiffSectionList({ const fileNoteCount = commentCountByFilePath.get(section.path) ?? 0 return fileNoteCount > 0 ? ( Promise - export async function submitDiffSectionComment({ + owner, addDiffComment, body, onAddLineComment, @@ -25,7 +18,8 @@ export async function submitDiffSectionComment({ section, worktreeId }: { - addDiffComment: AddDiffComment + owner: DiffCommentOwner | null + addDiffComment: AppState['addDiffComment'] body: string onAddLineComment?: ( section: DiffSection, @@ -46,11 +40,11 @@ export async function submitDiffSectionComment({ body }) } - if (!worktreeId) { + if (!worktreeId || !owner) { return false } // Close only after persistence succeeds; rollback must leave the draft available for retry. - const result = await addDiffComment({ + const result = await addDiffComment(owner, { worktreeId, filePath: section.path, source: 'diff', diff --git a/src/renderer/src/components/editor/diff-section-item-props.ts b/src/renderer/src/components/editor/diff-section-item-props.ts index 8e0ae181b2e..dc6aa536ebe 100644 --- a/src/renderer/src/components/editor/diff-section-item-props.ts +++ b/src/renderer/src/components/editor/diff-section-item-props.ts @@ -1,3 +1,4 @@ +import type { WorkspaceResource } from '@/lib/workspace-copy-owner' import type { Dispatch, MutableRefObject, ReactNode, SetStateAction } from 'react' import type { editor as monacoEditor } from 'monaco-editor' import type { DecoratedDiffComment } from '../diff-comments/decorated-diff-comment' @@ -11,6 +12,8 @@ export type DiffSectionItemProps = { isDark: boolean sectionHeight: number | undefined worktreeId?: string + /** The combined diff's tab; its review notes belong to the copy it names. */ + noteSource?: WorkspaceResource loadSection: (index: number) => void loadDeferredSection?: (index: number) => void retrySection: (index: number) => void diff --git a/src/renderer/src/components/editor/diff-viewer-props.ts b/src/renderer/src/components/editor/diff-viewer-props.ts index 06e22473523..87be81025f3 100644 --- a/src/renderer/src/components/editor/diff-viewer-props.ts +++ b/src/renderer/src/components/editor/diff-viewer-props.ts @@ -1,3 +1,4 @@ +import type { WorkspaceResource } from '@/lib/workspace-copy-owner' import type { LargeDiffRenderLimit } from './large-diff-render-limit' export type DiffViewerProps = { @@ -15,6 +16,8 @@ export type DiffViewerProps = { editable?: boolean // Hosted review dialogs may have no workspace for local comments. worktreeId?: string + /** The diff's tab; its review notes belong to the copy it names. */ + noteSource?: WorkspaceResource onAddLineComment?: (args: { lineNumber: number startLine?: number diff --git a/src/renderer/src/components/editor/markdown-preview-types.ts b/src/renderer/src/components/editor/markdown-preview-types.ts index 832d90df8cc..d7d1ff34ce9 100644 --- a/src/renderer/src/components/editor/markdown-preview-types.ts +++ b/src/renderer/src/components/editor/markdown-preview-types.ts @@ -1,4 +1,5 @@ import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' +import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-owner' export type MarkdownPreviewProps = { content: string @@ -34,6 +35,7 @@ export type MarkdownPreviewSourceOpenFile = { worktreeId: string runtimeEnvironmentId?: string | null externalSshTargetId?: string + operationProvenance?: EditorFileOperationProvenance mode: string markdownPreviewSourceFileId?: string } diff --git a/src/renderer/src/components/editor/rich-markdown-editor-props.ts b/src/renderer/src/components/editor/rich-markdown-editor-props.ts index 96fa3bd87da..eba765dd440 100644 --- a/src/renderer/src/components/editor/rich-markdown-editor-props.ts +++ b/src/renderer/src/components/editor/rich-markdown-editor-props.ts @@ -1,5 +1,6 @@ import type React from 'react' import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' +import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-owner' export type RichMarkdownEditorProps = { fileId: string @@ -9,6 +10,8 @@ export type RichMarkdownEditorProps = { worktreeId: string externalSshTargetId?: string runtimeEnvironmentId?: string | null + /** The tab's captured owner; with the fields above it names the copy whose notes show. */ + operationProvenance?: EditorFileOperationProvenance scrollCacheKey: string onContentChange: (content: string) => void onDirtyStateHint: (dirty: boolean) => void diff --git a/src/renderer/src/components/editor/use-markdown-preview-annotation-renderers.tsx b/src/renderer/src/components/editor/use-markdown-preview-annotation-renderers.tsx index be993bac353..a1dc86d4d88 100644 --- a/src/renderer/src/components/editor/use-markdown-preview-annotation-renderers.tsx +++ b/src/renderer/src/components/editor/use-markdown-preview-annotation-renderers.tsx @@ -1,4 +1,6 @@ +import { diffCommentOwnerKey } from '@/store/diff-comment-owner' import { useCallback } from 'react' +import { toast } from 'sonner' import { Check, Copy, Plus } from 'lucide-react' import { translate } from '@/i18n/i18n' import { @@ -36,6 +38,7 @@ export function useMarkdownPreviewAnnotationRenderers({ markdownAnnotationsEnabled: boolean }) { const { + commentOwner, sourceWorktree, sourceRelativePath, activeAnnotationBlockKey, @@ -61,7 +64,7 @@ export function useMarkdownPreviewAnnotationRenderers({ blockKey: string, annotationQuote?: string ): React.ReactNode => { - if (!sourceWorktree || sourceRelativePath === null) { + if (!commentOwner || !sourceWorktree || sourceRelativePath === null) { return null } if (!markdownAnnotationsEnabled) { @@ -70,7 +73,7 @@ export function useMarkdownPreviewAnnotationRenderers({ const commentsForBlock = getMarkdownCommentsForRange(range) const handleSubmit = async (body: string): Promise => { - const result = await addDiffComment({ + const result = await addDiffComment(commentOwner, { worktreeId: sourceWorktree.id, filePath: sourceRelativePath, source: 'markdown', @@ -84,6 +87,10 @@ export function useMarkdownPreviewAnnotationRenderers({ setActiveAnnotationBlockKey(null) return true } + // The composer keeps the draft for retry. + toast.error( + translate('auto.components.editor.diffCommentSaveFailed', 'Failed to save comment') + ) return false } @@ -105,6 +112,7 @@ export function useMarkdownPreviewAnnotationRenderers({ {activeAnnotationBlockKey === blockKey ? ( setActiveAnnotationBlockKey(null)} @@ -114,7 +122,7 @@ export function useMarkdownPreviewAnnotationRenderers({
{commentsForBlock.map((comment) => (
void deleteDiffComment(sourceWorktree.id, comment.id)} - onSubmitEdit={(body) => updateDiffComment(sourceWorktree.id, comment.id, body)} + onDelete={() => + void (commentOwner && deleteDiffComment(commentOwner, comment.id)) + } + onSubmitEdit={(body) => + commentOwner + ? updateDiffComment(commentOwner, comment.id, body) + : Promise.resolve(false) + } headerActions={ <>
{ - if (!activeWorktreeId || diffCommentCount === 0) { + if (!owner || !activeWorktreeId || diffCommentCount === 0) { return } - setPendingDiffCommentsClear({ kind: 'all', worktreeId: activeWorktreeId }) + setPendingDiffCommentsClear({ + kind: 'all', + worktreeId: activeWorktreeId, + owner, + count: diffCommentCount + }) }} > @@ -158,13 +167,16 @@ export function SourceControlNotesShelf({ {diffCommentsExpanded && ( void deleteDiffComment(activeWorktreeId, id)} + onDelete={(id) => void (owner && deleteDiffComment(owner, id))} onOpen={(comment) => handleOpenComment(comment)} onClearFile={(filePath) => + owner && setPendingDiffCommentsClear({ kind: 'file', + owner, worktreeId: activeWorktreeId, - filePath + filePath, + count: diffCommentsForActive.filter((comment) => comment.filePath === filePath).length }) } /> diff --git a/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.test.tsx b/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.test.tsx index d3490443815..cb72fe00140 100644 --- a/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.test.tsx @@ -14,8 +14,8 @@ vi.mock('sonner', () => ({ toast: { error: mocks.toastError, message: vi.fn() } vi.mock('@/store', () => ({ useAppStore: (selector: (state: Record) => unknown) => selector({}) })) -vi.mock('@/store/worktree-diff-comments-selector', () => ({ - selectWorktreeDiffCommentsOrEmpty: () => [ +vi.mock('@/store/diff-comment-owner', () => { + const comments = [ { id: 'c1', worktreeId: 'wt-1', @@ -26,7 +26,12 @@ vi.mock('@/store/worktree-diff-comments-selector', () => ({ side: 'modified' } satisfies DiffComment ] -})) + return { + createOwnedDiffCommentsSelector: () => () => undefined, + sourceParts: () => [], + createDiffCommentViewSelector: () => () => ({ owner: null, comments }) + } +}) import { useSourceControlDiffCommentNotes } from './use-diff-comment-notes' diff --git a/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.ts b/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.ts index 77e9237918a..78c61f4cb52 100644 --- a/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.ts +++ b/src/renderer/src/components/right-sidebar/source-control/notes/use-diff-comment-notes.ts @@ -1,9 +1,11 @@ +import type { AppState } from '@/store' +import { useOwnedDiffComments } from '../../../diff-comments/use-diff-comment-owner' +import { withoutMarkdownReviewNotes } from '@/lib/markdown-review-notes-setting' import { useCallback, useMemo, useState } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { formatDiffComments } from '@/lib/diff-comments-format' import { describeClipboardWriteFailure } from '@/lib/clipboard-write-failure' -import type { DiffCommentsClearOptions } from '@/store/slices/diffComments' import { useVisibleWorktreeDiffComments } from '../../../diff-comments/use-visible-worktree-diff-comments' import { countPendingDiffCommentsClear, @@ -19,15 +21,11 @@ export function useSourceControlDiffCommentNotes({ clearDiffCommentsForFile }: { activeWorktreeId: string | null - clearDiffComments: (worktreeId: string, options?: DiffCommentsClearOptions) => Promise - clearDiffCommentsForFile: ( - worktreeId: string, - filePath: string, - options?: DiffCommentsClearOptions - ) => Promise + clearDiffComments: AppState['clearDiffComments'] + clearDiffCommentsForFile: AppState['clearDiffCommentsForFile'] }) { const { comments: diffCommentsForActive, markdownReviewNotesEnabled } = - useVisibleWorktreeDiffComments(activeWorktreeId) + useVisibleWorktreeDiffComments(activeWorktreeId, 'selection') const diffCommentCount = diffCommentsForActive.length // Index counts once so each row need not refilter every comment. const diffCommentCountByPath = useMemo(() => { @@ -72,13 +70,21 @@ export function useSourceControlDiffCommentNotes({ } }, [diffCommentsForActive, diffCommentsPrompt, showDiffCommentsCopied]) + // Count the captured copy's notes, whichever twin is selected now; a copy gone since opening keeps its count so confirming reports the failure. + const ownedComments = useOwnedDiffComments(pendingDiffCommentsClear?.owner ?? null) const pendingDiffCommentsClearCount = useMemo(() => { + if (!pendingDiffCommentsClear || pendingDiffCommentsClear.worktreeId !== activeWorktreeId) { + return 0 + } + if (!ownedComments) { + return pendingDiffCommentsClear.count + } return countPendingDiffCommentsClear( pendingDiffCommentsClear, activeWorktreeId, - diffCommentsForActive + markdownReviewNotesEnabled ? ownedComments : withoutMarkdownReviewNotes(ownedComments) ) - }, [activeWorktreeId, diffCommentsForActive, pendingDiffCommentsClear]) + }, [activeWorktreeId, markdownReviewNotesEnabled, ownedComments, pendingDiffCommentsClear]) const resolvedPendingDiffCommentsClear = resolvePendingDiffCommentsClear({ activeWorktreeId, @@ -110,8 +116,8 @@ export function useSourceControlDiffCommentNotes({ try { const ok = pending.kind === 'all' - ? await clearDiffComments(pending.worktreeId, clearOptions) - : await clearDiffCommentsForFile(pending.worktreeId, pending.filePath, clearOptions) + ? await clearDiffComments(pending.owner, clearOptions) + : await clearDiffCommentsForFile(pending.owner, pending.filePath, clearOptions) if (ok) { setPendingDiffCommentsClear(null) } else { diff --git a/src/renderer/src/lib/editor-file-operation-provenance.ts b/src/renderer/src/lib/editor-file-operation-provenance.ts index 0c7b1271637..4caab32bebb 100644 --- a/src/renderer/src/lib/editor-file-operation-provenance.ts +++ b/src/renderer/src/lib/editor-file-operation-provenance.ts @@ -175,7 +175,9 @@ type AllRouteStateKeys = { const focusFreeRouteStates = new WeakMap() /** Neither workspace focus nor the Active Server focus can replace a file's catalog owner. Projects only route inputs: spreading the full app state per lookup dominated ownership sweeps. */ -function focusFreeRouteStateOf(state: WorktreeOperationRouteState): WorktreeOperationRouteState { +export function focusFreeRouteStateOf( + state: WorktreeOperationRouteState +): WorktreeOperationRouteState { let projected = focusFreeRouteStates.get(state) if (!projected) { const routeState: AllRouteStateKeys = { diff --git a/src/renderer/src/lib/notes-send-in-flight.ts b/src/renderer/src/lib/notes-send-in-flight.ts index de9e9a9ba1e..cd42727e846 100644 --- a/src/renderer/src/lib/notes-send-in-flight.ts +++ b/src/renderer/src/lib/notes-send-in-flight.ts @@ -1,3 +1,4 @@ +import { diffCommentOwnerKey, type DiffCommentOwner } from '@/store/diff-comment-owner' import { useSyncExternalStore } from 'react' import type { DiffCommentDeliverySnapshot } from '@/store/slices/diffComments' @@ -73,8 +74,12 @@ export function useNotesInFlightVersion(): number { } /** A note's identity for delivery: an edit makes it a new pending note, as for its removal. */ -export function diffCommentSendKey(note: DiffCommentDeliverySnapshot): string { +export function diffCommentSendKey( + owner: DiffCommentOwner, + note: DiffCommentDeliverySnapshot +): string { return JSON.stringify([ + diffCommentOwnerKey(owner), note.id, note.body, note.filePath, diff --git a/src/renderer/src/lib/resolve-owner.ts b/src/renderer/src/lib/resolve-owner.ts index fdb593fad8b..b16bfee1189 100644 --- a/src/renderer/src/lib/resolve-owner.ts +++ b/src/renderer/src/lib/resolve-owner.ts @@ -31,6 +31,7 @@ import { getFloatingWorkspaceOperationRoute, resolveWorktreeOperationRouteResultForHost, resolveWorktreeOperationRouteResult, + type WorktreeOperationRoute, type WorktreeOperationRouteResolution, type WorktreeOperationRouteState } from './worktree-operation-route' @@ -117,6 +118,21 @@ export function resolveOwner( return match.kind === 'resolved' ? withNestedPlace(state, ref, match.owner) : match } +/** An exact route (a record's complete stamps) as an owner, with the nested place its server's rows or repo name. */ +export function resolveOwnerOfRoute( + state: WorktreeOperationRouteState, + workspaceId: string, + route: WorktreeOperationRoute +): ExecutionHostOwnerMatch { + const match = toOwnerMatch({ kind: 'resolved', route }) + const hostId = + route.executionHostId ?? + (route.runtimeEnvironmentId ? toRuntimeExecutionHostId(route.runtimeEnvironmentId) : null) + return match.kind === 'resolved' + ? withNestedPlace(state, { workspaceId, ...(hostId ? { hostId } : {}) }, match.owner) + : match +} + /** Server routes omit nested SSH; resolve connectionId from the owning folder/repo row, matching resolveWorktreeExecutionHost. */ function withNestedPlace( state: WorktreeOperationRouteState, diff --git a/src/renderer/src/lib/workspace-copy-owner.ts b/src/renderer/src/lib/workspace-copy-owner.ts new file mode 100644 index 00000000000..66300258d47 --- /dev/null +++ b/src/renderer/src/lib/workspace-copy-owner.ts @@ -0,0 +1,348 @@ +/** + * Which copy of a workspace something belongs to. Copies on different hosts share one workspace + * id, so a retained resource and each listed record are resolved from their own evidence: neither + * borrows the current selection, and a route to one copy never vouches for another copy's record. + */ +import { + parseExecutionHostId, + toRuntimeExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' +import { + authorityKey, + hostAuthorityFromOperationRoute, + type HostAuthority, + type HostAuthorityEndpoint +} from '../../../shared/host-authority' +import type { ExecutionHostOwnerMatch } from '../../../shared/worktree-execution-host-resolution' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +import { + selectDetectedWorktreesByRepo, + selectFolderWorkspaceCopies, + selectWorktreesByRepo +} from '@/store/workspace-record-selectors' +import type { OpenFile } from '@/store/slices/editor' +import { focusFreeRouteStateOf } from './editor-file-operation-provenance' +import { namedHostForOwnerRef, resolveOwner, resolveOwnerOfRoute } from './resolve-owner' +import { resolveUnstampedRecordHost } from './worktree-operation-catalog-route' +import { resolveExactWorktreeRoute, routeForOwner } from './worktree-owner-route' +import { + findIndexedDetectedWorktrees, + findIndexedWorktreeOwners +} from './worktree-runtime-owner-index' +import type { + WorktreeOperationOwnerRecord, + WorktreeOperationRouteState +} from './worktree-operation-route' + +/** What a retained surface knows about its content's copy: the fields its tab already carries. */ +export type WorkspaceResource = Pick< + OpenFile, + 'runtimeEnvironmentId' | 'externalSshTargetId' | 'operationProvenance' +> + +/** A surface with no tab evidence: it may show the sole listed copy, never the selected one. */ +export const NO_RESOURCE_EVIDENCE: WorkspaceResource = Object.freeze({}) + +/** A retained resource, or a selection-bound view (the only kind that reads the selected host). */ +export type WorkspaceCopySource = WorkspaceResource | 'selection' + +type OwnerMatch = ExecutionHostOwnerMatch + +/** What a source proves: a whole copy, or only its endpoint (explicit null is this app; none is unknown). */ +type SourceEvidence = + | { kind: 'authority'; authority: HostAuthority } + | { kind: 'endpoint'; endpoint?: HostAuthorityEndpoint } + +const UNKNOWN_SOURCE: SourceEvidence = { kind: 'endpoint' } + +function fitsEvidence(evidence: SourceEvidence, authority: HostAuthority): boolean { + return evidence.kind === 'authority' + ? authorityKey(authority) === authorityKey(evidence.authority) + : !evidence.endpoint || sameEndpoint(evidence.endpoint, authority.endpoint) +} + +/** Stable spelling of the evidence, so readers of one source share qualification. */ +function evidenceKey(evidence: SourceEvidence): string { + return evidence.kind === 'authority' + ? `a:${authorityKey(evidence.authority)}` + : evidence.endpoint?.kind === 'environment' + ? `e:${evidence.endpoint.environmentId}` + : evidence.endpoint + ? 's' + : 'u' +} + +function sameEndpoint(a: HostAuthorityEndpoint, b: HostAuthorityEndpoint): boolean { + return a.kind === 'self' + ? b.kind === 'self' + : b.kind === 'environment' && a.environmentId === b.environmentId +} + +/** The immutable catalog snapshots results are shared under: a worktree catalog, or one folder id's copies. */ +type CatalogSnapshot = + | NonNullable + | ReturnType + +type CatalogMemo = WeakMap< + CatalogSnapshot, + { inputs: readonly unknown[]; results: Map } +> + +/** One result per key while the anchor snapshot and inputs stay the same, shared by every reader of that snapshot. */ +function memoOnCatalog( + cache: CatalogMemo, + anchor: CatalogSnapshot, + inputs: readonly unknown[], + key: string, + compute: () => R +): R { + let cached = cache.get(anchor) + if (!cached || cached.inputs.some((input, index) => !Object.is(input, inputs[index]))) { + cached = { inputs, results: new Map() } + cache.set(anchor, cached) + } + let result = cached.results.get(key) + if (!result) { + result = compute() + cached.results.set(key, result) + } + return result +} + +// Rows of one workspace on one host share an answer; resolving each row would rescan its same-id peers. +const recordOwnerCache: CatalogMemo = new WeakMap() + +/** The copy a record belongs to: complete stamps prove it; otherwise its host's evidence decides. */ +export function resolveRecordOwner( + state: WorktreeOperationRouteState, + record: WorktreeOperationOwnerRecord +): OwnerMatch { + const route = routeForOwner(record) + const stamped = route?.runtimeEnvironmentId ? route : null + const hostId = stamped ? null : (record.hostId ?? resolveUnstampedRecordHost(state, record)) + const compute = (): OwnerMatch => + stamped + ? // Resolving its host instead would merge rival servers proxying the same SSH target. + resolveOwnerOfRoute(state, record.id, stamped) + : hostId + ? resolveOwner(state, { workspaceId: record.id, hostId }) + : { kind: 'missing' } + const rows = selectWorktreesByRepo(state) + if (!rows) { + return compute() + } + const key = stamped + ? `r\0${record.id}\0${stamped.executionHostId ?? ''}\0${stamped.runtimeEnvironmentId}` + : `h\0${record.id}\0${hostId ?? ''}` + const inputs = [selectDetectedWorktreesByRepo(state), state.repos, state.runtimeEnvironments] + return memoOnCatalog(recordOwnerCache, rows, inputs, key, compute) +} + +/** A host's copy, also before it lists: an unlisted SSH copy takes its server from repo setup, as its record would. */ +export function resolveOwnerOnHost( + state: WorktreeOperationRouteState, + workspaceId: string, + hostId: ExecutionHostId +): OwnerMatch { + const host = parseExecutionHostId(hostId) + const onHost = (record: WorktreeOperationOwnerRecord) => + parseExecutionHostId(record.hostId)?.id === host?.id + if ( + host?.kind === 'ssh' && + parseWorkspaceKey(workspaceId)?.type !== 'folder' && + !findIndexedWorktreeOwners(selectWorktreesByRepo(state), workspaceId).some(onHost) && + !findIndexedDetectedWorktrees(selectDetectedWorktreesByRepo(state), workspaceId).some(onHost) + ) { + const route = resolveExactWorktreeRoute(state, { + id: workspaceId, + repoId: getRepoIdFromWorktreeId(workspaceId), + hostId: host.id + }) + return route.kind === 'resolved' ? resolveOwnerOfRoute(state, workspaceId, route.route) : route + } + return resolveOwner(state, { workspaceId, hostId }) +} + +/** The one listed copy that fits, `ambiguous` when several (or an unidentifiable one) might. */ +function soleListedCopy( + state: WorktreeOperationRouteState, + workspaceId: string, + fits: (authority: HostAuthority) => boolean +): OwnerMatch { + const copies = new Map() + for (const record of findIndexedWorktreeOwners(selectWorktreesByRepo(state), workspaceId)) { + const owner = resolveRecordOwner(state, record) + if (owner.kind === 'ambiguous') { + return owner + } + if (owner.kind === 'resolved' && fits(owner.owner)) { + copies.set(authorityKey(owner.owner), owner.owner) + } + } + const [only] = copies.values() + return copies.size > 1 + ? { kind: 'ambiguous' } + : only + ? { kind: 'resolved', owner: only } + : { kind: 'missing' } +} + +/** A resource's copy from its tab: captured provenance, else the endpoint (and SSH place) it names. */ +function resourceEvidence( + state: WorktreeOperationRouteState, + workspaceId: string, + resource: WorkspaceResource +): SourceEvidence { + const provenance = resource.operationProvenance + // A child repository's provenance names that repository's host, not this workspace's copy. + if (provenance && !provenance.childRepo) { + const { route, authority } = provenance.generation + if (authority) { + return { kind: 'authority', authority } + } + const fromRoute = hostAuthorityFromOperationRoute(route) + const onHost = route.executionHostId + ? resolveOwnerOnHost(state, workspaceId, route.executionHostId) + : null + // Its own route stays the copy when the catalog now names another server for that host. + if ( + onHost?.kind === 'resolved' && + fromRoute && + fromRoute !== 'contradictory' && + sameEndpoint(onHost.owner.endpoint, fromRoute.endpoint) + ) { + return { kind: 'authority', authority: onHost.owner } + } + if (fromRoute && fromRoute !== 'contradictory') { + return { kind: 'authority', authority: fromRoute } + } + } + const environmentId = resource.runtimeEnvironmentId?.trim() + const sshTargetId = resource.externalSshTargetId?.trim() + if (sshTargetId && !environmentId) { + return { + kind: 'authority', + authority: { endpoint: { kind: 'self' }, at: toSshExecutionHostId(sshTargetId) } + } + } + // Explicit null is this app; undefined says nothing. + return environmentId + ? { kind: 'endpoint', endpoint: { kind: 'environment', environmentId } } + : resource.runtimeEnvironmentId === null + ? { kind: 'endpoint', endpoint: { kind: 'self' } } + : UNKNOWN_SOURCE +} + +/** + * The copy a surface shows. Selection-bound views take the selected host's copy (or the sole + * listed one when none is selected); a retained resource takes its own evidence, completed only + * by the single listed copy it fits. Unknown and rival copies stay unresolved. + */ +export function resolveSourceCopy( + state: WorktreeOperationRouteState, + workspaceId: string, + source: WorkspaceCopySource +): OwnerMatch { + if (source === 'selection') { + const hostId = namedHostForOwnerRef(state, { workspaceId }) + return hostId + ? resolveOwnerOnHost(state, workspaceId, hostId) + : soleListedCopy(state, workspaceId, () => true) + } + const ownerState = focusFreeRouteStateOf(state) + const evidence = resourceEvidence(ownerState, workspaceId, source) + if (evidence.kind === 'authority') { + return { kind: 'resolved', owner: evidence.authority } + } + const { endpoint } = evidence + const listed = soleListedCopy(ownerState, workspaceId, (authority) => + fitsEvidence(evidence, authority) + ) + // A server's copy not listed yet is that server's own route, with the place its repo names. + return listed.kind === 'missing' && endpoint?.kind === 'environment' + ? resolveOwner(ownerState, { + workspaceId, + hostId: toRuntimeExecutionHostId(endpoint.environmentId) + }) + : listed +} + +/** + * The host qualifying the folder catalog record a source shows, by the same evidence and + * resolver as worktree copies: each catalog record's owner, filtered by what the source proves. + */ +export function resolveSourceFolderHost( + state: WorktreeOperationRouteState, + workspaceId: string, + folderWorkspaceId: string, + source: WorkspaceCopySource +): ExecutionHostOwnerMatch { + const named = source === 'selection' ? namedHostForOwnerRef(state, { workspaceId }) : null + if (named) { + return { kind: 'resolved', owner: named } + } + const ownerState = source === 'selection' ? state : focusFreeRouteStateOf(state) + // A file outside the folder names its own SSH target, not the folder catalog's host. + const evidence = + source === 'selection' + ? UNKNOWN_SOURCE + : resourceEvidence(ownerState, workspaceId, { ...source, externalSshTargetId: undefined }) + const copies = selectFolderWorkspaceCopies(ownerState, folderWorkspaceId) + // An absent folder has nothing to qualify; caching it would key on a shared empty list forever. + if (copies.length === 0) { + return NO_FOLDER_COPY + } + return memoOnCatalog( + folderQualificationCache, + copies, + FOLDER_OWNER_INPUTS.map((key) => ownerState[key]), + `${workspaceId}\0${evidenceKey(evidence)}`, + () => qualifyFolderCopies(ownerState, workspaceId, copies, evidence) + ) +} + +const NO_FOLDER_COPY: FolderQualification = { kind: 'missing' } + +/** Every catalog input a folder copy's owner is resolved from, besides the copies themselves. */ +const FOLDER_OWNER_INPUTS = [ + 'projectGroups', + 'repos', + 'runtimeEnvironments', + 'settings', + 'restoredRuntimeHostIdByWorkspaceSessionKey', + 'runtimeEnvironmentCatalogHydrated', + 'removedRuntimeEnvironmentIds' +] as const satisfies readonly (keyof WorktreeOperationRouteState)[] + +type FolderQualification = ExecutionHostOwnerMatch + +// Keyed by one id's copies from the folder index, so readers of that folder and evidence share the result until its catalog changes. +const folderQualificationCache: CatalogMemo = new WeakMap() + +function qualifyFolderCopies( + state: WorktreeOperationRouteState, + workspaceId: string, + copies: readonly { executionHostId?: string | null }[], + evidence: SourceEvidence +): FolderQualification { + const hosts = new Set(copies.map((copy) => parseExecutionHostId(copy.executionHostId)?.id)) + const fitting = new Map() + for (const hostId of hosts) { + const owner = resolveOwner(state, { workspaceId, ...(hostId ? { hostId } : {}) }) + if (owner.kind === 'ambiguous') { + return owner + } + if (owner.kind === 'resolved' && fitsEvidence(evidence, owner.owner)) { + fitting.set(authorityKey(owner.owner), hostId) + } + } + const [only] = fitting.entries() + return fitting.size > 1 + ? { kind: 'ambiguous' } + : only + ? { kind: 'resolved', owner: only[1] } + : { kind: 'missing' } +} diff --git a/src/renderer/src/lib/worktree-operation-catalog-route.ts b/src/renderer/src/lib/worktree-operation-catalog-route.ts index d3db78d14f2..bf072fd9304 100644 --- a/src/renderer/src/lib/worktree-operation-catalog-route.ts +++ b/src/renderer/src/lib/worktree-operation-catalog-route.ts @@ -2,12 +2,14 @@ import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID, - parseExecutionHostId + parseExecutionHostId, + type ExecutionHostId } from '../../../shared/execution-host' import { getRepoIdFromWorktreeId } from '@/store/slices/worktree-helpers' import { addRoute, resolveExactWorktreeRoute, routeForOwner } from './worktree-owner-route' import { findIndexedDetectedWorktrees, + findIndexedRepoOwnerForHost, resolveIndexedRepoOwner, resolveIndexedWorktreeOwner } from './worktree-runtime-owner-index' @@ -109,23 +111,60 @@ function isUnstampedRowOfSharedLocalProject( ) { return false } - let hasLocalRepoRow = false - let hasRuntimeRepoRow = false - for (const repo of state.repos ?? []) { - if (repo.id !== owner.repoId) { - continue - } - const hostId = getRepoExecutionHostId(repo) - if (hostId === LOCAL_EXECUTION_HOST_ID) { - hasLocalRepoRow = true - } else if (parseExecutionHostId(hostId)?.kind === 'runtime') { - hasRuntimeRepoRow = true - } else { - // Why: an SSH sibling keeps the existing connection-owned routing. - return false - } + return sharedLocalProjectRepoIds(state.repos).has(owner.repoId) +} + +const sharedLocalProjectIndexCache = new WeakMap< + NonNullable, + ReadonlySet +>() + +/** Repo ids with local and server setups and no SSH sibling (an SSH sibling keeps connection-owned routing); one pass per repo catalog. */ +function sharedLocalProjectRepoIds( + repos: WorktreeOperationRouteState['repos'] +): ReadonlySet { + if (!repos) { + return new Set() } - return hasLocalRepoRow && hasRuntimeRepoRow + let index = sharedLocalProjectIndexCache.get(repos) + if (!index) { + const kinds = new Map>() + for (const repo of repos) { + const hostId = getRepoExecutionHostId(repo) + const kind = + hostId === LOCAL_EXECUTION_HOST_ID + ? 'local' + : parseExecutionHostId(hostId)?.kind === 'runtime' + ? 'runtime' + : 'other' + kinds.set(repo.id, (kinds.get(repo.id) ?? new Set()).add(kind)) + } + index = new Set( + [...kinds] + .filter(([, seen]) => seen.has('local') && seen.has('runtime') && !seen.has('other')) + .map(([repoId]) => repoId) + ) + sharedLocalProjectIndexCache.set(repos, index) + } + return index +} + +/** An unstamped record's host by the rules above: a shared local project's row is local, else its repo setup; with no setup, or one this app also has, the row was listed here (paired listings stamp ownership). */ +export function resolveUnstampedRecordHost( + state: WorktreeOperationRouteState, + owner: WorktreeOperationOwnerRecord +): ExecutionHostId | null { + if (isUnstampedRowOfSharedLocalProject(state, owner)) { + return LOCAL_EXECUTION_HOST_ID + } + const repo = resolveIndexedRepoOperationRoute(state.repos, owner.repoId) + if (repo.kind === 'resolved') { + return repo.route.executionHostId + } + return repo.kind === 'missing' || + findIndexedRepoOwnerForHost(state.repos, owner.repoId, LOCAL_EXECUTION_HOST_ID) + ? LOCAL_EXECUTION_HOST_ID + : null } function resolveIndexedRepoOperationRoute( diff --git a/src/renderer/src/lib/worktree-runtime-owner-index.ts b/src/renderer/src/lib/worktree-runtime-owner-index.ts index 3577f8f0773..a8f8d2cdf26 100644 --- a/src/renderer/src/lib/worktree-runtime-owner-index.ts +++ b/src/renderer/src/lib/worktree-runtime-owner-index.ts @@ -29,6 +29,7 @@ const worktreeOwnerIndexCache = new WeakMap< { entries: ReadonlyMap ownersById: ReadonlyMap + locationsById: ReadonlyMap } >() const folderWorkspaceOwnerIndexCache = new WeakMap< @@ -167,9 +168,13 @@ export function resolveIndexedWorktreeOwner( if (!index) { const next = new Map() const ownersById = new Map() + const locationsById = new Map() for (const [bucket, worktrees] of Object.entries(worktreesByRepo)) { worktrees.forEach((worktree, position) => { const id = worktree.id + const locations = locationsById.get(id) ?? [] + locations.push({ bucket, position }) + locationsById.set(id, locations) const owners = ownersById.get(id) if (owners) { owners.push(worktree) @@ -182,7 +187,7 @@ export function resolveIndexedWorktreeOwner( } }) } - index = { entries: next, ownersById } + index = { entries: next, ownersById, locationsById } worktreeOwnerIndexCache.set(worktreesByRepo, index) } return index.entries.get(worktreeId) ?? { kind: 'missing' } @@ -200,6 +205,21 @@ export function findIndexedWorktreeOwners( ) } +/** Every listed row of `worktreeId` in one repo bucket, duplicates kept in catalog order, typed as the caller's catalog. */ +export function findIndexedWorktreeRows( + worktreesByRepo: Record | undefined, + repoId: string, + worktreeId: string +): W[] { + resolveIndexedWorktreeOwner(worktreesByRepo, worktreeId) + const locations = + worktreesByRepo && worktreeOwnerIndexCache.get(worktreesByRepo)?.locationsById.get(worktreeId) + return (locations ?? []).flatMap(({ bucket, position }) => { + const row = bucket === repoId ? worktreesByRepo?.[bucket]?.[position] : undefined + return row?.id === worktreeId ? [row] : [] + }) +} + /** * Every detected publication of `worktreeId`, in catalog order. Rival repos may publish the same * id, so callers that fail closed on conflicts need all matches rather than one resolved owner. diff --git a/src/renderer/src/store/diff-comment-owner.ts b/src/renderer/src/store/diff-comment-owner.ts new file mode 100644 index 00000000000..ca5cd1dd636 --- /dev/null +++ b/src/renderer/src/store/diff-comment-owner.ts @@ -0,0 +1,219 @@ +import type { DiffComment } from '../../../shared/diff-comment-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { authorityKey, type HostAuthority } from '../../../shared/host-authority' +import { + findFolderWorkspaceOwner, + getExecutionHostIdForFolderWorkspace, + getRuntimeEnvironmentIdForFolderWorkspace +} from '@/lib/folder-workspace-runtime-owner' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { + DIFF_COMMENT_OWNER_INPUTS, + EMPTY_DIFF_COMMENTS, + findCopyRows, + readCopyNotes, + type DiffCommentSelectorState +} from './worktree-diff-comments-selector' +import { focusFreeRouteStateOf } from '@/lib/editor-file-operation-provenance' +import { + resolveSourceCopy, + resolveSourceFolderHost, + type WorkspaceCopySource, + type WorkspaceResource +} from '@/lib/workspace-copy-owner' + +/** A copy whose notes can be changed: the workspace and the authority serving it (endpoint plus place). */ +export type DiffCommentOwner = + | { kind: 'worktree'; worktreeId: string; authority: HostAuthority } + | { + kind: 'folder' + worktreeId: string + executionHostId: ExecutionHostId + runtimeEnvironmentId: string | null + } + +/** + * Owner and notes from one read, so actions change exactly the copy whose notes are shown. + * `comments` is undefined while that copy is unknown or not listed yet; that is not an empty list. + */ +export type DiffCommentView = { + owner: DiffCommentOwner | null + comments: DiffComment[] | undefined +} + +const NO_DIFF_COMMENT_VIEW: DiffCommentView = Object.freeze({ owner: null, comments: undefined }) + +/** The folder copy a source names: its catalog record and the endpoint serving that catalog, together. */ +function selectFolderView( + state: DiffCommentSelectorState, + worktreeId: string, + folderWorkspaceId: string, + source: WorkspaceCopySource +): DiffCommentView { + const qualifier = resolveSourceFolderHost(state, worktreeId, folderWorkspaceId, source) + if (qualifier.kind !== 'resolved') { + return NO_DIFF_COMMENT_VIEW + } + const hostId = qualifier.owner + // Without its own host, a retained resource may not fall back to the selected folder. + const ownerState = source === 'selection' ? state : focusFreeRouteStateOf(state) + const folder = findFolderWorkspaceOwner(ownerState, folderWorkspaceId, hostId) + if (!folder) { + return NO_DIFF_COMMENT_VIEW + } + const executionHostId = getExecutionHostIdForFolderWorkspace( + ownerState, + folderWorkspaceId, + hostId + ) + return { + owner: { + kind: 'folder', + worktreeId, + executionHostId, + runtimeEnvironmentId: getRuntimeEnvironmentIdForFolderWorkspace( + ownerState, + folderWorkspaceId, + executionHostId + ) + }, + comments: folder.diffComments ?? EMPTY_DIFF_COMMENTS + } +} + +/** Owner and notes of the copy a source shows; resource-bound surfaces pass their own resource. */ +export function selectDiffCommentView( + state: DiffCommentSelectorState, + worktreeId: string | null | undefined, + source: WorkspaceCopySource +): DiffCommentView { + if (!worktreeId) { + return NO_DIFF_COMMENT_VIEW + } + const scope = parseWorkspaceKey(worktreeId) + if (scope?.type === 'folder') { + return selectFolderView(state, worktreeId, scope.folderWorkspaceId, source) + } + const copy = resolveSourceCopy(state, worktreeId, source) + // Rival copies with nothing naming one stay unknown rather than showing an arbitrary copy. + if (copy.kind !== 'resolved') { + return NO_DIFF_COMMENT_VIEW + } + return { + owner: { kind: 'worktree', worktreeId, authority: copy.owner }, + comments: readCopyNotes(findCopyRows(state, worktreeId, copy.owner)) + } +} + +/** Same copy, same key: stamps confirming an authority don't change it; rival servers and hosts differ. */ +export function diffCommentOwnerKey(owner: DiffCommentOwner): string { + return JSON.stringify( + owner.kind === 'folder' + ? [owner.worktreeId, owner.executionHostId, owner.runtimeEnvironmentId] + : [owner.worktreeId, authorityKey(owner.authority)] + ) +} + +/** A captured folder copy's catalog record, only while the captured endpoint still serves it: reads, mutations, the queue and rollback all use this one lookup. */ +export function findOwnedFolder( + state: DiffCommentSelectorState, + owner: Extract +): ReturnType { + const scope = parseWorkspaceKey(owner.worktreeId) + if (scope?.type !== 'folder') { + return null + } + const folder = findFolderWorkspaceOwner(state, scope.folderWorkspaceId, owner.executionHostId) + return folder && + getRuntimeEnvironmentIdForFolderWorkspace( + state, + scope.folderWorkspaceId, + owner.executionHostId + ) === owner.runtimeEnvironmentId + ? folder + : null +} + +/** The captured copy's notes, or undefined when it is not listed (gone, or not yet arrived). */ +export function readOwnedDiffComments( + state: DiffCommentSelectorState, + owner: DiffCommentOwner +): DiffComment[] | undefined { + if (owner.kind === 'folder') { + const folder = findOwnedFolder(state, owner) + return folder ? (folder.diffComments ?? EMPTY_DIFF_COMMENTS) : undefined + } + return readCopyNotes(findCopyRows(state, owner.worktreeId, owner.authority)) +} + +/** + * A per-consumer cached read: a store write that changes no ownership input, with the same + * arguments, returns the previous result without row work; an equal result keeps its identity. + */ +function cacheOnOwnerInputs( + read: (state: DiffCommentSelectorState, ...args: Args) => Result, + equal: (previous: Result, next: Result) => boolean +): (state: DiffCommentSelectorState, ...args: Args) => Result { + let inputs: unknown[] | null = null + let result: { value: Result } | null = null + return (state, ...args) => { + const next = [...args, ...DIFF_COMMENT_OWNER_INPUTS.map((key) => state[key])] + if (result && inputs?.every((input, index) => Object.is(input, next[index]))) { + return result.value + } + inputs = next + const value = read(state, ...args) + if (!result || !equal(result.value, value)) { + result = { value } + } + return result.value + } +} + +/** Cache arguments: the source's own fields, so a fresh wrapper object for the same tab still hits. */ +type SourceParts = [ + selection: boolean, + runtimeEnvironmentId: WorkspaceResource['runtimeEnvironmentId'], + externalSshTargetId: WorkspaceResource['externalSshTargetId'], + operationProvenance: WorkspaceResource['operationProvenance'] +] + +export function sourceParts(source: WorkspaceCopySource): SourceParts { + return source === 'selection' + ? [true, undefined, undefined, undefined] + : [false, source.runtimeEnvironmentId, source.externalSshTargetId, source.operationProvenance] +} + +export function createDiffCommentViewSelector(): ( + state: DiffCommentSelectorState, + worktreeId: string | null | undefined, + ...source: SourceParts +) => DiffCommentView { + return cacheOnOwnerInputs( + ( + state, + worktreeId: string | null | undefined, + ...[selection, runtimeEnvironmentId, externalSshTargetId, operationProvenance]: SourceParts + ) => + selectDiffCommentView( + state, + worktreeId, + selection ? 'selection' : { runtimeEnvironmentId, externalSshTargetId, operationProvenance } + ), + (previous, next) => + previous.comments === next.comments && + JSON.stringify(previous.owner) === JSON.stringify(next.owner) + ) +} + +/** A captured action's notes, read through the same cache as views (open Clear confirmations). */ +export function createOwnedDiffCommentsSelector(): ( + state: DiffCommentSelectorState, + owner: DiffCommentOwner | null +) => DiffComment[] | undefined { + return cacheOnOwnerInputs( + (state, owner: DiffCommentOwner | null) => + owner ? readOwnedDiffComments(state, owner) : undefined, + Object.is + ) +} diff --git a/src/renderer/src/store/slices/diff-comment-host-write.ts b/src/renderer/src/store/slices/diff-comment-host-write.ts index e053398095f..2721a84bafc 100644 --- a/src/renderer/src/store/slices/diff-comment-host-write.ts +++ b/src/renderer/src/store/slices/diff-comment-host-write.ts @@ -1,35 +1,21 @@ -import type { AppState } from '../types' import type { DiffComment } from '../../../../shared/diff-comment-types' -import type { ExecutionHostId } from '../../../../shared/execution-host' import type { FolderWorkspace } from '../../../../shared/folder-workspace-types' import { callRuntimeRpc } from '../../runtime/runtime-rpc-client' -import { runtimeTargetForWorkspaceOwner } from '@/lib/resolve-owner' +import type { DiffCommentOwner } from '../diff-comment-owner' import { toRuntimeWorktreeSelector } from '../../runtime/runtime-worktree-selector' -import { - getExecutionHostIdForFolderWorkspace, - getRuntimeEnvironmentIdForFolderWorkspace -} from '@/lib/folder-workspace-runtime-owner' import { callHostRoute } from '@/runtime/host-route-call' import { hostRouteForAuthority } from '@/runtime/runtime-client-target' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' /** Writes a workspace's whole review-note list to the host that owns it. */ export async function writeDiffCommentsToHost( - state: AppState, - worktreeId: string, - diffComments: DiffComment[], - folderExecutionHostId?: ReturnType, - writeHostId?: ExecutionHostId + owner: DiffCommentOwner, + diffComments: DiffComment[] ): Promise { + const worktreeId = owner.worktreeId const scope = parseWorkspaceKey(worktreeId) - if (scope?.type === 'folder') { - const executionHostId = - folderExecutionHostId ?? getExecutionHostIdForFolderWorkspace(state, scope.folderWorkspaceId) - const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace( - state, - scope.folderWorkspaceId, - executionHostId - ) + if (scope?.type === 'folder' && owner.kind === 'folder') { + const runtimeEnvironmentId = owner.runtimeEnvironmentId const updated = runtimeEnvironmentId ? ( await callHostRoute<{ folderWorkspace: FolderWorkspace | null }>( @@ -52,17 +38,15 @@ export async function writeDiffCommentsToHost( } return } - const target = runtimeTargetForWorkspaceOwner(state, { - workspaceId: worktreeId, - hostId: writeHostId - }) - if (!target) { + if (owner.kind !== 'worktree') { throw new Error('The workspace host is unresolved; review notes were not saved.') } - if (target.kind === 'local') { + // The captured authority is the route: this app names the place it keeps the copy, a server owns its own. + const { endpoint, at } = owner.authority + if (endpoint.kind === 'self') { const meta = await window.api.worktrees.updateMeta({ worktreeId, - ...(writeHostId ? { executionHostId: writeHostId } : {}), + executionHostId: at, updates: { diffComments } }) // Why: main answers null when it refuses or drops the write; reporting success would lose the notes. @@ -72,7 +56,7 @@ export async function writeDiffCommentsToHost( return } await callRuntimeRpc( - target, + { kind: 'environment', environmentId: endpoint.environmentId }, 'worktree.set', { worktree: toRuntimeWorktreeSelector(worktreeId), diffComments }, { timeoutMs: 15_000 } diff --git a/src/renderer/src/store/slices/diff-comment-persistence.ts b/src/renderer/src/store/slices/diff-comment-persistence.ts index d0e49fb396f..c65698b290b 100644 --- a/src/renderer/src/store/slices/diff-comment-persistence.ts +++ b/src/renderer/src/store/slices/diff-comment-persistence.ts @@ -3,18 +3,9 @@ import type { AppState } from '../types' import type { DiffComment } from '../../../../shared/diff-comment-types' import type { Worktree } from '../../../../shared/worktree/types' import { getRepoIdFromWorktreeId } from './worktree-helpers' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import { - diffCommentFloorKey, - diffCommentRowNotes, - findDiffCommentRows, - readQueuedDiffComments, - type DiffCommentTwin -} from '../worktree-diff-comments-selector' -import { - findFolderWorkspaceOwner, - getExecutionHostIdForFolderWorkspace -} from '@/lib/folder-workspace-runtime-owner' +import { findCopyRows } from '../worktree-diff-comments-selector' +import { diffCommentOwnerKey, findOwnedFolder, type DiffCommentOwner } from '../diff-comment-owner' +import type { getExecutionHostIdForFolderWorkspace } from '@/lib/folder-workspace-runtime-owner' import { writeDiffCommentsToHost } from './diff-comment-host-write' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' @@ -68,14 +59,17 @@ const lastMutationNextByQueue = new Map() // Why: bumped on every re-seed, so an in-flight write can tell whether the floor it captured is still the current one. const floorSeedEpochByQueue = new Map() +/** One change to one copy's notes; the owner alone says which rows it reads, writes and rolls back. */ export type DiffCommentMutation = { + owner: DiffCommentOwner previous: DiffComment[] | undefined next: DiffComment[] - folderExecutionHostId?: ReturnType - /** The identity of the rows changed, so a queued save never reads a copy listed later. */ - twin?: DiffCommentTwin - /** The rows' own host, whenever they stamp one; the write names it. */ - writeHostId?: ExecutionHostId +} + +function folderExecutionHostIdOf( + owner: DiffCommentOwner +): ReturnType | undefined { + return owner.kind === 'folder' ? owner.executionHostId : undefined } // Why: one key for the queue and both bookkeeping maps, so they can never drift apart. @@ -95,13 +89,10 @@ export function enqueueDiffCommentPersist( get: () => AppState, mutation: DiffCommentMutation ): Promise { - const folderExecutionHostId = mutation.folderExecutionHostId + const folderExecutionHostId = folderExecutionHostIdOf(mutation.owner) const queueKey = persistQueueKey(worktreeId, folderExecutionHostId) - // Continue the floor that produced this list across twin appearance/removal; new chains take the copy’s own floor. - const floorKey = - [...(floorKeysByQueue.get(queueKey) ?? [])].find( - (key) => lastMutationNextByQueue.get(key) === mutation.previous - ) ?? diffCommentFloorKey(queueKey, mutation.twin) + // Copies sharing an id share one queue; each keeps its own floor, so a floor never restores another copy. + const floorKey = diffCommentOwnerKey(mutation.owner) floorKeysByQueue.set(queueKey, (floorKeysByQueue.get(queueKey) ?? new Set()).add(floorKey)) const prior = persistQueueByWorktree.get(queueKey) ?? Promise.resolve() // Why: an idle queue means disk still holds the pre-mutation list, so that list is this burst's rollback floor. @@ -123,40 +114,21 @@ export function enqueueDiffCommentPersist( let stateList: DiffComment[] | undefined try { const scope = parseWorkspaceKey(worktreeId) - if (scope?.type === 'folder') { - const state = get() - const folderWorkspace = findFolderWorkspaceOwner( - state, - scope.folderWorkspaceId, - folderExecutionHostId - ) - stateList = folderWorkspace?.diffComments - await writeDiffCommentsToHost( - state, - worktreeId, - (stateList ?? []).map(normalizeDiffComment), - folderExecutionHostId - ) - } else { - const state = get() - const { twin, writeHostId } = mutation - const queued = readQueuedDiffComments(state, worktreeId, { - twin, - hostId: writeHostId, - latest: lastMutationNextByQueue.get(floorKey) - }) - // Why: the copy these notes were made on is gone or now unnamed; never send another's list. - if (!queued) { + if (scope?.type === 'folder' && mutation.owner.kind === 'folder') { + const folderWorkspace = findOwnedFolder(get(), mutation.owner) + if (!folderWorkspace) { throw new Error('The workspace copy is gone; review notes were not saved.') } - stateList = queued.list - await writeDiffCommentsToHost( - state, - worktreeId, - (stateList ?? []).map(normalizeDiffComment), - undefined, - writeHostId - ) + stateList = folderWorkspace.diffComments + await writeDiffCommentsToHost(mutation.owner, (stateList ?? []).map(normalizeDiffComment)) + } else if (mutation.owner.kind === 'worktree') { + const rows = findCopyRows(get(), worktreeId, mutation.owner.authority) + // Why: the copy these notes were made on is gone; never send another's list. + if (rows.length === 0) { + throw new Error('The workspace copy is gone; review notes were not saved.') + } + stateList = rows.at(-1)?.diffComments + await writeDiffCommentsToHost(mutation.owner, (stateList ?? []).map(normalizeDiffComment)) } } catch (err) { // Why: converge to what actually landed; rollback's identity guard no-ops when a later mutation owns the array. @@ -195,23 +167,23 @@ export function enqueueDiffCommentPersist( // Why: derive the next list inside the `set` updater so concurrent writes can't clobber each other via a stale closure. export function mutateDiffComments( set: Parameters>[0], - worktreeId: string, - mutate: (existing: DiffComment[]) => DiffComment[] | null, - commentIds?: Iterable + owner: DiffCommentOwner, + mutate: (existing: DiffComment[]) => DiffComment[] | null ): DiffCommentMutation | null { + const worktreeId = owner.worktreeId const repoId = getRepoIdFromWorktreeId(worktreeId) let previous: DiffComment[] | undefined let next: DiffComment[] | null = null - let folderExecutionHostId: ReturnType | undefined - let twin: Pick = {} set((s) => { const scope = parseWorkspaceKey(worktreeId) if (scope?.type === 'folder') { - const target = findFolderWorkspaceOwner(s, scope.folderWorkspaceId) + if (owner.kind !== 'folder') { + return s + } + const target = findOwnedFolder(s, owner) if (!target) { return s } - folderExecutionHostId = getExecutionHostIdForFolderWorkspace(s, scope.folderWorkspaceId) previous = target.diffComments const computed = mutate(previous ?? []) if (computed === null) { @@ -224,34 +196,29 @@ export function mutateDiffComments( ) } } - const repoList = s.worktreesByRepo[repoId] - const found = findDiffCommentRows( - s, - worktreeId, - commentIds ? { commentIds: new Set(commentIds) } : {} - ) - if (!repoList || !found) { + if (owner.kind !== 'worktree') { return s } - twin = { - ...(found.twin ? { twin: found.twin } : {}), - ...(found.hostId ? { writeHostId: found.hostId } : {}) + const repoList = s.worktreesByRepo[repoId] + const rows = findCopyRows(s, worktreeId, owner.authority) + if (!repoList || rows.length === 0) { + return s } - previous = diffCommentRowNotes(found) + previous = rows.at(-1)?.diffComments const computed = mutate(previous ?? []) if (computed === null) { return s } next = computed const nextList: Worktree[] = repoList.map((w) => - found.worktrees.includes(w) ? { ...w, diffComments: computed } : w + rows.includes(w) ? { ...w, diffComments: computed } : w ) return { worktreesByRepo: { ...s.worktreesByRepo, [repoId]: nextList } } }) if (next === null) { return null } - return { previous, next, folderExecutionHostId, ...twin } + return { owner, previous, next } } // Why: on IPC-write failure, roll back optimistic state so the renderer matches disk (identity-guarded below). @@ -259,13 +226,16 @@ function rollback( set: Parameters>[0], worktreeId: string, previous: DiffComment[] | undefined, - { next: expectedCurrent, folderExecutionHostId }: DiffCommentMutation + { next: expectedCurrent, owner }: DiffCommentMutation ): void { const repoId = getRepoIdFromWorktreeId(worktreeId) set((s) => { const scope = parseWorkspaceKey(worktreeId) if (scope?.type === 'folder') { - const target = findFolderWorkspaceOwner(s, scope.folderWorkspaceId, folderExecutionHostId) + if (owner.kind !== 'folder') { + return s + } + const target = findOwnedFolder(s, owner) if (!target || target.diffComments !== expectedCurrent) { return s } @@ -280,9 +250,12 @@ function rollback( return s } // Rollback only rows still holding this mutation’s array; later mutations and untouched twins must survive. - const targets = repoList.filter( - (w) => w.id === worktreeId && w.diffComments === expectedCurrent - ) + const targets = + owner.kind === 'worktree' + ? findCopyRows(s, worktreeId, owner.authority).filter( + (w) => w.diffComments === expectedCurrent + ) + : [] // Removed worktrees return before remapping to avoid pointless identity churn/notifications. if (targets.length === 0) { return s diff --git a/src/renderer/src/store/slices/diff-comments-host-twins.test.ts b/src/renderer/src/store/slices/diff-comments-host-twins.test.ts index e8867859d3e..be31cb23841 100644 --- a/src/renderer/src/store/slices/diff-comments-host-twins.test.ts +++ b/src/renderer/src/store/slices/diff-comments-host-twins.test.ts @@ -1,12 +1,30 @@ +import type * as RuntimeRpcClient from '../../runtime/runtime-rpc-client' +import { callRuntimeRpc } from '../../runtime/runtime-rpc-client' +import { + diffCommentSendKey, + holdNotesForSend, + isNoteInFlight, + resetNotesInFlightForTests +} from '@/lib/notes-send-in-flight' +import type { AppState } from '../types' +import { + diffCommentOwnerKey, + selectDiffCommentView, + type DiffCommentOwner +} from '../diff-comment-owner' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toast } from 'sonner' import type { DiffComment } from '../../../../shared/diff-comment-types' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' +import { toSshExecutionHostId } from '../../../../shared/execution-host' import { createTestStore } from './store-test-helpers' -import { - diffCommentTwinHostId, - selectWorktreeDiffCommentsOrEmpty -} from '../worktree-diff-comments-selector' +import { selectWorktreeDiffCommentsOrEmpty } from '../worktree-diff-comments-selector' + +vi.mock('../../runtime/runtime-rpc-client', async (importOriginal) => ({ + ...(await importOriginal()), + callRuntimeRpc: vi.fn().mockResolvedValue({ ok: true }) +})) vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) @@ -77,7 +95,14 @@ function rowNotes(store: ReturnType, hostId: string): st } function addNote(store: ReturnType) { - return store.getState().addDiffComment({ + return addNoteFor(store, capturedOwner(store, WT)) +} + +function addNoteFor(store: ReturnType, owner: DiffCommentOwner | null) { + if (!owner) { + throw new Error('no workspace') + } + return store.getState().addDiffComment(owner, { worktreeId: WT, filePath: 'README.md', lineNumber: 1, @@ -87,6 +112,9 @@ function addNote(store: ReturnType) { } beforeEach(() => { + vi.mocked(callRuntimeRpc).mockClear() + vi.mocked(toast.error).mockClear() + resetNotesInFlightForTests() updateMeta.mockReset() updateMeta.mockResolvedValue({}) }) @@ -123,10 +151,13 @@ describe('diff comments on twin worktrees', () => { expect(rowNotes(store, 'local')).toEqual(['local note']) }) - it('refuses when no host names the twin instead of editing both', async () => { + it('offers no copy to change when no host names one of two twins', () => { const store = createTwinStore(null) - expect(await addNote(store)).toBeNull() + expect(selectDiffCommentView(store.getState(), WT, 'selection')).toEqual({ + owner: null, + comments: undefined + }) expect(rowNotes(store, 'ssh:box')).toEqual([]) expect(rowNotes(store, 'local')).toEqual([]) @@ -183,9 +214,10 @@ describe('diff comments on twin worktrees', () => { if (!sent) { throw new Error('note was not saved') } + const owner = capturedOwner(store, WT) store.setState({ activeWorktreeId: null, activeWorkspaceExecutionHostId: null }) - expect(await store.getState().clearDeliveredDiffComments(WT, [sent])).toBe(true) + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(true) expect(rowNotes(store, 'ssh:box')).toEqual([]) expect(updateMeta).toHaveBeenLastCalledWith( @@ -203,7 +235,7 @@ describe('diff comments on twin worktrees', () => { expect(await addNote(store)).not.toBeNull() expect(updateMeta).toHaveBeenCalledTimes(1) - expect(updateMeta.mock.calls[0][0]).not.toHaveProperty('executionHostId') + expect(updateMeta.mock.calls[0][0]).toHaveProperty('executionHostId', 'ssh:box') }) it('saves an open unstamped row its SSH repo owns', async () => { @@ -215,7 +247,7 @@ describe('diff comments on twin worktrees', () => { expect(await addNote(store)).not.toBeNull() - expect(updateMeta.mock.calls[0][0]).not.toHaveProperty('executionHostId') + expect(updateMeta.mock.calls[0][0]).toHaveProperty('executionHostId', 'ssh:box') }) it('picks an SSH twin a paired server proxies by its own stamp', () => { @@ -257,7 +289,7 @@ describe('diff comments on twin worktrees', () => { }) it('keeps saves in order when a listing stamps the row mid-burst', async () => { - const store = createTwinStore(null) + const store = createTwinStore('local') store.setState({ worktreesByRepo: { [REPO]: [worktree(undefined)] } }) let releaseFirst = () => {} updateMeta.mockImplementationOnce( @@ -279,7 +311,7 @@ describe('diff comments on twin worktrees', () => { }) it('rolls a failed burst back to disk when a listing stamps the row mid-burst', async () => { - const store = createTwinStore(null) + const store = createTwinStore('local') store.setState({ worktreesByRepo: { [REPO]: [worktree(undefined)] } }) updateMeta.mockRejectedValue(new Error('write failed')) @@ -332,19 +364,15 @@ describe('diff comments on twin worktrees', () => { expect(rowNotes(store, 'ssh:box')).toEqual(['ssh note 1', 'ssh note']) }) - it('names the paired server for a proxied SSH twin, as rival servers share the target', () => { - expect(diffCommentTwinHostId({ hostId: 'ssh:box', runtimeOwnerEnvironmentId: 'hub-a' })).toBe( - 'runtime:hub-a' - ) - }) - it('edits the duplicate row the notes panel shows', async () => { const store = createTwinStore(null) store.setState({ worktreesByRepo: { [REPO]: [worktree('local'), worktree('local', [note('l1', 'old')])] } }) - expect(await store.getState().updateDiffComment(WT, 'l1', 'new')).toBe(true) + expect(await store.getState().updateDiffComment(capturedOwner(store, WT), 'l1', 'new')).toBe( + true + ) expect(updateMeta).toHaveBeenCalledWith( expect.objectContaining({ @@ -408,7 +436,7 @@ describe('diff comments on twin worktrees', () => { } }) - await store.getState().deleteDiffComment(WT, 'u1') + await store.getState().deleteDiffComment(capturedOwner(store, WT), 'u1') expect(updateMeta).not.toHaveBeenCalled() expect(store.getState().worktreesByRepo[REPO][0].diffComments?.map((c) => c.body)).toEqual([ @@ -467,14 +495,14 @@ describe('diff comments on twin worktrees', () => { const store = createTwinStore('ssh:box') store.setState({ worktreesByRepo: { [REPO]: [worktree('local', [note('l1', 'local note')])] } }) - await store.getState().clearDiffComments(WT) + await store.getState().clearDiffComments(capturedOwner(store, WT)) expect(updateMeta).not.toHaveBeenCalled() expect(rowNotes(store, 'local')).toEqual(['local note']) }) it('still saves a lone unstamped row a listing stamps and rebuilds before the save runs', async () => { - const store = createTwinStore(null) + const store = createTwinStore('local') store.setState({ worktreesByRepo: { [REPO]: [worktree(undefined)] } }) const pending = addNote(store) @@ -489,3 +517,347 @@ describe('diff comments on twin worktrees', () => { expect(updateMeta).toHaveBeenCalledTimes(1) }) }) + +function capturedOwner(store: { getState: () => AppState }, worktreeId: string): DiffCommentOwner { + const { owner } = selectDiffCommentView(store.getState(), worktreeId, 'selection') + if (!owner) { + throw new Error('No copy of the workspace is shown.') + } + return owner +} + +describe('captured note owners across delivery and selection', () => { + it('clears only the sent twin after deferred delivery and isolates the in-flight key', async () => { + const store = createTwinStore('ssh:box') + const sent = note('same-id', 'same body') + store.setState({ + worktreesByRepo: { [REPO]: [worktree('local', [sent]), worktree('ssh:box', [sent])] } + }) + const ownerA = capturedOwner(store, WT) + let deliver = (_result: { delivered: boolean }) => {} + const delivered = new Promise<{ delivered: boolean }>((resolve) => { + deliver = resolve + }) + let cleared: Promise | undefined + holdNotesForSend([diffCommentSendKey(ownerA, sent)], delivered, () => { + cleared = store.getState().clearDeliveredDiffComments(ownerA, [sent]) + }) + store.setState({ activeWorkspaceExecutionHostId: 'local' }) + const ownerB = capturedOwner(store, WT) + expect(isNoteInFlight(diffCommentSendKey(ownerA, sent))).toBe(true) + expect(isNoteInFlight(diffCommentSendKey(ownerB, sent))).toBe(false) + deliver({ delivered: true }) + await delivered + expect(await cleared).toBe(true) + expect(rowNotes(store, 'ssh:box')).toEqual([]) + expect(rowNotes(store, 'local')).toEqual(['same body']) + expect(updateMeta).toHaveBeenCalledExactlyOnceWith({ + worktreeId: WT, + executionHostId: 'ssh:box', + updates: { diffComments: [] } + }) + expect(isNoteInFlight(diffCommentSendKey(ownerA, sent))).toBe(false) + }) + + it('keeps add and delete on the captured host after selection changes', async () => { + const store = createTwinStore('ssh:box') + const owner = capturedOwner(store, WT) + store.setState({ activeWorkspaceExecutionHostId: 'local' }) + const saved = await store.getState().addDiffComment(owner, { + worktreeId: WT, + filePath: 'a', + lineNumber: 1, + body: 'captured', + side: 'modified' + }) + expect(saved).not.toBeNull() + if (!saved) { + throw new Error('save failed') + } + await store.getState().deleteDiffComment(owner, saved.id) + expect(rowNotes(store, 'local')).toEqual([]) + expect(rowNotes(store, 'ssh:box')).toEqual([]) + expect(updateMeta).toHaveBeenCalledTimes(2) + expect(updateMeta.mock.calls.every(([args]) => args.executionHostId === 'ssh:box')).toBe(true) + }) + + it('writes a paired SSH row through its server even when the row names no server', async () => { + const store = createTwinStore('ssh:box') + store.setState({ + repos: [{ ...repoBase, connectionId: 'box', executionHostId: 'runtime:hub' }], + worktreesByRepo: { [REPO]: [worktree('ssh:box')] } + }) + const owner = capturedOwner(store, WT) + store.setState({ activeWorkspaceExecutionHostId: 'local' }) + + expect(await addNoteFor(store, owner)).not.toBeNull() + + expect(updateMeta).not.toHaveBeenCalled() + expect(callRuntimeRpc).toHaveBeenCalledExactlyOnceWith( + { kind: 'environment', environmentId: 'hub' }, + 'worktree.set', + expect.objectContaining({ diffComments: [expect.objectContaining({ body: 'ssh note' })] }), + expect.anything() + ) + }) + + it('keeps one owner and in-flight Send when a listing stamps the same copy', () => { + const store = createTwinStore('local') + const sent = note('n1', 'body') + store.setState({ worktreesByRepo: { [REPO]: [worktree(undefined, [sent])] } }) + const unstamped = capturedOwner(store, WT) + holdNotesForSend([diffCommentSendKey(unstamped, sent)], new Promise(() => {})) + + store.setState({ worktreesByRepo: { [REPO]: [worktree('local', [sent])] } }) + const stamped = capturedOwner(store, WT) + + expect(diffCommentOwnerKey(stamped)).toBe(diffCommentOwnerKey(unstamped)) + expect(isNoteInFlight(diffCommentSendKey(stamped, sent))).toBe(true) + }) + + it('keeps a composer opened before its SSH copy lists on that copy, never a local row listed first', async () => { + const store = createTwinStore('ssh:box') + store.setState({ worktreesByRepo: { [REPO]: [worktree('local', [note('l1', 'local')])] } }) + const view = selectDiffCommentView(store.getState(), WT, 'selection') + // Unknown, not empty: the selected copy is not listed, and its sibling's notes are not shown. + expect(view.comments).toBeUndefined() + + store.setState({ + activeWorkspaceExecutionHostId: 'local', + worktreesByRepo: { [REPO]: [worktree(undefined, [note('l1', 'local only')])] } + }) + expect(await addNoteFor(store, view.owner)).toBeNull() + expect(updateMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[REPO][0].diffComments?.map((c) => c.body)).toEqual([ + 'local only' + ]) + + store.setState({ + worktreesByRepo: { + [REPO]: [worktree(undefined, [note('l1', 'local only')]), worktree('ssh:box')] + } + }) + expect(await addNoteFor(store, view.owner)).not.toBeNull() + expect(updateMeta).toHaveBeenCalledExactlyOnceWith({ + worktreeId: WT, + executionHostId: 'ssh:box', + updates: { diffComments: [expect.objectContaining({ body: 'ssh note' })] } + }) + }) + + it('keeps a paired SSH capture through its server stamp: queued save, rollback, Send cleanup', async () => { + const store = createTwinStore('ssh:box') + const sent = note('n1', 'sent') + store.setState({ + repos: [{ ...repoBase, connectionId: 'box', executionHostId: 'runtime:hub' }], + worktreesByRepo: { [REPO]: [worktree('ssh:box', [sent])] } + }) + const owner = capturedOwner(store, WT) + let fail = () => {} + vi.mocked(callRuntimeRpc).mockImplementationOnce( + () => new Promise((_resolve, reject) => (fail = () => reject(new Error('unreachable')))) + ) + const pending = addNoteFor(store, owner) + // The listing confirms the server already captured, before the queued save reads the list. + const [row] = store.getState().worktreesByRepo[REPO] + store.setState({ worktreesByRepo: { [REPO]: [{ ...row, runtimeOwnerEnvironmentId: 'hub' }] } }) + expect(diffCommentOwnerKey(capturedOwner(store, WT))).toBe(diffCommentOwnerKey(owner)) + await vi.waitFor(() => expect(callRuntimeRpc).toHaveBeenCalledTimes(1)) + expect(vi.mocked(callRuntimeRpc).mock.calls[0][2]).toMatchObject({ + diffComments: [{ body: 'sent' }, { body: 'ssh note' }] + }) + fail() + + expect(await pending).toBeNull() + expect(store.getState().worktreesByRepo[REPO][0].diffComments).toEqual([sent]) + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(true) + expect(store.getState().worktreesByRepo[REPO][0].diffComments).toEqual([]) + expect(callRuntimeRpc).toHaveBeenLastCalledWith( + { kind: 'environment', environmentId: 'hub' }, + 'worktree.set', + expect.objectContaining({ diffComments: [] }), + expect.anything() + ) + expect(updateMeta).not.toHaveBeenCalled() + expect(toast.error).not.toHaveBeenCalled() + + // A rival server proxying the same target is another copy. + store.setState({ + activeWorkspaceExecutionHostId: 'runtime:hub-b', + worktreesByRepo: { + [REPO]: [ + ...store.getState().worktreesByRepo[REPO], + { ...worktree('ssh:box'), runtimeOwnerEnvironmentId: 'hub-b' } + ] + } + }) + expect(diffCommentOwnerKey(capturedOwner(store, WT))).not.toBe(diffCommentOwnerKey(owner)) + }) + + it('keeps a legacy unstamped paired row on its nested copy through confirming stamps', async () => { + const store = createTwinStore('runtime:hub') + const sent = note('n1', 'sent') + store.setState({ + repos: [{ ...repoBase, connectionId: 'box', executionHostId: 'runtime:hub' }], + worktreesByRepo: { [REPO]: [worktree(undefined, [sent])] } + }) + const owner = capturedOwner(store, WT) + expect(owner).toMatchObject({ + authority: { endpoint: { kind: 'environment', environmentId: 'hub' }, at: 'ssh:box' } + }) + let fail = () => {} + vi.mocked(callRuntimeRpc).mockImplementationOnce( + () => new Promise((_resolve, reject) => (fail = () => reject(new Error('unreachable')))) + ) + const pending = addNoteFor(store, owner) + const [row] = store.getState().worktreesByRepo[REPO] + store.setState({ + worktreesByRepo: { + [REPO]: [{ ...row, hostId: 'ssh:box', runtimeOwnerEnvironmentId: 'hub' }] + } + }) + expect(diffCommentOwnerKey(capturedOwner(store, WT))).toBe(diffCommentOwnerKey(owner)) + await vi.waitFor(() => expect(callRuntimeRpc).toHaveBeenCalledTimes(1)) + fail() + + expect(await pending).toBeNull() + expect(store.getState().worktreesByRepo[REPO][0].diffComments).toEqual([sent]) + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(true) + expect(callRuntimeRpc).toHaveBeenLastCalledWith( + { kind: 'environment', environmentId: 'hub' }, + 'worktree.set', + expect.objectContaining({ diffComments: [] }), + expect.anything() + ) + expect(updateMeta).not.toHaveBeenCalled() + expect(toast.error).not.toHaveBeenCalled() + }) + + it('writes an SSH row through the server a detected listing already names', async () => { + const store = createTwinStore('ssh:box') + store.setState({ + repos: [{ ...repoBase, executionHostId: 'runtime:hub' }], + worktreesByRepo: { [REPO]: [worktree('ssh:box', [note('n1', 'sent')])] }, + detectedWorktreesByRepo: { + [REPO]: { + repoId: REPO, + authoritative: true, + source: 'git', + worktrees: [ + { + ...worktree('ssh:box'), + runtimeOwnerEnvironmentId: 'hub', + ownership: 'orca-managed', + selectedCheckout: false, + visible: true + } + ] + } + } + }) + + expect(await addNote(store)).not.toBeNull() + expect(callRuntimeRpc).toHaveBeenCalledExactlyOnceWith( + { kind: 'environment', environmentId: 'hub' }, + 'worktree.set', + expect.objectContaining({ + diffComments: [ + expect.objectContaining({ body: 'sent' }), + expect.objectContaining({ body: 'ssh note' }) + ] + }), + expect.anything() + ) + expect(updateMeta).not.toHaveBeenCalled() + }) + + it('keeps a restored external SSH target whose id needs encoding on its own listed copy', async () => { + const hostId = toSshExecutionHostId('user@box') + const store = createTwinStore(hostId) + store.setState({ + repos: [{ ...repoBase, connectionId: 'user@box', executionHostId: hostId }], + worktreesByRepo: { [REPO]: [worktree(hostId, [note('n1', 'listed')])] } + }) + const view = selectDiffCommentView(store.getState(), WT, { + runtimeEnvironmentId: null, + externalSshTargetId: 'user@box' + }) + + expect(view.comments?.map((comment) => comment.body)).toEqual(['listed']) + expect(await addNoteFor(store, view.owner)).not.toBeNull() + expect(updateMeta).toHaveBeenCalledExactlyOnceWith({ + worktreeId: WT, + executionHostId: hostId, + updates: { + diffComments: [ + expect.objectContaining({ body: 'listed' }), + expect.objectContaining({ body: 'ssh note' }) + ] + } + }) + }) + + it('reports a copy gone since Send or edit once, through the existing failure toast', async () => { + const store = createTwinStore('ssh:box') + const sent = note('same-id', 'same body') + store.setState({ + worktreesByRepo: { [REPO]: [worktree('local', [sent]), worktree('ssh:box', [sent])] } + }) + const owner = capturedOwner(store, WT) + store.setState({ worktreesByRepo: { [REPO]: [worktree('local', [sent])] } }) + + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(false) + expect(vi.mocked(toast.error)).toHaveBeenCalledExactlyOnceWith('Failed to clear notes.') + vi.mocked(toast.error).mockClear() + expect(await store.getState().updateDiffComment(owner, sent.id, 'edited')).toBe(false) + expect(vi.mocked(toast.error)).toHaveBeenCalledExactlyOnceWith('Failed to save comment') + expect(rowNotes(store, 'local')).toEqual(['same body']) + }) + + it('refuses every mutation when the captured twin was removed', async () => { + const store = createTwinStore('ssh:box') + const sent = note('same-id', 'same body') + store.setState({ + worktreesByRepo: { [REPO]: [worktree('local', [sent]), worktree('ssh:box', [sent])] } + }) + const owner = capturedOwner(store, WT) + store.setState({ + activeWorkspaceExecutionHostId: 'local', + worktreesByRepo: { [REPO]: [worktree('local', [sent])] } + }) + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(false) + expect(await store.getState().clearDiffComments(owner)).toBe(false) + expect(await store.getState().clearDiffCommentsForFile(owner, 'a')).toBe(false) + expect(await store.getState().markDiffCommentsSent(owner, [sent.id])).toBe(false) + expect(await store.getState().updateDiffComment(owner, sent.id, 'changed')).toBe(false) + await store.getState().deleteDiffComment(owner, sent.id) + expect(rowNotes(store, 'local')).toEqual(['same body']) + expect(updateMeta).not.toHaveBeenCalled() + }) +}) + +it('keeps the paired server write authority when two servers proxy the same target', async () => { + const store = createTwinStore('runtime:hub-a') + const sent = note('same-id', 'same body') + store.setState({ + worktreesByRepo: { + [REPO]: [ + { ...worktree('ssh:box', [sent]), runtimeOwnerEnvironmentId: 'hub-a' }, + { ...worktree('ssh:box', [sent]), runtimeOwnerEnvironmentId: 'hub-b' } + ] + } + }) + const owner = capturedOwner(store, WT) + store.setState({ activeWorkspaceExecutionHostId: 'runtime:hub-b' }) + expect(await store.getState().clearDeliveredDiffComments(owner, [sent])).toBe(true) + expect(store.getState().worktreesByRepo[REPO].map((row) => row.diffComments?.length)).toEqual([ + 0, 1 + ]) + expect(callRuntimeRpc).toHaveBeenCalledExactlyOnceWith( + { kind: 'environment', environmentId: 'hub-a' }, + 'worktree.set', + expect.objectContaining({ diffComments: [] }), + { timeoutMs: 15_000 } + ) + expect(updateMeta).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/store/slices/diffComments.test.ts b/src/renderer/src/store/slices/diffComments.test.ts index adafd34b428..fb5f4ef6151 100644 --- a/src/renderer/src/store/slices/diffComments.test.ts +++ b/src/renderer/src/store/slices/diffComments.test.ts @@ -1,6 +1,9 @@ +import type { AppState } from '../types' +import { selectDiffCommentView, type DiffCommentOwner } from '../diff-comment-owner' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import type { DiffComment } from '../../../../shared/diff-comment-types' import type { Worktree } from '../../../../shared/worktree/types' +import { SELF_LOCAL_AUTHORITY } from '../../../../shared/host-authority' import { createCompatibleRuntimeStatusResponseIfNeeded, type RuntimeEnvironmentCallRequest @@ -174,7 +177,7 @@ describe('addDiffComment', () => { const store = createTestStore() seed(store, []) - const saved = await store.getState().addDiffComment({ + const saved = await store.getState().addDiffComment(capturedOwner(store, WT), { worktreeId: WT, filePath: 'README.md', source: 'markdown', @@ -194,6 +197,7 @@ describe('addDiffComment', () => { }) ) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [ @@ -239,7 +243,9 @@ describe('updateDiffComment', () => { } seed(store, [original]) - const ok = await store.getState().updateDiffComment(WT, 'c1', ' new body ') + const ok = await store + .getState() + .updateDiffComment(capturedOwner(store, WT), 'c1', ' new body ') expect(ok).toBe(true) const saved = store.getState().getDiffComments(WT)[0] @@ -277,7 +283,9 @@ describe('updateDiffComment', () => { { hostId: 'local', runtimeOwnerEnvironmentId: 'env-1' } ) - const ok = await store.getState().updateDiffComment(WT, 'c1', 'remote body') + const ok = await store + .getState() + .updateDiffComment(capturedOwner(store, WT), 'c1', 'remote body') expect(ok).toBe(true) expect(updateMeta).not.toHaveBeenCalled() @@ -309,10 +317,13 @@ describe('updateDiffComment', () => { }) seed(store, [makeComment({ id: 'c1', body: 'old body' })]) - const ok = await store.getState().updateDiffComment(WT, 'c1', 'local body') + const ok = await store + .getState() + .updateDiffComment(capturedOwner(store, WT), 'c1', 'local body') expect(ok).toBe(true) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [expect.objectContaining({ id: 'c1', body: 'local body' })] @@ -335,7 +346,7 @@ describe('updateDiffComment', () => { } ]) - const ok = await store.getState().updateDiffComment(WT, 'c1', ' ') + const ok = await store.getState().updateDiffComment(capturedOwner(store, WT), 'c1', ' ') expect(ok).toBe(false) expect(store.getState().getDiffComments(WT)[0].body).toBe('old body') @@ -356,7 +367,7 @@ describe('updateDiffComment', () => { } ]) - const ok = await store.getState().updateDiffComment(WT, 'c1', 'same') + const ok = await store.getState().updateDiffComment(capturedOwner(store, WT), 'c1', 'same') expect(ok).toBe(true) expect(updateMeta).not.toHaveBeenCalled() @@ -366,7 +377,9 @@ describe('updateDiffComment', () => { const store = createTestStore() seed(store, []) - const ok = await store.getState().updateDiffComment(WT, 'missing', 'anything') + const ok = await store + .getState() + .updateDiffComment(capturedOwner(store, WT), 'missing', 'anything') expect(ok).toBe(false) expect(updateMeta).not.toHaveBeenCalled() @@ -388,7 +401,7 @@ describe('updateDiffComment', () => { updateMeta.mockRejectedValueOnce(new Error('disk full')) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const ok = await store.getState().updateDiffComment(WT, 'c1', 'new body') + const ok = await store.getState().updateDiffComment(capturedOwner(store, WT), 'c1', 'new body') expect(ok).toBe(false) expect(store.getState().getDiffComments(WT)[0].body).toBe('old body') @@ -421,7 +434,7 @@ describe('markDiffCommentsSent', () => { makeComment({ id: 'c2', filePath: 'src/bar.ts' }) ]) - const ok = await store.getState().markDiffCommentsSent(WT, ['c1'], 3000) + const ok = await store.getState().markDiffCommentsSent(capturedOwner(store, WT), ['c1'], 3000) expect(ok).toBe(true) const saved = store.getState().getDiffComments(WT) @@ -430,6 +443,7 @@ describe('markDiffCommentsSent', () => { expect(saved[1].sentAt).toBeUndefined() expect(updateMeta).toHaveBeenCalledTimes(1) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [expect.objectContaining({ id: 'c1', sentAt: 3000 }), expect.any(Object)] @@ -445,7 +459,9 @@ describe('markDiffCommentsSent', () => { const comments = [makeComment({ id: 'c1' })] seed(store, comments) - const ok = await store.getState().markDiffCommentsSent(WT, ['missing'], 3000) + const ok = await store + .getState() + .markDiffCommentsSent(capturedOwner(store, WT), ['missing'], 3000) expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toBe(comments) @@ -476,12 +492,15 @@ describe('clearDeliveredDiffComments', () => { const pending = makeComment({ id: 'c2', filePath: 'src/bar.ts' }) seed(store, [delivered, pending]) - const ok = await store.getState().clearDeliveredDiffComments(WT, [delivered]) + const ok = await store + .getState() + .clearDeliveredDiffComments(capturedOwner(store, WT), [delivered]) expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toEqual([pending]) expect(updateMeta).toHaveBeenCalledTimes(1) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [pending] } }) @@ -494,11 +513,14 @@ describe('clearDeliveredDiffComments', () => { const delivered = makeComment({ id: 'c2', body: 'unchanged' }) seed(store, [edited, delivered]) - const ok = await store.getState().clearDeliveredDiffComments(WT, [sentSnapshot, delivered]) + const ok = await store + .getState() + .clearDeliveredDiffComments(capturedOwner(store, WT), [sentSnapshot, delivered]) expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toEqual([edited]) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [edited] } }) @@ -511,7 +533,9 @@ describe('clearDeliveredDiffComments', () => { updateMeta.mockRejectedValueOnce(new Error('disk full')) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const ok = await store.getState().clearDeliveredDiffComments(WT, [comments[0]]) + const ok = await store + .getState() + .clearDeliveredDiffComments(capturedOwner(store, WT), [comments[0]]) expect(ok).toBe(false) expect(store.getState().getDiffComments(WT)).toBe(comments) @@ -543,12 +567,13 @@ describe('bulk clear diff comments', () => { makeComment({ id: 'c2', filePath: 'src/bar.ts' }) ]) - const ok = await store.getState().clearDiffComments(WT) + const ok = await store.getState().clearDiffComments(capturedOwner(store, WT)) expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toEqual([]) expect(updateMeta).toHaveBeenCalledTimes(1) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [] } }) @@ -562,7 +587,9 @@ describe('bulk clear diff comments', () => { makeComment({ id: 'c3', filePath: 'src/foo.ts', lineNumber: 20 }) ]) - const ok = await store.getState().clearDiffCommentsForFile(WT, 'src/foo.ts') + const ok = await store + .getState() + .clearDiffCommentsForFile(capturedOwner(store, WT), 'src/foo.ts') expect(ok).toBe(true) expect( @@ -573,6 +600,7 @@ describe('bulk clear diff comments', () => { ).toEqual(['c2']) expect(updateMeta).toHaveBeenCalledTimes(1) expect(updateMeta).toHaveBeenCalledWith({ + executionHostId: 'local', worktreeId: WT, updates: { diffComments: [expect.objectContaining({ id: 'c2' })] } }) @@ -586,7 +614,9 @@ describe('bulk clear diff comments', () => { makeComment({ id: 'other', filePath: 'src/foo.ts' }) ]) - await store.getState().clearDiffCommentsForFile(WT, 'README.md', { keepMarkdownNotes: true }) + await store + .getState() + .clearDiffCommentsForFile(capturedOwner(store, WT), 'README.md', { keepMarkdownNotes: true }) expect( store .getState() @@ -594,7 +624,7 @@ describe('bulk clear diff comments', () => { .map((c) => c.id) ).toEqual(['md', 'other']) - await store.getState().clearDiffComments(WT, { keepMarkdownNotes: true }) + await store.getState().clearDiffComments(capturedOwner(store, WT), { keepMarkdownNotes: true }) expect( store .getState() @@ -608,7 +638,9 @@ describe('bulk clear diff comments', () => { const comments = [makeComment({ id: 'md', filePath: 'README.md', source: 'markdown' })] seed(store, comments) - const ok = await store.getState().clearDiffComments(WT, { keepMarkdownNotes: true }) + const ok = await store + .getState() + .clearDiffComments(capturedOwner(store, WT), { keepMarkdownNotes: true }) expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toBe(comments) @@ -620,7 +652,9 @@ describe('bulk clear diff comments', () => { const comments = [makeComment({ id: 'c1', filePath: 'src/foo.ts' })] seed(store, comments) - const ok = await store.getState().clearDiffCommentsForFile(WT, 'src/missing.ts') + const ok = await store + .getState() + .clearDiffCommentsForFile(capturedOwner(store, WT), 'src/missing.ts') expect(ok).toBe(true) expect(store.getState().getDiffComments(WT)).toBe(comments) @@ -642,7 +676,7 @@ describe('bulk clear diff comments', () => { runtimeOwnerEnvironmentId: 'env-1' }) - const ok = await store.getState().clearDiffComments(WT) + const ok = await store.getState().clearDiffComments(capturedOwner(store, WT)) expect(ok).toBe(true) expect(updateMeta).not.toHaveBeenCalled() @@ -664,7 +698,7 @@ describe('bulk clear diff comments', () => { updateMeta.mockRejectedValueOnce(new Error('disk full')) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const ok = await store.getState().clearDiffComments(WT) + const ok = await store.getState().clearDiffComments(capturedOwner(store, WT)) expect(ok).toBe(false) expect(store.getState().getDiffComments(WT)).toBe(comments) @@ -685,7 +719,7 @@ describe('bulk clear diff comments', () => { ) const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const clearPromise = store.getState().clearDiffComments(WT) + const clearPromise = store.getState().clearDiffComments(capturedOwner(store, WT)) await Promise.resolve() seed(store, laterComments) rejectPersist(new Error('disk full')) @@ -723,7 +757,7 @@ describe('worktree diff comment rollback convergence', () => { }) function addNote(store: ReturnType, body: string, lineNumber: number) { - return store.getState().addDiffComment({ + return store.getState().addDiffComment(capturedOwner(store, WT), { worktreeId: WT, filePath: 'src/foo.ts', lineNumber, @@ -752,8 +786,8 @@ describe('worktree diff comment rollback convergence', () => { seed(store, comments) updateMeta.mockRejectedValue(new Error('disk full')) - const removed = store.getState().deleteDiffComment(WT, 'c1') - const marked = store.getState().markDiffCommentsSent(WT, ['c2'], 3000) + const removed = store.getState().deleteDiffComment(capturedOwner(store, WT), 'c1') + const marked = store.getState().markDiffCommentsSent(capturedOwner(store, WT), ['c2'], 3000) // deleteDiffComment returns no boolean; absent return must not hide write failures. await expect(removed).resolves.toBeUndefined() @@ -777,3 +811,14 @@ describe('worktree diff comment rollback convergence', () => { expect(store.getState().getDiffComments(WT)).toBe(comments) }) }) + +function capturedOwner(store: { getState: () => AppState }, worktreeId: string): DiffCommentOwner { + return ( + // An unlisted id stands for a copy that is gone, so actions on it are refused. + selectDiffCommentView(store.getState(), worktreeId, 'selection').owner ?? { + kind: 'worktree', + worktreeId, + authority: SELF_LOCAL_AUTHORITY + } + ) +} diff --git a/src/renderer/src/store/slices/diffComments.ts b/src/renderer/src/store/slices/diffComments.ts index 69d6d700de7..4edbece9a59 100644 --- a/src/renderer/src/store/slices/diffComments.ts +++ b/src/renderer/src/store/slices/diffComments.ts @@ -1,3 +1,5 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { DiffComment } from '../../../../shared/diff-comment-types' @@ -8,28 +10,32 @@ import { mutateDiffComments, normalizeDiffComment } from './diff-comment-persistence' -import { - readDiffCommentsForChange, - selectWorktreeDiffCommentsOrEmpty -} from '../worktree-diff-comments-selector' +import { selectWorktreeDiffCommentsOrEmpty } from '../worktree-diff-comments-selector' +import { readOwnedDiffComments, type DiffCommentOwner } from '../diff-comment-owner' export type DiffCommentsSlice = { getDiffComments: (worktreeId: string | null | undefined) => DiffComment[] - addDiffComment: (input: Omit) => Promise - updateDiffComment: (worktreeId: string, commentId: string, body: string) => Promise + addDiffComment: ( + owner: DiffCommentOwner, + input: Omit + ) => Promise + updateDiffComment: (owner: DiffCommentOwner, commentId: string, body: string) => Promise clearDeliveredDiffComments: ( - worktreeId: string, + owner: DiffCommentOwner, comments: readonly DiffCommentDeliverySnapshot[] ) => Promise markDiffCommentsSent: ( - worktreeId: string, + owner: DiffCommentOwner, commentIds: readonly string[], sentAt?: number ) => Promise - deleteDiffComment: (worktreeId: string, commentId: string) => Promise - clearDiffComments: (worktreeId: string, options?: DiffCommentsClearOptions) => Promise + deleteDiffComment: (owner: DiffCommentOwner, commentId: string) => Promise + clearDiffComments: ( + owner: DiffCommentOwner, + options?: DiffCommentsClearOptions + ) => Promise clearDiffCommentsForFile: ( - worktreeId: string, + owner: DiffCommentOwner, filePath: string, options?: DiffCommentsClearOptions ) => Promise @@ -73,6 +79,19 @@ function recordReviewNoteInteraction(get: () => AppState): void { } } +// Why: a copy gone since the user acted fails once, never on another copy. Add and clear callers already report their failures. +function reportLostDiffCommentOwner(action: 'save' | 'clear'): void { + console.error('Review notes were not changed: the workspace copy they belong to is gone.') + toast.error( + action === 'save' + ? translate('auto.components.editor.diffCommentSaveFailed', 'Failed to save comment') + : translate( + 'auto.components.right.sidebar.SourceControl.eae7a1da5f', + 'Failed to clear notes.' + ) + ) +} + export const createDiffCommentsSlice: StateCreator = ( set, get @@ -80,13 +99,16 @@ export const createDiffCommentsSlice: StateCreator selectWorktreeDiffCommentsOrEmpty(get(), worktreeId), - addDiffComment: async (input) => { + addDiffComment: async (owner, input) => { + if (!readOwnedDiffComments(get(), owner) || owner.worktreeId !== input.worktreeId) { + return null + } const comment: DiffComment = normalizeDiffComment({ ...input, id: generateId(), createdAt: Date.now() }) - const result = mutateDiffComments(set, input.worktreeId, (existing) => [...existing, comment]) + const result = mutateDiffComments(set, owner, (existing) => [...existing, comment]) if (!result) { return null } @@ -101,7 +123,12 @@ export const createDiffCommentsSlice: StateCreator { + updateDiffComment: async (owner, commentId, body) => { + if (!readOwnedDiffComments(get(), owner)) { + reportLostDiffCommentOwner('save') + return false + } + const worktreeId = owner.worktreeId // Why: reject an empty edit so we never save a note that renders as a blank card; false means "not committed", keep the editor open. const trimmed = body.trim() if (!trimmed) { @@ -109,7 +136,7 @@ export const createDiffCommentsSlice: StateCreator c.id === commentId) if (existingIdx === -1) { return false @@ -118,24 +145,19 @@ export const createDiffCommentsSlice: StateCreator { - const idx = current.findIndex((c) => c.id === commentId) - if (idx === -1) { - return null - } - if (current[idx].body === trimmed) { - return null - } - const next = current.slice() - // Why: editing a sent note makes the agent's copy stale, so reset sentAt to re-queue it for the next Send. - next[idx] = { ...current[idx], body: trimmed, sentAt: undefined } - return next - }, - [commentId] - ) + const result = mutateDiffComments(set, owner, (current) => { + const idx = current.findIndex((c) => c.id === commentId) + if (idx === -1) { + return null + } + if (current[idx].body === trimmed) { + return null + } + const next = current.slice() + // Why: editing a sent note makes the agent's copy stale, so reset sentAt to re-queue it for the next Send. + next[idx] = { ...current[idx], body: trimmed, sentAt: undefined } + return next + }) if (!result) { // Why: comment vanished or the same body was already written between pre-check and set; treat as success so the editor closes. return true @@ -149,24 +171,24 @@ export const createDiffCommentsSlice: StateCreator { + clearDeliveredDiffComments: async (owner, comments) => { + if (!readOwnedDiffComments(get(), owner)) { + reportLostDiffCommentOwner('clear') + return false + } + const worktreeId = owner.worktreeId if (comments.length === 0) { return true } const snapshotsById = new Map(comments.map((comment) => [comment.id, comment])) - const result = mutateDiffComments( - set, - worktreeId, - (existing) => { - const next = existing.filter((comment) => { - const snapshot = snapshotsById.get(comment.id) - // Why: delivery is async; a note edited after its snapshot was sent is a fresh pending note that must stay visible. - return !snapshot || !deliverySnapshotMatches(comment, snapshot) - }) - return next.length === existing.length ? null : next - }, - snapshotsById.keys() - ) + const result = mutateDiffComments(set, owner, (existing) => { + const next = existing.filter((comment) => { + const snapshot = snapshotsById.get(comment.id) + // Why: delivery is async; a note edited after its snapshot was sent is a fresh pending note that must stay visible. + return !snapshot || !deliverySnapshotMatches(comment, snapshot) + }) + return next.length === existing.length ? null : next + }) if (!result) { return true } @@ -180,27 +202,26 @@ export const createDiffCommentsSlice: StateCreator { + markDiffCommentsSent: async (owner, commentIds, sentAt = Date.now()) => { + if (!readOwnedDiffComments(get(), owner)) { + return false + } + const worktreeId = owner.worktreeId if (commentIds.length === 0) { return true } const ids = new Set(commentIds) - const result = mutateDiffComments( - set, - worktreeId, - (existing) => { - let changed = false - const next = existing.map((comment) => { - if (!ids.has(comment.id) || comment.sentAt === sentAt) { - return comment - } - changed = true - return { ...comment, sentAt } - }) - return changed ? next : null - }, - ids - ) + const result = mutateDiffComments(set, owner, (existing) => { + let changed = false + const next = existing.map((comment) => { + if (!ids.has(comment.id) || comment.sentAt === sentAt) { + return comment + } + changed = true + return { ...comment, sentAt } + }) + return changed ? next : null + }) if (!result) { return true } @@ -214,16 +235,16 @@ export const createDiffCommentsSlice: StateCreator { - const result = mutateDiffComments( - set, - worktreeId, - (existing) => { - const next = existing.filter((c) => c.id !== commentId) - return next.length === existing.length ? null : next - }, - [commentId] - ) + deleteDiffComment: async (owner, commentId) => { + if (!readOwnedDiffComments(get(), owner)) { + reportLostDiffCommentOwner('clear') + return + } + const worktreeId = owner.worktreeId + const result = mutateDiffComments(set, owner, (existing) => { + const next = existing.filter((c) => c.id !== commentId) + return next.length === existing.length ? null : next + }) if (!result) { return } @@ -235,8 +256,12 @@ export const createDiffCommentsSlice: StateCreator { - const result = mutateDiffComments(set, worktreeId, (existing) => { + clearDiffComments: async (owner, options) => { + if (!readOwnedDiffComments(get(), owner)) { + return false + } + const worktreeId = owner.worktreeId + const result = mutateDiffComments(set, owner, (existing) => { const next = options?.keepMarkdownNotes ? existing.filter(isMarkdownComment) : [] return next.length === existing.length ? null : next }) @@ -252,8 +277,12 @@ export const createDiffCommentsSlice: StateCreator { - const result = mutateDiffComments(set, worktreeId, (existing) => { + clearDiffCommentsForFile: async (owner, filePath, options) => { + if (!readOwnedDiffComments(get(), owner)) { + return false + } + const worktreeId = owner.worktreeId + const result = mutateDiffComments(set, owner, (existing) => { const next = existing.filter( (c) => c.filePath !== filePath || (options?.keepMarkdownNotes === true && isMarkdownComment(c)) diff --git a/src/renderer/src/store/slices/empty-update-notifications.test.ts b/src/renderer/src/store/slices/empty-update-notifications.test.ts index 692fa50b7d4..0e2cb2cf402 100644 --- a/src/renderer/src/store/slices/empty-update-notifications.test.ts +++ b/src/renderer/src/store/slices/empty-update-notifications.test.ts @@ -3,6 +3,7 @@ import { createTestStore } from './store-test-helpers' import { createTabsSliceMockApi } from './tabs-slice-test-harness' import { browserImportStateForHostUpdate } from './browser/browser-host-state' import { mutateDiffComments } from './diff-comment-persistence' +import { SELF_LOCAL_AUTHORITY } from '../../../../shared/host-authority' vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) createTabsSliceMockApi() @@ -72,7 +73,11 @@ describe('empty store updates', () => { before.switchBrowserTabProfile('missing', null, 'persist:missing') before.recordClientHostedBrowserCloseIntents([]) before.clearClientHostedBrowserCloseIntents('missing', []) - mutateDiffComments(store.setState, 'missing', () => null) + mutateDiffComments( + store.setState, + { kind: 'worktree', worktreeId: 'missing', authority: SELF_LOCAL_AUTHORITY }, + () => null + ) store.setState((state) => browserImportStateForHostUpdate(state, 'runtime:other', null)) expect(store.getState()).toBe(before) diff --git a/src/renderer/src/store/slices/folder-workspace-diff-comments.test.ts b/src/renderer/src/store/slices/folder-workspace-diff-comments.test.ts index becb12ff500..36ea8bea4f7 100644 --- a/src/renderer/src/store/slices/folder-workspace-diff-comments.test.ts +++ b/src/renderer/src/store/slices/folder-workspace-diff-comments.test.ts @@ -1,3 +1,4 @@ +import { selectDiffCommentView, type DiffCommentOwner } from '../diff-comment-owner' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { create } from 'zustand' import type { AppState } from '../types' @@ -5,6 +6,8 @@ import type { DiffComment } from '../../../../shared/diff-comment-types' import type { FolderWorkspace } from '../../../../shared/folder-workspace-types' import type { ProjectGroup } from '../../../../shared/project-group-types' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' +import { SELF_LOCAL_AUTHORITY } from '../../../../shared/host-authority' import { createCompatibleRuntimeStatusResponseIfNeeded, type RuntimeEnvironmentCallRequest @@ -78,7 +81,7 @@ function addNote( body: string, lineNumber = 1 ): Promise { - return store.getState().addDiffComment({ + return store.getState().addDiffComment(capturedOwner(store, workspaceKey), { worktreeId: workspaceKey, filePath: 'README.md', source: 'markdown', @@ -88,6 +91,31 @@ function addNote( }) } +function folderNote(worktreeId: string, body: string): DiffComment { + return { + id: body, + worktreeId, + filePath: 'README.md', + lineNumber: 1, + body, + createdAt: 1, + side: 'modified' + } +} + +function savedServer(id: string): PublicKnownRuntimeEnvironment { + return { + id, + name: id, + createdAt: 1, + updatedAt: 1, + lastUsedAt: null, + runtimeId: id, + endpoints: [{ id: 'ws', kind: 'websocket', label: 'WebSocket', endpoint: 'ws://server' }], + preferredEndpointId: 'ws' + } +} + function bodies(store: ReturnType, workspaceKey: string): string[] { return store .getState() @@ -113,14 +141,16 @@ describe('folder workspace diff comments', () => { ...updates })) - const saved = await store.getState().addDiffComment({ - worktreeId: folderWorkspaceKey(folderWorkspace.id), - filePath: 'README.md', - source: 'markdown', - lineNumber: 1, - body: 'folder note', - side: 'modified' - }) + const saved = await store + .getState() + .addDiffComment(capturedOwner(store, folderWorkspaceKey(folderWorkspace.id)), { + worktreeId: folderWorkspaceKey(folderWorkspace.id), + filePath: 'README.md', + source: 'markdown', + lineNumber: 1, + body: 'folder note', + side: 'modified' + }) expect(saved).toEqual(expect.objectContaining({ body: 'folder note' })) expect(store.getState().getDiffComments(folderWorkspaceKey(folderWorkspace.id))).toEqual([ @@ -146,23 +176,27 @@ describe('folder workspace diff comments', () => { return { ...folderWorkspace, ...updates } }) - const addFirst = store.getState().addDiffComment({ - worktreeId: folderWorkspaceKey(folderWorkspace.id), - filePath: 'README.md', - source: 'markdown', - lineNumber: 1, - body: 'first note', - side: 'modified' - }) + const addFirst = store + .getState() + .addDiffComment(capturedOwner(store, folderWorkspaceKey(folderWorkspace.id)), { + worktreeId: folderWorkspaceKey(folderWorkspace.id), + filePath: 'README.md', + source: 'markdown', + lineNumber: 1, + body: 'first note', + side: 'modified' + }) await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledTimes(1)) - const addSecond = store.getState().addDiffComment({ - worktreeId: folderWorkspaceKey(folderWorkspace.id), - filePath: 'README.md', - source: 'markdown', - lineNumber: 2, - body: 'second note', - side: 'modified' - }) + const addSecond = store + .getState() + .addDiffComment(capturedOwner(store, folderWorkspaceKey(folderWorkspace.id)), { + worktreeId: folderWorkspaceKey(folderWorkspace.id), + filePath: 'README.md', + source: 'markdown', + lineNumber: 2, + body: 'second note', + side: 'modified' + }) releaseFirstWrite?.() await Promise.all([addFirst, addSecond]) @@ -237,7 +271,7 @@ describe('folder workspace diff comments', () => { : [localWorkspace, runtimeWorkspace] }) - const localAdd = store.getState().addDiffComment({ + const localAdd = store.getState().addDiffComment(capturedOwner(store, workspaceKey), { worktreeId: workspaceKey, filePath: 'LOCAL.md', source: 'markdown', @@ -248,7 +282,7 @@ describe('folder workspace diff comments', () => { await vi.waitFor(() => expect(folderWorkspacesUpdate).toHaveBeenCalledOnce()) store.setState({ activeWorkspaceExecutionHostId: 'runtime:env-owner' }) - const runtimeAdd = store.getState().addDiffComment({ + const runtimeAdd = store.getState().addDiffComment(capturedOwner(store, workspaceKey), { worktreeId: workspaceKey, filePath: 'REMOTE.md', source: 'markdown', @@ -649,6 +683,119 @@ describe('folder workspace diff comment rollback convergence', () => { expect(folderWorkspacesUpdate).not.toHaveBeenCalled() }) + it("reads and saves a server folder's notes from its own source while the local twin is selected", async () => { + const store = createTestStore() + const key = folderWorkspaceKey('folder-1') + const runtimeWorkspace = makeFolderWorkspace({ + projectGroupId: 'runtime-group', + executionHostId: 'runtime:env-owner', + diffComments: [folderNote(key, 'runtime A')] + }) + store.setState({ + activeWorktreeId: key, + activeWorkspaceExecutionHostId: 'local', + folderWorkspaces: [ + makeFolderWorkspace({ diffComments: [folderNote(key, 'local B')] }), + runtimeWorkspace + ] + }) + runtimeEnvironmentCall.mockImplementation(async () => ({ + id: 'rpc-folder-update', + ok: true, + result: { folderWorkspace: runtimeWorkspace }, + _meta: { runtimeId: 'remote-runtime' } + })) + const view = selectDiffCommentView(store.getState(), key, { runtimeEnvironmentId: 'env-owner' }) + + expect(view.comments?.map((comment) => comment.body)).toEqual(['runtime A']) + expect(view.owner).toEqual({ + kind: 'folder', + worktreeId: key, + executionHostId: 'runtime:env-owner', + runtimeEnvironmentId: 'env-owner' + }) + if (!view.owner) { + throw new Error('no owner') + } + await store.getState().addDiffComment(view.owner, { + worktreeId: key, + filePath: 'README.md', + source: 'markdown', + lineNumber: 2, + body: 'added', + side: 'modified' + }) + expect(runtimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ selector: 'env-owner', method: 'folderWorkspace.update' }) + ) + expect(folderWorkspacesUpdate).not.toHaveBeenCalled() + expect(bodies(store, key)).toEqual(['local B']) + }) + + it("keeps an app source on this app's folder: shown beside a server twin, never adopting a lone server folder", () => { + const store = createTestStore() + const key = folderWorkspaceKey('folder-1') + const runtimeWorkspace = makeFolderWorkspace({ + projectGroupId: 'runtime-group', + executionHostId: 'runtime:env-owner', + diffComments: [folderNote(key, 'runtime B')] + }) + store.setState({ + activeWorktreeId: key, + activeWorkspaceExecutionHostId: 'runtime:env-owner', + folderWorkspaces: [ + makeFolderWorkspace({ diffComments: [folderNote(key, 'local A')] }), + runtimeWorkspace + ] + }) + const view = () => selectDiffCommentView(store.getState(), key, { runtimeEnvironmentId: null }) + + expect(view().comments?.map((comment) => comment.body)).toEqual(['local A']) + expect(view().owner).toMatchObject({ executionHostId: 'local', runtimeEnvironmentId: null }) + + store.setState({ folderWorkspaces: [runtimeWorkspace] }) + expect(view()).toEqual({ owner: null, comments: undefined }) + }) + + it('drops a queued folder save once its catalog endpoint is replaced, touching no other copy', async () => { + Object.assign(globalThis, { __ORCA_WEB_CLIENT__: true }) + try { + const store = createTestStore() + const key = folderWorkspaceKey('folder-1') + const folder = makeFolderWorkspace({ diffComments: [folderNote(key, 'hub A')] }) + store.setState({ + activeWorktreeId: key, + activeWorkspaceExecutionHostId: 'local', + runtimeEnvironments: [savedServer('hub-a')], + folderWorkspaces: [folder] + }) + const owner = capturedOwner(store, key) + expect(owner).toMatchObject({ runtimeEnvironmentId: 'hub-a' }) + + const pending = store.getState().addDiffComment(owner, { + worktreeId: key, + filePath: 'README.md', + lineNumber: 2, + body: 'added', + side: 'modified' + }) + const replacement = { ...folder, diffComments: [folderNote(key, 'hub B')] } + store.setState({ + runtimeEnvironments: [savedServer('hub-b')], + folderWorkspaces: [replacement] + }) + + expect(await pending).toBeNull() + expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith( + expect.objectContaining({ method: 'folderWorkspace.update' }) + ) + expect(folderWorkspacesUpdate).not.toHaveBeenCalled() + expect(store.getState().folderWorkspaces).toEqual([replacement]) + } finally { + Reflect.deleteProperty(globalThis, '__ORCA_WEB_CLIENT__') + } + }) + it('keeps a failing burst scoped to its own execution host', async () => { const store = createTestStore() const workspaceId = 'shared-folder-id' @@ -690,3 +837,14 @@ describe('folder workspace diff comment rollback convergence', () => { expect(bodies(store, key)).toEqual(['runtime note']) }) }) + +function capturedOwner(store: { getState: () => AppState }, worktreeId: string): DiffCommentOwner { + return ( + // An unlisted id stands for a copy that is gone, so actions on it are refused. + selectDiffCommentView(store.getState(), worktreeId, 'selection').owner ?? { + kind: 'worktree', + worktreeId, + authority: SELF_LOCAL_AUTHORITY + } + ) +} diff --git a/src/renderer/src/store/workspace-record-selectors.ts b/src/renderer/src/store/workspace-record-selectors.ts index 35932e3da60..0ddab5cd140 100644 --- a/src/renderer/src/store/workspace-record-selectors.ts +++ b/src/renderer/src/store/workspace-record-selectors.ts @@ -74,15 +74,10 @@ const qualifiedFolderOwnerCache = new WeakMap< } >() -export function resolveQualifiedIndexedFolderWorkspace( - state: QualifiedFolderHostState, - folderWorkspaceId: string, - executionHostId?: ExecutionHostId -): ReturnType> { - const folders = selectFolderWorkspaces(state) - if (!folders) { - return { kind: 'missing' } - } +function qualifiedFolderCacheOf( + state: QualifiedFolderHostState, + folders: readonly FolderHostWorkspace[] +) { let cache = qualifiedFolderOwnerCache.get(folders) if (!cache || cache.groups !== state.projectGroups || cache.repos !== state.repos) { const rows = new Map() @@ -97,6 +92,32 @@ export function resolveQualifiedIndexedFolderWorkspace( + state: QualifiedFolderHostState, + folderWorkspaceId: string, + executionHostId?: ExecutionHostId +): ReturnType> { + const folders = selectFolderWorkspaces(state) + if (!folders) { + return { kind: 'missing' } + } + const cache = qualifiedFolderCacheOf(state, folders) const key = executionHostId ? `${folderWorkspaceId}\0${executionHostId}` : folderWorkspaceId let result = cache.results.get(key) if (!result) { diff --git a/src/renderer/src/store/worktree-diff-comments-selector.test.ts b/src/renderer/src/store/worktree-diff-comments-selector.test.ts index f35c18c77ec..75421dd350c 100644 --- a/src/renderer/src/store/worktree-diff-comments-selector.test.ts +++ b/src/renderer/src/store/worktree-diff-comments-selector.test.ts @@ -1,18 +1,20 @@ import { describe, expect, it } from 'vitest' import type { DiffComment } from '../../../shared/diff-comment-types' -import type { Worktree } from '../../../shared/worktree/types' import type { AppState } from './types' +import { makeWorktree } from './slices/worktrees-slice-test-fixtures' import { selectWorktreeDiffComments, selectWorktreeDiffCommentsOrEmpty } from './worktree-diff-comments-selector' -import { getIndexedWorktreeById } from './worktree-repo-index' +import { createDiffCommentViewSelector, sourceParts } from './diff-comment-owner' + +const TARGET = 'repo-9::/w/target' function makeComment(id: string): DiffComment { return { id, - worktreeId: 'worktree-99-99', + worktreeId: TARGET, filePath: 'src/index.ts', lineNumber: 1, body: 'Review note', @@ -23,64 +25,89 @@ function makeComment(id: string): DiffComment { } } -describe('selectWorktreeDiffComments', () => { - it('indexes one immutable worktree snapshot across retained editor selectors', () => { - let worktreeIdReads = 0 - const targetWorktreeId = 'worktree-99-99' - const comments = [makeComment('comment-1')] - const worktreesByRepo: AppState['worktreesByRepo'] = {} - - for (let repoIndex = 0; repoIndex < 100; repoIndex += 1) { - const repoId = `repo-${repoIndex}` - worktreesByRepo[repoId] = Array.from({ length: 100 }, (_, worktreeIndex) => { - const worktreeId = `worktree-${repoIndex}-${worktreeIndex}` - const worktree = { - repoId, - path: `/${repoId}/${worktreeId}`, - ...(worktreeId === targetWorktreeId ? { diffComments: comments } : {}) - } as Worktree - Object.defineProperty(worktree, 'id', { - enumerable: true, - get: () => { - worktreeIdReads += 1 - return worktreeId - } - }) - return worktree +/** Mounted note consumers re-run their selector on every store write; count row reads per write. */ +function measureViewSelectors(rowsPerRepo: number) { + let idReads = 0 + const comments = [makeComment('comment-1')] + const worktreesByRepo: AppState['worktreesByRepo'] = {} + for (let repoIndex = 0; repoIndex < 10; repoIndex += 1) { + const repoId = `repo-${repoIndex}` + worktreesByRepo[repoId] = Array.from({ length: rowsPerRepo }, (_, index) => { + const id = repoIndex === 9 && index === 0 ? TARGET : `${repoId}::/w/${index}` + const worktree = makeWorktree({ + id, + repoId, + path: id.slice(repoId.length + 2), + hostId: 'local', + ...(id === TARGET ? { diffComments: comments } : {}) }) - } - - for (let write = 0; write < 200; write += 1) { - // Model all seven comment selectors plus the rich-editor path selector. - expect(selectWorktreeDiffComments({ worktreesByRepo }, targetWorktreeId)).toBe(comments) - expect(selectWorktreeDiffComments({ worktreesByRepo }, targetWorktreeId)).toBe(comments) - expect(selectWorktreeDiffComments({ worktreesByRepo }, targetWorktreeId)).toBe(comments) - expect(selectWorktreeDiffComments({ worktreesByRepo }, targetWorktreeId)).toBe(comments) - expect(selectWorktreeDiffCommentsOrEmpty({ worktreesByRepo }, targetWorktreeId)).toBe( - comments - ) - expect(selectWorktreeDiffCommentsOrEmpty({ worktreesByRepo }, targetWorktreeId)).toBe( - comments - ) - expect(selectWorktreeDiffCommentsOrEmpty({ worktreesByRepo }, targetWorktreeId)).toBe( - comments - ) - expect(getIndexedWorktreeById(worktreesByRepo, targetWorktreeId)?.path).toBe( - '/repo-99/worktree-99-99' - ) - } - - expect(worktreeIdReads).toBe(10_000) + Object.defineProperty(worktree, 'id', { + enumerable: true, + get: () => { + idReads += 1 + return id + } + }) + return worktree + }) + } + const consumers = Array.from({ length: 8 }, () => createDiffCommentViewSelector()) + let state: Pick< + AppState, + 'worktreesByRepo' | 'activeWorktreeId' | 'activeWorkspaceExecutionHostId' + > = { worktreesByRepo, activeWorktreeId: TARGET, activeWorkspaceExecutionHostId: 'local' } + const views = consumers.map((select) => select(state, TARGET, ...sourceParts('selection'))) + expect(views[0].comments).toBe(comments) + expect(views[0].owner).toEqual({ + kind: 'worktree', + worktreeId: TARGET, + authority: { endpoint: { kind: 'self' }, at: 'local' } }) + idReads = 0 + for (let write = 0; write < 200; write += 1) { + state = { ...state } + consumers.forEach((select, index) => + expect(select(state, TARGET, ...sourceParts('selection'))).toBe(views[index]) + ) + } + const unrelatedWriteReads = idReads + + // Another repo's listing changes: every consumer re-resolves once, and keeps its view. + idReads = 0 + state = { ...state, worktreesByRepo: { ...worktreesByRepo, 'repo-0': [] } } + consumers.forEach((select, index) => + expect(select(state, TARGET, ...sourceParts('selection'))).toBe(views[index]) + ) + return { unrelatedWriteReads, catalogWriteReads: idReads } +} + +describe('note owner view selectors', () => { + it('do no row work on writes that change no ownership input, at any catalog size', () => { + const small = measureViewSelectors(100) + const large = measureViewSelectors(1000) + + expect(small.unrelatedWriteReads).toBe(0) + expect(large.unrelatedWriteReads).toBe(0) + // A listing change costs one pass per consumer over the open repo plus one shared index build. + expect(small.catalogWriteReads).toBeLessThanOrEqual(8 * 100 + 9 * 100) + expect(large.catalogWriteReads).toBeLessThanOrEqual(8 * 1000 + 9 * 1000) + }) +}) + +describe('selectWorktreeDiffComments', () => { it('reads a replacement worktree snapshot and handles an absent id', () => { const firstComments = [makeComment('comment-1')] const nextComments = [makeComment('comment-2')] - const first = { repo: [{ id: 'worktree-1', diffComments: firstComments } as Worktree] } - const next = { repo: [{ id: 'worktree-1', diffComments: nextComments } as Worktree] } + const first = { + 'repo-9': [makeWorktree({ id: TARGET, repoId: 'repo-9', diffComments: firstComments })] + } + const next = { + 'repo-9': [makeWorktree({ id: TARGET, repoId: 'repo-9', diffComments: nextComments })] + } - expect(selectWorktreeDiffComments({ worktreesByRepo: first }, 'worktree-1')).toBe(firstComments) - expect(selectWorktreeDiffComments({ worktreesByRepo: next }, 'worktree-1')).toBe(nextComments) + expect(selectWorktreeDiffComments({ worktreesByRepo: first }, TARGET)).toBe(firstComments) + expect(selectWorktreeDiffComments({ worktreesByRepo: next }, TARGET)).toBe(nextComments) expect(selectWorktreeDiffComments({ worktreesByRepo: next }, null)).toBeUndefined() expect(selectWorktreeDiffCommentsOrEmpty({ worktreesByRepo: next }, null)).toBe( selectWorktreeDiffCommentsOrEmpty({ worktreesByRepo: next }, undefined) diff --git a/src/renderer/src/store/worktree-diff-comments-selector.ts b/src/renderer/src/store/worktree-diff-comments-selector.ts index b22def88823..227d474ae38 100644 --- a/src/renderer/src/store/worktree-diff-comments-selector.ts +++ b/src/renderer/src/store/worktree-diff-comments-selector.ts @@ -1,189 +1,57 @@ import type { DiffComment } from '../../../shared/diff-comment-types' -import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { authorityKey, type HostAuthority } from '../../../shared/host-authority' import type { Worktree } from '../../../shared/worktree/types' import type { AppState } from './types' -import { getIndexedWorktreeById } from './worktree-repo-index' import { findFolderWorkspaceOwner } from '@/lib/folder-workspace-runtime-owner' -import { namedHostForOwnerRef } from '@/lib/resolve-owner' -import { findIndexedWorktreeOwnerForHost } from '@/lib/worktree-runtime-owner-index' +import { resolveRecordOwner, resolveSourceCopy } from '@/lib/workspace-copy-owner' +import { findIndexedWorktreeRows } from '@/lib/worktree-runtime-owner-index' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { selectWorktreesByRepo } from './workspace-record-selectors' const EMPTY_DIFF_COMMENTS = Object.freeze([]) as unknown as DiffComment[] +export { EMPTY_DIFF_COMMENTS } -type DiffCommentSelectorState = Pick & - Partial< - Pick< - AppState, - | 'activeWorkspaceExecutionHostId' - | 'activeWorktreeId' - | 'folderWorkspaces' - | 'projectGroups' - | 'restoredRuntimeHostIdByWorkspaceSessionKey' - | 'runtimeEnvironments' - | 'settings' - > - > +/** Every store field note ownership is resolved from; a write changing none of them changes no owner. */ +export const DIFF_COMMENT_OWNER_INPUTS = [ + 'worktreesByRepo', + 'detectedWorktreesByRepo', + 'repos', + 'folderWorkspaces', + 'projectGroups', + 'restoredRuntimeHostIdByWorkspaceSessionKey', + 'activeWorktreeId', + 'activeWorkspaceExecutionHostId', + 'settings', + 'runtimeEnvironments', + 'runtimeEnvironmentCatalogHydrated', + 'removedRuntimeEnvironmentIds' +] as const satisfies readonly (keyof AppState)[] -/** One twin of a worktree id, as the owner index tells rows apart: its host and its paired server. */ -export type DiffCommentTwin = { hostId?: ExecutionHostId; runtimeOwnerEnvironmentId?: string } +export type DiffCommentSelectorState = Pick & + Partial> -function twinOf(row: Pick): DiffCommentTwin { - const runtimeOwnerEnvironmentId = row.runtimeOwnerEnvironmentId?.trim() - return { - ...(row.hostId ? { hostId: row.hostId } : {}), - ...(runtimeOwnerEnvironmentId ? { runtimeOwnerEnvironmentId } : {}) - } -} - -function isTwin(row: Worktree, twin: DiffCommentTwin): boolean { - const own = twinOf(row) - return ( - own.hostId === twin.hostId && own.runtimeOwnerEnvironmentId === twin.runtimeOwnerEnvironmentId - ) -} - -/** The rows' identity (`twin`) and, whenever they name one, the host the write names. */ -export type DiffCommentRows = { - twin?: DiffCommentTwin - hostId?: ExecutionHostId - worktrees: readonly Worktree[] -} - -/** - * The host a twin's write names: a paired server's row goes through that server (rival servers - * may proxy the same SSH target), else the row's own stamp. - */ -export function diffCommentTwinHostId(twin: DiffCommentTwin): ExecutionHostId | undefined { - return twin.runtimeOwnerEnvironmentId - ? toRuntimeExecutionHostId(twin.runtimeOwnerEnvironmentId) - : twin.hostId -} - -/** Rollback bookkeeping key: one per twin, so a twin's floor never restores another copy. */ -export function diffCommentFloorKey(worktreeId: string, twin: DiffCommentTwin | undefined): string { - return twin - ? `${JSON.stringify([twin.hostId ?? null, twin.runtimeOwnerEnvironmentId ?? null])}\0${worktreeId}` - : worktreeId -} - -/** With host twins, pick captured write identity, then uniquely held note UUIDs, then selected host; never guess. Single-host duplicate rows still represent one workspace. */ -export function findDiffCommentRows( - state: Pick< - DiffCommentSelectorState, - 'worktreesByRepo' | 'activeWorktreeId' | 'activeWorkspaceExecutionHostId' - >, - worktreeId: string, - hint: { twin?: DiffCommentTwin; hostId?: ExecutionHostId; commentIds?: ReadonlySet } = {} -): DiffCommentRows | null { - const rows = (selectWorktreesByRepo(state)[getRepoIdFromWorktreeId(worktreeId)] ?? []).filter( - (row) => row.id === worktreeId - ) - const { twin: captured, commentIds } = hint - if (captured) { - const exact = rows.filter((row) => isTwin(row, captured)) - // Listings may add the write’s host stamp; hostless writes can follow a newly stamped row only if all copies agree. - const sole = rows.length > 0 && rows.every((row) => isTwin(row, twinOf(rows[0]))) - const stamped = - exact.length > 0 || captured.hostId - ? [] - : hint.hostId - ? rows.filter((row) => isTwin(row, { ...captured, hostId: hint.hostId })) - : sole && twinOf(rows[0]).runtimeOwnerEnvironmentId === captured.runtimeOwnerEnvironmentId - ? rows - : [] - const worktrees = exact.length > 0 ? exact : stamped - return worktrees.length > 0 ? { twin: captured, worktrees } : null - } - if (rows.length === 0) { - return null - } - const pickTwin = (row: Worktree | undefined, named?: ExecutionHostId): DiffCommentRows | null => { - if (!row) { - return null - } - const twin = twinOf(row) - // Selection attributes unstamped rows; notes alone cannot. Hostless writes would follow the currently open workspace. - const hostId = diffCommentTwinHostId(twin) ?? named - return hostId - ? { twin, hostId, worktrees: rows.filter((candidate) => isTwin(candidate, twin)) } - : null - } - if (rows.every((row) => isTwin(row, twinOf(rows[0])))) { - // Main refuses hostless writes amid twins; capture identity too so queued saves cannot switch to newly listed copies. - const twin = twinOf(rows[0]) - const hostId = diffCommentTwinHostId(twin) - // A differently stamped row is not the selected host’s unlisted copy; named notes still identify it, while unstamped provenance remains unknown. - const named = namedHostForOwnerRef(state, { workspaceId: worktreeId }) - const holdsNamedNotes = rows.some((row) => row.diffComments?.some((c) => commentIds?.has(c.id))) - const owner = named - ? findIndexedWorktreeOwnerForHost(selectWorktreesByRepo(state), worktreeId, named) - : null - if (named && twin.hostId && !holdsNamedNotes && !rows.some((row) => row === owner)) { - return null - } - return { twin, ...(hostId ? { hostId } : {}), worktrees: rows } - } - const holders = commentIds?.size - ? rows.filter((row) => row.diffComments?.some((comment) => commentIds.has(comment.id))) - : [] - if (holders.length > 0 && holders.every((row) => isTwin(row, twinOf(holders[0])))) { - return pickTwin(holders[0]) - } - const named = namedHostForOwnerRef(state, { workspaceId: worktreeId }) - const owner = named - ? findIndexedWorktreeOwnerForHost(selectWorktreesByRepo(state), worktreeId, named) - : null - return pickTwin( - rows.find((row) => row === owner), - named ?? undefined - ) -} - -/** The notes of those rows; the last duplicate wins, as in the id index the rest of the app reads. */ -export function diffCommentRowNotes(found: { - worktrees: readonly Worktree[] -}): DiffComment[] | undefined { - return found.worktrees.at(-1)?.diffComments -} - -/** Queued saves follow rows holding the chain’s last list despite new host stamps; after external replacement, resolve the captured twin (or bare ID when never twinned) again. */ -export function readQueuedDiffComments( - state: Pick< - DiffCommentSelectorState, - 'worktreesByRepo' | 'activeWorktreeId' | 'activeWorkspaceExecutionHostId' - >, - worktreeId: string, - chain: { twin?: DiffCommentTwin; hostId?: ExecutionHostId; latest: DiffComment[] | undefined } -): { list: DiffComment[] | undefined } | null { - const rows = selectWorktreesByRepo(state)[getRepoIdFromWorktreeId(worktreeId)] ?? [] - if ( - chain.latest && - rows.some((row) => row.id === worktreeId && row.diffComments === chain.latest) - ) { - return { list: chain.latest } - } - const found = findDiffCommentRows( - state, - worktreeId, - chain.twin ? { twin: chain.twin, hostId: chain.hostId } : {} - ) - return found ? { list: diffCommentRowNotes(found) } : null -} - -/** The list a change naming these notes would edit; see {@link findDiffCommentRows}. */ -export function readDiffCommentsForChange( +/** The listed rows of one copy (each resolved by the shared record rule); duplicates share notes, the last winning as in the id index. */ +export function findCopyRows( state: DiffCommentSelectorState, worktreeId: string, - commentIds: Iterable -): DiffComment[] { - const scope = parseWorkspaceKey(worktreeId) - if (scope?.type === 'folder') { - return findFolderWorkspaceOwner(state, scope.folderWorkspaceId)?.diffComments ?? [] - } - const found = findDiffCommentRows(state, worktreeId, { commentIds: new Set(commentIds) }) - return (found && diffCommentRowNotes(found)) ?? [] + authority: HostAuthority +): Worktree[] { + const key = authorityKey(authority) + const rows = findIndexedWorktreeRows( + selectWorktreesByRepo(state), + getRepoIdFromWorktreeId(worktreeId), + worktreeId + ) + return rows.filter((row) => { + const own = resolveRecordOwner(state, row) + return own.kind === 'resolved' && authorityKey(own.owner) === key + }) +} + +/** Notes of the copy's rows; undefined while it is not listed. */ +export function readCopyNotes(rows: readonly Worktree[]): DiffComment[] | undefined { + return rows.length > 0 ? (rows.at(-1)?.diffComments ?? EMPTY_DIFF_COMMENTS) : undefined } export function selectWorktreeDiffComments( @@ -197,13 +65,11 @@ export function selectWorktreeDiffComments( if (scope?.type === 'folder') { return findFolderWorkspaceOwner(state, scope.folderWorkspaceId)?.diffComments } - // Open twins need their own notes (unnamed writes refuse); scan only the open bucket per store write, using the cached ID index elsewhere. - const open = namedHostForOwnerRef(state, { workspaceId: worktreeId }) - ? findDiffCommentRows(state, worktreeId) - : null - return open - ? diffCommentRowNotes(open) - : getIndexedWorktreeById(selectWorktreesByRepo(state), worktreeId)?.diffComments + // Only an identifiable copy shows notes; another copy's notes would invite writes to it. + const copy = resolveSourceCopy(state, worktreeId, 'selection') + return copy.kind === 'resolved' + ? readCopyNotes(findCopyRows(state, worktreeId, copy.owner)) + : undefined } export function selectWorktreeDiffCommentsOrEmpty( diff --git a/tests/e2e/diff-note-delete.spec.ts b/tests/e2e/diff-note-delete.spec.ts index 058d0a63d5a..171492a899f 100644 --- a/tests/e2e/diff-note-delete.spec.ts +++ b/tests/e2e/diff-note-delete.spec.ts @@ -42,14 +42,22 @@ test.describe('Diff note delete', () => { if (!store) { throw new Error('window.__store is not available') } - const comment = await store.getState().addDiffComment({ - worktreeId: wId, - filePath: rel, - source: 'diff', - lineNumber: 1, - body: 'delete-me note', - side: 'modified' - }) + // The seeded worktree is this app's own (local) copy. + const comment = await store.getState().addDiffComment( + { + kind: 'worktree', + worktreeId: wId, + authority: { endpoint: { kind: 'self' }, at: 'local' } + }, + { + worktreeId: wId, + filePath: rel, + source: 'diff', + lineNumber: 1, + body: 'delete-me note', + side: 'modified' + } + ) return comment }, { wId: worktreeId, rel: relativePath } diff --git a/tests/e2e/diff-note-edit.spec.ts b/tests/e2e/diff-note-edit.spec.ts index 27e641c3ad2..b1998430631 100644 --- a/tests/e2e/diff-note-edit.spec.ts +++ b/tests/e2e/diff-note-edit.spec.ts @@ -41,14 +41,22 @@ test.describe('Diff note edit', () => { if (!store) { throw new Error('window.__store is not available') } - return store.getState().addDiffComment({ - worktreeId: wId, - filePath: rel, - source: 'diff', - lineNumber: 1, - body, - side: 'modified' - }) + // The seeded worktree is this app's own (local) copy. + return store.getState().addDiffComment( + { + kind: 'worktree', + worktreeId: wId, + authority: { endpoint: { kind: 'self' }, at: 'local' } + }, + { + worktreeId: wId, + filePath: rel, + source: 'diff', + lineNumber: 1, + body, + side: 'modified' + } + ) }, { wId: worktreeId, rel: relativePath, body: seededBody } ) diff --git a/tests/e2e/diff-note-layout.spec.ts b/tests/e2e/diff-note-layout.spec.ts index 703bdd5a455..de00facb6c3 100644 --- a/tests/e2e/diff-note-layout.spec.ts +++ b/tests/e2e/diff-note-layout.spec.ts @@ -81,14 +81,22 @@ test.describe('Diff note layout', () => { const added = await orcaPage.evaluate( ({ wId, filePath, lineNumber, body }) => - window.__store?.getState().addDiffComment({ - worktreeId: wId, - filePath, - source: 'diff', - lineNumber, - body, - side: 'modified' - }), + // The seeded worktree is this app's own (local) copy. + window.__store?.getState().addDiffComment( + { + kind: 'worktree', + worktreeId: wId, + authority: { endpoint: { kind: 'self' }, at: 'local' } + }, + { + worktreeId: wId, + filePath, + source: 'diff', + lineNumber, + body, + side: 'modified' + } + ), { wId: worktreeId, filePath: relativePath, lineNumber: NOTE_LINE, body: NOTE_BODY } ) expect(added, 'addDiffComment returned null').not.toBeNull()