open-swe/ui/src/components/agents/utils/diffUtils.ts

166 lines
5.4 KiB
TypeScript
Raw Normal View History

import { useMemo } from "react"
import { preloadHighlighter } from "@pierre/diffs"
feat: split view, add-to-chat, virtualization + scroll/grouping perf (#1574) * feat: reviews page split view, add-to-chat, virtualization + perf - Virtualize the diff (Pierre Virtualizer + worker pool), mirroring the agent chat panel, so large PRs window rows instead of materializing every line. - Split chat and diff into independent scroll containers and make chat auto-scroll fully contained, so typing/streaming no longer moves the diff. - Memoize FileDiffCard with stable callbacks so focusing a finding re-renders only the affected card. - Add a persisted unified/split diff toggle. - Add highlight-to-chat: select lines (drag / shift-click) + gutter "+" to drop a file:line snippet into the chat composer. - Rebuild sidebar group rows: whole card scrolls to the group (incl. the expanded explanation), Read explanation stays a separate toggle, memoized. * feat: add-to-chat uses attachment pills + selection popup / ⌘L Replace the raw-snippet injection with a Cursor-style flow: - Selecting lines shows a floating "Add to Chat ⌘L" popup at the pointer; ⌘L adds the current selection without it. Removes the auto-adding gutter "+". - "Add to chat" now creates a removable attachment pill in the composer (and a pill in the sent message bubble) instead of pasting raw text. The code is still serialized into the message content so the model receives it as context. * feat: restore gutter + drag-handle for line selection Re-enable Pierre's gutter '+' as a click-and-drag line selector (with the highlight growing as you drag) — the affordance that was lost when the auto-adding gutter button was removed. It no longer auto-adds: the commit flows through onLineSelected to the 'Add to Chat' popup / ⌘L. * fix: live selection highlight while dragging + reposition Add to Chat popup - Feed onLineSelectionChange into the controlled selection so rows highlight live as you drag, not just on release (Pierre only paints the controlled selection when the prop updates). Popup now fires on onLineSelectionEnd. - Anchor the popup's bottom-left to the drag handle (drop horizontal centering) so it no longer overlaps the '+' button. * fix: anchor Add to Chat popup to gutter handle + click-away to unselect - Position the popup from the gutter '+' handle's rect (in the diff shadow DOM, placed on the selection's bottom line) instead of the pointer-release point, which landed inconsistently. Falls back to the pointer if not found. - Clear the line selection (and popup) on any outside pointer-down. * fix: sidebar-collapse header overlap + PR review comments - Lift useSidebarLayout to AgentsShell (single source), share collapsed via context, and pad the reviews header left when the sidebar is collapsed so the fixed collapse toggle no longer overlaps the header content. - add-to-chat: collect each diff side separately so a selection that spans a deletion->addition no longer pastes wrong-file lines (PR comment). - chat: clear attachments after sending via a suggested prompt, so an attached snippet isn't silently resent on the next message (PR comment). * fix: anchored finding card positions to the right of the diff again The virtualization refactor moved the card inside the main-width Virtualizer scroller, so it clamped over the diff. Render it in the outer container as a viewport-fixed card clamped to window width (right gutter / over the side panel, like prod) and track the finding as the diff scrolls (rAF-throttled), hiding when the finding scrolls out of view.
2026-06-18 16:54:07 -07:00
import type {
VirtualFileMetrics,
WorkerInitializationRenderOptions,
WorkerPoolOptions,
} from "@pierre/diffs/react"
import { useResolvedTheme } from "@/lib/theme"
feat: split view, add-to-chat, virtualization + scroll/grouping perf (#1574) * feat: reviews page split view, add-to-chat, virtualization + perf - Virtualize the diff (Pierre Virtualizer + worker pool), mirroring the agent chat panel, so large PRs window rows instead of materializing every line. - Split chat and diff into independent scroll containers and make chat auto-scroll fully contained, so typing/streaming no longer moves the diff. - Memoize FileDiffCard with stable callbacks so focusing a finding re-renders only the affected card. - Add a persisted unified/split diff toggle. - Add highlight-to-chat: select lines (drag / shift-click) + gutter "+" to drop a file:line snippet into the chat composer. - Rebuild sidebar group rows: whole card scrolls to the group (incl. the expanded explanation), Read explanation stays a separate toggle, memoized. * feat: add-to-chat uses attachment pills + selection popup / ⌘L Replace the raw-snippet injection with a Cursor-style flow: - Selecting lines shows a floating "Add to Chat ⌘L" popup at the pointer; ⌘L adds the current selection without it. Removes the auto-adding gutter "+". - "Add to chat" now creates a removable attachment pill in the composer (and a pill in the sent message bubble) instead of pasting raw text. The code is still serialized into the message content so the model receives it as context. * feat: restore gutter + drag-handle for line selection Re-enable Pierre's gutter '+' as a click-and-drag line selector (with the highlight growing as you drag) — the affordance that was lost when the auto-adding gutter button was removed. It no longer auto-adds: the commit flows through onLineSelected to the 'Add to Chat' popup / ⌘L. * fix: live selection highlight while dragging + reposition Add to Chat popup - Feed onLineSelectionChange into the controlled selection so rows highlight live as you drag, not just on release (Pierre only paints the controlled selection when the prop updates). Popup now fires on onLineSelectionEnd. - Anchor the popup's bottom-left to the drag handle (drop horizontal centering) so it no longer overlaps the '+' button. * fix: anchor Add to Chat popup to gutter handle + click-away to unselect - Position the popup from the gutter '+' handle's rect (in the diff shadow DOM, placed on the selection's bottom line) instead of the pointer-release point, which landed inconsistently. Falls back to the pointer if not found. - Clear the line selection (and popup) on any outside pointer-down. * fix: sidebar-collapse header overlap + PR review comments - Lift useSidebarLayout to AgentsShell (single source), share collapsed via context, and pad the reviews header left when the sidebar is collapsed so the fixed collapse toggle no longer overlaps the header content. - add-to-chat: collect each diff side separately so a selection that spans a deletion->addition no longer pastes wrong-file lines (PR comment). - chat: clear attachments after sending via a suggested prompt, so an attached snippet isn't silently resent on the next message (PR comment). * fix: anchored finding card positions to the right of the diff again The virtualization refactor moved the card inside the main-width Virtualizer scroller, so it clamped over the diff. Render it in the outer container as a viewport-fixed card clamped to window width (right gutter / over the side panel, like prod) and track the finding as the diff scrolls (rAF-throttled), hiding when the finding scrolls out of view.
2026-06-18 16:54:07 -07:00
export type DiffStyle = "unified" | "split"
feat: add Agents chat UI for cloud threads (#1323) * feat(ui): add Agents chat UI ported from open-swe-app Introduce a Cursor-style Agents surface separate from the dashboard, with ported chat/diff components and mock thread data until LangGraph APIs land. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(dashboard): wire Agents UI to LangGraph thread APIs Add dashboard thread list/detail/run/message/stream endpoints with a LangGraph message adapter, dashboard OAuth auth for runs, and TanStack Query hooks replacing mock data. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(dashboard): single agent reply per turn in Agents UI Use UUID thread IDs LangGraph accepts, skip confirming_completion for dashboard threads, and merge adapter agent messages so duplicate bubbles do not render. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): polish Agents UI with floating prompt and layout cleanup Remove no-op chrome (git panel, headers, sidebar search), port CloudPromptBar from open-swe-app, and refine chat layout so messages scroll behind the input. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agent): patch deepagents reducer for None messages on checkpoint replay LangGraph thread state could 500 when cancelled runs left messages as None. Apply the reducer guard before graph import, fall back to metadata in the dashboard API, and adjust Agents prompt bar layout. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): unify sidebar user menu and clean up Agents UI navigation Extract SidebarUserMenu so the dashboard and Agents sidebars render the same profile button, drop the redundant Agents nav row in favor of the existing Back to Agents link, add the open-swe logo header to the Agents sidebar, flatten the New Agent button, and cap the home screen run list to keep the prompt input in view. * feat(ui): resizable/collapsible sidebar shared across dashboard and Agents Add a useSidebarLayout hook + SidebarFrame wrapper so both sidebars share a persisted width (default 260px, drag to resize, 200-420 range) and a collapse toggle that hides the panel and surfaces a floating reopen button. Also adds a DELETE /threads/{id} endpoint and an X-on- hover thread delete control in the Agents sidebar. * feat(ui): instant user message and busy indicator on Agents transition Stash submitted prompts in sessionStorage, pre-populate the new thread detail cache, and merge pending prompts into the rendered message list so the Agents page renders the user bubble plus the existing thinking spinner immediately instead of flashing a skeleton and "Agent is starting" while the run boots. * feat(ui): token-stream agent replies in the Agents thread view Opt the LangGraph runs into messages-tuple streaming and forward those events through the existing SSE channel. The frontend now applies AIMessageChunk deltas directly to the cached thread (cancelling any in-flight refetch first so optimistic tokens are not clobbered) and keeps positional pending prompts so the user bubble stays in the right place while the agent streams its reply. * fix(dashboard): await threads.join_stream before iterating threads.join_stream is async def returning an AsyncIterator, so it must be awaited before async for. The SSE endpoint was raising TypeError: 'async for' requires an object with __aiter__ method, got coroutine on every connection. * fix(dashboard): drop messages-tuple stream_mode that broke thinking-mode tool turns Setting stream_mode=["values","messages-tuple","updates"] on runs.create forces langchain_anthropic into streaming, and on the second model call (after tool execution) its serialized thinking blocks come back malformed, so Anthropic rejects the request with 'messages.1.content.0.thinking.thinking: Field required'. Revert to the default stream_mode so claude-opus thinking + tool use runs to completion. The frontend keeps the messages-event handler in place as a no-op fallback for when streaming is re-enabled. * feat(agents): per-thread model picker wired through to the run Add optional model_id/effort to the create-thread and send-message request bodies, forward them as agent_model_id/agent_effort in the LangGraph run configurable, and record the resolved choice in thread metadata so the UI can show the model the run is actually using. get_agent now picks the per-thread override last (highest priority over team default + profile override) and falls back gracefully when it is absent or unsupported. The frontend prompt bar becomes a controlled component fed by a shared useModelOptions hook (options + profile -> defaultSelection). AgentsHome seeds the picker from the user's profile default; the thread view seeds from the thread's recorded model/effort and lets each follow-up retarget the run. * refactor(ui): align Agents prompt bar layout with open-swe-app PromptBar Drop the absolute-positioned send button, restore the original px-4 py-3.5 min-h-[106px] flex-col container, and move the model picker into a mt-auto pt-2 footer row so the placeholder text and the model selector share the same horizontal padding. * chore: fix lint/format CI failures Remove unused imports and reformat two files flagged by ruff. * fix(tests): stop messages-reducer patch tests from polluting the suite Restore agent modules after reducer patch tests and import LangSmithSandbox from agent.server in proxy refresh tests so isinstance checks stay valid. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:15:59 -07:00
export const DIFF_UNSAFE_CSS = `
[data-diffs-header],
[data-diff],
[data-file],
[data-error-wrapper],
[data-virtualizer-buffer] {
--diffs-bg: var(--ui-panel) !important;
--diffs-light-bg: var(--ui-panel) !important;
--diffs-dark-bg: var(--ui-panel) !important;
--diffs-token-light-bg: transparent;
--diffs-token-dark-bg: transparent;
--diffs-bg-context-override: var(--ui-panel);
--diffs-bg-hover-override: var(--ui-panel-2);
--diffs-bg-separator-override: var(--ui-accent-bubble);
--diffs-bg-buffer-override: var(--ui-bg);
--diffs-bg-addition-override: color-mix(in srgb, var(--ui-panel) 80%, #22c55e);
--diffs-bg-addition-number-override: color-mix(in srgb, var(--ui-panel) 75%, #22c55e);
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--ui-panel) 70%, #22c55e);
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--ui-panel) 60%, #22c55e);
--diffs-bg-deletion-override: color-mix(in srgb, var(--ui-panel) 80%, #ef4444);
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--ui-panel) 75%, #ef4444);
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--ui-panel) 70%, #ef4444);
--diffs-bg-deletion-emphasis-override: color-mix(in srgb, var(--ui-panel) 60%, #ef4444);
--diffs-fg-number-override: var(--ui-text-dim);
--diffs-font-size: 12px;
--diffs-line-height: 1.5;
--diffs-font-family: "SF Mono", "Fira Code", "Cascadia Code", Menlo, Monaco, monospace;
background-color: var(--ui-panel) !important;
}
[data-file-info] {
background-color: var(--ui-accent-bubble) !important;
border-block-color: var(--ui-border) !important;
color: var(--ui-text) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: var(--ui-accent-bubble) !important;
border-bottom: 1px solid var(--ui-border) !important;
}
[data-separator] {
background-color: var(--ui-accent-bubble) !important;
color: var(--ui-text-dim) !important;
}
`
feat: add Agents chat UI for cloud threads (#1323) * feat(ui): add Agents chat UI ported from open-swe-app Introduce a Cursor-style Agents surface separate from the dashboard, with ported chat/diff components and mock thread data until LangGraph APIs land. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(dashboard): wire Agents UI to LangGraph thread APIs Add dashboard thread list/detail/run/message/stream endpoints with a LangGraph message adapter, dashboard OAuth auth for runs, and TanStack Query hooks replacing mock data. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(dashboard): single agent reply per turn in Agents UI Use UUID thread IDs LangGraph accepts, skip confirming_completion for dashboard threads, and merge adapter agent messages so duplicate bubbles do not render. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): polish Agents UI with floating prompt and layout cleanup Remove no-op chrome (git panel, headers, sidebar search), port CloudPromptBar from open-swe-app, and refine chat layout so messages scroll behind the input. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agent): patch deepagents reducer for None messages on checkpoint replay LangGraph thread state could 500 when cancelled runs left messages as None. Apply the reducer guard before graph import, fall back to metadata in the dashboard API, and adjust Agents prompt bar layout. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): unify sidebar user menu and clean up Agents UI navigation Extract SidebarUserMenu so the dashboard and Agents sidebars render the same profile button, drop the redundant Agents nav row in favor of the existing Back to Agents link, add the open-swe logo header to the Agents sidebar, flatten the New Agent button, and cap the home screen run list to keep the prompt input in view. * feat(ui): resizable/collapsible sidebar shared across dashboard and Agents Add a useSidebarLayout hook + SidebarFrame wrapper so both sidebars share a persisted width (default 260px, drag to resize, 200-420 range) and a collapse toggle that hides the panel and surfaces a floating reopen button. Also adds a DELETE /threads/{id} endpoint and an X-on- hover thread delete control in the Agents sidebar. * feat(ui): instant user message and busy indicator on Agents transition Stash submitted prompts in sessionStorage, pre-populate the new thread detail cache, and merge pending prompts into the rendered message list so the Agents page renders the user bubble plus the existing thinking spinner immediately instead of flashing a skeleton and "Agent is starting" while the run boots. * feat(ui): token-stream agent replies in the Agents thread view Opt the LangGraph runs into messages-tuple streaming and forward those events through the existing SSE channel. The frontend now applies AIMessageChunk deltas directly to the cached thread (cancelling any in-flight refetch first so optimistic tokens are not clobbered) and keeps positional pending prompts so the user bubble stays in the right place while the agent streams its reply. * fix(dashboard): await threads.join_stream before iterating threads.join_stream is async def returning an AsyncIterator, so it must be awaited before async for. The SSE endpoint was raising TypeError: 'async for' requires an object with __aiter__ method, got coroutine on every connection. * fix(dashboard): drop messages-tuple stream_mode that broke thinking-mode tool turns Setting stream_mode=["values","messages-tuple","updates"] on runs.create forces langchain_anthropic into streaming, and on the second model call (after tool execution) its serialized thinking blocks come back malformed, so Anthropic rejects the request with 'messages.1.content.0.thinking.thinking: Field required'. Revert to the default stream_mode so claude-opus thinking + tool use runs to completion. The frontend keeps the messages-event handler in place as a no-op fallback for when streaming is re-enabled. * feat(agents): per-thread model picker wired through to the run Add optional model_id/effort to the create-thread and send-message request bodies, forward them as agent_model_id/agent_effort in the LangGraph run configurable, and record the resolved choice in thread metadata so the UI can show the model the run is actually using. get_agent now picks the per-thread override last (highest priority over team default + profile override) and falls back gracefully when it is absent or unsupported. The frontend prompt bar becomes a controlled component fed by a shared useModelOptions hook (options + profile -> defaultSelection). AgentsHome seeds the picker from the user's profile default; the thread view seeds from the thread's recorded model/effort and lets each follow-up retarget the run. * refactor(ui): align Agents prompt bar layout with open-swe-app PromptBar Drop the absolute-positioned send button, restore the original px-4 py-3.5 min-h-[106px] flex-col container, and move the model picker into a mt-auto pt-2 footer row so the placeholder text and the model selector share the same horizontal padding. * chore: fix lint/format CI failures Remove unused imports and reformat two files flagged by ruff. * fix(tests): stop messages-reducer patch tests from polluting the suite Restore agent modules after reducer patch tests and import LangSmithSandbox from agent.server in proxy refresh tests so isinstance checks stay valid. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:15:59 -07:00
export const diffOptions = {
theme: { light: "pierre-light", dark: "pierre-dark" } as const,
themeType: "system" as const,
feat: add Agents chat UI for cloud threads (#1323) * feat(ui): add Agents chat UI ported from open-swe-app Introduce a Cursor-style Agents surface separate from the dashboard, with ported chat/diff components and mock thread data until LangGraph APIs land. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(dashboard): wire Agents UI to LangGraph thread APIs Add dashboard thread list/detail/run/message/stream endpoints with a LangGraph message adapter, dashboard OAuth auth for runs, and TanStack Query hooks replacing mock data. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(dashboard): single agent reply per turn in Agents UI Use UUID thread IDs LangGraph accepts, skip confirming_completion for dashboard threads, and merge adapter agent messages so duplicate bubbles do not render. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): polish Agents UI with floating prompt and layout cleanup Remove no-op chrome (git panel, headers, sidebar search), port CloudPromptBar from open-swe-app, and refine chat layout so messages scroll behind the input. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agent): patch deepagents reducer for None messages on checkpoint replay LangGraph thread state could 500 when cancelled runs left messages as None. Apply the reducer guard before graph import, fall back to metadata in the dashboard API, and adjust Agents prompt bar layout. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ui): unify sidebar user menu and clean up Agents UI navigation Extract SidebarUserMenu so the dashboard and Agents sidebars render the same profile button, drop the redundant Agents nav row in favor of the existing Back to Agents link, add the open-swe logo header to the Agents sidebar, flatten the New Agent button, and cap the home screen run list to keep the prompt input in view. * feat(ui): resizable/collapsible sidebar shared across dashboard and Agents Add a useSidebarLayout hook + SidebarFrame wrapper so both sidebars share a persisted width (default 260px, drag to resize, 200-420 range) and a collapse toggle that hides the panel and surfaces a floating reopen button. Also adds a DELETE /threads/{id} endpoint and an X-on- hover thread delete control in the Agents sidebar. * feat(ui): instant user message and busy indicator on Agents transition Stash submitted prompts in sessionStorage, pre-populate the new thread detail cache, and merge pending prompts into the rendered message list so the Agents page renders the user bubble plus the existing thinking spinner immediately instead of flashing a skeleton and "Agent is starting" while the run boots. * feat(ui): token-stream agent replies in the Agents thread view Opt the LangGraph runs into messages-tuple streaming and forward those events through the existing SSE channel. The frontend now applies AIMessageChunk deltas directly to the cached thread (cancelling any in-flight refetch first so optimistic tokens are not clobbered) and keeps positional pending prompts so the user bubble stays in the right place while the agent streams its reply. * fix(dashboard): await threads.join_stream before iterating threads.join_stream is async def returning an AsyncIterator, so it must be awaited before async for. The SSE endpoint was raising TypeError: 'async for' requires an object with __aiter__ method, got coroutine on every connection. * fix(dashboard): drop messages-tuple stream_mode that broke thinking-mode tool turns Setting stream_mode=["values","messages-tuple","updates"] on runs.create forces langchain_anthropic into streaming, and on the second model call (after tool execution) its serialized thinking blocks come back malformed, so Anthropic rejects the request with 'messages.1.content.0.thinking.thinking: Field required'. Revert to the default stream_mode so claude-opus thinking + tool use runs to completion. The frontend keeps the messages-event handler in place as a no-op fallback for when streaming is re-enabled. * feat(agents): per-thread model picker wired through to the run Add optional model_id/effort to the create-thread and send-message request bodies, forward them as agent_model_id/agent_effort in the LangGraph run configurable, and record the resolved choice in thread metadata so the UI can show the model the run is actually using. get_agent now picks the per-thread override last (highest priority over team default + profile override) and falls back gracefully when it is absent or unsupported. The frontend prompt bar becomes a controlled component fed by a shared useModelOptions hook (options + profile -> defaultSelection). AgentsHome seeds the picker from the user's profile default; the thread view seeds from the thread's recorded model/effort and lets each follow-up retarget the run. * refactor(ui): align Agents prompt bar layout with open-swe-app PromptBar Drop the absolute-positioned send button, restore the original px-4 py-3.5 min-h-[106px] flex-col container, and move the model picker into a mt-auto pt-2 footer row so the placeholder text and the model selector share the same horizontal padding. * chore: fix lint/format CI failures Remove unused imports and reformat two files flagged by ruff. * fix(tests): stop messages-reducer patch tests from polluting the suite Restore agent modules after reducer patch tests and import LangSmithSandbox from agent.server in proxy refresh tests so isinstance checks stay valid. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:15:59 -07:00
diffStyle: "unified" as const,
overflow: "scroll" as const,
disableFileHeader: true,
unsafeCSS: DIFF_UNSAFE_CSS,
collapsedContextThreshold: 4,
lineDiffType: "word-alt" as const,
maxLineDiffLength: 800,
tokenizeMaxLineLength: 1200,
tokenizeMaxLength: 120_000,
}
feat: split view, add-to-chat, virtualization + scroll/grouping perf (#1574) * feat: reviews page split view, add-to-chat, virtualization + perf - Virtualize the diff (Pierre Virtualizer + worker pool), mirroring the agent chat panel, so large PRs window rows instead of materializing every line. - Split chat and diff into independent scroll containers and make chat auto-scroll fully contained, so typing/streaming no longer moves the diff. - Memoize FileDiffCard with stable callbacks so focusing a finding re-renders only the affected card. - Add a persisted unified/split diff toggle. - Add highlight-to-chat: select lines (drag / shift-click) + gutter "+" to drop a file:line snippet into the chat composer. - Rebuild sidebar group rows: whole card scrolls to the group (incl. the expanded explanation), Read explanation stays a separate toggle, memoized. * feat: add-to-chat uses attachment pills + selection popup / ⌘L Replace the raw-snippet injection with a Cursor-style flow: - Selecting lines shows a floating "Add to Chat ⌘L" popup at the pointer; ⌘L adds the current selection without it. Removes the auto-adding gutter "+". - "Add to chat" now creates a removable attachment pill in the composer (and a pill in the sent message bubble) instead of pasting raw text. The code is still serialized into the message content so the model receives it as context. * feat: restore gutter + drag-handle for line selection Re-enable Pierre's gutter '+' as a click-and-drag line selector (with the highlight growing as you drag) — the affordance that was lost when the auto-adding gutter button was removed. It no longer auto-adds: the commit flows through onLineSelected to the 'Add to Chat' popup / ⌘L. * fix: live selection highlight while dragging + reposition Add to Chat popup - Feed onLineSelectionChange into the controlled selection so rows highlight live as you drag, not just on release (Pierre only paints the controlled selection when the prop updates). Popup now fires on onLineSelectionEnd. - Anchor the popup's bottom-left to the drag handle (drop horizontal centering) so it no longer overlaps the '+' button. * fix: anchor Add to Chat popup to gutter handle + click-away to unselect - Position the popup from the gutter '+' handle's rect (in the diff shadow DOM, placed on the selection's bottom line) instead of the pointer-release point, which landed inconsistently. Falls back to the pointer if not found. - Clear the line selection (and popup) on any outside pointer-down. * fix: sidebar-collapse header overlap + PR review comments - Lift useSidebarLayout to AgentsShell (single source), share collapsed via context, and pad the reviews header left when the sidebar is collapsed so the fixed collapse toggle no longer overlaps the header content. - add-to-chat: collect each diff side separately so a selection that spans a deletion->addition no longer pastes wrong-file lines (PR comment). - chat: clear attachments after sending via a suggested prompt, so an attached snippet isn't silently resent on the next message (PR comment). * fix: anchored finding card positions to the right of the diff again The virtualization refactor moved the card inside the main-width Virtualizer scroller, so it clamped over the diff. Render it in the outer container as a viewport-fixed card clamped to window width (right gutter / over the side panel, like prod) and track the finding as the diff scrolls (rAF-throttled), hiding when the finding scrolls out of view.
2026-06-18 16:54:07 -07:00
export function useDiffOptions(diffStyle: DiffStyle = "unified") {
const resolvedTheme = useResolvedTheme()
return useMemo(
feat: split view, add-to-chat, virtualization + scroll/grouping perf (#1574) * feat: reviews page split view, add-to-chat, virtualization + perf - Virtualize the diff (Pierre Virtualizer + worker pool), mirroring the agent chat panel, so large PRs window rows instead of materializing every line. - Split chat and diff into independent scroll containers and make chat auto-scroll fully contained, so typing/streaming no longer moves the diff. - Memoize FileDiffCard with stable callbacks so focusing a finding re-renders only the affected card. - Add a persisted unified/split diff toggle. - Add highlight-to-chat: select lines (drag / shift-click) + gutter "+" to drop a file:line snippet into the chat composer. - Rebuild sidebar group rows: whole card scrolls to the group (incl. the expanded explanation), Read explanation stays a separate toggle, memoized. * feat: add-to-chat uses attachment pills + selection popup / ⌘L Replace the raw-snippet injection with a Cursor-style flow: - Selecting lines shows a floating "Add to Chat ⌘L" popup at the pointer; ⌘L adds the current selection without it. Removes the auto-adding gutter "+". - "Add to chat" now creates a removable attachment pill in the composer (and a pill in the sent message bubble) instead of pasting raw text. The code is still serialized into the message content so the model receives it as context. * feat: restore gutter + drag-handle for line selection Re-enable Pierre's gutter '+' as a click-and-drag line selector (with the highlight growing as you drag) — the affordance that was lost when the auto-adding gutter button was removed. It no longer auto-adds: the commit flows through onLineSelected to the 'Add to Chat' popup / ⌘L. * fix: live selection highlight while dragging + reposition Add to Chat popup - Feed onLineSelectionChange into the controlled selection so rows highlight live as you drag, not just on release (Pierre only paints the controlled selection when the prop updates). Popup now fires on onLineSelectionEnd. - Anchor the popup's bottom-left to the drag handle (drop horizontal centering) so it no longer overlaps the '+' button. * fix: anchor Add to Chat popup to gutter handle + click-away to unselect - Position the popup from the gutter '+' handle's rect (in the diff shadow DOM, placed on the selection's bottom line) instead of the pointer-release point, which landed inconsistently. Falls back to the pointer if not found. - Clear the line selection (and popup) on any outside pointer-down. * fix: sidebar-collapse header overlap + PR review comments - Lift useSidebarLayout to AgentsShell (single source), share collapsed via context, and pad the reviews header left when the sidebar is collapsed so the fixed collapse toggle no longer overlaps the header content. - add-to-chat: collect each diff side separately so a selection that spans a deletion->addition no longer pastes wrong-file lines (PR comment). - chat: clear attachments after sending via a suggested prompt, so an attached snippet isn't silently resent on the next message (PR comment). * fix: anchored finding card positions to the right of the diff again The virtualization refactor moved the card inside the main-width Virtualizer scroller, so it clamped over the diff. Render it in the outer container as a viewport-fixed card clamped to window width (right gutter / over the side panel, like prod) and track the finding as the diff scrolls (rAF-throttled), hiding when the finding scrolls out of view.
2026-06-18 16:54:07 -07:00
() => ({ ...diffOptions, themeType: resolvedTheme, diffStyle }),
[resolvedTheme, diffStyle]
)
}
feat: split view, add-to-chat, virtualization + scroll/grouping perf (#1574) * feat: reviews page split view, add-to-chat, virtualization + perf - Virtualize the diff (Pierre Virtualizer + worker pool), mirroring the agent chat panel, so large PRs window rows instead of materializing every line. - Split chat and diff into independent scroll containers and make chat auto-scroll fully contained, so typing/streaming no longer moves the diff. - Memoize FileDiffCard with stable callbacks so focusing a finding re-renders only the affected card. - Add a persisted unified/split diff toggle. - Add highlight-to-chat: select lines (drag / shift-click) + gutter "+" to drop a file:line snippet into the chat composer. - Rebuild sidebar group rows: whole card scrolls to the group (incl. the expanded explanation), Read explanation stays a separate toggle, memoized. * feat: add-to-chat uses attachment pills + selection popup / ⌘L Replace the raw-snippet injection with a Cursor-style flow: - Selecting lines shows a floating "Add to Chat ⌘L" popup at the pointer; ⌘L adds the current selection without it. Removes the auto-adding gutter "+". - "Add to chat" now creates a removable attachment pill in the composer (and a pill in the sent message bubble) instead of pasting raw text. The code is still serialized into the message content so the model receives it as context. * feat: restore gutter + drag-handle for line selection Re-enable Pierre's gutter '+' as a click-and-drag line selector (with the highlight growing as you drag) — the affordance that was lost when the auto-adding gutter button was removed. It no longer auto-adds: the commit flows through onLineSelected to the 'Add to Chat' popup / ⌘L. * fix: live selection highlight while dragging + reposition Add to Chat popup - Feed onLineSelectionChange into the controlled selection so rows highlight live as you drag, not just on release (Pierre only paints the controlled selection when the prop updates). Popup now fires on onLineSelectionEnd. - Anchor the popup's bottom-left to the drag handle (drop horizontal centering) so it no longer overlaps the '+' button. * fix: anchor Add to Chat popup to gutter handle + click-away to unselect - Position the popup from the gutter '+' handle's rect (in the diff shadow DOM, placed on the selection's bottom line) instead of the pointer-release point, which landed inconsistently. Falls back to the pointer if not found. - Clear the line selection (and popup) on any outside pointer-down. * fix: sidebar-collapse header overlap + PR review comments - Lift useSidebarLayout to AgentsShell (single source), share collapsed via context, and pad the reviews header left when the sidebar is collapsed so the fixed collapse toggle no longer overlaps the header content. - add-to-chat: collect each diff side separately so a selection that spans a deletion->addition no longer pastes wrong-file lines (PR comment). - chat: clear attachments after sending via a suggested prompt, so an attached snippet isn't silently resent on the next message (PR comment). * fix: anchored finding card positions to the right of the diff again The virtualization refactor moved the card inside the main-width Virtualizer scroller, so it clamped over the diff. Render it in the outer container as a viewport-fixed card clamped to window width (right gutter / over the side panel, like prod) and track the finding as the diff scrolls (rAF-throttled), hiding when the finding scrolls out of view.
2026-06-18 16:54:07 -07:00
// Shared virtualization + worker-pool config for <Virtualizer>/<MultiFileDiff>.
// Tuned for the agent git panel and the PR reviews page; keep them aligned so
// both viewers window rows and offload highlighting identically.
export const DIFF_VIRTUALIZER_CONFIG = {
overscrollSize: 1200,
intersectionObserverMargin: 4800,
}
export const DIFF_VIRTUAL_METRICS = {
hunkLineCount: 80,
lineHeight: 18,
diffHeaderHeight: 0,
spacing: 8,
} satisfies Partial<VirtualFileMetrics>
export const DIFF_WORKER_POOL_OPTIONS = {
workerFactory: () =>
new Worker(
new URL("@pierre/diffs/worker/worker-portable.js", import.meta.url),
{ type: "module" }
),
poolSize: 2,
totalASTLRUCacheSize: 120,
} satisfies WorkerPoolOptions
export const DIFF_WORKER_HIGHLIGHTER_OPTIONS = {
theme: { light: "pierre-light", dark: "pierre-dark" },
lineDiffType: "word-alt",
maxLineDiffLength: 800,
tokenizeMaxLineLength: 1200,
langs: ["text"],
} satisfies WorkerInitializationRenderOptions
function hashFileContents(contents: string): string {
let hash = 0x811c9dc5
for (let i = 0; i < contents.length; i++) {
hash ^= contents.charCodeAt(i)
hash = Math.imul(hash, 0x01000193)
}
return (hash >>> 0).toString(36)
}
// Stable per-file content key so the worker pool dedupes highlight work across
// re-renders instead of re-tokenizing identical content.
export function fileContentsCacheKey(
path: string,
side: "old" | "new",
contents: string
): string {
return `${path}:${side}:${contents.length}:${hashFileContents(contents)}`
}
let highlighterWarmup: Promise<void> | null = null
/**
* Pierre's <MultiFileDiff> renders an empty <diffs-container> on its first mount
* when the shared Shiki highlighter (specifically its themes) hasn't loaded yet:
* the cold-start render bails before painting and relies on an async repaint that
* can be dropped — most reliably under React StrictMode's mount/unmount/mount,
* which leaves a stale empty <pre> behind so the remounted instance no-ops.
*
* Warming the themes up-front makes that first render synchronous and non-empty.
* Idempotent and client-only (preloadHighlighter creates a Shiki instance).
*/
export function warmDiffHighlighter(): Promise<void> {
if (typeof window === "undefined") return Promise.resolve()
if (highlighterWarmup == null) {
highlighterWarmup = preloadHighlighter({
themes: [diffOptions.theme.light, diffOptions.theme.dark],
langs: ["text"],
}).catch((error) => {
highlighterWarmup = null
throw error
})
}
return highlighterWarmup
}