mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Keep review note changes on the workspace copy they came from (#37204)
* Keep review note changes on their captured workspace owner * Keep review note actions on the copy whose notes are shown Review notes now read their owner and their notes together, so an action always changes the copy the user is looking at: - A paired SSH copy saves through its server even when its row does not name the server, instead of saving on this computer. - The Markdown preview shows and edits the selected copy's notes, not the first copy listed with the same workspace id. - While the selected copy is not listed yet, no other copy's notes are shown; a note started then saves to that copy once it lists. - A listing that stamps the same copy's host no longer looks like a new copy: a pending Send stays held and unsaved note edits are kept. - Clear all / Clear file confirmations stay on the copy they opened on when the selected host changes. - A copy removed since the user acted reports the existing save or clear failure once instead of failing silently. - Mounted note views skip ownership work on store updates that cannot change it, and do not re-render for another copy's changes. * Keep review notes on the exact workspace copy each surface shows Notes, their owner and every note action now come from one copy identity. Previews and editors of a server's copy read and save that copy, paired SSH copies keep working through their server, an SSH draft never lands on a local row, and controls stay disabled instead of claiming "All notes sent" while a copy's notes are unknown. Open Clear confirmations share the cached read, so unrelated store writes do no row work. * Resolve review-note copies through the shared workspace ownership rules Every listed row now gets its copy from the same rules the app routes writes with, including server provenance from detected listings and the SSH place behind a paired server for older rows without host stamps. Previews, editors and diffs read notes from their own tab's provenance instead of the selected copy, folders honor their source's host, and a note composer's shortcut captures the copy its surface shows when it opens. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Keep folder review notes on the folder copy their source names A folder's notes now come from the same source rules as worktree notes, so a file from this app never shows or saves to a server's folder with the same id. Queued folder saves and rollbacks check the captured folder copy the same way reads do, and resolving copies no longer rescans the project list for every row. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Read review-note copies through the shared id indexes Folder and worktree note views now read only their own workspace's catalog entries from the shared indexes, and readers of one folder share its qualification, so listing updates cost work proportional to what is shown rather than catalog size times readers. Also fixes the type errors and the end-to-end note seeds, which now pass the owner of the worktree they seed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Share review-note copy resolution across rows and readers Rows of one workspace on the same host now share a single ownership answer per catalog snapshot, so duplicate listings of an SSH worktree no longer make every note view rescan its peers. Folders that are not listed return one shared answer instead of leaving cache entries behind. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Name the catalog snapshots review-note ownership results are shared under Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Save renamed-file drafts under the new path and encode restored SSH targets A diff note draft opened before its file was renamed in place now saves under the file's current path, still on the copy it was opened on. A restored SSH file whose target id needs encoding now shows and saves its own copy's notes. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Update the diff note path ref after render instead of during it Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e5fd4afd0b
commit
e59b843336
@@ -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()
|
||||
})
|
||||
|
||||
@@ -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<DraftZoneEntry | null>(null)
|
||||
// Retain the only draft copy between card teardown and replacement.
|
||||
const pendingDraftRef = useRef<CarriedDraft | null>(null)
|
||||
const pendingDraftRef = useRef<CarriedDiffCommentDraft | null>(null)
|
||||
const previousModelIdentityRef = useRef(monacoModelIdentity)
|
||||
const reanchorFrameRef = useRef<number | null>(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<OpenDiffCommentDraft>(() => 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<RestoreDiffCommentDraft>((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<OpenDiffCommentDraft>(
|
||||
(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)
|
||||
}
|
||||
|
||||
@@ -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<boolean>
|
||||
// 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<DraftZoneEntry, 'draft' | 'body' | 'createComment'>
|
||||
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
|
||||
|
||||
@@ -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<boolean>) | undefined>
|
||||
clearDeliveredDiffComments: (
|
||||
worktreeId: string,
|
||||
owner: DiffCommentOwner,
|
||||
comments: readonly DiffCommentDeliverySnapshot[]
|
||||
) => Promise<boolean>
|
||||
}
|
||||
@@ -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 ? (
|
||||
<NotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={worktreeId}
|
||||
groupId={activeGroupId}
|
||||
modeIdParts={['diff-comment-note', worktreeId, filePath, comment.id]}
|
||||
@@ -116,7 +120,7 @@ export function renderDiffCommentZoneCard(
|
||||
'auto.components.diff.comments.diffCommentZoneCard.noteAlreadySent',
|
||||
'Note already sent'
|
||||
)}
|
||||
onDelivered={(notes) => void clearDeliveredDiffComments(worktreeId, notes)}
|
||||
onDelivered={(notes) => void (owner && clearDeliveredDiffComments(owner, notes))}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
|
||||
@@ -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<typeof RuntimeRpcClient>()),
|
||||
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(
|
||||
<>
|
||||
<Probe id={WT} name="open" />
|
||||
<Probe id={OTHER} name="other" />
|
||||
</>
|
||||
)
|
||||
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 = <T extends { id: string }>(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()
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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<T extends object>(
|
||||
worktreeId: string | null | undefined,
|
||||
source: WorkspaceCopySource
|
||||
) {
|
||||
const [target, setTarget] = useState<T | null>(null)
|
||||
const capturedOwner = useRef<DiffCommentOwner | null>(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<Dispatch<SetStateAction<T | null>>>((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
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -89,6 +89,7 @@ export function ChangesModeView({
|
||||
sideBySide={sideBySide}
|
||||
editable={true}
|
||||
worktreeId={activeFile.worktreeId}
|
||||
noteSource={activeFile}
|
||||
onContentChange={onContentChange}
|
||||
onSave={onSave}
|
||||
/>
|
||||
|
||||
@@ -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 (
|
||||
<NotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={worktreeId}
|
||||
groupId={groupId}
|
||||
modeIdParts={['diff-notes', worktreeId, groupId, filePath ?? 'all']}
|
||||
@@ -97,7 +102,7 @@ export function DiffNotesSendMenu({
|
||||
openRequestNonce={openRequestNonce}
|
||||
openRequestExpiresAt={openRequestExpiresAt}
|
||||
onOpenRequestHandled={handleOpenRequestHandled}
|
||||
onDelivered={(notes) => void clearDeliveredDiffComments(worktreeId, notes)}
|
||||
onDelivered={(notes) => void (owner && clearDeliveredDiffComments(owner, notes))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<boolean> => {
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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: <T,>(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) => (
|
||||
<DiffNavigationProvider>
|
||||
<DiffViewer
|
||||
modelKey="rename"
|
||||
originalContent="original"
|
||||
modifiedContent="modified"
|
||||
language="typescript"
|
||||
filePath={`/work/${relativePath}`}
|
||||
relativePath={relativePath}
|
||||
sideBySide
|
||||
worktreeId="wt"
|
||||
/>
|
||||
</DiffNavigationProvider>
|
||||
)
|
||||
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 }
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -246,6 +246,7 @@ export function EditorEditFileSurface({
|
||||
key={monacoRemountKey}
|
||||
fileId={activeFile.id}
|
||||
filePath={activeFile.filePath}
|
||||
noteSource={activeFile}
|
||||
viewStateKey={editorViewStateKey}
|
||||
viewStateId={viewStateScopeId}
|
||||
relativePath={activeFile.relativePath}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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', () => ({
|
||||
|
||||
@@ -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 && (
|
||||
<DiffNotesSendMenu
|
||||
owner={commentOwner}
|
||||
worktreeId={activeFile.worktreeId}
|
||||
groupId={activeGroupId ?? activeFile.worktreeId}
|
||||
comments={diffComments}
|
||||
|
||||
@@ -16,7 +16,10 @@ const state = {
|
||||
updateDiffComment: vi.fn(),
|
||||
clearDeliveredDiffComments: vi.fn(),
|
||||
keybindings: {},
|
||||
worktreesByRepo: {},
|
||||
// The source copy is listed, so its notes are known and blocks offer Add note.
|
||||
worktreesByRepo: {
|
||||
fixture: [{ id: 'fixture', repoId: 'fixture', path: '/fixture', diffComments: [] }]
|
||||
},
|
||||
repos: [],
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import { ImeTextarea } from '@/lib/ime-text-field'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { CornerDownLeft } from 'lucide-react'
|
||||
@@ -9,6 +10,7 @@ import { installOpenDraftAddReviewNoteGuard } from './editor-shortcuts'
|
||||
import { NotesSendMenu } from './NotesSendMenu'
|
||||
|
||||
export function MarkdownPreviewSingleNoteSendMenu({
|
||||
owner,
|
||||
worktreeId,
|
||||
filePath,
|
||||
content,
|
||||
@@ -16,6 +18,7 @@ export function MarkdownPreviewSingleNoteSendMenu({
|
||||
modeSlot,
|
||||
onDelivered
|
||||
}: {
|
||||
owner: DiffCommentOwner | null
|
||||
worktreeId: string
|
||||
filePath: string
|
||||
content: string
|
||||
@@ -25,6 +28,7 @@ export function MarkdownPreviewSingleNoteSendMenu({
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<NotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={worktreeId}
|
||||
groupId={worktreeId}
|
||||
modeIdParts={['markdown-notes', worktreeId, filePath, modeSlot, note.id]}
|
||||
|
||||
@@ -16,6 +16,8 @@ export function MarkdownPreviewReviewToolbar({
|
||||
const {
|
||||
markdownReviewNotes,
|
||||
reviewNotesCopied,
|
||||
commentOwner,
|
||||
notesKnown,
|
||||
sourceWorktree,
|
||||
unsentMarkdownReviewScope,
|
||||
clearDeliveredDiffComments
|
||||
@@ -67,12 +69,16 @@ export function MarkdownPreviewReviewToolbar({
|
||||
</button>
|
||||
{sourceWorktree ? (
|
||||
<NotesSendMenu
|
||||
// Until the shown copy is listed its notes are unknown, not all sent.
|
||||
owner={notesKnown ? commentOwner : null}
|
||||
worktreeId={sourceWorktree.id}
|
||||
groupId={sourceWorktree.id}
|
||||
modeIdParts={['markdown-notes', sourceWorktree.id, filePath, 'preview-toolbar']}
|
||||
scopes={unsentMarkdownReviewScope}
|
||||
triggerClassName="markdown-review-icon-button"
|
||||
onDelivered={(notes) => void clearDeliveredDiffComments(sourceWorktree.id, notes)}
|
||||
onDelivered={(notes) =>
|
||||
void (commentOwner && clearDeliveredDiffComments(commentOwner, notes))
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -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
|
||||
})
|
||||
|
||||
|
||||
@@ -234,6 +234,11 @@ function renderMenu(
|
||||
hookRuntime.index = 0
|
||||
return expand(
|
||||
<NotesSendMenu<TestNote>
|
||||
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 })
|
||||
|
||||
@@ -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<TNote> = Omit<NotesSendMenuScope<TNote>, 'formatPrompt'>
|
||||
}
|
||||
|
||||
export type NotesSendMenuProps<TNote> = {
|
||||
/** 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<TNote extends DiffCommentDeliverySnapshot>({
|
||||
owner,
|
||||
worktreeId,
|
||||
groupId,
|
||||
modeIdParts,
|
||||
@@ -99,10 +103,12 @@ export function NotesSendMenu<TNote extends DiffCommentDeliverySnapshot>({
|
||||
const sendableScopes = useMemo<SendableNotesScope<TNote>[]>(() => {
|
||||
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<TNote extends DiffCommentDeliverySnapshot>({
|
||||
}, [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<TNote extends DiffCommentDeliverySnapshot>({
|
||||
)
|
||||
const holdInFlight = useCallback(
|
||||
(notes: readonly TNote[]) => (delivered: Promise<unknown>) =>
|
||||
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<TNote extends DiffCommentDeliverySnapshot>({
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" sideOffset={6}>
|
||||
{hasDeliverableNotes ? enabledSendTooltip() : disabledTitle}
|
||||
</TooltipContent>
|
||||
{hasDeliverableNotes || disabledTitle ? (
|
||||
<TooltipContent side="bottom" sideOffset={6}>
|
||||
{hasDeliverableNotes ? enabledSendTooltip() : disabledTitle}
|
||||
</TooltipContent>
|
||||
) : null}
|
||||
</Tooltip>
|
||||
<DropdownMenuContent
|
||||
align={align}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useDiffCommentView } from '../diff-comments/use-diff-comment-owner'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useFileOwnerRuntimeTarget } from '@/runtime/use-worktree-runtime-target'
|
||||
import { useEditorState, type Editor } from '@tiptap/react'
|
||||
import type { DiffComment } from '../../../../shared/diff-comment-types'
|
||||
import { useAppStore } from '@/store'
|
||||
import { selectWorktreeDiffComments } from '@/store/worktree-diff-comments-selector'
|
||||
import { useLocalImagePick } from './useLocalImagePick'
|
||||
import { useRichMarkdownSearch } from './useRichMarkdownSearch'
|
||||
import type { LinkBubbleState } from './RichMarkdownLinkBubble'
|
||||
@@ -42,6 +41,7 @@ export default function RichMarkdownEditor({
|
||||
worktreeId,
|
||||
externalSshTargetId,
|
||||
runtimeEnvironmentId,
|
||||
operationProvenance,
|
||||
scrollCacheKey,
|
||||
onContentChange,
|
||||
onDirtyStateHint,
|
||||
@@ -63,13 +63,16 @@ export default function RichMarkdownEditor({
|
||||
const runtimeTarget = useFileOwnerRuntimeTarget(worktreeId, runtimeEnvironmentId)
|
||||
const editorFontZoomLevel = useAppStore((s) => 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 (
|
||||
<RichMarkdownEditorSurface
|
||||
commentOwner={commentOwner}
|
||||
editor={editor}
|
||||
editorFontZoomLevel={editorFontZoomLevel}
|
||||
rootElement={rootRef.current}
|
||||
@@ -396,11 +402,15 @@ export default function RichMarkdownEditor({
|
||||
onCopyReviewNotes={() => 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}
|
||||
|
||||
@@ -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({
|
||||
<RichMarkdownTableControls editor={editor} scrollContainerRef={scrollContainerRef} />
|
||||
{reviewRailVisible && notePositions.length > 0 ? (
|
||||
<RichMarkdownReviewNoteLayer
|
||||
owner={commentOwner}
|
||||
positions={notePositions}
|
||||
activeCommentId={activeReviewCommentId}
|
||||
attentionCommentId={attentionReviewCommentId}
|
||||
@@ -329,6 +333,7 @@ export function RichMarkdownEditorSurface({
|
||||
/>
|
||||
{markdownCommentsCount > 0 ? (
|
||||
<RichMarkdownReviewRailActions
|
||||
owner={commentOwner}
|
||||
worktreeId={worktreeId}
|
||||
filePath={filePath}
|
||||
noteCount={markdownCommentsCount}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { diffCommentOwnerKey, type DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import type { DiffComment } from '../../../../shared/diff-comment-types'
|
||||
import { DiffCommentCard } from '../diff-comments/DiffCommentCard'
|
||||
@@ -23,6 +24,7 @@ type RichMarkdownReviewNoteLayerProps = {
|
||||
attentionCommentId: string | null
|
||||
copiedCommentId: string | null
|
||||
markdownReviewContent: string
|
||||
owner: DiffCommentOwner | null
|
||||
worktreeId: string
|
||||
filePath: string
|
||||
onCopyNote: (note: MarkdownReviewNote) => 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 }) => (
|
||||
<div
|
||||
key={comment.id}
|
||||
key={`${owner ? diffCommentOwnerKey(owner) : ''}:${comment.id}`}
|
||||
data-rich-markdown-review-note-id={comment.id}
|
||||
className={`rich-markdown-review-note-card ${
|
||||
activeCommentId === comment.id ? 'is-active' : ''
|
||||
@@ -123,6 +126,7 @@ export function RichMarkdownReviewNoteLayer({
|
||||
)}
|
||||
</button>
|
||||
<NotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={worktreeId}
|
||||
groupId={worktreeId}
|
||||
modeIdParts={['markdown-notes', worktreeId, filePath, 'note', comment.id]}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import { Check, Copy, MessageSquare } from 'lucide-react'
|
||||
import { NotesSendMenu, type NotesSendMenuScope } from './NotesSendMenu'
|
||||
import type { MarkdownReviewNote } from '@/lib/markdown-review-notes'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
type RichMarkdownReviewRailActionsProps = {
|
||||
owner: DiffCommentOwner | null
|
||||
worktreeId: string
|
||||
filePath: string
|
||||
noteCount: number
|
||||
@@ -16,6 +18,7 @@ type RichMarkdownReviewRailActionsProps = {
|
||||
}
|
||||
|
||||
export function RichMarkdownReviewRailActions({
|
||||
owner,
|
||||
worktreeId,
|
||||
filePath,
|
||||
noteCount,
|
||||
@@ -89,6 +92,7 @@ export function RichMarkdownReviewRailActions({
|
||||
{notesCopied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
|
||||
</button>
|
||||
<NotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={worktreeId}
|
||||
groupId={worktreeId}
|
||||
modeIdParts={['markdown-notes', worktreeId, filePath, 'rail']}
|
||||
|
||||
@@ -68,8 +68,8 @@ export default function CombinedDiffViewer({
|
||||
const openBranchAllDiffs = useAppStore((s) => 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({
|
||||
<CombinedDiffSectionList
|
||||
activeGroupId={activeGroupId}
|
||||
canOpenWorkspaceFileBrowserForPath={canOpenWorkspaceFileBrowserForPath}
|
||||
diffCommentsForWorktree={diffCommentsForWorktree}
|
||||
commentOwner={notesView.owner}
|
||||
diffCommentsForWorktree={notesView.comments}
|
||||
file={file}
|
||||
handleSectionSaveRef={handleSectionSaveRef}
|
||||
isAllMode={entrySet.isAllMode}
|
||||
@@ -406,7 +408,7 @@ export default function CombinedDiffViewer({
|
||||
</div>
|
||||
</div>
|
||||
<ClearDiffNotesDialog
|
||||
diffCommentCount={notes.diffCommentCount}
|
||||
diffCommentCount={notes.clearNotesCount}
|
||||
isClearingNotes={notes.isClearingNotes}
|
||||
onConfirm={() => void notes.handleConfirmClearNotes()}
|
||||
open={notes.clearNotesDialogVisible}
|
||||
|
||||
+4
@@ -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<OpenFile['branchCompare']> | null
|
||||
commitCompare: NonNullable<OpenFile['commitCompare']> | null
|
||||
commentOwner: DiffCommentOwner | null
|
||||
diffCommentCount: number
|
||||
diffCommentsForWorktree: DiffComment[]
|
||||
diffShowWhitespace: boolean | undefined
|
||||
@@ -152,6 +155,7 @@ export function CombinedDiffToolbar({
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<DiffNotesSendMenu
|
||||
owner={commentOwner}
|
||||
worktreeId={file.worktreeId}
|
||||
groupId={activeGroupId ?? file.worktreeId}
|
||||
comments={diffCommentsForWorktree}
|
||||
|
||||
+50
-11
@@ -1,11 +1,15 @@
|
||||
import type { AppState } from '@/store'
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import { useOwnedDiffComments } from '@/components/diff-comments/use-diff-comment-owner'
|
||||
import { withoutMarkdownReviewNotes } from '@/lib/markdown-review-notes-setting'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { formatDiffComments } from '@/lib/diff-comments-format'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { DiffComment } from '../../../../../../shared/diff-comment-types'
|
||||
import type { DiffCommentsClearOptions } from '@/store/slices/diffComments'
|
||||
|
||||
export type CombinedDiffNotesActions = {
|
||||
clearNotesCount: number
|
||||
clearNotesDialogVisible: boolean
|
||||
diffCommentCount: number
|
||||
handleConfirmClearNotes: () => Promise<void>
|
||||
@@ -18,15 +22,15 @@ export type CombinedDiffNotesActions = {
|
||||
}
|
||||
|
||||
export function useCombinedDiffNotesActions({
|
||||
owner,
|
||||
clearDiffComments,
|
||||
diffCommentsForWorktree,
|
||||
markdownReviewNotesEnabled,
|
||||
worktreeId
|
||||
markdownReviewNotesEnabled
|
||||
}: {
|
||||
clearDiffComments: (worktreeId: string, options?: DiffCommentsClearOptions) => Promise<boolean>
|
||||
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<React.SetStateAction<boolean>> = 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<void> => {
|
||||
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,
|
||||
|
||||
+5
@@ -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 ? (
|
||||
<DiffNotesSendMenu
|
||||
owner={commentOwner}
|
||||
worktreeId={file.worktreeId}
|
||||
groupId={activeGroupId ?? file.worktreeId}
|
||||
comments={diffCommentsForWorktree}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { AppState } from '@/store'
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import type { DiffSection } from './diff-section-types'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
@@ -7,17 +9,8 @@ type DiffSectionCommentTarget = {
|
||||
startLine?: number
|
||||
}
|
||||
|
||||
type AddDiffComment = (args: {
|
||||
worktreeId: string
|
||||
filePath: string
|
||||
source: 'diff'
|
||||
startLine?: number
|
||||
lineNumber: number
|
||||
body: string
|
||||
side: 'modified'
|
||||
}) => Promise<unknown>
|
||||
|
||||
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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<boolean> => {
|
||||
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({
|
||||
</button>
|
||||
{activeAnnotationBlockKey === blockKey ? (
|
||||
<MarkdownPreviewAnnotationComposer
|
||||
key={diffCommentOwnerKey(commentOwner)}
|
||||
lineNumber={range.endLine}
|
||||
startLine={range.startLine === range.endLine ? undefined : range.startLine}
|
||||
onCancel={() => setActiveAnnotationBlockKey(null)}
|
||||
@@ -114,7 +122,7 @@ export function useMarkdownPreviewAnnotationRenderers({
|
||||
<div className="markdown-annotation-note-stack">
|
||||
{commentsForBlock.map((comment) => (
|
||||
<div
|
||||
key={comment.id}
|
||||
key={`${diffCommentOwnerKey(commentOwner)}:${comment.id}`}
|
||||
data-markdown-review-note-id={comment.id}
|
||||
className={`markdown-annotation-card ${
|
||||
activeReviewCommentId === comment.id ? 'is-active' : ''
|
||||
@@ -131,8 +139,14 @@ export function useMarkdownPreviewAnnotationRenderers({
|
||||
}
|
||||
body={comment.body}
|
||||
sentAt={comment.sentAt}
|
||||
onDelete={() => 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={
|
||||
<>
|
||||
<button
|
||||
@@ -173,13 +187,14 @@ export function useMarkdownPreviewAnnotationRenderers({
|
||||
)}
|
||||
</button>
|
||||
<MarkdownPreviewSingleNoteSendMenu
|
||||
owner={commentOwner}
|
||||
worktreeId={sourceWorktree.id}
|
||||
filePath={filePath}
|
||||
content={renderedContent}
|
||||
note={comment as MarkdownReviewNote}
|
||||
modeSlot="preview-inline"
|
||||
onDelivered={(notes) =>
|
||||
void clearDeliveredDiffComments(sourceWorktree.id, notes)
|
||||
void (commentOwner && clearDeliveredDiffComments(commentOwner, notes))
|
||||
}
|
||||
/>
|
||||
</>
|
||||
@@ -207,6 +222,7 @@ export function useMarkdownPreviewAnnotationRenderers({
|
||||
renderedContent,
|
||||
setActiveAnnotationBlockKey,
|
||||
sourceRelativePath,
|
||||
commentOwner,
|
||||
sourceWorktree,
|
||||
updateDiffComment
|
||||
]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useDiffCommentView } from '../diff-comments/use-diff-comment-owner'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createConnectionIdForFileSelector } from '@/lib/connection-owner-resolution'
|
||||
import { computeEditorFontSize } from '@/lib/editor-font-zoom'
|
||||
@@ -83,7 +84,12 @@ export function useMarkdownPreviewSourceFoundation({
|
||||
resolvedSourceWorktreeId,
|
||||
filePath
|
||||
)
|
||||
const allDiffComments = sourceWorktree?.diffComments
|
||||
// Notes and their owner come from the copy this preview's content does: its source tab's own
|
||||
// provenance and host. The row lookup above only supplies the id and path every copy shares.
|
||||
const { owner: commentOwner, comments: allDiffComments } = useDiffCommentView(
|
||||
sourceWorktree?.id,
|
||||
sourceOpenFile ?? { runtimeEnvironmentId: resolvedSourceRuntimeEnvironmentId }
|
||||
)
|
||||
const sourceRoutingWorktreeId = sourceWorktree?.id ?? resolvedSourceWorktreeId
|
||||
const runtimeOwnerId = resolvedSourceRuntimeEnvironmentId?.trim()
|
||||
const sourceConnectionIdSelector = useMemo(
|
||||
@@ -195,6 +201,8 @@ export function useMarkdownPreviewSourceFoundation({
|
||||
clearDeliveredDiffComments,
|
||||
keybindings,
|
||||
worktreesByRepo,
|
||||
commentOwner,
|
||||
notesKnown: allDiffComments !== undefined,
|
||||
sourceWorktree,
|
||||
sourceRoutingWorktreeId,
|
||||
sourceConnectionId,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
useDiffCommentView,
|
||||
useOwnedDiffCommentTarget
|
||||
} from '../diff-comments/use-diff-comment-owner'
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -10,8 +14,10 @@ import {
|
||||
} from 'react'
|
||||
import type { editor } from 'monaco-editor'
|
||||
import type { DiffComment } from '../../../../shared/diff-comment-types'
|
||||
import type { WorkspaceResource } from '@/lib/workspace-copy-owner'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { useAppStore } from '@/store'
|
||||
import { selectWorktreeDiffComments } from '@/store/worktree-diff-comments-selector'
|
||||
import { isMarkdownComment } from '@/lib/diff-comment-compat'
|
||||
import { formatMarkdownReviewNotes, type MarkdownReviewNote } from '@/lib/markdown-review-notes'
|
||||
import { useDiffCommentDecorator } from '../diff-comments/useDiffCommentDecorator'
|
||||
@@ -51,6 +57,7 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
content: string
|
||||
language: string
|
||||
worktreeId: string | undefined
|
||||
noteSource: WorkspaceResource
|
||||
markdownAnnotationsEnabled: boolean
|
||||
}): MonacoMarkdownAnnotations {
|
||||
const {
|
||||
@@ -60,17 +67,19 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
content,
|
||||
language,
|
||||
worktreeId,
|
||||
noteSource,
|
||||
markdownAnnotationsEnabled
|
||||
} = params
|
||||
|
||||
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)
|
||||
const allDiffComments = useAppStore((s): DiffComment[] | undefined =>
|
||||
selectWorktreeDiffComments(s, worktreeId)
|
||||
)
|
||||
|
||||
const markdownComments = useMemo(
|
||||
() =>
|
||||
@@ -78,7 +87,8 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
[allDiffComments, relativePath]
|
||||
)
|
||||
|
||||
const [commentPopover, setCommentPopover] = useState<MarkdownCommentPopoverState | null>(null)
|
||||
const [commentPopover, setCommentPopover, commentPopoverOwnerRef] =
|
||||
useOwnedDiffCommentTarget<MarkdownCommentPopoverState>(worktreeId, noteSource)
|
||||
const [selectionAnnotationTarget, setSelectionAnnotationTarget] =
|
||||
useState<MonacoMarkdownSelectionAnnotationTarget | null>(null)
|
||||
// Why: claim drafts synchronously so a same-tick second chord can't remount the composer before React commits state.
|
||||
@@ -88,7 +98,7 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
}, [commentPopover])
|
||||
|
||||
const shouldShowMarkdownAnnotations =
|
||||
markdownAnnotationsEnabled && language === 'markdown' && Boolean(worktreeId)
|
||||
markdownAnnotationsEnabled && language === 'markdown' && Boolean(worktreeId && commentOwner)
|
||||
// Why: the mount closure installs keydown listeners once, so the shortcut reads current enablement through a ref.
|
||||
const shouldShowMarkdownAnnotationsRef = useRef(shouldShowMarkdownAnnotations)
|
||||
useEffect(() => {
|
||||
@@ -109,6 +119,7 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
)
|
||||
|
||||
useDiffCommentDecorator({
|
||||
commentOwner,
|
||||
editor: shouldShowMarkdownAnnotations ? mountedEditor : null,
|
||||
filePath: relativePath,
|
||||
worktreeId: worktreeId ?? '',
|
||||
@@ -127,10 +138,13 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
},
|
||||
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,
|
||||
formatCommentPrompt: formatMarkdownCommentPrompt,
|
||||
pendingScrollCommentId: pendingScrollForThisEditor,
|
||||
onPendingScrollConsumed: () => setScrollToDiffCommentId(null)
|
||||
@@ -157,7 +171,7 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
contentSub.dispose()
|
||||
layoutSub.dispose()
|
||||
}
|
||||
}, [mountedEditor, popoverLineNumber, editorContainerRef])
|
||||
}, [mountedEditor, popoverLineNumber, editorContainerRef, setCommentPopover])
|
||||
|
||||
useEffect(() => {
|
||||
if (!mountedEditor || !shouldShowMarkdownAnnotations || commentPopover) {
|
||||
@@ -189,20 +203,26 @@ export function useMonacoMarkdownAnnotations(params: {
|
||||
if (!commentPopover || !worktreeId) {
|
||||
return
|
||||
}
|
||||
const result = await addDiffComment({
|
||||
worktreeId,
|
||||
filePath: relativePath,
|
||||
source: 'markdown',
|
||||
startLine: commentPopover.startLine,
|
||||
lineNumber: commentPopover.lineNumber,
|
||||
selectedText: commentPopover.selectedText,
|
||||
body,
|
||||
side: 'modified'
|
||||
})
|
||||
const owner = commentPopoverOwnerRef.current
|
||||
const result = await (owner
|
||||
? addDiffComment(owner, {
|
||||
worktreeId,
|
||||
filePath: relativePath,
|
||||
source: 'markdown',
|
||||
startLine: commentPopover.startLine,
|
||||
lineNumber: commentPopover.lineNumber,
|
||||
selectedText: commentPopover.selectedText,
|
||||
body,
|
||||
side: 'modified'
|
||||
})
|
||||
: null)
|
||||
if (result) {
|
||||
setCommentPopover(null)
|
||||
} else {
|
||||
console.error('Failed to add markdown comment — draft preserved')
|
||||
// The draft stays open for retry.
|
||||
toast.error(
|
||||
translate('auto.components.editor.diffCommentSaveFailed', 'Failed to save comment')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ describe('useRichMarkdownReviewController openAnnotationPopover draft guard', ()
|
||||
markdownAnnotationsEnabled: true,
|
||||
markdownReviewContent: 'abc',
|
||||
markdownSourceLineOffset: 0,
|
||||
noteSource: {},
|
||||
rootRef,
|
||||
scrollContainerRef,
|
||||
worktreeId: 'wt-1',
|
||||
|
||||
+22
-2
@@ -2,7 +2,9 @@
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { Editor } from '@tiptap/react'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures'
|
||||
import type { DiffComment } from '../../../../shared/diff-comment-types'
|
||||
import {
|
||||
createRichMarkdownAnnotationHighlightExtension,
|
||||
@@ -67,7 +69,9 @@ function mountReview() {
|
||||
const editorRef: { current: Editor | null } = { current: editor }
|
||||
const rootRef: { current: HTMLDivElement | null } = { current: document.createElement('div') }
|
||||
const pending = Promise.withResolvers<DiffComment | null>()
|
||||
const addDiffComment = vi.fn((_input: Omit<DiffComment, 'id' | 'createdAt'>) => pending.promise)
|
||||
const addDiffComment = vi.fn(
|
||||
(_owner: unknown, _input: Omit<DiffComment, 'id' | 'createdAt'>) => pending.promise
|
||||
)
|
||||
let comments: DiffComment[] = []
|
||||
const hook = renderHook(() =>
|
||||
useRichMarkdownReviewController({
|
||||
@@ -79,6 +83,7 @@ function mountReview() {
|
||||
markdownAnnotationsEnabled: true,
|
||||
markdownReviewContent: 'abc xyz',
|
||||
markdownSourceLineOffset: 0,
|
||||
noteSource: {},
|
||||
rootRef,
|
||||
scrollContainerRef: { current: document.createElement('div') },
|
||||
worktreeId: 'folder-owner',
|
||||
@@ -98,7 +103,21 @@ function mountReview() {
|
||||
}
|
||||
}
|
||||
|
||||
const initialState = useAppStore.getState()
|
||||
|
||||
beforeEach(() => {
|
||||
// The draft captures the listed copy it opens on.
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: {
|
||||
'folder-owner': [
|
||||
makeWorktree({ id: 'folder-owner', repoId: 'folder-owner', path: '/workspace' })
|
||||
]
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAppStore.setState(initialState, true)
|
||||
cleanup()
|
||||
for (const editor of editors.splice(0)) {
|
||||
editor.destroy()
|
||||
@@ -115,6 +134,7 @@ describe('review submission owner', () => {
|
||||
review.pending.resolve(saved)
|
||||
await submission
|
||||
})
|
||||
expect(review.addDiffComment).toHaveBeenCalledOnce()
|
||||
expect(review.result.current.annotationPopover).toEqual(nextTarget)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useOwnedDiffCommentTarget } from '../diff-comments/use-diff-comment-owner'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { MutableRefObject } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import type { AppState } from '@/store'
|
||||
import { richMarkdownAnnotationHighlightPluginKey } from './rich-markdown-annotation-highlight'
|
||||
@@ -16,6 +19,7 @@ import { useRichMarkdownReviewData } from './useRichMarkdownReviewData'
|
||||
import { useRichMarkdownReviewCopyFeedback } from './useRichMarkdownReviewCopyFeedback'
|
||||
import { useRichMarkdownReviewRailController } from './useRichMarkdownReviewRailController'
|
||||
import type { DiffComment } from '../../../../shared/diff-comment-types'
|
||||
import type { WorkspaceResource } from '@/lib/workspace-copy-owner'
|
||||
|
||||
type UseRichMarkdownReviewControllerOptions = {
|
||||
addDiffComment: AppState['addDiffComment']
|
||||
@@ -29,6 +33,7 @@ type UseRichMarkdownReviewControllerOptions = {
|
||||
markdownSourceLineOffset: number
|
||||
rootRef: MutableRefObject<HTMLDivElement | null>
|
||||
scrollContainerRef: MutableRefObject<HTMLDivElement | null>
|
||||
noteSource: WorkspaceResource
|
||||
worktreeId: string
|
||||
worktreeRoot: string | null
|
||||
}
|
||||
@@ -45,15 +50,15 @@ export function useRichMarkdownReviewController({
|
||||
markdownSourceLineOffset,
|
||||
rootRef,
|
||||
scrollContainerRef,
|
||||
noteSource,
|
||||
worktreeId,
|
||||
worktreeRoot
|
||||
}: UseRichMarkdownReviewControllerOptions) {
|
||||
const [annotationTarget, setAnnotationTarget] = useState<RichMarkdownAnnotationTarget | null>(
|
||||
null
|
||||
)
|
||||
const [annotationPopover, setAnnotationPopover] = useState<RichMarkdownAnnotationTarget | null>(
|
||||
null
|
||||
)
|
||||
const [annotationPopover, setAnnotationPopover, annotationOwnerRef] =
|
||||
useOwnedDiffCommentTarget<RichMarkdownAnnotationTarget>(worktreeId, noteSource)
|
||||
const annotationPopoverRef = useRef<RichMarkdownAnnotationTarget | null>(null)
|
||||
const canAnnotateRichMarkdownRef = useRef(false)
|
||||
const markdownCommentsRef = useRef<DiffComment[]>([])
|
||||
@@ -164,7 +169,11 @@ export function useRichMarkdownReviewController({
|
||||
return
|
||||
}
|
||||
const submittedEditor = editorRef.current
|
||||
const result = await addDiffComment({
|
||||
const owner = annotationOwnerRef.current
|
||||
if (!owner) {
|
||||
return
|
||||
}
|
||||
const result = await addDiffComment(owner, {
|
||||
worktreeId,
|
||||
filePath: sourceRelativePath,
|
||||
source: 'markdown',
|
||||
@@ -178,7 +187,10 @@ export function useRichMarkdownReviewController({
|
||||
side: 'modified'
|
||||
})
|
||||
if (!result) {
|
||||
console.error('Failed to add markdown comment — draft preserved')
|
||||
// The draft stays open for retry.
|
||||
toast.error(
|
||||
translate('auto.components.editor.diffCommentSaveFailed', 'Failed to save comment')
|
||||
)
|
||||
return
|
||||
}
|
||||
if (
|
||||
@@ -203,11 +215,13 @@ export function useRichMarkdownReviewController({
|
||||
},
|
||||
[
|
||||
addDiffComment,
|
||||
annotationOwnerRef,
|
||||
annotationPopover,
|
||||
clearAnnotationHighlight,
|
||||
editorRef,
|
||||
markdownSourceLineOffset,
|
||||
sourceRelativePath,
|
||||
setAnnotationPopover,
|
||||
worktreeId
|
||||
]
|
||||
)
|
||||
@@ -262,6 +276,7 @@ export function useRichMarkdownReviewController({
|
||||
markdownComments,
|
||||
markdownSourceLineOffset,
|
||||
rootRef,
|
||||
setAnnotationPopover,
|
||||
setReviewRailOpen
|
||||
]
|
||||
)
|
||||
@@ -276,7 +291,7 @@ export function useRichMarkdownReviewController({
|
||||
// oxlint-disable-next-line react-doctor/no-adjust-state-on-prop-change
|
||||
setAnnotationPopover(null)
|
||||
clearAllAnnotationHighlights()
|
||||
}, [canAnnotateRichMarkdown, clearAllAnnotationHighlights])
|
||||
}, [canAnnotateRichMarkdown, clearAllAnnotationHighlights, setAnnotationPopover])
|
||||
|
||||
return {
|
||||
...copyFeedback,
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import {
|
||||
resolvePendingDiffCommentsClear,
|
||||
type PendingDiffCommentsClear
|
||||
} from './source-control/notes/diff-comments-clear-dialog-state'
|
||||
|
||||
const allPending: PendingDiffCommentsClear = { kind: 'all', worktreeId: 'wt-1' }
|
||||
const owner: DiffCommentOwner = {
|
||||
kind: 'worktree',
|
||||
worktreeId: 'wt-1',
|
||||
authority: { endpoint: { kind: 'self' }, at: 'local' }
|
||||
}
|
||||
const allPending: PendingDiffCommentsClear = { kind: 'all', worktreeId: 'wt-1', owner, count: 1 }
|
||||
const filePending: PendingDiffCommentsClear = {
|
||||
kind: 'file',
|
||||
owner,
|
||||
worktreeId: 'wt-1',
|
||||
filePath: 'src/app.tsx'
|
||||
filePath: 'src/app.tsx',
|
||||
count: 1
|
||||
}
|
||||
|
||||
describe('diff comments clear dialog state', () => {
|
||||
|
||||
+4
-2
@@ -1,8 +1,10 @@
|
||||
import type { DiffCommentOwner } from '@/store/diff-comment-owner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
/** A clear confirmation on the copy shown when it opened; `count` stands in once that copy is gone. */
|
||||
export type PendingDiffCommentsClear =
|
||||
| { kind: 'all'; worktreeId: string }
|
||||
| { kind: 'file'; worktreeId: string; filePath: string }
|
||||
| { kind: 'all'; worktreeId: string; owner: DiffCommentOwner; count: number }
|
||||
| { kind: 'file'; worktreeId: string; owner: DiffCommentOwner; filePath: string; count: number }
|
||||
|
||||
type DiffCommentWithPath = {
|
||||
filePath: string
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useDiffCommentView } from '@/components/diff-comments/use-diff-comment-owner'
|
||||
import type { AppState } from '@/store'
|
||||
import React from 'react'
|
||||
import { Check, ChevronDown, Copy, MessageSquare, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import { DiffNotesSendMenu } from '@/components/editor/DiffNotesSendMenu'
|
||||
@@ -36,9 +38,10 @@ export function SourceControlNotesShelf({
|
||||
diffCommentsCopied: boolean
|
||||
handleCopyDiffComments: () => Promise<void>
|
||||
setPendingDiffCommentsClear: React.Dispatch<React.SetStateAction<PendingDiffCommentsClear | null>>
|
||||
deleteDiffComment: (worktreeId: string, id: string) => Promise<void> | void
|
||||
deleteDiffComment: AppState['deleteDiffComment']
|
||||
handleOpenComment: (comment: DiffComment) => void
|
||||
}): React.JSX.Element {
|
||||
const { owner } = useDiffCommentView(activeWorktreeId, 'selection')
|
||||
return (
|
||||
<div className="border-b border-border">
|
||||
<div className="flex items-center gap-1 pl-3 pr-2 py-1.5">
|
||||
@@ -74,6 +77,7 @@ export function SourceControlNotesShelf({
|
||||
</button>
|
||||
<div className="ml-1 flex shrink-0 items-center gap-1.5">
|
||||
<DiffNotesSendMenu
|
||||
owner={owner}
|
||||
worktreeId={activeWorktreeId}
|
||||
groupId={activeGroupId ?? activeWorktreeId}
|
||||
comments={diffCommentsForActive}
|
||||
@@ -139,10 +143,15 @@ export function SourceControlNotesShelf({
|
||||
className="text-destructive focus:text-destructive"
|
||||
disabled={diffCommentCount === 0}
|
||||
onSelect={() => {
|
||||
if (!activeWorktreeId || diffCommentCount === 0) {
|
||||
if (!owner || !activeWorktreeId || diffCommentCount === 0) {
|
||||
return
|
||||
}
|
||||
setPendingDiffCommentsClear({ kind: 'all', worktreeId: activeWorktreeId })
|
||||
setPendingDiffCommentsClear({
|
||||
kind: 'all',
|
||||
worktreeId: activeWorktreeId,
|
||||
owner,
|
||||
count: diffCommentCount
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
@@ -158,13 +167,16 @@ export function SourceControlNotesShelf({
|
||||
{diffCommentsExpanded && (
|
||||
<DiffCommentsInlineList
|
||||
comments={diffCommentsForActive}
|
||||
onDelete={(id) => 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
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
+8
-3
@@ -14,8 +14,8 @@ vi.mock('sonner', () => ({ toast: { error: mocks.toastError, message: vi.fn() }
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => 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'
|
||||
|
||||
|
||||
+18
-12
@@ -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<boolean>
|
||||
clearDiffCommentsForFile: (
|
||||
worktreeId: string,
|
||||
filePath: string,
|
||||
options?: DiffCommentsClearOptions
|
||||
) => Promise<boolean>
|
||||
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 {
|
||||
|
||||
@@ -175,7 +175,9 @@ type AllRouteStateKeys = {
|
||||
const focusFreeRouteStates = new WeakMap<WorktreeOperationRouteState, WorktreeOperationRouteState>()
|
||||
|
||||
/** 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 = {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<HostAuthority> {
|
||||
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,
|
||||
|
||||
@@ -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<HostAuthority>
|
||||
|
||||
/** 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<WorktreeOperationRouteState['worktreesByRepo']>
|
||||
| ReturnType<typeof selectFolderWorkspaceCopies>
|
||||
|
||||
type CatalogMemo<R> = WeakMap<
|
||||
CatalogSnapshot,
|
||||
{ inputs: readonly unknown[]; results: Map<string, R> }
|
||||
>
|
||||
|
||||
/** One result per key while the anchor snapshot and inputs stay the same, shared by every reader of that snapshot. */
|
||||
function memoOnCatalog<R>(
|
||||
cache: CatalogMemo<R>,
|
||||
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<OwnerMatch> = 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<string, HostAuthority>()
|
||||
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<ExecutionHostId | undefined> {
|
||||
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<ExecutionHostId | undefined>
|
||||
|
||||
// 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<FolderQualification> = 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<string, ExecutionHostId | undefined>()
|
||||
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' }
|
||||
}
|
||||
@@ -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<WorktreeOperationRouteState['repos']>,
|
||||
ReadonlySet<string>
|
||||
>()
|
||||
|
||||
/** 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<string> {
|
||||
if (!repos) {
|
||||
return new Set()
|
||||
}
|
||||
return hasLocalRepoRow && hasRuntimeRepoRow
|
||||
let index = sharedLocalProjectIndexCache.get(repos)
|
||||
if (!index) {
|
||||
const kinds = new Map<string, Set<'local' | 'runtime' | 'other'>>()
|
||||
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(
|
||||
|
||||
@@ -29,6 +29,7 @@ const worktreeOwnerIndexCache = new WeakMap<
|
||||
{
|
||||
entries: ReadonlyMap<string, IndexedWorktreeOwnerEntry>
|
||||
ownersById: ReadonlyMap<string, readonly WorktreeOwnerRecord[]>
|
||||
locationsById: ReadonlyMap<string, readonly { bucket: string; position: number }[]>
|
||||
}
|
||||
>()
|
||||
const folderWorkspaceOwnerIndexCache = new WeakMap<
|
||||
@@ -167,9 +168,13 @@ export function resolveIndexedWorktreeOwner(
|
||||
if (!index) {
|
||||
const next = new Map<string, IndexedWorktreeOwnerEntry>()
|
||||
const ownersById = new Map<string, WorktreeOwnerRecord[]>()
|
||||
const locationsById = new Map<string, { bucket: string; position: number }[]>()
|
||||
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<W extends WorktreeOwnerRecord>(
|
||||
worktreesByRepo: Record<string, readonly W[]> | 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.
|
||||
|
||||
@@ -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<DiffCommentOwner, { kind: 'folder' }>
|
||||
): ReturnType<typeof findFolderWorkspaceOwner> {
|
||||
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<Args extends readonly unknown[], Result>(
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -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<typeof getExecutionHostIdForFolderWorkspace>,
|
||||
writeHostId?: ExecutionHostId
|
||||
owner: DiffCommentOwner,
|
||||
diffComments: DiffComment[]
|
||||
): Promise<void> {
|
||||
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 }
|
||||
|
||||
@@ -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<string, DiffComment[]>()
|
||||
// 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<string, number>()
|
||||
|
||||
/** 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<typeof getExecutionHostIdForFolderWorkspace>
|
||||
/** 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<typeof getExecutionHostIdForFolderWorkspace> | 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<void> {
|
||||
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<StateCreator<AppState>>[0],
|
||||
worktreeId: string,
|
||||
mutate: (existing: DiffComment[]) => DiffComment[] | null,
|
||||
commentIds?: Iterable<string>
|
||||
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<typeof getExecutionHostIdForFolderWorkspace> | undefined
|
||||
let twin: Pick<DiffCommentMutation, 'twin' | 'writeHostId'> = {}
|
||||
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<StateCreator<AppState>>[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
|
||||
|
||||
@@ -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<typeof RuntimeRpcClient>()),
|
||||
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<typeof createTwinStore>, hostId: string): st
|
||||
}
|
||||
|
||||
function addNote(store: ReturnType<typeof createTwinStore>) {
|
||||
return store.getState().addDiffComment({
|
||||
return addNoteFor(store, capturedOwner(store, WT))
|
||||
}
|
||||
|
||||
function addNoteFor(store: ReturnType<typeof createTwinStore>, 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<typeof createTwinStore>) {
|
||||
}
|
||||
|
||||
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<boolean> | 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()
|
||||
})
|
||||
|
||||
@@ -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<typeof createTestStore>, 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
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<DiffComment, 'id' | 'createdAt'>) => Promise<DiffComment | null>
|
||||
updateDiffComment: (worktreeId: string, commentId: string, body: string) => Promise<boolean>
|
||||
addDiffComment: (
|
||||
owner: DiffCommentOwner,
|
||||
input: Omit<DiffComment, 'id' | 'createdAt'>
|
||||
) => Promise<DiffComment | null>
|
||||
updateDiffComment: (owner: DiffCommentOwner, commentId: string, body: string) => Promise<boolean>
|
||||
clearDeliveredDiffComments: (
|
||||
worktreeId: string,
|
||||
owner: DiffCommentOwner,
|
||||
comments: readonly DiffCommentDeliverySnapshot[]
|
||||
) => Promise<boolean>
|
||||
markDiffCommentsSent: (
|
||||
worktreeId: string,
|
||||
owner: DiffCommentOwner,
|
||||
commentIds: readonly string[],
|
||||
sentAt?: number
|
||||
) => Promise<boolean>
|
||||
deleteDiffComment: (worktreeId: string, commentId: string) => Promise<void>
|
||||
clearDiffComments: (worktreeId: string, options?: DiffCommentsClearOptions) => Promise<boolean>
|
||||
deleteDiffComment: (owner: DiffCommentOwner, commentId: string) => Promise<void>
|
||||
clearDiffComments: (
|
||||
owner: DiffCommentOwner,
|
||||
options?: DiffCommentsClearOptions
|
||||
) => Promise<boolean>
|
||||
clearDiffCommentsForFile: (
|
||||
worktreeId: string,
|
||||
owner: DiffCommentOwner,
|
||||
filePath: string,
|
||||
options?: DiffCommentsClearOptions
|
||||
) => Promise<boolean>
|
||||
@@ -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<AppState, [], [], DiffCommentsSlice> = (
|
||||
set,
|
||||
get
|
||||
@@ -80,13 +99,16 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
|
||||
// Why the shared selector: rendered surfaces and actions must read the same twin's notes.
|
||||
getDiffComments: (worktreeId) => 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<AppState, [], [], DiffComment
|
||||
return comment
|
||||
},
|
||||
|
||||
updateDiffComment: async (worktreeId, commentId, body) => {
|
||||
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<AppState, [], [], DiffComment
|
||||
}
|
||||
|
||||
// Missing notes return false to keep draft; unchanged body returns true to close editor without mutation.
|
||||
const existing = readDiffCommentsForChange(get(), worktreeId, [commentId])
|
||||
const existing = readOwnedDiffComments(get(), owner) ?? []
|
||||
const existingIdx = existing.findIndex((c) => c.id === commentId)
|
||||
if (existingIdx === -1) {
|
||||
return false
|
||||
@@ -118,24 +145,19 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
|
||||
return true
|
||||
}
|
||||
|
||||
const result = mutateDiffComments(
|
||||
set,
|
||||
worktreeId,
|
||||
(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
|
||||
},
|
||||
[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<AppState, [], [], DiffComment
|
||||
}
|
||||
},
|
||||
|
||||
clearDeliveredDiffComments: async (worktreeId, comments) => {
|
||||
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<AppState, [], [], DiffComment
|
||||
return true
|
||||
},
|
||||
|
||||
markDiffCommentsSent: async (worktreeId, commentIds, sentAt = Date.now()) => {
|
||||
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<AppState, [], [], DiffComment
|
||||
return true
|
||||
},
|
||||
|
||||
deleteDiffComment: async (worktreeId, commentId) => {
|
||||
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<AppState, [], [], DiffComment
|
||||
}
|
||||
},
|
||||
|
||||
clearDiffComments: async (worktreeId, options) => {
|
||||
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<AppState, [], [], DiffComment
|
||||
}
|
||||
},
|
||||
|
||||
clearDiffCommentsForFile: async (worktreeId, filePath, options) => {
|
||||
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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<DiffComment | null> {
|
||||
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<typeof createTestStore>, 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
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -74,15 +74,10 @@ const qualifiedFolderOwnerCache = new WeakMap<
|
||||
}
|
||||
>()
|
||||
|
||||
export function resolveQualifiedIndexedFolderWorkspace<W extends FolderHostWorkspace>(
|
||||
state: QualifiedFolderHostState<W>,
|
||||
folderWorkspaceId: string,
|
||||
executionHostId?: ExecutionHostId
|
||||
): ReturnType<typeof resolveQualifiedFolderWorkspaceResult<W>> {
|
||||
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<string, FolderHostWorkspace[]>()
|
||||
@@ -97,6 +92,32 @@ export function resolveQualifiedIndexedFolderWorkspace<W extends FolderHostWorks
|
||||
cache = { groups: state.projectGroups, repos: state.repos, rows, positions, results: new Map() }
|
||||
qualifiedFolderOwnerCache.set(folders, cache)
|
||||
}
|
||||
return cache
|
||||
}
|
||||
|
||||
const NO_FOLDER_COPIES: readonly FolderHostWorkspace[] = []
|
||||
|
||||
/** The catalog's copies of one folder id from the shared id index (one pass per catalog snapshot); the array is stable until the catalog changes. */
|
||||
export function selectFolderWorkspaceCopies(
|
||||
state: QualifiedFolderHostState,
|
||||
folderWorkspaceId: string
|
||||
): readonly FolderHostWorkspace[] {
|
||||
const folders = selectFolderWorkspaces(state)
|
||||
return folders
|
||||
? (qualifiedFolderCacheOf(state, folders).rows.get(folderWorkspaceId) ?? NO_FOLDER_COPIES)
|
||||
: NO_FOLDER_COPIES
|
||||
}
|
||||
|
||||
export function resolveQualifiedIndexedFolderWorkspace<W extends FolderHostWorkspace>(
|
||||
state: QualifiedFolderHostState<W>,
|
||||
folderWorkspaceId: string,
|
||||
executionHostId?: ExecutionHostId
|
||||
): ReturnType<typeof resolveQualifiedFolderWorkspaceResult<W>> {
|
||||
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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<AppState, 'worktreesByRepo'> &
|
||||
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<AppState, 'worktreesByRepo'> &
|
||||
Partial<Pick<AppState, (typeof DIFF_COMMENT_OWNER_INPUTS)[number]>>
|
||||
|
||||
function twinOf(row: Pick<Worktree, 'hostId' | 'runtimeOwnerEnvironmentId'>): 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<string> } = {}
|
||||
): 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<string>
|
||||
): 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(
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 }
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user