The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(code): the plan and a real file tree move into the right panel
David147d40a7c118
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 4ffbb90d..d17db6ce 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -17,7 +17,6 @@ import { useCodexConfirmStore } from '../../stores/codexConfirmStore'import { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'import { GoalBar } from './GoalBar'-import { PlanBar } from './PlanBar'import { LoopBar } from './LoopBar'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'@@ -509,17 +508,16 @@ export function CodexView() {isGenerating={isRunning || codexGenerating}slashCommandscomposerModel={<ModelSelector openUpward surface="code" />}- composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /><PlanBar /></>}+ composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /></>}composerActions={<PluginsDropdown openUpward />}/></div>- {/* Right sidebar: File Tree */}- <div className="w-48 shrink-0">- <FileTree />- </div>+ {/* Right column: plan (C2) + explorer tree + file preview (C3). It+ owns its own width and collapsed state, both persisted in uiStore. */}+ <ExplorerPanel /></div>)}-import { FileTree } from './FileTree'+import { ExplorerPanel } from './ExplorerPanel'diff --git a/src/components/chat/ExplorerPanel.tsx b/src/components/chat/ExplorerPanel.tsxnew file mode 100644index 00000000..c9217f5e--- /dev/null+++ b/src/components/chat/ExplorerPanel.tsx@@ -0,0 +1,305 @@+/**+ * The right column of the Code tab (2.6.6 C2 + C3): the model's plan on top, a+ * real lazy file tree below it, and the preview of a clicked file underneath.+ *+ * What changed against the old FileTree:+ * - Folders EXPAND in place. They used to replace the workspace root, which+ * moved the agent's jail every time somebody browsed, and the way back was+ * a string split on "/" that breaks on a Windows backslash (plan R2). The+ * root is now set by the picker only, and every listing carries it as+ * `workingDirectory`.+ * - node_modules, .git, target and dist are filtered, and the backend's+ * 500-entry cap is shown instead of silently looking complete.+ * - The panel is resizable and collapsible, and remembers both (uiStore).+ *+ * Like before, the panel calls `fs_list` DIRECTLY and never the model's tool+ * executor, so a model-supplied workingDirectory can never pick its own jail+ * root (security review 2.5.7).+ */++import { Fragment, useEffect, useRef, useState } from 'react'+import {+ ChevronDown,+ ChevronRight,+ FileText,+ Folder,+ FolderOpen,+ Loader2,+ PanelRightClose,+ PanelRightOpen,+ RefreshCw,+} from 'lucide-react'+import { useCodexStore } from '../../stores/codexStore'+import { useUIStore } from '../../stores/uiStore'+import { backendCall, isTauri, isMacOS } from '../../api/backend'+import {+ EMPTY_LISTING,+ EXPLORER_IGNORED,+ FS_LIST_CAP,+ flattenTree,+ loadChildren,+ toggleExpanded,+ type ExplorerListing,+ type ExplorerNode,+ type FsList,+} from '../../lib/explorer-tree'+import { PlanBar } from './PlanBar'+import { FilePreview } from './FilePreview'++const fsList: FsList = (args) => backendCall('fs_list', args as unknown as Record<string, unknown>)++export function ExplorerPanel() {+ const root = useCodexStore((s) => s.workingDirectory)+ const setWorkingDirectory = useCodexStore((s) => s.setWorkingDirectory)+ const fileTreeVersion = useCodexStore((s) => s.fileTreeVersion)++ const width = useUIStore((s) => s.explorerWidth)+ const collapsed = useUIStore((s) => s.explorerCollapsed)+ const setExplorerWidth = useUIStore((s) => s.setExplorerWidth)+ const setExplorerCollapsed = useUIStore((s) => s.setExplorerCollapsed)++ const [listings, setListings] = useState<Record<string, ExplorerListing>>({})+ const [expanded, setExpanded] = useState<string[]>([])+ const [busy, setBusy] = useState<string[]>([])+ const [error, setError] = useState<string | null>(null)+ const [selected, setSelected] = useState<ExplorerNode | null>(null)++ const load = async (dir: string) => {+ setBusy((b) => (b.includes(dir) ? b : [...b, dir]))+ try {+ const listing = await loadChildren(dir, root, fsList)+ setListings((prev) => ({ ...prev, [dir]: listing }))+ if (dir === root) setError(null)+ } catch (e) {+ if (dir === root) setError(e instanceof Error ? e.message : 'Failed to read directory')+ setListings((prev) => ({ ...prev, [dir]: EMPTY_LISTING }))+ } finally {+ setBusy((b) => b.filter((p) => p !== dir))+ }+ }++ // A new root is a new tree: nothing expanded, nothing previewed.+ useEffect(() => {+ setListings({})+ setExpanded([])+ setSelected(null)+ setError(null)+ if (root) load(root)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [root])++ // Refresh after the agent wrote or ran something. codexStore bumps+ // fileTreeVersion on file_change / terminal_output. Reload the root and every+ // open folder, so an expanded subtree stays expanded across a write.+ const first = useRef(true)+ useEffect(() => {+ if (first.current) {+ first.current = false+ return+ }+ if (!root) return+ load(root)+ for (const dir of expanded) load(dir)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fileTreeVersion])++ const refresh = () => {+ if (!root) return+ load(root)+ for (const dir of expanded) load(dir)+ }++ const onToggleDir = (node: ExplorerNode) => {+ const next = toggleExpanded(expanded, node.path)+ setExpanded(next)+ if (next.includes(node.path) && !listings[node.path]) load(node.path)+ }++ // Native folder picker. Tauri uses the Rust dialog, dev mode a prompt.+ const pickFolder = async () => {+ let picked: string | null = null+ if (isTauri()) {+ try {+ const invoke = (await import('@tauri-apps/api/core')).invoke+ picked = await invoke<string | null>('pick_folder', { defaultPath: root || undefined })+ } catch {+ picked = window.prompt('Enter folder path:', root || (isMacOS() ? '/Users/' : 'C:\\Users'))+ }+ } else {+ picked = window.prompt('Enter folder path:', root || (isMacOS() ? '/Users/' : 'C:\\Users'))+ }+ if (picked) setWorkingDirectory(picked)+ }++ const startDrag = (e: React.PointerEvent) => {+ e.preventDefault()+ const startX = e.clientX+ const startWidth = width+ const onMove = (ev: PointerEvent) => {+ // The panel is on the right, so dragging left makes it wider.+ setExplorerWidth(startWidth + (startX - ev.clientX), window.innerWidth)+ }+ const onUp = () => {+ window.removeEventListener('pointermove', onMove)+ window.removeEventListener('pointerup', onUp)+ }+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', onUp)+ }++ if (collapsed) {+ return (+ <div className="w-7 shrink-0 flex flex-col items-center py-1 border-l border-gray-200 dark:border-white/[0.04] bg-gray-50 dark:bg-white/[0.01]">+ <button+ onClick={() => setExplorerCollapsed(false)}+ title="Show the explorer"+ data-testid="explorer-expand"+ className="p-1 rounded text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ >+ <PanelRightOpen size={12} />+ </button>+ </div>+ )+ }++ const rootListing = listings[root]+ const rows = flattenTree(root, listings, expanded)+ const loadingRoot = busy.includes(root)++ return (+ <aside+ style={{ width: `${width}px` }}+ className="relative shrink-0 h-full flex flex-col border-l border-gray-200 dark:border-white/[0.04] bg-gray-50 dark:bg-white/[0.01]"+ >+ {/* Drag handle on the panel edge. */}+ <div+ onPointerDown={startDrag}+ title="Drag to resize"+ data-testid="explorer-resize-handle"+ className="absolute left-0 top-0 h-full w-1 -ml-0.5 z-10 cursor-col-resize hover:bg-blue-500/40 active:bg-blue-500/60 transition-colors"+ />++ {/* C2: the plan lives here now, not above the prompt. */}+ <PlanBar variant="panel" />++ <div className="flex items-center gap-1 p-1.5 border-b border-gray-200 dark:border-white/[0.04]">+ <button+ onClick={pickFolder}+ title={root || 'Pick the folder the agent works in'}+ className="flex-1 min-w-0 flex items-center gap-1 px-1.5 py-1 rounded bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 transition-colors text-left"+ >+ <FolderOpen size={10} className="text-gray-500 shrink-0" />+ {root ? (+ <span className="text-[0.5rem] text-gray-700 dark:text-gray-300 font-mono truncate flex-1">{root}</span>+ ) : (+ <span className="text-[0.5rem] text-gray-400 dark:text-gray-600 flex-1">Select folder...</span>+ )}+ </button>+ <button+ onClick={refresh}+ disabled={!root}+ title="Refresh"+ className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 disabled:opacity-30 transition-colors shrink-0"+ >+ <RefreshCw size={10} className={loadingRoot ? 'animate-spin' : ''} />+ </button>+ <button+ onClick={() => setExplorerCollapsed(true)}+ title="Hide the explorer"+ data-testid="explorer-collapse"+ className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 transition-colors shrink-0"+ >+ <PanelRightClose size={12} />+ </button>+ </div>++ <div className={`overflow-y-auto scrollbar-thin p-1 ${selected ? 'max-h-[45%] shrink-0' : 'flex-1 min-h-0'}`}>+ {!root ? (+ <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Click above to set a folder</p>+ ) : error ? (+ <p className="text-[0.5rem] text-red-500/80 px-1 py-2 break-words">{error}</p>+ ) : !rootListing ? (+ <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Loading...</p>+ ) : rows.length === 0 ? (+ <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Empty directory</p>+ ) : (+ <>+ <ListingHints listing={rootListing} depth={0} />+ {rows.map((row) => {+ const isOpen = row.expanded+ const childListing = listings[row.node.path]+ const isBusy = busy.includes(row.node.path)+ const isSelected = selected?.path === row.node.path+ return (+ <Fragment key={row.node.path}>+ <button+ onClick={() =>+ row.node.isDirectory ? onToggleDir(row.node) : setSelected(row.node)+ }+ title={row.node.path}+ style={{ paddingLeft: `${row.depth * 8 + 4}px` }}+ className={`flex items-center gap-1 w-full pr-1 py-[2px] text-[0.5rem] rounded transition-colors text-left ${+ isSelected+ ? 'bg-blue-500/10 text-gray-800 dark:text-gray-100'+ : row.node.isDirectory+ ? 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5'+ : 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-white/5'+ }`}+ >+ {row.node.isDirectory ? (+ isBusy ? (+ <Loader2 size={8} className="text-gray-500 shrink-0 animate-spin" />+ ) : isOpen ? (+ <ChevronDown size={8} className="text-gray-500 shrink-0" />+ ) : (+ <ChevronRight size={8} className="text-gray-500 shrink-0" />+ )+ ) : (+ <span className="w-2 shrink-0" />+ )}+ {row.node.isDirectory ? (+ <Folder size={8} className="text-gray-500 shrink-0" />+ ) : (+ <FileText size={8} className="text-gray-400 dark:text-gray-600 shrink-0" />+ )}+ <span className="truncate">{row.node.name}</span>+ </button>+ {isOpen && childListing && (+ <ListingHints listing={childListing} depth={row.depth + 1} />+ )}+ </Fragment>+ )+ })}+ </>+ )}+ </div>++ {selected && (+ // Keyed on the path: another file is another component, so the+ // per-file script opt-in cannot survive the switch.+ <FilePreview key={selected.path} node={selected} root={root} onClose={() => setSelected(null)} />+ )}+ </aside>+ )+}++/** The two things a listing has to admit: the backend cut it off at 500, and+ * the ignore filter took entries out. Both silently looked like "this is the+ * whole folder" before. */+function ListingHints({ listing, depth }: { listing: ExplorerListing; depth: number }) {+ if (!listing.truncated && listing.hidden === 0) return null+ return (+ <div style={{ paddingLeft: `${depth * 8 + 4}px` }} className="py-[1px]">+ {listing.truncated && (+ <p className="text-[0.45rem] text-amber-500/80" data-testid="explorer-truncated">+ shortened, first {FS_LIST_CAP} entries only+ </p>+ )}+ {listing.hidden > 0 && (+ <p className="text-[0.45rem] text-gray-400 dark:text-gray-600" title={EXPLORER_IGNORED.join(', ')}>+ {listing.hidden} hidden ({EXPLORER_IGNORED.join(', ')})+ </p>+ )}+ </div>+ )+}diff --git a/src/components/chat/FilePreview.tsx b/src/components/chat/FilePreview.tsxnew file mode 100644index 00000000..41963251--- /dev/null+++ b/src/components/chat/FilePreview.tsx@@ -0,0 +1,223 @@+/**+ * Preview of ONE file inside the Explorer panel (2.6.6 C3).+ *+ * Text and code go through `fs_read` and the existing CodeBlock highlighter,+ * images through the jailed byte read as a blob URL, HTML through the shared+ * sandboxed frame.+ *+ * SECURITY:+ * - Every read carries `workingDirectory: root`, so the Rust jail+ * (resolve_path / contain_within) is the same one the agent runs under, and+ * a path outside the root is refused here before the backend is asked.+ * - HTML renders WITHOUT allow-scripts. Clicking a file means "show me this",+ * not "execute this repository's JavaScript". Scripts are a deliberate+ * per-file opt-in and reset when another file is opened.+ * - Images do not use a static Tauri asset scope. That scope knows nothing+ * about the jail, so a home-wide one would be a read surface right next to+ * the jail instead of inside it.+ * - There is no "open in browser": it would need a data URL, which the+ * backend's openExternal refuses on purpose.+ */++import { useEffect, useState } from 'react'+import { AlertTriangle, Loader2, X, ShieldAlert, ShieldCheck } from 'lucide-react'+import { backendCall } from '../../api/backend'+import { CodeBlock } from './CodeBlock'+import { HtmlPreviewFrame, ViewportSwitcher } from './HtmlPreviewFrame'+import { buildDocument, type Viewport } from '../../lib/html-preview'+import {+ capPreviewText,+ imageMimeFor,+ previewKindFor,+ previewLanguageFor,+} from '../../lib/file-preview'+import { isWithinRoot, type ExplorerNode } from '../../lib/explorer-tree'++interface Props {+ node: ExplorerNode+ root: string+ onClose: () => void+}++type PreviewState =+ | { status: 'loading' }+ | { status: 'error'; message: string }+ | { status: 'text'; text: string; truncated: boolean }+ | { status: 'html'; doc: string }+ | { status: 'image'; url: string }+ | { status: 'binary'; bytes: number }++function base64ToBlobUrl(base64: string, mime: string): string {+ const binary = atob(base64)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)+ return URL.createObjectURL(new Blob([bytes], { type: mime }))+}++export function FilePreview({ node, root, onClose }: Props) {+ const [state, setState] = useState<PreviewState>({ status: 'loading' })+ const [viewport, setViewport] = useState<Viewport>('desktop')+ // Off, per file. The panel mounts this component keyed on the path, so+ // opening another file starts a fresh component with scripts off again:+ // an opt-in can never leak from one file to the next.+ const [allowScripts, setAllowScripts] = useState(false)++ useEffect(() => {+ let cancelled = false+ let objectUrl: string | null = null++ const run = async () => {+ if (!isWithinRoot(root, node.path)) {+ setState({ status: 'error', message: 'This file sits outside the workspace root.' })+ return+ }+ const kind = previewKindFor(node.name)+ try {+ if (kind === 'binary') {+ setState({ status: 'binary', bytes: node.size ?? 0 })+ return+ }+ if (kind === 'image') {+ const data = await backendCall<{ base64?: string; bytes?: number }>('fs_read_bytes', {+ path: node.path,+ workingDirectory: root,+ })+ if (cancelled) return+ if (!data?.base64) {+ setState({ status: 'error', message: 'The image could not be read.' })+ return+ }+ objectUrl = base64ToBlobUrl(data.base64, imageMimeFor(node.name))+ setState({ status: 'image', url: objectUrl })+ return+ }+ const data = await backendCall<{ content?: string; encoding?: string; bytes?: number }>(+ 'fs_read',+ { path: node.path, workingDirectory: root },+ )+ if (cancelled) return+ if (data?.encoding === 'binary' || typeof data?.content !== 'string') {+ setState({ status: 'binary', bytes: data?.bytes ?? node.size ?? 0 })+ return+ }+ if (kind === 'html') {+ setState({ status: 'html', doc: buildDocument(data.content) })+ return+ }+ const capped = capPreviewText(data.content)+ setState({ status: 'text', text: capped.text, truncated: capped.truncated })+ } catch (e) {+ if (cancelled) return+ setState({ status: 'error', message: e instanceof Error ? e.message : 'Preview failed' })+ }+ }++ run()+ return () => {+ cancelled = true+ if (objectUrl) URL.revokeObjectURL(objectUrl)+ }+ }, [node.path, node.name, node.size, root])++ return (+ <div className="flex flex-col min-h-0 flex-1 border-t border-gray-200 dark:border-white/[0.06]">+ <div className="flex items-center gap-1 px-1.5 py-1 border-b border-gray-200 dark:border-white/[0.04] bg-gray-100/60 dark:bg-white/[0.02]">+ <span+ className="text-[0.55rem] font-mono text-gray-700 dark:text-gray-300 truncate flex-1"+ title={node.path}+ >+ {node.name}+ </span>+ {state.status === 'html' && (+ <>+ <ViewportSwitcher viewport={viewport} onChange={setViewport} compact />+ <button+ onClick={() => setAllowScripts((v) => !v)}+ title={+ allowScripts+ ? 'Scripts are running for this file. Click to turn them off.'+ : 'Scripts are off. This page is only rendered, not executed. Click to allow scripts for this file.'+ }+ className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[0.5rem] border transition-colors ${+ allowScripts+ ? 'border-amber-500/40 text-amber-500 bg-amber-500/[0.08]'+ : 'border-gray-200 dark:border-white/10 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'+ }`}+ data-testid="explorer-scripts-toggle"+ >+ {allowScripts ? <ShieldAlert size={9} /> : <ShieldCheck size={9} />}+ <span>{allowScripts ? 'Scripts on' : 'Enable scripts'}</span>+ </button>+ </>+ )}+ <button+ onClick={onClose}+ title="Close the preview"+ className="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-200 dark:hover:bg-white/5 transition-colors shrink-0"+ >+ <X size={10} />+ </button>+ </div>++ <div className="flex-1 min-h-0 overflow-auto scrollbar-thin">+ {state.status === 'loading' && (+ <div className="flex items-center gap-1 px-2 py-2 text-[0.55rem] text-gray-400 dark:text-gray-600">+ <Loader2 size={10} className="animate-spin" /> Reading...+ </div>+ )}++ {state.status === 'error' && (+ <div className="flex items-start gap-1 px-2 py-2 text-[0.55rem] text-red-500/90">+ <AlertTriangle size={10} className="mt-[1px] shrink-0" />+ <span className="break-words">{state.message}</span>+ </div>+ )}++ {state.status === 'binary' && (+ <p className="px-2 py-2 text-[0.55rem] text-gray-400 dark:text-gray-600">+ Binary file{state.bytes ? `, ${state.bytes.toLocaleString()} bytes` : ''}. Not previewed.+ </p>+ )}++ {state.status === 'text' && (+ <div className="p-1">+ <CodeBlock code={state.text} language={previewLanguageFor(node.name)} />+ {state.truncated && (+ <p className="px-1 pb-1 text-[0.5rem] text-amber-500/80">+ Shortened for the preview. Open the file to see the rest.+ </p>+ )}+ </div>+ )}++ {state.status === 'image' && (+ <div className="flex items-center justify-center p-2 h-full">+ <img+ src={state.url}+ alt={node.name}+ className="max-w-full max-h-full object-contain rounded border border-gray-200 dark:border-white/10"+ />+ </div>+ )}++ {state.status === 'html' && (+ <div className="flex items-center justify-center h-full p-1">+ <HtmlPreviewFrame+ doc={state.doc}+ viewport={viewport}+ allowScripts={allowScripts}+ title={`Preview of ${node.name}`}+ className="w-full h-full bg-white border border-gray-200 dark:border-white/10 rounded"+ />+ </div>+ )}+ </div>++ {state.status === 'html' && (+ <p className="px-1.5 py-0.5 text-[0.45rem] text-gray-400 dark:text-gray-600 border-t border-gray-200 dark:border-white/[0.04]">+ Rendered in a sandbox: sibling css and js files do not load.+ </p>+ )}+ </div>+ )+}diff --git a/src/components/chat/FileTree.tsx b/src/components/chat/FileTree.tsxdeleted file mode 100644index 2ca327b2..00000000--- a/src/components/chat/FileTree.tsx+++ /dev/null@@ -1,171 +0,0 @@-import { useState, useEffect, useRef } from 'react'-import { FolderOpen, Folder, FileText, ArrowLeft, RefreshCw } from 'lucide-react'-import { useCodexStore } from '../../stores/codexStore'-import { isTauri, isMacOS, backendCall } from '../../api/backend'-import type { FileTreeNode } from '../../types/codex'--export function FileTree() {- const workingDirectory = useCodexStore((s) => s.workingDirectory)- const fileTree = useCodexStore((s) => s.fileTree)- const fileTreeVersion = useCodexStore((s) => s.fileTreeVersion)- const setFileTree = useCodexStore((s) => s.setFileTree)- const setWorkingDirectory = useCodexStore((s) => s.setWorkingDirectory)- const [loading, setLoading] = useState(false)- const [error, setError] = useState<string | null>(null)-- const loadDirectory = async (dir: string) => {- if (!dir.trim()) return- setLoading(true)- setError(null)- try {- // The tree browser lists the picked folder as its OWN workspace root so- // the Rust containment jail accepts it. This is a UI browse — go STRAIGHT- // to the backend, NOT through the model's `file_list` tool executor, so a- // model-supplied `workingDirectory` can never pick its own jail root- // (security review 2.5.7: that passthrough let a prompt-injected model- // enumerate any directory on disk).- const data = await backendCall('fs_list', {- path: dir,- recursive: false,- pattern: null,- workingDirectory: dir,- })- const entries: any[] = Array.isArray(data?.entries) ? data.entries : []- const nodes: FileTreeNode[] = entries- .map((e) => ({ name: e.name as string, path: e.path as string, isDirectory: !!e.isDir }))- .filter((n) => n.name)-- setFileTree(nodes)- setWorkingDirectory(dir)- } catch (e) {- setFileTree([])- setError(e instanceof Error ? e.message : 'Failed to read directory')- } finally {- setLoading(false)- }- }-- // Go to parent directory- const goBack = () => {- if (!workingDirectory) return- const normalized = workingDirectory.replace(/\\/g, '/')- const parts = normalized.split('/').filter(Boolean)- if (parts.length <= 1) {- loadDirectory(parts[0] + '/')- } else {- const parent = parts.slice(0, -1).join('/')- loadDirectory(parent)- }- }-- // Native folder picker — Tauri uses Rust dialog, dev mode uses prompt fallback- const handlePickClick = async () => {- if (isTauri()) {- try {- const invoke = (await import('@tauri-apps/api/core')).invoke- const selected = await invoke<string | null>('pick_folder', {- defaultPath: workingDirectory || undefined,- })- if (selected) loadDirectory(selected)- } catch {- // Fallback if invoke fails- const dir = window.prompt('Enter folder path:', workingDirectory || (isMacOS() ? '/Users/' : 'C:\\Users'))- if (dir) loadDirectory(dir)- }- } else {- const dir = window.prompt('Enter folder path:', workingDirectory || (isMacOS() ? '/Users/' : 'C:\\Users'))- if (dir) loadDirectory(dir)- }- }-- useEffect(() => {- if (workingDirectory && fileTree.length === 0) {- loadDirectory(workingDirectory)- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [])-- // Auto-refresh when Codex writes / executes in the working directory.- // fileTreeVersion is bumped by codexStore.addEvent for file_change /- // terminal_output events. Skip the first mount (already handled above).- const isFirstRender = useRef(true)- useEffect(() => {- if (isFirstRender.current) {- isFirstRender.current = false- return- }- if (workingDirectory) loadDirectory(workingDirectory)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [fileTreeVersion])-- return (- <div className="h-full flex flex-col border-l border-gray-200 dark:border-white/[0.04] bg-gray-50 dark:bg-white/[0.01]">- {/* Directory picker — click to open native dialog */}- <div className="p-1.5 border-b border-gray-200 dark:border-white/[0.04]">- <button- onClick={handlePickClick}- className="w-full flex items-center gap-1 px-1.5 py-1 rounded bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 transition-colors text-left"- >- <FolderOpen size={10} className="text-gray-500 shrink-0" />- {workingDirectory ? (- <span className="text-[0.5rem] text-gray-700 dark:text-gray-300 font-mono truncate flex-1">{workingDirectory}</span>- ) : (- <span className="text-[0.5rem] text-gray-400 dark:text-gray-600 flex-1">Select folder...</span>- )}- </button>- </div>-- {/* File list */}- <div className="flex-1 overflow-y-auto scrollbar-thin p-1">- {loading ? (- <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Loading...</p>- ) : error ? (- <p className="text-[0.5rem] text-red-500/80 px-1 py-2">{error}</p>- ) : fileTree.length === 0 ? (- <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">- {workingDirectory ? 'Empty directory' : 'Click above to set a folder'}- </p>- ) : (- fileTree.map((node, i) => (- <button- key={i}- onClick={() => node.isDirectory && loadDirectory(node.path)}- className={`flex items-center gap-1 w-full px-1 py-[2px] text-[0.5rem] rounded transition-colors text-left ${- node.isDirectory- ? 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 cursor-pointer'- : 'text-gray-400 dark:text-gray-600'- }`}- >- {node.isDirectory ? (- <Folder size={8} className="text-gray-500 shrink-0" />- ) : (- <FileText size={8} className="text-gray-400 dark:text-gray-600 shrink-0" />- )}- <span className="truncate">{node.name}</span>- </button>- ))- )}- </div>-- {/* Bottom nav */}- <div className="flex items-center justify-center gap-1 px-1.5 py-1 border-t border-gray-200 dark:border-white/[0.04]">- <button- onClick={goBack}- disabled={!workingDirectory}- className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 disabled:opacity-30 transition-colors"- title="Parent directory"- >- <ArrowLeft size={10} />- </button>- <button- onClick={() => workingDirectory && loadDirectory(workingDirectory)}- disabled={!workingDirectory}- className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 disabled:opacity-30 transition-colors"- title="Refresh"- >- <RefreshCw size={10} />- </button>- </div>- </div>- )-}diff --git a/src/components/chat/PlanBar.tsx b/src/components/chat/PlanBar.tsxindex 4b8ae8bd..c82eb2b2 100644--- a/src/components/chat/PlanBar.tsx+++ b/src/components/chat/PlanBar.tsx@@ -1,14 +1,18 @@-// The model's own plan for the current task, above the composer in Code and in-// Agent (audit C4).+// The model's own plan for the current task.//// On a long run the transcript scrolls away and the user is left guessing which// step the agent is on and whether it still remembers the goal. The agent writes// this list through `todo_write` and keeps it current, so progress is one glance// instead of a scroll back through twenty tool calls.//-// Collapsed to the current step by default: this sits directly above the-// composer and a ten-item list would push the input off screen. Expanded state-// is per session, not persisted, because a plan is short-lived.+// Two homes since 2.6.6 C2:+// - 'composer' (Agent tab): above the input, inside the composer's 70% width+// wrapper. Collapsed to the current step by default, because a ten-item+// list would push the input off screen.+// - 'panel' (Code tab): the top section of the Explorer column, full column+// width and expanded by default. It has vertical room there, and the plan+// stops stealing the prompt window it used to sit in.+// Expanded state is per session, not persisted, because a plan is short-lived.import { useState } from 'react'import { CheckCircle2, Circle, ChevronDown, ChevronRight, Loader2, ListTodo, X } from 'lucide-react'@@ -23,7 +27,14 @@ export function planDoneLabel(pendingChanges: number): string {return `every step done, ${pendingChanges} change${pendingChanges === 1 ? '' : 's'} still waiting for your approval`}-export function PlanBar() {+export type PlanBarVariant = 'composer' | 'panel'++interface Props {+ variant?: PlanBarVariant+}++export function PlanBar({ variant = 'composer' }: Props) {+ const panel = variant === 'panel'const activeConversationId = useChatStore((s) => s.activeConversationId)const todos = useTodoStore((s) =>activeConversationId ? s.byConversation[activeConversationId] : undefined,@@ -35,7 +46,7 @@ export function PlanBar() {activeConversationId ? (s.byChat[activeConversationId]?.length ?? 0) : 0,)const clearTodos = useTodoStore((s) => s.clearTodos)- const [expanded, setExpanded] = useState(false)+ const [expanded, setExpanded] = useState(panel)if (!activeConversationId || !todos || todos.length === 0) return null@@ -48,7 +59,10 @@ export function PlanBar() {const headline = current ?? todos.find((t) => t.status === 'pending') ?? todos[todos.length - 1]return (- <div className="w-full max-w-[70%] mx-auto px-3 pb-1 flex justify-center">+ <div+ className={panel ? 'w-full p-1.5' : 'w-full max-w-[70%] mx-auto px-3 pb-1 flex justify-center'}+ data-testid={panel ? 'plan-panel' : 'plan-composer'}+ ><div className="w-full rounded-md border border-blue-500/20 bg-blue-500/[0.04]"><div className="flex items-center gap-1.5 px-2 py-1"><button@@ -84,8 +98,9 @@ export function PlanBar() {</div>{expanded && (- // Capped so a fifteen-step plan cannot push the composer off screen.- <ul className="px-2 pb-1.5 space-y-0.5 max-h-40 overflow-y-auto">+ // Capped so a fifteen-step plan cannot push the composer off screen,+ // and in the panel so it cannot push the file tree out of view.+ <ul className={`px-2 pb-1.5 space-y-0.5 overflow-y-auto ${panel ? 'max-h-48 scrollbar-thin' : 'max-h-40'}`}>{todos.map((t, i) => (<li key={`${i}-${t.content}`} className="flex items-start gap-1.5">{t.status === 'completed' ? (@@ -111,14 +126,18 @@ export function PlanBar() {</ul>)}- {!expanded && allDone && (+ {(panel || !expanded) && allDone && (+ // In the composer this is the collapsed summary line. In the panel the+ // list is open by default, so the line has to stay: "every step done"+ // while six writes sit refused in the queue is exactly the sentence+ // Morgan believed.<div className="px-2 pb-1 flex items-center gap-1.5" data-testid="plan-all-done"><CheckCircle2size={9}className={`${pending > 0 ? 'text-amber-400' : 'text-emerald-400'} shrink-0`}/><span- className={`text-[0.55rem] ${pending > 0 ? 'text-amber-400/90' : 'text-emerald-400/80'}`}+ className={`text-[0.55rem] leading-snug ${pending > 0 ? 'text-amber-400/90' : 'text-emerald-400/80'}`}>{planDoneLabel(pending)}</span>diff --git a/src/components/chat/__tests__/plan-done-vs-applied.test.ts b/src/components/chat/__tests__/plan-done-vs-applied.test.tsindex 610e79a3..38740eb7 100644--- a/src/components/chat/__tests__/plan-done-vs-applied.test.ts+++ b/src/components/chat/__tests__/plan-done-vs-applied.test.ts@@ -4,6 +4,11 @@* are written" when nothing was. Morgan (2026-08-11) saw exactly that: plan* 6 of 6, every step done, and six file changes that had all been refused.*+ * Since 2.6.6 C2 the coding tab shows this in the right-hand panel instead of+ * above the prompt, so the same claims are now tested on the panel variant:+ * the staged-changes coupling and the clear button moved with it, and the+ * composer above the input no longer carries a plan at all.+ ** Run: npx vitest run src/components/chat/__tests__/plan-done-vs-applied.test.ts*/import { describe, it, expect } from 'vitest'@@ -12,6 +17,9 @@ import { fileURLToPath } from 'node:url'import { dirname, resolve } from 'node:path'import { planDoneLabel } from '../PlanBar'+const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+describe('planDoneLabel', () => {it('says done, plainly, when nothing is waiting', () => {expect(planDoneLabel(0)).toBe('every step done')@@ -25,9 +33,55 @@ describe('planDoneLabel', () => {describe('the bar reads the staging queue', () => {it('PlanBar subscribes to stagedChangesStore', () => {- const here = dirname(fileURLToPath(import.meta.url))- const src = readFileSync(resolve(here, '../PlanBar.tsx'), 'utf8')+ const src = read('../PlanBar.tsx')expect(src).toMatch(/useStagedChangesStore/)expect(src).toMatch(/planDoneLabel\(pending\)/)})++ it('the warning survives the panel, where the list is open by default', () => {+ const src = read('../PlanBar.tsx')+ // Collapsed-only would have hidden the Morgan line in the panel, because+ // the panel starts expanded.+ expect(src).toMatch(/\(panel \|\| !expanded\) && allDone/)+ expect(src).toMatch(/useState\(panel\)/)+ })+})++describe('the plan moved into the panel (C2)', () => {+ it('PlanBar has a panel variant without the composer width wrapper', () => {+ const src = read('../PlanBar.tsx')+ expect(src).toMatch(/variant = 'composer'/)+ expect(src).toMatch(/panel = variant === 'panel'/)+ // The 70% wrapper belongs to the composer only; in a 280px column it would+ // squeeze the plan into a third of the panel.+ expect(src).toMatch(/panel \? 'w-full p-1\.5' : 'w-full max-w-\[70%\]/)+ })++ it('the clear button and the staged count came along, unchanged', () => {+ const src = read('../PlanBar.tsx')+ expect(src).toMatch(/clearTodos\(activeConversationId\)/)+ expect(src).toMatch(/s\.byChat\[activeConversationId\]\?\.length \?\? 0/)+ })++ it('the coding composer no longer carries a plan', () => {+ const src = read('../CodexView.tsx')+ expect(src).toMatch(/composerAbove=\{<><LoopBar onStop=\{stopCodex\} \/><GoalBar \/><\/>\}/)+ expect(src).not.toMatch(/PlanBar/)+ })++ it('the panel renders it, above the tree', () => {+ const src = read('../ExplorerPanel.tsx')+ expect(src).toMatch(/<PlanBar variant="panel" \/>/)+ const plan = src.indexOf('<PlanBar variant="panel" />')+ const tree = src.indexOf('{rows.map((row) => {')+ expect(plan).toBeGreaterThan(-1)+ expect(tree).toBeGreaterThan(plan)+ })++ it('counter-test: the chat tab keeps the plan above its composer', () => {+ // Only the Code tab moved. ChatView is not ours to change and must still+ // render the composer variant.+ const src = read('../ChatView.tsx')+ expect(src).toMatch(/<PlanBar \/>/)+ })})diff --git a/src/lib/__tests__/explorer-preview.test.ts b/src/lib/__tests__/explorer-preview.test.tsnew file mode 100644index 00000000..21473c7c--- /dev/null+++ b/src/lib/__tests__/explorer-preview.test.ts@@ -0,0 +1,183 @@+/**+ * The Explorer preview (2.6.6 C3): which preview a file gets, and the sandbox+ * the HTML one runs in.+ *+ * SECURITY claim under test: clicking a file in the repository tree renders it,+ * it does not EXECUTE it. The explorer frame starts with an empty sandbox+ * attribute (every restriction on) and only gains allow-scripts after a+ * per-file opt-in; allow-same-origin appears nowhere. The model-snippet modal+ * keeps its old behaviour, and the test below pins both sides so a later+ * refactor cannot quietly swap them.+ *+ * Run: npx vitest run src/lib/__tests__/explorer-preview.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'+import {+ PREVIEW_TEXT_CAP,+ capPreviewText,+ extensionOf,+ imageMimeFor,+ previewKindFor,+ previewLanguageFor,+ sandboxAttr,+} from '../file-preview'+import { buildDocument } from '../html-preview'+import { isWithinRoot } from '../explorer-tree'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+/** Source with comments removed: a rule explained in prose must not be able to+ * satisfy a test that asks whether the rule is implemented. */+const code = (rel: string) =>+ read(rel).replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')++describe('the preview switch reads the file type', () => {+ it('sends images to the image branch', () => {+ for (const n of ['logo.png', 'a.JPG', 'b.jpeg', 'c.gif', 'd.webp', 'e.svg', 'f.avif', 'g.ico']) {+ expect(previewKindFor(n)).toBe('image')+ }+ })++ it('sends html to the sandboxed frame', () => {+ for (const n of ['index.html', 'page.HTM', 'old.xhtml']) {+ expect(previewKindFor(n)).toBe('html')+ }+ })++ it('sends code and prose to the highlighter', () => {+ for (const n of ['main.ts', 'App.tsx', 'lib.rs', 'README.md', 'Makefile', 'notes', '.gitignore']) {+ expect(previewKindFor(n)).toBe('text')+ }+ })++ it('refuses to render a binary as text', () => {+ for (const n of ['model.gguf', 'app.exe', 'lib.dylib', 'clip.mp4', 'archive.zip', 'doc.pdf']) {+ expect(previewKindFor(n)).toBe('binary')+ }+ })++ it('counter-test: html-ish names that are not html stay text', () => {+ expect(previewKindFor('template.html.tera')).toBe('text')+ expect(previewKindFor('index.html.bak')).toBe('text')+ expect(previewKindFor('render.tsx')).toBe('text')+ })++ it('reads the extension off the NAME, on both platforms', () => {+ expect(extensionOf('a.PNG')).toBe('png')+ expect(extensionOf('archive.tar.gz')).toBe('gz')+ expect(extensionOf('Makefile')).toBe('')+ expect(extensionOf('.gitignore')).toBe('gitignore')+ })++ it('picks the blob content type from the same extension', () => {+ expect(imageMimeFor('a.png')).toBe('image/png')+ expect(imageMimeFor('a.JPG')).toBe('image/jpeg')+ expect(imageMimeFor('a.svg')).toBe('image/svg+xml')+ expect(imageMimeFor('a.unknown')).toBe('application/octet-stream')+ })++ it('names a language for the highlighter, or falls back to text', () => {+ expect(previewLanguageFor('main.rs')).toBe('rust')+ expect(previewLanguageFor('App.tsx')).toBe('tsx')+ expect(previewLanguageFor('Dockerfile')).toBe('docker')+ expect(previewLanguageFor('weird.qqq')).toBe('text')+ })++ it('caps a minified bundle instead of feeding it to the highlighter', () => {+ const small = capPreviewText('hello')+ expect(small).toEqual({ text: 'hello', truncated: false })+ const huge = capPreviewText('x'.repeat(PREVIEW_TEXT_CAP + 10))+ expect(huge.truncated).toBe(true)+ expect(huge.text).toHaveLength(PREVIEW_TEXT_CAP)+ })+})++describe('scripts are off in the Explorer preview', () => {+ it('the default sandbox is the fully restricted one', () => {+ expect(sandboxAttr(false)).toBe('')+ })++ it('the opt-in adds scripts and nothing else', () => {+ expect(sandboxAttr(true)).toBe('allow-scripts')+ })++ it('allow-same-origin is never granted, on either setting', () => {+ expect(sandboxAttr(false)).not.toContain('allow-same-origin')+ expect(sandboxAttr(true)).not.toContain('allow-same-origin')+ expect(code('../../components/chat/HtmlPreviewFrame.tsx')).not.toMatch(/allow-same-origin/)+ })++ it('the panel preview starts with scripts off and resets per file', () => {+ const src = code('../../components/chat/FilePreview.tsx')+ // The opt-in state starts false ...+ expect(src).toMatch(/const \[allowScripts, setAllowScripts\] = useState\(false\)/)+ expect(src).toMatch(/allowScripts=\{allowScripts\}/)+ // ... and the panel mounts a FRESH preview per path, so an opt-in on one+ // file cannot carry over to the next one.+ expect(code('../../components/chat/ExplorerPanel.tsx')).toMatch(+ /<FilePreview key=\{selected\.path\}/,+ )+ // The frame never hard-codes the permissive sandbox: no bare `allowScripts`+ // prop (which is JSX for true) and no literal sandbox attribute.+ const frame = /<HtmlPreviewFrame[\s\S]*?\/>/.exec(src)?.[0] ?? ''+ expect(frame).toMatch(/allowScripts=\{allowScripts\}/)+ expect(frame).not.toMatch(/allowScripts\s*(\/>|[a-zA-Z]+=)/)+ expect(src).not.toMatch(/sandbox="allow-scripts"/)+ })++ it('counter-test: the model-snippet modal keeps running scripts', () => {+ const src = code('../../components/chat/HtmlPreviewModal.tsx')+ expect(src).toMatch(/<HtmlPreviewFrame[^>]*allowScripts/)+ })++ it('the panel has no dead open-in-browser button', () => {+ // openExternal refuses a data: URL, so the button was a no-op in the panel.+ const src = code('../../components/chat/FilePreview.tsx')+ expect(src).not.toMatch(/openExternal/)+ expect(src).not.toMatch(/data:text\/html/)+ })+})++describe('a preview outside the workspace root is refused', () => {+ it('the guard says no before anything is read', () => {+ expect(isWithinRoot('/repo', '/etc/passwd')).toBe(false)+ expect(isWithinRoot('/repo', '/repo/../etc/passwd')).toBe(false)+ expect(isWithinRoot('/repo', '/repo/src/main.ts')).toBe(true)+ })++ it('FilePreview asks the guard first and reads only inside the root', () => {+ const src = code('../../components/chat/FilePreview.tsx')+ const guard = src.indexOf('isWithinRoot(root, node.path)')+ const firstCall = src.indexOf('backendCall')+ expect(guard).toBeGreaterThan(-1)+ // The import of backendCall sits above, so compare against the first CALL.+ const firstInvocation = src.indexOf("backendCall<", guard)+ expect(firstCall).toBeGreaterThan(-1)+ expect(firstInvocation).toBeGreaterThan(guard)+ // Every read carries the picked root, so the Rust jail is the same one the+ // agent runs under.+ expect(src.match(/workingDirectory: root/g) ?? []).toHaveLength(2)+ })+})++describe('the shared document shell', () => {+ it('passes a full document through untouched', () => {+ const doc = '<!doctype html><html><body>hi</body></html>'+ expect(buildDocument(doc)).toBe(doc)+ })++ it('wraps a bare snippet so it has a charset', () => {+ const out = buildDocument('<p>hi</p>')+ expect(out).toMatch(/^<!doctype html>/)+ expect(out).toContain('<p>hi</p>')+ expect(out).toContain('charset="utf-8"')+ })++ it('centres a bare svg', () => {+ const out = buildDocument('<svg xmlns="http://www.w3.org/2000/svg"><circle r="4"/></svg>')+ expect(out).toContain('SVG Preview')+ })+})