diff --git "a/piweb/hf-design.patch" "b/piweb/hf-design.patch" --- "a/piweb/hf-design.patch" +++ "b/piweb/hf-design.patch" @@ -1,18 +1,24 @@ diff --git a/AGENTS.md b/AGENTS.md -index a5c8983..108f6ca 100644 +index a5c8983..38cfb19 100644 --- a/AGENTS.md +++ b/AGENTS.md -@@ -138,6 +138,9 @@ lib/ +@@ -138,9 +138,13 @@ lib/ extension-ui-queue.ts FIFO queues for extension dialogs and custom panels, by request id; isBlockingExtensionUiRequest() (which method a run waits on) markdown.ts shared markdown helpers markdown-blocks.ts splitMarkdownBlocks(): where a streaming reply may be cut into blocks parsed apart +- highlight-queue.ts code fences past a task's highlight budget get their colors in idle slices +- prism-languages.ts loadPrismLanguages(): every Prism language in a chunk of its own, loaded when a highlighter first needs it + step-summary.ts a turn's steps counted by kind (ran, read, edited, …) for their one summary line above the answer -+ neutral-code-theme.ts the Prism themes (dark+, vs) with their blue tokens in neutral grays, keywords bold; Mermaid's neutral base theme ++ diffs-theme.ts the Shiki themes all code is highlighted with: dark+/light+ with their blue tokens in neutral grays, keywords bold ++ diff-patch.ts split diff rows (apply_patch, previews) as one unified patch for the diff viewer ++ mermaid-theme.ts Mermaid's neutral base theme + focus.ts rangeFill() for app/focus.css's slider track; keepTabInside() for aria-modal dialogs - highlight-queue.ts code fences past a task's highlight budget get their colors in idle slices - prism-languages.ts loadPrismLanguages(): every Prism language in a chunk of its own, loaded when a highlighter first needs it gfm-autolink-email-loader.cjs bundler loader: remark-gfm's email regex without a lookbehind literal -@@ -174,7 +177,8 @@ lib/ ++ pierre-diffs-split-loader.cjs bundler loader: @pierre/diffs' newline split without a lookbehind literal + node-cli.ts locate bundled npm-cli.js / npx-cli.js to spawn npm/npx without a shell (Windows) + npx.ts npx runner for skill install + plugin-updates.ts npm view update checks for /api/plugins/check +@@ -174,7 +178,8 @@ lib/ components/ AppShell.tsx layout, URL state, tab management SessionSidebar.tsx toolbar row (Sessions | Files tabs, or the Pi Web brand with the files below them; new, search): tree, archive, menus, toast; files section (resizable, foldable; one header row with the file keys and changed-files count, the picker's row) or tab (picker boxes + file buttons), FileExplorer @@ -22,7 +28,44 @@ index a5c8983..108f6ca 100644 SessionTree.tsx virtualized rows of the session tree and the archive view SidebarMenu.tsx sidebar popup menu (bottom sheet on phones), portaled to body: filter field, item secondary actions, the files tab's classic look ProjectWorktreePicker.tsx project and worktree boxes + menus: the files' (one row below the sessions, stacked in the tab) and the new-session bar's -@@ -274,3 +278,27 @@ Location: `~/.pi/agent/sessions//_.jsonl` +@@ -189,6 +194,10 @@ components/ + BranchNavigator.tsx in-session branch switcher + ChatMinimap.tsx scroll minimap beside the message list + MarkdownBody.tsx markdown renderer ++ highlighting.ts the one code-highlighting stack: @pierre/diffs + Shiki (JS engine) in two web workers, themes, metrics ++ CodeDiff.tsx diffs (an edit, apply_patch, the file viewer's Diff mode) ++ CodeFile.tsx all other code: fences, the file viewer's source, tool inputs and outputs ++ CodeLazy.tsx both, loaded on demand and warmed when idle; plain text until then + ModelsConfig.tsx Settings › Models: models.json editor + EnabledModelsSection.tsx model switches inside ModelsConfig (enabledModels) + OAuthPastePanel.tsx paste box for a sign-in's redirected address or code (Models, MCP) +@@ -221,7 +230,6 @@ hooks/ + useSidebarMotion.ts the sidebar's fold and archive-view motion: phase, end fallback, reduced motion, what shows meanwhile + useKeyboardShortcuts.ts Esc stops the running agent unless a field or nearer handler took it; Ctrl+Alt+N + useResizablePanel.ts drag/keyboard panel size kept per key; persistClamp: false never saves a short window's clamp +- usePrismLanguages.ts true once the Prism languages are loaded; starts the load for a highlighter + useTheme.ts theme state + ``` + +@@ -231,7 +239,7 @@ hooks/ + + Design decisions and traps live in `docs/agents/`, one note per area. Read every note whose files a change touches before making it. Add new notes to the area's file, not here. + +-- [sessions.md](docs/agents/sessions.md): AgentSession lifecycle and shutdown, fork vs in-session branching, the sidebar's on-disk Fork, session file rewrites, toolCall normalization, SSE reconnect and tool events, transcript system / usage / context-edit entries, running-state polling, custom-message collapsing, streamed chunks re-rendering only the reply, streaming markdown block by block, history caches (tool-result images, subagent runs, session views) and deferred code highlighting with Prism languages loaded on demand, the session sidebar (toolbar row and its brand, project groups, their order and display names, pins, archive, new-session project adoption, the files below the sessions or in a tab), the project/worktree bar above a fresh composer (the header: brand, then the bar) and what it carries across the remount, exported HTML, the extension status bar and its `command:` buttons. Files: `lib/rpc-manager.ts`, `lib/session-reader.ts`, `lib/session-fork*.ts`, `lib/session-delete.ts`, `lib/normalize.ts`, `lib/session-tree.ts`, `lib/session-ui-state*.ts`, `lib/sidebar-prefs.ts`, `lib/sidebar-actions.ts`, `lib/session-links.ts`, `lib/new-session-context.ts`, `hooks/useAgentSession.ts`, `hooks/useSessionUiState.ts`, `hooks/useSidebarMotion.ts`, `hooks/useGroupDrag.ts`, `hooks/useFilesPlacement.ts`, `hooks/useResizablePanel.ts`, `app/api/agent/**`, `app/api/sessions/**`, `components/SessionSidebar.tsx`, `components/PiWebTitle.tsx`, `components/SessionTree.tsx`, `components/SidebarMenu.tsx`, `components/SidebarToast.tsx`, `components/SidebarIcons.tsx`, `components/ProjectWorktreePicker.tsx`, `components/NewSessionContextBar.tsx`, `components/WorktreeCreateForm.tsx`, `handleNewSession`, `handleSelectSession` and the bar's handlers in `components/AppShell.tsx`, `components/BranchNavigator.tsx`, `components/MessageView.tsx`, `components/MarkdownBody.tsx`, `lib/markdown-blocks.ts`, `lib/streaming-message.ts`, `hooks/useStreamingSelector.ts`, `components/MermaidBlock.tsx`, `lib/highlight-queue.ts`, `lib/prism-languages.ts`, `hooks/usePrismLanguages.ts`, `lib/session-view-cache.ts`, `components/CodemodeToolView.tsx`, `components/ExtensionStatusBar.tsx`, `components/ExtensionWidgets.tsx`. ++- [sessions.md](docs/agents/sessions.md): AgentSession lifecycle and shutdown, fork vs in-session branching, the sidebar's on-disk Fork, session file rewrites, toolCall normalization, SSE reconnect and tool events, transcript system / usage / context-edit entries, running-state polling, custom-message collapsing, streamed chunks re-rendering only the reply, streaming markdown block by block, history caches (tool-result images, subagent runs, session views) and code highlighting (the one Shiki stack, `components/highlighting.ts`), the session sidebar (toolbar row and its brand, project groups, their order and display names, pins, archive, new-session project adoption, the files below the sessions or in a tab), the project/worktree bar above a fresh composer (the header: brand, then the bar) and what it carries across the remount, exported HTML, the extension status bar and its `command:` buttons. Files: `lib/rpc-manager.ts`, `lib/session-reader.ts`, `lib/session-fork*.ts`, `lib/session-delete.ts`, `lib/normalize.ts`, `lib/session-tree.ts`, `lib/session-ui-state*.ts`, `lib/sidebar-prefs.ts`, `lib/sidebar-actions.ts`, `lib/session-links.ts`, `lib/new-session-context.ts`, `hooks/useAgentSession.ts`, `hooks/useSessionUiState.ts`, `hooks/useSidebarMotion.ts`, `hooks/useGroupDrag.ts`, `hooks/useFilesPlacement.ts`, `hooks/useResizablePanel.ts`, `app/api/agent/**`, `app/api/sessions/**`, `components/SessionSidebar.tsx`, `components/PiWebTitle.tsx`, `components/SessionTree.tsx`, `components/SidebarMenu.tsx`, `components/SidebarToast.tsx`, `components/SidebarIcons.tsx`, `components/ProjectWorktreePicker.tsx`, `components/NewSessionContextBar.tsx`, `components/WorktreeCreateForm.tsx`, `handleNewSession`, `handleSelectSession` and the bar's handlers in `components/AppShell.tsx`, `components/BranchNavigator.tsx`, `components/MessageView.tsx`, `components/MarkdownBody.tsx`, `lib/markdown-blocks.ts`, `lib/streaming-message.ts`, `hooks/useStreamingSelector.ts`, `components/MermaidBlock.tsx`, `components/highlighting.ts`, `components/CodeFile.tsx`, `components/CodeDiff.tsx`, `components/CodeLazy.tsx`, `lib/session-view-cache.ts`, `components/CodemodeToolView.tsx`, `components/ExtensionStatusBar.tsx`, `components/ExtensionWidgets.tsx`. + - [tools.md](docs/agents/tools.md): tool presets and Chat only, exact system prompts, tool exposure, the codemode / tool-search / mcp built-ins, the read-only MCP policy, the Code mode and PowerShell `defaultTools` switches. Files: `lib/tool-presets.ts`, `lib/tool-preset-preference.ts`, `lib/chat-only.ts`, `lib/exact-system-prompt.ts`, `lib/builtin-extensions.ts`, `lib/mcp-read-only-policy.ts`, `lib/codemode-settings.ts`, `lib/powershell-settings.ts`, `lib/global-settings-file.ts`, `app/api/agent/new/route.ts`, `app/api/tools/settings/route.ts`, tool selection in `lib/rpc-manager.ts`. + - [mcp-runtime.md](docs/agents/mcp-runtime.md): the per-session MCP host (when servers register and connect, reported states, trust read on every sync, idle release); `/mcp` in the composer. Files: `lib/mcp-host.ts`, `lib/mcp-transport.ts`, `lib/mcp-status.ts`, `lib/mcp-command.ts`, `lib/mcp-config-key.ts`, MCP wiring in `lib/rpc-manager.ts` and `lib/builtin-extensions.ts`, `/mcp` handling in `hooks/useAgentSession.ts`. + - [mcp-settings.md](docs/agents/mcp-settings.md): Settings › MCP reads without running anything, masking, the trust dialog's server list, row states, notices, Code mode choice, trust from Settings, Escape stacking, every `mcp.json` write and undo. Files: `app/api/mcp/route.ts`, `app/api/project-trust/route.ts`, `lib/mcp-config-read.ts`, `lib/mcp-config-file.ts`, `lib/mcp-override.ts`, `lib/mcp-undo.ts`, `lib/mcp-secrets.ts`, `lib/mcp-server-display.ts`, `lib/mcp-json-error.ts`, `lib/project-trust.ts`, `lib/regular-file.ts`, `lib/stacked-dialog.ts`, `lib/settings-navigation.ts`, `components/McpConfig.tsx`, `components/mcp-config-helpers.ts`, `components/ProjectTrustDialog.tsx`, `components/SettingsPanel.tsx`. +@@ -248,7 +256,7 @@ Design decisions and traps live in `docs/agents/`, one note per area. Read every + ## Old Safari (iOS 16.2) + + - `/` renders entirely on the client, so one script chunk the browser cannot parse is a blank page. Next 16 targets Safari 16.4+; the `browserslist` in `package.json` lowers Safari and iOS to 16.2 so SWC turns class `static {}` blocks into private static fields. That covers Next's client runtime; other node_modules keep their syntax unless listed in `transpilePackages` (mermaid and `@mermaid-js/parser` are, for their lazy diagram chunks). Keep the other browserslist entries at Next's defaults. +-- Never write a RegExp lookbehind (`(?<=`, `(?/_.jsonl` --accent --user-bg --tool-bg --font-mono ``` @@ -45,7 +88,7 @@ index a5c8983..108f6ca 100644 +are styled there too. +`--accent` is a neutral gray in light and dark (no blue anywhere: links are told apart by their +underline, focus by a 2px ring), `--accent-soft` its tint; Mist, Rose and Pine keep their own hues. -+Code blocks and the file viewer use `lib/neutral-code-theme.ts`; the terminal keeps its ANSI hues. ++All code (fences, the file viewer, tool inputs and outputs, diffs) is highlighted by Shiki in `lib/diffs-theme.ts`'s neutral themes (`components/highlighting.ts`); the terminal keeps its ANSI hues. +Keyboard focus is `app/focus.css`, imported last: one 2px `--focus-ring` ring, inset on controls, +rows and fields (a row draws it on the row; its link or toggle draws nothing), 2px off ink-filled +controls and text links. Hidden row actions fold to width 0 (never `display: none`: Tab would drop @@ -3434,7 +3477,7 @@ index 0000000..8d003fe +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/globals.css b/app/globals.css -index d6b5535..e0f4e31 100644 +index d6b5535..609ed6e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -24,46 +24,109 @@ @@ -4185,7 +4228,26 @@ index d6b5535..e0f4e31 100644 background: var(--bg-panel); } .markdown-frontmatter-title { -@@ -2474,3 +2555,429 @@ span.token.table { +@@ -2114,18 +2195,6 @@ pre, code { + text-underline-offset: 2px; + } + +-/* syntax highlighter line numbers */ +-.markdown-body span.linenumber, +-span.linenumber { +- color: var(--text-dim) !important; +- font-style: normal !important; +-} +- +-/* Prism's markdown table tokens collide with Tailwind's display utility. */ +-span.token.table { +- display: inline; +-} +- + @keyframes drop-zone-in { + from { opacity: 0; transform: scale(0.97); } + to { opacity: 1; transform: scale(1); } +@@ -2474,3 +2543,475 @@ span.token.table { display: none !important; } } @@ -4482,17 +4544,18 @@ index d6b5535..e0f4e31 100644 + +/* A diff in a tool call (MessageView UnifiedFilesView): line number, mark, code; + added and removed lines tinted, no rules between them. */ -+/* The diff viewer (components/CodeDiff.tsx, @pierre/diffs): its shadow root reads these. The -+ design system's code type (text-code: 12px on 18px, ligatures off), Pi Web's canvas, the state -+ colours for additions and deletions, and a neutral "modified" (selection), never the library's blue. */ -+.code-diff { ++/* Pi Web's code and diff viewers (components/highlighting.ts: @pierre/diffs, Shiki): their shadow ++ roots read these. The design system's code type (text-code: 12px on 18px, ligatures off), the ++ surface they sit on (--code-bg), the state colours for additions and deletions, and a neutral ++ "modified" (selection), never the library's blue. */ ++.code-diff, ++.code-file { ++ --code-bg: var(--bg); + --diffs-font-family: var(--font-mono); + --diffs-header-font-family: var(--font-ui); + --diffs-font-size: calc(12px + var(--chat-font-size-offset, 0px)); + --diffs-line-height: 18px; + --diffs-font-features: "liga" 0, "calt" 0; -+ --diffs-light-bg: var(--bg); -+ --diffs-dark-bg: var(--bg); + --diffs-addition-color-override: var(--success); + --diffs-deletion-color-override: var(--danger); + --diffs-modified-color-override: var(--text-muted); @@ -4504,9 +4567,19 @@ index d6b5535..e0f4e31 100644 + --diffs-bg-deletion-emphasis-override: color-mix(in srgb, var(--danger) 26%, transparent); + min-width: 0; + padding-block: 6px; ++ background: var(--code-bg); ++ font-weight: var(--font-mono-weight); ++} ++/* The background goes on the viewer's host itself: its theme sets these two there (:host), which ++ beats a value inherited from the wrapper; a document rule on the host beats the :host rule. */ ++.code-diff diffs-container, ++.code-file diffs-container { ++ --diffs-light-bg: var(--code-bg); ++ --diffs-dark-bg: var(--code-bg); ++} ++.code-diff { + overflow: auto; + overscroll-behavior: contain; -+ font-weight: var(--font-mono-weight); +} +.code-diff-file + .code-diff-file { margin-top: 8px; } +.code-diff-path { @@ -4518,14 +4591,49 @@ index d6b5535..e0f4e31 100644 + text-overflow: ellipsis; + white-space: nowrap; +} -+/* A long diff renders the rows in view only: the virtualizer is its scroll box. */ -+.code-diff.is-virtual { overflow: visible; } -+.code-diff.is-fill { height: 100%; padding-block: 0; } -+.code-diff-scroll { overflow: auto; overscroll-behavior: contain; } ++/* A Markdown code fence: the tinted box Pi Web's code blocks have always had. */ ++.markdown-code-block .code-file { ++ --code-bg: color-mix(in srgb, var(--bg) 92%, var(--bg-panel)); ++ padding-block: 8px; ++} ++/* What a tool read, wrote or ran. */ ++.tool-code { --code-bg: var(--bg); } ++.tool-code-note { ++ padding: 4px 12px 8px; ++ background: var(--bg); ++ color: var(--text-dim); ++ font-family: var(--font-mono); ++ font-size: calc(11px + var(--chat-font-size-offset, 0px)); ++} ++/* The code before its viewer's script is here: the same text, box and type, no colours yet. */ ++.code-file.is-plain { ++ overflow: auto; ++ color: var(--text-muted); ++ font-family: var(--font-mono); ++ font-size: var(--diffs-font-size); ++ line-height: var(--diffs-line-height); ++} ++.code-file-plain { ++ margin: 0; ++ padding: 0 12px; ++ font: inherit; ++ white-space: pre-wrap; ++ overflow-wrap: anywhere; ++} ++.code-file.is-plain.is-scroll .code-file-plain { ++ white-space: pre; ++ overflow-wrap: normal; ++} ++/* Long code renders the rows in view only: a virtualizer is its scroll box, or the panel's. */ ++.code-diff.is-virtual, ++.code-file.is-virtual { overflow: visible; } ++.code-diff-scroll, ++.code-file-scroll { overflow: auto; overscroll-behavior: contain; } +/* While the viewer's script loads: a line's height, so the step does not jump. */ +.code-diff.is-loading { min-height: 30px; } +/* In the file viewer the panel scrolls, and code keeps its 12px whatever the chat's size. */ -+.code-diff.file-diff-view { ++.code-diff.file-diff-view, ++.code-file.file-source-view { + --diffs-font-size: 12px; + overflow: visible; +} @@ -8423,7 +8531,7 @@ index 2c78471..12d53ec 100644 {minimapHovered && allNodes.length > 0 && ( diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx -index 6c540a4..57ffd84 100644 +index 6c540a4..014fa8a 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -1,19 +1,20 @@ @@ -8747,7 +8855,20 @@ index 6c540a4..57ffd84 100644 ); } -@@ -1767,7 +1758,7 @@ function ExtensionDialog({ +@@ -1692,7 +1683,11 @@ function ExtensionDialog({ + let disposed = false; + const fit = () => { + if (disposed) return; +- const blocks = body.querySelectorAll("pre, .markdown-table-wrap"); ++ const blocks = [ ++ ...body.querySelectorAll("pre, .markdown-table-wrap"), ++ // Pi Web's code viewer (CodeFile) draws in a shadow root: the code that scrolls there. ++ ...Array.from(body.querySelectorAll("diffs-container"), (host) => [...(host.shadowRoot?.querySelectorAll("[data-code]") ?? [])]).flat(), ++ ]; + if (blocks.length === 0) return; + const needed = fitExtensionDialogWidth( + dialog.offsetWidth, +@@ -1767,7 +1762,7 @@ function ExtensionDialog({ width: "100%", padding: "10px 12px", border: "1px solid var(--border)", @@ -8756,7 +8877,7 @@ index 6c540a4..57ffd84 100644 background: "var(--bg)", boxShadow: "0 12px 32px rgba(0,0,0,0.18)", color: "var(--text)", -@@ -1806,7 +1797,7 @@ function ExtensionDialog({ +@@ -1806,7 +1801,7 @@ function ExtensionDialog({ display: "flex", flexDirection: "column", border: "1px solid var(--border)", @@ -8765,7 +8886,7 @@ index 6c540a4..57ffd84 100644 background: "var(--bg)", boxShadow: "0 20px 60px rgba(0,0,0,0.28)", overflow: "hidden", -@@ -1833,7 +1824,7 @@ function ExtensionDialog({ +@@ -1833,7 +1828,7 @@ function ExtensionDialog({ placeItems: "center", width: 28, height: 28, @@ -8774,7 +8895,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text-muted)", -@@ -1854,7 +1845,7 @@ function ExtensionDialog({ +@@ -1854,7 +1849,7 @@ function ExtensionDialog({ placeItems: "center", width: 28, height: 28, @@ -8783,7 +8904,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text-muted)", -@@ -1862,9 +1853,7 @@ function ExtensionDialog({ +@@ -1862,9 +1857,7 @@ function ExtensionDialog({ flexShrink: 0, }} > @@ -8794,7 +8915,7 @@ index 6c540a4..57ffd84 100644 -@@ -1911,7 +1900,7 @@ function ExtensionDialog({ +@@ -1911,7 +1904,7 @@ function ExtensionDialog({ style={{ width: "100%", padding: "9px 10px", @@ -8803,7 +8924,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text)", -@@ -1944,7 +1933,7 @@ function ExtensionDialog({ +@@ -1944,7 +1937,7 @@ function ExtensionDialog({ style={{ width: "100%", padding: "9px 10px", @@ -8812,7 +8933,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text)", -@@ -1965,7 +1954,7 @@ function ExtensionDialog({ +@@ -1965,7 +1958,7 @@ function ExtensionDialog({ width: "100%", minHeight: 220, padding: 10, @@ -8821,7 +8942,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text)", -@@ -1985,7 +1974,7 @@ function ExtensionDialog({ +@@ -1985,7 +1978,7 @@ function ExtensionDialog({ onClick={() => onRespond(request, { cancelled: true })} style={{ padding: "6px 10px", @@ -8830,7 +8951,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg)", color: "var(--text-muted)", -@@ -1999,7 +1988,7 @@ function ExtensionDialog({ +@@ -1999,7 +1992,7 @@ function ExtensionDialog({ onClick={submitValue} style={{ padding: "6px 10px", @@ -8839,7 +8960,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--accent)", background: "var(--accent)", color: "var(--accent-contrast)", -@@ -2013,7 +2002,7 @@ function ExtensionDialog({ +@@ -2013,7 +2006,7 @@ function ExtensionDialog({ onClick={submitValue} style={{ padding: "6px 10px", @@ -8848,7 +8969,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--accent)", background: "var(--accent)", color: "var(--accent-contrast)", -@@ -2080,7 +2069,7 @@ function ExtensionCustomPanel({ +@@ -2080,7 +2073,7 @@ function ExtensionCustomPanel({ width: "100%", padding: "10px 12px", border: "1px solid var(--border)", @@ -8857,7 +8978,7 @@ index 6c540a4..57ffd84 100644 background: "var(--bg)", boxShadow: "0 12px 32px rgba(0,0,0,0.18)", color: "var(--text)", -@@ -2122,7 +2111,7 @@ function ExtensionCustomPanel({ +@@ -2122,7 +2115,7 @@ function ExtensionCustomPanel({ display: "flex", flexDirection: "column", border: "1px solid var(--border)", @@ -8866,7 +8987,7 @@ index 6c540a4..57ffd84 100644 background: "var(--bg)", boxShadow: "0 20px 60px rgba(0,0,0,0.28)", overflow: "hidden", -@@ -2192,7 +2181,7 @@ function ExtensionCustomPanel({ +@@ -2192,7 +2185,7 @@ function ExtensionCustomPanel({ placeItems: "center", width: 28, height: 28, @@ -8875,7 +8996,7 @@ index 6c540a4..57ffd84 100644 border: "1px solid var(--border)", background: "var(--bg-panel)", color: "var(--text-muted)", -@@ -2200,15 +2189,13 @@ function ExtensionCustomPanel({ +@@ -2200,15 +2193,13 @@ function ExtensionCustomPanel({ flexShrink: 0, }} > @@ -8895,115 +9016,33 @@ index 6c540a4..57ffd84 100644 color: "var(--text-muted)", diff --git a/components/CodeDiff.tsx b/components/CodeDiff.tsx new file mode 100644 -index 0000000..0c690de +index 0000000..3d6da95 --- /dev/null +++ b/components/CodeDiff.tsx -@@ -0,0 +1,215 @@ +@@ -0,0 +1,133 @@ +"use client"; + -+import { useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; -+import { parsePatchFiles, registerCustomTheme, type FileDiffLoadedFiles, type ThemeRegistration } from "@pierre/diffs"; -+import { FileDiff, Virtualizer, WorkerPoolContext, type FileDiffMetadata, type FileDiffOptions, type VirtualFileMetrics } from "@pierre/diffs/react"; -+import { getOrCreateWorkerPoolSingleton, type WorkerPoolManager } from "@pierre/diffs/worker"; ++import { useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react"; ++import { parsePatchFiles, type FileDiffLoadedFiles } from "@pierre/diffs"; ++import { FileDiff, Virtualizer, VirtualizerContext, WorkerPoolContext, type FileDiffMetadata, type FileDiffOptions } from "@pierre/diffs/react"; +import { useTheme } from "@/hooks/useTheme"; -+import { DIFF_THEMES, neutralShikiTheme, type ShikiTheme } from "@/lib/diffs-theme"; +import { splitFilesToPatch } from "@/lib/diff-patch"; +import type { SplitDiffFile } from "@/lib/patch"; ++import { ++ RENDER, UNSAFE_CSS, VIRTUALIZE_AFTER_ROWS, VIRTUAL_METRICS, ++ codePool, hashText, keyboardExpanders, useScrollRootVirtualizer, ++} from "./highlighting"; + +/** -+ * Pi Web's diff viewer: @pierre/diffs (diffs.com), highlighted by Shiki with its JavaScript regex -+ * engine in a pool of web workers, in the design system's neutral themes (lib/diffs-theme.ts). -+ * Unified, one column of line numbers and +/- marks, as Claude Desktop shows edits; split once the -+ * viewer is 960px or wider. Inline changes are marked by word. Used for the agent's edits in the -+ * transcript and for a file's changes against HEAD in the file viewer. ++ * Pi Web's diff viewer (components/highlighting.ts has the stack): unified, one column of line ++ * numbers and +/- marks, as Claude Desktop shows edits; split once the viewer is 960px or wider. ++ * Inline changes are marked by word. Used for the agent's edits in the transcript and for a file's ++ * changes against HEAD in the file viewer. + */ + +/** Side by side only where both halves have room for code. */ +export const SPLIT_DIFF_MIN_WIDTH = 960; + -+// A diff longer than this renders only the rows in view (and a margin), so a big change does not -+// build tens of thousands of nodes at once; the estimates are the design system's metrics (an -+// 18px line, a 24px separator row, no file header). -+const VIRTUALIZE_AFTER_ROWS = 400; -+const VIRTUAL_METRICS: VirtualFileMetrics = { hunkLineCount: 50, lineHeight: 18, diffHeaderHeight: 0, hunkSeparatorHeight: 24, spacing: 8 }; -+ -+// Settings the worker pool renders with; the components get the same ones, so a pool render and a -+// main-thread render (before the pool is up, or without workers) look alike. -+const RENDER = { -+ theme: DIFF_THEMES, -+ preferredHighlighter: "shiki-js", -+ lineDiffType: "word-alt", -+ maxLineDiffLength: 1000, -+ // Minified and generated lines are left plain rather than tokenized. -+ tokenizeMaxLineLength: 1000, -+} as const; -+ -+let themesRegistered = false; -+function registerThemes() { -+ if (themesRegistered) return; -+ themesRegistered = true; -+ const load = (mode: "dark" | "light", source: () => Promise<{ default: unknown }>) => async () => -+ neutralShikiTheme((await source()).default as ShikiTheme, mode, DIFF_THEMES[mode]) as unknown as ThemeRegistration; -+ registerCustomTheme(DIFF_THEMES.dark, load("dark", () => import("@shikijs/themes/dark-plus"))); -+ registerCustomTheme(DIFF_THEMES.light, load("light", () => import("@shikijs/themes/light-plus"))); -+} -+ -+// One pool for the page, created by the first diff shown and kept: workers start only when a diff -+// is opened, and stay warm (grammars loaded) for the next one. -+let pool: WorkerPoolManager | null | undefined; -+function diffsPool(): WorkerPoolManager | undefined { -+ if (pool !== undefined) return pool ?? undefined; -+ registerThemes(); -+ if (typeof window === "undefined" || typeof Worker === "undefined") return undefined; -+ try { -+ pool = getOrCreateWorkerPoolSingleton({ -+ poolOptions: { -+ workerFactory: () => new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), { type: "module" }), -+ poolSize: Math.max(1, Math.min(2, (navigator.hardwareConcurrency || 2) - 1)), -+ }, -+ highlighterOptions: { ...RENDER, langs: [] }, -+ }); -+ } catch { -+ pool = null; -+ } -+ return pool ?? undefined; -+} -+ -+// Inside the viewer's shadow root. The library sets a token's weight and style through -+// light-dark(), which only takes colours, so a bold or italic token would stay regular: both -+// themes mark the same tokens, so the token's own declaration is enough. Keywords are 600, as in -+// Pi Web's other code. Separators ("13 unmodified lines") are a quiet 24px row in small type. -+const UNSAFE_CSS = ` -+[data-line] span[style*="font-weight:bold"] { font-weight: 600; } -+[data-line] span[style*="font-style:italic"] { font-style: italic; } -+[data-separator=line-info-basic] { height: 24px; } -+[data-separator-content] { font-size: 12px; } -+[data-expand-index] [data-separator-wrapper] { grid-template-columns: 28px auto; } -+[data-expand-button]:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; } -+`; -+ -+// The library's expand controls are role=button divs out of the tab order: give them a place in -+// it, a name and the keys a button has. -+const EXPAND_LABELS: Array<[string, string]> = [ -+ ["data-expand-up", "Show the lines above"], -+ ["data-expand-down", "Show the lines below"], -+ ["data-expand-both", "Show the unmodified lines"], -+]; -+function keyboardExpanders(host: HTMLElement) { -+ for (const button of host.shadowRoot?.querySelectorAll("[data-expand-button]") ?? []) { -+ if (button.dataset.keyboard !== undefined) continue; -+ button.dataset.keyboard = ""; -+ button.tabIndex = 0; -+ const label = EXPAND_LABELS.find(([attribute]) => button.hasAttribute(attribute))?.[1] ?? EXPAND_LABELS[2][1]; -+ button.setAttribute("aria-label", label); -+ button.addEventListener("keydown", (event) => { -+ if (event.key !== "Enter" && event.key !== " ") return; -+ event.preventDefault(); -+ button.click(); -+ }); -+ } -+} -+ +/** A unified patch, or Pi Web's split diff rows. */ +export type CodeDiffSource = { patch: string } | { files: SplitDiffFile[] }; + @@ -9016,7 +9055,7 @@ index 0000000..0c690de + maxHeight, + fallback = null, + loadFullFiles, -+ fill = false, ++ scrollRoot, + className, + style, +}: { @@ -9028,8 +9067,8 @@ index 0000000..0c690de + fallback?: ReactNode; + /** Given, the unchanged lines between hunks can be expanded; called on the first expansion. */ + loadFullFiles?: FullFilesLoader; -+ /** Fill the parent's height and scroll inside it (the file viewer's panel). */ -+ fill?: boolean; ++ /** The element that scrolls the diff (the file viewer's panel); without one, a long diff scrolls itself. */ ++ scrollRoot?: RefObject; + className?: string; + style?: CSSProperties; +}) { @@ -9047,7 +9086,7 @@ index 0000000..0c690de + }, []); + + const { files, lineNumbers } = useMemo(() => parseSource(source), [source]); -+ const workers = useMemo(() => diffsPool(), []); ++ const workers = useMemo(() => codePool(), []); + const options = useMemo>(() => ({ + ...RENDER, + themeType: isDark ? "dark" : "light", @@ -9071,22 +9110,32 @@ index 0000000..0c690de + } : undefined, + }), [isDark, wide, overflow, lineNumbers, loadFullFiles]); + -+ if (!files) return <>{fallback}; -+ const rows = files.reduce((total, file) => total + (wide ? file.splitLineCount : file.unifiedLineCount), 0); ++ const rows = files?.reduce((total, file) => total + (wide ? file.splitLineCount : file.unifiedLineCount), 0) ?? 0; + const virtual = rows > VIRTUALIZE_AFTER_ROWS; ++ const rootVirtualizer = useScrollRootVirtualizer(scrollRoot, ref, virtual && scrollRoot !== undefined); ++ ++ if (!files) return <>{fallback}; + const body = files.map((file, index) => ( +
+ {files.length > 1 &&
{file.name}
} + +
+ )); -+ const classes = `code-diff${fill ? " is-fill" : ""}${virtual ? " is-virtual" : ""}${className ? ` ${className}` : ""}`; ++ let content: ReactNode = body; ++ if (virtual && scrollRoot) { ++ // The panel scrolls: its virtualizer, once set up (a viewer takes it when it is created). ++ content = rootVirtualizer ? {body} : null; ++ } else if (virtual) { ++ content = {body}; ++ } + return ( + -+
-+ {virtual ? ( -+ {body} -+ ) : body} ++
++ {content} +
+ + ); @@ -9104,41 +9153,205 @@ index 0000000..0c690de + return { files: null, lineNumbers }; + } +} +diff --git a/components/CodeFile.tsx b/components/CodeFile.tsx +new file mode 100644 +index 0000000..0ca973e +--- /dev/null ++++ b/components/CodeFile.tsx +@@ -0,0 +1,112 @@ ++"use client"; + -+/** FNV-1a, 32 bits, hex: a cache key, not a checksum. */ -+function hashText(text: string): string { -+ let h = 0x811c9dc5; -+ for (let i = 0; i < text.length; i++) { -+ h ^= text.charCodeAt(i); -+ h = Math.imul(h, 0x01000193); ++import { useMemo, useRef, type CSSProperties, type ReactNode, type RefObject } from "react"; ++import type { FileContents, SupportedLanguages } from "@pierre/diffs"; ++import { File, Virtualizer, VirtualizerContext, WorkerPoolContext, type FileOptions } from "@pierre/diffs/react"; ++import { useTheme } from "@/hooks/useTheme"; ++import { ++ RENDER, UNSAFE_CSS, VIRTUALIZE_AFTER_ROWS, VIRTUAL_METRICS, ++ codeLanguage, codePool, hashText, useScrollRootVirtualizer, ++} from "./highlighting"; ++ ++/** Lines picked on the gutter's line numbers (a click, a drag, a shift-click). */ ++export interface CodeLineRange { ++ startLine: number; ++ endLine: number; ++} ++ ++export interface CodeFileProps { ++ code: string; ++ /** A code fence's language (aliases too: ts, py, sh); without one, inferred from `name`. */ ++ lang?: string; ++ /** The file the code is, for its language when `lang` is not given. */ ++ name?: string; ++ lineNumbers?: boolean; ++ /** Long lines wrap, or scroll sideways. */ ++ overflow?: "wrap" | "scroll"; ++ /** A height past which the code scrolls in its own box. */ ++ maxHeight?: number; ++ /** The element that scrolls the code (the file viewer's panel). */ ++ scrollRoot?: RefObject; ++ /** Lines can be picked on the gutter; called with the range, or null when it is cleared. */ ++ onSelectLines?: (range: CodeLineRange | null) => void; ++ className?: string; ++ style?: CSSProperties; ++} ++ ++/** ++ * Code as Pi Web shows it everywhere outside diffs: Markdown code blocks, the file viewer's source, ++ * the files a tool reads or writes, a codemode script, a tool's JSON. Highlighted by the stack in ++ * components/highlighting.ts (Shiki in web workers, the neutral dark+/light+ themes), plain text ++ * first and colours a moment later, never blocking the page. Longer than 400 lines, with a box ++ * that scrolls, only the lines in view are rendered. ++ */ ++export function CodeFile({ ++ code, ++ lang, ++ name, ++ lineNumbers = true, ++ overflow = "wrap", ++ maxHeight, ++ scrollRoot, ++ onSelectLines, ++ className, ++ style, ++}: CodeFileProps) { ++ const { isDark } = useTheme(); ++ const ref = useRef(null); ++ const file = useMemo(() => { ++ const language = lang !== undefined ? codeLanguage(lang) : undefined; ++ return { ++ name: name ?? "code", ++ contents: code, ++ lang: (language ?? (name ? undefined : "text")) as SupportedLanguages | undefined, ++ // Keyed by content and language, so the workers' result cache serves code shown again. ++ cacheKey: `pi-f-${hashText(code)}-${language ?? name ?? "text"}`, ++ }; ++ }, [code, lang, name]); ++ const workers = useMemo(() => codePool(), []); ++ const options = useMemo>(() => ({ ++ ...RENDER, ++ themeType: isDark ? "dark" : "light", ++ overflow, ++ disableFileHeader: true, ++ disableLineNumbers: !lineNumbers, ++ unsafeCSS: UNSAFE_CSS, ++ enableLineSelection: onSelectLines !== undefined, ++ onLineSelected: onSelectLines ++ ? (range) => onSelectLines(range ? { startLine: Math.min(range.start, range.end), endLine: Math.max(range.start, range.end) } : null) ++ : undefined, ++ }), [isDark, overflow, lineNumbers, onSelectLines]); ++ ++ const lines = useMemo(() => countLines(code), [code]); ++ const scrolls = scrollRoot !== undefined || maxHeight !== undefined; ++ const virtual = scrolls && lines > VIRTUALIZE_AFTER_ROWS; ++ const rootVirtualizer = useScrollRootVirtualizer(scrollRoot, ref, virtual && scrollRoot !== undefined); ++ ++ const view = ; ++ let content: ReactNode = view; ++ if (virtual && scrollRoot) { ++ // The panel scrolls: its virtualizer, once set up (a viewer takes it when it is created). ++ content = rootVirtualizer ? {view} : null; ++ } else if (virtual) { ++ content = {view}; + } -+ return (h >>> 0).toString(16) + text.length.toString(16); ++ return ( ++ ++
++ {content} ++
++
++ ); ++} ++ ++function countLines(text: string): number { ++ let count = 1; ++ for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) count++; ++ return count; +} -diff --git a/components/CodeDiffLazy.tsx b/components/CodeDiffLazy.tsx +diff --git a/components/CodeLazy.tsx b/components/CodeLazy.tsx new file mode 100644 -index 0000000..ca27152 +index 0000000..c94059e --- /dev/null -+++ b/components/CodeDiffLazy.tsx -@@ -0,0 +1,20 @@ ++++ b/components/CodeLazy.tsx +@@ -0,0 +1,76 @@ +"use client"; + -+import dynamic from "next/dynamic"; ++import { useEffect, useState, type CSSProperties } from "react"; ++import type { CodeDiff as CodeDiffView } from "./CodeDiff"; ++import type { CodeFile as CodeFileView, CodeFileProps } from "./CodeFile"; ++import { splitFilesToPatch } from "@/lib/diff-patch"; + +/** -+ * The diff viewer (CodeDiff: @pierre/diffs and Shiki's engine, about 1 MB of script) loaded on -+ * demand, so a page load without a diff does not pay for it. It is fetched once the page is idle, -+ * so the first diff opened does not wait for it either. ++ * The code and diff viewers (components/highlighting.ts: @pierre/diffs and Shiki, about 400 KB of ++ * script) loaded on demand, so a page load without code does not pay for them, and fetched once the ++ * page is idle, so the first code shown does not wait either. Until they are here (and if their ++ * chunk cannot load) code shows as plain text in the same box. + */ -+const load = () => import("./CodeDiff").then((module) => module.CodeDiff); ++type Viewers = { CodeDiff: typeof CodeDiffView; CodeFile: typeof CodeFileView }; + -+export const CodeDiff = dynamic(load, { -+ ssr: false, -+ loading: () =>
, -+}); ++let viewers: Viewers | null = null; ++let pending: Promise | null = null; ++function loadViewers(): Promise { ++ pending ??= import("./code-viewers").then((module) => (viewers = module)); ++ return pending; ++} + +if (typeof window !== "undefined") { + const whenIdle = window.requestIdleCallback ?? ((callback: () => void) => window.setTimeout(callback, 2000)); -+ whenIdle(() => void load()); ++ whenIdle(() => void loadViewers().catch(() => { pending = null; })); ++} ++ ++function useViewers(): { loaded: Viewers | null; failed: boolean } { ++ const [loaded, setLoaded] = useState(viewers); ++ const [failed, setFailed] = useState(false); ++ useEffect(() => { ++ if (loaded) return; ++ let live = true; ++ loadViewers().then( ++ (module) => { if (live) setLoaded(module); }, ++ () => { pending = null; if (live) setFailed(true); }, ++ ); ++ return () => { live = false; }; ++ }, [loaded]); ++ return { loaded, failed }; ++} ++ ++export function CodeFile(props: CodeFileProps) { ++ const { loaded } = useViewers(); ++ if (loaded) return ; ++ return ; ++} ++ ++export function CodeDiff(props: Parameters[0]) { ++ const { loaded, failed } = useViewers(); ++ if (loaded) return ; ++ if (failed) { ++ // No viewer (its script could not load): the patch as text. ++ const patch = "patch" in props.source ? props.source.patch : splitFilesToPatch(props.source.files).patch; ++ return ; ++ } ++ return
; ++} ++ ++/** ++ * The code before its viewer is here: the same text, box, type and wrapping (a dialog sizes itself ++ * to code that scrolls), no colours. ++ */ ++export function PlainCode({ code, overflow = "wrap", className, style, maxHeight }: { ++ code: string; ++ overflow?: "wrap" | "scroll"; ++ className?: string; ++ style?: CSSProperties; ++ maxHeight?: number; ++}) { ++ return ( ++
++
{code}
++
++ ); +} diff --git a/components/DirectoryPicker.tsx b/components/DirectoryPicker.tsx index 433cd89..344b0c2 100644 @@ -9653,20 +9866,121 @@ index b46d21a..8a8b640 100644 } export function FolderIcon({ size = 14, open = false }: IconProps & { open?: boolean }) { +diff --git a/components/FileViewer.state.test.mjs b/components/FileViewer.state.test.mjs +deleted file mode 100644 +index 3c33252..0000000 +--- a/components/FileViewer.state.test.mjs ++++ /dev/null +@@ -1,22 +0,0 @@ +-import assert from "node:assert/strict"; +-import { readFile } from "node:fs/promises"; +-import test from "node:test"; +-import React from "react"; +-import { renderToStaticMarkup } from "react-dom/server"; +-import reactSyntaxHighlighter from "react-syntax-highlighter"; +- +-const cssSource = await readFile(new URL("../app/globals.css", import.meta.url), "utf8"); +-const { Prism: SyntaxHighlighter } = reactSyntaxHighlighter; +- +-test("markdown table tokens stay inline despite Tailwind's table utility", () => { +- const html = renderToStaticMarkup( +- React.createElement( +- SyntaxHighlighter, +- { language: "markdown" }, +- "| Name | Desc |\n| --- | --- |\n| A | first |", +- ), +- ); +- +- assert.match(html, /class="token table[ "]/); +- assert.match(cssSource, /span\.token\.table\s*\{[^}]*display:\s*inline;/); +-}); +diff --git a/components/FileViewer.test.mjs b/components/FileViewer.test.mjs +index 1bb0712..38215d6 100644 +--- a/components/FileViewer.test.mjs ++++ b/components/FileViewer.test.mjs +@@ -1,51 +1,19 @@ + import assert from "node:assert/strict"; + import { readFile } from "node:fs/promises"; + import test from "node:test"; +-import React from "react"; + import ts from "typescript"; + + const source = await readFile(new URL("./FileViewer.tsx", import.meta.url), "utf8"); + +-test("lightweight source rows are skipped for highlighted, diff, and preview views", () => { +- // Execute the source-view calculations without mounting the file-fetching component. +- const file = ts.createSourceFile("FileViewer.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +- const viewer = file.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === "TextFileViewer"); +- const calculations = viewer.body.statements.filter((node) => +- ts.isVariableStatement(node) && node.declarationList.declarations.some((declaration) => +- ["isDelimitedTable", "viewerContent", "sourceLines", "language", "isHtml", "isMarkdown", "hasPreview", "effectiveDisplayMode", "useLightweightSource", "lightweightSourceLines"].includes(declaration.name.getText(file)), +- ), +- ).map((node) => node.getText(file)).join("\n"); +- const { outputText } = ts.transpileModule(` +- return (data, displayMode, hasGitDiff = false, isDeletedDiff = false, wrapLines = false, filePath = "/tmp/file.txt") => { +- const isDelimitedTablePath = (path) => /\\.(csv|tsv)$/i.test(path); +- const SOURCE_HIGHLIGHT_MAX_LINES = 1_000; +- const HTML_PREVIEW_MAX_BYTES = 10 * 1024 * 1024; +- const FILE_LINE_NUMBER_STYLE = {}; +- ${calculations} +- return lightweightSourceLines; +- }; +- `, { compilerOptions: { jsx: ts.JsxEmit.React } }); +- const render = new Function("React", "useMemo", outputText)(React, (calculate) => calculate()); +- const large = { content: "line\n".repeat(1_000), language: "text" }; +- +- assert.equal(render({ ...large, content: "line\n".repeat(999) }, "source"), null); +- assert.equal(render(large, "diff", true), null); +- assert.equal(render(large, "source", true, true), null); +- for (const language of ["html", "markdown"]) { +- assert.equal(render({ ...large, language }, "preview"), null); +- } +- // A CSV/TSV table previews a loaded prefix too; markdown waits for the whole file. +- assert.equal(render({ ...large, truncated: true }, "preview", false, false, false, "/tmp/data.csv"), null); +- assert.equal(render({ ...large, language: "markdown", truncated: true }, "preview").length, 1_001); +- // A partly loaded HTML file previews too: the preview fetches it whole. +- assert.equal(render({ ...large, language: "html", truncated: true, size: 900 * 1024 }, "preview"), null); +- for (const mode of ["source", "diff", "preview"]) { +- const rows = render(large, mode); +- assert.equal(rows.length, 1_001, `${mode} must retain its source fallback`); +- assert.equal(rows[0].props["data-line-number"], 1); +- assert.equal(rows[0].props.children[1].props.children, "line"); +- } +- assert.equal(render(large, "source", false, false, true)[0].props.children[1].props.style.whiteSpace, "pre-wrap"); ++test("the source view is the code viewer at every size, scrolled by the panel; no Prism, no plain fallback mode", () => { ++ // A long file is virtualized by the viewer (CodeFile, components/highlighting.ts) instead of ++ // falling back to unhighlighted rows past a line count. ++ const view = source.match(//)?.[0]; ++ assert.ok(view, "the source view renders CodeFile"); ++ assert.match(view, /scrollRoot=\{contentRef\}/); ++ assert.match(view, /overflow=\{wrapLines \? "wrap" : "scroll"\}/); ++ assert.match(view, /onSelectLines=\{selectSourceLines\}/); ++ assert.doesNotMatch(source, /react-syntax-highlighter|SyntaxHighlighter|useLightweightSource|SOURCE_HIGHLIGHT_MAX_LINES/); + }); + + test("partly loaded HTML previews up to the HTML cap; partly loaded markdown does not", () => { diff --git a/components/FileViewer.tsx b/components/FileViewer.tsx -index 9426211..42f0dac 100644 +index 9426211..f4da5f8 100644 --- a/components/FileViewer.tsx +++ b/components/FileViewer.tsx -@@ -6,6 +6,8 @@ import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light"; - import renderSyntaxNode from "react-syntax-highlighter/dist/esm/create-element"; - import { vs } from "react-syntax-highlighter/dist/cjs/styles/prism"; - import { vscDarkPlus } from "react-syntax-highlighter/dist/cjs/styles/prism"; -+import { neutralCodeTheme } from "@/lib/neutral-code-theme"; -+import { CodeDiff } from "./CodeDiffLazy"; +@@ -1,14 +1,8 @@ + "use client"; + +-import { useEffect, useState, useRef, useCallback, useMemo, type CSSProperties, type MouseEvent } from "react"; +-import type { SyntaxHighlighterProps } from "react-syntax-highlighter"; +-import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light"; +-import renderSyntaxNode from "react-syntax-highlighter/dist/esm/create-element"; +-import { vs } from "react-syntax-highlighter/dist/cjs/styles/prism"; +-import { vscDarkPlus } from "react-syntax-highlighter/dist/cjs/styles/prism"; ++import { useEffect, useState, useRef, useCallback, useMemo, type MouseEvent, type RefObject } from "react"; ++import { CodeDiff, CodeFile } from "./CodeLazy"; import ReactMarkdown from "react-markdown"; - import { useTheme } from "@/hooks/useTheme"; - import { usePrismLanguages } from "@/hooks/usePrismLanguages"; -@@ -26,7 +28,6 @@ import { CodeBlock, MermaidBlock } from "./MermaidBlock"; +-import { useTheme } from "@/hooks/useTheme"; +-import { usePrismLanguages } from "@/hooks/usePrismLanguages"; + import { + DOCX_PREVIEW_MAX_BYTES, + HTML_PREVIEW_MAX_BYTES, +@@ -26,7 +20,6 @@ import { CodeBlock, MermaidBlock } from "./MermaidBlock"; import { DelimitedTable } from "./DelimitedTable"; import { isDelimitedTablePath } from "@/lib/delimited-table"; import { FrontmatterCard } from "./FrontmatterCard"; @@ -9674,7 +9988,7 @@ index 9426211..42f0dac 100644 import type { GitFileDiffResponse } from "@/lib/git-types"; import { useI18n } from "@/hooks/useI18n"; import { -@@ -34,6 +35,8 @@ import { +@@ -34,6 +27,8 @@ import { type FileViewerDisplayMode as DisplayMode, type FileViewerState, } from "@/lib/file-viewer-state"; @@ -9683,52 +9997,64 @@ index 9426211..42f0dac 100644 export type { FileViewerState } from "@/lib/file-viewer-state"; -@@ -69,11 +72,16 @@ const DISPLAY_MODE_LABELS: Record = { +@@ -62,56 +57,12 @@ interface FileData { + truncated: boolean; + } + +-const SOURCE_HIGHLIGHT_MAX_LINES = 1_000; + const DISPLAY_MODE_LABELS: Record = { + source: "Source", + preview: "Preview", diff: "Diff", }; -+// Code in the file viewer (source, diff, large files): 12px on an 18px line, compact -+// and still easy to read; the line numbers keep the same 18px rhythm. -+const FILE_CODE_FONT_SIZE = 12; -+const FILE_CODE_LINE_HEIGHT = "18px"; -+ - const FILE_CODE_STYLE: CSSProperties = { - fontFamily: "var(--font-mono)", - fontWeight: "var(--font-mono-weight)", +-const FILE_CODE_STYLE: CSSProperties = { +- fontFamily: "var(--font-mono)", +- fontWeight: "var(--font-mono-weight)", - fontSize: 13, - lineHeight: 1.6, -+ fontSize: FILE_CODE_FONT_SIZE, -+ lineHeight: FILE_CODE_LINE_HEIGHT, - }; - - // Prism's light theme colors
 with backgroundColor, its dark theme with
-@@ -81,12 +89,14 @@ const FILE_CODE_STYLE: CSSProperties = {
- // dark theme's shorthand is dropped, as CodeBlock does: a theme switch then never
- // makes React remove one beside the other (it warned, and the view lost its
- // background).
+-};
+-
+-// Prism's light theme colors 
 with backgroundColor, its dark theme with
+-// the background shorthand. The source view sets backgroundColor itself and the
+-// dark theme's shorthand is dropped, as CodeBlock does: a theme switch then never
+-// makes React remove one beside the other (it warned, and the view lost its
+-// background).
 -const fileViewerDarkTheme = {
-+const fileViewerDarkTheme = neutralCodeTheme({
-   ...vscDarkPlus,
-   'pre[class*="language-"]': {
-     ...vscDarkPlus['pre[class*="language-"]'],
-   },
+-  ...vscDarkPlus,
+-  'pre[class*="language-"]': {
+-    ...vscDarkPlus['pre[class*="language-"]'],
+-  },
 -};
-+}, "dark");
-+// Both without blue: lib/neutral-code-theme.ts.
-+const fileViewerLightTheme = neutralCodeTheme(vs, "light");
- delete fileViewerDarkTheme['pre[class*="language-"]'].background;
- 
- const FILE_LINE_NUMBER_STYLE: CSSProperties = {
-@@ -102,7 +112,7 @@ const FILE_LINE_NUMBER_STYLE: CSSProperties = {
-   fontSize: 11,
-   fontStyle: "normal",
-   fontVariantNumeric: "tabular-nums",
+-delete fileViewerDarkTheme['pre[class*="language-"]'].background;
+-
+-const FILE_LINE_NUMBER_STYLE: CSSProperties = {
+-  width: 48,
+-  minWidth: 48,
+-  padding: "0 10px",
+-  textAlign: "right",
+-  color: "var(--text-dim)",
+-  background: "var(--bg-panel)",
+-  borderRight: "1px solid var(--border)",
+-  fontFamily: "var(--font-mono)",
+-  fontWeight: "var(--font-mono-weight)",
+-  fontSize: 11,
+-  fontStyle: "normal",
+-  fontVariantNumeric: "tabular-nums",
 -  lineHeight: "20.8px",
-+  lineHeight: FILE_CODE_LINE_HEIGHT,
-   userSelect: "none",
-   flexShrink: 0,
-   verticalAlign: "top",
-@@ -119,10 +129,7 @@ interface SelectedLineRange {
+-  userSelect: "none",
+-  flexShrink: 0,
+-  verticalAlign: "top",
+-};
+-
+-type SourceCodeRendererProps = Parameters>[0] & {
+-  wrapLines: boolean;
+-};
+-
+ interface SelectedLineRange {
+   startLine: number;
+   endLine: number;
+@@ -119,114 +70,70 @@ interface SelectedLineRange {
  
  function MentionIcon() {
    return (
@@ -9740,7 +10066,158 @@ index 9426211..42f0dac 100644
    );
  }
  
-@@ -252,196 +259,46 @@ function DownloadLink({ filePath, sourceSessionId }: { filePath: string; sourceS
++type BoundaryPoint = { node: Node; offset: number };
++
++/**
++ * Where a text selection starts and ends inside the source view's code (CodeFile renders it in a
++ * shadow root, so the document's own selection does not reach its lines). Selection.getComposedRanges
++ * where the browser has it, else Chrome's ShadowRoot.getSelection().
++ */
++function selectionInShadow(selection: Selection, shadow: ShadowRoot): { start: BoundaryPoint; end: BoundaryPoint } | null {
++  const composed = (selection as Selection & { getComposedRanges?: (...args: unknown[]) => StaticRange[] }).getComposedRanges;
++  let range: StaticRange | AbstractRange | undefined;
++  if (typeof composed === "function") {
++    try {
++      range = composed.call(selection, { shadowRoots: [shadow] })[0];
++    } catch {
++      range = composed.call(selection, shadow)[0];
++    }
++  } else {
++    const inner = (shadow as ShadowRoot & { getSelection?: () => Selection | null }).getSelection?.();
++    if (inner && inner.rangeCount > 0) range = inner.getRangeAt(0);
++  }
++  if (!range || range.collapsed) return null;
++  return { start: { node: range.startContainer, offset: range.startOffset }, end: { node: range.endContainer, offset: range.endOffset } };
++}
++
+ function closestSourceLine(node: Node): HTMLElement | null {
+-  const element = node.nodeType === Node.ELEMENT_NODE
+-    ? node as Element
+-    : node.parentElement;
+-  return element?.closest(".file-source-line[data-line-number]") ?? null;
++  const element = node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
++  return element?.closest("[data-line]") ?? null;
+ }
+ 
+ function getSelectedSourceLineRange(root: HTMLElement, selection: Selection | null): SelectedLineRange | null {
+-  if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;
+-
+-  const range = selection.getRangeAt(0);
+-  if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null;
+-
+-  let startElement = closestSourceLine(range.startContainer);
+-  let endElement = closestSourceLine(range.endContainer);
+-  if (!startElement || !endElement || !root.contains(startElement) || !root.contains(endElement)) return null;
+-
+-  let startLine = Number(startElement.dataset.lineNumber);
+-  let endLine = Number(endElement.dataset.lineNumber);
++  if (!selection || selection.rangeCount === 0) return null;
++  const shadow = root.querySelector(".file-source-view diffs-container")?.shadowRoot;
++  if (!shadow) return null;
++  const points = selectionInShadow(selection, shadow);
++  if (!points || !shadow.contains(points.start.node) || !shadow.contains(points.end.node)) return null;
++
++  const startElement = closestSourceLine(points.start.node);
++  const endElement = closestSourceLine(points.end.node);
++  if (!startElement || !endElement) return null;
++  let startLine = Number(startElement.dataset.line);
++  let endLine = Number(endElement.dataset.line);
+   if (!Number.isInteger(startLine) || !Number.isInteger(endLine)) return null;
+ 
+   if (startLine < endLine) {
+-    // Browser ranges can start at the end of the preceding line or end at the
+-    // start of the following line. Exclude either boundary line when none of
+-    // its source text is actually selected.
+-    const startContent = startElement.querySelector(".file-source-line-content");
+-    if (startContent?.contains(range.startContainer)) {
+-      const selectedSuffix = document.createRange();
+-      selectedSuffix.selectNodeContents(startContent);
+-      selectedSuffix.setStart(range.startContainer, range.startOffset);
+-      if (selectedSuffix.toString().length === 0) {
+-        const nextLine = startElement.nextElementSibling;
+-        if (nextLine instanceof HTMLElement && nextLine.matches(".file-source-line[data-line-number]")) {
+-          startElement = nextLine;
+-          startLine = Number(startElement.dataset.lineNumber);
+-        }
+-      }
+-    }
+-
+-    const endContent = endElement.querySelector(".file-source-line-content");
+-    if (endContent?.contains(range.endContainer)) {
+-      const selectedPrefix = document.createRange();
+-      selectedPrefix.selectNodeContents(endContent);
+-      selectedPrefix.setEnd(range.endContainer, range.endOffset);
+-      if (selectedPrefix.toString().length === 0) {
+-        const previousLine = endElement.previousElementSibling;
+-        if (previousLine instanceof HTMLElement && previousLine.matches(".file-source-line[data-line-number]")) {
+-          endElement = previousLine;
+-          endLine = Number(endElement.dataset.lineNumber);
+-        }
+-      }
+-    }
++    // A range can start at the end of the line before or end at the start of the line after:
++    // a boundary line none of whose text is selected is not part of it.
++    const selectedSuffix = document.createRange();
++    selectedSuffix.selectNodeContents(startElement);
++    selectedSuffix.setStart(points.start.node, points.start.offset);
++    if (selectedSuffix.toString().length === 0) startLine += 1;
++    const selectedPrefix = document.createRange();
++    selectedPrefix.selectNodeContents(endElement);
++    selectedPrefix.setEnd(points.end.node, points.end.offset);
++    if (selectedPrefix.toString().length === 0) endLine -= 1;
+   }
+ 
+   if (startLine > endLine) return null;
+   return { startLine, endLine };
+ }
+ 
+-function SourceCodeRenderer({ rows, stylesheet, useInlineStyles, wrapLines }: SourceCodeRendererProps) {
+-  return rows.map((row, lineIndex) => {
+-    const children = row.children ?? [];
+-    const firstChildClasses = children[0]?.properties?.className;
+-    const hasLineNumber = Array.isArray(firstChildClasses)
+-      && firstChildClasses.includes("react-syntax-highlighter-line-number");
+-    const lineNumberNode = hasLineNumber ? children[0] : null;
+-    const contentNodes = hasLineNumber ? children.slice(1) : children;
+-
+-    return (
+-      
+-        {lineNumberNode && renderSyntaxNode({
+-          node: lineNumberNode,
+-          stylesheet,
+-          useInlineStyles,
+-          key: `source-line-number-${lineIndex}`,
+-        })}
+-        
+-          {contentNodes.map((node, tokenIndex) => renderSyntaxNode({
+-            node,
+-            stylesheet,
+-            useInlineStyles,
+-            key: `source-token-${lineIndex}-${tokenIndex}`,
+-          }))}
+-        
+-      
+-    );
+-  });
+-}
+-
+ function getFileApiUrl(
+   filePath: string,
+   type: "read" | "download" | "meta" | "preview" | "watch",
+@@ -252,196 +159,52 @@ function DownloadLink({ filePath, sourceSessionId }: { filePath: string; sourceS
        aria-label={t("i18n.downloadFile")}
        className="file-viewer-icon-button"
      >
@@ -9808,7 +10285,13 @@ index 9426211..42f0dac 100644
 + * A file's changes against HEAD in the diff viewer (CodeDiff). Unchanged lines between hunks
 + * expand on demand: the first expansion fetches both whole versions of the file.
 + */
-+function FileChangesView({ patch, cwd, filePath, wrapLines }: { patch: string; cwd?: string; filePath: string; wrapLines: boolean }) {
++function FileChangesView({ patch, cwd, filePath, wrapLines, scrollRoot }: {
++  patch: string;
++  cwd?: string;
++  filePath: string;
++  wrapLines: boolean;
++  scrollRoot: RefObject;
++}) {
    const { t } = useI18n();
 -  const diff = diffLines(patch);
 -
@@ -9952,7 +10435,7 @@ index 9426211..42f0dac 100644
 -        return 
{lines}
; - })} -
-+ fill ++ scrollRoot={scrollRoot} + overflow={wrapLines ? "wrap" : "scroll"} + loadFullFiles={loadFullFiles} + fallback={( @@ -9964,47 +10447,198 @@ index 9426211..42f0dac 100644 ); } -@@ -1442,7 +1299,7 @@ function TextFileViewer({ - (null); + const [gitDiff, setGitDiff] = useState(null); +@@ -1419,8 +1181,6 @@ function TextFileViewer({ + const viewerContent = data?.content ?? ""; + const sourceLines = useMemo(() => viewerContent.split("\n"), [viewerContent]); + const language = data?.language ?? "text"; +- // Plain text needs no Prism languages; any other file loads them once. +- const prismReady = usePrismLanguages(Boolean(data) && language !== "text"); + const isHtml = language === "html"; + const isMarkdown = language === "markdown"; + // A table shows a loaded prefix too, without its cut last record; an HTML +@@ -1431,76 +1191,13 @@ function TextFileViewer({ + const effectiveDisplayMode = isDeletedDiff ? "diff" : displayMode; + // A partly loaded HTML file previews whole, so Load more belongs to its source view. + const showLoadMore = !!data?.truncated && !(isHtml && effectiveDisplayMode === "preview"); +- const useLightweightSource = sourceLines.length > SOURCE_HIGHLIGHT_MAX_LINES +- && !(effectiveDisplayMode === "diff" && hasGitDiff) +- && !(effectiveDisplayMode === "preview" && hasPreview); +- // react-syntax-highlighter rebuilds every token element on each render, which +- // costs hundreds of milliseconds on large files. Cache the rendered trees so +- // unrelated re-renders (panel open/close, selection changes) reuse them as-is. +- const highlightedSource = useMemo( +- () => ( +- -- -+ - - - )} -@@ -1733,7 +1585,7 @@ function TextFileViewer({ - gap: 10, - padding: "5px 8px", - border: "1px solid var(--border)", -- borderRadius: 6, +- showLineNumbers +- lineNumberStyle={{ +- ...FILE_LINE_NUMBER_STYLE, +- }} +- customStyle={{ +- margin: 0, +- padding: 0, +- border: 0, +- backgroundColor: "var(--bg)", +- ...FILE_CODE_STYLE, +- width: wrapLines ? "100%" : "max-content", +- minWidth: "100%", +- minHeight: "100%", +- overflow: "visible", +- }} +- codeTagProps={{ +- style: { +- fontFamily: "var(--font-mono)", +- fontWeight: "var(--font-mono-weight)", +- overflowWrap: wrapLines ? "anywhere" : "normal", +- }, +- }} +- renderer={(rendererProps) => ( +- +- )} +- wrapLongLines={wrapLines} +- > +- {viewerContent} +- +- ), +- [isDark, language, prismReady, viewerContent, wrapLines], +- ); +- const lightweightSourceLines = useMemo( +- () => useLightweightSource ? sourceLines.map((line, lineIndex) => ( +- +- +- +- {line} +- +- +- )) : null, +- [sourceLines, useLightweightSource, wrapLines], +- ); ++ // Lines picked on the source's line numbers (CodeFile's gutter), beside a text selection. ++ const [gutterLineRange, setGutterLineRange] = useState(null); ++ const gutterLineRangeRef = useRef(null); ++ gutterLineRangeRef.current = gutterLineRange; ++ useEffect(() => setGutterLineRange(null), [filePath]); ++ const activeLineRange = selectedLineRange ?? gutterLineRange; ++ const selectSourceLines = useMemo(() => (onMentionLines ? setGutterLineRange : undefined), [onMentionLines]); + + useEffect(() => { + const updateSelectedLineRange = () => { +@@ -1543,7 +1240,7 @@ function TextFileViewer({ + if (target instanceof Element && target.closest("input, textarea, [contenteditable='true']")) return; + + const root = contentRef.current; +- const lineRange = root ? getSelectedSourceLineRange(root, window.getSelection()) : null; ++ const lineRange = (root ? getSelectedSourceLineRange(root, window.getSelection()) : null) ?? gutterLineRangeRef.current; + if (!lineRange) return; + + event.preventDefault(); +@@ -1676,15 +1373,15 @@ function TextFileViewer({ + // Mention selected lines when a range is active (and line + // mention is wired up); otherwise fall back to a whole-file + // @mention. Same button, behavior follows the selection. +- if (selectedLineRange && onMentionLines) { +- mentionLineRange(selectedLineRange); ++ if (activeLineRange && onMentionLines) { ++ mentionLineRange(activeLineRange); + } else { + onAtMention?.(getRelativeFilePath(filePath, cwd), false); + } + }} + title={ +- selectedLineRange && onMentionLines +- ? `${t("i18n.mentionSelectedLines")} (L${selectedLineRange.startLine}${selectedLineRange.startLine !== selectedLineRange.endLine ? `-L${selectedLineRange.endLine}` : ""})` ++ activeLineRange && onMentionLines ++ ? `${t("i18n.mentionSelectedLines")} (L${activeLineRange.startLine}${activeLineRange.startLine !== activeLineRange.endLine ? `-L${activeLineRange.endLine}` : ""})` + : t("files.insertPath") + } + aria-label={t("files.mention")} +@@ -1708,12 +1405,7 @@ function TextFileViewer({ + color: wrapLines ? "var(--text)" : "var(--text-muted)", + }} + > +- ++ + + + )} +@@ -1733,7 +1425,7 @@ function TextFileViewer({ + gap: 10, + padding: "5px 8px", + border: "1px solid var(--border)", +- borderRadius: 6, + borderRadius: "var(--radius-sm)", color: "var(--text-dim)", fontSize: 11, }} -@@ -1764,7 +1616,7 @@ function TextFileViewer({ +@@ -1764,7 +1456,7 @@ function TextFileViewer({ style={{ flex: 1, overflow: "auto", background: "var(--bg)", paddingBottom: showLoadMore ? 48 : undefined }} > {effectiveDisplayMode === "diff" && hasGitDiff ? ( - -+ ++ ) : isHtml && effectiveDisplayMode === "preview" && data?.truncated && !htmlFull?.text ? (
{htmlFull?.error ?? t("i18n.loading")} +@@ -1852,21 +1544,15 @@ function TextFileViewer({ + complete={!data?.truncated} + scrollRef={contentRef} + /> +- ) : useLightweightSource ? ( +-
+- {lightweightSourceLines} +-
+ ) : ( +- highlightedSource ++ + )} +
+
diff --git a/components/FontSettings.tsx b/components/FontSettings.tsx index 7e4c208..960fc5e 100644 --- a/components/FontSettings.tsx @@ -10062,21 +10696,95 @@ index 9b81f64..22b3e6d 100644 )} +diff --git a/components/MermaidBlock.test.mjs b/components/MermaidBlock.test.mjs +index 45088d3..cf1df98 100644 +--- a/components/MermaidBlock.test.mjs ++++ b/components/MermaidBlock.test.mjs +@@ -10,7 +10,6 @@ const React = await jiti.import("react"); + const { renderToStaticMarkup } = await jiti.import("react-dom/server"); + const { MermaidBlock, CodeBlock, downloadMermaidSvg } = await jiti.import("./MermaidBlock.tsx"); + const { I18nProvider } = await jiti.import("@/hooks/useI18n"); +-const { loadPrismLanguages } = await jiti.import("@/lib/prism-languages"); + + // Simple sequenceDiagram for testing + const mermaidSrc = `sequenceDiagram +@@ -69,36 +68,34 @@ function renderCode(props) { + ); + } + +-test("CodeBlock renders the same numbered lines without tokens until the Prism languages load", () => { ++test("CodeBlock shows its text at once, in the code box, with its language and Copy", () => { + const html = renderCode({ code: "const x = 1;\nlet y = 2;", lang: "javascript" }); + +- assert.doesNotMatch(html, /class="token/); +- assert.equal(html.match(/react-syntax-highlighter-line-number/g)?.length, 2); +- assert.match(html, /const x = 1;/); ++ assert.match(html, /class="markdown-code-lang">javascript { +- await loadPrismLanguages(); +- const html = renderCode({ code: "const x = 1;", lang: "javascript" }); +- +- assert.match(html, /class="token/); +- assert.match(html, /const/); ++test("CodeBlock has no Prism left: no token classes, no react-syntax-highlighter markup", () => { ++ for (const isStreaming of [false, true]) { ++ const html = renderCode({ code: "const x = 1;", lang: "javascript", isStreaming }); ++ assert.doesNotMatch(html, /class="token|react-syntax-highlighter|language-javascript/); ++ } + }); + +-test("CodeBlock owns the pre background without a competing shorthand", () => { ++test("CodeBlock leaves its background to the stylesheet, so a theme switch has nothing to fight", () => { + for (const isStreaming of [false, true]) { + const html = renderCode({ code: "const x = 1;", lang: "javascript", isStreaming }); +- const pre = html.match(/]*>/)?.[0]; +- assert.ok(pre); +- assert.match(pre, /background-color:color-mix/); +- assert.doesNotMatch(pre, /(?:[;\"]|^)background:/); ++ assert.doesNotMatch(html, /style="[^"]*background/); + } + }); + +-test("CodeBlock renders plain text without tokenization while streaming", () => { ++test("CodeBlock renders plain text while its message streams", () => { + const html = renderCode({ code: "const x = 1;", lang: "javascript", isStreaming: true }); + +- assert.doesNotMatch(html, /class="token/); ++ assert.match(html, /class="code-file is-plain is-scroll"/); + assert.match(html, /const x = 1;/); + }); + diff --git a/components/MermaidBlock.tsx b/components/MermaidBlock.tsx -index 25e4a63..8ce9799 100644 +index 25e4a63..171bf7c 100644 --- a/components/MermaidBlock.tsx +++ b/components/MermaidBlock.tsx -@@ -10,6 +10,9 @@ import { usePrismLanguages } from "@/hooks/usePrismLanguages"; +@@ -1,15 +1,13 @@ + "use client"; + + import { memo, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +-import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light"; +-import { vs } from "react-syntax-highlighter/dist/cjs/styles/prism"; +-import { vscDarkPlus } from "react-syntax-highlighter/dist/cjs/styles/prism"; + import { useTheme } from "@/hooks/useTheme"; + import { useI18n } from "@/hooks/useI18n"; +-import { usePrismLanguages } from "@/hooks/usePrismLanguages"; import { copyText } from "@/lib/clipboard"; - import { takeHighlightBudget, waitForHighlight } from "@/lib/highlight-queue"; - import { prismLanguagesLoaded } from "@/lib/prism-languages"; -+import { neutralCodeTheme, neutralMermaidTheme } from "@/lib/neutral-code-theme"; +-import { takeHighlightBudget, waitForHighlight } from "@/lib/highlight-queue"; +-import { prismLanguagesLoaded } from "@/lib/prism-languages"; ++import { neutralMermaidTheme } from "@/lib/mermaid-theme"; ++import { CodeFile, PlainCode } from "./CodeLazy"; +import { CarbonIcon } from "./CarbonIcon"; +import * as Carbon from "./carbon/icons"; interface MermaidBlockProps { code: string; -@@ -59,7 +62,7 @@ export function MermaidBlock({ code, isStreaming, defaultPreview = false }: Merm +@@ -59,7 +57,7 @@ export function MermaidBlock({ code, isStreaming, defaultPreview = false }: Merm startOnLoad: false, securityLevel: "strict", suppressErrorRendering: true, @@ -10085,7 +10793,7 @@ index 25e4a63..8ce9799 100644 }); const parsed = await mermaid.parse(code, { suppressErrors: true }); -@@ -194,9 +197,7 @@ function MermaidZoomDialog({ svg, onClose }: { svg: string; onClose: () => void +@@ -194,9 +192,7 @@ function MermaidZoomDialog({ svg, onClose }: { svg: string; onClose: () => void title={t("i18n.zoomOut")} aria-label={t("i18n.zoomOut")} > @@ -10096,7 +10804,7 @@ index 25e4a63..8ce9799 100644 {Math.round(zoom * 100)}%
-@@ -262,12 +257,14 @@ interface CodeBlockProps { - // Prism's light theme uses backgroundColor, while its dark theme uses the - // background shorthand. Keep the pre background solely in customStyle so a - // theme switch cannot remove/update one and reset the other in React's diff. +@@ -259,46 +249,19 @@ interface CodeBlockProps { + isStreaming?: boolean; + } + +-// Prism's light theme uses backgroundColor, while its dark theme uses the +-// background shorthand. Keep the pre background solely in customStyle so a +-// theme switch cannot remove/update one and reset the other in React's diff. -const codeBlockDarkTheme = { -+const codeBlockDarkTheme = neutralCodeTheme({ - ...vscDarkPlus, - 'pre[class*="language-"]': { - ...vscDarkPlus['pre[class*="language-"]'], - }, +- ...vscDarkPlus, +- 'pre[class*="language-"]': { +- ...vscDarkPlus['pre[class*="language-"]'], +- }, -}; -+}, "dark"); -+// Both without blue: lib/neutral-code-theme.ts. -+const codeBlockLightTheme = neutralCodeTheme(vs, "light"); - delete codeBlockDarkTheme['pre[class*="language-"]'].background; - +-delete codeBlockDarkTheme['pre[class*="language-"]'].background; +- /** -@@ -337,7 +334,7 @@ export const CodeBlock = memo(function CodeBlock({ code, lang, headerAction, isS - ) : ( - !isStreaming && prismLanguagesLoaded() && takeHighlightBudget(code.length), +- ); +- +- useEffect(() => { +- if (isStreaming || highlighted || !languagesReady) return; +- return waitForHighlight(() => setHighlighted(true)); +- }, [isStreaming, highlighted, languagesReady]); + + const copy = () => { + copyText(code).then(() => { +@@ -321,42 +284,8 @@ export const CodeBlock = memo(function CodeBlock({ code, lang, headerAction, isS + + + +- {isStreaming ? ( +-
+-          {code}
+-        
+- ) : ( +- ; the +- // block's wrapper already draws the frame. +- border: "none", +- borderRadius: 0, +- backgroundColor: "color-mix(in srgb, var(--bg) 92%, var(--bg-panel))", +- }} +- codeTagProps={{ style: { fontFamily: "var(--font-mono)", fontWeight: "var(--font-mono-weight)" } }} +- > +- {code} +- +- )} ++ {/* Long lines scroll sideways, as code blocks always have (an extension dialog widens for them). */} ++ {isStreaming ? : } + + ); + }); diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 515b033..eeb4c1e 100644 --- a/components/MessageView.test.mjs @@ -10181,10 +10962,10 @@ index 515b033..eeb4c1e 100644 test("collapses a displayed custom message from its header alone", () => { diff --git a/components/MessageView.tsx b/components/MessageView.tsx -index f2ff1de..82a4551 100644 +index f2ff1de..7cb3f86 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx -@@ -5,11 +5,13 @@ import ReactMarkdown from "react-markdown"; +@@ -5,13 +5,15 @@ import ReactMarkdown from "react-markdown"; import { MarkdownBody } from "./MarkdownBody"; import { ImagePreview } from "./ImagePreview"; import { ThinkingIcon } from "./ThinkingIcon"; @@ -10195,10 +10976,13 @@ index f2ff1de..82a4551 100644 import { getAssistantErrorMessage, getThinkingPreview, hasAssistantAnswer, isAssistantTruncated, isEmptyThinkingBlock } from "@/lib/message-display"; -import { parseUnifiedPatch, type SplitDiffCell, type SplitDiffFile } from "@/lib/patch"; +import type { SplitDiffFile } from "@/lib/patch"; -+import { CodeDiff } from "./CodeDiffLazy"; ++import { CodeDiff, CodeFile } from "./CodeLazy"; import { applyPatchPreviewToFiles, applyPatchResultHasFailures, extractApplyPatchPaths, getApplyPatchInputText, parseApplyPatchInput } from "@/lib/apply-patch"; - import { isApplyPatchToolName, isEditToolName, isWriteToolName } from "@/lib/tool-names"; +-import { isApplyPatchToolName, isEditToolName, isWriteToolName } from "@/lib/tool-names"; ++import { isApplyPatchToolName, isEditToolName, isReadToolName, isWriteToolName } from "@/lib/tool-names"; import { isToolCallExpanded, setToolCallExpanded } from "@/lib/tool-call-expansion"; + import { isThinkingExpandedByDefault, THINKING_EXPANDED_EVENT } from "@/lib/thinking-expansion-preference"; + import { TurnWrittenFiles } from "./TurnWrittenFiles"; @@ -35,6 +37,8 @@ import type { ToolCallContent, ThinkingContent, @@ -10953,7 +11737,15 @@ index f2ff1de..82a4551 100644 ); } -@@ -1176,136 +981,131 @@ function ToolCallBlock({ block, result, duration, onOpenSubagent }: { block: Too +@@ -1146,6 +951,7 @@ function ToolCallBlock({ block, result, duration, onOpenSubagent }: { block: Too + setExpanded(next); + }; + const inputStr = getWrittenFileText(block) ?? getToolCallInputText(block); ++ const readFile = getReadFile(block); + const isStreamingInput = block.rawInput !== undefined; + const isEditTool = isEditToolName(block.toolName); + const resultDiff = result && !result.isError ? getResultDiff(result) : null; +@@ -1176,136 +982,121 @@ function ToolCallBlock({ block, result, duration, onOpenSubagent }: { block: Too const subagent = isSubagentToolDetails(result?.details) ? result.details : null; const codemodeCallCount = codemode ? codemode.calls.length + codemode.omitted : 0; @@ -11086,21 +11878,7 @@ index f2ff1de..82a4551 100644 +
+ {/* ── Input args (only when no richer view exists); a codemode script in place of its JSON ── */} + {(isStreamingInput || !isEditTool) && !patchFiles && ( -+
-+              {codemode ? codemode.code.replace(/\r/g, "").trimEnd() : inputStr}
-+            
++ + )} - {/* ── Paired result — only shown when expanded ── */} @@ -11148,6 +11926,10 @@ index f2ff1de..82a4551 100644 + ++ ) : readFile && !isError && !resultIsEmpty && resultText ? ( ++ ++ ) : !isError && resultText && isJsonText(resultText) ? ( ++ + ) : (!resultIsEmpty || resultImages.length === 0) && ( + -@@ -1325,148 +1124,16 @@ function PairedDiffResult({ diff }: { +@@ -1325,148 +1115,16 @@ function PairedDiffResult({ diff }: { ); } @@ -11343,7 +12125,7 @@ index f2ff1de..82a4551 100644 } function PatchTextView({ text }: { text: string }) { -@@ -1483,12 +1150,12 @@ function PatchTextView({ text }: { text: string }) { +@@ -1483,12 +1141,12 @@ function PatchTextView({ text }: { text: string }) { const bg = kind === "added" ? "rgba(34,197,94,0.12)" : kind === "removed" ? "rgba(248,113,113,0.13)" : @@ -11358,7 +12140,7 @@ index f2ff1de..82a4551 100644 "var(--text)"; return ( -@@ -1502,7 +1169,7 @@ function PatchTextView({ text }: { text: string }) { +@@ -1502,7 +1160,7 @@ function PatchTextView({ text }: { text: string }) { : kind === "removed" ? "3px solid #f87171" : kind === "hunk" @@ -11367,7 +12149,7 @@ index f2ff1de..82a4551 100644 : "3px solid transparent", }} > -@@ -1587,7 +1254,6 @@ function ResultImages({ images, isError }: { images: ImageContent[]; isError: bo +@@ -1587,7 +1245,6 @@ function ResultImages({ images, isError }: { images: ImageContent[]; isError: bo flexWrap: "wrap", padding: "10px", background: "var(--bg)", @@ -11375,7 +12157,7 @@ index f2ff1de..82a4551 100644 }} > {images.map((image, index) => { -@@ -1608,7 +1274,7 @@ function ResultImages({ images, isError }: { images: ImageContent[]; isError: bo +@@ -1608,7 +1265,7 @@ function ResultImages({ images, isError }: { images: ImageContent[]; isError: bo display: "block", maxWidth: "min(100%, 720px)", maxHeight: 520, @@ -11384,7 +12166,75 @@ index f2ff1de..82a4551 100644 objectFit: "contain", border: "1px solid var(--border)", }} -@@ -1629,8 +1295,7 @@ function PairedResult({ text, isEmpty, isError }: { +@@ -1620,6 +1277,67 @@ function ResultImages({ images, isError }: { images: ImageContent[]; isError: bo + ); + } + ++/** ++ * A tool call's input as code (CodeFile, Shiki): the file a write creates, highlighted for its ++ * name; a codemode script as JavaScript; any other call's arguments as JSON. Input still streaming ++ * is incomplete JSON and stays plain text. ++ */ ++function ToolInputView({ block, inputStr, codemodeCode, isStreaming }: { ++ block: ToolCallContent; ++ inputStr: string; ++ codemodeCode: string | null; ++ isStreaming: boolean; ++}) { ++ if (isStreaming) { ++ return ( ++
++        {inputStr}
++      
++ ); ++ } ++ const written = getWrittenFileText(block); ++ if (written !== null) { ++ const path = writtenFilePath(block); ++ return ; ++ } ++ if (codemodeCode !== null) { ++ return ; ++ } ++ return ; ++} ++ ++// pi's read tool ends a partial read with where to continue: "[Showing lines 1-200 of 500. Use ++// offset=201 to continue.]" or "[300 more lines in file. Use offset=201 to continue.]". ++const READ_CONTINUATION = /\n\n(\[[^\]\n]*Use offset=\d+ to continue\.\])\s*$/; ++ ++/** ++ * A read's output: the file's text, highlighted for its name, its lines numbered from where the ++ * read started; pi's note on where to continue under it, as text. ++ */ ++function ReadResultView({ text, path, fromLine }: { text: string; path: string; fromLine: number }) { ++ const match = text.match(READ_CONTINUATION); ++ const code = match ? text.slice(0, match.index) : text; ++ return ( ++
++ {/* The viewer numbers from 1, so a read from further down shows its text without numbers. */} ++ ++ {match &&
{match[1]}
} ++
++ ); ++} ++ + function PairedResult({ text, isEmpty, isError }: { + text: string; + isEmpty: boolean; +@@ -1629,8 +1347,7 @@ function PairedResult({ text, isEmpty, isError }: { return (
@@ -11414,7 +12264,7 @@ index f2ff1de..82a4551 100644
              
                
                  {t("i18n.conversationCompacted")}
-@@ -1806,7 +1469,7 @@ function CustomMessageView({ message, cwd, onOpenFile }: { message: CustomMessag
+@@ -1806,7 +1521,7 @@ function CustomMessageView({ message, cwd, onOpenFile }: { message: CustomMessag
        
)} {time && {time}} @@ -11434,7 +12284,7 @@ index f2ff1de..82a4551 100644
-@@ -1872,7 +1533,7 @@ function CustomMessageView({ message, cwd, onOpenFile }: { message: CustomMessag +@@ -1872,7 +1585,7 @@ function CustomMessageView({ message, cwd, onOpenFile }: { message: CustomMessag ); -@@ -2021,13 +1682,16 @@ function getToolPreview(block: ToolCallContent): string { +@@ -1999,6 +1712,32 @@ function getWrittenFileText(block: ToolCallContent): string | null { + return Object.keys(block.input).every((key) => WRITE_VIEW_KEYS.has(key)) ? content : null; + } + ++function writtenFilePath(block: ToolCallContent): string | null { ++ const { path, file_path: filePath } = block.input; ++ return typeof path === "string" ? path : typeof filePath === "string" ? filePath : null; ++} ++ ++/** A tool's output that is a JSON object or array (an API's answer, an MCP result): shown as JSON. */ ++function isJsonText(text: string): boolean { ++ const trimmed = text.trim(); ++ if (trimmed.length < 2 || trimmed.length > 200_000 || !/^[[{]/.test(trimmed)) return false; ++ try { ++ const value: unknown = JSON.parse(trimmed); ++ return typeof value === "object" && value !== null; ++ } catch { ++ return false; ++ } ++} ++ ++/** The file a read call reads and the line it starts at (pi's offset is 1-based). */ ++function getReadFile(block: ToolCallContent): { path: string; offset: number } | null { ++ if (block.rawInput !== undefined || !isReadToolName(block.toolName)) return null; ++ const path = writtenFilePath(block); ++ if (!path) return null; ++ const offset = Number(block.input.offset ?? 1); ++ return { path, offset: Number.isFinite(offset) && offset > 1 ? Math.floor(offset) : 1 }; ++} ++ + function formatCustomType(type: string): string { + return type || "extension"; + } +@@ -2021,13 +1760,16 @@ function getToolPreview(block: ToolCallContent): string { return String(first).slice(0, 120); } @@ -13457,6 +14340,212 @@ index 0000000..5547fb4 +export const Warning: CarbonIconData = { viewBox: "0 0 16 16", shapes: [["path", {"d":"M8,1C4.1,1,1,4.1,1,8s3.1,7,7,7s7-3.1,7-7S11.9,1,8,1z M8,14c-3.3,0-6-2.7-6-6s2.7-6,6-6s6,2.7,6,6S11.3,14,8,14z"}], ["path", {"d":"M7.5 4H8.5V9H7.5z"}], ["path", {"d":"M8,10.2c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8c0.4,0,0.8-0.3,0.8-0.8S8.4,10.2,8,10.2z"}]] }; +/** carbon: warning--alt */ +export const WarningAlt: CarbonIconData = { viewBox: "0 0 16 16", shapes: [["path", {"d":"M14.5,14h-13c-0.2,0-0.3-0.1-0.4-0.2c-0.1-0.2-0.1-0.3,0-0.5l6.5-12C7.7,1,8,0.9,8.2,1.1c0.1,0,0.2,0.1,0.2,0.2l6.5,12\tc0.1,0.2,0.1,0.3,0,0.5C14.9,13.9,14.7,14,14.5,14z M2.3,13h11.3L8,2.5L2.3,13z"}], ["path", {"d":"M7.5 6H8.5V9.5H7.5z"}], ["path", {"d":"M8,10.8c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8c0.4,0,0.8-0.3,0.8-0.8S8.4,10.8,8,10.8z"}]] }; +diff --git a/components/code-viewers.ts b/components/code-viewers.ts +new file mode 100644 +index 0000000..a620a61 +--- /dev/null ++++ b/components/code-viewers.ts +@@ -0,0 +1,3 @@ ++// The code and diff viewers in one chunk (components/CodeLazy.tsx loads it). ++export { CodeDiff } from "./CodeDiff"; ++export { CodeFile } from "./CodeFile"; +diff --git a/components/highlighting.test.mjs b/components/highlighting.test.mjs +new file mode 100644 +index 0000000..3d8fca8 +--- /dev/null ++++ b/components/highlighting.test.mjs +@@ -0,0 +1,28 @@ ++import assert from "node:assert/strict"; ++import test from "node:test"; ++import { createJiti } from "jiti"; ++ ++const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); ++const { codeLanguage, hashText, RENDER, UNSAFE_CSS } = await jiti.import("./highlighting.ts"); ++ ++test("a fence's language is a Shiki grammar: names and aliases as written, plain text otherwise", () => { ++ for (const [lang, expected] of [ ++ ["ts", "ts"], ["TypeScript", "typescript"], ["py", "py"], ["sh", "sh"], ["console", "console"], ["json", "json"], ++ ["diff", "diff"], ["mermaid", "mermaid"], ["Dockerfile", "dockerfile"], ["yml", "yml"], ++ ["c++", "c++"], ["h", "c"], ["env", "dotenv"], ["patch", "diff"], ++ ["", "text"], [undefined, "text"], ["text", "text"], ["plaintext", "text"], ["txt", "text"], ["no-such-language", "text"], ++ ]) assert.equal(codeLanguage(lang), expected, String(lang)); ++}); ++ ++test("the cache key follows the text", () => { ++ assert.equal(hashText("abc"), hashText("abc")); ++ assert.notEqual(hashText("abc"), hashText("abd")); ++ assert.notEqual(hashText(""), hashText(" ")); ++}); ++ ++test("one stack: the neutral themes, keywords bolder than any base weight, no blue in the viewer CSS", () => { ++ assert.deepEqual(RENDER.theme, { dark: "pi-web-dark", light: "pi-web-light" }); ++ assert.match(RENDER.preferredHighlighter, /^shiki-(js|wasm)$/); ++ assert.match(UNSAFE_CSS, /font-weight: calc\(var\(--font-mono-weight, 400\) \+ 200\)/); ++ assert.doesNotMatch(UNSAFE_CSS, /#[0-9a-f]{3,6}\b/i); ++}); +diff --git a/components/highlighting.ts b/components/highlighting.ts +new file mode 100644 +index 0000000..ae9fdae +--- /dev/null ++++ b/components/highlighting.ts +@@ -0,0 +1,157 @@ ++"use client"; ++ ++import { useEffect, useState, type RefObject } from "react"; ++import { Virtualizer, registerCustomTheme, type ThemeRegistration, type VirtualFileMetrics } from "@pierre/diffs"; ++import { getOrCreateWorkerPoolSingleton, type WorkerPoolManager } from "@pierre/diffs/worker"; ++import { bundledLanguages } from "shiki"; ++import { DIFF_THEMES, neutralShikiTheme, type ShikiTheme } from "@/lib/diffs-theme"; ++ ++/** ++ * Pi Web's one syntax-highlighting stack, behind every surface that shows code: diffs (CodeDiff), ++ * Markdown code blocks, the file viewer's source and the code a tool reads, writes or runs ++ * (CodeFile). @pierre/diffs (diffs.com) renders; Shiki highlights, with its JavaScript regex ++ * engine, in a pool of web workers, in the design system's neutral themes (lib/diffs-theme.ts). ++ * Loaded only through components/CodeLazy.tsx, so a page without code does not pay for it. ++ */ ++ ++export const CODE_THEMES = DIFF_THEMES; ++ ++// Shiki's JavaScript engine compiles grammars to RegExps with lookbehind, which Safari parses only ++// from 16.4 (Pi Web still serves iOS 16.2, AGENTS.md): there it uses the Oniguruma engine (WASM). ++function supportsLookbehind(): boolean { ++ try { ++ return new RegExp("(?<=a)b").test("ab"); ++ } catch { ++ return false; ++ } ++} ++ ++// Settings the worker pool renders with; the components get the same ones, so a pool render and a ++// main-thread render (before the pool is up, or without workers) look alike. ++export const RENDER = { ++ theme: CODE_THEMES, ++ preferredHighlighter: supportsLookbehind() ? "shiki-js" : "shiki-wasm", ++ lineDiffType: "word-alt", ++ maxLineDiffLength: 1000, ++ // Minified and generated lines are left plain rather than tokenized. ++ tokenizeMaxLineLength: 1000, ++} as const; ++ ++let themesRegistered = false; ++function registerThemes() { ++ if (themesRegistered) return; ++ themesRegistered = true; ++ const load = (mode: "dark" | "light", source: () => Promise<{ default: unknown }>) => async () => ++ neutralShikiTheme((await source()).default as ShikiTheme, mode, CODE_THEMES[mode]) as unknown as ThemeRegistration; ++ registerCustomTheme(CODE_THEMES.dark, load("dark", () => import("@shikijs/themes/dark-plus"))); ++ registerCustomTheme(CODE_THEMES.light, load("light", () => import("@shikijs/themes/light-plus"))); ++} ++ ++// One pool for the page, created by the first code shown and kept: workers start only when code is ++// on screen, and stay warm (grammars loaded) for the next block. ++let pool: WorkerPoolManager | null | undefined; ++export function codePool(): WorkerPoolManager | undefined { ++ if (pool !== undefined) return pool ?? undefined; ++ registerThemes(); ++ if (typeof window === "undefined" || typeof Worker === "undefined") return undefined; ++ try { ++ pool = getOrCreateWorkerPoolSingleton({ ++ poolOptions: { ++ workerFactory: () => new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), { type: "module" }), ++ poolSize: Math.max(1, Math.min(2, (navigator.hardwareConcurrency || 2) - 1)), ++ }, ++ highlighterOptions: { ...RENDER, langs: [] }, ++ }); ++ } catch { ++ pool = null; ++ } ++ return pool ?? undefined; ++} ++ ++// Inside a viewer's shadow root. The library sets a token's weight and style through light-dark(), ++// which only takes colours, so a bold or italic token would stay regular: both themes mark the same ++// tokens, so the token's own declaration is enough. Keywords are 200 above the monospace weight ++// (600 at the default 400), so they stay bolder than any base weight Settings allows (up to 600). ++// Separators ("13 unmodified lines") are a quiet 24px row in small type. ++export const UNSAFE_CSS = ` ++[data-line] span[style*="font-weight:bold"] { font-weight: calc(var(--font-mono-weight, 400) + 200); } ++[data-line] span[style*="font-style:italic"] { font-style: italic; } ++[data-separator=line-info-basic] { height: 24px; } ++[data-separator-content] { font-size: 12px; } ++[data-expand-index] [data-separator-wrapper] { grid-template-columns: 28px auto; } ++[data-expand-button]:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; } ++`; ++ ++// The library's expand controls are role=button divs out of the tab order: give them a place in ++// it, a name and the keys a button has. ++const EXPAND_LABELS: Array<[string, string]> = [ ++ ["data-expand-up", "Show the lines above"], ++ ["data-expand-down", "Show the lines below"], ++ ["data-expand-both", "Show the unmodified lines"], ++]; ++export function keyboardExpanders(host: HTMLElement) { ++ for (const button of host.shadowRoot?.querySelectorAll("[data-expand-button]") ?? []) { ++ if (button.dataset.keyboard !== undefined) continue; ++ button.dataset.keyboard = ""; ++ button.tabIndex = 0; ++ const label = EXPAND_LABELS.find(([attribute]) => button.hasAttribute(attribute))?.[1] ?? EXPAND_LABELS[2][1]; ++ button.setAttribute("aria-label", label); ++ button.addEventListener("keydown", (event) => { ++ if (event.key !== "Enter" && event.key !== " ") return; ++ event.preventDefault(); ++ button.click(); ++ }); ++ } ++} ++ ++// Code longer than this renders only the rows in view (and a margin), so a big file or change does ++// not build tens of thousands of nodes at once; the estimates are the design system's metrics (an ++// 18px line, a 24px separator row, no file header). ++export const VIRTUALIZE_AFTER_ROWS = 400; ++export const VIRTUAL_METRICS: VirtualFileMetrics = { hunkLineCount: 50, lineHeight: 18, diffHeaderHeight: 0, hunkSeparatorHeight: 24, spacing: 8 }; ++ ++/** ++ * A virtualizer on an element that already scrolls (the file viewer's panel), so its scroll ++ * position, padding and restore stay its own. Undefined until it is set up: render the code only ++ * then, since a viewer takes its virtualizer when it is created. Set up in a passive effect: the ++ * panel often mounts in the same commit as the code, and a child's layout effect runs before the ++ * parent's ref is attached. ++ */ ++export function useScrollRootVirtualizer( ++ root: RefObject | undefined, ++ content: RefObject, ++ enabled: boolean, ++): Virtualizer | undefined { ++ const [instance, setInstance] = useState(); ++ useEffect(() => { ++ const scroller = root?.current; ++ if (!enabled || !scroller || !content.current) { ++ setInstance(undefined); ++ return; ++ } ++ const virtualizer = new Virtualizer(); ++ virtualizer.setup(scroller, content.current); ++ setInstance(virtualizer); ++ return () => virtualizer.cleanUp(); ++ }, [root, content, enabled]); ++ return instance; ++} ++ ++/** A code fence's or a caller's language as a Shiki grammar name; plain text when Shiki has none. */ ++export function codeLanguage(lang: string | undefined | null): string { ++ const name = (lang ?? "").trim().toLowerCase(); ++ if (!name || name === "text" || name === "plaintext" || name === "plain" || name === "txt") return "text"; ++ if (Object.prototype.hasOwnProperty.call(bundledLanguages, name)) return name; ++ const alias: Record = { "c++": "cpp", h: "c", hpp: "cpp", env: "dotenv", ipynb: "json", patch: "diff", gitignore: "ini" }; ++ return alias[name] && Object.prototype.hasOwnProperty.call(bundledLanguages, alias[name]) ? alias[name] : "text"; ++} ++ ++/** FNV-1a, 32 bits, hex, and the length: a cache key, not a checksum. */ ++export function hashText(text: string): string { ++ let h = 0x811c9dc5; ++ for (let i = 0; i < text.length; i++) { ++ h ^= text.charCodeAt(i); ++ h = Math.imul(h, 0x01000193); ++ } ++ return (h >>> 0).toString(16) + text.length.toString(16); ++} diff --git a/demo/public/icons/apple-touch-icon.png b/demo/public/icons/apple-touch-icon.png index 5f7f2b155e7b5c4517b8556909f9dcbe6d9d6f40..17beb7135ed0a030d2d6e6b0342749914855c071 100644 GIT binary patch @@ -14696,8 +15785,27 @@ z`lBVr!2nt$V0bx-sVz|0P$bXi4NieUXqyffH)*5mO593r9Jz4hr(*2fqaI_|4lV-a za8eL^)SPxaxQ474TgO3Dx+=lt**@4jiTmoXh>QX;DqIUnCXbm^o4n^-mRR&Qm{tL_JHERF> +diff --git a/docs/agents/sessions.md b/docs/agents/sessions.md +index 42e1816..2e5afa6 100644 +--- a/docs/agents/sessions.md ++++ b/docs/agents/sessions.md +@@ -174,9 +174,11 @@ New sessions and the files tab ("the files tab" here is the files section below + - One check at a time, at most one per second (`SESSION_MEMBERSHIP_CHECK_MS`) whatever the number of tabs, none before the first scan. A change is recorded as it is reported, so it bumps once, not on every poll until the rescan. A scan that records its listing while a check reads replaces the baseline and the check's result is dropped: comparing an older read against a newer scan would bump for nothing, and the next check compares against the scan anyway. + - No `fs.watch`: a recursive watch on Linux is Node's JS layer (one inotify watch per file and folder, a synchronous walk of the whole tree when it starts, and a silently partial watch at the inotify limit), and on macOS it reports appends as `rename`. A missing sessions directory counts as empty; a changed `PI_CODING_AGENT_DIR` is just another listing. The cost is a readdir per project folder per second while some tab polls (about 10 ms for 18,000 files). + +-## History caches and deferred highlighting (`lib/session-reader.ts`, `lib/session-view-cache.ts`, `lib/highlight-queue.ts`) ++## History caches and code highlighting (`lib/session-reader.ts`, `lib/session-view-cache.ts`, `components/highlighting.ts`) + - `GET /api/sessions/[id]/entries/[entryId]/tool-result-image?blockIndex=` answers `private, max-age=31536000, immutable`: a session's entry id and block index name the same bytes for good (pi only appends, a migration's rewrite keeps every entry, a `context_edit` leaves raw history alone). With `no-cache` every view re-sent multi-MB images and decoded their base64 again. Error replies carry no cache header. + - A list rebuild reads a fork's or subagent's run (`readSubagentRun()` over the file's bounded head and tail) once per scanned row: `listSessionsIncremental()` hands back the index's same row object while the file's size and mtime hold, so a `WeakMap` keyed by the row caches the run. A rebuild on 355 sessions (137 subagents) went from 36 ms to 7 ms, synchronous reads that blocked the event loop. A row the scanner makes anew (a changed file, a restart) is read again; a failed read is not cached. + - `lib/session-view-cache.ts` measures a snapshot (its `JSON.stringify` length) once, when it is stored, and evicts by the stored sizes: snapshots are never mutated in place. Re-serializing every cached session on each store took 7.7 ms with eight 0.8 MB snapshots (1.3 ms now), at every run's end, compaction and session switch. The unmount check for a wider cached window is `snapshotCoversLoadedEntries()` (a `Set`), not nested `includes`. +-- Code fences (`CodeBlock`, `components/MermaidBlock.tsx`): Prism tokenizes in the render, about 5-10 ms per 1,000 characters of TypeScript on a desktop. Within one task the first 2,000 characters of fences are highlighted at once (`takeHighlightBudget()`); the others render through the same `SyntaxHighlighter` as `text` (same lines, numbers and box, no tokens) and take their language one per idle slice, newest first (`waitForHighlight()`; Safari has no `requestIdleCallback` and waits 50 ms). Opening a session with 86 fences at 4x CPU throttling, the commit that shows the messages went from 1.1 s to 0.66 s; the end of a streamed reply gets the same budget. `codeTagProps` sets no class, so tell a highlighted fence by its `span.token` elements other than `.linenumber`, not by a `language-*` class. +-- Prism languages load on demand (`lib/prism-languages.ts`, `hooks/usePrismLanguages.ts`). `CodeBlock` and `FileViewer` render with `react-syntax-highlighter/dist/esm/prism-light` (refractor's core), never the package index: its `Prism` imports `refractor/all`, which registers about 300 languages when evaluated, ~650 ms of the first `AppShell` render at 4x CPU throttling on every page load, code on screen or not. The first highlighter to mount imports `refractor/all` as a chunk of its own; it registers into the same core instance, so every language and alias works as before. Until then fences render as `text` and files as `plaintext` (same lines, numbers and box). A page with no code never loads it. Client code imports only types from `react-syntax-highlighter` itself. ++- All code is highlighted by one stack (`components/highlighting.ts`): @pierre/diffs (diffs.com) renders, Shiki highlights with its JavaScript regex engine in a pool of two web workers, in the design system's neutral dark+/light+ themes (`lib/diffs-theme.ts`). `CodeDiff` shows diffs (an edit, `apply_patch`, the file viewer's Diff mode); `CodeFile` shows everything else: Markdown fences (`CodeBlock`, `components/MermaidBlock.tsx`), the file viewer's source, a write's file, a read's output, a codemode script, a tool's JSON arguments and JSON results. Both come from one chunk loaded on demand and warmed when the page is idle (`components/CodeLazy.tsx`); until it is there, and if it cannot load, code shows as plain text in the same box (`PlainCode`). No tokenizing runs in a render, so there is no per-task highlight budget any more: a fence shows its text at once and its colours a moment later. Opening a session with 86 fences (the 50 of its last page render) at 4x CPU throttling: all highlighted in 2.2 s instead of Prism's 3.3 s, the main thread blocked 0.93 s instead of 1.26 s, the longest task 0.33 s instead of 0.5 s. ++- The pool starts with the first code shown and is kept (`codePool()`, our own lazy singleton passed through the library's `WorkerPoolContext`; its `WorkerPoolContextProvider` would start workers at mount and stop them with the last provider). Results are cached by content (`cacheKey`). Grammars load per language the first time it is needed; a fence's language is mapped to a Shiki name or plain text (`codeLanguage()`), since the library throws on unknown names. ++- The viewers render in shadow roots. Their colours and type come from CSS variables in `app/globals.css` (`.code-diff, .code-file`); the background is set on the host (`diffs-container`) because the library's theme sets it there (`:host`), which beats an inherited value. A text selection inside a viewer reaches the document through `Selection.getComposedRanges` (the file viewer's "mention selected lines"); an extension dialog measures the viewer's scrolling `[data-code]` to widen for code. More than 400 lines with a scroll box (the file viewer's panel, a tool's 400px box) render only the rows in view (`useScrollRootVirtualizer`, set up in a passive effect: the panel mounts in the same commit as the code). ++- Library quirks handled here: a token's bold/italic is applied in the shadow root (the library sets them through `light-dark()`, which only takes colours); the expand controls get a tab stop, a name and Enter/Space; its "modified" accent is overridden to gray (it is blue); its lookbehind literal `/(?<=\n)/` is rewritten at build time (`lib/pierre-diffs-split-loader.cjs`, as for #753), and Safari before 16.4 highlights with Shiki's Oniguruma (WASM) engine since the JavaScript engine compiles grammars to lookbehind RegExps. diff --git a/e2e/chat-appearance.mjs b/e2e/chat-appearance.mjs -index f1bd91a..6c1667a 100644 +index f1bd91a..204ed8c 100644 --- a/e2e/chat-appearance.mjs +++ b/e2e/chat-appearance.mjs @@ -9,7 +9,7 @@ export async function checkChatAppearanceReset(page) { @@ -14733,6 +15841,52 @@ index f1bd91a..6c1667a 100644 assert.equal(await fontSize.inputValue(), "14"); await width.press("End"); await closeSettings(); +@@ -77,7 +77,8 @@ export async function checkChatAppearance(page) { + await page.locator(".markdown-code-block pre").waitFor(); + assert.equal(await font(textarea), "18px"); + assert.equal(await font(page.locator(".markdown-user-message")), "18px"); +- assert.equal(await font(page.locator(".markdown-code-block pre")), "16.5px"); ++ // Code is the design system's text-code (12px) plus the chat's size step, as diffs are. ++ assert.equal(await font(page.locator(".markdown-code-block pre")), "16px"); + + await openSettings(); + assert.equal(await width.inputValue(), "2000"); +diff --git a/e2e/code-background.mjs b/e2e/code-background.mjs +index 26adf1a..4693626 100644 +--- a/e2e/code-background.mjs ++++ b/e2e/code-background.mjs +@@ -13,6 +13,7 @@ export async function checkCodeBackground(page) { + await source.click(); + const blocks = page.locator(".markdown-code-block pre"); + await blocks.nth(1).waitFor(); ++ + try { + for (const colorScheme of ["light", "dark", "light", "dark", "light"]) { + await page.emulateMedia({ colorScheme }); +@@ -23,12 +24,17 @@ export async function checkCodeBackground(page) { + document.body.append(probe); + const expected = getComputedStyle(probe).backgroundColor; + probe.remove(); +- const nodes = [...document.querySelectorAll(".markdown-code-block pre")]; +- return nodes.length === 2 && nodes.every((node) => ( +- getComputedStyle(node).backgroundColor === expected +- && getComputedStyle(node).borderTopWidth === "0px" +- && getComputedStyle(node.querySelector("code")).backgroundColor === "rgba(0, 0, 0, 0)" +- )); ++ // The code viewer (CodeFile) draws a fence in its shadow root: its pre, else the plain text's. ++ const nodes = [...document.querySelectorAll(".markdown-code-block")] ++ .map((block) => block.querySelector("diffs-container")?.shadowRoot?.querySelector("pre") ?? block.querySelector("pre")); ++ return nodes.length === 2 && nodes.every((node) => { ++ if (!node) return false; ++ const code = getComputedStyle(node.querySelector("code")).backgroundColor; ++ return getComputedStyle(node).backgroundColor === expected ++ && getComputedStyle(node).borderTopWidth === "0px" ++ // the code paints nothing of its own over the block: transparent, or the same colour ++ && (code === "rgba(0, 0, 0, 0)" || code === expected); ++ }); + }); + } + assert.deepEqual(warnings, [], "Theme switches must not mix background shorthand and backgroundColor"); diff --git a/e2e/font-preferences.mjs b/e2e/font-preferences.mjs index b3e0140..04a27d3 100644 --- a/e2e/font-preferences.mjs @@ -14771,6 +15925,35 @@ index cb888c4..a0c5783 100644 const width = Number(value); if (!Number.isFinite(width)) return CHAT_CONTENT_WIDTH_DEFAULT; return Math.max(CHAT_CONTENT_WIDTH_MIN, Math.min(CHAT_CONTENT_WIDTH_MAX, Math.round(width))); +diff --git a/hooks/usePrismLanguages.ts b/hooks/usePrismLanguages.ts +deleted file mode 100644 +index 38b6356..0000000 +--- a/hooks/usePrismLanguages.ts ++++ /dev/null +@@ -1,23 +0,0 @@ +-"use client"; +- +-import { useEffect, useState } from "react"; +-import { loadPrismLanguages, prismLanguagesLoaded } from "@/lib/prism-languages"; +- +-/** +- * True once every Prism language is registered (lib/prism-languages.ts). While +- * `enabled`, a highlighter mounting before that starts the load and renders +- * again when it is done; until then it should render its code as plain text. +- */ +-export function usePrismLanguages(enabled = true): boolean { +- const [ready, setReady] = useState(prismLanguagesLoaded); +- useEffect(() => { +- if (ready || !enabled) return; +- let active = true; +- loadPrismLanguages().then( +- () => { if (active) setReady(true); }, +- () => { /* Stays plain text; the next highlighter to mount retries. */ }, +- ); +- return () => { active = false; }; +- }, [enabled, ready]); +- return ready; +-} diff --git a/lib/diff-patch.test.mjs b/lib/diff-patch.test.mjs new file mode 100644 index 0000000..a8e2fb3 @@ -15022,18 +16205,18 @@ index 0000000..d3e9819 +}); diff --git a/lib/diffs-theme.ts b/lib/diffs-theme.ts new file mode 100644 -index 0000000..7134615 +index 0000000..56f2288 --- /dev/null +++ b/lib/diffs-theme.ts @@ -0,0 +1,110 @@ +/** -+ * The Shiki themes the diff viewer (components/CodeDiff.tsx, @pierre/diffs) highlights with: -+ * VS Code's dark+ and light+, the palette Pi Web's Prism code blocks use (lib/neutral-code-theme.ts), -+ * with their blue tokens turned into the design system's neutral grays. Keywords stand out by -+ * weight instead of hue; strings, numbers, functions and comments keep their colours. The diff's -+ * own colours come from the design system too: additions `success`, deletions `danger`, and the -+ * "modified" accent (selection, changed files) a neutral gray, never the terminal blue Shiki -+ * themes fall back to. Pure, client-safe. ++ * The Shiki themes all of Pi Web's code is highlighted with (components/highlighting.ts: diffs, ++ * fences, the file viewer, tool inputs and outputs): VS Code's dark+ and light+ with their blue ++ * tokens turned into the design system's neutral grays. Keywords stand out by weight instead of ++ * hue; strings, numbers, functions and comments keep their colours. The diff's own colours come ++ * from the design system too: additions `success`, deletions `danger`, and the "modified" accent ++ * (selection, changed files) a neutral gray, never the terminal blue Shiki themes fall back to. ++ * Pure, client-safe. + */ + +export const DIFF_THEMES = { dark: "pi-web-dark", light: "pi-web-light" } as const; @@ -15289,6 +16472,119 @@ index 2e833b0..e09dd9c 100644 + oldContent?: string; + newContent?: string; } +diff --git a/lib/highlight-queue.test.mjs b/lib/highlight-queue.test.mjs +deleted file mode 100644 +index a1d5a54..0000000 +--- a/lib/highlight-queue.test.mjs ++++ /dev/null +@@ -1,38 +0,0 @@ +-import assert from "node:assert/strict"; +-import test from "node:test"; +-import { setTimeout as delay } from "node:timers/promises"; +-import { createJiti } from "jiti"; +- +-const jiti = createJiti(import.meta.url, { moduleCache: false }); +-const { takeHighlightBudget, waitForHighlight } = await jiti.import("./highlight-queue.ts"); +- +-test("a task highlights its first fences up to the budget, the next task starts afresh", async () => { +- assert.equal(takeHighlightBudget(1_500), true); +- assert.equal(takeHighlightBudget(1_000), false); +- assert.equal(takeHighlightBudget(400), true); +- await delay(5); +- assert.equal(takeHighlightBudget(1_900), true); +- await delay(5); +-}); +- +-async function until(condition) { +- for (let waited = 0; !condition(); waited += 5) { +- if (waited > 2_000) throw new Error("timed out"); +- await delay(5); +- } +-} +- +-test("waiting fences get their colors one per slice, newest first, and a cancel drops one", async () => { +- const shown = []; +- waitForHighlight(() => shown.push("top")); +- const cancel = waitForHighlight(() => shown.push("middle")); +- waitForHighlight(() => shown.push("bottom")); +- cancel(); +- assert.deepEqual(shown, []); +- await until(() => shown.length > 0); +- assert.deepEqual(shown, ["bottom"]); +- await until(() => shown.length > 1); +- assert.deepEqual(shown, ["bottom", "top"]); +- await delay(120); +- assert.deepEqual(shown, ["bottom", "top"]); +-}); +diff --git a/lib/highlight-queue.ts b/lib/highlight-queue.ts +deleted file mode 100644 +index fa76036..0000000 +--- a/lib/highlight-queue.ts ++++ /dev/null +@@ -1,63 +0,0 @@ +-// Prism tokenizes a code fence in the render that shows it: about 5-10 ms per +-// 1,000 characters of TypeScript on a desktop (a 32 KB file takes 180 ms). A +-// reply that finishes streaming, or a session opened on a long history, +-// highlighted every fence in that one task. Within a task the first +-// HIGHLIGHT_TASK_BUDGET characters are still highlighted at once; the other +-// fences render without colors first and get them one per idle slice, newest +-// first (the end of a chat is what is on screen). +- +-const HIGHLIGHT_TASK_BUDGET = 2_000; +-const FALLBACK_IDLE_DELAY_MS = 50; +- +-let taskBudget = HIGHLIGHT_TASK_BUDGET; +-let budgetResetQueued = false; +-const waiting: Array<() => void> = []; +-let releaseQueued = false; +- +-/** True when a fence of `chars` characters may be highlighted in this task. */ +-export function takeHighlightBudget(chars: number): boolean { +- if (!budgetResetQueued) { +- budgetResetQueued = true; +- setTimeout(() => { +- taskBudget = HIGHLIGHT_TASK_BUDGET; +- budgetResetQueued = false; +- }, 0); +- } +- if (chars > taskBudget) return false; +- taskBudget -= chars; +- return true; +-} +- +-function whenIdle(run: () => void): void { +- // Safari has no requestIdleCallback. +- if (typeof window !== "undefined" && typeof window.requestIdleCallback === "function") { +- window.requestIdleCallback(run, { timeout: 500 }); +- } else { +- setTimeout(run, FALLBACK_IDLE_DELAY_MS); +- } +-} +- +-function releaseNewest(): void { +- releaseQueued = false; +- waiting.pop()?.(); +- if (waiting.length > 0) queueRelease(); +-} +- +-function queueRelease(): void { +- if (releaseQueued) return; +- releaseQueued = true; +- whenIdle(releaseNewest); +-} +- +-/** +- * Calls `show` in a later idle slice, one waiting fence per slice so each +- * highlight render gets a task of its own. Returns a cancel for unmount. +- */ +-export function waitForHighlight(show: () => void): () => void { +- waiting.push(show); +- queueRelease(); +- return () => { +- const index = waiting.indexOf(show); +- if (index !== -1) waiting.splice(index, 1); +- }; +-} diff --git a/lib/i18n/messages/en.ts b/lib/i18n/messages/en.ts index cd39a31..d2a4229 100644 --- a/lib/i18n/messages/en.ts @@ -15406,19 +16702,16 @@ index d8b6d41..e9a45e1 100644 "chat.filesWritten": "已變更的檔案", "chat.openWrittenFile": "開啟 {name}", "chat.loadEarlier": "向上捲動以載入較早的訊息", -diff --git a/lib/neutral-code-theme.test.mjs b/lib/neutral-code-theme.test.mjs +diff --git a/lib/mermaid-theme.test.mjs b/lib/mermaid-theme.test.mjs new file mode 100644 -index 0000000..a9dc596 +index 0000000..94f5cfd --- /dev/null -+++ b/lib/neutral-code-theme.test.mjs -@@ -0,0 +1,45 @@ ++++ b/lib/mermaid-theme.test.mjs +@@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; -+import { createRequire } from "node:module"; + -+const require = createRequire(import.meta.url); -+const { vscDarkPlus, vs } = require("react-syntax-highlighter/dist/cjs/styles/prism"); -+const load = () => import("./neutral-code-theme.ts"); ++const load = () => import("./mermaid-theme.ts"); + +// A colour is blue when its hue sits between cyan and violet and it is not a gray. +function isBlue(hex) { @@ -15433,21 +16726,6 @@ index 0000000..a9dc596 + return s > 0.2 && h >= 180 && h <= 275; +} + -+test("no token of either code theme is blue; keywords keep standing out by weight", async () => { -+ const { neutralCodeTheme } = await load(); -+ for (const [theme, mode, keyword] of [[vscDarkPlus, "dark", "keyword"], [vs, "light", "keyword"]]) { -+ const out = neutralCodeTheme(theme, mode); -+ const blue = Object.entries(out).filter(([, style]) => isBlue(style.color)).map(([k, style]) => `${k} ${style.color}`); -+ assert.deepEqual(blue, [], `${mode}: blue tokens left`); -+ assert.equal(out[keyword].fontWeight, 600, `${mode}: keywords are bold`); -+ } -+ // the other hues stay: strings, comments -+ assert.equal(neutralCodeTheme(vscDarkPlus, "dark").string.color, vscDarkPlus.string.color); -+ assert.equal(neutralCodeTheme(vs, "light").comment.color, vs.comment.color); -+ // the source themes are not changed -+ assert.equal(vscDarkPlus.keyword.color.toLowerCase(), "#569cd6"); -+}); -+ +test("Mermaid diagrams use the base theme with neutral variables only", async () => { + const { neutralMermaidTheme } = await load(); + for (const dark of [true, false]) { @@ -15457,46 +16735,16 @@ index 0000000..a9dc596 + assert.deepEqual(blue, []); + } +}); -diff --git a/lib/neutral-code-theme.ts b/lib/neutral-code-theme.ts +diff --git a/lib/mermaid-theme.ts b/lib/mermaid-theme.ts new file mode 100644 -index 0000000..ff0d9d6 +index 0000000..512fab9 --- /dev/null -+++ b/lib/neutral-code-theme.ts -@@ -0,0 +1,60 @@ -+import type { CSSProperties } from "react"; -+ ++++ b/lib/mermaid-theme.ts +@@ -0,0 +1,30 @@ +/** -+ * The Prism themes Pi Web highlights code with (VS Code's dark+ and light "vs"), -+ * with their blue tokens turned into the design system's neutral grays: no blue -+ * anywhere in the app, code blocks included. Keywords keep standing out by weight -+ * (600) instead of hue; strings, numbers, functions and comments keep their own -+ * colours. Client-safe and pure. ++ * Mermaid's diagrams in the design system's neutral grays ("base" theme), never its lavender and ++ * blue defaults. Code itself is highlighted by Shiki in the same grays (lib/diffs-theme.ts). + */ -+type PrismTheme = Record; -+ -+const DARK: Record = { -+ "#569cd6": { color: "#e5e5e5", fontWeight: 600 }, // keywords, tags, booleans -+ "#9cdcfe": { color: "#e5e5e5" }, // properties, constants, attribute names -+}; -+ -+const LIGHT: Record = { -+ "#0000ff": { color: "#0a0a0a", fontWeight: 600 }, // keywords, at-rules, attribute values -+ "#00009f": { color: "#0a0a0a", fontWeight: 600 }, -+ "#2b91af": { color: "#404040", fontWeight: 500 }, // class names, JSON keys -+ "#36acaa": { color: "#5c5c5c" }, // numbers, booleans, variables -+}; -+ -+export function neutralCodeTheme(theme: PrismTheme, mode: "dark" | "light"): PrismTheme { -+ const map = mode === "dark" ? DARK : LIGHT; -+ const out: PrismTheme = {}; -+ for (const [selector, style] of Object.entries(theme)) { -+ const color = typeof style.color === "string" ? style.color.toLowerCase() : ""; -+ out[selector] = map[color] ? { ...style, ...map[color] } : { ...style }; -+ } -+ return out; -+} -+ -+/** Mermaid's diagrams in the same neutral grays ("base" theme), never its lavender and blue defaults. */ +export function neutralMermaidTheme(isDark: boolean) { + return { + theme: "base" as const, @@ -15523,6 +16771,146 @@ index 0000000..ff0d9d6 + }, + }; +} +diff --git a/lib/pierre-diffs-split-loader.cjs b/lib/pierre-diffs-split-loader.cjs +new file mode 100644 +index 0000000..ddba9af +--- /dev/null ++++ b/lib/pierre-diffs-split-loader.cjs +@@ -0,0 +1,34 @@ ++// Bundler loader for @pierre/diffs (the diff and code viewers, components/highlighting.ts). Its ++// constants split file contents after each newline with a lookbehind literal, /(?<=\n)/, which ++// Safari parses only from 16.4: a regex literal Safari cannot parse is a SyntaxError for the whole ++// chunk, so on iOS 16.2 no code or diff would show (the same trap as #753, ++// lib/gfm-autolink-email-loader.cjs). ++// ++// The loader builds the same regex at runtime instead, and where lookbehind is missing uses an ++// object whose Symbol.split gives the same pieces: "a\nb\n" -> ["a\n", "b\n"], "a\nb" -> ["a\n", "b"]. ++// The library uses the constant only in `contents.split(SPLIT_WITH_NEWLINES)` (never on ""). ++"use strict"; ++ ++const LOOKBEHIND_DECLARATION = "const SPLIT_WITH_NEWLINES = /(?<=\\n)/;"; ++ ++const REPLACEMENT = ++ "const SPLIT_WITH_NEWLINES = (function () { try { return new RegExp(\"(?<=\\\\n)\"); } " + ++ "catch (_) { return { [Symbol.split](text) { return text.match(/[^\\n]*\\n|[^\\n]+$/g) ?? []; } }; } })();"; ++ ++function rewritePierreDiffsSplit(source) { ++ const index = source.indexOf(LOOKBEHIND_DECLARATION); ++ if (index === -1) { ++ throw new Error( ++ "@pierre/diffs no longer declares SPLIT_WITH_NEWLINES as lib/pierre-diffs-split-loader.cjs expects. " + ++ "Check whether its new code still uses a RegExp lookbehind literal (unparseable before Safari 16.4), " + ++ "then update or remove the loader.", ++ ); ++ } ++ return source.slice(0, index) + REPLACEMENT + source.slice(index + LOOKBEHIND_DECLARATION.length); ++} ++ ++module.exports = function pierreDiffsSplitLoader(source) { ++ return rewritePierreDiffsSplit(source); ++}; ++module.exports.rewritePierreDiffsSplit = rewritePierreDiffsSplit; ++module.exports.REPLACEMENT = REPLACEMENT; +diff --git a/lib/pierre-diffs-split-loader.test.mjs b/lib/pierre-diffs-split-loader.test.mjs +new file mode 100644 +index 0000000..21e74fa +--- /dev/null ++++ b/lib/pierre-diffs-split-loader.test.mjs +@@ -0,0 +1,31 @@ ++import assert from "node:assert/strict"; ++import { readFile } from "node:fs/promises"; ++import { createRequire } from "node:module"; ++import test from "node:test"; ++ ++const require = createRequire(import.meta.url); ++const { rewritePierreDiffsSplit, REPLACEMENT } = require("./pierre-diffs-split-loader.cjs"); ++// the file the bundler loads (the package exports map hides it from require.resolve) ++const constantsPath = new URL("../node_modules/@pierre/diffs/dist/constants.js", import.meta.url); ++ ++test("the library's lookbehind literal is gone from the module the bundler sees", async () => { ++ const out = rewritePierreDiffsSplit(await readFile(constantsPath, "utf8")); ++ // only inside the string handed to new RegExp at runtime ++ assert.doesNotMatch(out.replace(/new RegExp\("[^"]*"\)/g, ""), /\(\?<[=!]/); ++ assert.match(out, /const SPLIT_WITH_NEWLINES = \(function \(\)/); ++}); ++ ++test("both the runtime regex and the fallback split after each newline, keeping it", () => { ++ const lookbehind = new Function(`${REPLACEMENT}; return SPLIT_WITH_NEWLINES;`)(); ++ // the fallback, as a browser without lookbehind gets it ++ const fallback = new Function("RegExp", `${REPLACEMENT}; return SPLIT_WITH_NEWLINES;`)(function () { throw new SyntaxError("no lookbehind"); }); ++ assert.equal(typeof fallback[Symbol.split], "function"); ++ for (const text of ["a\nb\n", "a\nb", "\n\n", "one line", "x\n\ny"]) { ++ assert.deepEqual(text.split(fallback), text.split(/(?<=\n)/), JSON.stringify(text)); ++ assert.deepEqual(text.split(lookbehind), text.split(/(?<=\n)/), JSON.stringify(text)); ++ } ++}); ++ ++test("the build fails loudly when upstream changes the declaration", () => { ++ assert.throws(() => rewritePierreDiffsSplit("const SPLIT_WITH_NEWLINES = /\\n/;"), /no longer declares SPLIT_WITH_NEWLINES/); ++}); +diff --git a/lib/prism-languages.test.mjs b/lib/prism-languages.test.mjs +deleted file mode 100644 +index 2aa0d35..0000000 +--- a/lib/prism-languages.test.mjs ++++ /dev/null +@@ -1,23 +0,0 @@ +-import assert from "node:assert/strict"; +-import test from "node:test"; +-import { createJiti } from "jiti"; +-import { refractor } from "refractor/core"; +- +-const { loadPrismLanguages, prismLanguagesLoaded } = await createJiti(import.meta.url).import("./prism-languages.ts"); +- +-test("languages load into the core PrismLight renders with, aliases included", async () => { +- // PrismLight (react-syntax-highlighter/dist/esm/prism-light) highlights with refractor/core. +- assert.equal(prismLanguagesLoaded(), false); +- assert.equal(refractor.registered("typescript"), false); +- +- const first = loadPrismLanguages(); +- assert.equal(loadPrismLanguages(), first, "one load for every caller"); +- await first; +- +- assert.equal(prismLanguagesLoaded(), true); +- for (const name of ["typescript", "ts", "tsx", "javascript", "js", "bash", "sh", "shell", "python", "py", "json", "yaml", "yml", "css", "markup", "html", "diff", "rust", "go"]) { +- assert.equal(refractor.registered(name), true, `${name} is registered`); +- } +- const tree = refractor.highlight("const a: number = 1;", "ts"); +- assert.ok(tree.children.some((node) => node.type === "element"), "ts is tokenized"); +-}); +diff --git a/lib/prism-languages.ts b/lib/prism-languages.ts +deleted file mode 100644 +index a436aa3..0000000 +--- a/lib/prism-languages.ts ++++ /dev/null +@@ -1,28 +0,0 @@ +-// react-syntax-highlighter's `Prism` build imports refractor/all, which +-// registers every Prism language (about 300) when its module is evaluated: +-// ~650 ms of the first render at 4x CPU throttling on every page load, code on +-// screen or not. Components use the core-only `PrismLight` instead, and the +-// languages load in a chunk of their own the first time a highlighter needs +-// them. refractor/all registers into the same core instance PrismLight +-// renders with, so every language and alias works as it did. +- +-let loaded = false; +-let loading: Promise | null = null; +- +-export function prismLanguagesLoaded(): boolean { +- return loaded; +-} +- +-/** Loads every Prism language once; a failed chunk load may be retried. */ +-export function loadPrismLanguages(): Promise { +- loading ??= import("refractor/all").then( +- () => { +- loaded = true; +- }, +- (error: unknown) => { +- loading = null; +- throw error; +- }, +- ); +- return loading; +-} diff --git a/lib/step-summary.test.mjs b/lib/step-summary.test.mjs new file mode 100644 index 0000000..6cbe005 @@ -15625,8 +17013,59 @@ index 0000000..b0253eb + } + return order.map((kind) => ({ kind, count: counts.get(kind) ?? 0 })).filter((entry) => entry.count > 0); +} +diff --git a/lib/tool-names.ts b/lib/tool-names.ts +index 92d8480..4af2f3d 100644 +--- a/lib/tool-names.ts ++++ b/lib/tool-names.ts +@@ -14,6 +14,14 @@ export function isWriteToolName(toolName: string): boolean { + name.endsWith("_write"); + } + ++export function isReadToolName(toolName: string): boolean { ++ const name = toolName.toLowerCase(); ++ return name === "read" || ++ name.startsWith("read_") || ++ name.endsWith(".read") || ++ name.endsWith("_read"); ++} ++ + export function isEditToolName(toolName: string): boolean { + const name = toolName.toLowerCase(); + return name === "edit" || +diff --git a/next.config.ts b/next.config.ts +index 566fcb0..0ad475b 100644 +--- a/next.config.ts ++++ b/next.config.ts +@@ -15,6 +15,8 @@ try { + // Safari parses only from 16.4, which blanked `/` on iOS 16.2 (#753). The loader + // swaps it for an equivalent built at runtime; both bundlers must run it. + const gfmAutolinkEmailLoader = join(configDir, "lib/gfm-autolink-email-loader.cjs"); ++// @pierre/diffs (the code and diff viewers) ships a lookbehind literal too; the same fix. ++const pierreDiffsSplitLoader = join(configDir, "lib/pierre-diffs-split-loader.cjs"); + + const nextConfig: NextConfig = { + outputFileTracingRoot: configDir, +@@ -32,6 +34,7 @@ const nextConfig: NextConfig = { + turbopack: { + rules: { + "**/mdast-util-gfm-autolink-literal/lib/index.js": { loaders: [gfmAutolinkEmailLoader] }, ++ "**/@pierre/diffs/dist/constants.js": { loaders: [pierreDiffsSplitLoader] }, + }, + }, + webpack(config) { +@@ -39,6 +42,10 @@ const nextConfig: NextConfig = { + test: /[\\/]mdast-util-gfm-autolink-literal[\\/]lib[\\/]index\.js$/, + loader: gfmAutolinkEmailLoader, + }); ++ config.module.rules.push({ ++ test: /[\\/]@pierre[\\/]diffs[\\/]dist[\\/]constants\.js$/, ++ loader: pierreDiffsSplitLoader, ++ }); + return config; + }, + // Node modules keep the syntax they ship unless listed here, and mermaid's diff --git a/package-lock.json b/package-lock.json -index 9cd6e2c..53ea09a 100644 +index 9cd6e2c..2957223 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,8 @@ @@ -15638,7 +17077,31 @@ index 9cd6e2c..53ea09a 100644 "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "js-yaml": "^5.2.3", -@@ -2235,6 +2237,72 @@ +@@ -26,6 +28,7 @@ + "react": "^19.2.4", + "react-dom": "^19.2.4", + "semver": "7.8.5", ++ "shiki": "4.5.0", + "undici": "8.11.0", + "web-push": "^3.6.7" + }, +@@ -40,7 +43,6 @@ + "@types/proper-lockfile": "4.1.4", + "@types/react": "^19", + "@types/react-dom": "^19", +- "@types/react-syntax-highlighter": "^15.5.13", + "@types/semver": "7.8.0", + "@types/web-push": "^3.6.4", + "ansi_up": "^6.0.6", +@@ -53,7 +55,6 @@ + "playwright": "^1.62.1", + "postcss": "^8.5.26", + "react-markdown": "^10.1.0", +- "react-syntax-highlighter": "^16.1.1", + "rehype-katex": "^7.0.1", + "rehype-raw": "^7.0.0", + "rehype-sanitize": "^6.0.0", +@@ -2235,6 +2236,72 @@ "node": ">=12.4.0" } }, @@ -15711,7 +17174,7 @@ index 9cd6e2c..53ea09a 100644 "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", -@@ -2299,6 +2367,119 @@ +@@ -2299,6 +2366,119 @@ "dev": true, "license": "MIT" }, @@ -15831,7 +17294,7 @@ index 9cd6e2c..53ea09a 100644 "node_modules/@smithy/core": { "version": "3.35.1", "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.1.tgz", -@@ -3060,10 +3241,9 @@ +@@ -3060,10 +3240,9 @@ "license": "MIT" }, "node_modules/@types/hast": { @@ -15845,7 +17308,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "*" -@@ -3101,7 +3281,6 @@ +@@ -3101,7 +3280,6 @@ "version": "4.0.4", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", @@ -15853,7 +17316,38 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "*" -@@ -3195,7 +3374,6 @@ +@@ -3123,13 +3301,6 @@ + "undici-types": "~7.18.0" + } + }, +- "node_modules/@types/prismjs": { +- "version": "1.26.6", +- "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.6.tgz", +- "integrity": "sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==", +- "dev": true, +- "license": "MIT" +- }, + "node_modules/@types/proper-lockfile": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@types/proper-lockfile/-/proper-lockfile-4.1.4.tgz", +@@ -3160,16 +3331,6 @@ + "@types/react": "^19.2.0" + } + }, +- "node_modules/@types/react-syntax-highlighter": { +- "version": "15.5.13", +- "resolved": "https://registry.npmjs.org/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz", +- "integrity": "sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "@types/react": "*" +- } +- }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", +@@ -3195,7 +3356,6 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", @@ -15861,7 +17355,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT" }, "node_modules/@types/web-push": { -@@ -3442,7 +3620,6 @@ +@@ -3442,7 +3602,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", @@ -15869,7 +17363,7 @@ index 9cd6e2c..53ea09a 100644 "license": "ISC" }, "node_modules/@unrs/resolver-binding-android-arm-eabi": { -@@ -4267,7 +4444,6 @@ +@@ -4267,7 +4426,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", @@ -15877,7 +17371,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -4306,7 +4482,6 @@ +@@ -4306,7 +4464,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", @@ -15885,7 +17379,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -4317,7 +4492,6 @@ +@@ -4317,7 +4474,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", @@ -15893,7 +17387,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -4365,7 +4539,6 @@ +@@ -4365,7 +4521,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", @@ -15901,7 +17395,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -5157,7 +5330,6 @@ +@@ -5157,7 +5312,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", @@ -15909,7 +17403,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "engines": { "node": ">=6" -@@ -5177,7 +5349,6 @@ +@@ -5177,7 +5331,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", @@ -15917,7 +17411,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "dequal": "^2.0.0" -@@ -5187,6 +5358,15 @@ +@@ -5187,6 +5340,15 @@ "url": "https://github.com/sponsors/wooorm" } }, @@ -15933,7 +17427,28 @@ index 9cd6e2c..53ea09a 100644 "node_modules/dingbat-to-unicode": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dingbat-to-unicode/-/dingbat-to-unicode-1.0.1.tgz", -@@ -6804,6 +6984,29 @@ +@@ -6137,20 +6299,6 @@ + "reusify": "^1.0.4" + } + }, +- "node_modules/fault": { +- "version": "1.0.4", +- "resolved": "https://registry.npmjs.org/fault/-/fault-1.0.4.tgz", +- "integrity": "sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "format": "^0.2.0" +- }, +- "funding": { +- "type": "github", +- "url": "https://github.com/sponsors/wooorm" +- } +- }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", +@@ -6804,6 +6952,29 @@ "url": "https://opencollective.com/unified" } }, @@ -15963,7 +17478,7 @@ index 9cd6e2c..53ea09a 100644 "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", -@@ -6873,7 +7076,6 @@ +@@ -6873,7 +7044,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", @@ -15971,7 +17486,21 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/hast": "^3.0.0" -@@ -6949,7 +7151,6 @@ +@@ -6927,13 +7097,6 @@ + "node": "*" + } + }, +- "node_modules/highlightjs-vue": { +- "version": "1.0.0", +- "resolved": "https://registry.npmjs.org/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz", +- "integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==", +- "dev": true, +- "license": "CC0-1.0" +- }, + "node_modules/html-url-attributes": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", +@@ -6949,7 +7112,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", @@ -15979,20 +17508,33 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -8172,6 +8373,12 @@ - "url": "https://github.com/sponsors/wooorm" +@@ -8157,20 +8319,11 @@ + "underscore": "^1.13.1" } }, +- "node_modules/lowlight": { +- "version": "1.20.0", +- "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz", +- "integrity": "sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "fault": "^1.0.0", +- "highlight.js": "~10.7.0" +- }, +- "funding": { +- "type": "github", +- "url": "https://github.com/sponsors/wooorm" +- } + "node_modules/lru_map": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/lru_map/-/lru_map-0.4.1.tgz", + "integrity": "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg==", + "license": "MIT" -+ }, + }, "node_modules/lru-cache": { "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", -@@ -8554,7 +8761,6 @@ +@@ -8554,7 +8707,6 @@ "version": "13.2.1", "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", @@ -16000,7 +17542,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/hast": "^3.0.0", -@@ -9111,7 +9317,6 @@ +@@ -9111,7 +9263,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", @@ -16008,7 +17550,7 @@ index 9cd6e2c..53ea09a 100644 "funding": [ { "type": "GitHub Sponsors", -@@ -9238,7 +9443,6 @@ +@@ -9238,7 +9389,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", @@ -16016,7 +17558,7 @@ index 9cd6e2c..53ea09a 100644 "funding": [ { "type": "GitHub Sponsors", -@@ -9312,7 +9516,6 @@ +@@ -9312,7 +9462,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", @@ -16024,7 +17566,7 @@ index 9cd6e2c..53ea09a 100644 "funding": [ { "type": "GitHub Sponsors", -@@ -9357,7 +9560,6 @@ +@@ -9357,7 +9506,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", @@ -16032,7 +17574,7 @@ index 9cd6e2c..53ea09a 100644 "funding": [ { "type": "GitHub Sponsors", -@@ -9374,7 +9576,6 @@ +@@ -9374,7 +9522,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", @@ -16040,7 +17582,7 @@ index 9cd6e2c..53ea09a 100644 "funding": [ { "type": "GitHub Sponsors", -@@ -9789,6 +9990,23 @@ +@@ -9789,6 +9936,23 @@ "url": "https://github.com/sponsors/ljharb" } }, @@ -16064,7 +17606,24 @@ index 9cd6e2c..53ea09a 100644 "node_modules/openai": { "version": "7.19.0", "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz", -@@ -10194,7 +10412,6 @@ +@@ -10141,16 +10305,6 @@ + "node": ">= 0.8.0" + } + }, +- "node_modules/prismjs": { +- "version": "1.30.0", +- "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", +- "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==", +- "dev": true, +- "license": "MIT", +- "engines": { +- "node": ">=6" +- } +- }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", +@@ -10194,7 +10348,6 @@ "version": "7.1.0", "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", @@ -16072,19 +17631,60 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -10425,6 +10642,30 @@ - "url": "https://github.com/sponsors/wooorm" +@@ -10334,27 +10487,6 @@ + "react": ">=18" } }, +- "node_modules/react-syntax-highlighter": { +- "version": "16.1.1", +- "resolved": "https://registry.npmjs.org/react-syntax-highlighter/-/react-syntax-highlighter-16.1.1.tgz", +- "integrity": "sha512-PjVawBGy80C6YbC5DDZJeUjBmC7skaoEUdvfFQediQHgCL7aKyVHe57SaJGfQsloGDac+gCpTfRdtxzWWKmCXA==", +- "dev": true, +- "license": "MIT", +- "dependencies": { +- "@babel/runtime": "^7.28.4", +- "highlight.js": "^10.4.1", +- "highlightjs-vue": "^1.0.0", +- "lowlight": "^1.17.0", +- "prismjs": "^1.30.0", +- "refractor": "^5.0.0" +- }, +- "engines": { +- "node": ">= 16.20.2" +- }, +- "peerDependencies": { +- "react": ">= 0.14.0" +- } +- }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", +@@ -10408,23 +10540,30 @@ + "url": "https://github.com/sponsors/ljharb" + } + }, +- "node_modules/refractor": { +- "version": "5.0.0", +- "resolved": "https://registry.npmjs.org/refractor/-/refractor-5.0.0.tgz", +- "integrity": "sha512-QXOrHQF5jOpjjLfiNk5GFnWhRXvxjUVnlFxkeDmewR5sXkr3iM46Zo+CnRR8B+MDVqkULW4EcLVcRBNOPXHosw==", +- "dev": true, + "node_modules/regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz", + "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==", -+ "license": "MIT", -+ "dependencies": { + "license": "MIT", + "dependencies": { +- "@types/hast": "^3.0.0", +- "@types/prismjs": "^1.0.0", +- "hastscript": "^9.0.0", +- "parse-entities": "^4.0.0" +- }, +- "funding": { +- "type": "github", +- "url": "https://github.com/sponsors/wooorm" + "regex-utilities": "^2.3.0" -+ } -+ }, + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", @@ -16103,7 +17703,7 @@ index 9cd6e2c..53ea09a 100644 "node_modules/regexp.prototype.flags": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", -@@ -10962,6 +11203,25 @@ +@@ -10962,6 +11101,25 @@ "node": ">=8" } }, @@ -16129,7 +17729,7 @@ index 9cd6e2c..53ea09a 100644 "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", -@@ -11057,7 +11317,6 @@ +@@ -11057,7 +11215,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", @@ -16137,7 +17737,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -11243,7 +11502,6 @@ +@@ -11243,7 +11400,6 @@ "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", @@ -16145,7 +17745,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "character-entities-html4": "^2.0.0", -@@ -11449,7 +11707,6 @@ +@@ -11449,7 +11605,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", @@ -16153,7 +17753,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "funding": { "type": "github", -@@ -11737,7 +11994,6 @@ +@@ -11737,7 +11892,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", @@ -16161,7 +17761,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0" -@@ -11751,7 +12007,6 @@ +@@ -11751,7 +11905,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", @@ -16169,7 +17769,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0" -@@ -11780,7 +12035,6 @@ +@@ -11780,7 +11933,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", @@ -16177,7 +17777,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0" -@@ -11794,7 +12048,6 @@ +@@ -11794,7 +11946,6 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", @@ -16185,7 +17785,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", -@@ -11810,7 +12063,6 @@ +@@ -11810,7 +11961,6 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", @@ -16193,7 +17793,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", -@@ -11908,7 +12160,6 @@ +@@ -11908,7 +12058,6 @@ "version": "6.0.3", "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", @@ -16201,7 +17801,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", -@@ -11938,7 +12189,6 @@ +@@ -11938,7 +12087,6 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", @@ -16209,7 +17809,7 @@ index 9cd6e2c..53ea09a 100644 "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", -@@ -12180,7 +12430,6 @@ +@@ -12180,7 +12328,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", @@ -16218,7 +17818,7 @@ index 9cd6e2c..53ea09a 100644 "funding": { "type": "github", diff --git a/package.json b/package.json -index 14d9cb5..b9b2b64 100644 +index 14d9cb5..be8ed9f 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,8 @@ @@ -16230,6 +17830,30 @@ index 14d9cb5..b9b2b64 100644 "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "js-yaml": "^5.2.3", +@@ -64,6 +66,7 @@ + "react": "^19.2.4", + "react-dom": "^19.2.4", + "semver": "7.8.5", ++ "shiki": "4.5.0", + "undici": "8.11.0", + "web-push": "^3.6.7" + }, +@@ -75,7 +78,6 @@ + "@types/proper-lockfile": "4.1.4", + "@types/react": "^19", + "@types/react-dom": "^19", +- "@types/react-syntax-highlighter": "^15.5.13", + "@types/semver": "7.8.0", + "@types/web-push": "^3.6.4", + "ansi_up": "^6.0.6", +@@ -88,7 +90,6 @@ + "playwright": "^1.62.1", + "postcss": "^8.5.26", + "react-markdown": "^10.1.0", +- "react-syntax-highlighter": "^16.1.1", + "rehype-katex": "^7.0.1", + "rehype-raw": "^7.0.0", + "rehype-sanitize": "^6.0.0", diff --git a/public/icons/apple-touch-icon.png b/public/icons/apple-touch-icon.png index 5f7f2b155e7b5c4517b8556909f9dcbe6d9d6f40..17beb7135ed0a030d2d6e6b0342749914855c071 100644 GIT binary patch