From f79c03e3df27e74503887a4ba14cfbec7a300a4b Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Tue, 19 May 2026 18:14:49 -0700 Subject: [PATCH] fix: address review findings (#2381) --- .../github/pr-review-comment-lines.test.ts | 26 + src/main/github/pr-review-comment-lines.ts | 42 + src/main/github/work-item-details.ts | 4 +- .../src/assets/rich-markdown-editor.css | 10 +- .../src/components/GitHubItemDialog.tsx | 1001 +++++++++-------- .../diff-comments/DiffCommentCard.tsx | 3 + .../diff-comments/useDiffCommentDecorator.tsx | 44 +- .../editor/CombinedDiffFileTree.tsx | 152 +-- .../components/editor/CombinedDiffViewer.tsx | 67 +- .../components/editor/DiffNotesSendMenu.tsx | 136 +++ .../components/editor/DiffSectionHeader.tsx | 7 +- .../src/components/editor/DiffSectionItem.tsx | 64 +- .../src/components/editor/DiffViewer.tsx | 3 + .../components/editor/EditorPanelHeader.tsx | 14 + .../src/components/editor/MarkdownPreview.tsx | 47 +- .../components/editor/RichMarkdownEditor.tsx | 34 +- .../src/components/pr-diff-tree.test.ts | 150 --- src/renderer/src/components/pr-diff-tree.ts | 98 -- .../right-sidebar/SourceControl.tsx | 44 +- .../components/tab-bar/QuickLaunchButton.tsx | 10 +- src/renderer/src/lib/diff-comments-format.ts | 2 +- .../src/lib/launch-agent-in-new-tab.ts | 18 +- .../src/store/slices/diffComments.test.ts | 55 + src/renderer/src/store/slices/diffComments.ts | 50 +- src/shared/types.ts | 4 + 25 files changed, 1170 insertions(+), 915 deletions(-) create mode 100644 src/main/github/pr-review-comment-lines.test.ts create mode 100644 src/main/github/pr-review-comment-lines.ts create mode 100644 src/renderer/src/components/editor/DiffNotesSendMenu.tsx delete mode 100644 src/renderer/src/components/pr-diff-tree.test.ts delete mode 100644 src/renderer/src/components/pr-diff-tree.ts diff --git a/src/main/github/pr-review-comment-lines.test.ts b/src/main/github/pr-review-comment-lines.test.ts new file mode 100644 index 000000000..13a525bca --- /dev/null +++ b/src/main/github/pr-review-comment-lines.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' + +import { getPRReviewCommentLineNumbersFromPatch } from './pr-review-comment-lines' + +describe('getPRReviewCommentLineNumbersFromPatch', () => { + it('returns modified-side context and added lines from GitHub patch hunks', () => { + const patch = [ + '@@ -10,4 +20,5 @@ function example() {', + ' const kept = true', + '-const oldValue = 1', + '+const newValue = 1', + '+const added = true', + ' return kept', + '@@ -40,2 +51,2 @@ function other() {', + '-removeMe()', + '+addMe()', + ' done()' + ].join('\n') + + expect(getPRReviewCommentLineNumbersFromPatch(patch)).toEqual([20, 21, 22, 23, 51, 52]) + }) + + it('returns an empty list when GitHub omits the patch', () => { + expect(getPRReviewCommentLineNumbersFromPatch(undefined)).toEqual([]) + }) +}) diff --git a/src/main/github/pr-review-comment-lines.ts b/src/main/github/pr-review-comment-lines.ts new file mode 100644 index 000000000..0d64d214e --- /dev/null +++ b/src/main/github/pr-review-comment-lines.ts @@ -0,0 +1,42 @@ +const HUNK_HEADER_RE = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/ + +export function getPRReviewCommentLineNumbersFromPatch(patch: string | undefined): number[] { + if (!patch) { + return [] + } + + const lineNumbers: number[] = [] + let nextModifiedLine: number | null = null + + for (const line of patch.split('\n')) { + const hunk = HUNK_HEADER_RE.exec(line) + if (hunk) { + const start = Number(hunk[1]) + const count = hunk[2] === undefined ? 1 : Number(hunk[2]) + nextModifiedLine = Number.isInteger(start) && count > 0 ? start : null + continue + } + + if (nextModifiedLine === null || line.startsWith('\\')) { + continue + } + + if (line.startsWith('+') && !line.startsWith('+++')) { + lineNumbers.push(nextModifiedLine) + nextModifiedLine++ + continue + } + + if (line.startsWith(' ')) { + lineNumbers.push(nextModifiedLine) + nextModifiedLine++ + continue + } + + if (!line.startsWith('-')) { + nextModifiedLine++ + } + } + + return lineNumbers +} diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 1f374500d..70157abe6 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -22,6 +22,7 @@ import { } from './gh-utils' import { getWorkItem, getPRChecks, getPRComments } from './client' import { noteRateLimitSpend, rateLimitGuard } from './rate-limit' +import { getPRReviewCommentLineNumbersFromPatch } from './pr-review-comment-lines' // Why: a PR "changed file" listing returned by the REST endpoint is paginated // at 100 per page; we cap at a reasonable total so a massive PR cannot starve @@ -328,7 +329,8 @@ async function getPRFiles( status: mapFileStatus(file.status), additions: file.additions, deletions: file.deletions, - isBinary: isBinaryHint(file) + isBinary: isBinaryHint(file), + reviewCommentLineNumbers: getPRReviewCommentLineNumbersFromPatch(file.patch) })) } catch { return [] diff --git a/src/renderer/src/assets/rich-markdown-editor.css b/src/renderer/src/assets/rich-markdown-editor.css index 423cf6441..eb235a242 100644 --- a/src/renderer/src/assets/rich-markdown-editor.css +++ b/src/renderer/src/assets/rich-markdown-editor.css @@ -114,11 +114,17 @@ .rich-markdown-review-rail-toggle:hover, .rich-markdown-review-rail-toggle[aria-expanded='true'], -.rich-markdown-review-rail-send:hover { +.rich-markdown-review-rail-send:hover:not(:disabled) { background: var(--accent); color: var(--foreground); } +.rich-markdown-review-rail-send:disabled, +.rich-markdown-review-note-send:disabled { + cursor: default; + opacity: 0.45; +} + .rich-markdown-review-note-layer { position: absolute; top: 0; @@ -151,7 +157,7 @@ z-index: 1; } -.rich-markdown-review-note-send:hover { +.rich-markdown-review-note-send:hover:not(:disabled) { border-color: color-mix(in srgb, var(--foreground) 20%, transparent); background: color-mix(in srgb, var(--foreground) 6%, transparent); color: var(--foreground); diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 22ab974f6..0d702028d 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -4,35 +4,34 @@ import React, { lazy, useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import { useVirtualizer } from '@tanstack/react-virtual' +import type { editor as monacoEditor } from 'monaco-editor' import { - AlignJustify, ArrowDown, ArrowRight, ArrowUp, Braces, Check, ChevronDown, - ChevronRight, CircleDashed, CircleDot, Copy, ExternalLink, FileText, - Folder, - FolderOpen, GitMerge, GitPullRequest, GitPullRequestClosed, - LayoutList, ListChecks, LoaderCircle, MessageSquare, MessageSquarePlus, + PanelLeftOpen, Pencil, RefreshCw, Send, @@ -66,7 +65,18 @@ import { import CommentMarkdown from '@/components/sidebar/CommentMarkdown' import { detectLanguage } from '@/lib/language-detect' import { cn } from '@/lib/utils' -import { buildDiffTree, type DiffTreeNode } from '@/components/pr-diff-tree' +import { DiffSectionItem } from '@/components/editor/DiffSectionItem' +import { + CombinedDiffFileTree, + createCombinedDiffSectionIndexMap, + handleCombinedDiffFileTreeNavigation +} from '@/components/editor/CombinedDiffFileTree' +import { + getDiffSectionEstimatedHeight, + isIntrinsicHeightImageDiff +} from '@/components/editor/diff-section-layout' +import type { DiffSection } from '@/components/editor/diff-section-types' +import type { CombinedDiffFileTreeEntry } from '@/components/editor/combined-diff-file-tree-model' import { CHECK_COLOR, CHECK_ICON } from '@/components/right-sidebar/checks-panel-content' import { filterPRCommentsByAudience, @@ -110,6 +120,8 @@ import type { GitHubWorkItemDetails, GitHubAssignableUser, GitHubReaction, + GitBranchChangeEntry, + GitDiffResult, PRCheckDetail, PRCheckRunDetails, PRComment, @@ -142,9 +154,6 @@ function parseOwnerRepoFromItemUrl(url: string): GitHubOwnerRepo | null { } } -// Why: the editor's DiffViewer loads Monaco, which is heavy and should not be -// pulled into the dialog's bundle until the user actually opens the Files tab. -const DiffViewer = lazy(() => import('@/components/editor/DiffViewer')) const MonacoCodeExcerpt = lazy(() => import('@/components/editor/MonacoCodeExcerpt')) export type ItemDialogTab = 'conversation' | 'checks' | 'files' @@ -1004,47 +1013,10 @@ function PRReviewersPanel({ ) } -function fileStatusTone(status: GitHubPRFile['status']): string { - switch (status) { - case 'added': - return 'text-emerald-500' - case 'removed': - return 'text-rose-500' - case 'renamed': - case 'copied': - return 'text-sky-500' - default: - return 'text-amber-500' - } -} - -function fileStatusLabel(status: GitHubPRFile['status']): string { - switch (status) { - case 'added': - return 'A' - case 'removed': - return 'D' - case 'renamed': - return 'R' - case 'copied': - return 'C' - case 'unchanged': - return '·' - default: - return 'M' - } -} - function isPRFileViewed(file: GitHubPRFile): boolean { return file.viewerViewedState === 'VIEWED' } -// Why: GitHub's viewed toggle auto-collapses the file; keying rows by the -// viewed state resets the row's local expanded/content state without an Effect. -function getPRFileRowKey(file: GitHubPRFile): string { - return `${file.path}:${file.viewerViewedState ?? 'UNVIEWED'}` -} - function findNearestBraceBlock( lines: string[], targetLine: number @@ -1083,164 +1055,6 @@ function findNearestBraceBlock( ) } -type FileRowProps = { - file: GitHubPRFile - repoPath: string - repoId: string - prNumber: number - headSha: string | undefined - baseSha: string | undefined - viewed: boolean - viewedPending: boolean - onViewedChange: (path: string, viewed: boolean) => Promise -} - -type DiffViewMode = 'flat' | 'tree' - -// ─── Tree view components ──────────────────────────────────────────── - -type DiffTreeNodeProps = { - node: DiffTreeNode - depth: number - repoPath: string - repoId: string - prNumber: number - headSha: string | undefined - baseSha: string | undefined - pendingViewedPaths: ReadonlySet - onCommentAdded: (comment: PRComment) => void - onViewedChange: (path: string, viewed: boolean) => Promise -} - -function PRDiffTreeNode({ - node, - depth, - repoPath, - repoId, - prNumber, - headSha, - baseSha, - pendingViewedPaths, - onCommentAdded, - onViewedChange -}: DiffTreeNodeProps): React.JSX.Element { - const [open, setOpen] = useState(true) - - if (node.kind === 'file') { - return ( - - ) - } - - // Directory node - return ( -
- - {open && ( -
- {node.children.map((child) => ( - - ))} -
- )} -
- ) -} - -type PRDiffTreeViewProps = { - files: GitHubPRFile[] - repoPath: string - repoId: string - prNumber: number - headSha: string | undefined - baseSha: string | undefined - pendingViewedPaths: ReadonlySet - onCommentAdded: (comment: PRComment) => void - onViewedChange: (path: string, viewed: boolean) => Promise -} - -function PRDiffTreeView({ - files, - repoPath, - repoId, - prNumber, - headSha, - baseSha, - pendingViewedPaths, - onCommentAdded, - onViewedChange -}: PRDiffTreeViewProps): React.JSX.Element { - const tree = useMemo(() => buildDiffTree(files), [files]) - return ( -
- {tree.map((node) => ( - - ))} -
- ) -} - // Why: SWR cache for the work-item details fetch. Reopening the same drawer // pays full IPC + `gh` process startup latency without this; with it, cached // data paints immediately while a background refetch keeps the view honest. @@ -1666,38 +1480,213 @@ function PRViewedCheckbox({ ) } -function PRFileRow({ - file, +const PR_DIFF_OVERSCAN = 5 + +function mapPRFileStatus(status: GitHubPRFile['status']): GitBranchChangeEntry['status'] { + switch (status) { + case 'added': + return 'added' + case 'removed': + return 'deleted' + case 'renamed': + return 'renamed' + case 'copied': + return 'copied' + default: + return 'modified' + } +} + +function getPRFileSectionKey(path: string): string { + return `combined-commit:${path}` +} + +function gitHubPRFileToBranchEntry(file: GitHubPRFile): GitBranchChangeEntry { + return { + path: file.path, + oldPath: file.oldPath, + status: mapPRFileStatus(file.status), + added: file.additions, + removed: file.deletions + } +} + +function getPRFileDiffResult(contents: GitHubPRFileContents): GitDiffResult { + if (contents.originalIsBinary) { + return { + kind: 'binary', + originalContent: contents.original, + modifiedContent: contents.modified, + originalIsBinary: true, + modifiedIsBinary: contents.modifiedIsBinary + } + } + if (contents.modifiedIsBinary) { + return { + kind: 'binary', + originalContent: contents.original, + modifiedContent: contents.modified, + originalIsBinary: false, + modifiedIsBinary: true + } + } + + return { + kind: 'text', + originalContent: contents.original, + modifiedContent: contents.modified, + originalIsBinary: false, + modifiedIsBinary: false + } +} + +type PRFilesCombinedDiffViewerProps = { + files: GitHubPRFile[] + repoPath: string + repoId: string + prNumber: number + prUrl: string + headSha: string | undefined + baseSha: string | undefined + pendingViewedPaths: ReadonlySet + onCommentAdded: (comment: PRComment) => void + onViewedChange: (path: string, viewed: boolean) => Promise +} + +function PRFilesCombinedDiffViewer({ + files, repoPath, repoId, prNumber, + prUrl, headSha, baseSha, - viewed, - viewedPending, - onViewedChange, + pendingViewedPaths, onCommentAdded, - indentDepth = 0, - label -}: FileRowProps & { - onCommentAdded: (comment: PRComment) => void - indentDepth?: number - label?: string -}): React.JSX.Element { - const [expanded, setExpanded] = useState(false) - const [contents, setContents] = useState(null) - const [loading, setLoading] = useState(false) - const [error, setError] = useState(null) + onViewedChange +}: PRFilesCombinedDiffViewerProps): React.JSX.Element { + const settings = useAppStore((s) => s.settings) + const isDark = + settings?.theme === 'dark' || + (settings?.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches) + const entriesCacheRef = useRef<{ + signature: string + entries: GitBranchChangeEntry[] + } | null>(null) + const diffEntrySignature = useMemo( + () => + JSON.stringify( + files.map((file) => ({ + path: file.path, + oldPath: file.oldPath ?? null, + status: file.status, + additions: file.additions, + deletions: file.deletions, + isBinary: file.isBinary + })) + ), + [files] + ) + const entries = useMemo(() => { + if (entriesCacheRef.current?.signature === diffEntrySignature) { + return entriesCacheRef.current.entries + } + const nextEntries = files.map(gitHubPRFileToBranchEntry) + entriesCacheRef.current = { signature: diffEntrySignature, entries: nextEntries } + return nextEntries + }, [diffEntrySignature, files]) + const fileByPath = useMemo(() => new Map(files.map((file) => [file.path, file])), [files]) + const entrySignature = useMemo( + () => + JSON.stringify({ + repoId, + prNumber, + headSha: headSha ?? null, + baseSha: baseSha ?? null, + files: diffEntrySignature + }), + [baseSha, diffEntrySignature, headSha, prNumber, repoId] + ) + const [sections, setSections] = useState([]) + const [sideBySide, setSideBySide] = useState(false) + const [fileTreeCollapsed, setFileTreeCollapsed] = useState(false) + const [sectionHeights, setSectionHeights] = useState>({}) + const [activeTreeSectionKey, setActiveTreeSectionKey] = useState(null) + const scrollContainerRef = useRef(null) + const loadedIndicesRef = useRef>(new Set()) + const loadingIndicesRef = useRef>(new Set()) + const sectionsRef = useRef([]) + const generationRef = useRef(0) + const modifiedEditorsRef = useRef>(new Map()) + const handleSectionSaveRef = useRef<(index: number) => Promise>(async () => {}) + sectionsRef.current = sections - const canLoadDiff = Boolean(headSha && baseSha) && !file.isBinary + useEffect(() => { + generationRef.current += 1 + loadedIndicesRef.current.clear() + loadingIndicesRef.current.clear() + setSectionHeights({}) + setActiveTreeSectionKey(null) + setSections( + entries.map((entry) => ({ + key: getPRFileSectionKey(entry.path), + path: entry.path, + oldPath: entry.oldPath, + status: entry.status, + added: entry.added, + removed: entry.removed, + originalContent: '', + modifiedContent: '', + collapsed: false, + loading: true, + error: undefined, + dirty: false, + diffResult: null + })) + ) + }, [entries, entrySignature]) - const handleToggle = useCallback(() => { - setExpanded((prev) => { - const next = !prev - if (next && !contents && !loading && canLoadDiff && headSha && baseSha) { - setLoading(true) - setError(null) - loadPRFileContents({ + const loadSection = useCallback( + (index: number) => { + const section = sectionsRef.current[index] + if (!section || section.collapsed) { + return + } + if (loadedIndicesRef.current.has(index) || loadingIndicesRef.current.has(index)) { + return + } + const file = fileByPath.get(section.path) + if (!file) { + return + } + const generation = generationRef.current + loadingIndicesRef.current.add(index) + + const load = async (): Promise<{ result: GitDiffResult; error?: string }> => { + if (file.isBinary) { + return { + result: { + kind: 'binary', + originalContent: '', + modifiedContent: '', + originalIsBinary: true, + modifiedIsBinary: true + } + } + } + if (!headSha || !baseSha) { + return { + result: { + kind: 'text', + originalContent: '', + modifiedContent: '', + originalIsBinary: false, + modifiedIsBinary: false + }, + error: 'Diff unavailable because the PR commit SHAs are missing.' + } + } + const contents = await loadPRFileContents({ repoPath, repoId, prNumber, @@ -1705,32 +1694,169 @@ function PRFileRow({ headSha, baseSha }) - .then((result) => { - setContents(result) - }) - .catch((err) => { - setError(err instanceof Error ? err.message : 'Failed to load diff') - }) - .finally(() => { - setLoading(false) - }) + return { result: getPRFileDiffResult(contents) } } - return next - }) - }, [baseSha, canLoadDiff, contents, file, headSha, loading, prNumber, repoId, repoPath]) - const language = useMemo(() => detectLanguage(file.path), [file.path]) - const modelKey = `gh-dialog:pr:${prNumber}:${file.path}` + load() + .catch((error) => ({ + result: { + kind: 'text', + originalContent: '', + modifiedContent: '', + originalIsBinary: false, + modifiedIsBinary: false + } as GitDiffResult, + error: error instanceof Error ? error.message : 'Failed to load diff.' + })) + .then(({ result, error }) => { + loadingIndicesRef.current.delete(index) + if (generationRef.current !== generation) { + return + } + loadedIndicesRef.current.add(index) + setSections((prev) => + prev.map((current, currentIndex) => + currentIndex === index + ? { + ...current, + diffResult: result, + originalContent: result.kind === 'text' ? result.originalContent : '', + modifiedContent: result.kind === 'text' ? result.modifiedContent : '', + loading: false, + error + } + : current + ) + ) + }) + }, + [baseSha, fileByPath, headSha, prNumber, repoId, repoPath] + ) + + const retrySection = useCallback( + (index: number) => { + loadedIndicesRef.current.delete(index) + loadingIndicesRef.current.delete(index) + setSections((prev) => + prev.map((section, sectionIndex) => + sectionIndex === index + ? { + ...section, + diffResult: null, + originalContent: '', + modifiedContent: '', + loading: true, + error: undefined + } + : section + ) + ) + loadSection(index) + }, + [loadSection] + ) + + const toggleSection = useCallback( + (index: number) => { + const shouldLoadAfterExpand = sectionsRef.current[index]?.collapsed ?? false + setSections((prev) => + prev.map((section, sectionIndex) => + sectionIndex === index ? { ...section, collapsed: !section.collapsed } : section + ) + ) + if (shouldLoadAfterExpand) { + window.requestAnimationFrame(() => loadSection(index)) + } + }, + [loadSection] + ) + + const setAllSectionsCollapsed = useCallback( + (collapsed: boolean) => { + setSections((prev) => prev.map((section) => ({ ...section, collapsed }))) + if (!collapsed) { + window.requestAnimationFrame(() => { + sectionsRef.current.forEach((_, index) => loadSection(index)) + }) + } + }, + [loadSection] + ) + + const allSectionsCollapsed = sections.length > 0 && sections.every((section) => section.collapsed) + const sectionIndexByKey = useMemo(() => createCombinedDiffSectionIndexMap(sections), [sections]) + const viewedSectionKeys = useMemo( + () => new Set(files.filter(isPRFileViewed).map((file) => getPRFileSectionKey(file.path))), + [files] + ) + + const virtualizer = useVirtualizer({ + count: sections.length, + getScrollElement: () => scrollContainerRef.current, + estimateSize: (index) => { + const section = sections[index] + if (!section) { + return 88 + } + return getDiffSectionEstimatedHeight({ + collapsed: section.collapsed, + measuredContentHeight: sectionHeights[index], + originalContent: section.originalContent, + modifiedContent: section.modifiedContent, + changedLineCount: + section.added === undefined && section.removed === undefined + ? undefined + : (section.added ?? 0) + (section.removed ?? 0), + useIntrinsicImageHeight: isIntrinsicHeightImageDiff(section.diffResult) + }) + }, + overscan: PR_DIFF_OVERSCAN, + getItemKey: (index) => { + const section = sections[index] + return section + ? `${section.key}:${section.collapsed ? 'collapsed' : 'expanded'}:${entrySignature}` + : `${index}:${entrySignature}` + } + }) + + useLayoutEffect(() => { + virtualizer.measure() + }, [sideBySide, virtualizer]) + + const handleTreeNavigate = useCallback( + (entry: CombinedDiffFileTreeEntry) => { + const navigatedIndex = handleCombinedDiffFileTreeNavigation({ + mode: 'commit', + entry, + sections: sectionsRef.current, + sectionIndexByKey, + toggleSection, + scrollToIndex: (index) => virtualizer.scrollToIndex(index, { align: 'start' }) + }) + if (navigatedIndex !== null) { + setActiveTreeSectionKey(sectionsRef.current[navigatedIndex]?.key ?? null) + } + }, + [sectionIndexByKey, toggleSection, virtualizer] + ) + + const openFilesOnGitHub = useCallback(() => { + void window.api.shell.openUrl(`${prUrl.replace(/\/$/, '')}/files`) + }, [prUrl]) + const handleAddLineComment = useCallback( - async ({ - lineNumber, - startLine, - body: commentBody - }: { - lineNumber: number - startLine?: number - body: string - }) => { + async ( + section: DiffSection, + { + lineNumber, + startLine, + body + }: { + lineNumber: number + startLine?: number + body: string + } + ) => { if (!headSha) { toast.error('Unable to comment without the PR head SHA.') return false @@ -1740,10 +1866,10 @@ function PRFileRow({ repoId, prNumber, commitId: headSha, - path: file.path, + path: section.path, line: lineNumber, startLine, - body: commentBody + body }) if (!result.ok) { toast.error(result.error || 'Failed to add review comment.') @@ -1753,152 +1879,135 @@ function PRFileRow({ toast.success('Review comment added.') return true }, - [file.path, headSha, onCommentAdded, prNumber, repoId, repoPath] + [headSha, onCommentAdded, prNumber, repoId, repoPath] ) - const handleViewedToggle = useCallback(async () => { - if (viewedPending) { - return - } - await onViewedChange(file.path, !viewed) - }, [file.path, onViewedChange, viewed, viewedPending]) - - return ( -
-
- - - +{file.additions} - / - −{file.deletions} - + const renderViewedCheckbox = useCallback( + (section: DiffSection) => { + const file = fileByPath.get(section.path) + if (!file) { + return null + } + const viewed = isPRFileViewed(file) + const pending = pendingViewedPaths.has(file.path) + return ( { + if (!pending) { + void onViewedChange(file.path, !viewed) + } + }} /> -
+ ) + }, + [fileByPath, onViewedChange, pendingViewedPaths] + ) - {expanded && ( - // Why: DiffViewer's inner layout uses flex-1/min-h-0, so this wrapper - // must be a flex column with a fixed height for Monaco to size itself - // correctly. A plain block div collapses flex-1 to 0 and renders empty. -
- {!canLoadDiff ? ( -
- {file.isBinary - ? 'Binary file — diff not shown.' - : 'Diff unavailable (missing commit SHAs).'} -
- ) : loading ? ( -
- -
- ) : error ? ( -
- {error} -
- ) : contents ? ( - contents.originalIsBinary || contents.modifiedIsBinary ? ( -
- Binary file — diff not shown. -
- ) : ( - - -
- } - > - - - ) - ) : null} + return ( +
+
+
+ {fileTreeCollapsed && ( + + + + + + Show file tree + + + )} + + {files.filter(isPRFileViewed).length} / {files.length} files viewed +
- )} +
+ + +
+
+
+ +
+
+ {virtualizer.getVirtualItems().map((virtualItem) => { + const section = sections[virtualItem.index] + if (!section) { + return null + } + return ( +
+ + fileByPath.get(section.path)?.reviewCommentLineNumbers + } + setSectionHeights={setSectionHeights} + setSections={setSections} + modifiedEditorsRef={modifiedEditorsRef} + handleSectionSaveRef={handleSectionSaveRef} + /> +
+ ) + })} +
+
+
) } @@ -4734,7 +4843,6 @@ export default function GitHubItemDialog({ const [tab, setTab] = useState(() => normalizeItemDialogTab(workItem, initialTab)) const [localState, setLocalState] = useState(workItem?.state ?? 'open') const [localLabels, setLocalLabels] = useState(workItem?.labels ?? []) - const [diffViewMode, setDiffViewMode] = useState('flat') const [linkCopied, setLinkCopied] = useState(false) const workItemId = workItem?.id const workItemState = workItem?.state @@ -5001,7 +5109,6 @@ export default function GitHubItemDialog({ const comments = details?.comments ?? [] const files = details?.files ?? [] const checks = details?.checks ?? [] - const viewedFileCount = files.filter(isPRFileViewed).length const [pendingViewedPaths, setPendingViewedPaths] = useState>(() => new Set()) useEffect(() => { @@ -5110,14 +5217,21 @@ export default function GitHubItemDialog({ side="right" showCloseButton={false} className={cn( - 'flex w-full flex-col gap-0 overflow-hidden p-0 xl:max-w-[1120px] 2xl:max-w-[1240px]', + 'flex w-full flex-col gap-0 overflow-hidden p-0 lg:max-w-[var(--github-item-dialog-max-width)]', // Why: native macOS traffic lights are drawn above web content, so a // nearly full-width right sheet must leave the titlebar's 80px // traffic-light pad uncovered instead of relying on z-index. IS_MAC - ? 'max-w-[calc(100vw-(80px/var(--ui-zoom-factor,1)))] sm:max-w-[calc(100vw-(80px/var(--ui-zoom-factor,1)))] lg:max-w-[calc(100vw-(80px/var(--ui-zoom-factor,1)))]' - : 'max-w-[calc(100vw-1rem)] sm:max-w-[calc(100vw-1rem)] lg:max-w-[calc(100vw-2rem)]' + ? 'max-w-[calc(100vw-(80px/var(--ui-zoom-factor,1)))] sm:max-w-[calc(100vw-(80px/var(--ui-zoom-factor,1)))]' + : 'max-w-[calc(100vw-1rem)] sm:max-w-[calc(100vw-1rem)]' )} + style={ + { + '--github-item-dialog-max-width': IS_MAC + ? 'min(calc(100vw - (80px / var(--ui-zoom-factor, 1))), 1600px)' + : 'min(calc(100vw - 2rem), 1600px)' + } as React.CSSProperties + } onOpenAutoFocus={(event) => { // Why: focusing the first actionable element inside the drawer // causes the "Start workspace" action to receive focus and @@ -5385,89 +5499,18 @@ export default function GitHubItemDialog({ No files changed.
) : ( -
- {/* Files-tab toolbar: view-mode toggle */} -
- - {viewedFileCount} / {files.length} files viewed - -
- - - - - - Flat view - - - - - - - - Tree view - - -
-
- {diffViewMode === 'flat' ? ( - files.map((file) => ( - - )) - ) : ( - - )} -
+ )} diff --git a/src/renderer/src/components/diff-comments/DiffCommentCard.tsx b/src/renderer/src/components/diff-comments/DiffCommentCard.tsx index c2aa9fdde..dcfeadbf3 100644 --- a/src/renderer/src/components/diff-comments/DiffCommentCard.tsx +++ b/src/renderer/src/components/diff-comments/DiffCommentCard.tsx @@ -18,6 +18,7 @@ type Props = { startLine?: number label?: string body: string + sentAt?: number onDelete: () => void // Why: Monaco view zones have a fixed `heightInPx` set at insertion time // and aren't auto-measured. While the user is in edit mode the textarea @@ -33,6 +34,7 @@ export function DiffCommentCard({ startLine, label, body, + sentAt, onDelete, onContentResize, onSubmitEdit, @@ -132,6 +134,7 @@ export function DiffCommentCard({
Note · {label ?? getDiffCommentLineLabel({ lineNumber, startLine }).toLowerCase()} + {sentAt ? ' · sent' : ''}
{!editing && headerActions} diff --git a/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx b/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx index f1f5d8d79..e645925f8 100644 --- a/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx +++ b/src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react' +import { useEffect, useMemo, useRef } from 'react' import * as monaco from 'monaco-editor' import type { editor as monacoEditor, IDisposable } from 'monaco-editor' import { createRoot, type Root } from 'react-dom/client' @@ -19,6 +19,7 @@ type DecoratorArgs = { filePath: string worktreeId: string comments: DiffComment[] + commentableLineNumbers?: readonly number[] addButtonLabel?: string onAddCommentClick: (args: { lineNumber: number; startLine?: number; top: number }) => void onDeleteComment: (commentId: string) => void @@ -65,6 +66,7 @@ export function useDiffCommentDecorator({ filePath, worktreeId, comments, + commentableLineNumbers, addButtonLabel = 'Add note for the AI', onAddCommentClick, onDeleteComment, @@ -106,6 +108,10 @@ export function useDiffCommentDecorator({ onDeleteCommentRef.current = onDeleteComment onUpdateCommentRef.current = onUpdateComment onPendingScrollConsumedRef.current = onPendingScrollConsumed + const commentableLineSet = useMemo( + () => (commentableLineNumbers ? new Set(commentableLineNumbers) : null), + [commentableLineNumbers] + ) useEffect(() => { if (!editor) { @@ -181,6 +187,24 @@ export function useDiffCommentDecorator({ return editor.getTargetAtClientPoint(clientX, clientY)?.position?.lineNumber ?? null } + const canCommentOnLine = (lineNumber: number): boolean => { + return commentableLineSet === null || commentableLineSet.has(lineNumber) + } + + const canCommentOnRange = (startLine: number, endLine: number): boolean => { + if (commentableLineSet === null) { + return true + } + const from = Math.min(startLine, endLine) + const to = Math.max(startLine, endLine) + for (let line = from; line <= to; line++) { + if (!commentableLineSet.has(line)) { + return false + } + } + return true + } + const positionAtLine = (lineNumber: number): void => { const lineTop = editor.getTopForLineNumber(lineNumber) - editor.getScrollTop() const top = Math.round(lineTop + (getLineHeight() - BUTTON_SIZE) / 2) @@ -202,6 +226,9 @@ export function useDiffCommentDecorator({ if (!currentDrag) { return } + if (!canCommentOnRange(currentDrag.startLine, currentDrag.endLine)) { + return + } const startLine = Math.min(currentDrag.startLine, currentDrag.endLine) const lineNumber = Math.max(currentDrag.startLine, currentDrag.endLine) const top = getDiffCommentPopoverTop(editor, lineNumber, getLineHeight()) @@ -220,7 +247,12 @@ export function useDiffCommentDecorator({ return } const line = getLineAtClientPoint(ev.clientX, ev.clientY) - if (line == null || line === dragState.endLine) { + if ( + line == null || + line === dragState.endLine || + !canCommentOnLine(line) || + !canCommentOnRange(dragState.startLine, line) + ) { return } dragState = { ...dragState, endLine: line } @@ -231,7 +263,7 @@ export function useDiffCommentDecorator({ ev.preventDefault() ev.stopPropagation() const line = hoverLineRef.current - if (line == null) { + if (line == null || !canCommentOnLine(line)) { return } dragState = { startLine: line, endLine: line } @@ -253,7 +285,8 @@ export function useDiffCommentDecorator({ return } const ln = e.target.position?.lineNumber ?? null - if (ln == null) { + if (ln == null || !canCommentOnLine(ln)) { + hoverLineRef.current = null setDisplay('none') return } @@ -316,7 +349,7 @@ export function useDiffCommentDecorator({ pendingScrollRef.current = null scrollToZoneRef.current = null } - }, [addButtonLabel, editor]) + }, [addButtonLabel, commentableLineSet, editor]) useEffect(() => { if (!editor) { @@ -401,6 +434,7 @@ export function useDiffCommentDecorator({ lineNumber={comment.lineNumber} startLine={comment.startLine} body={comment.body} + sentAt={comment.sentAt} onDelete={() => onDeleteCommentRef.current(comment.id)} onSubmitEdit={ onUpdateCommentRef.current diff --git a/src/renderer/src/components/editor/CombinedDiffFileTree.tsx b/src/renderer/src/components/editor/CombinedDiffFileTree.tsx index 5a330da84..30a9da415 100644 --- a/src/renderer/src/components/editor/CombinedDiffFileTree.tsx +++ b/src/renderer/src/components/editor/CombinedDiffFileTree.tsx @@ -193,88 +193,90 @@ export function CombinedDiffFileTree({ } return ( -
) @@ -1302,6 +1288,11 @@ function DiffNotesPreviewPopover({
{comment.filePath} + {comment.sentAt ? ( + + Sent + + ) : null} {getDiffCommentLineLabel(comment, true)} diff --git a/src/renderer/src/components/editor/DiffNotesSendMenu.tsx b/src/renderer/src/components/editor/DiffNotesSendMenu.tsx new file mode 100644 index 000000000..c5e315459 --- /dev/null +++ b/src/renderer/src/components/editor/DiffNotesSendMenu.tsx @@ -0,0 +1,136 @@ +import React, { useMemo } from 'react' +import { Send } from 'lucide-react' +import type { DiffComment } from '../../../../shared/types' +import { useAppStore } from '@/store' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuLabel, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { QuickLaunchAgentMenuItems } from '@/components/tab-bar/QuickLaunchButton' +import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { formatDiffComments } from '@/lib/diff-comments-format' +import { cn } from '@/lib/utils' + +export function DiffNotesSendMenu({ + worktreeId, + groupId, + comments, + filePath, + showFileScope = false, + triggerClassName, + iconClassName = 'size-3.5', + align = 'end' +}: { + worktreeId: string + groupId: string + comments: readonly DiffComment[] + filePath?: string + showFileScope?: boolean + triggerClassName?: string + iconClassName?: string + align?: 'start' | 'center' | 'end' +}): React.JSX.Element { + const markDiffCommentsSent = useAppStore((s) => s.markDiffCommentsSent) + const unsentNotes = useMemo(() => comments.filter((comment) => !comment.sentAt), [comments]) + const unsentNoteIds = useMemo(() => unsentNotes.map((comment) => comment.id), [unsentNotes]) + const unsentPrompt = useMemo(() => formatDiffComments(unsentNotes), [unsentNotes]) + const fileNotes = useMemo( + () => (filePath ? comments.filter((comment) => comment.filePath === filePath) : []), + [comments, filePath] + ) + const unsentFileNotes = useMemo(() => fileNotes.filter((comment) => !comment.sentAt), [fileNotes]) + const unsentFileNoteIds = useMemo( + () => unsentFileNotes.map((comment) => comment.id), + [unsentFileNotes] + ) + const unsentFilePrompt = useMemo(() => formatDiffComments(unsentFileNotes), [unsentFileNotes]) + const hasUnsentNotes = unsentNotes.length > 0 + const canSendFileScope = showFileScope && Boolean(filePath) + + return ( + + + + + + + + + {hasUnsentNotes ? 'Send notes to a new agent' : 'All notes sent'} + + + + {canSendFileScope ? ( + <> + Send notes + + + This file + + {unsentFileNotes.length} + + + + void markDiffCommentsSent(worktreeId, unsentFileNoteIds)} + /> + + + + + All unsent notes + + {unsentNotes.length} + + + + void markDiffCommentsSent(worktreeId, unsentNoteIds)} + /> + + + + ) : ( + void markDiffCommentsSent(worktreeId, unsentNoteIds)} + /> + )} + + + ) +} diff --git a/src/renderer/src/components/editor/DiffSectionHeader.tsx b/src/renderer/src/components/editor/DiffSectionHeader.tsx index d97e45987..2a35c7437 100644 --- a/src/renderer/src/components/editor/DiffSectionHeader.tsx +++ b/src/renderer/src/components/editor/DiffSectionHeader.tsx @@ -1,5 +1,5 @@ import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-react' -import type { MouseEvent, ReactElement } from 'react' +import type { MouseEvent, ReactElement, ReactNode } from 'react' export function DiffSectionHeader({ path, @@ -9,7 +9,8 @@ export function DiffSectionHeader({ removed, onToggle, onOpenSection, - openSectionTitle + openSectionTitle, + trailingContent }: { path: string dirty: boolean @@ -19,6 +20,7 @@ export function DiffSectionHeader({ onToggle: () => void onOpenSection: (event: MouseEvent) => void openSectionTitle: string + trailingContent?: ReactNode }): ReactElement { return (
+ {trailingContent} - - - - - - - - - - Send notes to a new agent - - - - - - - + {diffCommentCount > 0 && ( @@ -4149,6 +4124,11 @@ function DiffCommentsInlineList({ {getDiffCommentSource(c) === 'markdown' ? 'MD' : 'Diff'} + {c.sentAt ? ( + + Sent + + ) : null} {c.body} diff --git a/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx b/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx index d6ae5577a..b20417861 100644 --- a/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx +++ b/src/renderer/src/components/tab-bar/QuickLaunchButton.tsx @@ -27,6 +27,8 @@ export type QuickLaunchAgentMenuItemsProps = { * `'tab_bar_quick_launch'` so the existing tab-bar `+` callsite is * unchanged. */ launchSource?: LaunchSource + /** Called after a prompt is queued into the agent, or immediately for argv prompt launches. */ + onPromptDelivered?: () => void } function getCatalogEntry(agent: TuiAgent): { id: TuiAgent; label: string } | null { @@ -77,7 +79,8 @@ function QuickLaunchAgentMenuItemsInner({ onFocusTerminal, prompt, promptDelivery, - launchSource + launchSource, + onPromptDelivered }: QuickLaunchAgentMenuItemsProps): React.JSX.Element | null { // Why: must be a reactive selector (not getConnectionId() which reads a // snapshot via getState()). This ensures the component re-renders when the @@ -112,7 +115,8 @@ function QuickLaunchAgentMenuItemsInner({ groupId, ...(prompt !== undefined ? { prompt } : {}), ...(promptDelivery !== undefined ? { promptDelivery } : {}), - ...(launchSource !== undefined ? { launchSource } : {}) + ...(launchSource !== undefined ? { launchSource } : {}), + ...(onPromptDelivered !== undefined ? { onPromptDelivered } : {}) }) if (!result) { toast.error(`Could not build launch command for ${label}.`) @@ -155,7 +159,7 @@ function QuickLaunchAgentMenuItemsInner({ toast.message(getLaunchWatchdogTimeoutMessage(label)) }) }, - [worktreeId, groupId, onFocusTerminal, prompt, promptDelivery, launchSource] + [worktreeId, groupId, onFocusTerminal, prompt, promptDelivery, launchSource, onPromptDelivered] ) const agents = detectedIds ? orderAgents(defaultAgent, detectedIds) : [] diff --git a/src/renderer/src/lib/diff-comments-format.ts b/src/renderer/src/lib/diff-comments-format.ts index 1af7ea9dc..26f8cdf83 100644 --- a/src/renderer/src/lib/diff-comments-format.ts +++ b/src/renderer/src/lib/diff-comments-format.ts @@ -23,6 +23,6 @@ export function formatDiffComment(c: DiffComment): string { ) } -export function formatDiffComments(comments: DiffComment[]): string { +export function formatDiffComments(comments: readonly DiffComment[]): string { return comments.map(formatDiffComment).join('\n\n') } diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.ts b/src/renderer/src/lib/launch-agent-in-new-tab.ts index 717e2c072..79170f70d 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.ts @@ -28,6 +28,8 @@ export type LaunchAgentInNewTabArgs = { /** Telemetry surface that initiated this launch. Defaults to the tab-bar * quick-launch entry point so existing callers stay unchanged. */ launchSource?: LaunchSource + /** Called after the prompt is actually delivered to the agent input path. */ + onPromptDelivered?: () => void } export type LaunchAgentInNewTabResult = { @@ -59,7 +61,15 @@ export type LaunchAgentInNewTabResult = { * surface that as a launch failure (see `QuickLaunchButton.runLaunch`). */ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentInNewTabResult { - const { agent, worktreeId, groupId, prompt, promptDelivery = 'auto-submit', launchSource } = args + const { + agent, + worktreeId, + groupId, + prompt, + promptDelivery = 'auto-submit', + launchSource, + onPromptDelivered + } = args const store = useAppStore.getState() const cmdOverrides = store.settings?.agentCmdOverrides ?? {} const trimmedPrompt = prompt?.trim() ?? '' @@ -201,7 +211,13 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI agent_kind: tuiAgentToAgentKind(agent) }) } + }).then((delivered) => { + if (delivered) { + onPromptDelivered?.() + } }) + } else if (hasPrompt) { + onPromptDelivered?.() } // Why: match the `+` button's `createNewTerminalTab` sequence — without diff --git a/src/renderer/src/store/slices/diffComments.test.ts b/src/renderer/src/store/slices/diffComments.test.ts index af4a6cf68..7947af7a9 100644 --- a/src/renderer/src/store/slices/diffComments.test.ts +++ b/src/renderer/src/store/slices/diffComments.test.ts @@ -288,6 +288,7 @@ describe('updateDiffComment', () => { lineNumber: 10, body: 'old body', createdAt: 1000, + sentAt: 2000, side: 'modified' } seed(store, [original]) @@ -301,6 +302,7 @@ describe('updateDiffComment', () => { expect(saved.id).toBe('c1') expect(saved.lineNumber).toBe(10) expect(saved.createdAt).toBe(1000) + expect(saved.sentAt).toBeUndefined() expect(updateMeta).toHaveBeenCalledTimes(1) }) @@ -411,6 +413,59 @@ describe('updateDiffComment', () => { }) }) +describe('markDiffCommentsSent', () => { + beforeEach(() => { + vi.clearAllMocks() + clearRuntimeCompatibilityCacheForTests() + runtimeEnvironmentTransportCall.mockReset() + runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) + }) + updateMeta.mockResolvedValue({}) + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-1', + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + + it('marks selected notes as sent and persists once', async () => { + const store = createTestStore() + seed(store, [ + makeComment({ id: 'c1', filePath: 'src/foo.ts' }), + makeComment({ id: 'c2', filePath: 'src/bar.ts' }) + ]) + + const ok = await store.getState().markDiffCommentsSent(WT, ['c1'], 3000) + + expect(ok).toBe(true) + const saved = store.getState().getDiffComments(WT) + expect(saved[0]).toEqual(expect.objectContaining({ id: 'c1', sentAt: 3000 })) + expect(saved[1]).toEqual(expect.objectContaining({ id: 'c2' })) + expect(saved[1].sentAt).toBeUndefined() + expect(updateMeta).toHaveBeenCalledTimes(1) + expect(updateMeta).toHaveBeenCalledWith({ + worktreeId: WT, + updates: { + diffComments: [expect.objectContaining({ id: 'c1', sentAt: 3000 }), expect.any(Object)] + } + }) + }) + + it('returns success without persisting when no selected notes match', async () => { + const store = createTestStore() + const comments = [makeComment({ id: 'c1' })] + seed(store, comments) + + const ok = await store.getState().markDiffCommentsSent(WT, ['missing'], 3000) + + expect(ok).toBe(true) + expect(store.getState().getDiffComments(WT)).toBe(comments) + expect(updateMeta).not.toHaveBeenCalled() + }) +}) + describe('bulk clear diff comments', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/src/renderer/src/store/slices/diffComments.ts b/src/renderer/src/store/slices/diffComments.ts index 17c1fa9ad..80862b2e8 100644 --- a/src/renderer/src/store/slices/diffComments.ts +++ b/src/renderer/src/store/slices/diffComments.ts @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: this slice keeps optimistic note +mutation, rollback, persistence ordering, and sent-state transitions together +so every write follows the same queue and rollback invariants. */ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { DiffComment, Worktree } from '../../../../shared/types' @@ -9,6 +12,11 @@ export type DiffCommentsSlice = { getDiffComments: (worktreeId: string | null | undefined) => DiffComment[] addDiffComment: (input: Omit) => Promise updateDiffComment: (worktreeId: string, commentId: string, body: string) => Promise + markDiffCommentsSent: ( + worktreeId: string, + commentIds: readonly string[], + sentAt?: number + ) => Promise deleteDiffComment: (worktreeId: string, commentId: string) => Promise clearDiffComments: (worktreeId: string) => Promise clearDiffCommentsForFile: (worktreeId: string, filePath: string) => Promise @@ -34,6 +42,11 @@ function normalizeDiffComment(comment: DiffComment): DiffComment { typeof rawSelectedText === 'string' && rawSelectedText.trim().length > 0 ? rawSelectedText.trim() : undefined + const rawSentAt = (comment as { sentAt?: unknown }).sentAt + const sentAt = + typeof rawSentAt === 'number' && Number.isFinite(rawSentAt) && rawSentAt > 0 + ? rawSentAt + : undefined return { ...comment, @@ -42,7 +55,9 @@ function normalizeDiffComment(comment: DiffComment): DiffComment { ...(selectedText !== undefined ? { selectedText } : {}), ...(selectedText === undefined ? { selectedText: undefined } : {}), ...(startLine !== undefined ? { startLine } : {}), - ...(startLine === undefined ? { startLine: undefined } : {}) + ...(startLine === undefined ? { startLine: undefined } : {}), + ...(sentAt !== undefined ? { sentAt } : {}), + ...(sentAt === undefined ? { sentAt: undefined } : {}) } } @@ -288,7 +303,9 @@ export const createDiffCommentsSlice: StateCreator { + if (commentIds.length === 0) { + return true + } + const ids = new Set(commentIds) + const result = mutateComments(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 + }) + if (!result) { + return true + } + try { + await enqueuePersist(worktreeId, get) + return true + } catch (err) { + console.error('Failed to persist diff comments:', err) + rollback(set, worktreeId, result.previous, result.next) + return false + } + }, + deleteDiffComment: async (worktreeId, commentId) => { const result = mutateComments(set, worktreeId, (existing) => { const next = existing.filter((c) => c.id !== commentId) diff --git a/src/shared/types.ts b/src/shared/types.ts index 676d394c6..ce6d44709 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -289,6 +289,8 @@ export type DiffComment = { lineNumber: number body: string createdAt: number + /** Set after the note has been handed to an agent. Edits clear it. */ + sentAt?: number // Reserved for future "comments on the original side" — always 'modified' in v1. side: 'modified' } @@ -877,6 +879,8 @@ export type GitHubPRFile = { deletions: number /** GitHub marks files above its diff size limit as binary-like; we skip content fetches for these. */ isBinary: boolean + /** Modified-side line numbers that GitHub accepts for inline review comments. */ + reviewCommentLineNumbers?: number[] /** GitHub's per-viewer review state. DISMISSED means new changes arrived after the file was viewed. */ viewerViewedState?: GitHubPRFileViewedState }