A desktop coding agent with free access to frontier models.
TypeScript
feat: split editor, markdown preview and image preview
ogsamratc980f5641643
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 1df7b56a..922bf8ab 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -2864,6 +2864,14 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: stimeoutMs,}),+ /** An image file's bytes for the editor's image preview (image types only, capped by the server). */+ editorRaw: (workspaceId: string, path: string) =>+ requestBinary(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/raw?path=${encodeURIComponent(path)}`, {+ token,+ hostToken,+ timeoutMs: 30_000,+ }),+editorGitStatus: (workspaceId: string) =>requestJson<OmniRushEditorGitStatus>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/git/status`, { token, hostToken, timeoutMs: 30_000 }),diff --git a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx b/apps/app/src/react-app/domains/session/editor/editor-panel.tsxindex 83831213..daa674af 100644--- a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx+++ b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx@@ -29,9 +29,12 @@ import {SquareTerminal,Undo2,X,+ Columns2,+ Eye,} from "lucide-react";import type { Client } from "@/app/types";+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";import type { OmniRushEditorGitFile, OmniRushEditorGitStatus, OmniRushServerClient } from "@/app/lib/omnirush-server";import { Button } from "@/components/ui/button";import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";@@ -72,6 +75,18 @@ import { baselinesForTurns, turnFileChange, type TurnFileChange } from "./reviewimport "./editor.css";import { AUTO_SAVE_DELAY_MS, useEditorSettings } from "./editor-settings";import { GitGutter } from "./git-gutter";+import { Group2Editor } from "./group2-editor";+import { ImageView, isImagePath } from "./image-view";+import { MarkdownPreview } from "./markdown-preview";+import { openDesktopUrl } from "@/app/lib/desktop";+import { useGroupRef } from "react-resizable-panels";+import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";++/** What the main group shows: a text file or diff (Monaco), a Markdown preview, or an image. */+type PanelSurface = SurfaceDoc | { kind: "preview"; key: string; doc: FileDoc } | { kind: "image"; key: string; path: string };+/** Each editor group needs this much width; below twice this the split folds away. */+const MIN_GROUP_PX = 320;+const isMarkdownPath = (path: string) => /\.(md|markdown|mdx)$/i.test(path);/** How long a file stays the active one before its language features start. */const LSP_DWELL_MS = 2500;@@ -542,7 +557,7 @@ export default function EditorPanel(props: EditorPanelProps) {const reviewScope = useEditorStore((store) => store.reviewScope);const sideOpen = useEditorStore((store) => store.sideOpen);const activeTab = state.tabs.find((tab) => tab.id === state.activeId) ?? null;- const [surface, setSurface] = useState<SurfaceDoc | null>(null);+ const [surface, setSurface] = useState<PanelSurface | null>(null);const surfaceHandle = useRef<SurfaceHandle | null>(null);const [surfaceReady, setSurfaceReady] = useState(false);const pendingReveal = useRef<{ path: string; line: number; column: number; endColumn?: number } | null>(null);@@ -879,7 +894,11 @@ export default function EditorPanel(props: EditorPanelProps) {}const key = `${workspaceId}|${activeTab.id}`;void (async () => {- if (activeTab.kind === "file") {+ if (activeTab.kind === "file" && isImagePath(activeTab.path)) {+ setSurface({ kind: "image", key, path: activeTab.path });+ return;+ }+ if (activeTab.kind === "file" || activeTab.kind === "preview") {const opened = await docs.open(activeTab.path);if (cancelled) return;if (!opened.ok) {@@ -892,7 +911,7 @@ export default function EditorPanel(props: EditorPanelProps) {setTabError("This file was deleted.");return;}- setSurface({ kind: "file", key, doc: opened.doc });+ setSurface({ kind: activeTab.kind, key, doc: opened.doc });return;}if (activeTab.kind === "review") {@@ -919,6 +938,7 @@ export default function EditorPanel(props: EditorPanelProps) {});return;}+ if (activeTab.kind !== "git") return;// Git: the file against HEAD (staged view) or the index (working-tree view).const [original, opened] = await Promise.all([client.editorGitOriginal(workspaceId, activeTab.path, activeTab.ref).catch(() => null),@@ -1158,6 +1178,124 @@ export default function EditorPanel(props: EditorPanelProps) {}}, [client, queryClient, workspaceId]);+ // ── second editor group (split editor) ────────────────────────────────+ const group2 = state.group2 ?? null;+ const group2Tab = group2?.tabs.find((tab) => tab.id === group2.activeId) ?? null;+ const focusedGroup = useEditorStore((store) => store.focusedGroup);+ const [group2Doc, setGroup2Doc] = useState<FileDoc | null>(null);+ const [group2Error, setGroup2Error] = useState<string | null>(null);+ const group2EditorRef = useRef<MonacoApi.editor.IStandaloneCodeEditor | null>(null);+ const [group2Ready, setGroup2Ready] = useState(false);+ useEffect(() => {+ let cancelled = false;+ setGroup2Error(null);+ if (!group2Tab || (group2Tab.kind !== "file" && group2Tab.kind !== "preview") || isImagePath(group2Tab.path)) {+ setGroup2Doc(null);+ return;+ }+ void docs.open(group2Tab.path).then((opened) => {+ if (cancelled) return;+ if (!opened.ok) {+ setGroup2Doc(null);+ setGroup2Error(opened.message);+ return;+ }+ setGroup2Doc(opened.doc);+ });+ return () => {+ cancelled = true;+ };+ }, [docs, group2Tab, docsTick]);+ // The git gutter in group 2 too.+ useEffect(() => {+ const editor = group2EditorRef.current;+ if (!group2Ready || !editor || !group2Doc || group2Tab?.kind !== "file" || !gitFiles) return;+ if (editor.getModel() !== group2Doc.model) return;+ const changedInGit = gitFiles.some((file) => file.path === group2Doc.path);+ return gutter.attach(editor, group2Doc.model, group2Doc.path, changedInGit, () => docs.isDirty(group2Doc));+ }, [docs, gitFiles, group2Doc, group2Ready, group2Tab, gutter]);++ // The editor area's width: two groups need room, else the split folds into one group (tabs and unsaved text kept).+ const editorAreaRef = useRef<HTMLDivElement | null>(null);+ const [editorWidth, setEditorWidth] = useState(0);+ useEffect(() => {+ const element = editorAreaRef.current;+ if (!element) return;+ const observer = new ResizeObserver(([entry]) => setEditorWidth(Math.round(entry?.contentRect.width ?? 0)));+ observer.observe(element);+ return () => observer.disconnect();+ }, []);+ const splitAllowed = editorWidth === 0 || editorWidth >= MIN_GROUP_PX * 2;+ useEffect(() => {+ if (!group2 || splitAllowed) return;+ useEditorStore.getState().foldGroup2(workspaceId);+ toast("The window got too narrow for two editor groups, so they were joined. Split again when it is wider.");+ }, [group2, splitAllowed, workspaceId]);+ const splitGroupRef = useGroupRef();++ const focusGroup = useCallback((group: 1 | 2) => {+ useEditorStore.getState().setFocusedGroup(group);+ const editor = group === 2 ? group2EditorRef.current : surfaceHandle.current?.activeEditor();+ window.setTimeout(() => editor?.focus(), 0);+ }, []);++ /** Cmd/Ctrl+\: the current file in the other group (a new group on the right when there is one group). */+ const splitEditor = useCallback(() => {+ const store = useEditorStore.getState();+ if (!splitAllowed) {+ toast("Widen the window or hide the file tree to split the editor.");+ return;+ }+ if (store.focusedGroup === 2 && group2Tab) {+ store.openTab(workspaceId, group2Tab);+ focusGroup(1);+ return;+ }+ if (!activeTab || (activeTab.kind !== "file" && activeTab.kind !== "preview")) {+ toast("Open a file to split the editor.");+ return;+ }+ store.openTab2(workspaceId, { ...activeTab });+ focusGroup(2);+ }, [activeTab, focusGroup, group2Tab, splitAllowed, workspaceId]);++ /** Markdown preview: in the other group (`side`) or in the focused group. */+ const openPreview = useCallback((where: "side" | "here") => {+ const store = useEditorStore.getState();+ const source = store.focusedGroup === 2 ? group2Tab : activeTab;+ if (!source || !isMarkdownPath(source.path)) {+ toast("Open a Markdown file to preview it.");+ return;+ }+ const tab: EditorTab = { id: tabId({ kind: "preview", path: source.path }), kind: "preview", path: source.path };+ const inGroup2 = (store.focusedGroup === 2) === (where === "here");+ if (inGroup2 && !splitAllowed && !group2) {+ store.openTab(workspaceId, tab);+ return;+ }+ if (inGroup2) store.openTab2(workspaceId, tab);+ else {+ store.openTab(workspaceId, tab);+ store.setFocusedGroup(1);+ }+ }, [activeTab, group2, group2Tab, splitAllowed, workspaceId]);++ const moveToOtherGroup = useCallback((tab: EditorTab, from: 1 | 2, keepOpen: boolean) => {+ const store = useEditorStore.getState();+ if (from === 1) {+ if (!splitAllowed) {+ toast("Widen the window or hide the file tree to split the editor.");+ return;+ }+ store.openTab2(workspaceId, { ...tab });+ if (!keepOpen) store.closeTab(workspaceId, tab.id);+ } else {+ store.openTab(workspaceId, { ...tab });+ store.setFocusedGroup(1);+ if (!keepOpen) store.closeTab2(workspaceId, tab.id);+ }+ }, [splitAllowed, workspaceId]);+// Commands from the app's shortcuts and palette (use-shell-shortcuts.ts, session-route.tsx).useEffect(() => {const onCommand = (event: Event) => {@@ -1178,11 +1316,19 @@ export default function EditorPanel(props: EditorPanelProps) {editor?.trigger("palette", "editor.action.quickOutline", null);} else if (command === "outline") {useEditorStore.getState().setView(workspaceId, "files");+ } else if (command === "split") {+ splitEditor();+ } else if (command === "preview-side") {+ openPreview("side");+ } else if (command === "preview-here") {+ openPreview("here");+ } else if (command === "focus-other-group") {+ if (useEditorStore.getState().byWorkspace[workspaceId]?.group2) focusGroup(useEditorStore.getState().focusedGroup === 1 ? 2 : 1);}};window.addEventListener("omnirush:editor-command", onCommand);return () => window.removeEventListener("omnirush:editor-command", onCommand);- }, [workspaceId]);+ }, [focusGroup, openPreview, splitEditor, workspaceId]);// ── keys ───────────────────────────────────────────────────────────────const panelRef = useRef<HTMLDivElement | null>(null);@@ -1239,7 +1385,12 @@ export default function EditorPanel(props: EditorPanelProps) {selected={activePath}loading={treeQuery.isFetching}error={treeQuery.isError}- onOpen={openFile}+ onOpen={(path) => {+ // In the group that has the keyboard, like VS Code.+ const store = useEditorStore.getState();+ if (store.focusedGroup === 2 && store.byWorkspace[workspaceId]?.group2) store.openTab2(workspaceId, { id: tabId({ kind: "file", path }), kind: "file", path });+ else openFile(path);+ }}onRefresh={() => void treeQuery.refetch()}/></div>@@ -1280,49 +1431,104 @@ export default function EditorPanel(props: EditorPanelProps) {</div>);- const main = (- <div className="flex h-full min-h-0 min-w-0 flex-col">- <div className="flex h-8 shrink-0 items-stretch overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" data-editor-tabs>- {state.tabs.map((tab) => {- const active = tab.id === state.activeId;- const name = tab.path.split("/").pop() ?? tab.path;- const isDirty = tab.kind === "file" && dirty?.[tab.path];- return (- <div- key={tab.id}- role="tab"- aria-selected={active}- title={tab.path}- data-editor-tab={tab.id}- onMouseDown={(event) => {- if (event.button === 1) {- event.preventDefault();- closeTab(tab);- }+ const mac = /Mac/i.test(navigator.platform);+ const renderTab = (tab: EditorTab, group: 1 | 2, active: boolean) => {+ const name = tab.path.split("/").pop() ?? tab.path;+ const isDirty = (tab.kind === "file") && dirty?.[tab.path];+ const focused = group === focusedGroup;+ const close = () => (group === 1 ? closeTab(tab) : useEditorStore.getState().closeTab2(workspaceId, tab.id));+ const canMove = tab.kind === "file" || tab.kind === "preview";+ return (+ <ContextMenu key={tab.id}>+ <ContextMenuTrigger className="flex shrink-0">+ <div+ role="tab"+ aria-selected={active}+ title={tab.path}+ data-editor-tab={tab.id}+ data-editor-tab-group={group}+ onMouseDown={(event) => {+ if (event.button === 1) {+ event.preventDefault();+ close();+ }+ }}+ className={cn(+ "group flex max-w-48 shrink-0 cursor-pointer items-center gap-1.5 border-e border-border ps-3 pe-1.5 text-xs",+ active+ ? cn("bg-background text-foreground", focused || !group2 ? "shadow-[inset_0_-2px_0_var(--primary)]" : "shadow-[inset_0_-2px_0_var(--border)]")+ : "text-muted-foreground hover:text-foreground",+ )}+ onClick={() => (group === 1 ? useEditorStore.getState().selectTab(workspaceId, tab.id) : useEditorStore.getState().selectTab2(workspaceId, tab.id))}+ >+ {tab.kind === "review" ? <CircleDot className="size-3 shrink-0 text-link" /> : tab.kind === "git" ? <GitBranch className="size-3 shrink-0" /> : tab.kind === "preview" ? <Eye className="size-3 shrink-0" /> : null}+ <span className="truncate">{tab.kind === "preview" ? `Preview ${name}` : name}{tab.kind === "git" ? ` (${tab.ref === "HEAD" ? "staged" : "working"})` : ""}</span>+ <button+ type="button"+ aria-label={`Close ${name}`}+ onClick={(event) => {+ event.stopPropagation();+ close();}}- className={cn(- "group flex max-w-48 shrink-0 cursor-pointer items-center gap-1.5 border-e border-border ps-3 pe-1.5 text-xs",- active ? "bg-background text-foreground shadow-[inset_0_-2px_0_var(--primary)]" : "text-muted-foreground hover:text-foreground",- )}- onClick={() => useEditorStore.getState().selectTab(workspaceId, tab.id)}+ className="flex size-4 items-center justify-center rounded hover:bg-muted">- {tab.kind === "review" ? <CircleDot className="size-3 shrink-0 text-link" /> : tab.kind === "git" ? <GitBranch className="size-3 shrink-0" /> : null}- <span className="truncate">{name}{tab.kind === "git" ? ` (${tab.ref === "HEAD" ? "staged" : "working"})` : ""}</span>- <button- type="button"- aria-label={`Close ${name}`}- onClick={(event) => {- event.stopPropagation();- closeTab(tab);- }}- className="flex size-4 items-center justify-center rounded hover:bg-muted"- >- {isDirty ? <span className="size-2 rounded-full bg-foreground group-hover:hidden" /> : null}- <X className={cn("size-3", isDirty && "hidden group-hover:block")} />- </button>- </div>- );- })}+ {isDirty ? <span className="size-2 rounded-full bg-foreground group-hover:hidden" /> : null}+ <X className={cn("size-3", isDirty && "hidden group-hover:block")} />+ </button>+ </div>+ </ContextMenuTrigger>+ <ContextMenuContent>+ <ContextMenuItem disabled={!canMove} onClick={() => moveToOtherGroup(tab, group, false)}>Move to other group</ContextMenuItem>+ <ContextMenuItem disabled={!canMove} onClick={() => moveToOtherGroup(tab, group, true)}>Open in other group</ContextMenuItem>+ {isMarkdownPath(tab.path) && tab.kind === "file" ? (+ <ContextMenuItem onClick={() => openPreview("side")}>Open preview to the side</ContextMenuItem>+ ) : null}+ <ContextMenuItem onClick={close}>Close</ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ );+ };++ const focusedTab = focusedGroup === 2 ? group2Tab : activeTab;+ const tabTools = (+ <div className="ms-auto flex shrink-0 items-center gap-0.5 px-1">+ {focusedTab && focusedTab.kind === "file" && isMarkdownPath(focusedTab.path) ? (+ <Tooltip>+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" aria-label="Open preview to the side" onClick={() => openPreview("side")} data-editor-preview-button><Eye /></Button>} />+ <TooltipContent>Open preview to the side ({mac ? "⌘⇧V" : "Ctrl+Shift+V"})</TooltipContent>+ </Tooltip>+ ) : null}+ <Tooltip>+ <TooltipTrigger+ render={(+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Split editor"+ aria-disabled={!splitAllowed}+ className={cn(!splitAllowed && "opacity-50")}+ onClick={splitEditor}+ data-editor-split+ >+ <Columns2 />+ </Button>+ )}+ />+ <TooltipContent>{splitAllowed ? `Split editor (${mac ? "⌘\\" : "Ctrl+\\"})` : "Widen the window or hide the file tree to split"}</TooltipContent>+ </Tooltip>+ </div>+ );++ const group1 = (+ <div+ className="flex h-full min-h-0 min-w-0 flex-col"+ data-editor-group="1"+ onFocusCapture={() => useEditorStore.getState().setFocusedGroup(1)}+ onPointerDownCapture={() => useEditorStore.getState().setFocusedGroup(1)}+ >+ <div className="flex h-8 shrink-0 items-stretch overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" data-editor-tabs>+ {state.tabs.map((tab) => renderTab(tab, 1, tab.id === state.activeId))}+ {!group2 ? tabTools : null}</div>{activeTab?.kind === "review" ? (<div className="flex h-8 shrink-0 items-center gap-2 overflow-hidden whitespace-nowrap border-b border-border bg-primary/5 px-3 text-xs" data-editor-review-bar>@@ -1364,9 +1570,10 @@ export default function EditorPanel(props: EditorPanelProps) {</div>) : null}<div className={cn("flex min-h-0 flex-1", state.tabs.length === 0 && "hidden")}>+ <div className={cn("flex min-h-0 min-w-0 flex-1", (surface?.kind === "preview" || surface?.kind === "image") && "hidden")}><EditorSurfacemonaco={monaco}- surface={surface}+ surface={surface && (surface.kind === "file" || surface.kind === "diff") ? surface : null}onSave={() => void save()}onCursor={setCursor}onHunks={setHunks}@@ -1377,8 +1584,104 @@ export default function EditorPanel(props: EditorPanelProps) {setSurfaceReady(Boolean(handle));}}/>+ </div>+ {surface?.kind === "preview" ? (+ <MarkdownPreview+ client={client}+ workspaceId={workspaceId}+ path={surface.doc.path}+ model={surface.doc.model}+ isDirty={() => docs.isDirty(surface.doc)}+ onOpenFile={openFile}+ onOpenExternal={(url) => void openDesktopUrl(url).catch(() => toast.error("Could not open the link."))}+ />+ ) : null}+ {surface?.kind === "image" ? <ImageView client={client} workspaceId={workspaceId} path={surface.path} /> : null}</div></div>+ </div>+ );++ const group2View = group2 ? (+ <div+ className="flex h-full min-h-0 min-w-0 flex-col"+ data-editor-group="2"+ onFocusCapture={() => useEditorStore.getState().setFocusedGroup(2)}+ onPointerDownCapture={() => useEditorStore.getState().setFocusedGroup(2)}+ >+ <div className="flex h-8 shrink-0 items-stretch overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" aria-label="Second editor group" data-editor-tabs-2>+ {group2.tabs.map((tab) => renderTab(tab, 2, tab.id === group2.activeId))}+ {tabTools}+ <Tooltip>+ <TooltipTrigger+ render={(+ <Button+ variant="ghost"+ size="icon-xs"+ className="my-auto me-1 shrink-0"+ aria-label="Close group"+ onClick={() => {+ for (const tab of group2.tabs) useEditorStore.getState().closeTab2(workspaceId, tab.id);+ }}+ data-editor-close-group+ >+ <X />+ </Button>+ )}+ />+ <TooltipContent>Close group (its tabs close; unsaved text stays until you reopen the file)</TooltipContent>+ </Tooltip>+ </div>+ {group2Error ? <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{group2Error}</div> : null}+ <div className={cn("flex min-h-0 flex-1", (group2Error || group2Tab?.kind !== "file" || isImagePath(group2Tab.path)) && "hidden")}>+ <Group2Editor+ monaco={monaco}+ model={group2Tab?.kind === "file" && group2Doc?.path === group2Tab.path ? group2Doc.model : null}+ onSave={() => {+ if (group2Tab) void saveFile(group2Tab.path, "manual");+ }}+ onFocus={() => useEditorStore.getState().setFocusedGroup(2)}+ onAgentAction={agentAction}+ onReady={(editor) => {+ group2EditorRef.current = editor;+ setGroup2Ready(Boolean(editor));+ // Just split (Cmd/Ctrl+\): the new group takes the keyboard.+ if (editor && useEditorStore.getState().focusedGroup === 2) window.setTimeout(() => editor.focus(), 0);+ }}+ />+ </div>+ {group2Tab?.kind === "preview" && group2Doc && group2Doc.path === group2Tab.path ? (+ <MarkdownPreview+ client={client}+ workspaceId={workspaceId}+ path={group2Doc.path}+ model={group2Doc.model}+ isDirty={() => docs.isDirty(group2Doc)}+ onOpenFile={(path) => useEditorStore.getState().openTab2(workspaceId, { id: tabId({ kind: "file", path }), kind: "file", path })}+ onOpenExternal={(url) => void openDesktopUrl(url).catch(() => toast.error("Could not open the link."))}+ />+ ) : null}+ {group2Tab?.kind === "file" && isImagePath(group2Tab.path) ? <ImageView client={client} workspaceId={workspaceId} path={group2Tab.path} /> : null}+ </div>+ ) : null;++ const main = (+ <div className="flex h-full min-h-0 min-w-0 flex-col" ref={editorAreaRef}>+ <div className="flex min-h-0 flex-1">+ {/* Always a panel group, so splitting adds group 2 beside group 1 without rebuilding group 1's editor. */}+ <ResizablePanelGroup orientation="horizontal" className="h-full min-h-0" groupRef={splitGroupRef}>+ <ResizablePanel id="editor-group-1" minSize={`${MIN_GROUP_PX}px`} className="min-h-0 min-w-0">{group1}</ResizablePanel>+ {group2View && splitAllowed ? (+ <>+ <ResizableHandle+ aria-label="Resize editor groups (double-click: equal widths)"+ onDoubleClick={() => splitGroupRef.current?.setLayout({ "editor-group-1": 50, "editor-group-2": 50 })}+ />+ <ResizablePanel id="editor-group-2" minSize={`${MIN_GROUP_PX}px`} className="min-h-0 min-w-0">{group2View}</ResizablePanel>+ </>+ ) : null}+ </ResizablePanelGroup>+ </div><div className="flex h-6 shrink-0 items-center gap-3 overflow-hidden whitespace-nowrap border-t border-border px-3 text-[11px] text-muted-foreground" data-editor-status>{branch ? <span className="flex min-w-0 items-center gap-1 truncate"><GitBranch className="size-3 shrink-0" />{branch}</span> : null}{gitQuery.data?.repo ? <span className="shrink-0">{gitQuery.data.files.length} changed</span> : null}@@ -1401,7 +1704,6 @@ export default function EditorPanel(props: EditorPanelProps) {</div>);- const mac = /Mac/i.test(navigator.platform);const railItem = (view: EditorSideView, label: string, icon: ReactNode, shortcut: string | null, badge?: number) => {const active = state.view === view && sideOpen;return (@@ -1572,9 +1874,12 @@ export default function EditorPanel(props: EditorPanelProps) {<QuickOpenfiles={files}recent={recentRef.current}- onOpen={(path) => {+ onOpen={(path, side) => {useEditorStore.getState().setQuickOpen(false);- openFile(path);+ const store = useEditorStore.getState();+ const inGroup2 = side ? splitAllowed : store.focusedGroup === 2 && Boolean(store.byWorkspace[workspaceId]?.group2);+ if (inGroup2) store.openTab2(workspaceId, { id: tabId({ kind: "file", path }), kind: "file", path });+ else openFile(path);}}onClose={() => useEditorStore.getState().setQuickOpen(false)}/>diff --git a/apps/app/src/react-app/domains/session/editor/editor-settings.ts b/apps/app/src/react-app/domains/session/editor/editor-settings.tsindex 5a1de2b3..317bb662 100644--- a/apps/app/src/react-app/domains/session/editor/editor-settings.ts+++ b/apps/app/src/react-app/domains/session/editor/editor-settings.ts@@ -77,9 +77,8 @@ export const EDITOR_SHORTCUTS: Array<{ keys: string; action: string }> = [{ keys: "F8", action: "Next problem" },{ keys: "Cmd/Ctrl+S", action: "Save" },{ keys: "Cmd/Ctrl+\\", action: "Split editor" },- { keys: "Cmd/Ctrl+K Cmd/Ctrl+Left / Right", action: "Focus the other editor group" },- { keys: "Cmd/Ctrl+K V", action: "Markdown preview in the other group" },- { keys: "Cmd/Ctrl+Shift+V", action: "Markdown preview in this group" },+ { keys: "Cmd/Ctrl+Shift+V", action: "Markdown preview in the other group" },+ { keys: "Cmd/Ctrl+Enter (in Go to file)", action: "Open the file in the other group" },{ keys: "Cmd/Ctrl+L", action: "Ask about selection" },{ keys: "Cmd/Ctrl+J", action: "Show or hide the bottom panel" },{ keys: "Ctrl+`", action: "Terminal" },diff --git a/apps/app/src/react-app/domains/session/editor/editor-store.ts b/apps/app/src/react-app/domains/session/editor/editor-store.tsindex ed4207f2..32371995 100644--- a/apps/app/src/react-app/domains/session/editor/editor-store.ts+++ b/apps/app/src/react-app/domains/session/editor/editor-store.ts@@ -11,7 +11,12 @@ export type EditorTab =/** The agent's change to one file, for review (accept/reject per hunk). */| { id: string; kind: "review"; path: string }/** A file against git (HEAD or the index), from the git panel. */- | { id: string; kind: "git"; path: string; ref: "HEAD" | "index" };+ | { id: string; kind: "git"; path: string; ref: "HEAD" | "index" }+ /** A Markdown file rendered (read-only, follows the file's text as you type). */+ | { id: string; kind: "preview"; path: string };++/** The second editor group (split editor): its own tabs, files and previews only. */+export type EditorGroup2 = { tabs: EditorTab[]; activeId: string | null };export type EditorSideView = "files" | "changes" | "git" | "search";/** The window layout: Chat (sessions sidebar + chat) or IDE (files, editor and terminal, chat docked right). */@@ -22,6 +27,8 @@ type WorkspaceEditorState = {tabs: EditorTab[];activeId: string | null;view: EditorSideView;+ /** The split editor's second group, when open (remembered per project). */+ group2?: EditorGroup2 | null;};type EditorStore = {@@ -66,6 +73,14 @@ type EditorStore = {setProblemsOpen: (open: boolean) => void;setBottomTab: (tab: "problems" | "terminal") => void;setLanguageFeatures: (on: boolean) => void;+ /** Which editor group has the keyboard (1 = the main one). */+ focusedGroup: 1 | 2;+ setFocusedGroup: (group: 1 | 2) => void;+ openTab2: (workspaceId: string, tab: EditorTab) => void;+ selectTab2: (workspaceId: string, id: string) => void;+ closeTab2: (workspaceId: string, id: string) => void;+ /** Closes the second group; its tabs move into the main one (folds the split away). */+ foldGroup2: (workspaceId: string) => void;};export const DEFAULT_IDE_CHAT_WIDTH = 420;@@ -74,6 +89,7 @@ const EMPTY: WorkspaceEditorState = { tabs: [], activeId: null, view: "files" };const MAX_TABS = 20;export function tabId(tab: { kind: EditorTab["kind"]; path: string; ref?: "HEAD" | "index" }): string {+ if (tab.kind === "preview") return `preview:${tab.path}`;return tab.kind === "git" ? `git:${tab.ref ?? "HEAD"}:${tab.path}` : `${tab.kind}:${tab.path}`;}@@ -155,6 +171,44 @@ export const useEditorStore = create<EditorStore>()(setProblemsOpen: (problemsOpen) => set(problemsOpen ? { problemsOpen, bottomTab: "problems" } : { problemsOpen }),setBottomTab: (bottomTab) => set({ bottomTab }),setLanguageFeatures: (languageFeatures) => set({ languageFeatures }),+ focusedGroup: 1,+ setFocusedGroup: (focusedGroup) => set((state) => (state.focusedGroup === focusedGroup ? state : { focusedGroup })),+ openTab2: (workspaceId, tab) =>+ set((state) => {+ const current = state.byWorkspace[workspaceId] ?? EMPTY;+ const group = current.group2 ?? { tabs: [], activeId: null };+ const tabs = group.tabs.some((item) => item.id === tab.id) ? group.tabs : [...group.tabs, tab].slice(-MAX_TABS);+ return { focusedGroup: 2, byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, group2: { tabs, activeId: tab.id } } } };+ }),+ selectTab2: (workspaceId, id) =>+ set((state) => {+ const current = state.byWorkspace[workspaceId] ?? EMPTY;+ const group = current.group2;+ if (!group || !group.tabs.some((item) => item.id === id)) return state;+ return { focusedGroup: 2, byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, group2: { ...group, activeId: id } } } };+ }),+ closeTab2: (workspaceId, id) =>+ set((state) => {+ const current = state.byWorkspace[workspaceId] ?? EMPTY;+ const group = current.group2;+ if (!group) return state;+ const index = group.tabs.findIndex((item) => item.id === id);+ if (index < 0) return state;+ const tabs = group.tabs.filter((item) => item.id !== id);+ // The last tab closed: the group goes.+ if (!tabs.length) return { focusedGroup: 1, byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, group2: null } } };+ const activeId = group.activeId === id ? (tabs[Math.min(index, tabs.length - 1)]?.id ?? null) : group.activeId;+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, group2: { tabs, activeId } } } };+ }),+ foldGroup2: (workspaceId) =>+ set((state) => {+ const current = state.byWorkspace[workspaceId] ?? EMPTY;+ const group = current.group2;+ if (!group) return state;+ const known = new Set(current.tabs.map((item) => item.id));+ const tabs = [...current.tabs, ...group.tabs.filter((item) => !known.has(item.id))].slice(-MAX_TABS);+ return { focusedGroup: 1, byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, tabs, activeId: current.activeId ?? group.activeId, group2: null } } };+ }),}),{name: "omnirush:editor:v1",diff --git a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx b/apps/app/src/react-app/domains/session/editor/editor-surface.tsxindex 53c3a667..61fa871c 100644--- a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx+++ b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx@@ -9,7 +9,7 @@ import { useEffect, useRef, useState } from "react";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";import { subscribeToTheme } from "@/app/theme";-import { applyMonacoTheme, monacoThemeName, type Monaco } from "./monaco";+import { addGroupKeys, applyMonacoTheme, monacoThemeName, type Monaco } from "./monaco";import type { FileDoc } from "./editor-models";import { hunkCounts, type LineHunk } from "./hunk-ops";import { monacoOptionsFor, useEditorSettings } from "./editor-settings";@@ -167,6 +167,8 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navirun: (target: MonacoApi.editor.ICodeEditor) => onAgentRef.current?.(item.action, target),}));disposables.push(...agentActions(code), ...agentActions(diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor));+ addGroupKeys(monaco, code);+ addGroupKeys(monaco, diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor);codeRef.current = code;diffRef.current = diff;onReadyRef.current?.({diff --git a/apps/app/src/react-app/domains/session/editor/group2-editor.tsx b/apps/app/src/react-app/domains/session/editor/group2-editor.tsxnew file mode 100644index 00000000..0840c843--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/group2-editor.tsx@@ -0,0 +1,84 @@+/** @jsxImportSource react */+/**+ * The split editor's second group: one Monaco code editor (the only other one besides the main group's), showing+ * the same file models as the main group, so a file open in both shares its text, undo and unsaved state.+ */+import { useEffect, useRef } from "react";+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";++import { monacoOptionsFor, useEditorSettings } from "./editor-settings";+import type { AgentAction } from "./editor-surface";+import { addGroupKeys, monacoThemeName, type Monaco } from "./monaco";++export function Group2Editor(props: {+ monaco: Monaco;+ model: MonacoApi.editor.ITextModel | null;+ onSave: () => void;+ onFocus: () => void;+ onAgentAction: (action: AgentAction, editor: MonacoApi.editor.ICodeEditor) => void;+ onReady: (editor: MonacoApi.editor.IStandaloneCodeEditor | null) => void;+}) {+ const hostRef = useRef<HTMLDivElement | null>(null);+ const editorRef = useRef<MonacoApi.editor.IStandaloneCodeEditor | null>(null);+ const latest = useRef(props);+ latest.current = props;++ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;+ const monaco = props.monaco;+ const editor = monaco.editor.create(host, {+ automaticLayout: true,+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",+ scrollBeyondLastLine: false,+ renderLineHighlight: "line",+ padding: { top: 6, bottom: 6 },+ maxTokenizationLineLength: 20_000,+ wordBasedSuggestions: "currentDocument",+ fixedOverflowWidgets: true,+ ...monacoOptionsFor(useEditorSettings.getState()),+ model: null,+ theme: monacoThemeName(),+ });+ editorRef.current = editor;+ const disposables = [+ editor.onDidFocusEditorWidget(() => latest.current.onFocus()),+ editor.onDidBlurEditorWidget(() => window.dispatchEvent(new Event("omnirush:editor-blur"))),+ ];+ editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => latest.current.onSave());+ addGroupKeys(monaco, editor);+ const actions: Array<{ id: string; label: string; action: AgentAction; keys: number[]; order: number }> = [+ { id: "omnirush.agent.ask", label: "Ask about selection", action: "ask", keys: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL], order: 1 },+ { id: "omnirush.agent.explain", label: "Explain with agent", action: "explain", keys: [], order: 2 },+ { id: "omnirush.agent.refactor", label: "Refactor with agent…", action: "refactor", keys: [], order: 3 },+ { id: "omnirush.agent.tests", label: "Write tests with agent", action: "tests", keys: [], order: 4 },+ ];+ for (const item of actions) {+ disposables.push(editor.addAction({+ id: item.id,+ label: item.label,+ keybindings: item.keys,+ contextMenuGroupId: "navigation",+ contextMenuOrder: item.order / 10,+ run: (target) => latest.current.onAgentAction(item.action, target),+ }));+ }+ const unsubscribe = useEditorSettings.subscribe((settings) => editor.updateOptions(monacoOptionsFor(settings)));+ latest.current.onReady(editor);+ return () => {+ latest.current.onReady(null);+ unsubscribe();+ for (const disposable of disposables) disposable.dispose();+ editor.setModel(null);+ editor.dispose();+ editorRef.current = null;+ };+ }, [props.monaco]);++ useEffect(() => {+ const editor = editorRef.current;+ if (editor && editor.getModel() !== props.model) editor.setModel(props.model);+ }, [props.model]);++ return <div ref={hostRef} className="monaco-component min-h-0 flex-1" data-editor-group2-surface />;+}diff --git a/apps/app/src/react-app/domains/session/editor/image-view.tsx b/apps/app/src/react-app/domains/session/editor/image-view.tsxnew file mode 100644index 00000000..7cbee030--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/image-view.tsx@@ -0,0 +1,98 @@+/** @jsxImportSource react */+/**+ * An image file in an editor tab: shown with <img> from a blob (an SVG is never inlined, framed or embedded, so it+ * runs no script and loads nothing), on a checkerboard from the theme, with Fit / 100% / zoom buttons. One decoded+ * image per tab, released when the tab is hidden or closed. Too-large files are refused before decoding.+ */+import { useEffect, useState } from "react";+import { Maximize2, Minus, Plus } from "lucide-react";++import type { OmniRushServerClient } from "@/app/lib/omnirush-server";+import { Button } from "@/components/ui/button";++export const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".bmp", ".ico", ".svg"]);+const MAX_PIXELS = 50_000_000;++export function isImagePath(path: string): boolean {+ const dot = path.lastIndexOf(".");+ return dot >= 0 && IMAGE_EXTENSIONS.has(path.slice(dot).toLowerCase());+}++function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+}++export function ImageView(props: { client: OmniRushServerClient; workspaceId: string; path: string }) {+ const [state, setState] = useState<{ url: string; bytes: number; type: string } | { error: string } | null>(null);+ const [size, setSize] = useState<{ width: number; height: number } | null>(null);+ const [zoom, setZoom] = useState<number | "fit">("fit");+ const name = props.path.split("/").pop() ?? props.path;++ useEffect(() => {+ let cancelled = false;+ let url: string | null = null;+ setState(null);+ setSize(null);+ setZoom("fit");+ props.client.editorRaw(props.workspaceId, props.path).then(+ (result) => {+ if (cancelled) return;+ const type = result.contentType ?? "application/octet-stream";+ url = URL.createObjectURL(new Blob([result.data], { type }));+ setState({ url, bytes: result.data.byteLength, type });+ },+ (error: { status?: number; message?: string }) => {+ if (!cancelled) setState({ error: error.status === 413 ? "Too large to preview (over 20 MB)." : error.message || "This image cannot be shown." });+ },+ );+ return () => {+ cancelled = true;+ if (url) URL.revokeObjectURL(url);+ };+ }, [props.client, props.path, props.workspaceId]);++ const scale = zoom === "fit" ? null : zoom;+ const step = (factor: number) => setZoom((value) => Math.min(8, Math.max(0.1, (value === "fit" ? 1 : value) * factor)));++ return (+ <div className="flex min-h-0 flex-1 flex-col" data-editor-image={props.path}>+ <div className="flex h-8 shrink-0 items-center gap-1 border-b border-border px-2 text-xs text-muted-foreground">+ <span className="min-w-0 truncate">+ {size ? `${size.width} × ${size.height}` : ""}{state && "bytes" in state ? ` · ${state.type.replace("image/", "").replace("+xml", "").toUpperCase()} · ${formatBytes(state.bytes)}` : ""}+ </span>+ <span className="flex-1" />+ <Button variant="ghost" size="icon-xs" aria-label="Zoom out" title="Zoom out" onClick={() => step(1 / 1.25)}><Minus /></Button>+ <span className="w-12 text-center tabular-nums" aria-live="polite">{scale === null ? "Fit" : `${Math.round(scale * 100)}%`}</span>+ <Button variant="ghost" size="icon-xs" aria-label="Zoom in" title="Zoom in" onClick={() => step(1.25)}><Plus /></Button>+ <Button variant="ghost" size="xs" onClick={() => setZoom(zoom === "fit" ? 1 : "fit")} aria-label={zoom === "fit" ? "Actual size" : "Fit to window"}>+ <Maximize2 /> {zoom === "fit" ? "100%" : "Fit"}+ </Button>+ </div>+ <div+ className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4"+ style={{+ backgroundColor: "var(--background)",+ backgroundImage: "linear-gradient(45deg, var(--muted) 25%, transparent 25%), linear-gradient(-45deg, var(--muted) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--muted) 75%), linear-gradient(-45deg, transparent 75%, var(--muted) 75%)",+ backgroundSize: "16px 16px",+ backgroundPosition: "0 0, 0 8px, 8px -8px, -8px 0",+ }}+ >+ {state === null ? <p className="text-sm text-muted-foreground">Loading…</p>+ : "error" in state ? <p className="rounded-md bg-background/90 px-3 py-2 text-sm text-muted-foreground">{state.error}</p>+ : size && size.width * size.height > MAX_PIXELS ? <p className="rounded-md bg-background/90 px-3 py-2 text-sm text-muted-foreground">Too large to preview ({size.width} × {size.height}).</p>+ : (+ <img+ src={state.url}+ alt={name}+ draggable={false}+ onLoad={(event) => setSize({ width: event.currentTarget.naturalWidth, height: event.currentTarget.naturalHeight })}+ className="block"+ style={scale === null ? { maxWidth: "100%", maxHeight: "100%", objectFit: "contain" } : { width: size ? size.width * scale : undefined, maxWidth: "none" }}+ />+ )}+ </div>+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/session/editor/markdown-preview.tsx b/apps/app/src/react-app/domains/session/editor/markdown-preview.tsxnew file mode 100644index 00000000..e51a1756--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/markdown-preview.tsx@@ -0,0 +1,147 @@+/** @jsxImportSource react */+/**+ * A Markdown file rendered in an editor tab, read-only, following the file's text as you type (300 ms; files over+ * 1 MB update when saved). The chat's renderer (sanitised: no raw HTML, no scripts). Links: a relative link opens+ * the file in the editor, `#anchor` scrolls, http(s) opens in the browser, anything else does nothing. Images: a+ * relative one loads from the project; a remote one is not loaded (a placeholder with its address).+ */+import { useEffect, useMemo, useRef, useState } from "react";+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";++import type { OmniRushServerClient } from "@/app/lib/omnirush-server";+import { renderMarkdownHtml } from "@/components/markdown/markdown";+import { isImagePath } from "./image-view";++const LARGE = 1_000_000;+const MAX_IMAGES = 30;++/** `target` relative to the folder of `from` (both project paths), or null when it leaves the project. */+export function resolveProjectPath(from: string, target: string): string | null {+ const clean = target.split(/[?#]/)[0]!;+ if (!clean) return null;+ let decoded: string;+ try {+ decoded = decodeURIComponent(clean);+ } catch {+ return null;+ }+ const parts = decoded.startsWith("/") ? [] : from.split("/").slice(0, -1);+ for (const part of decoded.split("/")) {+ if (!part || part === ".") continue;+ if (part === "..") {+ if (!parts.length) return null;+ parts.pop();+ } else parts.push(part);+ }+ return parts.length ? parts.join("/") : null;+}++export function MarkdownPreview(props: {+ client: OmniRushServerClient;+ workspaceId: string;+ path: string;+ model: MonacoApi.editor.ITextModel;+ isDirty: () => boolean;+ onOpenFile: (path: string) => void;+ onOpenExternal: (url: string) => void;+}) {+ const [text, setText] = useState(() => props.model.getValue());+ const rootRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ setText(props.model.getValue());+ let timer = 0;+ const subscription = props.model.onDidChangeContent(() => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ if (props.model.getValueLength() > LARGE && props.isDirty()) return;+ setText(props.model.getValue());+ }, 300);+ });+ return () => {+ window.clearTimeout(timer);+ subscription.dispose();+ };+ }, [props.model, props.isDirty]);++ const html = useMemo(() => ({ __html: renderMarkdownHtml(text, "surface") }), [text]);++ // Images: relative ones from the project (blob URLs, released with the render); remote ones not loaded.+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ const urls: string[] = [];+ let cancelled = false;+ let loaded = 0;+ for (const image of Array.from(root.querySelectorAll("img"))) {+ const src = image.getAttribute("src") ?? "";+ image.removeAttribute("srcset");+ if (/^[a-z][a-z0-9+.-]*:/i.test(src) && !src.startsWith("blob:")) {+ const note = document.createElement("span");+ note.className = "my-2 inline-block rounded-md border border-dashed border-border px-2 py-1 text-xs text-muted-foreground";+ note.textContent = `Remote image not loaded: ${src}`;+ note.dataset.editorRemoteImage = src;+ (image.closest("button") ?? image).replaceWith(note);+ continue;+ }+ const target = resolveProjectPath(props.path, src);+ image.removeAttribute("src");+ if (!target || !isImagePath(target) || loaded >= MAX_IMAGES) continue;+ loaded += 1;+ props.client.editorRaw(props.workspaceId, target).then(+ (result) => {+ if (cancelled) return;+ const url = URL.createObjectURL(new Blob([result.data], { type: result.contentType ?? "application/octet-stream" }));+ urls.push(url);+ image.src = url;+ },+ () => undefined,+ );+ }+ return () => {+ cancelled = true;+ for (const url of urls) URL.revokeObjectURL(url);+ };+ }, [html, props.client, props.path, props.workspaceId]);++ const onClick = (event: React.MouseEvent<HTMLDivElement>) => {+ const anchor = (event.target as HTMLElement).closest("a");+ if (!anchor) {+ // The chat renderer wraps images in an "expand" button: nothing to expand here.+ if ((event.target as HTMLElement).closest("button[data-omnirush-image-preview]")) event.preventDefault();+ return;+ }+ event.preventDefault();+ const href = anchor.getAttribute("href") ?? "";+ const inline = anchor.getAttribute("data-omnirush-inline-code-path");+ if (href.startsWith("#") && href.length > 1) {+ const id = decodeURIComponent(href.slice(1));+ const heading = rootRef.current?.querySelector(`[id="${CSS.escape(id)}"]`)+ ?? Array.from(rootRef.current?.querySelectorAll("h1,h2,h3,h4,h5,h6") ?? []).find((element) => slug(element.textContent ?? "") === id);+ heading?.scrollIntoView({ block: "start" });+ return;+ }+ if (/^https?:\/\//i.test(href)) {+ props.onOpenExternal(href);+ return;+ }+ const target = resolveProjectPath(props.path, inline ?? href);+ if (target && !/^[a-z][a-z0-9+.-]*:/i.test(inline ?? href)) props.onOpenFile(target);+ };++ return (+ <div className="min-h-0 flex-1 overflow-y-auto" data-editor-preview={props.path}>+ <div+ ref={rootRef}+ className="markdown-content mx-auto max-w-3xl select-text px-6 py-5 text-foreground"+ onClick={onClick}+ dangerouslySetInnerHTML={html}+ />+ </div>+ );+}++/** GitHub-style heading anchor. */+function slug(text: string): string {+ return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, "").replace(/\s+/g, "-");+}diff --git a/apps/app/src/react-app/domains/session/editor/monaco.ts b/apps/app/src/react-app/domains/session/editor/monaco.tsindex 3cd01f0d..eeb28e2a 100644--- a/apps/app/src/react-app/domains/session/editor/monaco.ts+++ b/apps/app/src/react-app/domains/session/editor/monaco.ts@@ -131,8 +131,19 @@ import "monaco-editor/languages/definitions/wgsl/register.js";import "monaco-editor/languages/definitions/xml/register.js";import "monaco-editor/languages/definitions/yaml/register.js";+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";export type Monaco = typeof monaco;+/**+ * Editor keys for the editor groups: Cmd/Ctrl+Shift+V opens the Markdown preview in the other group. (Cmd/Ctrl+K is+ * the app's command palette, so VS Code's Cmd/Ctrl+K chords are not used.)+ */+export function addGroupKeys(monaco: Monaco, editor: MonacoApi.editor.IStandaloneCodeEditor) {+ const { KeyMod, KeyCode } = monaco;+ editor.addCommand(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyV, () => window.dispatchEvent(new CustomEvent("omnirush:editor-command", { detail: "preview-side" })));+}++/** The app's theme: `data-theme` on <html> (app/theme.ts), or a `dark` class. */export function appIsDark(): boolean {const root = document.documentElement;diff --git a/apps/app/src/react-app/domains/session/editor/quick-open.tsx b/apps/app/src/react-app/domains/session/editor/quick-open.tsxindex 89d99890..27c9f235 100644--- a/apps/app/src/react-app/domains/session/editor/quick-open.tsx+++ b/apps/app/src/react-app/domains/session/editor/quick-open.tsx@@ -8,13 +8,14 @@ import { rankPaths } from "./quick-open-rank";type QuickOpenProps = {files: readonly string[];recent: readonly string[];- onOpen: (path: string) => void;+ /** `side`: Cmd/Ctrl+Enter, open in the other editor group. */+ onOpen: (path: string, side?: boolean) => void;onClose: () => void;};const LIMIT = 60;-/** Cmd/Ctrl+P: type part of a file name, arrows to move, Enter to open, Esc to close. */+/** Cmd/Ctrl+P: type part of a file name, arrows to move, Enter to open (Cmd/Ctrl+Enter: in the other group), Esc to close. */export function QuickOpen({ files, recent, onOpen, onClose }: QuickOpenProps) {const [query, setQuery] = useState("");const [index, setIndex] = useState(0);@@ -62,7 +63,7 @@ export function QuickOpen({ files, recent, onOpen, onClose }: QuickOpenProps) {} else if (event.key === "Enter") {event.preventDefault();const path = results[index];- if (path) onOpen(path);+ if (path) onOpen(path, event.metaKey || event.ctrlKey);}}}placeholder="Go to file…"diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex b348f873..7e553f57 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -2947,6 +2947,10 @@ export function SessionRoute() {["editor.quick-open", "Go to file", "Open a project file by name", "Cmd/Ctrl+P", "quick-open"],["editor.symbol", "Go to symbol in file", "Jump to a function, class or variable", "Cmd/Ctrl+Shift+O", "symbol"],["editor.outline", "Show outline", "The active file's symbols, under Files", "", "outline"],+ ["editor.split", "Split editor", "Open the current file in a second editor group", "Cmd/Ctrl+\\", "split"],+ ["editor.preview", "Open Markdown preview to the side", "The current Markdown file, rendered in the other group", "Cmd/Ctrl+Shift+V", "preview-side"],+ ["editor.preview-here", "Open Markdown preview", "The current Markdown file, rendered in this group", "", "preview-here"],+ ["editor.focus-other-group", "Focus the other editor group", "Move the keyboard to the other side of a split editor", "", "focus-other-group"],] as const).map(([id, title, detail, meta, command]) => ({id,title,diff --git a/apps/app/src/react-app/shell/use-shell-shortcuts.ts b/apps/app/src/react-app/shell/use-shell-shortcuts.tsindex 75e1670e..b02fdcdf 100644--- a/apps/app/src/react-app/shell/use-shell-shortcuts.ts+++ b/apps/app/src/react-app/shell/use-shell-shortcuts.ts@@ -188,6 +188,12 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {else setSessionSearchOpen((value) => !value);return;}+ // Cmd/Ctrl+\ (the Backslash key wherever the layout puts it): split the editor, IDE layout only.+ if (ideLayout && !event.shiftKey && !event.altKey && event.code === "Backslash") {+ event.preventDefault();+ editorCommand("split");+ return;+ }if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "p") {event.preventDefault();setCommandPaletteOpen(true);diff --git a/apps/app/tests/command-palette-settings.test.ts b/apps/app/tests/command-palette-settings.test.tsindex 90ec6cbb..9edb1fe9 100644--- a/apps/app/tests/command-palette-settings.test.ts+++ b/apps/app/tests/command-palette-settings.test.ts@@ -32,6 +32,7 @@ describe("command palette settings", () => {"settings:advanced","settings:ai","settings:appearance",+ "settings:editor","settings:voice","settings:environment","settings:updates",diff --git a/apps/app/tests/undo-editor-sync.test.ts b/apps/app/tests/undo-editor-sync.test.tsindex d67a41ed..b9b9ac0e 100644--- a/apps/app/tests/undo-editor-sync.test.ts+++ b/apps/app/tests/undo-editor-sync.test.ts@@ -134,7 +134,8 @@ describe("editor documents after an undo", () => {Uri: { from: (value: unknown) => value },editor: {createModel: (content: string) => {- const model = fakeModel(content);+ // Indentation settings are applied on open; the fake model takes them and does nothing.+ const model = Object.assign(fakeModel(content), { detectIndentation: () => undefined, updateOptions: () => undefined });models.push(model);return model;},diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.tsindex 26601bca..7fab036e 100644--- a/apps/server/src/routes/editor.ts+++ b/apps/server/src/routes/editor.ts@@ -11,7 +11,7 @@*/import { spawn } from "node:child_process";import { readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";-import { dirname, join, relative, resolve, sep } from "node:path";+import { dirname, extname, join, relative, resolve, sep } from "node:path";import { ApiError } from "../errors.js";import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../session-uploader.js";import type { ApprovalRequest, ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";@@ -149,6 +149,20 @@ export function editorPath(input: unknown): string {}/** The file's absolute path inside the workspace; a symlinked folder that leads out of it is refused. */+/** Image types the editor previews, by extension. */+const EDITOR_IMAGE_TYPES: Record<string, string> = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".avif": "image/avif",+ ".bmp": "image/bmp",+ ".ico": "image/x-icon",+ ".svg": "image/svg+xml",+};+const EDITOR_MAX_IMAGE_BYTES = 20 * 1024 * 1024;+async function resolveInside(root: string, relativePath: string): Promise<string> {const rootResolved = resolve(root);const candidate = resolve(rootResolved, relativePath);@@ -353,6 +367,26 @@ export function registerEditorRoutes(options: RegisterEditorRoutesOptions): voidreturn jsonResponse({ path, content: buffer.toString("utf8"), bytes: info.size, updatedAt: info.mtimeMs });});+ // An image file's bytes, for the editor's image preview: image types only, inside the project, capped.+ addRoute(routes, "GET", "/workspace/:id/editor/raw", "client", async (ctx) => {+ const workspace = await resolveWorkspace(config, ctx.params.id);+ const path = editorPath(ctx.url.searchParams.get("path"));+ const type = EDITOR_IMAGE_TYPES[extname(path).toLowerCase()];+ if (!type) throw new ApiError(415, "unsupported_type", "Only images can be previewed");+ const absolute = await resolveInside(workspace.path, path);+ const info = await stat(absolute).catch(() => null);+ if (!info?.isFile()) throw new ApiError(404, "file_not_found", "File not found");+ if (info.size > EDITOR_MAX_IMAGE_BYTES) {+ throw new ApiError(413, "file_too_large", "Too large to preview", { bytes: info.size, maxBytes: EDITOR_MAX_IMAGE_BYTES });+ }+ const buffer = await readFile(absolute);+ // SVG goes back as an image the page shows with <img> only (no scripts run there); nothing else may embed it.+ return new Response(buffer, {+ status: 200,+ headers: { "Content-Type": type, "Content-Length": String(buffer.length), "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'", "Cache-Control": "no-store" },+ });+ });+addRoute(routes, "PUT", "/workspace/:id/editor/file", "client", async (ctx) => {ensureWritable(config);requireClientScope(ctx, "collaborator");