Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(workbench): open extensionless text files in editor + harden search response parsing (#724)

Call Whitec43c4e878256
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index 88711be5a..2fce533b3 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -433,6 +433,9 @@ def metadata(raw_path: str) -> dict[str, Any]:
kind = _kind_from_mode(stat_result.st_mode)
size = stat_result.st_size if stat.S_ISREG(stat_result.st_mode) else None
mime = _guess_mime(path) if kind == "file" else None
+ # Content sniff so the editor can open extensionless / unknown-type text files instead of forcing
+ # a download. Name/extension alone can't tell a text `LICENSE` from a binary blob.
+ text = kind == "file" and _looks_like_text(path)
return {
"ok": True,
"name": path.name,
@@ -441,6 +444,7 @@ def metadata(raw_path: str) -> dict[str, Any]:
"size": size,
"mtime": _mtime_seconds(stat_result),
"mime": mime,
+ "text": text,
}
@@ -983,6 +987,31 @@ def _match_globs(rel_posix: str, patterns: list[str]) -> bool:
return False
+def _looks_like_text(path: Path) -> bool:
+ """Sniff whether a regular file is text (editable) by CONTENT, independent of name/extension.
+
+ Mirrors the search reader's binary check: a NUL byte in the first chunk, or a head that decodes
+ to mostly replacement characters, marks it binary. This lets extensionless text files (LICENSE,
+ README, notes, config) open in the editor while true binaries (images, executables, archives)
+ stay on the download path. Reads at most the sniff window, so it's cheap even for huge files.
+ """
+ try:
+ if path.is_symlink() or not path.is_file():
+ return False
+ with open(path, "rb") as handle:
+ head = handle.read(_BINARY_SNIFF_BYTES)
+ except OSError:
+ return False
+ if not head:
+ return True # an empty file is editable
+ if b"\x00" in head:
+ return False
+ # Decode leniently and require almost no replacement characters: real text has none (or a single
+ # multibyte char split at the sniff boundary), while binary content produces many.
+ decoded = head.decode("utf-8", errors="replace")
+ return decoded.count("�") <= max(1, len(decoded) // 100)
+
+
def _read_file_text(path: Path, *, lossy: bool) -> tuple[str | None, float | None]:
"""Read a regular text file for search/replace; returns (text, mtime) or (None, None) to skip.
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index c3aa315e8..7cd90c517 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -1233,3 +1233,30 @@ def test_startup_reconcile_skips_tmux_when_env_set(monkeypatch):
out_with_skip = api.reconcile_startup_dependencies()
assert out_with_skip["tmux"] == {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_TMUX"}
+
+
+def test_metadata_text_sniff_distinguishes_text_from_binary(tmp_path):
+ # Extensionless text file → text=True, so the editor opens it instead of downloading.
+ license_file = tmp_path / "LICENSE"
+ license_file.write_text("MIT License\n\nPermission is hereby granted, free of charge...\n", encoding="utf-8")
+ assert fs.metadata(str(license_file))["text"] is True
+
+ # An empty file is editable.
+ empty = tmp_path / "notes"
+ empty.write_bytes(b"")
+ assert fs.metadata(str(empty))["text"] is True
+
+ # Binary content (NUL bytes) → not text → stays on the download path.
+ blob = tmp_path / "image" # no extension, but binary
+ blob.write_bytes(b"\x89PNG\r\n\x00\x00\x00\rIHDR" + bytes(64))
+ assert fs.metadata(str(blob))["text"] is False
+
+ # A known-extension text file still reports text.
+ code = tmp_path / "script.py"
+ code.write_text("print('hi')\n", encoding="utf-8")
+ assert fs.metadata(str(code))["text"] is True
+
+ # Directories carry no text flag.
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ assert fs.metadata(str(sub))["text"] is False
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index cdfb62de5..1e88f68fa 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -27,7 +27,7 @@ import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useWindowManager } from '../../context/WindowManagerContext';
-import { isEditableFile, isRenderOnlyImage } from '../../lib/filePreview';
+import { isEditableFile, isEditableMeta, isRenderOnlyImage } from '../../lib/filePreview';
import {
contentUrl,
downloadFile,
@@ -191,29 +191,31 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
setPreview({ path: full, name: e.name });
return;
}
- // Non-editable (symlink / binary / oversized — gated by the listing entry's kind+size) or
- // mobile (the editor window layer is hidden below md): download. This branch MUST run
- // synchronously, before any await, or the click's user activation is lost and Safari/iOS block
- // the popup.
+ // Mobile has no editor window layer (windows are md+), so a non-image file just downloads.
const desktop = window.matchMedia('(min-width: 768px)').matches;
- if (!isEditableFile(e) || !desktop) {
+ if (!desktop) {
downloadFile(full);
return;
}
- // Editable + desktop → editor window. Fetch CURRENT metadata: it gives the save-baseline mtime
- // AND re-validates the open (the file may have grown past the cap or become a symlink since it
- // was listed) — if it's no longer editable, download instead. Safe to await: opening an internal
- // window needs no user activation, and the rare changed-since-listing download is acceptable.
+ // Desktop: fetch CURRENT metadata (which content-sniffs `text`) and decide by CONTENT, not just
+ // the extension — so an extensionless / unknown-type TEXT file (LICENSE, README, a `notes` file)
+ // opens in the editor instead of downloading, while a symlink / oversized / binary file
+ // downloads. Awaiting is safe: opening an internal window needs no user activation, and the
+ // anchor download (the binary branch) isn't a popup, so it survives the await.
try {
const m = await fileMeta(full);
- if (!isEditableFile(m)) {
+ if (isEditableMeta(m)) {
+ wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: m.mtime } });
+ } else {
downloadFile(full);
- return;
}
- wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: m.mtime } });
} catch {
- // Metadata fetch failed — open with the listing mtime as the baseline.
- wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: e.mtime } });
+ // Metadata fetch failed — fall back to the name-only guess so a known text type still opens.
+ if (isEditableFile(e)) {
+ wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: e.mtime } });
+ } else {
+ downloadFile(full);
+ }
}
};
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index 75bb84922..83566df58 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -5,7 +5,7 @@ import clsx from 'clsx';
import { useWindowCloseGuard, useWindowManager } from '../../context/WindowManagerContext';
import { contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
-import { imageKind, isEditableFile, isRenderOnlyImage } from '../../lib/filePreview';
+import { imageKind, isEditableFile, isEditableMeta, isRenderOnlyImage } from '../../lib/filePreview';
import { FileTree } from './FileTree';
import { FilePreview } from './FilePreview';
import { FilePicker, type FilePickerMode } from './FilePicker';
@@ -176,21 +176,23 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
openImage(path, entry.name);
return;
}
- if (!isEditableFile(entry)) {
- downloadFile(path);
- return;
- }
- // Fetch fresh metadata: gives the save-baseline mtime AND re-validates (the file may have
- // grown past the cap or become a symlink since it was listed) → download if no longer editable.
+ // Fetch fresh metadata (also content-sniffs `text`) and decide by CONTENT, not just the
+ // extension — an extensionless / unknown-type TEXT file opens in the editor, while a
+ // symlink / oversized / binary file downloads. Meta also gives the save-baseline mtime.
try {
const m = await fileMeta(path);
- if (!isEditableFile(m)) {
+ if (isEditableMeta(m)) {
+ openFile(path, entry.name, m.mtime);
+ } else {
downloadFile(path);
- return;
}
- openFile(path, entry.name, m.mtime);
} catch {
- openFile(path, entry.name, entry.mtime);
+ // Metadata fetch failed — fall back to the name-only guess so a known text type still opens.
+ if (isEditableFile(entry)) {
+ openFile(path, entry.name, entry.mtime);
+ } else {
+ downloadFile(path);
+ }
}
},
[openFile, openImage],
diff --git a/ui/src/components/workbench/EditorSearchView.tsx b/ui/src/components/workbench/EditorSearchView.tsx
index 98191b066..c05cab969 100644
--- a/ui/src/components/workbench/EditorSearchView.tsx
+++ b/ui/src/components/workbench/EditorSearchView.tsx
@@ -374,9 +374,10 @@ export const EditorSearchView: React.FC<Props> = ({ root, focusNonce, onOpenFold
{notice && <div className="mx-3 mb-1 rounded border border-gold/30 bg-gold/[0.08] px-2 py-1 text-[11px] text-gold">{notice}</div>}
- {/* Results tree */}
+ {/* Results tree. `?? []` is defense-in-depth: parse() now rejects a non-JSON response so
+ `data` is always a valid SearchResponse or null, but never crash the panel on a stray shape. */}
<div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
- {data?.results.map((file) => (
+ {(data?.results ?? []).map((file) => (
<FileGroup
key={file.path}
file={file}
@@ -415,7 +416,7 @@ const FileGroup: React.FC<{
</button>
{!collapsed && (
<div className="flex flex-col gap-px pl-2.5">
- {file.matches.map((m, i) => (
+ {(file.matches ?? []).map((m, i) => (
<MatchRow key={`${m.line}:${m.col}:${i}`} match={m} previewer={previewer} onClick={() => onJump(file.path, m.line, m.col, m.end)} />
))}
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 125603264..a666aa9a3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -729,7 +729,8 @@
"createFolderFailed": "Couldn't create the folder.",
"loadFailed": "Couldn't load this file.",
"saveFailed": "Couldn't save this file.",
- "deleteFailed": "Couldn't delete this item."
+ "deleteFailed": "Couldn't delete this item.",
+ "invalid_response": "The server returned an unexpected response. Try again."
}
},
"terminal": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c58b0413e..8183700d7 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -729,7 +729,8 @@
"createFolderFailed": "无法创建文件夹。",
"loadFailed": "无法加载这个文件。",
"saveFailed": "无法保存这个文件。",
- "deleteFailed": "无法删除这个项目。"
+ "deleteFailed": "无法删除这个项目。",
+ "invalid_response": "服务器返回了异常响应,请重试。"
}
},
"terminal": {
diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.ts
index f9981576e..43f454925 100644
--- a/ui/src/lib/filePreview.ts
+++ b/ui/src/lib/filePreview.ts
@@ -90,6 +90,18 @@ export function isEditableFile(entry: { kind: string; size: number | null; name:
return entry.kind === 'file' && previewKind(entry.name) != null && (entry.size == null || entry.size <= PREVIEW_MAX_BYTES);
}
+// Content-aware editability, decided AFTER fetching `/api/files/meta` (which sniffs file content).
+// A regular file within the size cap opens in the editor when it's a known text/code type by name
+// (`previewKind`) OR the backend sniffed its content as text (`meta.text`) — so extensionless /
+// unknown-type text files (LICENSE, README, a `notes` file) edit instead of downloading, while true
+// binaries (no text kind, sniffed non-text) still download. The name-only `isEditableFile` stays the
+// cheap pre-fetch guess for listings; this is the authoritative open decision.
+export function isEditableMeta(meta: { kind: string; size: number | null; name: string; text?: boolean }): boolean {
+ if (meta.kind !== 'file') return false;
+ if (meta.size != null && meta.size > PREVIEW_MAX_BYTES) return false;
+ return previewKind(meta.name) != null || meta.text === true;
+}
+
// Raster image extensions an <img> tag can render directly. SVG is handled separately because it's
// ALSO editable text (it keeps its 'source' previewKind), so it can be both edited and rendered.
const RASTER_IMAGE_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'bmp', 'ico', 'apng']);
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
index c6ca2dec4..2b9d1c6ba 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -28,6 +28,9 @@ export type FsMeta = {
size: number | null;
mtime: number | null;
mime: string | null;
+ /** Content sniff: true when the file decodes as text, so an extensionless / unknown-type file
+ * still opens in the editor instead of downloading. Absent on older backends → treated as unknown. */
+ text?: boolean;
};
export type Favorite = { key: string; path: string };
@@ -54,11 +57,27 @@ export function fileBrowserErrorMessage(error: unknown, t: (key: string) => stri
}
async function parse<T>(res: Response): Promise<T> {
- const data = await res.json().catch(() => ({}) as Record<string, unknown>);
- if (!res.ok || (data as { ok?: boolean }).ok === false) {
- const err = (data as { error?: { code?: string; message?: string } }).error || {};
+ // Read the body as text first so a non-JSON response (an upstream HTML/error page, a truncated
+ // body, an empty 2xx) is distinguishable from a real payload — rather than silently collapsing to
+ // `{}` that callers would treat as valid data and then crash dereferencing (e.g. `data.results.map`).
+ const raw = await res.text();
+ let data: unknown;
+ if (raw) {
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ data = undefined;
+ }
+ }
+ if (!res.ok || (data as { ok?: boolean } | undefined)?.ok === false) {
+ const err = (data as { error?: { code?: string; message?: string } } | undefined)?.error || {};
throw new FilesApiError(err.code || String(res.status), err.message || 'Request failed');
}
+ if (data === undefined) {
+ // 2xx but the body was empty or not valid JSON (truncated / upstream error page). Surface it as
+ // a failure so the caller shows an error state instead of feeding a malformed object to the UI.
+ throw new FilesApiError('invalid_response', 'The server returned an unexpected response.');
+ }
return data as T;
}