Skip to content

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.

feat(code): tree logic, a jailed byte read and a shared preview frame

David41081cf41d85
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index ee584c2d..b924f8f1 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -192,6 +192,50 @@ pub fn fs_read(path: String, chatId: Option<String>, workingDirectory: Option<St
}
}
+/// The cap for a single `fs_read_bytes` call. A preview is a picture on a
+/// 280px panel, not a payload: base64 over IPC costs 4/3 of the file in Rust
+/// plus a copy in the WebView, so the ceiling stays low on purpose.
+const READ_BYTES_CAP: u64 = 16 * 1024 * 1024;
+
+/// Raw bytes of ONE file, base64, through the SAME jail as every other fs
+/// command (`resolve_path` -> `contain_within`).
+///
+/// This exists for the Explorer panel's image preview (2.6.6 C3). The obvious
+/// alternative, a static Tauri asset scope plus convertFileSrc, knows nothing
+/// about the jail: a scope wide enough to cover whatever folder the user picks
+/// is a read surface NEXT TO the workspace jail rather than inside it. Bytes
+/// through this command become a blob URL in the WebView instead.
+///
+/// `fs_read` deliberately refuses to carry binary payloads (it answers with a
+/// marker), and it stays that way: this is a separate, capped, opt-in door
+/// that only the panel walks through.
+#[tauri::command]
+#[allow(non_snake_case)]
+pub fn fs_read_bytes(
+ path: String,
+ chatId: Option<String>,
+ workingDirectory: Option<String>,
+ maxBytes: Option<u64>,
+) -> Result<serde_json::Value, String> {
+ let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref())?;
+ if !full.is_file() {
+ return Err(format!("File not found: {}", full.display()));
+ }
+ let cap = maxBytes.unwrap_or(READ_BYTES_CAP).min(READ_BYTES_CAP);
+ let size = fs::metadata(&full).map(|m| m.len()).unwrap_or(0);
+ if size > cap {
+ return Err(format!(
+ "File is too large to preview: {} bytes (limit {})",
+ size, cap
+ ));
+ }
+ let bytes = fs::read(&full).map_err(|e| format!("Read error: {}", e))?;
+ Ok(serde_json::json!({
+ "base64": base64::engine::general_purpose::STANDARD.encode(&bytes),
+ "bytes": bytes.len(),
+ }))
+}
+
/// Match new content to the EXISTING file's line-ending + BOM convention so an
/// edit produces a minimal diff instead of flipping every line. Local coding
/// models emit `\n`; on a Windows repo whose files are CRLF, writing that raw
@@ -884,3 +928,111 @@ mod binary_read_tests {
let _ = fs::remove_dir_all(&dir);
}
}
+
+/// The Explorer panel's image preview reads bytes, and it must read them
+/// through the same jail as everything else (2.6.6 C3 security review).
+#[cfg(test)]
+mod explorer_byte_read_tests {
+ use super::*;
+ use std::fs;
+
+ fn ws(tag: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("lu-fsbytes-{}-{}", tag, std::process::id()));
+ let _ = fs::remove_dir_all(&d);
+ fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn bytes_inside_the_workspace_come_back_base64() {
+ let dir = ws("inside");
+ // A one-pixel PNG header is enough: the point is byte fidelity.
+ let raw: Vec<u8> = vec![0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00];
+ fs::write(dir.join("pixel.png"), &raw).unwrap();
+
+ let v = fs_read_bytes(
+ "pixel.png".into(),
+ None,
+ Some(dir.to_string_lossy().to_string()),
+ None,
+ )
+ .expect("read");
+
+ assert_eq!(v["bytes"], raw.len());
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(v["base64"].as_str().unwrap())
+ .unwrap();
+ assert_eq!(decoded, raw);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ /// The jail, from both directions: a `..` climb and an absolute path that
+ /// points somewhere else entirely.
+ #[test]
+ fn bytes_outside_the_workspace_are_refused() {
+ let dir = ws("outside");
+ let secret = dir.parent().unwrap().join("lu-fsbytes-secret.txt");
+ fs::write(&secret, b"private").unwrap();
+ let root = dir.join("repo");
+ fs::create_dir_all(&root).unwrap();
+
+ let climb = fs_read_bytes(
+ "../lu-fsbytes-secret.txt".into(),
+ None,
+ Some(root.to_string_lossy().to_string()),
+ None,
+ );
+ assert!(climb.is_err(), "a .. climb must not read bytes");
+
+ let absolute = fs_read_bytes(
+ secret.to_string_lossy().to_string(),
+ None,
+ Some(root.to_string_lossy().to_string()),
+ None,
+ );
+ assert!(absolute.is_err(), "an outside absolute path must not read bytes");
+
+ let _ = fs::remove_file(&secret);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_file_over_the_cap_is_refused_instead_of_shipped() {
+ let dir = ws("cap");
+ fs::write(dir.join("wide.bin"), vec![0u8; 4096]).unwrap();
+
+ let err = fs_read_bytes(
+ "wide.bin".into(),
+ None,
+ Some(dir.to_string_lossy().to_string()),
+ Some(1024),
+ )
+ .expect_err("over the cap");
+ assert!(err.contains("too large"), "got: {err}");
+
+ // The caller cannot raise the ceiling past the built-in one either.
+ let v = fs_read_bytes(
+ "wide.bin".into(),
+ None,
+ Some(dir.to_string_lossy().to_string()),
+ Some(u64::MAX),
+ )
+ .expect("under the built-in cap");
+ assert_eq!(v["bytes"], 4096);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_missing_file_is_an_error_not_an_empty_blob() {
+ let dir = ws("missing");
+ let err = fs_read_bytes(
+ "nope.png".into(),
+ None,
+ Some(dir.to_string_lossy().to_string()),
+ None,
+ )
+ .expect_err("missing");
+ assert!(err.contains("File not found"), "got: {err}");
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 3a845649..91b5c4ed 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -173,6 +173,7 @@ fn main() {
commands::shell::shell_execute,
// Filesystem
commands::filesystem::fs_read,
+ commands::filesystem::fs_read_bytes,
commands::filesystem::fs_write,
commands::filesystem::fs_list,
commands::filesystem::fs_search,
diff --git a/src/components/chat/HtmlPreviewFrame.tsx b/src/components/chat/HtmlPreviewFrame.tsx
new file mode 100644
index 00000000..f98e12a7
--- /dev/null
+++ b/src/components/chat/HtmlPreviewFrame.tsx
@@ -0,0 +1,97 @@
+/**
+ * The sandboxed iframe plus its viewport switcher, shared by the model-snippet
+ * modal (HtmlPreviewModal) and the Explorer panel's file preview (2.6.6 C3).
+ *
+ * `allowScripts` is the whole reason this is a prop and not a constant. A
+ * snippet the model just wrote is code the user asked for; a file the user
+ * clicked in their repository is code they asked to LOOK at. The panel passes
+ * false and offers a per-file opt-in, the modal keeps its old behaviour.
+ * `allow-same-origin` is never set on either path.
+ */
+
+import { Smartphone, Tablet, Monitor } from 'lucide-react'
+import { VIEWPORTS, type Viewport } from '../../lib/html-preview'
+import { sandboxAttr } from '../../lib/file-preview'
+
+interface FrameProps {
+ doc: string
+ viewport: Viewport
+ allowScripts: boolean
+ /** Bumping this remounts the iframe, which is how "reload" works. */
+ reloadKey?: number
+ title?: string
+ className?: string
+}
+
+export function HtmlPreviewFrame({
+ doc,
+ viewport,
+ allowScripts,
+ reloadKey = 0,
+ title = 'HTML Preview',
+ className,
+}: FrameProps) {
+ const dims = VIEWPORTS[viewport]
+ return (
+ <iframe
+ key={reloadKey}
+ srcDoc={doc}
+ sandbox={sandboxAttr(allowScripts)}
+ referrerPolicy="no-referrer"
+ title={title}
+ className={
+ className ??
+ 'bg-white border border-gray-200 dark:border-white/10 shadow-lg rounded transition-all'
+ }
+ style={{
+ width: viewport === 'desktop' ? '100%' : `${dims.width}px`,
+ height: viewport === 'desktop' ? '100%' : `${dims.height}px`,
+ maxWidth: '100%',
+ maxHeight: '100%',
+ }}
+ />
+ )
+}
+
+interface SwitcherProps {
+ viewport: Viewport
+ onChange: (v: Viewport) => void
+ /** The panel sits in a 280px column, so its buttons are smaller. */
+ compact?: boolean
+}
+
+export function ViewportSwitcher({ viewport, onChange, compact }: SwitcherProps) {
+ return (
+ <div className="flex items-center gap-0.5 bg-gray-100 dark:bg-white/[0.04] rounded-md p-0.5">
+ <ViewportBtn icon={Smartphone} active={viewport === 'mobile'} onClick={() => onChange('mobile')} label="Mobile" compact={compact} />
+ <ViewportBtn icon={Tablet} active={viewport === 'tablet'} onClick={() => onChange('tablet')} label="Tablet" compact={compact} />
+ <ViewportBtn icon={Monitor} active={viewport === 'desktop'} onClick={() => onChange('desktop')} label="Desktop" compact={compact} />
+ </div>
+ )
+}
+
+interface ViewportBtnProps {
+ icon: typeof Smartphone
+ active: boolean
+ onClick: () => void
+ label: string
+ compact?: boolean
+}
+
+function ViewportBtn({ icon: Icon, active, onClick, label, compact }: ViewportBtnProps) {
+ return (
+ <button
+ onClick={onClick}
+ className={
+ `flex items-center justify-center ${compact ? 'w-5 h-5' : 'w-7 h-7'} rounded transition-colors ` +
+ (active
+ ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm'
+ : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-white')
+ }
+ aria-label={label}
+ title={label}
+ >
+ <Icon size={compact ? 10 : 13} />
+ </button>
+ )
+}
diff --git a/src/components/chat/HtmlPreviewModal.tsx b/src/components/chat/HtmlPreviewModal.tsx
index bd68d533..74a520fe 100644
--- a/src/components/chat/HtmlPreviewModal.tsx
+++ b/src/components/chat/HtmlPreviewModal.tsx
@@ -1,7 +1,9 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { X, ExternalLink, Smartphone, Tablet, Monitor, RotateCw } from 'lucide-react'
+import { X, ExternalLink, RotateCw } from 'lucide-react'
import { openExternal } from '../../api/backend'
+import { buildDocument, type Viewport } from '../../lib/html-preview'
+import { HtmlPreviewFrame, ViewportSwitcher } from './HtmlPreviewFrame'
interface Props {
code: string
@@ -9,61 +11,21 @@ interface Props {
onClose: () => void
}
-type Viewport = 'mobile' | 'tablet' | 'desktop'
-
-const VIEWPORTS: Record<Viewport, { width: number; height: number }> = {
- mobile: { width: 375, height: 667 },
- tablet: { width: 768, height: 1024 },
- desktop: { width: 1280, height: 800 },
-}
-
/**
- * Wrap an HTML / SVG snippet so the iframe always has a sane shell.
- * - Bare SVG → centred dark page that hugs the artwork.
- * - Snippet HTML (no <html>/<doctype>) → minimal doc with utf-8 + body padding.
- * - Full document → passed through untouched.
+ * Preview for a snippet the MODEL produced. It keeps `allow-scripts` on (the
+ * user asked for that code to exist, and a generated page without its script
+ * is not a preview); the Explorer panel's file preview deliberately does not,
+ * see file-preview.ts. Neither ever gets `allow-same-origin`, so the markup
+ * lives in an opaque origin and cannot reach the app.
*
- * The iframe runs with `sandbox="allow-scripts"` (no allow-same-origin), so
- * any user JS lives in an opaque origin and can't reach our app.
+ * The document shell lives in lib/html-preview.ts, shared with the panel.
*/
-function buildDocument(code: string, language?: string): string {
- const lang = (language || '').toLowerCase()
- const trimmed = code.trim()
- const lower = trimmed.toLowerCase()
-
- // Bare SVG.
- if (lang === 'svg' || (lower.startsWith('<svg') && lower.includes('xmlns'))) {
- return [
- '<!doctype html><html><head><meta charset="utf-8"><title>SVG Preview</title>',
- '<style>html,body{margin:0;padding:0;background:#0e0e0e;color:#fff;height:100%;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif}svg{max-width:100%;max-height:100%}</style>',
- '</head><body>',
- code,
- '</body></html>',
- ].join('')
- }
-
- // Already a full document.
- if (lower.startsWith('<!doctype') || lower.startsWith('<html')) {
- return code
- }
-
- // Snippet — wrap.
- return [
- '<!doctype html><html><head><meta charset="utf-8"><title>HTML Preview</title>',
- '<style>body{margin:0;padding:16px;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;line-height:1.5;background:#ffffff;color:#111}</style>',
- '</head><body>',
- code,
- '</body></html>',
- ].join('')
-}
-
export function HtmlPreviewModal({ code, language, onClose }: Props) {
const [viewport, setViewport] = useState<Viewport>('desktop')
const [reloadKey, setReloadKey] = useState(0)
- const iframeRef = useRef<HTMLIFrameElement>(null)
const doc = useMemo(() => buildDocument(code, language), [code, language])
- // Esc closes — matches every other overlay in the app.
+ // Esc closes, matching every other overlay in the app.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
@@ -72,8 +34,6 @@ export function HtmlPreviewModal({ code, language, onClose }: Props) {
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
- const dims = VIEWPORTS[viewport]
-
const openInBrowser = () => {
// Hand the data URL to the host browser. data: URLs work in modern
// browsers; users can then save / share / inspect with full devtools.
@@ -109,12 +69,7 @@ export function HtmlPreviewModal({ code, language, onClose }: Props) {
</span>
</div>
- {/* Viewport switcher */}
- <div className="flex items-center gap-0.5 bg-gray-100 dark:bg-white/[0.04] rounded-md p-0.5">
- <ViewportBtn icon={Smartphone} active={viewport === 'mobile'} onClick={() => setViewport('mobile')} label="Mobile" />
- <ViewportBtn icon={Tablet} active={viewport === 'tablet'} onClick={() => setViewport('tablet')} label="Tablet" />
- <ViewportBtn icon={Monitor} active={viewport === 'desktop'} onClick={() => setViewport('desktop')} label="Desktop" />
- </div>
+ <ViewportSwitcher viewport={viewport} onChange={setViewport} />
<div className="flex items-center gap-1">
<button
@@ -144,50 +99,12 @@ export function HtmlPreviewModal({ code, language, onClose }: Props) {
</div>
</div>
- {/* Frame area — checkered background to make the rendered surface obvious */}
+ {/* Frame area, checkered background to make the rendered surface obvious */}
<div className="flex-1 overflow-auto bg-[length:24px_24px] bg-[linear-gradient(45deg,rgba(0,0,0,0.04)_25%,transparent_25%,transparent_75%,rgba(0,0,0,0.04)_75%),linear-gradient(45deg,rgba(0,0,0,0.04)_25%,transparent_25%,transparent_75%,rgba(0,0,0,0.04)_75%)] bg-[position:0_0,12px_12px] dark:bg-[length:24px_24px] dark:bg-[linear-gradient(45deg,rgba(255,255,255,0.03)_25%,transparent_25%,transparent_75%,rgba(255,255,255,0.03)_75%),linear-gradient(45deg,rgba(255,255,255,0.03)_25%,transparent_25%,transparent_75%,rgba(255,255,255,0.03)_75%)] flex items-center justify-center p-4">
- <iframe
- key={reloadKey}
- ref={iframeRef}
- srcDoc={doc}
- sandbox="allow-scripts"
- referrerPolicy="no-referrer"
- title="HTML Preview"
- className="bg-white border border-gray-200 dark:border-white/10 shadow-lg rounded transition-all"
- style={{
- width: viewport === 'desktop' ? '100%' : `${dims.width}px`,
- height: viewport === 'desktop' ? '100%' : `${dims.height}px`,
- maxWidth: '100%',
- maxHeight: '100%',
- }}
- />
+ <HtmlPreviewFrame doc={doc} viewport={viewport} allowScripts reloadKey={reloadKey} />
</div>
</motion.div>
</motion.div>
</AnimatePresence>
)
}
-
-interface ViewportBtnProps {
- icon: typeof Smartphone
- active: boolean
- onClick: () => void
- label: string
-}
-function ViewportBtn({ icon: Icon, active, onClick, label }: ViewportBtnProps) {
- return (
- <button
- onClick={onClick}
- className={
- 'flex items-center justify-center w-7 h-7 rounded transition-colors ' +
- (active
- ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm'
- : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-white')
- }
- aria-label={label}
- title={label}
- >
- <Icon size={13} />
- </button>
- )
-}
diff --git a/src/lib/__tests__/explorer-tree.test.ts b/src/lib/__tests__/explorer-tree.test.ts
new file mode 100644
index 00000000..062bbbe6
--- /dev/null
+++ b/src/lib/__tests__/explorer-tree.test.ts
@@ -0,0 +1,227 @@
+/**
+ * The Explorer tree (2.6.6 C3): lazy per node, jailed to the picked root,
+ * ignore filter, and a listing that admits when the backend cut it off.
+ *
+ * The three claims that matter, each with its counter-test:
+ * 1. Expanding a folder lists THAT folder and nothing else (lazy).
+ * 2. Expanding never moves the jail: every call carries the picked root as
+ * workingDirectory, which is exactly what the old panel got wrong.
+ * 3. A path outside the root is refused before the backend is asked.
+ *
+ * Run: npx vitest run src/lib/__tests__/explorer-tree.test.ts
+ */
+import { describe, it, expect, vi } from 'vitest'
+import {
+ EXPLORER_IGNORED,
+ FS_LIST_CAP,
+ flattenTree,
+ isIgnoredEntry,
+ isWithinRoot,
+ loadChildren,
+ parseListing,
+ toggleExpanded,
+ type ExplorerListing,
+} from '../explorer-tree'
+
+const ROOT = '/repo'
+
+const entry = (dir: string, name: string, isDir = false) => ({
+ name,
+ path: `${dir}/${name}`,
+ isDir,
+ size: 12,
+ modified: 0,
+})
+
+/** A stand-in for the fs_list backend command. */
+function fakeBackend(dirs: Record<string, unknown[]>) {
+ const calls: Array<{ path: string; workingDirectory: string; recursive: boolean }> = []
+ const fsList = vi.fn(async (args: { path: string; recursive: boolean; pattern: null; workingDirectory: string }) => {
+ calls.push({ path: args.path, workingDirectory: args.workingDirectory, recursive: args.recursive })
+ const entries = dirs[args.path]
+ if (!entries) throw new Error(`Not a directory: ${args.path}`)
+ return { entries, count: entries.length }
+ })
+ return { fsList, calls }
+}
+
+const REPO = {
+ '/repo': [entry('/repo', 'src', true), entry('/repo', 'node_modules', true), entry('/repo', 'README.md')],
+ '/repo/src': [entry('/repo/src', 'lib', true), entry('/repo/src', 'main.ts')],
+ '/repo/src/lib': [entry('/repo/src/lib', 'util.ts')],
+}
+
+describe('expanding a folder loads it lazily', () => {
+ it('lists only the root until a folder is expanded', async () => {
+ const { fsList, calls } = fakeBackend(REPO)
+ const listings: Record<string, ExplorerListing> = {}
+ listings[ROOT] = await loadChildren(ROOT, ROOT, fsList)
+
+ expect(calls.map((c) => c.path)).toEqual(['/repo'])
+ // src is visible but has no children yet, so the tree is one level deep.
+ const rows = flattenTree(ROOT, listings, [])
+ expect(rows.map((r) => r.node.name)).toEqual(['src', 'README.md'])
+ expect(rows.every((r) => r.depth === 0)).toBe(true)
+ })
+
+ it('fetches a folder exactly once, when it is opened', async () => {
+ const { fsList, calls } = fakeBackend(REPO)
+ const listings: Record<string, ExplorerListing> = {}
+ listings[ROOT] = await loadChildren(ROOT, ROOT, fsList)
+
+ const expanded = toggleExpanded([], '/repo/src')
+ listings['/repo/src'] = await loadChildren('/repo/src', ROOT, fsList)
+
+ expect(calls.map((c) => c.path)).toEqual(['/repo', '/repo/src'])
+ const rows = flattenTree(ROOT, listings, expanded)
+ expect(rows.map((r) => `${r.depth}:${r.node.name}`)).toEqual([
+ '0:src',
+ '1:lib',
+ '1:main.ts',
+ '0:README.md',
+ ])
+ // The deeper folder is still untouched: lazy means lazy.
+ expect(calls.some((c) => c.path === '/repo/src/lib')).toBe(false)
+ })
+
+ it('collapsing hides the children again without re-fetching', async () => {
+ const { fsList, calls } = fakeBackend(REPO)
+ const listings: Record<string, ExplorerListing> = {}
+ listings[ROOT] = await loadChildren(ROOT, ROOT, fsList)
+ listings['/repo/src'] = await loadChildren('/repo/src', ROOT, fsList)
+
+ const closed = toggleExpanded(['/repo/src'], '/repo/src')
+ expect(closed).toEqual([])
+ expect(flattenTree(ROOT, listings, closed).map((r) => r.node.name)).toEqual(['src', 'README.md'])
+ expect(calls).toHaveLength(2)
+ })
+
+ it('counter-test: an unloaded folder contributes no rows even when marked open', () => {
+ const listings: Record<string, ExplorerListing> = {
+ [ROOT]: parseListing({ entries: REPO['/repo'] }),
+ }
+ const rows = flattenTree(ROOT, listings, ['/repo/src'])
+ expect(rows.map((r) => r.node.name)).toEqual(['src', 'README.md'])
+ })
+})
+
+describe('the jail stays where the user put it', () => {
+ it('carries the picked root as workingDirectory for every node', async () => {
+ const { fsList, calls } = fakeBackend(REPO)
+ await loadChildren(ROOT, ROOT, fsList)
+ await loadChildren('/repo/src', ROOT, fsList)
+ await loadChildren('/repo/src/lib', ROOT, fsList)
+
+ // The old panel passed the clicked folder here, which moved the agent's
+ // workspace root on every browse click.
+ expect(calls.map((c) => c.workingDirectory)).toEqual(['/repo', '/repo', '/repo'])
+ expect(calls.every((c) => c.recursive === false)).toBe(true)
+ })
+
+ it('refuses a path outside the root without asking the backend', async () => {
+ const { fsList, calls } = fakeBackend({ ...REPO, '/etc': [entry('/etc', 'passwd')] })
+ await expect(loadChildren('/etc', ROOT, fsList)).rejects.toThrow(/outside the workspace root/)
+ await expect(loadChildren('/repo/../etc', ROOT, fsList)).rejects.toThrow(/outside/)
+ expect(calls).toHaveLength(0)
+ })
+
+ it('drops entries that point out of the root', async () => {
+ const { fsList } = fakeBackend({
+ '/repo': [
+ entry('/repo', 'src', true),
+ { name: 'escape', path: '/etc/shadow', isDir: false, size: 1, modified: 0 },
+ ],
+ })
+ const listing = await loadChildren(ROOT, ROOT, fsList)
+ expect(listing.nodes.map((n) => n.name)).toEqual(['src'])
+ })
+
+ it('isWithinRoot: the root itself and its children pass, look-alikes do not', () => {
+ expect(isWithinRoot('/repo', '/repo')).toBe(true)
+ expect(isWithinRoot('/repo', '/repo/src/main.ts')).toBe(true)
+ expect(isWithinRoot('/repo', '/repo-evil/main.ts')).toBe(false)
+ expect(isWithinRoot('/repo', '/etc/passwd')).toBe(false)
+ expect(isWithinRoot('/repo', '/repo/../etc/passwd')).toBe(false)
+ expect(isWithinRoot('', '/repo/a')).toBe(false)
+ expect(isWithinRoot('/repo', '')).toBe(false)
+ })
+
+ it('isWithinRoot speaks Windows: backslashes and case', () => {
+ expect(isWithinRoot('D:\\Projects\\site', 'D:\\Projects\\site\\src\\main.rs')).toBe(true)
+ expect(isWithinRoot('D:\\Projects\\site', 'D:/Projects/Site/src/main.rs')).toBe(true)
+ expect(isWithinRoot('D:\\Projects\\site', 'D:\\Projects\\other\\x.txt')).toBe(false)
+ expect(isWithinRoot('D:\\Projects\\site', 'D:\\Projects\\site\\..\\other\\x.txt')).toBe(false)
+ // A POSIX root stays case-sensitive: /repo and /REPO are two folders.
+ expect(isWithinRoot('/repo', '/REPO/a.txt')).toBe(false)
+ })
+})
+
+describe('the ignore filter', () => {
+ it('hides exactly the four heavy folders', () => {
+ expect([...EXPLORER_IGNORED].sort()).toEqual(['.git', 'dist', 'node_modules', 'target'])
+ for (const name of EXPLORER_IGNORED) expect(isIgnoredEntry(name)).toBe(true)
+ })
+
+ it('counter-test: a name that merely starts the same is kept', () => {
+ expect(isIgnoredEntry('node_modules.md')).toBe(false)
+ expect(isIgnoredEntry('distribution')).toBe(false)
+ expect(isIgnoredEntry('.gitignore')).toBe(false)
+ expect(isIgnoredEntry('targets')).toBe(false)
+ })
+
+ it('takes them out of a listing and counts what it hid', () => {
+ const listing = parseListing({
+ entries: [
+ entry('/repo', 'node_modules', true),
+ entry('/repo', '.git', true),
+ entry('/repo', 'dist', true),
+ entry('/repo', 'target', true),
+ entry('/repo', 'src', true),
+ entry('/repo', '.gitignore'),
+ ],
+ })
+ expect(listing.nodes.map((n) => n.name)).toEqual(['src', '.gitignore'])
+ expect(listing.hidden).toBe(4)
+ })
+
+ it('puts folders first and sorts by name', () => {
+ const listing = parseListing({
+ entries: [
+ entry('/repo', 'zeta.ts'),
+ entry('/repo', 'alpha.ts'),
+ entry('/repo', 'src', true),
+ entry('/repo', 'Assets', true),
+ ],
+ })
+ expect(listing.nodes.map((n) => n.name)).toEqual(['Assets', 'src', 'alpha.ts', 'zeta.ts'])
+ })
+})
+
+describe('the 500 cap is visible', () => {
+ it('flags a listing that came back at the cap', () => {
+ const entries = Array.from({ length: FS_LIST_CAP }, (_, i) => entry('/repo', `f${i}.txt`))
+ expect(parseListing({ entries }).truncated).toBe(true)
+ })
+
+ it('counter-test: one entry short of the cap is not flagged', () => {
+ const entries = Array.from({ length: FS_LIST_CAP - 1 }, (_, i) => entry('/repo', `f${i}.txt`))
+ expect(parseListing({ entries }).truncated).toBe(false)
+ })
+
+ it('survives a junk answer instead of guessing', () => {
+ expect(parseListing(null)).toEqual({ nodes: [], truncated: false, hidden: 0 })
+ expect(parseListing({ entries: 'nope' })).toEqual({ nodes: [], truncated: false, hidden: 0 })
+ expect(parseListing({ entries: [{ name: '', path: '' }, { path: '/repo/x' }] }).nodes).toEqual([])
+ })
+})
+
+describe('flattenTree', () => {
+ it('cannot loop on a folder that contains itself (symlink)', () => {
+ const listings: Record<string, ExplorerListing> = {
+ '/repo': parseListing({ entries: [entry('/repo', 'self', true)] }),
+ '/repo/self': parseListing({ entries: [{ name: 'self', path: '/repo/self', isDir: true }] }),
+ }
+ const rows = flattenTree('/repo', listings, ['/repo/self'])
+ expect(rows.length).toBeLessThan(5)
+ })
+})
diff --git a/src/lib/explorer-tree.ts b/src/lib/explorer-tree.ts
new file mode 100644
index 00000000..1fd2e214
--- /dev/null
+++ b/src/lib/explorer-tree.ts
@@ -0,0 +1,165 @@
+/**
+ * Tree logic for the coding Explorer panel (2.6.6 C3).
+ *
+ * The old file panel was a one-level listing that REPLACED the workspace root
+ * on every folder click, so opening `src/` moved the agent's jail with it and
+ * the way back was a string split on "/" that breaks on a Windows backslash
+ * (plan R2). Here the root is picked once and every expand is a lazy listing
+ * of ONE node underneath it: `workingDirectory` stays the picked root, so the
+ * jail never moves, and no path is ever taken apart in the frontend. Every
+ * path the panel uses comes back from the backend verbatim.
+ *
+ * The panel calls `fs_list` DIRECTLY (never the model's tool executor) for the
+ * same reason the old one did: a model-supplied workingDirectory must never be
+ * able to pick its own jail root (security review 2.5.7).
+ */
+
+export interface ExplorerNode {
+ name: string
+ path: string
+ isDirectory: boolean
+ size?: number
+}
+
+/** Folders that turn a real repo into an unusable tree. A single npm install
+ * is 30k+ entries, which is 60 times the backend cap on its own. */
+export const EXPLORER_IGNORED: readonly string[] = ['node_modules', '.git', 'target', 'dist']
+
+/** filesystem.rs stops a listing at 500 entries (`max_entries`). The panel has
+ * to say so, otherwise a big folder silently looks complete. */
+export const FS_LIST_CAP = 500
+
+export function isIgnoredEntry(name: string): boolean {
+ return EXPLORER_IGNORED.includes(name)
+}
+
+export interface ExplorerListing {
+ nodes: ExplorerNode[]
+ /** The backend hit its 500 cap, so this listing is a prefix, not the folder. */
+ truncated: boolean
+ /** How many entries the ignore filter took out, for the muted hint row. */
+ hidden: number
+}
+
+export const EMPTY_LISTING: ExplorerListing = { nodes: [], truncated: false, hidden: 0 }
+
+/** Separator-agnostic comparison form. This normalises for COMPARING two
+ * backend paths; it never derives a new path from an old one. */
+function comparable(path: string): string {
+ const slashed = path.replace(/\\/g, '/').replace(/\/+$/, '')
+ // Windows paths compare case-insensitively (drive prefix or UNC share).
+ if (/^[a-zA-Z]:/.test(slashed) || slashed.startsWith('//')) return slashed.toLowerCase()
+ return slashed
+}
+
+/** True when `candidate` is the workspace root itself or sits underneath it.
+ * The real jail lives in Rust (`resolve_path` / `contain_within`); this is the
+ * frontend half, so the panel never even asks for a file it may not show. */
+export function isWithinRoot(root: string, candidate: string): boolean {
+ if (!root || !root.trim() || !candidate || !candidate.trim()) return false
+ // A ".." segment means the string says one thing and the filesystem another.
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(candidate)) return false
+ const r = comparable(root)
+ const c = comparable(candidate)
+ if (c === r) return true
+ return c.startsWith(r === '' ? '/' : `${r}/`)
+}
+
+function sortNodes(nodes: ExplorerNode[]): ExplorerNode[] {
+ return [...nodes].sort((a, b) => {
+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1
+ return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
+ })
+}
+
+/** Turn a raw `fs_list` answer into a listing: ignore filter, folders first,
+ * and the truncation flag the panel shows. */
+export function parseListing(data: unknown): ExplorerListing {
+ const raw = (data as { entries?: unknown } | null)?.entries
+ const entries: unknown[] = Array.isArray(raw) ? raw : []
+ const mapped: ExplorerNode[] = []
+ let hidden = 0
+ for (const entry of entries) {
+ const e = entry as { name?: unknown; path?: unknown; isDir?: unknown; size?: unknown }
+ const name = typeof e?.name === 'string' ? e.name : ''
+ const path = typeof e?.path === 'string' ? e.path : ''
+ if (!name || !path) continue
+ if (isIgnoredEntry(name)) {
+ hidden += 1
+ continue
+ }
+ mapped.push({
+ name,
+ path,
+ isDirectory: !!e?.isDir,
+ size: typeof e?.size === 'number' ? e.size : undefined,
+ })
+ }
+ return { nodes: sortNodes(mapped), truncated: entries.length >= FS_LIST_CAP, hidden }
+}
+
+export type FsList = (args: {
+ path: string
+ recursive: boolean
+ pattern: null
+ workingDirectory: string
+}) => Promise<unknown>
+
+/**
+ * Lazily list ONE directory node. `workingDirectory` stays the picked root for
+ * every node in the tree, so expanding a subfolder does not move the jail, and
+ * a path outside the root is refused before the backend is even asked.
+ */
+export async function loadChildren(
+ dir: string,
+ root: string,
+ fsList: FsList,
+): Promise<ExplorerListing> {
+ if (!isWithinRoot(root, dir)) {
+ throw new Error('Path is outside the workspace root')
+ }
+ const data = await fsList({ path: dir, recursive: false, pattern: null, workingDirectory: root })
+ const listing = parseListing(data)
+ // A symlink can point anywhere; the backend answers with the link's own path,
+ // so drop anything that does not sit under the root the user picked.
+ const inside = listing.nodes.filter((n) => isWithinRoot(root, n.path))
+ return { ...listing, nodes: inside }
+}
+
+export function toggleExpanded(expanded: readonly string[], path: string): string[] {
+ return expanded.includes(path) ? expanded.filter((p) => p !== path) : [...expanded, path]
+}
+
+export interface TreeRow {
+ node: ExplorerNode
+ depth: number
+ expanded: boolean
+}
+
+/**
+ * Flatten the loaded listings into the rows the panel renders. A folder only
+ * contributes children when it is expanded AND its listing has been loaded,
+ * which is what makes the loading lazy in the first place.
+ */
+export function flattenTree(
+ root: string,
+ listings: Readonly<Record<string, ExplorerListing | undefined>>,
+ expanded: readonly string[],
+): TreeRow[] {
+ const rows: TreeRow[] = []
+ const seen = new Set<string>()
+ const walk = (dir: string, depth: number) => {
+ const key = comparable(dir)
+ if (seen.has(key)) return
+ seen.add(key)
+ const listing = listings[dir]
+ if (!listing) return
+ for (const node of listing.nodes) {
+ const isOpen = node.isDirectory && expanded.includes(node.path)
+ rows.push({ node, depth, expanded: isOpen })
+ if (isOpen) walk(node.path, depth + 1)
+ }
+ }
+ walk(root, 0)
+ return rows
+}
diff --git a/src/lib/file-preview.ts b/src/lib/file-preview.ts
new file mode 100644
index 00000000..137d5275
--- /dev/null
+++ b/src/lib/file-preview.ts
@@ -0,0 +1,99 @@
+/**
+ * Which preview a clicked file gets in the Explorer panel (2.6.6 C3), and the
+ * sandbox the HTML one runs in.
+ *
+ * SECURITY (plan C3, round 2): the user clicked a file to LOOK at it, not to
+ * run the repository's JavaScript. So the explorer's HTML preview starts with
+ * an empty sandbox attribute, which is the fully restricted iframe, and gains
+ * `allow-scripts` only after an explicit per-file opt-in. `allow-same-origin`
+ * is never granted anywhere: together with allow-scripts it would let the page
+ * reach out of the frame and into the app's own origin.
+ */
+
+export type PreviewKind = 'text' | 'image' | 'html' | 'binary'
+
+/** Lowercase extension without the dot. Reads the tail of the NAME only, so
+ * no path is ever taken apart (plan R2, Windows parity). */
+export function extensionOf(name: string): string {
+ const m = /\.([^.\\/]+)$/.exec(name || '')
+ return m ? m[1].toLowerCase() : ''
+}
+
+const IMAGE_EXT = new Set([
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif', 'svg',
+])
+
+const HTML_EXT = new Set(['html', 'htm', 'xhtml'])
+
+const BINARY_EXT = new Set([
+ 'pdf', 'zip', 'gz', 'bz2', 'xz', 'tar', 'rar', '7z', 'exe', 'dll', 'so',
+ 'dylib', 'bin', 'wasm', 'woff', 'woff2', 'ttf', 'otf', 'eot', 'mp3', 'mp4',
+ 'mov', 'avi', 'mkv', 'wav', 'flac', 'ogg', 'webm', 'psd', 'class', 'jar',
+ 'pyc', 'db', 'sqlite', 'sqlite3', 'dmg', 'iso', 'gguf', 'safetensors',
+ 'ckpt', 'pt', 'pth', 'onnx',
+])
+
+export function previewKindFor(name: string): PreviewKind {
+ const ext = extensionOf(name)
+ if (IMAGE_EXT.has(ext)) return 'image'
+ if (HTML_EXT.has(ext)) return 'html'
+ if (BINARY_EXT.has(ext)) return 'binary'
+ return 'text'
+}
+
+const MIME: Record<string, string> = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp',
+ bmp: 'image/bmp',
+ ico: 'image/x-icon',
+ avif: 'image/avif',
+ svg: 'image/svg+xml',
+}
+
+/** Content type for the blob the image preview builds from the jailed bytes. */
+export function imageMimeFor(name: string): string {
+ return MIME[extensionOf(name)] ?? 'application/octet-stream'
+}
+
+const LANGUAGE: Record<string, string> = {
+ ts: 'typescript', tsx: 'tsx', js: 'javascript', jsx: 'jsx', mjs: 'javascript',
+ cjs: 'javascript', json: 'json', md: 'markdown', markdown: 'markdown',
+ css: 'css', scss: 'scss', less: 'less', html: 'html', htm: 'html',
+ xml: 'xml', yml: 'yaml', yaml: 'yaml', toml: 'toml', ini: 'ini',
+ rs: 'rust', py: 'python', rb: 'ruby', go: 'go', java: 'java', kt: 'kotlin',
+ swift: 'swift', c: 'c', h: 'c', cpp: 'cpp', cc: 'cpp', hpp: 'cpp',
+ cs: 'csharp', php: 'php', sh: 'bash', bash: 'bash', zsh: 'bash',
+ ps1: 'powershell', bat: 'batch', sql: 'sql', graphql: 'graphql',
+ dockerfile: 'docker', lua: 'lua', r: 'r', dart: 'dart', vue: 'markup',
+ svelte: 'markup', tf: 'hcl', gradle: 'groovy',
+}
+
+/** Prism language tag for the syntax highlighter, 'text' when unknown. */
+export function previewLanguageFor(name: string): string {
+ const ext = extensionOf(name)
+ if (LANGUAGE[ext]) return LANGUAGE[ext]
+ if (/^dockerfile$/i.test(name)) return 'docker'
+ if (/^makefile$/i.test(name)) return 'makefile'
+ return 'text'
+}
+
+/** A minified bundle is one line of two million characters, and the
+ * highlighter would chew on it for minutes. */
+export const PREVIEW_TEXT_CAP = 200_000
+
+export function capPreviewText(text: string): { text: string; truncated: boolean } {
+ if (text.length <= PREVIEW_TEXT_CAP) return { text, truncated: false }
+ return { text: text.slice(0, PREVIEW_TEXT_CAP), truncated: true }
+}
+
+/**
+ * The iframe sandbox for a preview. Empty string = every restriction on, which
+ * is the explorer default. `allow-same-origin` is deliberately absent from both
+ * branches: an opaque origin is what keeps previewed markup away from the app.
+ */
+export function sandboxAttr(allowScripts: boolean): string {
+ return allowScripts ? 'allow-scripts' : ''
+}
diff --git a/src/lib/html-preview.ts b/src/lib/html-preview.ts
new file mode 100644
index 00000000..268ca48b
--- /dev/null
+++ b/src/lib/html-preview.ts
@@ -0,0 +1,57 @@
+/**
+ * The document and viewport maths behind every HTML preview: the model-snippet
+ * modal and, since 2.6.6 C3, the Explorer panel's file preview.
+ *
+ * Pulled out of HtmlPreviewModal so both surfaces build the identical document
+ * and so this half is testable without a DOM.
+ */
+
+export type Viewport = 'mobile' | 'tablet' | 'desktop'
+
+export const VIEWPORTS: Record<Viewport, { width: number; height: number }> = {
+ mobile: { width: 375, height: 667 },
+ tablet: { width: 768, height: 1024 },
+ desktop: { width: 1280, height: 800 },
+}
+
+/**
+ * Wrap an HTML / SVG snippet so the iframe always has a sane shell.
+ * - Bare SVG becomes a centred dark page that hugs the artwork.
+ * - Snippet HTML (no html tag, no doctype) becomes a minimal document with
+ * utf-8 and body padding.
+ * - A full document is passed through untouched.
+ *
+ * Note for the panel preview: the document is handed to the iframe via
+ * `srcDoc`, so relative assets next to the file (a css or js sibling) do NOT
+ * load. That is a documented v1 limit (plan R2), not a bug.
+ */
+export function buildDocument(code: string, language?: string): string {
+ const lang = (language || '').toLowerCase()
+ const trimmed = code.trim()
+ const lower = trimmed.toLowerCase()
+
+ // Bare SVG.
+ if (lang === 'svg' || (lower.startsWith('<svg') && lower.includes('xmlns'))) {
+ return [
+ '<!doctype html><html><head><meta charset="utf-8"><title>SVG Preview</title>',
+ '<style>html,body{margin:0;padding:0;background:#0e0e0e;color:#fff;height:100%;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif}svg{max-width:100%;max-height:100%}</style>',
+ '</head><body>',
+ code,
+ '</body></html>',
+ ].join('')
+ }
+
+ // Already a full document.
+ if (lower.startsWith('<!doctype') || lower.startsWith('<html')) {
+ return code
+ }
+
+ // Snippet, so wrap it.
+ return [
+ '<!doctype html><html><head><meta charset="utf-8"><title>HTML Preview</title>',
+ '<style>body{margin:0;padding:16px;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;line-height:1.5;background:#ffffff;color:#111}</style>',
+ '</head><body>',
+ code,
+ '</body></html>',
+ ].join('')
+}
diff --git a/src/stores/__tests__/uiStore-explorer.test.ts b/src/stores/__tests__/uiStore-explorer.test.ts
new file mode 100644
index 00000000..91c24b61
--- /dev/null
+++ b/src/stores/__tests__/uiStore-explorer.test.ts
@@ -0,0 +1,127 @@
+/**
+ * uiStore persist (2.6.6 C3 / R1).
+ *
+ * This store was NOT persisted before. It carries currentView and
+ * cloudGateOpen, so a naive persist would change what the app does on start:
+ * it would reopen on whatever tab was left behind, or come up with the cloud
+ * gate on screen. partialize therefore has to hold EXACTLY the two explorer
+ * fields, and this test is the guard on that word "exactly".
+ *
+ * Run: npx vitest run src/stores/__tests__/uiStore-explorer.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+// The suite runs in node, where there is no localStorage. Without one, zustand
+// skips the persist middleware entirely and there would be nothing to assert
+// against. Hoisted so it exists before the store module is imported.
+const memory = vi.hoisted(() => {
+ const map = new Map<string, string>()
+ const storage = {
+ getItem: (k: string) => map.get(k) ?? null,
+ setItem: (k: string, v: string) => void map.set(k, String(v)),
+ removeItem: (k: string) => void map.delete(k),
+ clear: () => map.clear(),
+ key: (i: number) => [...map.keys()][i] ?? null,
+ get length() {
+ return map.size
+ },
+ }
+ // zustand reaches for window.localStorage specifically, so the shim has to
+ // sit there and not only on globalThis.
+ const g = globalThis as unknown as { window?: { localStorage: typeof storage }; localStorage?: typeof storage }
+ g.localStorage = storage
+ g.window = { ...(g.window ?? {}), localStorage: storage }
+ return storage
+})
+
+import {
+ EXPLORER_DEFAULT_WIDTH,
+ EXPLORER_MIN_WIDTH,
+ clampExplorerWidth,
+ useUIStore,
+} from '../uiStore'
+
+describe('what the ui store writes to disk', () => {
+ it('persists exactly explorerWidth and explorerCollapsed', () => {
+ const partialize = useUIStore.persist.getOptions().partialize
+ expect(partialize).toBeTypeOf('function')
+ const written = partialize!(useUIStore.getState()) as Record<string, unknown>
+ expect(Object.keys(written).sort()).toEqual(['explorerCollapsed', 'explorerWidth'])
+ })
+
+ it('counter-test: nothing that steers the app start comes along', () => {
+ const partialize = useUIStore.persist.getOptions().partialize!
+ const written = partialize(useUIStore.getState()) as Record<string, unknown>
+ for (const forbidden of ['currentView', 'cloudGateOpen', 'cloudTeaser', 'sidebarOpen']) {
+ expect(written).not.toHaveProperty(forbidden)
+ }
+ // Actions must not ride along either, they would be dead weight in storage.
+ expect(Object.values(written).every((v) => typeof v !== 'function')).toBe(true)
+ })
+
+ it('keeps writing only those two after the state moved', () => {
+ useUIStore.setState({ currentView: 'settings', cloudGateOpen: true, explorerCollapsed: true, explorerWidth: 333 })
+ const written = useUIStore.persist.getOptions().partialize!(useUIStore.getState()) as Record<string, unknown>
+ expect(written).toEqual({ explorerWidth: 333, explorerCollapsed: true })
+ })
+
+ it('and that is what actually lands in storage', () => {
+ useUIStore.setState({ currentView: 'benchmark', cloudGateOpen: true })
+ useUIStore.getState().setExplorerWidth(420, 1600)
+ useUIStore.getState().setExplorerCollapsed(true)
+ const raw = memory.getItem('locally-uncensored-ui')
+ expect(raw).toBeTruthy()
+ const parsed = JSON.parse(raw!)
+ expect(parsed.state).toEqual({ explorerWidth: 420, explorerCollapsed: true })
+ })
+})
+
+describe('the drag stays inside the panel limits', () => {
+ it('keeps a sane width untouched', () => {
+ expect(clampExplorerWidth(320, 1600)).toBe(320)
+ })
+
+ it('floors at the minimum', () => {
+ expect(clampExplorerWidth(40, 1600)).toBe(EXPLORER_MIN_WIDTH)
+ expect(clampExplorerWidth(-500, 1600)).toBe(EXPLORER_MIN_WIDTH)
+ })
+
+ it('ceilings at half the window', () => {
+ expect(clampExplorerWidth(5000, 1600)).toBe(800)
+ expect(clampExplorerWidth(900, 1000)).toBe(500)
+ })
+
+ it('counter-test: on a narrow window the minimum wins over the half', () => {
+ // Half of 300 is 150, which is below the floor: the panel stays readable.
+ expect(clampExplorerWidth(280, 300)).toBe(EXPLORER_MIN_WIDTH)
+ })
+
+ it('falls back to the default when the number is not one', () => {
+ expect(clampExplorerWidth(Number.NaN, 1600)).toBe(EXPLORER_DEFAULT_WIDTH)
+ })
+})
+
+describe('the store actions', () => {
+ beforeEach(() => {
+ useUIStore.setState({ explorerWidth: EXPLORER_DEFAULT_WIDTH, explorerCollapsed: false })
+ })
+
+ it('starts at 280 and open', () => {
+ expect(useUIStore.getState().explorerWidth).toBe(280)
+ expect(useUIStore.getState().explorerCollapsed).toBe(false)
+ })
+
+ it('clamps through the setter, not only in the component', () => {
+ useUIStore.getState().setExplorerWidth(10_000, 1200)
+ expect(useUIStore.getState().explorerWidth).toBe(600)
+ useUIStore.getState().setExplorerWidth(10, 1200)
+ expect(useUIStore.getState().explorerWidth).toBe(EXPLORER_MIN_WIDTH)
+ })
+
+ it('collapses and comes back', () => {
+ useUIStore.getState().setExplorerCollapsed(true)
+ expect(useUIStore.getState().explorerCollapsed).toBe(true)
+ useUIStore.getState().setExplorerCollapsed(false)
+ expect(useUIStore.getState().explorerCollapsed).toBe(false)
+ })
+})
diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.ts
index e0a77129..090fa2f8 100644
--- a/src/stores/uiStore.ts
+++ b/src/stores/uiStore.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark'
@@ -6,7 +7,7 @@ export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark'
* 'intent' = a locked Create tab (the cloud-only intents incl. the five
* 2.5.8 categories); 'create-model' = a hosted model row in the Create
* picker (modelId = the tapped catalog id). The chat picker's Cloud rows
- * open the CloudGateModal directly — no sheet there. */
+ * open the CloudGateModal directly, no sheet there. */
export type CloudTeaserTarget =
| {
surface: 'intent'
@@ -14,33 +15,74 @@ export type CloudTeaserTarget =
}
| { surface: 'create-model'; kind: 'image' | 'video'; modelId: string }
+/** Explorer panel geometry (2.6.6 C3). 280px is wide enough for a nested
+ * path, 200 is the floor where names stop being readable, and the ceiling is
+ * half the window so the panel can never eat the transcript. */
+export const EXPLORER_DEFAULT_WIDTH = 280
+export const EXPLORER_MIN_WIDTH = 200
+
+/** Clamp a dragged width against the current window. Pure so the drag maths
+ * is testable without a DOM. */
+export function clampExplorerWidth(width: number, viewportWidth: number): number {
+ if (!Number.isFinite(width)) return EXPLORER_DEFAULT_WIDTH
+ const half = Math.floor((Number.isFinite(viewportWidth) ? viewportWidth : 0) / 2)
+ const max = Math.max(EXPLORER_MIN_WIDTH, half)
+ return Math.round(Math.min(Math.max(width, EXPLORER_MIN_WIDTH), max))
+}
+
interface UIState {
currentView: View
sidebarOpen: boolean
- /** CloudGateModal (login → plan → beta gate) — opened by the header's
+ /** CloudGateModal (login, plan, beta gate), opened by the header's
* Cloud switch when the cloud side isn't usable yet. */
cloudGateOpen: boolean
- /** CloudTeaserModal — null = closed. */
+ /** CloudTeaserModal, null = closed. */
cloudTeaser: CloudTeaserTarget | null
+ /** Explorer panel width in px, persisted. */
+ explorerWidth: number
+ /** Explorer panel collapsed to its rail, persisted. */
+ explorerCollapsed: boolean
setView: (view: View) => void
toggleSidebar: () => void
setSidebarOpen: (open: boolean) => void
setCloudGateOpen: (open: boolean) => void
setCloudTeaser: (target: CloudTeaserTarget | null) => void
+ setExplorerWidth: (width: number, viewportWidth: number) => void
+ setExplorerCollapsed: (collapsed: boolean) => void
}
-export const useUIStore = create<UIState>()((set) => ({
- currentView: 'chat',
- sidebarOpen: true,
- cloudGateOpen: false,
- cloudTeaser: null,
+export const useUIStore = create<UIState>()(
+ persist(
+ (set) => ({
+ currentView: 'chat',
+ sidebarOpen: true,
+ cloudGateOpen: false,
+ cloudTeaser: null,
+ explorerWidth: EXPLORER_DEFAULT_WIDTH,
+ explorerCollapsed: false,
- // Sidebar visibility follows the view: it's the conversation list, which
- // only makes sense in Chat. The hamburger toggle still works on other views;
- // it just resets to the view's default on the next setView() call.
- setView: (view) => set({ currentView: view, sidebarOpen: view === 'chat' }),
- toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen })),
- setSidebarOpen: (open) => set({ sidebarOpen: open }),
- setCloudGateOpen: (open) => set({ cloudGateOpen: open }),
- setCloudTeaser: (target) => set({ cloudTeaser: target }),
-}))
+ // Sidebar visibility follows the view: it's the conversation list, which
+ // only makes sense in Chat. The hamburger toggle still works on other views;
+ // it just resets to the view's default on the next setView() call.
+ setView: (view) => set({ currentView: view, sidebarOpen: view === 'chat' }),
+ toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen })),
+ setSidebarOpen: (open) => set({ sidebarOpen: open }),
+ setCloudGateOpen: (open) => set({ cloudGateOpen: open }),
+ setCloudTeaser: (target) => set({ cloudTeaser: target }),
+ setExplorerWidth: (width, viewportWidth) =>
+ set({ explorerWidth: clampExplorerWidth(width, viewportWidth) }),
+ setExplorerCollapsed: (collapsed) => set({ explorerCollapsed: collapsed }),
+ }),
+ {
+ name: 'locally-uncensored-ui',
+ // EXACTLY the two explorer fields (plan C3 / R1). This store was not
+ // persisted at all before, and persisting it naively would carry
+ // currentView and cloudGateOpen across restarts: the app would reopen on
+ // whatever tab was left behind, or come up with the cloud gate on screen.
+ partialize: (state) => ({
+ explorerWidth: state.explorerWidth,
+ explorerCollapsed: state.explorerCollapsed,
+ }),
+ },
+ ),
+)