diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts index 25e5f9ce48..b61735f955 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts @@ -78,4 +78,68 @@ describe("review comment serialization", () => { ); expect(segments[2]).toEqual(expect.objectContaining({ kind: "text", text: "\nAfter" })); }); + + it("parses source-language review comments created by the web file viewer", () => { + const [segment] = parseReviewCommentMessageSegments( + [ + '', + "Clarify this.", + "```md", + "# Plan", + "- Step one", + "```", + "", + ].join("\n"), + ); + + expect(segment).toEqual( + expect.objectContaining({ + kind: "review-comment", + comment: expect.objectContaining({ + filePath: "docs/plan.md", + fenceLanguage: "md", + diff: "# Plan\n- Step one", + }), + }), + ); + }); + + it("keeps fenced examples in comment prose separate from the context fence", () => { + const [segment] = parseReviewCommentMessageSegments( + [ + '', + "Try this:", + "```ts", + "const value = 1;", + "```", + "Then retry.", + "```diff", + "@@ -0,0 +1,1 @@", + "+one", + "```", + "", + ].join("\n"), + ); + + expect(segment).toEqual( + expect.objectContaining({ + kind: "review-comment", + comment: expect.objectContaining({ + text: ["Try this:", "```ts", "const value = 1;", "```", "Then retry."].join("\n"), + diff: "@@ -0,0 +1,1 @@\n+one", + }), + }), + ); + }); + + it("round-trips greater-than signs in review attributes", () => { + const serialized = formatReviewCommentContext( + { ...makeTarget(), sectionTitle: "Changes > 5" }, + "Check this.", + ); + const [comment] = parseReviewInlineComments(serialized); + + expect(serialized).toContain('sectionTitle="Changes > 5"'); + expect(comment?.sectionTitle).toBe("Changes > 5"); + }); }); diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts index 09e1927d17..5e6e1c3683 100644 --- a/apps/mobile/src/features/review/reviewCommentSelection.ts +++ b/apps/mobile/src/features/review/reviewCommentSelection.ts @@ -21,6 +21,7 @@ export interface ReviewInlineComment { readonly rangeLabel: string; readonly text: string; readonly diff: string; + readonly fenceLanguage?: string; } export type ReviewCommentMessageSegment = @@ -38,6 +39,7 @@ let currentTarget: ReviewCommentTarget | null = null; const listeners = new Set<() => void>(); const REVIEW_COMMENT_BLOCK_PATTERN = /]*)>\s*([\s\S]*?)<\/review_comment>/g; const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g; +const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g; function emitChange() { listeners.forEach((listener) => listener()); @@ -170,12 +172,17 @@ function formatReviewSelectedDiff(target: ReviewCommentTarget): string { } function escapeReviewCommentAttribute(value: string): string { - return value.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } function unescapeReviewCommentAttribute(value: string): string { return value .replace(/</g, "<") + .replace(/>/g, ">") .replace(/"/g, '"') .replace(/&/g, "&"); } @@ -195,15 +202,19 @@ function readNonNegativeInteger(value: string | undefined): number | null { return Number(value); } -function extractReviewCommentText(rawBody: string): string { - const fenceIndex = rawBody.indexOf("```diff"); - const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody; - return commentBody.trim(); -} - -function extractReviewCommentDiff(rawBody: string): string { - const match = rawBody.match(/```diff\s*\n([\s\S]*?)\n```/); - return match?.[1]?.trim() ?? ""; +function extractReviewCommentBody(rawBody: string): { + text: string; + language: string; + contents: string; +} { + const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN)); + const match = matches.at(-1); + const fenceIndex = match?.index; + return { + text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(), + language: match?.[2]?.trim() || "diff", + contents: match?.[3] ?? "", + }; } function parseReviewInlineComment( @@ -219,6 +230,7 @@ function parseReviewInlineComment( if (!filePath || !sectionId || startIndex === null || endIndex === null) { return null; } + const body = extractReviewCommentBody(rawBody); return { id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`, @@ -228,13 +240,20 @@ function parseReviewInlineComment( startIndex: Math.min(startIndex, endIndex), endIndex: Math.max(startIndex, endIndex), rangeLabel: attributes.rangeLabel?.trim() || "line", - text: extractReviewCommentText(rawBody), - diff: extractReviewCommentDiff(rawBody), + text: body.text, + diff: body.contents, + fenceLanguage: body.language, }; } export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string { const rangeLabel = formatReviewSelectedRangeLabel(target); + const diff = formatReviewSelectedDiff(target); + const longestBacktickRun = Math.max( + 0, + ...Array.from(diff.matchAll(/`+/g), (match) => match[0].length), + ); + const fence = "`".repeat(Math.max(3, longestBacktickRun + 1)); return [ [ "", ].join(""), comment.trim(), - "```diff", - formatReviewSelectedDiff(target), - "```", + `${fence}diff`, + diff, + fence, "", ].join("\n"); } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index cb9d06230a..abb486cbbc 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1215,6 +1215,9 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: { }); function buildReviewCommentPatch(comment: ReviewInlineComment): string { + if ((comment.fenceLanguage ?? "diff") !== "diff") { + return ""; + } const diff = comment.diff.trim(); if (!diff) { return ""; diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx index be90ff8b47..23b84665c1 100644 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -77,6 +77,26 @@ describe("ChatMarkdown", () => { document.body.innerHTML = ""; }); + it("makes task-list checkboxes interactive when a change handler is provided", async () => { + const onTaskListChange = vi.fn(); + const screen = await render( + , + ); + + try { + const checkbox = page.getByRole("checkbox", { name: "Toggle task" }); + await expect.element(checkbox).not.toBeDisabled(); + await checkbox.click(); + expect(onTaskListChange).toHaveBeenCalledWith({ markerOffset: 2, checked: true }); + } finally { + await screen.unmount(); + } + }); + it("rewrites file uri hrefs into direct paths before rendering", async () => { const filePath = "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 9f51b5b41c..225e8e1dfc 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -98,6 +98,7 @@ interface ChatMarkdownProps { text: string; cwd: string | undefined; threadRef?: ScopedThreadRef | undefined; + onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined; isStreaming?: boolean; skills?: ReadonlyArray>; className?: string; @@ -115,6 +116,17 @@ const highlightedCodeCache = new LRUCache( MAX_HIGHLIGHT_CACHE_MEMORY_BYTES, ); const highlighterPromiseCache = new Map>(); + +function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} const CHAT_MARKDOWN_SANITIZE_SCHEMA = { ...defaultSchema, attributes: { @@ -1114,6 +1126,7 @@ function ChatMarkdown({ text, cwd, threadRef, + onTaskListChange, isStreaming = false, skills = EMPTY_MARKDOWN_SKILLS, className, @@ -1192,8 +1205,44 @@ function ChatMarkdown({ p({ node: _node, children, ...props }) { return

{renderSkillInlineMarkdownChildren(children, skills)}

; }, - li({ node: _node, children, ...props }) { - return
  • {renderSkillInlineMarkdownChildren(children, skills)}
  • ; + li({ node, children, ...props }) { + const listItemStart = node?.position?.start.offset; + const markerOffset = + typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null; + return ( +
  • + {renderSkillInlineMarkdownChildren(children, skills)} +
  • + ); + }, + input({ node: _node, type, checked, disabled: _disabled, ...props }) { + if (type !== "checkbox" || !onTaskListChange) { + return ( + + ); + } + return ( + { + const markerOffset = Number( + event.currentTarget.closest("li")?.dataset.taskMarkerOffset, + ); + if (!Number.isSafeInteger(markerOffset)) return; + onTaskListChange({ markerOffset, checked: event.currentTarget.checked }); + }} + /> + ); }, a({ node, href, children, ...props }) { const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; @@ -1337,11 +1386,13 @@ function ChatMarkdown({ fileLinkParentSuffixByPath, isStreaming, markdownFileLinkMetaByHref, + onTaskListChange, openInPreferredEditor, openExternalLinkInPreview, openMarkdownFileInPreview, resolvedTheme, skills, + text, threadRef, ], ); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b847288605..b416b8f3ec 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -153,6 +153,7 @@ import { formatElementContextLabel, } from "../lib/elementContext"; import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation"; +import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../reviewCommentContext"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions"; import { projectEnvironment } from "../state/projects"; @@ -1072,6 +1073,7 @@ function ChatViewContent(props: ChatViewProps) { const setComposerDraftPreviewAnnotations = useComposerDraftStore( (store) => store.setPreviewAnnotations, ); + const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments); const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection); const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); const setComposerDraftInteractionMode = useComposerDraftStore( @@ -2939,29 +2941,32 @@ function ChatViewContent(props: ChatViewProps) { threadKey === routeThreadKey ? null : routeThreadKey, ); }, [canMaximizeRightPanel, routeThreadKey]); - const closeRightPanelSurface = useCallback( - (surface: RightPanelSurface) => { + const cleanupRightPanelSurfaces = useCallback( + (surfaces: readonly RightPanelSurface[]) => { if (!activeThreadRef) return; - if (surface.kind === "preview" && surface.resourceId) { - usePreviewStateStore.getState().removeSession(activeThreadRef, surface.resourceId); - void closePreview({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, tabId: surface.resourceId }, - }).catch(() => undefined); - } - if (surface.kind === "terminal") { - for (const terminalId of surface.terminalIds) { - void closeTerminalMutation({ + + for (const surface of surfaces) { + if (surface.kind === "preview" && surface.resourceId) { + usePreviewStateStore.getState().removeSession(activeThreadRef, surface.resourceId); + void closePreview({ environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, + input: { threadId: activeThreadRef.threadId, tabId: surface.resourceId }, }).catch(() => undefined); } + if (surface.kind === "terminal") { + for (const terminalId of surface.terminalIds) { + void closeTerminalMutation({ + environmentId: activeThreadRef.environmentId, + input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, + }).catch(() => undefined); + } + } } - if (surface.kind === "plan") { + if (surfaces.some((surface) => surface.kind === "plan")) { closePlanSidebar(); } - useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id); - if (surface.kind === "diff" && diffOpen) { + + if (diffOpen && surfaces.some((surface) => surface.kind === "diff")) { void navigate({ to: "/$environmentId/$threadId", params: { environmentId, threadId }, @@ -2981,7 +2986,93 @@ function ChatViewContent(props: ChatViewProps) { threadId, ], ); + const syncActivePreviewSurface = useCallback(() => { + if (!activeThreadRef) return; + const nextActiveSurface = selectActiveRightPanelSurface( + useRightPanelStore.getState().byThreadKey, + activeThreadRef, + ); + if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) { + usePreviewStateStore.getState().setActiveTab(activeThreadRef, nextActiveSurface.resourceId); + } + }, [activeThreadRef]); + const closeRightPanelSurface = useCallback( + (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + cleanupRightPanelSurfaces([surface]); + useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id); + syncActivePreviewSurface(); + }, + [activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface], + ); + const closeOtherRightPanelSurfaces = useCallback( + (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id); + cleanupRightPanelSurfaces(surfaces); + useRightPanelStore.getState().closeOtherSurfaces(activeThreadRef, surface.id); + syncActivePreviewSurface(); + }, + [ + activeThreadRef, + cleanupRightPanelSurfaces, + rightPanelState.surfaces, + syncActivePreviewSurface, + ], + ); + const closeRightPanelSurfacesToRight = useCallback( + (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id); + if (surfaceIndex < 0) return; + const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1); + cleanupRightPanelSurfaces(surfaces); + useRightPanelStore.getState().closeSurfacesToRight(activeThreadRef, surface.id); + syncActivePreviewSurface(); + }, + [ + activeThreadRef, + cleanupRightPanelSurfaces, + rightPanelState.surfaces, + syncActivePreviewSurface, + ], + ); + const closeAllRightPanelSurfaces = useCallback(() => { + if (!activeThreadRef) return; + cleanupRightPanelSurfaces(rightPanelState.surfaces); + useRightPanelStore.getState().closeAllSurfaces(activeThreadRef); + }, [activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces]); + const copyRightPanelFilePath = useCallback((relativePath: string) => { + if (typeof window === "undefined" || !navigator.clipboard?.writeText) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy path", + description: "Clipboard API unavailable.", + }), + ); + return; + } + void navigator.clipboard.writeText(relativePath).then( + () => { + toastManager.add({ + type: "success", + title: "Path copied", + description: relativePath, + }); + }, + (error) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy path", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }, + ); + }, []); useEffect( () => subscribePreviewAction((action) => { @@ -2989,7 +3080,6 @@ function ChatViewContent(props: ChatViewProps) { }), [togglePreviewPanel], ); - const persistThreadSettingsForNextTurn = useCallback( async (input: { threadId: ThreadId; @@ -3482,6 +3572,7 @@ function ChatViewContent(props: ChatViewProps) { terminalContexts: composerTerminalContexts, elementContexts: composerElementContexts, previewAnnotations: composerPreviewAnnotations, + reviewComments: composerReviewComments, selectedProvider: ctxSelectedProvider, selectedModel: ctxSelectedModel, selectedProviderModels: ctxSelectedProviderModels, @@ -3498,7 +3589,10 @@ function ChatViewContent(props: ChatViewProps) { prompt: promptForSend, imageCount: composerImages.length, terminalContexts: composerTerminalContexts, - elementContextCount: composerElementContexts.length + composerPreviewAnnotations.length, + elementContextCount: + composerElementContexts.length + + composerPreviewAnnotations.length + + composerReviewComments.length, }); if (showPlanFollowUpPrompt && activeProposedPlan) { const followUp = resolvePlanFollowUpSubmission({ @@ -3518,7 +3612,8 @@ function ChatViewContent(props: ChatViewProps) { composerImages.length === 0 && sendableComposerTerminalContexts.length === 0 && composerElementContexts.length === 0 && - composerPreviewAnnotations.length === 0 + composerPreviewAnnotations.length === 0 && + composerReviewComments.length === 0 ? parseStandaloneComposerSlashCommand(trimmed) : null; if (standaloneSlashCommand) { @@ -3568,14 +3663,19 @@ function ChatViewContent(props: ChatViewProps) { const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; const composerElementContextsSnapshot = [...composerElementContexts]; const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations]; + const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments]; const messageTextWithContexts = appendElementContextsToPrompt( appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot), composerElementContextsSnapshot, ); - const messageTextForSend = composerPreviewAnnotationsSnapshot.reduce( + const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce( (text, annotation) => appendPreviewAnnotationPrompt(text, annotation), messageTextWithContexts, ); + const messageTextForSend = appendReviewCommentsToPrompt( + messageTextWithPreviewAnnotations, + composerReviewCommentsSnapshot, + ); const messageIdForSend = newMessageId(); const messageCreatedAt = new Date().toISOString(); const outgoingMessageText = formatOutgoingPrompt({ @@ -3749,6 +3849,8 @@ function ChatViewContent(props: ChatViewProps) { composerTerminalContextsRef.current.length === 0 && composerElementContextsRef.current.length === 0 && (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations + .length ?? 0) === 0 && + (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments .length ?? 0) === 0 ) { setOptimisticUserMessages((existing) => { @@ -3769,6 +3871,7 @@ function ChatViewContent(props: ChatViewProps) { setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot); setComposerDraftElementContexts(composerDraftTarget, composerElementContextsSnapshot); setComposerDraftPreviewAnnotations(composerDraftTarget, composerPreviewAnnotationsSnapshot); + setComposerDraftReviewComments(composerDraftTarget, composerReviewCommentsSnapshot); composerRef.current?.resetCursorState({ cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length), prompt: promptForSend, @@ -4713,6 +4816,10 @@ function ChatViewContent(props: ChatViewProps) { terminalLabelsById={activeTerminalLabelsById} onActivate={activateRightPanelSurface} onCloseSurface={closeRightPanelSurface} + onCloseOtherSurfaces={closeOtherRightPanelSurfaces} + onCloseSurfacesToRight={closeRightPanelSurfacesToRight} + onCloseAllSurfaces={closeAllRightPanelSurfaces} + onCopyFilePath={copyRightPanelFilePath} onAddBrowser={createBrowserSurface} onAddTerminal={addTerminalSurface} onAddDiff={addDiffSurface} @@ -4752,7 +4859,7 @@ function ChatViewContent(props: ChatViewProps) { ) : activeRightPanelSurface?.kind === "diff" ? ( - + ) : activeRightPanelSurface?.kind === "plan" ? ( @@ -4776,6 +4883,10 @@ function ChatViewContent(props: ChatViewProps) { environmentId={activeProject.environmentId} cwd={activeProject.workspaceRoot} projectName={activeProject.title} + threadRef={activeThreadRef} + composerDraftTarget={composerDraftTarget} + keybindings={keybindings} + availableEditors={availableEditors} relativePath={ activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath @@ -4799,6 +4910,10 @@ function ChatViewContent(props: ChatViewProps) { terminalLabelsById={activeTerminalLabelsById} onActivate={activateRightPanelSurface} onCloseSurface={closeRightPanelSurface} + onCloseOtherSurfaces={closeOtherRightPanelSurfaces} + onCloseSurfacesToRight={closeRightPanelSurfacesToRight} + onCloseAllSurfaces={closeAllRightPanelSurfaces} + onCopyFilePath={copyRightPanelFilePath} onAddBrowser={createBrowserSurface} onAddTerminal={addTerminalSurface} onAddDiff={addDiffSurface} @@ -4838,7 +4953,7 @@ function ChatViewContent(props: ChatViewProps) { ) : activeRightPanelSurface?.kind === "diff" ? ( - + ) : activeRightPanelSurface?.kind === "plan" ? ( @@ -4862,6 +4977,10 @@ function ChatViewContent(props: ChatViewProps) { environmentId={activeProject.environmentId} cwd={activeProject.workspaceRoot} projectName={activeProject.title} + threadRef={activeThreadRef} + composerDraftTarget={composerDraftTarget} + keybindings={keybindings} + availableEditors={availableEditors} relativePath={ activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 807ef82d2a..8981b3911d 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -1,7 +1,7 @@ -import { FileDiff, Virtualizer } from "@pierre/diffs/react"; +import { Virtualizer } from "@pierre/diffs/react"; import { useNavigate, useParams, useSearch } from "@tanstack/react-router"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import type { TurnId } from "@t3tools/contracts"; +import type { ScopedThreadRef, TurnId } from "@t3tools/contracts"; import { ChevronDownIcon, ChevronLeftIcon, @@ -20,6 +20,7 @@ import { useState, } from "react"; import { useOpenInPreferredEditor } from "../editorPreferences"; +import { type DraftId } from "../composerDraftStore"; import { useCheckpointDiff } from "~/lib/checkpointDiffState"; import { cn } from "~/lib/utils"; import { resolvePathLinkTarget } from "../terminal-links"; @@ -38,6 +39,7 @@ import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { useSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; +import { AnnotatableFileDiff } from "./diffs/AnnotatableFileDiff"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; @@ -112,11 +114,12 @@ const DIFF_PANEL_UNSAFE_CSS = ` interface DiffPanelProps { mode?: DiffPanelMode; + composerDraftTarget: ScopedThreadRef | DraftId; } export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; -export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { +export default function DiffPanel({ mode = "inline", composerDraftTarget }: DiffPanelProps) { const navigate = useNavigate(); const { resolvedTheme } = useTheme(); const settings = useSettings(); @@ -197,6 +200,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const selectedCheckpointTurnCount = selectedTurn && (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]); + const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : "conversation"; + const reviewSectionTitle = selectedTurn + ? `Turn ${selectedCheckpointTurnCount ?? "?"}` + : "All turns"; const selectedCheckpointRange = useMemo( () => typeof selectedCheckpointTurnCount === "number" @@ -618,8 +625,12 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { openDiffFile(filePath); }} > - ( + + } + /> + + {comment.text} + + + ); + })} + + ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index f1cf01d82b..3207876f70 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -300,6 +300,44 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain("</review_comment>"); }); + it("renders file review comments as source code instead of diffs", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + ', + "Clarify this.", + "```md", + "# Plan", + "- Step one", + "```", + "", + ].join("\n"), + turnId: null, + createdAt: "2026-03-17T19:12:28.000Z", + updatedAt: "2026-03-17T19:12:28.000Z", + streaming: false, + }, + }, + ]} + />, + ); + + expect(markup).toContain("plan.md"); + expect(markup).toContain("Clarify this."); + expect(markup).toContain("# Plan"); + expect(markup).not.toContain('data-testid="file-diff"'); + }); + it("renders a failure marker for failed tool lifecycle entries", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 515e32e0f3..b0d83be7b1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -102,6 +102,7 @@ import { SkillInlineText } from "./SkillInlineText"; import { formatWorkspaceRelativePath } from "../../filePathDisplay"; import { buildReviewCommentRenderablePatch, + formatReviewCommentFence, parseReviewCommentMessageSegments, type ReviewCommentContext, } from "../../reviewCommentContext"; @@ -1264,6 +1265,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) { const ctx = use(TimelineRowCtx); + const fenceLanguage = comment.fenceLanguage ?? "diff"; const renderablePatch = getRenderablePatch( buildReviewCommentRenderablePatch(comment), `review-comment:${comment.id}`, @@ -1284,6 +1286,15 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte )} + {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && ( + + )} {renderablePatch?.kind === "files" && renderablePatch.files.map((fileDiff) => ( ; openInCwd: string | null; + compact?: boolean; + enableShortcut?: boolean; }) { const openInEditorMutation = useAtomSet(shellEnvironment.openInEditor, { mode: "promise", @@ -195,6 +199,7 @@ export const OpenInPicker = memo(function OpenInPicker({ ); useEffect(() => { + if (!enableShortcut) return; const handler = (e: globalThis.KeyboardEvent) => { if (!isOpenFavoriteEditorShortcut(e, keybindings)) return; if (!openInCwd) return; @@ -211,24 +216,46 @@ export const OpenInPicker = memo(function OpenInPicker({ }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); - }, [environmentId, keybindings, openInCwd, openInEditorMutation, preferredEditor]); + }, [ + enableShortcut, + environmentId, + keybindings, + openInCwd, + openInEditorMutation, + preferredEditor, + ]); return ( - + - + - }> + + } + > diff --git a/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx b/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx new file mode 100644 index 0000000000..1f1bba90eb --- /dev/null +++ b/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx @@ -0,0 +1,122 @@ +import "../../index.css"; + +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; +import { render } from "vitest-browser-react"; + +import { useComposerDraftStore } from "~/composerDraftStore"; + +import { AnnotatableFileDiff } from "./AnnotatableFileDiff"; + +function dispatchPointer(target: EventTarget, type: string, pointerId: number): void { + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + cancelable: true, + composed: true, + pointerId, + pointerType: "mouse", + }), + ); +} + +const threadRef = scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread-1")); + +function TestDiff() { + const fileDiff = parsePatchFiles( + [ + "diff --git a/src/app.ts b/src/app.ts", + "--- a/src/app.ts", + "+++ b/src/app.ts", + "@@ -1,3 +1,3 @@", + " one", + "-two", + "+TWO", + " three", + ].join("\n"), + "annotatable-file-diff-test", + )[0]!.files[0]!; + + return ( + null} + options={{ + diffStyle: "unified", + lineDiffType: "none", + themeType: "light", + }} + /> + ); +} + +async function getRenderedDiff() { + return vi.waitFor(() => { + const element = document.querySelector("diffs-container"); + expect(element?.shadowRoot).not.toBeNull(); + return element!; + }); +} + +describe("annotatable Pierre file diff", () => { + afterEach(() => { + document.body.innerHTML = ""; + useComposerDraftStore.getState().setReviewComments(threadRef, []); + }); + + it("creates a local annotation from the gutter and attaches it to the composer", async () => { + let screen = await render(); + + try { + const diff = await getRenderedDiff(); + const addedLineNumber = await vi.waitFor(() => { + const elements = Array.from( + diff.shadowRoot?.querySelectorAll('[data-column-number="2"]') ?? [], + ); + const element = elements.at(-1) ?? null; + expect(element).not.toBeNull(); + return element!; + }); + + dispatchPointer(addedLineNumber, "pointerdown", 1); + dispatchPointer(addedLineNumber, "pointerup", 1); + + const textarea = page.getByRole("textbox", { name: "Comment on lines +2" }); + await expect.element(textarea).toBeVisible(); + await textarea.fill("Use the compatible value."); + await page.getByRole("button", { name: "Comment" }).click(); + + await vi.waitFor(() => { + expect( + useComposerDraftStore.getState().getComposerDraft(threadRef)?.reviewComments, + ).toEqual([ + expect.objectContaining({ + sectionId: "turn:2", + filePath: "src/app.ts", + rangeLabel: "+2", + text: "Use the compatible value.", + diff: "@@ -0,0 +2,1 @@\n+TWO", + }), + ]); + }); + expect(document.querySelector("[data-file-comment-annotation]")?.textContent).toContain( + "Use the compatible value.", + ); + + await screen.unmount(); + screen = await render(); + await expect + .element(page.getByText("Use the compatible value.", { exact: true })) + .toBeVisible(); + } finally { + await screen.unmount(); + } + }); +}); diff --git a/apps/web/src/components/diffs/AnnotatableFileDiff.tsx b/apps/web/src/components/diffs/AnnotatableFileDiff.tsx new file mode 100644 index 0000000000..ceb2f87785 --- /dev/null +++ b/apps/web/src/components/diffs/AnnotatableFileDiff.tsx @@ -0,0 +1,239 @@ +import type { + AnnotationSide, + DiffLineAnnotation, + FileDiffMetadata, + SelectedLineRange, +} from "@pierre/diffs"; +import { FileDiff, type FileDiffProps } from "@pierre/diffs/react"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useCallback, useMemo, useState, type ReactNode } from "react"; + +import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; +import { + buildDiffReviewComment, + restoreDiffReviewCommentRange, + type ReviewCommentContext, +} from "~/reviewCommentContext"; + +import { LocalCommentAnnotation } from "../files/LocalCommentAnnotation"; +import { nextFileCommentId } from "../files/fileCommentAnnotations"; + +interface DiffCommentAnnotationEntry { + id: string; + kind: "draft" | "comment"; + range: SelectedLineRange; + rangeLabel: string; + text: string; +} + +interface DiffCommentAnnotationGroup { + entries: DiffCommentAnnotationEntry[]; +} + +type DiffCommentLineAnnotation = DiffLineAnnotation; +const EMPTY_REVIEW_COMMENTS: ReadonlyArray = []; + +function annotationSide(range: SelectedLineRange): AnnotationSide { + return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions"; +} + +function appendAnnotationEntry( + annotations: ReadonlyArray, + range: SelectedLineRange, + entry: DiffCommentAnnotationEntry, +): DiffCommentLineAnnotation[] { + const side = annotationSide(range); + const annotationIndex = annotations.findIndex( + (annotation) => annotation.side === side && annotation.lineNumber === range.end, + ); + if (annotationIndex < 0) { + return [ + ...annotations, + { + side, + lineNumber: range.end, + metadata: { entries: [entry] }, + }, + ]; + } + return annotations.map((annotation, index) => + index === annotationIndex + ? { + ...annotation, + metadata: { entries: [...annotation.metadata.entries, entry] }, + } + : annotation, + ); +} + +interface AnnotatableFileDiffProps { + fileDiff: FileDiffMetadata; + filePath: string; + sectionId: string; + sectionTitle: string; + composerDraftTarget: ScopedThreadRef | DraftId; + options: FileDiffProps["options"]; + renderHeaderPrefix: (fileDiff: FileDiffMetadata) => ReactNode; +} + +export function AnnotatableFileDiff({ + fileDiff, + filePath, + sectionId, + sectionTitle, + composerDraftTarget, + options, + renderHeaderPrefix, +}: AnnotatableFileDiffProps) { + const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); + const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); + const reviewComments = useComposerDraftStore( + (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS, + ); + const [selectedRange, setSelectedRange] = useState(null); + const [draftAnnotation, setDraftAnnotation] = useState(null); + const persistedAnnotations = useMemo( + () => + reviewComments + .filter( + (comment) => + comment.sectionId === sectionId && + comment.filePath === filePath && + (comment.fenceLanguage ?? "diff") === "diff", + ) + .reduce((annotations, comment) => { + const range = restoreDiffReviewCommentRange(fileDiff, comment); + if (!range) return annotations; + return appendAnnotationEntry(annotations, range, { + id: comment.id, + kind: "comment", + range, + rangeLabel: comment.rangeLabel, + text: comment.text, + }); + }, []), + [fileDiff, filePath, reviewComments, sectionId], + ); + const lineAnnotations = useMemo( + () => (draftAnnotation ? [...persistedAnnotations, draftAnnotation] : persistedAnnotations), + [draftAnnotation, persistedAnnotations], + ); + + const removeAnnotationEntry = useCallback( + (entryId: string) => { + setSelectedRange(null); + if ( + draftAnnotation?.metadata.entries.some( + (entry) => entry.id === entryId && entry.kind === "draft", + ) + ) { + setDraftAnnotation(null); + return; + } + removeReviewComment(composerDraftTarget, entryId); + }, + [composerDraftTarget, draftAnnotation, removeReviewComment], + ); + + const submitAnnotationEntry = useCallback( + (entryId: string, text: string) => { + const entry = draftAnnotation?.metadata.entries.find((candidate) => candidate.id === entryId); + if (!entry) return; + + const comment = buildDiffReviewComment({ + id: entry.id, + sectionId, + sectionTitle, + filePath, + fileDiff, + range: entry.range, + text, + }); + if (comment) { + addReviewComment(composerDraftTarget, comment); + } + setSelectedRange(null); + setDraftAnnotation(null); + }, + [ + addReviewComment, + composerDraftTarget, + fileDiff, + filePath, + draftAnnotation, + sectionId, + sectionTitle, + ], + ); + + const beginComment = useCallback( + (range: SelectedLineRange) => { + const id = nextFileCommentId(); + const comment = buildDiffReviewComment({ + id, + sectionId, + sectionTitle, + filePath, + fileDiff, + range, + text: "", + }); + if (!comment) return; + + const draftEntry: DiffCommentAnnotationEntry = { + id, + kind: "draft", + range, + rangeLabel: comment.rangeLabel, + text: "", + }; + setDraftAnnotation({ + side: annotationSide(range), + lineNumber: range.end, + metadata: { entries: [draftEntry] }, + }); + }, + [fileDiff, filePath, sectionId, sectionTitle], + ); + + const hasOpenCommentForm = draftAnnotation !== null; + const handleLineSelectionEnd = useCallback( + (range: SelectedLineRange | null) => { + setSelectedRange(range); + if (range) beginComment(range); + }, + [beginComment], + ); + + return ( + + fileDiff={fileDiff} + renderHeaderPrefix={renderHeaderPrefix} + options={{ + ...options, + enableGutterUtility: !hasOpenCommentForm, + enableLineSelection: !hasOpenCommentForm, + onGutterUtilityClick: setSelectedRange, + onLineSelectionChange: setSelectedRange, + onLineSelectionEnd: handleLineSelectionEnd, + }} + selectedLines={selectedRange} + lineAnnotations={lineAnnotations} + renderAnnotation={(annotation) => ( +
    + {annotation.metadata.entries.map((entry) => ( + removeAnnotationEntry(entry.id)} + onComment={(text) => submitAnnotationEntry(entry.id, text)} + onDelete={() => removeAnnotationEntry(entry.id)} + /> + ))} +
    + )} + /> + ); +} diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.tsx new file mode 100644 index 0000000000..7886e99cba --- /dev/null +++ b/apps/web/src/components/files/FilePreviewPanel.browser.tsx @@ -0,0 +1,168 @@ +import "../../index.css"; + +import type { LineAnnotation, SelectedLineRange } from "@pierre/diffs"; +import { Editor } from "@pierre/diffs/editor"; +import { EditorProvider, File } from "@pierre/diffs/react"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; +import { render } from "vitest-browser-react"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import { installFileEditorDismissal } from "./fileEditorDismissal"; + +interface AnnotationMetadata { + label: string; +} + +function dispatchPointer(target: EventTarget, type: string, pointerId: number): void { + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + cancelable: true, + composed: true, + pointerId, + pointerType: "mouse", + }), + ); +} + +function EditableAnnotatedFile() { + const [selectedLines, setSelectedLines] = useState(null); + const [lineAnnotations, setLineAnnotations] = useState[]>([]); + const rootRef = useRef(null); + const editor = useMemo(() => new Editor(), []); + + useEffect(() => () => editor.cleanUp(), [editor]); + useEffect(() => { + const root = rootRef.current; + if (!root) return; + return installFileEditorDismissal({ + root, + editor, + isBlocked: () => false, + onDismiss: () => setSelectedLines(null), + }); + }, [editor]); + + return ( + <> +
    + + + file={{ name: "example.ts", contents: "one\ntwo\nthree\n" }} + options={{ + disableFileHeader: true, + enableGutterUtility: true, + enableLineSelection: true, + onGutterUtilityClick: setSelectedLines, + onLineSelectionChange: setSelectedLines, + onLineSelectionEnd: (range) => { + setSelectedLines(range); + if (range) { + setLineAnnotations([ + { + lineNumber: Math.max(range.start, range.end), + metadata: { label: `${range.start}:${range.end}` }, + }, + ]); + } + }, + }} + selectedLines={selectedLines} + lineAnnotations={lineAnnotations} + renderAnnotation={(annotation) => ( +
    + {annotation.metadata.label} +
    + )} + disableWorkerPool + contentEditable + /> +
    +
    + + + ); +} + +async function getEditableFile() { + const file = await vi.waitFor(() => { + const element = document.querySelector("diffs-container"); + expect(element?.shadowRoot).not.toBeNull(); + return element!; + }); + const content = await vi.waitFor(() => { + const element = file?.shadowRoot?.querySelector("[data-content]") ?? null; + expect(element).not.toBeNull(); + return element!; + }); + return { file, content }; +} + +describe("editable Pierre file annotations", () => { + afterEach(() => { + document.body.innerHTML = ""; + }); + + it("keeps gutter selection and annotations enabled while the file is editable", async () => { + const screen = await render(); + + try { + const { file, content } = await getEditableFile(); + const secondLineNumber = await vi.waitFor(() => { + const element = + file?.shadowRoot?.querySelector('[data-column-number="2"]') ?? null; + expect(element).not.toBeNull(); + return element; + }); + await vi.waitFor(() => { + expect( + file?.shadowRoot?.querySelector("pre")?.hasAttribute("data-interactive-line-numbers"), + ).toBe(true); + }); + + dispatchPointer(secondLineNumber!, "pointerdown", 1); + dispatchPointer(secondLineNumber!, "pointerup", 1); + + await vi.waitFor(() => { + expect(document.querySelector("[data-test-file-annotation]")?.textContent).toBe("2:2"); + }); + + expect(content.contentEditable).toBe("true"); + expect(content.getAttribute("role")).toBe("textbox"); + } finally { + await screen.unmount(); + } + }); + + it("dismisses editor focus and selection with outside click or Escape", async () => { + const screen = await render(); + + try { + const { file, content } = await getEditableFile(); + content.focus(); + expect(file?.shadowRoot?.activeElement).toBe(content); + + await page.getByRole("button", { name: "Outside file" }).click(); + await vi.waitFor(() => { + expect(file?.shadowRoot?.activeElement).not.toBe(content); + }); + + content.focus(); + expect(file?.shadowRoot?.activeElement).toBe(content); + content.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + cancelable: true, + composed: true, + }), + ); + await vi.waitFor(() => { + expect(file?.shadowRoot?.activeElement).not.toBe(content); + }); + } finally { + await screen.unmount(); + } + }); +}); diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts new file mode 100644 index 0000000000..3b5295f180 --- /dev/null +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + formatFileCommentRange, + normalizeFileCommentRange, + remapFileCommentAnnotations, +} from "./fileCommentAnnotations"; +import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode"; + +describe("file comment annotations", () => { + it("normalizes and formats selected line ranges", () => { + expect(normalizeFileCommentRange({ start: 16, end: 7 })).toEqual({ + startLine: 7, + endLine: 16, + }); + expect(formatFileCommentRange(7, 7)).toBe("L7"); + expect(formatFileCommentRange(7, 16)).toBe("L7 to L16"); + }); + + it("keeps an annotation range attached when Pierre remaps its anchor line", () => { + expect( + remapFileCommentAnnotations([ + { + lineNumber: 20, + metadata: { + entries: [ + { + id: "comment-1", + kind: "comment", + startLine: 7, + endLine: 16, + text: "Keep this guarded.", + }, + ], + }, + }, + ]), + ).toEqual([ + { + lineNumber: 20, + metadata: { + entries: [ + { + id: "comment-1", + kind: "comment", + startLine: 11, + endLine: 20, + text: "Keep this guarded.", + }, + ], + }, + }, + ]); + }); +}); + +describe("isMarkdownPreviewFile", () => { + it("recognizes markdown and MDX files case-insensitively", () => { + expect(isMarkdownPreviewFile("README.md")).toBe(true); + expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true); + }); + + it("does not treat other text files as markdown", () => { + expect(isMarkdownPreviewFile("docs/guide.txt")).toBe(false); + expect(isMarkdownPreviewFile("docs/markdown.ts")).toBe(false); + }); +}); + +describe("setMarkdownTaskChecked", () => { + const markdown = "- [ ] First\n- [x] Second\n"; + + it("checks and unchecks the task marker at the supplied offset", () => { + expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n"); + expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n"); + expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n"); + }); + + it("leaves the document unchanged for a stale or invalid marker offset", () => { + expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown); + expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown); + }); +}); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 7d88ccb16d..aa84b7402d 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -1,24 +1,54 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import type { + EditorId, + EnvironmentId, + ResolvedKeybindingsConfig, + ScopedThreadRef, +} from "@t3tools/contracts"; +import type { SelectedLineRange } from "@pierre/diffs"; import { Editor } from "@pierre/diffs/editor"; import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react"; -import { ChevronRight, FolderTree, LoaderCircle } from "lucide-react"; -import { useEffect, useMemo, useRef, useState } from "react"; import { useAtomSet } from "@effect/atom-react"; +import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; +import ChatMarkdown from "~/components/ChatMarkdown"; +import { OpenInPicker } from "~/components/chat/OpenInPicker"; import { useTheme } from "~/hooks/useTheme"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { cn } from "~/lib/utils"; +import { isPreviewSupportedInRuntime } from "~/previewStateStore"; +import { resolvePathLinkTarget } from "~/terminal-links"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Toggle } from "~/components/ui/toggle"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; +import { stackedThreadToast, toastManager } from "~/components/ui/toast"; +import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; +import { buildFileReviewComment } from "~/reviewCommentContext"; +import { assetEnvironment } from "~/state/assets"; +import { useEnvironmentHttpBaseUrl, usePrimaryEnvironmentId } from "~/state/environments"; +import { usePreviewActions } from "~/state/preview"; import { projectEnvironment } from "~/state/projects"; import FileBrowserPanel from "./FileBrowserPanel"; +import { + type FileCommentAnnotationEntry, + type FileCommentAnnotationGroup, + type FileCommentLineAnnotation, + formatFileCommentRange, + nextFileCommentId, + normalizeFileCommentRange, + remapFileCommentAnnotations, +} from "./fileCommentAnnotations"; +import { installFileEditorDismissal } from "./fileEditorDismissal"; +import { LocalCommentAnnotation } from "./LocalCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; import { fileBreadcrumbs } from "./filePath"; +import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode"; import { FileSaveCoordinator } from "./fileSaveCoordinator"; import { confirmProjectFileQueryData, + getOptimisticProjectFileQueryData, setProjectFileQueryData, useProjectFileQuery, } from "./projectFilesQueryState"; @@ -28,6 +58,10 @@ interface FilePreviewPanelProps { cwd: string; projectName: string; relativePath: string | null; + threadRef: ScopedThreadRef; + composerDraftTarget: ScopedThreadRef | DraftId; + keybindings: ResolvedKeybindingsConfig; + availableEditors: ReadonlyArray; onOpenFile: (relativePath: string) => void; onPendingChange: (relativePath: string, pending: boolean) => void; } @@ -39,21 +73,23 @@ interface EditableFileSurfaceProps { environmentId: EnvironmentId; cwd: string; relativePath: string; + composerDraftTarget: ScopedThreadRef | DraftId; contents: string; resolvedTheme: "light" | "dark"; onPendingChange: (relativePath: string, pending: boolean) => void; } -function EditableFileSurface({ +function useFileSaveCoordinator({ environmentId, cwd, relativePath, - contents, - resolvedTheme, onPendingChange, -}: EditableFileSurfaceProps) { +}: Pick< + EditableFileSurfaceProps, + "environmentId" | "cwd" | "relativePath" | "onPendingChange" +>): FileSaveCoordinator { const writeFile = useAtomSet(projectEnvironment.writeFile, { mode: "promise" }); - const saveCoordinator = useMemo( + const coordinator = useMemo( () => new FileSaveCoordinator({ debounceMs: FILE_SAVE_DEBOUNCE_MS, @@ -70,54 +106,270 @@ function EditableFileSurface({ }), [cwd, environmentId, onPendingChange, relativePath, writeFile], ); + + useEffect(() => () => coordinator.dispose(), [coordinator]); + return coordinator; +} + +function EditableFileSurface({ + environmentId, + cwd, + relativePath, + composerDraftTarget, + contents, + resolvedTheme, + onPendingChange, +}: EditableFileSurfaceProps) { + const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); + const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); + const [lineAnnotations, setLineAnnotations] = useState([]); + const [selectedRange, setSelectedRange] = useState(null); + const surfaceRef = useRef(null); + const saveCoordinator = useFileSaveCoordinator({ + environmentId, + cwd, + relativePath, + onPendingChange, + }); const editor = useMemo( () => - new Editor({ - onChange: (file) => { + new Editor({ + onChange: (file, nextLineAnnotations) => { setProjectFileQueryData(environmentId, cwd, relativePath, file.contents); saveCoordinator.change(file.contents); + if (nextLineAnnotations) { + const remapped = remapFileCommentAnnotations( + nextLineAnnotations as FileCommentLineAnnotation[], + ); + setLineAnnotations(remapped); + for (const annotation of remapped) { + for (const entry of annotation.metadata.entries) { + if (entry.kind !== "comment") continue; + addReviewComment( + composerDraftTarget, + buildFileReviewComment({ + id: entry.id, + filePath: relativePath, + startLine: entry.startLine, + endLine: entry.endLine, + text: entry.text, + contents: file.contents, + }), + ); + } + } + } }, }), - [cwd, environmentId, relativePath, saveCoordinator], + [addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator], ); useEffect( () => () => { editor.cleanUp(); - saveCoordinator.dispose(); }, - [editor, saveCoordinator], + [editor], + ); + + const removeAnnotationEntry = useCallback( + (entryId: string) => { + setSelectedRange(null); + removeReviewComment(composerDraftTarget, entryId); + setLineAnnotations((current) => { + return current.flatMap((annotation) => { + const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId); + return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : []; + }); + }); + }, + [composerDraftTarget, removeReviewComment], + ); + + const submitAnnotationEntry = useCallback( + (entryId: string, text: string) => { + setSelectedRange(null); + const entry = lineAnnotations + .flatMap((annotation) => annotation.metadata.entries) + .find((candidate) => candidate.id === entryId); + if (entry) { + addReviewComment( + composerDraftTarget, + buildFileReviewComment({ + id: entry.id, + filePath: relativePath, + startLine: entry.startLine, + endLine: entry.endLine, + text, + contents, + }), + ); + } + setLineAnnotations((current) => + current.map((annotation) => ({ + ...annotation, + metadata: { + entries: annotation.metadata.entries.map((annotationEntry) => + annotationEntry.id === entryId + ? { ...annotationEntry, kind: "comment", text } + : annotationEntry, + ), + }, + })), + ); + }, + [addReviewComment, composerDraftTarget, contents, lineAnnotations, relativePath], + ); + + const beginComment = useCallback((range: SelectedLineRange) => { + const { startLine, endLine } = normalizeFileCommentRange(range); + const draftEntry: FileCommentAnnotationEntry = { + id: nextFileCommentId(), + kind: "draft", + startLine, + endLine, + text: "", + }; + setLineAnnotations((current) => { + const withoutDraft = current.flatMap((annotation) => { + const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft"); + return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : []; + }); + const existingIndex = withoutDraft.findIndex( + (annotation) => annotation.lineNumber === endLine, + ); + if (existingIndex < 0) { + return [ + ...withoutDraft, + { + lineNumber: endLine, + metadata: { entries: [draftEntry] }, + }, + ]; + } + return withoutDraft.map((annotation, index) => + index === existingIndex + ? { + ...annotation, + metadata: { entries: [...annotation.metadata.entries, draftEntry] }, + } + : annotation, + ); + }); + }, []); + const hasOpenCommentForm = lineAnnotations.some((annotation) => + annotation.metadata.entries.some((entry) => entry.kind === "draft"), + ); + useEffect(() => { + const root = surfaceRef.current; + if (!root) return; + return installFileEditorDismissal({ + root, + editor, + isBlocked: () => hasOpenCommentForm, + onDismiss: () => setSelectedRange(null), + }); + }, [editor, hasOpenCommentForm]); + const handleLineSelectionEnd = useCallback( + (range: SelectedLineRange | null) => { + setSelectedRange(range); + if (range) { + beginComment(range); + } + }, + [beginComment], ); return ( - - + - + > + + file={{ + name: relativePath, + contents, + cacheKey: projectFileCacheKey(cwd, relativePath, contents), + }} + options={{ + disableFileHeader: true, + enableGutterUtility: !hasOpenCommentForm, + enableLineSelection: !hasOpenCommentForm, + onGutterUtilityClick: setSelectedRange, + onLineSelectionChange: setSelectedRange, + onLineSelectionEnd: handleLineSelectionEnd, + overflow: "scroll", + theme: resolveDiffThemeName(resolvedTheme), + themeType: resolvedTheme, + }} + selectedLines={selectedRange} + lineAnnotations={lineAnnotations} + renderAnnotation={(annotation) => ( +
    + {annotation.metadata.entries.map((entry) => ( + removeAnnotationEntry(entry.id)} + onComment={(text) => submitAnnotationEntry(entry.id, text)} + onDelete={() => removeAnnotationEntry(entry.id)} + /> + ))} +
    + )} + className="min-h-full" + contentEditable + /> +
    +
    ); } +function RenderedMarkdownSurface({ + environmentId, + cwd, + relativePath, + contents, + threadRef, + onPendingChange, +}: Omit & { + threadRef: ScopedThreadRef; +}) { + const saveCoordinator = useFileSaveCoordinator({ + environmentId, + cwd, + relativePath, + onPendingChange, + }); + + return ( + + { + const currentContents = + getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? + contents; + const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); + if (nextContents === currentContents) return; + setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); + saveCoordinator.change(nextContents); + }} + /> + + ); +} + function initialExplorerOpen(): boolean { try { return window.localStorage.getItem(FILE_EXPLORER_STORAGE_KEY) !== "false"; @@ -131,13 +383,27 @@ export default function FilePreviewPanel({ cwd, projectName, relativePath, + threadRef, + composerDraftTarget, + keybindings, + availableEditors, onOpenFile, onPendingChange, }: FilePreviewPanelProps) { const { resolvedTheme } = useTheme(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId); + const createAssetUrl = useAtomSet(assetEnvironment.createUrl, { mode: "promise" }); + const { open: openPreview } = usePreviewActions(); const file = useProjectFileQuery(environmentId, cwd, relativePath); const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); + const [renderedMarkdownPath, setRenderedMarkdownPath] = useState(null); const breadcrumbRef = useRef(null); + const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false; + const renderMarkdown = isMarkdown && renderedMarkdownPath === relativePath; + const canOpenInBrowser = + relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath); + const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null; const breadcrumbs = useMemo( () => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []), [projectName, relativePath], @@ -160,6 +426,25 @@ export default function FilePreviewPanel({ }); }; + const handleOpenInBrowser = useCallback(() => { + if (!absolutePath || !environmentHttpBaseUrl) return; + void openFileInPreview({ + threadRef, + filePath: absolutePath, + httpBaseUrl: environmentHttpBaseUrl, + createAssetUrl, + openPreview, + }).catch((error) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open file in browser", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }); + }, [absolutePath, createAssetUrl, environmentHttpBaseUrl, openPreview, threadRef]); + return (
    {relativePath ? ( @@ -196,6 +481,58 @@ export default function FilePreviewPanel({ ))}
    + {absolutePath && environmentId === primaryEnvironmentId ? ( + + ) : null} + {isMarkdown ? ( + + + setRenderedMarkdownPath(pressed ? relativePath : null) + } + aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"} + variant="ghost" + size="sm" + > + {renderMarkdown ? : } + + } + /> + + {renderMarkdown ? "Show markdown source" : "Show rendered markdown"} + + + ) : null} + {canOpenInBrowser ? ( + + + + + } + /> + Open file in preview browser + + ) : null} ) : relativePath && file.data ? ( - file.data.truncated ? ( + isMarkdown && renderMarkdown ? ( + + ) : file.data.truncated ? ( void; + onComment: (text: string) => void; + onDelete: () => void; +} + +export function LocalCommentAnnotation({ + kind, + rangeLabel, + text: savedText, + onCancel, + onComment, + onDelete, +}: LocalCommentAnnotationProps) { + const [text, setText] = useState(""); + + if (kind === "comment") { + return ( +
    event.stopPropagation()} + > +
    + + Local comment + {rangeLabel} + +
    +

    + {savedText} +

    +
    + ); + } + + return ( +
    event.stopPropagation()} + > +
    + + Local comment +
    +
    Comment on lines {rangeLabel}
    +