LocalWebAgent / js /files.js
ereniko's picture
LocalWebAgent v0.3.0: LFM3-1.7B agent + CheerpX Linux + file viewer, fully offline
a8f5a2f verified
Raw History Blame Contribute Delete
22 kB
// File viewer for the Linux machine: a directory explorer plus viewers for code,
// text, Markdown, images, audio/video and HTML. Files are read through hidden VM
// processes (vm.listDir / vm.readFile), so nothing shows up in the terminal.
//
// HTML files open as sandboxed previews: the page is bundled with the stylesheets,
// scripts and images it references (inlined as data: URLs) and rendered in an iframe
// with an opaque origin, so it can't touch the app. A small injected shim forwards
// clicks on relative links (opens that file in the viewer) and relative fetch() calls
// (answered with the file's contents) to the app.
import hljs from "../vendor/highlight.min.js";
import { renderMarkdown } from "./markdown.js";
const HOME = "/home/user";
const MAX_TEXT = 2e6; // larger text files are shown truncated
const MAX_HIGHLIGHT = 4e5; // above this, no syntax highlighting
const MAX_INLINE_ASSET = 15e6;
const IMAGE = { 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" };
const VIDEO = { mp4: "video/mp4", webm: "video/webm", ogv: "video/ogg", mov: "video/quicktime" };
const AUDIO = { mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", oga: "audio/ogg", m4a: "audio/mp4", flac: "audio/flac" };
const MIME = {
...IMAGE, ...VIDEO, ...AUDIO, html: "text/html", htm: "text/html", css: "text/css", js: "text/javascript", mjs: "text/javascript",
json: "application/json", txt: "text/plain", md: "text/markdown", csv: "text/csv", xml: "application/xml", wasm: "application/wasm",
woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", pdf: "application/pdf",
};
const LANG = {
py: "python", js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "javascript", ts: "typescript", tsx: "typescript",
json: "json", c: "c", h: "c", cpp: "cpp", cc: "cpp", cxx: "cpp", hpp: "cpp", hh: "cpp", sh: "bash", bash: "bash", zsh: "bash",
css: "css", scss: "scss", less: "less", html: "xml", htm: "xml", xml: "xml", svg: "xml", md: "markdown", markdown: "markdown",
rs: "rust", go: "go", java: "java", kt: "kotlin", rb: "ruby", lua: "lua", sql: "sql", yml: "yaml", yaml: "yaml", toml: "ini",
ini: "ini", cfg: "ini", conf: "ini", php: "php", pl: "perl", r: "r", swift: "swift", diff: "diff", patch: "diff",
makefile: "makefile", mk: "makefile", dockerfile: "dockerfile", cs: "csharp", vim: "vim", tex: "latex",
};
const TEXTISH = new Set(["txt", "log", "csv", "tsv", "env", "gitignore", "lock", "rst", "service", "list", "sources"]);
const extOf = (name) => {
const base = name.split("/").pop().toLowerCase();
if (base === "makefile" || base === "dockerfile") return base;
const i = base.lastIndexOf(".");
return i > 0 ? base.slice(i + 1) : "";
};
const kindOf = (name) => {
const e = extOf(name);
if (e === "svg") return "svg";
if (IMAGE[e]) return "image";
if (VIDEO[e]) return "video";
if (AUDIO[e]) return "audio";
if (e === "html" || e === "htm") return "html";
if (e === "md" || e === "markdown") return "markdown";
if (LANG[e] || TEXTISH.has(e)) return "code";
return "unknown";
};
export const dirname = (p) => (p.replace(/\/+$/, "").replace(/\/[^/]*$/, "") || "/");
export function resolvePath(base, ref) {
const parts = (ref.startsWith("/") ? ref : base + "/" + ref).split("/");
const out = [];
for (const s of parts) {
if (!s || s === ".") continue;
if (s === "..") out.pop(); else out.push(s);
}
return "/" + out.join("/");
}
const isRelativeRef = (u) => !!u && !/^([a-z][a-z0-9+.-]*:|\/\/|#)/i.test(u.trim());
const stripQuery = (u) => u.split(/[?#]/)[0];
const fmtSize = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function h(tag, attrs = {}, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") el.className = v;
else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
else if (v !== false && v != null) el.setAttribute(k, v === true ? "" : v);
}
for (const kid of kids.flat()) if (kid != null) el.append(kid);
return el;
}
function icon(name) {
const s = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const u = document.createElementNS("http://www.w3.org/2000/svg", "use");
u.setAttribute("href", "#i-" + name);
s.append(u);
return s;
}
const iconFor = (entry) => entry.type === "d" ? "folder" : ({ image: "image", svg: "image", html: "globe", code: "file-code", markdown: "file", video: "film", audio: "music" })[kindOf(entry.name)] ?? "file";
export class FileBrowser {
/** @param {{vm: import('./vm.js').VM, root: HTMLElement, onOpen?: (path:string)=>void}} opts */
constructor({ vm, root, onOpen }) {
this.vm = vm;
this.root = root;
this.onOpen = onOpen;
this.dir = HOME;
this.entries = [];
this.current = null; // { path, kind, size, mode: 'preview'|'source' }
this.showHidden = false;
this.objectUrls = [];
this.#build();
window.addEventListener("message", (e) => this.#onFrameMessage(e));
}
#build() {
this.crumbs = h("div", { class: "crumbs" });
this.list = h("div", { class: "ex-list", role: "listbox", "aria-label": "Files" });
this.hiddenBtn = h("button", { class: "mini-btn", title: "Show hidden files", "aria-pressed": "false", onclick: () => this.#toggleHidden() }, icon("eye"));
const explorer = h("aside", { class: "explorer" },
h("div", { class: "ex-head" },
h("button", { class: "mini-btn", title: "Up one folder", onclick: () => this.navigate(dirname(this.dir)) }, icon("arrow-up")),
h("button", { class: "mini-btn", title: "Home", onclick: () => this.navigate(HOME) }, icon("home")),
h("span", { class: "spacer" }),
this.hiddenBtn,
h("button", { class: "mini-btn", title: "Refresh", onclick: () => this.refresh() }, icon("refresh"))),
this.crumbs, this.list);
this.vwPath = h("span", { class: "vw-path" });
this.vwMeta = h("span", { class: "vw-meta" });
this.modeSeg = h("div", { class: "seg small", hidden: true },
h("button", { "data-mode": "preview", onclick: () => this.#setMode("preview") }, "Preview"),
h("button", { "data-mode": "source", onclick: () => this.#setMode("source") }, "Source"));
this.vwActions = h("div", { class: "vw-actions", hidden: true },
this.modeSeg,
h("button", { class: "mini-btn", title: "Reload file", onclick: () => this.current && this.open(this.current.path, { mode: this.current.mode }) }, icon("refresh")),
h("button", { class: "mini-btn", title: "Download", onclick: () => this.#download() }, icon("download")));
this.vwBody = h("div", { class: "vw-body" });
this.viewer = h("div", { class: "viewer" },
h("div", { class: "vw-head" }, this.vwPath, this.vwMeta, h("span", { class: "spacer" }), this.vwActions),
this.vwBody);
this.root.append(explorer, this.viewer);
this.#placeholder("Select a file to view it.", "Code, text, images, audio, video and HTML pages open here.");
}
#placeholder(title, sub) {
this.vwPath.textContent = "";
this.vwMeta.textContent = "";
this.vwActions.hidden = true;
this.vwBody.replaceChildren(h("div", { class: "vw-empty" }, icon("folder-open"), h("div", { class: "vw-empty-title" }, title), sub ? h("div", { class: "vw-empty-sub" }, sub) : null));
}
#toggleHidden() {
this.showHidden = !this.showHidden;
this.hiddenBtn.setAttribute("aria-pressed", String(this.showHidden));
this.#renderList();
}
async navigate(dir) {
this.list.classList.add("loading");
try {
const res = await this.vm.listDir(dir);
this.dir = res.path || dir;
this.entries = res.entries.sort((a, b) => (a.type === "d") !== (b.type === "d") ? (a.type === "d" ? -1 : 1) : a.name.localeCompare(b.name, undefined, { numeric: true }));
this.#renderList();
} catch (err) {
this.list.replaceChildren(h("div", { class: "ex-error" }, err.message));
} finally {
this.list.classList.remove("loading");
}
}
refresh() { return this.navigate(this.dir); }
#renderList() {
const parts = this.dir.split("/").filter(Boolean);
this.crumbs.replaceChildren(
h("button", { class: "crumb", onclick: () => this.navigate("/") }, "/"),
...parts.flatMap((p, i) => [
i ? h("span", { class: "crumb-sep" }, "/") : null,
h("button", { class: "crumb", onclick: () => this.navigate("/" + parts.slice(0, i + 1).join("/")) }, p),
]).filter(Boolean),
);
const shown = this.entries.filter((e) => this.showHidden || !e.name.startsWith("."));
if (!shown.length) { this.list.replaceChildren(h("div", { class: "ex-empty" }, "Empty folder")); return; }
this.list.replaceChildren(...shown.map((e) => {
const full = resolvePath(this.dir, e.name);
const row = h("button", { class: "ex-item" + (this.current?.path === full ? " active" : "") + (e.name.startsWith(".") ? " dim" : ""), role: "option", title: full },
icon(iconFor(e)), h("span", { class: "ex-name" }, e.name), e.type === "f" ? h("span", { class: "ex-size" }, fmtSize(e.size)) : null);
row.addEventListener("click", () => (e.type === "d" ? this.navigate(full) : this.open(full)));
return row;
}));
}
/** Opens a file (absolute path). Also moves the explorer to its folder. */
async open(path, { mode } = {}) {
const kind = kindOf(path);
const defaultMode = kind === "html" || kind === "markdown" || kind === "svg" ? "preview" : "source";
this.current = { path, kind, mode: mode ?? defaultMode };
if (dirname(path) !== this.dir) this.navigate(dirname(path)); else this.#renderList();
this.onOpen?.(path);
const cut = path.lastIndexOf("/") + 1;
this.vwPath.replaceChildren(h("span", { class: "vw-dir" }, path.slice(0, cut)), h("span", { class: "vw-file" }, path.slice(cut)));
this.vwPath.title = path;
this.vwMeta.textContent = "";
this.vwActions.hidden = false;
this.modeSeg.hidden = !(kind === "html" || kind === "markdown" || kind === "svg");
for (const b of this.modeSeg.children) b.setAttribute("aria-pressed", String(b.dataset.mode === this.current.mode));
this.vwBody.replaceChildren(h("div", { class: "vw-loading" }, h("span", { class: "spinner" })));
this.#revokeUrls();
let blob;
try {
blob = await this.vm.readFile(path);
} catch (err) {
if (err.code === "EISDIR") return this.navigate(path);
this.vwBody.replaceChildren(h("div", { class: "vw-empty" }, icon("alert"), h("div", { class: "vw-empty-title" }, "Can't open this file"), h("div", { class: "vw-empty-sub" }, err.message)));
return;
}
if (this.current?.path !== path) return; // another file was opened meanwhile
this.current.blob = blob;
this.current.size = blob.size;
this.vwMeta.textContent = fmtSize(blob.size);
await this.#render();
}
#setMode(mode) {
if (!this.current) return;
this.current.mode = mode;
for (const b of this.modeSeg.children) b.setAttribute("aria-pressed", String(b.dataset.mode === mode));
this.#render();
}
async #render() {
const { path, kind, blob, mode } = this.current;
const ext = extOf(path);
const body = this.vwBody;
if ((kind === "image" || (kind === "svg" && mode === "preview"))) {
const url = this.#url(new Blob([blob], { type: IMAGE[ext] }));
const img = h("img", { src: url, alt: path.split("/").pop(), class: "fit" });
img.addEventListener("load", () => { this.vwMeta.textContent = `${img.naturalWidth} × ${img.naturalHeight} · ${fmtSize(blob.size)}`; });
img.addEventListener("click", () => img.classList.toggle("fit"));
body.replaceChildren(h("div", { class: "vw-image" }, img));
return;
}
if (kind === "video" || kind === "audio") {
const url = this.#url(new Blob([blob], { type: (VIDEO[ext] || AUDIO[ext]) }));
body.replaceChildren(h("div", { class: "vw-media" }, h(kind, { src: url, controls: true })));
return;
}
if (kind === "html" && mode === "preview") return this.#renderHtml();
if (kind === "markdown" && mode === "preview") {
body.replaceChildren(h("div", { class: "vw-doc md" }));
body.firstChild.innerHTML = renderMarkdown(await blob.slice(0, MAX_TEXT).text());
return;
}
// text / code / unknown
const head = new Uint8Array(await blob.slice(0, 8000).arrayBuffer());
if (kind === "unknown" && head.includes(0)) return this.#renderBinary(head);
const truncated = blob.size > MAX_TEXT;
const text = await blob.slice(0, MAX_TEXT).text();
this.#renderCode(text, LANG[ext] ?? (kind === "unknown" && text.length < 50000 ? null : "plaintext"), truncated);
}
#renderCode(text, lang, truncated) {
let html;
if (text.length > MAX_HIGHLIGHT || lang === "plaintext") html = esc(text);
else {
try {
html = lang && hljs.getLanguage(lang) ? hljs.highlight(text, { language: lang, ignoreIllegals: true }).value : hljs.highlightAuto(text).value;
} catch { html = esc(text); }
}
const lines = text.endsWith("\n") ? text.split("\n").length - 1 : text.split("\n").length;
const gutter = h("pre", { class: "gutter", "aria-hidden": "true" });
gutter.textContent = Array.from({ length: Math.max(1, lines) }, (_, i) => i + 1).join("\n");
const code = h("pre", { class: "code hljs" });
code.innerHTML = html;
this.vwBody.replaceChildren(h("div", { class: "vw-code" }, gutter, code),
truncated ? h("div", { class: "vw-note" }, `Showing the first ${fmtSize(MAX_TEXT)}.`) : null);
this.vwMeta.textContent = `${lines.toLocaleString()} line${lines === 1 ? "" : "s"} · ${fmtSize(this.current.size)}`;
}
#renderBinary(head) {
const rows = [];
for (let i = 0; i < Math.min(head.length, 512); i += 16) {
const bytes = [...head.slice(i, i + 16)];
rows.push(i.toString(16).padStart(8, "0") + " " + bytes.map((b) => b.toString(16).padStart(2, "0")).join(" ").padEnd(48) + " " +
bytes.map((b) => (b >= 32 && b < 127 ? String.fromCharCode(b) : ".")).join(""));
}
this.vwBody.replaceChildren(
h("div", { class: "vw-binary" },
h("div", { class: "vw-note top" }, `Binary file · ${fmtSize(this.current.size)}. Showing the first ${Math.min(head.length, 512)} bytes.`),
h("pre", { class: "hex" }, rows.join("\n"))));
}
// ---------- HTML preview ----------
async #renderHtml() {
const { path, blob } = this.current;
const frame = h("iframe", {
class: "vw-frame", title: "Preview of " + path,
sandbox: "allow-scripts allow-forms allow-modals allow-popups allow-downloads",
referrerpolicy: "no-referrer",
});
this.vwBody.replaceChildren(h("div", { class: "vw-loading" }, h("span", { class: "spinner" })));
const srcdoc = await this.#bundleHtml(path, await blob.text());
if (this.current?.path !== path) return;
frame.srcdoc = srcdoc;
this.frame = frame;
this.frameDir = dirname(path);
this.vwBody.replaceChildren(h("div", { class: "vw-frame-wrap" }, frame));
}
async #readAsset(vmPath) {
try {
const b = await this.vm.readFile(vmPath, MAX_INLINE_ASSET);
return b;
} catch { return null; }
}
async #dataUrl(vmPath) {
const b = await this.#readAsset(vmPath);
if (!b) return null;
const typed = new Blob([b], { type: MIME[extOf(vmPath)] ?? "application/octet-stream" });
return new Promise((res) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => res(null); r.readAsDataURL(typed); });
}
async #inlineCss(css, baseDir, depth = 0) {
// url(...) references
const refs = new Set();
css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (_, q, u) => { if (isRelativeRef(u) && !u.startsWith("data:")) refs.add(u); return _; });
const map = new Map();
await Promise.all([...refs].map(async (u) => map.set(u, await this.#dataUrl(resolvePath(baseDir, stripQuery(u))))));
css = css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (m, q, u) => (map.get(u) ? `url("${map.get(u)}")` : m));
// @import "file.css"
if (depth < 3) {
const imports = [...css.matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]\s*\)?\s*;/g)];
for (const m of imports) {
if (!isRelativeRef(m[1])) continue;
const p = resolvePath(baseDir, stripQuery(m[1]));
const b = await this.#readAsset(p);
css = css.replace(m[0], b ? await this.#inlineCss(await b.text(), dirname(p), depth + 1) : "");
}
}
return css;
}
async #bundleHtml(path, html) {
const dir = dirname(path);
const doc = new DOMParser().parseFromString(html, "text/html");
const jobs = [];
for (const link of doc.querySelectorAll('link[rel~="stylesheet"][href]')) {
const href = link.getAttribute("href");
if (!isRelativeRef(href)) continue;
jobs.push((async () => {
const p = resolvePath(dir, stripQuery(href));
const b = await this.#readAsset(p);
const style = doc.createElement("style");
style.textContent = b ? await this.#inlineCss(await b.text(), dirname(p)) : `/* missing: ${href} */`;
link.replaceWith(style);
})());
}
for (const style of doc.querySelectorAll("style")) jobs.push((async () => { style.textContent = await this.#inlineCss(style.textContent, dir); })());
for (const s of doc.querySelectorAll("script[src]")) {
const src = s.getAttribute("src");
if (!isRelativeRef(src)) continue;
jobs.push((async () => {
const b = await this.#readAsset(resolvePath(dir, stripQuery(src)));
s.removeAttribute("src");
s.textContent = b ? (await b.text()).replace(/<\/script/gi, "<\\/script") : `console.error("LocalWebAgent preview: missing ${src.replace(/"/g, "")}")`;
})());
}
for (const el of doc.querySelectorAll("img[src], source[src], video[src], audio[src], input[type=image][src], track[src], embed[src], link[rel~=icon][href], video[poster]")) {
for (const attr of ["src", "href", "poster"]) {
const v = el.getAttribute(attr);
if (!v || !isRelativeRef(v) || (attr === "href" && el.tagName !== "LINK")) continue;
jobs.push((async () => { const d = await this.#dataUrl(resolvePath(dir, stripQuery(v))); if (d) el.setAttribute(attr, d); })());
}
}
for (const el of doc.querySelectorAll("img[srcset], source[srcset]")) el.removeAttribute("srcset");
for (const el of doc.querySelectorAll("[style]")) jobs.push((async () => el.setAttribute("style", await this.#inlineCss(el.getAttribute("style"), dir)))());
await Promise.all(jobs);
const shim = doc.createElement("script");
shim.textContent = PREVIEW_SHIM;
(doc.head ?? doc.documentElement).prepend(shim);
return "<!doctype html>\n" + doc.documentElement.outerHTML;
}
async #onFrameMessage(e) {
if (!this.frame || e.source !== this.frame.contentWindow) return;
const d = e.data;
if (d?.__lwa === "open" && typeof d.href === "string") {
if (isRelativeRef(d.href)) this.open(resolvePath(this.frameDir, stripQuery(d.href)));
else if (/^https?:/i.test(d.href)) window.open(d.href, "_blank", "noopener");
} else if (d?.__lwa === "fetch" && typeof d.url === "string") {
const p = resolvePath(this.frameDir, stripQuery(d.url));
const b = await this.#readAsset(p);
const reply = b
? { __lwa: "file", id: d.id, body: await b.arrayBuffer(), type: MIME[extOf(p)] ?? "application/octet-stream" }
: { __lwa: "file", id: d.id, status: 404 };
e.source.postMessage(reply, "*", reply.body ? [reply.body] : []);
}
}
// ---------- misc ----------
#url(blob) { const u = URL.createObjectURL(blob); this.objectUrls.push(u); return u; }
#revokeUrls() { for (const u of this.objectUrls) URL.revokeObjectURL(u); this.objectUrls = []; this.frame = null; }
#download() {
if (!this.current?.blob) return;
const a = h("a", { href: URL.createObjectURL(this.current.blob), download: this.current.path.split("/").pop() });
document.body.append(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
}
/** Called after the agent wrote a file: refresh the listing and the open file if it changed. */
noteChanged(path) {
if (dirname(path) === this.dir) this.refresh();
if (this.current?.path === path) this.open(path, { mode: this.current.mode });
}
}
// Runs inside the sandboxed preview (opaque origin). Relative links and fetch() calls
// are forwarded to the app, which answers from the Linux machine's files.
const PREVIEW_SHIM = `(() => {
const rel = (u) => typeof u === "string" && u.trim() && !/^([a-z][a-z0-9+.-]*:|\\/\\/|#)/i.test(u.trim());
let seq = 0; const pending = new Map();
addEventListener("message", (e) => {
const d = e.data; if (e.source !== parent || !d || d.__lwa !== "file") return;
const p = pending.get(d.id); if (!p) return; pending.delete(d.id);
p(d.body ? new Response(d.body, { status: 200, headers: { "Content-Type": d.type } }) : new Response("Not found", { status: 404 }));
});
const nativeFetch = window.fetch.bind(window);
window.fetch = (input, init) => {
if (rel(input)) return new Promise((resolve) => { const id = ++seq; pending.set(id, resolve); parent.postMessage({ __lwa: "fetch", id, url: input }, "*"); });
return nativeFetch(input, init);
};
document.addEventListener("click", (e) => {
const a = e.target.closest && e.target.closest("a[href]"); if (!a) return;
const href = a.getAttribute("href"); if (!href || href.startsWith("#") || /^javascript:/i.test(href)) return;
e.preventDefault(); parent.postMessage({ __lwa: "open", href }, "*");
}, true);
})();`;