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.

feat(apps): Workbench Apps layer — File Browser + Terminal (#659)

Call Whiteb7281f175129
diff --git a/.github/workflows/build-tmux.yml b/.github/workflows/build-tmux.yml
new file mode 100644
index 000000000..8b80a2d06
--- /dev/null
+++ b/.github/workflows/build-tmux.yml
@@ -0,0 +1,164 @@
+name: Build tmux runtime
+
+on:
+ workflow_dispatch:
+ inputs:
+ tmux_version:
+ description: "tmux version to build"
+ required: true
+ default: "3.6b"
+ release_tag:
+ description: "Optional release tag to upload assets to"
+ required: false
+ default: ""
+
+permissions:
+ contents: write
+
+jobs:
+ build-linux:
+ name: linux-${{ matrix.arch }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x64
+ target: x86_64-linux-musl
+ - arch: arm64
+ target: aarch64-linux-musl
+ steps:
+ - uses: actions/checkout@v5
+ - name: Build static tmux
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p dist
+ cat > "dist/README-linux-${{ matrix.arch }}.txt" <<'EOF'
+ Scaffold placeholder for the Avibe-owned tmux runtime build.
+
+ The final implementation must cross-build tmux with static libevent,
+ ncurses, and utf8proc for this musl target, then package:
+
+ tmux-${TMUX_VERSION}-linux-${ARCH}.tar.gz
+
+ Required properties:
+ - tmux built WITH utf8proc for CJK width correctness
+ - terminfo available to terminal sessions
+ - only the tmux binary and required metadata in the archive
+ EOF
+ tar -czf "dist/tmux-${{ inputs.tmux_version }}-linux-${{ matrix.arch }}.tar.gz" -C dist "README-linux-${{ matrix.arch }}.txt"
+
+ - name: Generate checksum
+ shell: bash
+ run: |
+ (cd dist && shasum -a 256 "tmux-${{ inputs.tmux_version }}-linux-${{ matrix.arch }}.tar.gz" > "tmux-${{ inputs.tmux_version }}-linux-${{ matrix.arch }}.sha256")
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: tmux-linux-${{ matrix.arch }}
+ path: dist/tmux-${{ inputs.tmux_version }}-linux-${{ matrix.arch }}.*
+
+ build-macos:
+ name: macos-${{ matrix.arch }}
+ runs-on: ${{ matrix.runner }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x64
+ runner: macos-13
+ - arch: arm64
+ runner: macos-15
+ steps:
+ - uses: actions/checkout@v5
+ - name: Build relocatable tmux
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p dist
+ cat > "dist/README-macos-${{ matrix.arch }}.txt" <<'EOF'
+ Scaffold placeholder for the Avibe-owned tmux runtime build.
+
+ The final implementation must build tmux with libevent, ncurses, and
+ utf8proc vendored or otherwise relocatable, leaving only system macOS
+ libraries dynamic. The dependency manager ad-hoc signs downloaded
+ binaries before execution.
+ EOF
+ tar -czf "dist/tmux-${{ inputs.tmux_version }}-darwin-${{ matrix.arch }}.tar.gz" -C dist "README-macos-${{ matrix.arch }}.txt"
+
+ - name: Generate checksum
+ shell: bash
+ run: |
+ (cd dist && shasum -a 256 "tmux-${{ inputs.tmux_version }}-darwin-${{ matrix.arch }}.tar.gz" > "tmux-${{ inputs.tmux_version }}-darwin-${{ matrix.arch }}.sha256")
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: tmux-darwin-${{ matrix.arch }}
+ path: dist/tmux-${{ inputs.tmux_version }}-darwin-${{ matrix.arch }}.*
+
+ manifest:
+ name: manifest
+ needs: [build-linux, build-macos]
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/download-artifact@v6
+ with:
+ pattern: tmux-*
+ path: dist
+ merge-multiple: true
+
+ - name: Generate manifest scaffold
+ shell: bash
+ run: |
+ set -euo pipefail
+ python - <<'PY'
+ import hashlib
+ import json
+ import os
+ from pathlib import Path
+
+ version = os.environ["TMUX_VERSION"]
+ archives = {}
+ for platform in ("darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"):
+ path = next(Path("dist").glob(f"tmux-{version}-{platform}.tar.gz"), None)
+ if path is None:
+ raise SystemExit(f"missing archive for {platform}")
+ archives[platform] = {
+ "name": path.name,
+ "url": f"https://github.com/avibe-bot/avibe/releases/download/${{ inputs.release_tag || '<tag>' }}/{path.name}",
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
+ "size": path.stat().st_size,
+ "bin_path": "tmux",
+ }
+ manifest = {
+ "schema_version": 1,
+ "tmux_version": version,
+ "source": "avibe-build-tmux",
+ "source_url": "https://github.com/avibe-bot/avibe/actions/workflows/build-tmux.yml",
+ "requires_utf8proc": True,
+ "terminfo": "bundled-or-system",
+ "archives": archives,
+ }
+ Path("dist/tmux-runtime-manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
+ PY
+ env:
+ TMUX_VERSION: ${{ inputs.tmux_version }}
+
+ - uses: actions/upload-artifact@v6
+ with:
+ name: tmux-runtime-manifest
+ path: dist/tmux-runtime-manifest.json
+
+ # The build jobs above currently package scaffold placeholders (a README, not a real
+ # tmux binary), so the archives would install as a broken/missing binary. Refuse to
+ # publish them as release assets and fail loudly instead of silently shipping. Once
+ # the cross-build produces a real relocatable tmux, replace this guard with the
+ # softprops/action-gh-release@v2 upload of dist/tmux-*.tar.gz, *.sha256, and the
+ # manifest.
+ - name: Refuse to publish placeholder release assets
+ if: inputs.release_tag != ''
+ shell: bash
+ run: |
+ echo "::error::build-tmux still packages scaffold placeholders; refusing to publish release assets for tag '${{ inputs.release_tag }}'. Implement the real tmux cross-build before enabling the release upload." >&2
+ exit 1
diff --git a/Dockerfile b/Dockerfile
index 659dd5a2e..100544632 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,6 +17,7 @@ FROM python:3.12-slim AS base
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
+ tmux \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
@@ -54,6 +55,7 @@ FROM base AS integration
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
+ tmux \
&& rm -rf /var/lib/apt/lists/*
# Reuse the Node runtime from the UI builder stage.
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
new file mode 100644
index 000000000..bb7b5727e
--- /dev/null
+++ b/core/file_browser_service.py
@@ -0,0 +1,871 @@
+from __future__ import annotations
+
+import ctypes
+import errno
+import logging
+import mimetypes
+import os
+import shutil
+import stat
+import sys
+import tempfile
+import threading
+import uuid
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable
+
+logger = logging.getLogger(__name__)
+
+MAX_FILE_BYTES = 25 * 1024 * 1024
+MAX_LIST_ENTRIES = 5000
+
+INLINE_SAFE_CONTENT_TYPES = {
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ "image/avif",
+ "image/bmp",
+ "image/x-icon",
+ "image/heic",
+ "image/heif",
+ "application/pdf",
+ "text/plain",
+ "text/markdown",
+ "text/csv",
+ "application/json",
+ "audio/mpeg",
+ "audio/mp4",
+ "audio/aac",
+ "audio/ogg",
+ "audio/wav",
+ "audio/webm",
+ "audio/flac",
+ "audio/x-m4a",
+ "video/mp4",
+ "video/webm",
+ "video/ogg",
+ "video/quicktime",
+}
+
+_AT_FDCWD = -100
+_RENAME_NOREPLACE = 1
+_RENAME_NOREPLACE_FALLBACK_WARNED = False
+_WRITE_LOCKS_MUTEX = threading.Lock()
+_WRITE_LOCKS: dict[str, threading.Lock] = {}
+_WRITE_TEMP_PREFIX = ".avibe-write-"
+
+
+class FileBrowserError(Exception):
+ def __init__(self, code: str, message: str, status_code: int = 400) -> None:
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.status_code = status_code
+
+
+class NotFoundError(FileBrowserError):
+ def __init__(self, message: str = "Path not found") -> None:
+ super().__init__("not_found", message, 404)
+
+
+class ConflictError(FileBrowserError):
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(code, message, 409)
+
+
+@dataclass(frozen=True)
+class FileContent:
+ path: Path
+ mime: str
+ disposition: str
+ data: bytes
+
+
+def resolve_safe_path(raw: str) -> Path:
+ """Expand and canonicalize one user-supplied absolute filesystem path."""
+ expanded = _expanded_absolute_path(raw)
+ try:
+ return expanded.resolve(strict=False)
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("invalid_path", str(exc), 400) from exc
+
+
+def _expanded_absolute_path(raw: str) -> Path:
+ if not isinstance(raw, str) or not raw.strip():
+ raise FileBrowserError("invalid_path", "Path is required", 400)
+ expanded = Path(os.path.expanduser(raw))
+ if not expanded.is_absolute():
+ raise FileBrowserError("invalid_path", "Path must be absolute", 400)
+ return expanded
+
+
+def _resolve_existing_path(raw: str) -> Path:
+ resolved = resolve_safe_path(raw)
+ try:
+ return resolved.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise NotFoundError() from exc
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("invalid_path", str(exc), 400) from exc
+
+
+def _resolve_entry_path(raw: str) -> Path:
+ expanded = _expanded_absolute_path(raw)
+ if expanded.name in {"", ".", ".."} or _raw_final_component(raw) in {".", ".."}:
+ raise FileBrowserError("invalid_path", "Path must include a valid entry name", 400)
+ try:
+ parent = expanded.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise NotFoundError("Parent directory not found") from exc
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("invalid_path", str(exc), 400) from exc
+ return parent / expanded.name
+
+
+def _raw_final_component(raw: str) -> str:
+ expanded_raw = os.path.expanduser(raw)
+ separators = os.sep
+ if os.altsep:
+ separators += os.altsep
+ stripped = expanded_raw.rstrip(separators)
+ if not stripped:
+ return ""
+ return os.path.basename(stripped)
+
+
+def _resolve_existing_entry_path(raw: str) -> Path:
+ path = _resolve_entry_path(raw)
+ _stat_existing(path, follow_symlinks=False)
+ return path
+
+
+def _exists_no_follow(path: Path) -> bool:
+ try:
+ path.lstat()
+ return True
+ except FileNotFoundError:
+ return False
+
+
+def _same_entry_no_follow(left: Path, right: Path) -> bool:
+ try:
+ left_stat = left.lstat()
+ right_stat = right.lstat()
+ except FileNotFoundError:
+ return False
+ return (left_stat.st_dev, left_stat.st_ino) == (right_stat.st_dev, right_stat.st_ino)
+
+
+def _same_directory_entry(left: Path, right: Path) -> bool:
+ try:
+ left_parent = left.parent.resolve(strict=True)
+ right_parent = right.parent.resolve(strict=True)
+ left_stat = left.lstat()
+ except (OSError, RuntimeError):
+ return False
+ if left_parent != right_parent:
+ return False
+ if left.name == right.name:
+ return True
+ same_inode_entries = 0
+ for entry in left_parent.iterdir():
+ try:
+ entry_stat = entry.lstat()
+ except OSError:
+ continue
+ if (entry_stat.st_dev, entry_stat.st_ino) == (left_stat.st_dev, left_stat.st_ino):
+ same_inode_entries += 1
+ if same_inode_entries > 1:
+ return False
+ return same_inode_entries == 1
+
+
+def _is_dir_no_follow(path: Path) -> bool:
+ try:
+ return stat.S_ISDIR(path.lstat().st_mode)
+ except FileNotFoundError:
+ return False
+
+
+def _entry_contains_no_follow(parent: Path, child: Path) -> bool:
+ parent_resolved = parent.resolve(strict=True)
+ child_resolved = child.parent.resolve(strict=True) / child.name
+ return child_resolved == parent_resolved or parent_resolved in child_resolved.parents
+
+
+def _rename_no_replace(source: Path, target: Path) -> None:
+ """Rename ``source`` -> ``target`` without ever replacing an existing target.
+
+ ``os.rename()`` REPLACES an existing destination on POSIX, so a separate existence
+ check before it is a TOCTOU race — a target created in between is silently clobbered.
+ ``os.link()`` is atomic and fails with ``FileExistsError`` if the target exists, so use
+ link()+unlink() for the common same-directory, regular-file case. Symlinks and
+ directories cannot be hard-linked; for those use renameat2(RENAME_NOREPLACE) where
+ available, with a documented platform fallback.
+ """
+ try:
+ os.link(source, target, follow_symlinks=False)
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except OSError:
+ _os_rename_noreplace(source, target)
+ return
+ _unlink_source_after_hard_link(source, target)
+
+
+def _os_rename_noreplace(source: Path, target: Path) -> None:
+ """Rename ``source`` to ``target`` without replacing an existing destination."""
+ try:
+ _glibc_renameat2_noreplace(source, target)
+ return
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except OSError as exc:
+ if exc.errno == errno.EXDEV:
+ raise
+ if exc.errno not in {errno.ENOSYS, errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP}:
+ raise
+ except AttributeError:
+ pass
+
+ try:
+ os.link(source, target, follow_symlinks=False)
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except OSError as exc:
+ if exc.errno == errno.EXDEV:
+ raise
+ else:
+ _unlink_source_after_hard_link(source, target)
+ return
+
+ _warn_rename_noreplace_fallback()
+ if _exists_no_follow(target):
+ raise ConflictError("exists", "Destination already exists")
+ # Non-Linux or old libc fallback: POSIX rename can still replace a target
+ # that appears after this check, notably an empty directory during directory
+ # rename. Linux deployments should take the atomic renameat2 path above.
+ source.rename(target)
+
+
+def _unlink_source_after_hard_link(source: Path, target: Path) -> None:
+ try:
+ os.unlink(source)
+ except OSError:
+ _remove_created_hard_link(target, source)
+ raise
+
+
+def _remove_created_hard_link(target: Path, source: Path) -> None:
+ try:
+ source_stat = source.lstat()
+ target_stat = target.lstat()
+ if (source_stat.st_dev, source_stat.st_ino) == (target_stat.st_dev, target_stat.st_ino):
+ os.unlink(target)
+ except OSError:
+ logger.debug("Failed to remove rollback hard link after no-replace rename failure", exc_info=True)
+
+
+def _glibc_renameat2_noreplace(source: Path, target: Path) -> None:
+ if sys.platform != "linux":
+ raise AttributeError("renameat2 is only available on Linux")
+ libc = ctypes.CDLL(None, use_errno=True)
+ renameat2 = libc.renameat2
+ renameat2.argtypes = [
+ ctypes.c_int,
+ ctypes.c_char_p,
+ ctypes.c_int,
+ ctypes.c_char_p,
+ ctypes.c_uint,
+ ]
+ renameat2.restype = ctypes.c_int
+ result = renameat2(
+ _AT_FDCWD,
+ os.fsencode(source),
+ _AT_FDCWD,
+ os.fsencode(target),
+ _RENAME_NOREPLACE,
+ )
+ if result != 0:
+ err = ctypes.get_errno()
+ if err == errno.EEXIST:
+ raise FileExistsError(err, os.strerror(err), str(target))
+ raise OSError(err, os.strerror(err), str(target))
+
+
+def _warn_rename_noreplace_fallback() -> None:
+ global _RENAME_NOREPLACE_FALLBACK_WARNED
+ if _RENAME_NOREPLACE_FALLBACK_WARNED:
+ return
+ _RENAME_NOREPLACE_FALLBACK_WARNED = True
+ logger.warning(
+ "Atomic no-replace rename is unavailable on this platform; falling back to "
+ "check-then-rename with a residual empty-directory race."
+ )
+
+
+def _stat_existing(path: Path, *, follow_symlinks: bool = True) -> os.stat_result:
+ try:
+ return path.stat() if follow_symlinks else path.lstat()
+ except FileNotFoundError as exc:
+ raise NotFoundError() from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+
+def _require_stable_resolved_path(path: Path) -> None:
+ try:
+ current = path.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise NotFoundError() from exc
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("invalid_path", str(exc), 400) from exc
+ if current != path:
+ raise NotFoundError()
+
+
+def _require_regular_file(raw: str) -> Path:
+ path = _resolve_existing_path(raw)
+ _require_stable_resolved_path(path)
+ if not path.is_file():
+ raise FileBrowserError("not_file", "Path is not a regular file", 400)
+ return path
+
+
+def _require_directory(raw: str) -> Path:
+ path = _resolve_existing_path(raw)
+ if not path.is_dir():
+ raise FileBrowserError("not_dir", "Path is not a directory", 400)
+ return path
+
+
+def _kind_from_mode(mode: int) -> str:
+ if stat.S_ISLNK(mode):
+ return "symlink"
+ if stat.S_ISDIR(mode):
+ return "dir"
+ return "file"
+
+
+def _mtime_seconds(stat_result: os.stat_result) -> float:
+ return stat_result.st_mtime_ns / 1_000_000_000
+
+
+def _extension(path: Path) -> str:
+ suffix = path.suffix
+ return suffix[1:].lower() if suffix.startswith(".") else suffix.lower()
+
+
+def _guess_mime(path: Path) -> str:
+ return mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+
+
+def _entry_payload(entry: os.DirEntry[str]) -> dict[str, Any] | None:
+ try:
+ stat_result = entry.stat(follow_symlinks=False)
+ except OSError:
+ stat_result = None
+ kind = "file"
+ size = None
+ mtime = None
+ if stat_result is not None:
+ kind = _kind_from_mode(stat_result.st_mode)
+ if stat.S_ISREG(stat_result.st_mode):
+ size = stat_result.st_size
+ mtime = _mtime_seconds(stat_result)
+ return {
+ "name": entry.name,
+ "kind": kind,
+ "size": size,
+ "mtime": mtime,
+ "ext": _extension(Path(entry.name)) if kind != "dir" else "",
+ }
+
+
+def list_directory(raw_path: str, *, show_hidden: bool = False) -> dict[str, Any]:
+ target = _require_directory(raw_path)
+ entries: list[dict[str, Any]] = []
+ scanned_entries = 0
+ truncated = False
+ try:
+ with os.scandir(target) as iterator:
+ for entry in iterator:
+ scanned_entries += 1
+ if not show_hidden and entry.name.startswith("."):
+ if scanned_entries > MAX_LIST_ENTRIES:
+ truncated = True
+ break
+ continue
+ payload = _entry_payload(entry)
+ if payload is not None:
+ entries.append(payload)
+ if len(entries) > MAX_LIST_ENTRIES:
+ entries.pop()
+ truncated = True
+ break
+ if scanned_entries > MAX_LIST_ENTRIES:
+ truncated = True
+ break
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+ entries.sort(key=lambda item: (0 if item["kind"] == "dir" else 1, str(item["name"]).lower(), str(item["name"])))
+ parent = None if target.parent == target else str(target.parent)
+ payload = {"ok": True, "path": str(target), "parent": parent, "entries": entries, "truncated": truncated}
+ if truncated:
+ payload["limit"] = MAX_LIST_ENTRIES
+ return payload
+
+
+def metadata(raw_path: str) -> dict[str, Any]:
+ path = _resolve_existing_entry_path(raw_path)
+ stat_result = _stat_existing(path, follow_symlinks=False)
+ 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
+ return {
+ "ok": True,
+ "name": path.name,
+ "ext": _extension(path),
+ "kind": kind,
+ "size": size,
+ "mtime": _mtime_seconds(stat_result),
+ "mime": mime,
+ }
+
+
+def file_content(raw_path: str, *, download: bool = False) -> FileContent:
+ path = _require_regular_file(raw_path)
+ stat_result = _stat_existing(path)
+ if stat_result.st_size > MAX_FILE_BYTES:
+ raise FileBrowserError("too_large", "File is too large", 413)
+ mime = _guess_mime(path)
+ base_mime = mime.split(";", 1)[0].strip().lower()
+ disposition = "attachment" if download or base_mime not in INLINE_SAFE_CONTENT_TYPES else "inline"
+ try:
+ flags = os.O_RDONLY
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = os.open(path, flags)
+ try:
+ stat_result = os.fstat(fd)
+ if not stat.S_ISREG(stat_result.st_mode):
+ raise FileBrowserError("not_file", "Path is not a regular file", 400)
+ if stat_result.st_size > MAX_FILE_BYTES:
+ raise FileBrowserError("too_large", "File is too large", 413)
+ with os.fdopen(fd, "rb", closefd=False) as handle:
+ data = handle.read(MAX_FILE_BYTES + 1)
+ finally:
+ os.close(fd)
+ except FileNotFoundError as exc:
+ raise NotFoundError() from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ if len(data) > MAX_FILE_BYTES:
+ raise FileBrowserError("too_large", "File is too large", 413)
+ return FileContent(path=path, mime=mime, disposition=disposition, data=data)
+
+
+def _audit_mutation(op: str, path: Path, **extra: Any) -> None:
+ if extra:
+ logger.info("file_browser.%s path=%s extra=%s", op, path, extra)
+ else:
+ logger.info("file_browser.%s path=%s", op, path)
+
+
+def _run_mutation(op: str, path: Path, func, **audit_extra: Any):
+ _audit_mutation(op, path, **audit_extra)
+ return func()
+
+
+def _fsync_dir(path: Path) -> None:
+ # Persist the directory entry change (e.g. an os.replace rename) so the new
+ # name survives a crash, not just the file's contents. Best-effort: some
+ # platforms (Windows) lack O_DIRECTORY or can't fsync a directory.
+ flags = getattr(os, "O_DIRECTORY", None)
+ if flags is None:
+ return
+ try:
+ dir_fd = os.open(path, flags)
+ except OSError:
+ return
+ try:
+ os.fsync(dir_fd)
+ except OSError:
+ pass
+ finally:
+ os.close(dir_fd)
+
+
+def _write_lock_for(path: Path) -> threading.Lock:
+ # Retained for the process lifetime; this keeps compare-and-replace cheap and
+ # per-path without a cleanup protocol that could race active worker threads.
+ key = str(path)
+ with _WRITE_LOCKS_MUTEX:
+ lock = _WRITE_LOCKS.get(key)
+ if lock is None:
+ lock = threading.Lock()
+ _WRITE_LOCKS[key] = lock
+ return lock
+
+
+def write_file(raw_path: str, content: str, *, expected_mtime: float | None = None) -> dict[str, Any]:
+ if not isinstance(content, str):
+ raise FileBrowserError("invalid_content", "Content must be UTF-8 text", 400)
+ data = content.encode("utf-8")
+ if len(data) > MAX_FILE_BYTES:
+ raise FileBrowserError("too_large", "Content is too large", 413)
+
+ # Operate on the entry itself (parent resolved, final component NOT
+ # symlink-followed) so writing matches the no-follow semantics of
+ # list/meta/delete and never silently clobbers a symlink's target.
+ target = _resolve_entry_path(raw_path)
+ parent = target.parent
+ if not parent.is_dir():
+ raise FileBrowserError("not_dir", "Parent is not a directory", 400)
+ if target.is_symlink():
+ raise FileBrowserError("is_symlink", "Refusing to write through a symlink", 400)
+ if target.exists() and not target.is_file():
+ raise FileBrowserError("not_file", "Path is not a regular file", 400)
+ if expected_mtime is not None:
+ try:
+ current_mtime = _mtime_seconds(target.stat())
+ except FileNotFoundError as exc:
+ raise ConflictError("conflict", "File was removed before save") from exc
+ if abs(current_mtime - float(expected_mtime)) > 1e-6:
+ raise ConflictError("conflict", "File changed on disk")
+
+ def _write() -> dict[str, Any]:
+ with _write_lock_for(target):
+ # Re-check at write time to defeat a file→symlink swap between the
+ # checks above and the replace below.
+ if target.is_symlink():
+ raise FileBrowserError("is_symlink", "Refusing to write through a symlink", 400)
+ if target.exists() and not target.is_file():
+ raise FileBrowserError("not_file", "Path is not a regular file", 400)
+ fd = -1
+ temp_name = ""
+ try:
+ mode = stat.S_IMODE(target.stat().st_mode) if target.exists() else None
+ fd, temp_name = tempfile.mkstemp(prefix=_WRITE_TEMP_PREFIX, suffix=".tmp", dir=parent)
+ if mode is not None:
+ os.fchmod(fd, mode)
+ with os.fdopen(fd, "wb") as handle:
+ fd = -1
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ if expected_mtime is not None:
+ try:
+ disk_mtime = _mtime_seconds(target.stat())
+ except FileNotFoundError as exc:
+ raise ConflictError("conflict", "File was removed before save") from exc
+ if abs(disk_mtime - float(expected_mtime)) > 1e-6:
+ raise ConflictError("conflict", "File changed on disk")
+ os.replace(temp_name, target)
+ temp_name = ""
+ _fsync_dir(parent)
+ stat_result = target.stat()
+ return {"ok": True, "mtime": _mtime_seconds(stat_result)}
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ finally:
+ if fd >= 0:
+ os.close(fd)
+ if temp_name:
+ try:
+ os.unlink(temp_name)
+ except FileNotFoundError:
+ pass
+
+ return _run_mutation("write", target, _write)
+
+
+def make_directory(raw_path: str) -> dict[str, Any]:
+ # Resolve the entry without following a final symlink, so mkdir on a name that
+ # is a (possibly dangling) symlink reports "exists" instead of creating the
+ # symlink's target — matching the no-follow semantics of the other mutations.
+ target = _resolve_entry_path(raw_path)
+ parent = target.parent
+ if not parent.is_dir():
+ raise FileBrowserError("not_dir", "Parent is not a directory", 400)
+ if _exists_no_follow(target):
+ raise ConflictError("exists", "Path already exists")
+
+ def _mkdir() -> dict[str, Any]:
+ try:
+ target.mkdir()
+ return {"ok": True}
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Path already exists") from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+ return _run_mutation("mkdir", target, _mkdir)
+
+
+def _validate_new_name(new_name: str) -> str:
+ if not isinstance(new_name, str) or not new_name.strip():
+ raise FileBrowserError("invalid_name", "New name is required", 400)
+ name = new_name.strip()
+ if name in {".", ".."} or "/" in name or "\\" in name or Path(name).name != name:
+ raise FileBrowserError("invalid_name", "New name must not contain path separators", 400)
+ return name
+
+
+def rename_path(raw_path: str, new_name: str) -> dict[str, Any]:
+ source = _resolve_existing_entry_path(raw_path)
+ name = _validate_new_name(new_name)
+ target = source.with_name(name)
+ same_entry = _same_entry_no_follow(source, target)
+ same_directory_entry = same_entry and _same_directory_entry(source, target)
+ if same_directory_entry and name == source.name:
+ return {"ok": True, "path": str(source)}
+ if _exists_no_follow(target) and not same_directory_entry:
+ raise ConflictError("exists", "Destination already exists")
+
+ def _rename() -> dict[str, Any]:
+ try:
+ if same_directory_entry:
+ source.rename(target)
+ return {"ok": True, "path": str(target)}
+ # Atomic no-replace rename: never clobber a destination that appears between the
+ # precheck above and the rename itself.
+ _rename_no_replace(source, target)
+ return {"ok": True, "path": str(target)}
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Destination already exists") from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+ return _run_mutation("rename", source, _rename)
+
+
+def move_path(raw_src: str, raw_dst: str, *, overwrite: bool = False) -> dict[str, Any]:
+ source = _resolve_existing_entry_path(raw_src)
+ target = _resolve_entry_path(raw_dst)
+ if source == target:
+ # Moving onto itself is a no-op; never unlink-then-move (it would delete it). Kept
+ # before the subtree guard below so an exact self-move stays idempotent rather than
+ # erroring as "into itself" — the guard is only meant to reject moves into a descendant.
+ return {"ok": True}
+ if _is_dir_no_follow(source) and _entry_contains_no_follow(source, target):
+ raise FileBrowserError("invalid_path", "Cannot move a folder into itself", 400)
+ if source.is_symlink():
+ try:
+ same_target = source.resolve() == target.resolve()
+ except (OSError, RuntimeError):
+ same_target = False
+ if same_target:
+ raise ConflictError("invalid_move", "Cannot move a symlink onto the file it points to")
+ parent = target.parent
+ if not parent.is_dir():
+ raise FileBrowserError("not_dir", "Destination parent is not a directory", 400)
+ if _exists_no_follow(target) and not overwrite:
+ raise ConflictError("exists", "Destination already exists")
+ if _is_dir_no_follow(target) and not _is_dir_no_follow(source):
+ # No-follow: only a real directory may overwrite a directory. is_file() follows
+ # symlinks and is False for a symlink/broken link, which would let a symlink replace
+ # (and thus erase) a directory under overwrite=True.
+ raise ConflictError("exists", "Cannot overwrite a directory with a non-directory")
+
+ def _move() -> dict[str, Any]:
+ backup: Path | None = None
+ source_was_dir = _is_dir_no_follow(source)
+ target_was_placed = False
+
+ def mark_target_placed() -> None:
+ nonlocal target_was_placed
+ target_was_placed = True
+
+ try:
+ if not overwrite:
+ _move_to_absent_target(source, target)
+ return {"ok": True}
+ # Re-check at move time for the overwrite path so file-vs-directory
+ # conflicts are caught before the destination is moved aside.
+ if _exists_no_follow(target):
+ if _is_dir_no_follow(target) and not _is_dir_no_follow(source):
+ raise ConflictError("exists", "Cannot overwrite a directory with a non-directory")
+ backup = _reserve_backup_path(target)
+ target.rename(backup)
+ try:
+ _move_to_absent_target(source, target, on_target_placed=mark_target_placed)
+ except Exception:
+ if backup is not None:
+ _handle_failed_overwrite_move(
+ target,
+ backup,
+ source_was_dir=source_was_dir,
+ target_was_placed=target_was_placed,
+ )
+ raise
+ if backup is not None:
+ _remove_backup_path(backup)
+ return {"ok": True}
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+ return _run_mutation("move", source, _move, dst=str(target), overwrite=overwrite)
+
+
+def _move_to_absent_target(
+ source: Path,
+ target: Path,
+ *,
+ on_target_placed: Callable[[], None] | None = None,
+) -> None:
+ try:
+ _os_rename_noreplace(source, target)
+ except OSError as exc:
+ if exc.errno != errno.EXDEV:
+ raise
+ _copy_cross_fs_move_to_absent_target(source, target, on_target_placed=on_target_placed)
+ else:
+ if on_target_placed is not None:
+ on_target_placed()
+
+
+def _copy_cross_fs_move_to_absent_target(
+ source: Path,
+ target: Path,
+ *,
+ on_target_placed: Callable[[], None] | None = None,
+) -> None:
+ temp_target: Path | None = _reserve_backup_path(target)
+ try:
+ if _is_dir_no_follow(source):
+ shutil.copytree(source, temp_target, symlinks=True)
+ else:
+ shutil.copy2(source, temp_target, follow_symlinks=False)
+ _os_rename_noreplace(temp_target, target)
+ temp_target = None
+ created_target_stat = target.lstat()
+ if on_target_placed is not None:
+ on_target_placed()
+ try:
+ _remove_backup_path(source)
+ except OSError:
+ if _can_delete_placed_target_after_source_removal_failure(source):
+ _remove_created_cross_fs_move_target(target, source, created_target_stat)
+ raise
+ except Exception:
+ if temp_target is not None:
+ _remove_path_if_exists(temp_target)
+ raise
+
+
+def _reserve_backup_path(target: Path) -> Path:
+ for _ in range(100):
+ candidate = target.with_name(f".avibe-overwrite-{uuid.uuid4().hex}")
+ if not _exists_no_follow(candidate):
+ return candidate
+ raise FileBrowserError("fs_error", "Could not reserve overwrite backup path", 400)
+
+
+def _restore_move_backup(backup: Path, target: Path, *, replace_target: bool) -> None:
+ if not _exists_no_follow(backup):
+ return
+ if replace_target and _exists_no_follow(target):
+ _remove_backup_path(target)
+ try:
+ _os_rename_noreplace(backup, target)
+ except ConflictError:
+ if not replace_target:
+ logger.debug("Leaving overwrite backup in place because target is occupied during restore")
+ return
+ raise
+
+
+def _handle_failed_overwrite_move(
+ target: Path,
+ backup: Path,
+ *,
+ source_was_dir: bool,
+ target_was_placed: bool,
+) -> None:
+ if source_was_dir and target_was_placed and _exists_no_follow(target):
+ _remove_path_if_exists_best_effort(backup)
+ return
+ _restore_move_backup(backup, target, replace_target=target_was_placed)
+
+
+def _can_delete_placed_target_after_source_removal_failure(source: Path) -> bool:
+ # Non-directory source cleanup uses unlink, which is atomic: if it failed and
+ # the source still exists, the source copy is intact. Directory cleanup uses
+ # rmtree, which can partially delete children before raising.
+ return _exists_no_follow(source) and not _is_dir_no_follow(source)
+
+
+def _remove_created_cross_fs_move_target(target: Path, source: Path, created_target_stat: os.stat_result) -> None:
+ try:
+ target_stat = target.lstat()
+ if (
+ _exists_no_follow(source)
+ and (target_stat.st_dev, target_stat.st_ino)
+ == (created_target_stat.st_dev, created_target_stat.st_ino)
+ ):
+ _remove_backup_path(target)
+ except OSError:
+ logger.debug("Failed to remove rollback target after cross-filesystem move failure", exc_info=True)
+
+
+def _remove_backup_path(path: Path) -> None:
+ if _is_dir_no_follow(path):
+ shutil.rmtree(path)
+ else:
+ path.unlink()
+
+
+def _remove_path_if_exists(path: Path) -> None:
+ try:
+ _remove_backup_path(path)
+ except FileNotFoundError:
+ pass
+
+
+def _remove_path_if_exists_best_effort(path: Path) -> None:
+ try:
+ _remove_path_if_exists(path)
+ except OSError:
+ logger.debug("Failed to remove move backup after preserving placed target", exc_info=True)
+
+
+def delete_path(raw_path: str, *, recursive: bool = False) -> dict[str, Any]:
+ target = _resolve_existing_entry_path(raw_path)
+ if target == target.parent:
+ # A filesystem root (/, or a drive root on Windows). Never deletable — a recursive
+ # delete here would try to wipe everything the process can reach.
+ raise FileBrowserError("invalid_path", "Refusing to delete a filesystem root", 400)
+ target_stat = _stat_existing(target, follow_symlinks=False)
+
+ def _delete() -> dict[str, Any]:
+ try:
+ if stat.S_ISDIR(target_stat.st_mode):
+ if recursive:
+ shutil.rmtree(target)
+ else:
+ target.rmdir()
+ else:
+ target.unlink()
+ return {"ok": True}
+ except OSError as exc:
+ if stat.S_ISDIR(target_stat.st_mode) and not recursive and exc.errno in {errno.ENOTEMPTY, errno.EEXIST}:
+ raise ConflictError("not_empty", "Directory is not empty") from exc
+ if isinstance(exc, FileNotFoundError):
+ raise NotFoundError() from exc
+ if isinstance(exc, PermissionError):
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+
+ return _run_mutation("delete", target, _delete, recursive=recursive)
diff --git a/core/terminal_service.py b/core/terminal_service.py
new file mode 100644
index 000000000..b79a5f4de
--- /dev/null
+++ b/core/terminal_service.py
@@ -0,0 +1,665 @@
+from __future__ import annotations
+
+import asyncio
+import errno
+import hashlib
+import json
+import logging
+import os
+import re
+import signal
+import struct
+import sys
+import time
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+from typing import Any
+
+from fastapi import WebSocket, WebSocketDisconnect
+
+from config import paths
+
+try: # POSIX-only; the PTY + tmux terminal is not supported on native Windows.
+ import fcntl
+ import termios
+except ImportError: # pragma: no cover - Windows
+ fcntl = None # type: ignore[assignment]
+ termios = None # type: ignore[assignment]
+
+try:
+ from core.tmux_runtime import resolve_tmux_binary
+except Exception: # pragma: no cover - integration branch may not be present.
+
+ def resolve_tmux_binary() -> str | None:
+ return None
+
+
+logger = logging.getLogger(__name__)
+
+# The terminal needs a PTY (os.openpty) + ioctl winsize; all POSIX-only. On native
+# Windows the websocket endpoint refuses instead of crashing at import/spawn time.
+TERMINAL_SUPPORTED = hasattr(os, "openpty") and fcntl is not None and termios is not None
+
+_SAFE_SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]+")
+
+
+@dataclass
+class TerminalConnection:
+ session_id: str
+ process: asyncio.subprocess.Process
+ master_fd: int
+ persistent: bool
+ attached_at: float
+ last_seen: float
+
+ def touch(self) -> None:
+ self.last_seen = time.monotonic()
+
+
+class _Phase(Enum):
+ OPENING = "opening" # open() in progress; no usable connection yet
+ ATTACHED = "attached" # a live websocket client is connected
+ CLOSING = "closing" # tearing the client down; still counts until reconciled
+ DETACHED = "detached" # tmux session alive but no client (reattachable)
+
+
+@dataclass
+class _Session:
+ """One terminal session id, always in exactly one phase.
+
+ The whole service tracks sessions in a single dict keyed by id, so an id can never be
+ double-counted or land in two collections out of sync — the root cause of an entire
+ class of bookkeeping races. Capacity is just len(self._sessions); a reconnect reuses an
+ existing entry, only a brand-new id is checked against the cap.
+ """
+
+ session_id: str
+ phase: _Phase
+ persistent: bool = False
+ connection: TerminalConnection | None = None # set while ATTACHED
+ detached_at: float | None = None # set while DETACHED
+
+
+class TerminalService:
+ def __init__(self, *, idle_timeout_seconds: int = 3600, max_sessions: int = 8) -> None:
+ self.idle_timeout_seconds = max(60, int(idle_timeout_seconds))
+ self.max_sessions = max(1, int(max_sessions))
+ # One entry per session id, each in exactly one phase. Capacity is simply
+ # len(self._sessions) — no cross-collection arithmetic to keep in sync.
+ self._sessions: dict[str, _Session] = {}
+ self._lock = asyncio.Lock()
+ self._reaper_task: asyncio.Task | None = None
+ self._closed = False
+
+ def start_reaper(self) -> None:
+ if self._closed:
+ return
+ task = self._reaper_task
+ if task is None or task.done():
+ self._reaper_task = asyncio.create_task(self._reaper_loop(), name="terminal-session-reaper")
+
+ async def shutdown(self) -> None:
+ self._closed = True
+ task, self._reaper_task = self._reaper_task, None
+ if task is not None and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ async with self._lock:
+ sessions = list(self._sessions.values())
+ self._sessions.clear()
+ # Kill every tmux session for real so `vibe stop` leaves no orphaned server, and reap
+ # any live client process. An in-flight open() finds its slot gone and tears its own
+ # child down.
+ await asyncio.gather(*(self._shutdown_session(s) for s in sessions), return_exceptions=True)
+ # Tracked teardown above only covers this process's registry. Also kill the whole tmux
+ # server on our private socket so sessions orphaned by a prior crashed/restarted process
+ # (absent from _sessions, so untouched above) don't survive `vibe stop`.
+ await _kill_tmux_server()
+
+ async def _shutdown_session(self, session: _Session) -> None:
+ if session.connection is not None:
+ await self._teardown_client(session.connection, kill_session=True)
+ elif session.persistent:
+ await _kill_tmux_session(session.session_id)
+
+ async def handle_websocket(self, websocket: WebSocket, raw_session_id: str) -> None:
+ session_id = sanitize_session_id(raw_session_id)
+ connection = await self.open(session_id)
+ try:
+ await websocket.send_text(json.dumps({"type": "ready", "persistent": connection.persistent}))
+ except BaseException:
+ # The browser can drop right after accept; open() already registered the PTY, so
+ # close it here or it leaks against max_sessions until the service restarts.
+ await self.close(connection)
+ raise
+ output_task = asyncio.create_task(self._pump_output(websocket, connection), name=f"terminal-output-{session_id}")
+ input_task = asyncio.create_task(self._pump_input(websocket, connection), name=f"terminal-input-{session_id}")
+ wait_task = asyncio.create_task(connection.process.wait(), name=f"terminal-process-{session_id}")
+ exit_code: int | None = None
+ try:
+ while True:
+ done, _pending = await asyncio.wait(
+ {output_task, input_task, wait_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if wait_task in done:
+ exit_code = await wait_task
+ input_task.cancel()
+ await asyncio.gather(input_task, return_exceptions=True)
+ try:
+ await asyncio.wait_for(output_task, timeout=0.5)
+ except asyncio.TimeoutError:
+ output_task.cancel()
+ await asyncio.gather(output_task, return_exceptions=True)
+ except WebSocketDisconnect:
+ pass
+ await _send_exit_status(websocket, exit_code)
+ break
+ if input_task in done:
+ try:
+ await input_task
+ except WebSocketDisconnect:
+ output_task.cancel()
+ wait_task.cancel()
+ await asyncio.gather(output_task, wait_task, return_exceptions=True)
+ break
+ output_task.cancel()
+ wait_task.cancel()
+ await asyncio.gather(output_task, wait_task, return_exceptions=True)
+ break
+ if output_task in done:
+ try:
+ await output_task
+ except WebSocketDisconnect:
+ input_task.cancel()
+ wait_task.cancel()
+ await asyncio.gather(input_task, wait_task, return_exceptions=True)
+ break
+ output_task = asyncio.create_task(
+ self._wait_for_process_exit(websocket, connection),
+ name=f"terminal-output-drain-{session_id}",
+ )
+ finally:
+ # Structural backstop: guarantee no pump/wait task outlives the connection,
+ # however the loop exits. The per-branch logic above cancels siblings on the
+ # expected paths (clean disconnect, process exit); this covers the rest — e.g. a
+ # pump raising a non-WebSocketDisconnect error (EBADF when a fast reconnect or
+ # shutdown closes the PTY fd) would otherwise propagate out of the loop leaving
+ # input/wait still reading the old socket or awaiting the old process. Cancelling
+ # an already-finished task is a no-op, so this is safe over the happy paths too.
+ for task in (output_task, input_task, wait_task):
+ task.cancel()
+ await asyncio.gather(output_task, input_task, wait_task, return_exceptions=True)
+ await self.close(connection)
+
+ async def open(self, session_id: str) -> TerminalConnection:
+ # Claim the id as OPENING under the lock. A single registry entry per id means a
+ # concurrent open for the same id is rejected here (the slot is already OPENING), and
+ # reconnecting an existing attached/detached id reuses its slot rather than allocating
+ # a new one — so the cap is just len(self._sessions), no per-collection arithmetic.
+ async with self._lock:
+ self._forget_finished_locked()
+ current = self._sessions.get(session_id)
+ if current is not None and current.phase in (_Phase.OPENING, _Phase.CLOSING):
+ # Either an open is in progress, or the session is mid-teardown (e.g. the
+ # reaper is awaiting a kill-session). Reject rather than reuse the id — a
+ # reconnect must not attach to a session that is being killed (which the
+ # delayed kill would then terminate). The client retries; once teardown
+ # finishes the slot is gone and the retry opens a fresh session.
+ raise TerminalServiceError("session_opening")
+ if current is None and len(self._sessions) >= self.max_sessions:
+ raise TerminalServiceError("too_many_sessions")
+ # A live client for this id will be replaced; its tmux session stays alive and
+ # the new client reattaches to it.
+ replaced = current.connection if (current is not None and current.phase is _Phase.ATTACHED) else None
+ # Carry the persistent flag onto the OPENING placeholder: if shutdown or a cancel
+ # lands in the reconnect window (after we overwrite the slot, before the new client
+ # registers), shutdown must still see this id as persistent and kill its existing
+ # tmux session — otherwise the replaced session leaks untracked after `vibe stop`.
+ was_persistent = current is not None and current.persistent
+ self._sessions[session_id] = _Session(session_id, _Phase.OPENING, persistent=was_persistent)
+ registered = False
+ spawned: TerminalConnection | None = None
+ try:
+ if replaced is not None:
+ await self._teardown_client(replaced, kill_session=False)
+
+ persistent = False
+ tmux_binary = resolve_tmux_binary()
+ if tmux_binary:
+ cmd = _tmux_launch_command(tmux_binary, session_id)
+ persistent = True
+ else:
+ cmd = [os.environ.get("SHELL") or "/bin/bash", "-l"]
+
+ master_fd, slave_fd = os.openpty()
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdin=slave_fd,
+ stdout=slave_fd,
+ stderr=slave_fd,
+ cwd=str(Path.home()),
+ env=_spawn_env(),
+ # start_new_session runs setsid() in the child via C (post-fork, pre-exec)
+ # instead of a Python preexec_fn — a Python preexec_fn can deadlock the
+ # forked child if another thread (FastAPI threadpool, dependency jobs) holds
+ # a lock at fork time, which would hang open() with the slot reserved.
+ start_new_session=True,
+ )
+ except BaseException:
+ # Close the PTY master on cancellation too (CancelledError is a BaseException,
+ # not Exception) — otherwise a cancelled spawn leaks the fd.
+ _close_fd(master_fd)
+ raise
+ finally:
+ _close_fd(slave_fd)
+
+ spawned = TerminalConnection(
+ session_id=session_id,
+ process=process,
+ master_fd=master_fd,
+ persistent=persistent,
+ attached_at=time.monotonic(),
+ last_seen=time.monotonic(),
+ )
+ async with self._lock:
+ slot = self._sessions.get(session_id)
+ if slot is not None and slot.phase is _Phase.OPENING:
+ slot.phase = _Phase.ATTACHED
+ slot.connection = spawned
+ slot.persistent = persistent
+ registered = True
+ if not registered:
+ # The OPENING slot was taken over or the service shut down while we spawned;
+ # we lost the race — tear our own child down (below) and report busy.
+ raise TerminalServiceError("session_opening")
+ return spawned
+ except BaseException:
+ if not registered:
+ await self._abandon_open(session_id, spawned)
+ raise
+
+ async def _abandon_open(self, session_id: str, spawned: TerminalConnection | None) -> None:
+ # Reconcile an open that never registered. Decide first whether our OPENING slot is
+ # still ours: if it is gone (the service shut down, or we were superseded) there is no
+ # one left to track the child, so kill its tmux session for real instead of merely
+ # detaching it — otherwise a terminal opened during `vibe stop`/reload would leave an
+ # orphaned tmux server. If the slot is still ours, just detach and re-track below when
+ # the session survived (a failed reconnect must never lose a live session).
+ async with self._lock:
+ slot = self._sessions.get(session_id)
+ ours = slot is not None and slot.phase is _Phase.OPENING
+ if ours:
+ self._sessions.pop(session_id, None)
+ if spawned is not None:
+ await self._teardown_client(spawned, kill_session=not ours)
+ # Re-track only when our slot is still ours AND a tmux session for this id is alive —
+ # which covers a failed reconnect to an existing DETACHED session (its tmux server is
+ # still up) regardless of whether our own child spawned. A session that does not exist
+ # (fresh open whose spawn failed before creating one) is simply dropped.
+ if ours and await _tmux_has_session(session_id):
+ async with self._lock:
+ if session_id not in self._sessions:
+ self._sessions[session_id] = _Session(
+ session_id, _Phase.DETACHED, persistent=True, detached_at=time.monotonic()
+ )
+
+ async def close(self, connection: TerminalConnection) -> None:
+ async with self._lock:
+ slot = self._sessions.get(connection.session_id)
+ superseded = slot is None or slot.connection is not connection
+ if not superseded:
+ # Mark CLOSING but keep the entry in place so the session keeps counting
+ # toward the cap across the async teardown; _finalize_connection settles it.
+ slot.phase = _Phase.CLOSING
+ if superseded:
+ # A newer connection already owns this id (fast reconnect): just reap our own
+ # client process; the registry belongs to the live owner.
+ await self._teardown_client(connection, kill_session=False)
+ return
+ await self._finalize_connection(connection)
+
+ async def _finalize_connection(self, connection: TerminalConnection) -> None:
+ # Detach the client, then settle the CLOSING slot against tmux reality. The slot stays
+ # in _sessions (CLOSING) for the whole teardown, so there is no window where the
+ # session is uncounted and a concurrent open could overfill max_sessions. A reconnect
+ # that grabbed the id (slot no longer our CLOSING entry) wins and we leave it be.
+ await self._teardown_client(connection, kill_session=False)
+ alive = connection.persistent and await _tmux_has_session(connection.session_id)
+ async with self._lock:
+ slot = self._sessions.get(connection.session_id)
+ if slot is None or slot.connection is not connection or slot.phase is not _Phase.CLOSING:
+ return
+ if alive:
+ slot.phase = _Phase.DETACHED
+ slot.connection = None
+ slot.detached_at = time.monotonic()
+ else:
+ self._sessions.pop(connection.session_id, None)
+
+ async def _teardown_client(self, connection: TerminalConnection, *, kill_session: bool) -> None:
+ """Release a connection's OS resources only — never touches the registry (the caller
+ owns the _sessions transition). SIGHUP detaches a tmux client so its session survives
+ for reattach; SIGTERM ends an ephemeral shell. kill_session=True also tears the tmux
+ session down (shutdown / idle expiry) so nothing is left running.
+
+ Idempotent: a fast reconnect tears down the replaced connection, then os.openpty() for
+ the replacement can reuse that same fd number. If the superseded connection's stale
+ close() then ran a second teardown it would close the NEW terminal's fd — so we poison
+ master_fd to -1 on first teardown and a repeat call closes nothing."""
+ fd, connection.master_fd = connection.master_fd, -1
+ if fd >= 0:
+ _close_fd(fd)
+ if kill_session and connection.persistent:
+ await _kill_tmux_session(connection.session_id)
+ if connection.process.returncode is None:
+ signum = signal.SIGHUP if connection.persistent else signal.SIGTERM
+ await _terminate_process(connection.process, signum)
+
+ async def resize(self, connection: TerminalConnection, cols: int, rows: int) -> None:
+ rows = max(1, min(int(rows), 1000))
+ cols = max(1, min(int(cols), 1000))
+ payload = struct.pack("HHHH", rows, cols, 0, 0)
+ await asyncio.to_thread(fcntl.ioctl, connection.master_fd, termios.TIOCSWINSZ, payload)
+ connection.touch()
+
+ async def _write_all(self, fd: int, data: bytes) -> None:
+ # master_fd is non-blocking (see _pump_output), so a single os.write can
+ # accept only part of a large frame or raise EAGAIN (easy to hit by pasting
+ # a long command). Loop until every byte is written.
+ view = memoryview(data)
+ while view:
+ try:
+ written = os.write(fd, view)
+ except BlockingIOError:
+ await asyncio.sleep(0.005)
+ continue
+ view = view[written:]
+
+ async def _pump_input(self, websocket: WebSocket, connection: TerminalConnection) -> None:
+ while True:
+ message = await websocket.receive()
+ if message["type"] == "websocket.disconnect":
+ raise WebSocketDisconnect(message.get("code", 1000))
+ if bytes_payload := message.get("bytes"):
+ await self._write_all(connection.master_fd, bytes_payload)
+ connection.touch()
+ elif text_payload := message.get("text"):
+ await self._handle_control_message(connection, text_payload)
+
+ async def _handle_control_message(self, connection: TerminalConnection, payload: str) -> None:
+ try:
+ message = json.loads(payload)
+ except json.JSONDecodeError:
+ return
+ if not isinstance(message, dict) or message.get("type") != "resize":
+ return
+ try:
+ cols = int(message.get("cols"))
+ rows = int(message.get("rows"))
+ except (TypeError, ValueError):
+ return
+ await self.resize(connection, cols, rows)
+
+ async def _pump_output(self, websocket: WebSocket, connection: TerminalConnection) -> None:
+ os.set_blocking(connection.master_fd, False)
+ while True:
+ try:
+ chunk = os.read(connection.master_fd, 8192)
+ except BlockingIOError:
+ if connection.process.returncode is not None:
+ return
+ await asyncio.sleep(0.02)
+ continue
+ except OSError as err:
+ if err.errno == errno.EIO:
+ return
+ raise
+ if not chunk:
+ if connection.process.returncode is not None:
+ return
+ await asyncio.sleep(0.02)
+ continue
+ connection.touch()
+ await websocket.send_bytes(chunk)
+
+ async def _wait_for_process_exit(self, websocket: WebSocket, connection: TerminalConnection) -> None:
+ while connection.process.returncode is None:
+ await asyncio.sleep(0.05)
+
+ def _forget_finished_locked(self) -> None:
+ # Drop EPHEMERAL attached sessions whose client has exited — they have no tmux session
+ # to preserve. A persistent client can exit while its tmux session is still alive (the
+ # user detached with the prefix key), so we must NOT pop those here: that would untrack
+ # a live session. Leave them for the reaper's finalize, which checks has-session and
+ # reconciles to DETACHED or removes them.
+ for session_id, session in list(self._sessions.items()):
+ if (
+ session.phase is _Phase.ATTACHED
+ and session.connection is not None
+ and session.connection.process.returncode is not None
+ and not session.persistent
+ ):
+ self._sessions.pop(session_id, None)
+
+ async def _reaper_loop(self) -> None:
+ while True:
+ await asyncio.sleep(60)
+ try:
+ await self.reap_idle()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ # One bad session (e.g. a kill-session subprocess that fails because the
+ # vendored tmux binary went missing) must not kill the reaper for good, or
+ # idle/detached sessions would never be reclaimed until a restart.
+ logger.exception("terminal reaper cycle failed; continuing")
+
+ async def reap_idle(self) -> None:
+ cutoff = time.monotonic() - self.idle_timeout_seconds
+ async with self._lock:
+ closing: list[TerminalConnection] = []
+ expired_detached: list[str] = []
+ for session_id, session in list(self._sessions.items()):
+ if session.phase is _Phase.ATTACHED and session.connection is not None:
+ conn = session.connection
+ if conn.process.returncode is not None or conn.last_seen < cutoff:
+ # Mark CLOSING (keep counted) and run it through the same finalize path
+ # as close(): a dead OR idle client is reconciled against has-session,
+ # so a still-alive tmux session is re-tracked as DETACHED rather than
+ # silently dropped (and an idle client's session is preserved).
+ session.phase = _Phase.CLOSING
+ closing.append(conn)
+ elif session.phase is _Phase.DETACHED and (session.detached_at or 0.0) < cutoff:
+ # Keep the entry registered (CLOSING) across the async kill so it stays
+ # counted and a reconnect in the gap can't be silently killed.
+ session.phase = _Phase.CLOSING
+ expired_detached.append(session_id)
+ for conn in closing:
+ await self._finalize_connection(conn)
+ # Kill detached sessions that outlived the idle window — but only if a reconnect has
+ # not grabbed the id meanwhile (it would have flipped the phase away from CLOSING), so
+ # we never kill a freshly reattached terminal. Drop the entry once the kill completes.
+ for session_id in expired_detached:
+ async with self._lock:
+ slot = self._sessions.get(session_id)
+ if slot is None or slot.phase is not _Phase.CLOSING or slot.connection is not None:
+ continue
+ await _kill_tmux_session(session_id)
+ async with self._lock:
+ slot = self._sessions.get(session_id)
+ if slot is not None and slot.phase is _Phase.CLOSING and slot.connection is None:
+ self._sessions.pop(session_id, None)
+
+
+class TerminalServiceError(Exception):
+ pass
+
+
+def sanitize_session_id(raw_session_id: str) -> str:
+ safe = _SAFE_SESSION_ID_RE.sub("_", raw_session_id.strip())[:80].strip("_-")
+ return safe or "terminal"
+
+
+def _tmux_launch_command(tmux_binary: str, session_id: str) -> list[str]:
+ return [
+ tmux_binary,
+ "-L",
+ _tmux_socket_name(),
+ "-f",
+ "/dev/null",
+ "new-session",
+ "-A",
+ "-s",
+ session_id,
+ ";",
+ "set-option",
+ "-g",
+ "status",
+ "off",
+ ]
+
+
+def _spawn_env() -> dict[str, str]:
+ env = dict(os.environ)
+ env["TERM"] = "xterm-256color"
+ # Drop any tmux context inherited from the Avibe daemon (which may itself have been
+ # started from inside tmux). Otherwise the spawned terminal — the vendored tmux client
+ # OR a plain fallback shell — points at the operator's tmux socket and nesting/targeting
+ # breaks (e.g. running tmux/byobu inside the fallback shell). tmux sets the correct
+ # TMUX/TMUX_PANE itself inside the persistent panes it creates.
+ env.pop("TMUX", None)
+ env.pop("TMUX_PANE", None)
+ # macOS lacks a C.UTF-8 locale; fall back to one that exists there so inner
+ # programs don't warn on startup. Only override a missing/C/POSIX locale — a
+ # real UTF-8 locale inherited from the user is kept as-is.
+ utf8_fallback = "en_US.UTF-8" if sys.platform == "darwin" else "C.UTF-8"
+ for key in ("LANG", "LC_CTYPE"):
+ value = env.get(key, "")
+ if not value or value in {"C", "POSIX"}:
+ env[key] = utf8_fallback
+ # LC_ALL overrides LANG/LC_CTYPE; an inherited C/POSIX LC_ALL would defeat the UTF-8
+ # fallback set above, so drop it and let the UTF-8 LANG/LC_CTYPE take effect. A real
+ # inherited locale is left untouched, mirroring the LANG/LC_CTYPE handling.
+ if env.get("LC_ALL", "") in {"C", "POSIX"}:
+ env.pop("LC_ALL", None)
+ return env
+
+
+async def _send_exit_status(websocket: WebSocket, code: int | None) -> None:
+ try:
+ await websocket.send_text(json.dumps({"type": "exit", "code": code}))
+ except Exception:
+ pass
+
+
+async def _terminate_process(process: asyncio.subprocess.Process, signum: signal.Signals) -> None:
+ try:
+ if hasattr(os, "killpg") and process.pid:
+ os.killpg(os.getpgid(process.pid), signum)
+ else:
+ process.send_signal(signum)
+ except ProcessLookupError:
+ return
+ except Exception:
+ logger.debug("terminal process signal failed", exc_info=True)
+ try:
+ await asyncio.wait_for(process.wait(), timeout=2)
+ return
+ except asyncio.TimeoutError:
+ pass
+ try:
+ if hasattr(os, "killpg") and process.pid:
+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)
+ else:
+ process.kill()
+ except ProcessLookupError:
+ return
+ await process.wait()
+
+
+async def _kill_tmux_session(session_id: str) -> None:
+ tmux_binary = resolve_tmux_binary()
+ if not tmux_binary:
+ return
+ process = await asyncio.create_subprocess_exec(
+ tmux_binary,
+ "-L",
+ _tmux_socket_name(),
+ "-f",
+ "/dev/null",
+ "kill-session",
+ "-t",
+ session_id,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ await process.wait()
+
+
+async def _kill_tmux_server() -> None:
+ # Kill the entire tmux server on our dedicated socket. Unlike kill-session (one tracked id),
+ # this also removes sessions orphaned by a prior process that crashed/restarted — those are
+ # still on the socket but absent from this process's registry, so they would otherwise
+ # outlive `vibe stop` with no reaper to ever collect them. The socket is private to Avibe
+ # terminals, so killing the server only affects our own sessions.
+ tmux_binary = resolve_tmux_binary()
+ if not tmux_binary:
+ return
+ try:
+ process = await asyncio.create_subprocess_exec(
+ tmux_binary,
+ "-L",
+ _tmux_socket_name(),
+ "-f",
+ "/dev/null",
+ "kill-server",
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ except OSError:
+ return
+ await process.wait()
+
+
+async def _tmux_has_session(session_id: str) -> bool:
+ # `has-session` exits 0 when the named session still exists on our socket. Used to tell
+ # a real detach (session alive) from a shell exit (session gone) before counting an id
+ # as a live detached session.
+ tmux_binary = resolve_tmux_binary()
+ if not tmux_binary:
+ return False
+ try:
+ process = await asyncio.create_subprocess_exec(
+ tmux_binary,
+ "-L",
+ _tmux_socket_name(),
+ "-f",
+ "/dev/null",
+ "has-session",
+ "-t",
+ session_id,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ except OSError:
+ return False
+ return await process.wait() == 0
+
+
+def _tmux_socket_name() -> str:
+ runtime_dir = str(paths.get_runtime_dir())
+ digest = hashlib.sha256(runtime_dir.encode("utf-8")).hexdigest()[:12]
+ return f"avibe-{digest}"
+
+
+def _close_fd(fd: int) -> None:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
diff --git a/core/tmux_runtime.py b/core/tmux_runtime.py
new file mode 100644
index 000000000..27506dff0
--- /dev/null
+++ b/core/tmux_runtime.py
@@ -0,0 +1,646 @@
+from __future__ import annotations
+
+import hashlib
+import importlib.resources as package_resources
+import json
+import logging
+import os
+import platform
+import shutil
+import stat
+import subprocess
+import sys
+import tarfile
+import tempfile
+import threading
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath, PureWindowsPath
+from sysconfig import get_platform
+from typing import Any
+
+from config import paths
+from core.process_isolation import isolated_subprocess_kwargs
+
+
+logger = logging.getLogger(__name__)
+
+_TMUX_MANIFEST_RESOURCE = "tmux_runtime_manifest.json"
+_TMUX_RUNTIME_SOURCE_MANIFEST = "manifest"
+_TMUX_INSTALL_LOCK = threading.Lock()
+
+
+@dataclass(frozen=True)
+class TmuxArchive:
+ platform: str
+ name: str
+ url: str
+ sha256: str
+ size: int | None = None
+ bin_path: str = "tmux"
+
+
+@dataclass(frozen=True)
+class TmuxManifest:
+ schema_version: int
+ tmux_version: str
+ source: str
+ source_url: str | None
+ requires_utf8proc: bool
+ terminfo: str | None
+ archives: dict[str, TmuxArchive]
+ digest: str
+ loaded_from: str
+
+
+class TmuxRuntimeManager:
+ """Install and resolve Avibe's vendored tmux binary.
+
+ The future Web Terminal will prefer this deterministic tmux over any system
+ tmux to avoid client/server protocol skew. The manifest source must point at
+ builds made with utf8proc for correct macOS CJK width handling, and with
+ terminfo handled by the archive or target platform. TERM/terminfo wiring is
+ owned by the terminal PTY spawn layer, not this dependency manager.
+ """
+
+ def __init__(
+ self,
+ *,
+ runtime_dir: Path | None = None,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool | None = None,
+ ) -> None:
+ self.runtime_dir = runtime_dir or paths.get_runtime_dir() / "tmux"
+ manifest_path_value = manifest_path or os.environ.get("VIBE_TMUX_MANIFEST_PATH")
+ self.manifest_path = Path(manifest_path_value).expanduser() if manifest_path_value else None
+ self.manifest_url = manifest_url if manifest_url is not None else os.environ.get("VIBE_TMUX_MANIFEST_URL")
+ self.offline = _env_flag_enabled("VIBE_TMUX_OFFLINE", default=False) if offline is None else offline
+ self._install_reason: str | None = None
+
+ def ensure(self, *, force: bool = False) -> dict[str, Any]:
+ if not _TMUX_INSTALL_LOCK.acquire(blocking=False):
+ return {
+ "ok": False,
+ "skipped": True,
+ "reason": "tmux_install_already_running",
+ "message": "tmux install or repair is already running; try again shortly.",
+ }
+ try:
+ manifest = self._load_manifest()
+ if not manifest:
+ return self._failure(self._install_reason or "tmux_manifest_missing")
+ archive = self._manifest_archive_for_platform(manifest)
+ if not archive:
+ return self._failure(self._install_reason or "tmux_platform_unsupported", manifest=manifest)
+ install_dir = self._manifest_install_dir(manifest, archive)
+ existing = self._verified_manifest_binary(install_dir, manifest, archive)
+ if existing and not force:
+ return {
+ "ok": True,
+ "installed": True,
+ "changed": False,
+ "path": str(existing),
+ "version": manifest.tmux_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ }
+ archive_path = self._resolve_manifest_archive(archive)
+ if not archive_path:
+ if existing:
+ return {
+ "ok": True,
+ "installed": True,
+ "changed": False,
+ "path": str(existing),
+ "version": manifest.tmux_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ "reason": self._install_reason,
+ }
+ return self._failure(self._install_reason or "tmux_archive_unavailable", manifest=manifest, archive=archive)
+ self.runtime_dir.mkdir(parents=True, exist_ok=True)
+ tmp_dir = Path(tempfile.mkdtemp(prefix="manifest-", dir=self.runtime_dir))
+ try:
+ with tarfile.open(archive_path, "r:gz") as tar:
+ _safe_extract_tar(tar, tmp_dir)
+ binary = tmp_dir / archive.bin_path
+ if not binary.is_file():
+ return self._failure("tmux_install_missing_bin", manifest=manifest, archive=archive)
+ _make_executable(binary)
+ signing = self._prepare_macos_binary(binary)
+ if not signing.get("ok"):
+ return {
+ **self._failure(str(signing.get("reason") or "tmux_codesign_failed"), manifest=manifest, archive=archive),
+ "signing": signing,
+ }
+ if not _tmux_binary_runnable(binary):
+ return self._failure("tmux_binary_not_runnable", manifest=manifest, archive=archive)
+ if install_dir.exists():
+ shutil.rmtree(install_dir)
+ install_dir.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(tmp_dir), str(install_dir))
+ binary = install_dir / archive.bin_path
+ self._write_manifest_install_metadata(install_dir, manifest, archive)
+ self._write_current_pointer(manifest, archive, install_dir)
+ self._install_reason = None
+ return {
+ "ok": True,
+ "installed": True,
+ "changed": True,
+ "path": str(binary),
+ "version": manifest.tmux_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ "signing": signing,
+ }
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Failed to install tmux runtime")
+ return self._failure("tmux_install_failed", manifest=manifest, archive=archive, message=str(exc))
+ finally:
+ if tmp_dir.exists():
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ finally:
+ _TMUX_INSTALL_LOCK.release()
+
+ def resolve_binary(self) -> Path | None:
+ manifest = self._load_manifest()
+ if not manifest:
+ return None
+ archive = self._manifest_archive_for_platform(manifest)
+ if not archive:
+ return None
+ binary = self._verified_manifest_binary(self._manifest_install_dir(manifest, archive), manifest, archive)
+ if binary:
+ return binary
+ return self._verified_manifest_binary(self._legacy_manifest_install_dir(manifest, archive), manifest, archive)
+
+ def status(self) -> dict[str, Any]:
+ manifest = self._load_manifest()
+ platform_tag = _runtime_platform_tag()
+ archive = manifest.archives.get(platform_tag) if manifest else None
+ install_dir = self._manifest_install_dir(manifest, archive) if manifest and archive else None
+ binary = self.resolve_binary() if manifest and archive else None
+ version = _tmux_binary_version(binary) if binary else None
+ return {
+ "id": "tmux",
+ "provider": _TMUX_RUNTIME_SOURCE_MANIFEST,
+ "platform": platform_tag,
+ "installed": binary is not None,
+ "version": version or (manifest.tmux_version if manifest else None),
+ "status": "ready" if binary else "missing",
+ "path": str(binary) if binary else None,
+ "install_dir": str(install_dir) if install_dir else None,
+ "manifest": _manifest_status_payload(manifest),
+ "archive": _archive_status_payload(archive),
+ "reason": self._install_reason,
+ }
+
+ def _load_manifest(self) -> TmuxManifest | None:
+ payload: bytes | None = None
+ loaded_from = ""
+ if self.manifest_path:
+ if not self.manifest_path.exists():
+ self._install_reason = "tmux_manifest_missing"
+ return None
+ payload = self.manifest_path.read_bytes()
+ loaded_from = str(self.manifest_path)
+ elif self.manifest_url:
+ if self.offline:
+ self._install_reason = "tmux_manifest_unavailable_offline"
+ return None
+ try:
+ with urllib.request.urlopen(self.manifest_url, timeout=30) as response:
+ payload = response.read()
+ loaded_from = self.manifest_url
+ except Exception:
+ logger.exception("Failed to download tmux manifest from %s", self.manifest_url)
+ self._install_reason = "tmux_manifest_download_failed"
+ return None
+ else:
+ try:
+ resource = package_resources.files("vibe").joinpath(_TMUX_MANIFEST_RESOURCE)
+ except Exception:
+ resource = None
+ if resource is None or not resource.is_file():
+ self._install_reason = "tmux_manifest_missing"
+ return None
+ payload = resource.read_bytes()
+ loaded_from = f"package:{_TMUX_MANIFEST_RESOURCE}"
+ digest = hashlib.sha256(payload).hexdigest()
+ try:
+ data = json.loads(payload.decode("utf-8"))
+ archives = {
+ platform_tag: TmuxArchive(
+ platform=platform_tag,
+ name=str(item["name"]),
+ url=str(item["url"]),
+ sha256=str(item["sha256"]),
+ size=int(item["size"]) if item.get("size") is not None else None,
+ bin_path=str(item.get("bin_path") or "tmux"),
+ )
+ for platform_tag, item in (data.get("archives") or {}).items()
+ if isinstance(item, dict)
+ }
+ manifest = TmuxManifest(
+ schema_version=int(data.get("schema_version")),
+ tmux_version=str(data.get("tmux_version") or ""),
+ source=str(data.get("source") or ""),
+ source_url=str(data.get("source_url") or "") or None,
+ requires_utf8proc=bool(data.get("requires_utf8proc")),
+ terminfo=str(data.get("terminfo") or "") or None,
+ archives=archives,
+ digest=digest,
+ loaded_from=loaded_from,
+ )
+ except Exception:
+ self._install_reason = "tmux_manifest_invalid"
+ return None
+ if manifest.schema_version != 1 or not manifest.tmux_version or not manifest.archives:
+ self._install_reason = "tmux_manifest_invalid"
+ return None
+ return manifest
+
+ def _manifest_archive_for_platform(self, manifest: TmuxManifest) -> TmuxArchive | None:
+ platform_tag = _runtime_platform_tag()
+ archive = manifest.archives.get(platform_tag)
+ if not archive:
+ self._install_reason = "tmux_platform_unsupported"
+ return None
+ return archive
+
+ def _resolve_manifest_archive(self, archive: TmuxArchive) -> Path | None:
+ cached = self.runtime_dir / "downloads" / archive.name
+ if cached.exists() and self._downloaded_archive_matches(cached, archive):
+ return cached
+ if self.offline:
+ self._install_reason = "tmux_archive_unavailable_offline"
+ return None
+ parsed = urllib.parse.urlparse(archive.url)
+ if parsed.scheme not in {"https", "file"}:
+ self._install_reason = "tmux_archive_url_unsupported"
+ return None
+ tmp_path = cached.with_suffix(cached.suffix + ".tmp")
+ cached.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ with urllib.request.urlopen(archive.url, timeout=60) as response, tmp_path.open("wb") as destination:
+ shutil.copyfileobj(response, destination)
+ if not self._downloaded_archive_matches(tmp_path, archive):
+ tmp_path.unlink(missing_ok=True)
+ return None
+ tmp_path.replace(cached)
+ return cached
+ except Exception:
+ logger.exception("Failed to download tmux archive from %s", archive.url)
+ tmp_path.unlink(missing_ok=True)
+ self._install_reason = "tmux_archive_download_failed"
+ return None
+
+ def _downloaded_archive_matches(self, path: Path, archive: TmuxArchive) -> bool:
+ if archive.size is not None and path.stat().st_size != archive.size:
+ self._install_reason = "tmux_archive_size_mismatch"
+ return False
+ if _file_sha256(path) != archive.sha256:
+ self._install_reason = "tmux_archive_checksum_mismatch"
+ return False
+ return True
+
+ def _manifest_install_dir(self, manifest: TmuxManifest, archive: TmuxArchive) -> Path:
+ fingerprint = hashlib.sha256(f"{manifest.digest}:{archive.sha256}".encode("utf-8")).hexdigest()[:16]
+ return (
+ self.runtime_dir
+ / "versions"
+ / _safe_path_part(manifest.tmux_version)
+ / _safe_path_part(archive.platform)
+ / fingerprint
+ )
+
+ def _legacy_manifest_install_dir(self, manifest: TmuxManifest, archive: TmuxArchive) -> Path:
+ return self.runtime_dir / "versions" / _safe_path_part(manifest.tmux_version) / _safe_path_part(archive.platform)
+
+ def _manifest_metadata_path(self, install_dir: Path) -> Path:
+ return install_dir / ".avibe-tmux-runtime.json"
+
+ def _verified_manifest_binary(self, install_dir: Path, manifest: TmuxManifest, archive: TmuxArchive) -> Path | None:
+ binary = install_dir / archive.bin_path
+ if not binary.is_file() or not os.access(binary, os.X_OK):
+ return None
+ if self._manifest_install_matches(install_dir, manifest, archive) and _tmux_binary_runnable(binary):
+ return binary
+ return None
+
+ def _manifest_install_matches(self, install_dir: Path, manifest: TmuxManifest, archive: TmuxArchive) -> bool:
+ try:
+ payload = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))
+ except Exception:
+ return False
+ return (
+ payload.get("provider") == _TMUX_RUNTIME_SOURCE_MANIFEST
+ and payload.get("manifest_sha256") == manifest.digest
+ and payload.get("tmux_version") == manifest.tmux_version
+ and payload.get("platform") == archive.platform
+ and payload.get("archive_sha256") == archive.sha256
+ and payload.get("bin_path") == archive.bin_path
+ )
+
+ def _write_manifest_install_metadata(self, install_dir: Path, manifest: TmuxManifest, archive: TmuxArchive) -> None:
+ self._manifest_metadata_path(install_dir).write_text(
+ json.dumps(
+ {
+ "provider": _TMUX_RUNTIME_SOURCE_MANIFEST,
+ "manifest_sha256": manifest.digest,
+ "tmux_version": manifest.tmux_version,
+ "platform": archive.platform,
+ "archive_name": archive.name,
+ "archive_sha256": archive.sha256,
+ "bin_path": archive.bin_path,
+ "manifest_source": manifest.loaded_from,
+ "source": manifest.source,
+ "requires_utf8proc": manifest.requires_utf8proc,
+ "terminfo": manifest.terminfo,
+ },
+ sort_keys=True,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+ def _write_current_pointer(self, manifest: TmuxManifest, archive: TmuxArchive, install_dir: Path) -> None:
+ pointer = self.runtime_dir / "current.json"
+ pointer.parent.mkdir(parents=True, exist_ok=True)
+ pointer.write_text(
+ json.dumps(
+ {
+ "provider": _TMUX_RUNTIME_SOURCE_MANIFEST,
+ "tmux_version": manifest.tmux_version,
+ "platform": archive.platform,
+ "install_dir": str(install_dir),
+ "manifest_sha256": manifest.digest,
+ "archive_sha256": archive.sha256,
+ "bin_path": archive.bin_path,
+ },
+ sort_keys=True,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+ def _prepare_macos_binary(self, binary: Path) -> dict[str, Any]:
+ if sys_platform() != "darwin":
+ return {"ok": True, "skipped": True, "reason": "not_macos"}
+ quarantine = _strip_quarantine(binary)
+ if _codesign_valid(binary):
+ return {"ok": True, "changed": False, "quarantine": quarantine}
+ codesign = shutil.which("codesign")
+ if not codesign:
+ return {"ok": False, "reason": "codesign_missing", "quarantine": quarantine}
+ proc = subprocess.run(
+ [codesign, "-f", "-s", "-", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ **isolated_subprocess_kwargs(),
+ )
+ verified = proc.returncode == 0 and _codesign_valid(binary)
+ return {
+ "ok": verified,
+ "changed": proc.returncode == 0,
+ "reason": None if verified else ("codesign_failed" if proc.returncode != 0 else "codesign_verify_failed"),
+ "output": _truncate((proc.stdout or "") + (proc.stderr or "")),
+ "quarantine": quarantine,
+ }
+
+ def _failure(
+ self,
+ reason: str,
+ *,
+ manifest: TmuxManifest | None = None,
+ archive: TmuxArchive | None = None,
+ message: str | None = None,
+ ) -> dict[str, Any]:
+ self._install_reason = reason
+ return {
+ "ok": False,
+ "installed": False,
+ "changed": False,
+ "reason": reason,
+ "message": message or _reason_message(reason),
+ "version": manifest.tmux_version if manifest else None,
+ "platform": archive.platform if archive else _runtime_platform_tag(),
+ "path": None,
+ "output": None,
+ }
+
+
+def get_tmux_runtime_manager(**kwargs: Any) -> TmuxRuntimeManager:
+ return TmuxRuntimeManager(**kwargs)
+
+
+def ensure_tmux_installed(force: bool = False) -> dict[str, Any]:
+ return get_tmux_runtime_manager().ensure(force=force)
+
+
+def resolve_tmux_binary() -> Path | None:
+ return get_tmux_runtime_manager().resolve_binary()
+
+
+def tmux_status() -> dict[str, Any]:
+ return get_tmux_runtime_manager().status()
+
+
+def _runtime_platform_tag() -> str:
+ raw = get_platform().lower()
+ machine = raw.rsplit("-", 1)[-1]
+ if machine == "universal2":
+ machine = platform.machine().lower()
+ if machine in {"amd64", "x86_64"}:
+ arch = "x64"
+ elif machine in {"arm64", "aarch64"}:
+ arch = "arm64"
+ else:
+ arch = machine
+ if raw.startswith("macosx"):
+ os_name = "darwin"
+ elif raw.startswith("linux"):
+ os_name = "linux"
+ elif raw.startswith("win"):
+ os_name = "win32"
+ else:
+ os_name = os.name
+ return f"{os_name}-{arch}"
+
+
+def sys_platform() -> str:
+ return sys.platform
+
+
+def _codesign_valid(binary: Path) -> bool:
+ codesign = shutil.which("codesign")
+ if not codesign:
+ return False
+ try:
+ proc = subprocess.run(
+ [codesign, "-v", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return False
+ return proc.returncode == 0
+
+
+def _strip_quarantine(binary: Path) -> dict[str, Any]:
+ xattr = shutil.which("xattr")
+ if not xattr:
+ return {"ok": True, "skipped": True, "reason": "xattr_missing"}
+ proc = subprocess.run(
+ [xattr, "-d", "com.apple.quarantine", str(binary)],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ **isolated_subprocess_kwargs(),
+ )
+ if proc.returncode == 0:
+ return {"ok": True, "changed": True}
+ text = (proc.stderr or proc.stdout or "").lower()
+ if "no such xattr" in text or "no such file" in text:
+ return {"ok": True, "changed": False}
+ return {"ok": False, "changed": False, "reason": "xattr_failed", "output": _truncate(proc.stderr or proc.stdout or "")}
+
+
+def _tmux_binary_runnable(binary: Path) -> bool:
+ return _tmux_binary_version(binary) is not None
+
+
+def _tmux_binary_version(binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ try:
+ proc = subprocess.run(
+ [str(binary), "-V"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if proc.returncode != 0:
+ return None
+ text = (proc.stdout or proc.stderr or "").strip()
+ if not text:
+ return None
+ parts = text.split()
+ return parts[-1] if parts else text
+
+
+def _safe_extract_tar(tar: tarfile.TarFile, destination: Path) -> None:
+ destination_resolved = destination.resolve()
+ for member in tar.getmembers():
+ if not (member.isfile() or member.isdir() or member.issym() or member.islnk()):
+ raise ValueError(f"Unsupported tmux archive member type: {member.name}")
+ if _tar_archive_path_is_unsafe(member.name):
+ raise ValueError(f"Unsafe tmux archive member path: {member.name}")
+ if (member.issym() or member.islnk()) and _tar_archive_path_is_unsafe(member.linkname):
+ raise ValueError(f"Unsafe tmux archive link target: {member.name}")
+ target = (destination / member.name).resolve()
+ if target != destination_resolved and destination_resolved not in target.parents:
+ raise ValueError(f"Unsafe tmux archive member path: {member.name}")
+ if member.issym():
+ link_target = Path(member.linkname)
+ resolved_link = (target.parent / link_target).resolve() if not link_target.is_absolute() else link_target.resolve()
+ if resolved_link != destination_resolved and destination_resolved not in resolved_link.parents:
+ raise ValueError(f"Unsafe tmux archive link target: {member.name}")
+ if member.islnk():
+ link_target = Path(member.linkname)
+ resolved_link = (destination / link_target).resolve()
+ if resolved_link != destination_resolved and destination_resolved not in resolved_link.parents:
+ raise ValueError(f"Unsafe tmux archive link target: {member.name}")
+ if sys.version_info >= (3, 12):
+ tar.extractall(destination, filter="data")
+ else:
+ tar.extractall(destination)
+
+
+def _tar_archive_path_is_unsafe(value: str) -> bool:
+ if not value:
+ return True
+ posix_path = PurePosixPath(value)
+ windows_path = PureWindowsPath(value)
+ if posix_path.is_absolute() or windows_path.is_absolute():
+ return True
+ if windows_path.drive or windows_path.root:
+ return True
+ return ".." in posix_path.parts or ".." in windows_path.parts
+
+
+def _file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _make_executable(path: Path) -> None:
+ mode = path.stat().st_mode
+ path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+
+def _safe_path_part(value: str) -> str:
+ cleaned = "".join(ch if ch.isalnum() or ch in {"-", "_", "."} else "-" for ch in value.strip())
+ return cleaned.strip(".-") or "unknown"
+
+
+def _env_flag_enabled(name: str, *, default: bool) -> bool:
+ value = os.environ.get(name)
+ if value is None:
+ return default
+ return value.strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _manifest_status_payload(manifest: TmuxManifest | None) -> dict[str, Any] | None:
+ if manifest is None:
+ return None
+ return {
+ "schema_version": manifest.schema_version,
+ "tmux_version": manifest.tmux_version,
+ "source": manifest.source,
+ "source_url": manifest.source_url,
+ "requires_utf8proc": manifest.requires_utf8proc,
+ "terminfo": manifest.terminfo,
+ "sha256": manifest.digest,
+ "loaded_from": manifest.loaded_from,
+ }
+
+
+def _archive_status_payload(archive: TmuxArchive | None) -> dict[str, Any] | None:
+ if archive is None:
+ return None
+ return {
+ "platform": archive.platform,
+ "name": archive.name,
+ "url": archive.url,
+ "sha256": archive.sha256,
+ "size": archive.size,
+ "bin_path": archive.bin_path,
+ }
+
+
+def _reason_message(reason: str) -> str:
+ messages = {
+ "tmux_archive_checksum_mismatch": "tmux archive checksum did not match the pinned manifest.",
+ "tmux_archive_size_mismatch": "tmux archive size did not match the pinned manifest.",
+ "tmux_platform_unsupported": "No pinned tmux runtime is available for this platform.",
+ "tmux_manifest_missing": "tmux runtime manifest is missing.",
+ "tmux_binary_not_runnable": "tmux runtime binary could not be executed after installation.",
+ "tmux_install_failed": "tmux runtime install failed.",
+ }
+ return messages.get(reason, reason)
+
+
+def _truncate(output: str, limit: int = 4096) -> str:
+ return output if len(output) <= limit else "...(truncated)\n" + output[-limit:]
diff --git a/docs/plans/apps-file-browser-terminal.md b/docs/plans/apps-file-browser-terminal.md
new file mode 100644
index 000000000..63616acf2
--- /dev/null
+++ b/docs/plans/apps-file-browser-terminal.md
@@ -0,0 +1,232 @@
+# Workbench Apps: File Browser + Terminal — Implementation Plan
+
+Status: design locked (brainstorm complete), not yet implemented · Owner: TBD ·
+Design: `design.pen` (frames TBD) · Show Page: this feature's brainstorm page
+
+## 1. Background
+
+Avibe positions as a local-first Agent OS, but the Workbench has no first-class
+"OS utility" surface: you can't browse/edit arbitrary files on the machine, and
+you can't get a real shell. The agent already has full machine access; these apps
+expose that capability, to the authenticated owner, as direct human tools.
+
+Framing: not two one-off features, but the first two entries of an **"Apps layer"**
+in the Workbench. Show Pages (already per-session mini React/Vite apps at
+`/show/<id>`) become a third, *pinnable* app over time. This framing is what makes
+the sidebar entry an extensible launcher rather than two ad-hoc nav items.
+
+## 2. Goal
+
+- A Finder-like **File Browser** app: browse the whole machine, view files (reusing
+ the existing preview stack), edit + save text/code files, and do basic file ops.
+- A **Terminal** app: a real shell in the browser with parity to the local terminal,
+ persistent across disconnects.
+- An **Apps** launcher in the sidebar that can host these and future apps.
+- Ship in two phases: **Phase 1** = Apps shell + File Browser; **Phase 2** = Terminal.
+
+## 3. Locked decisions
+
+1. **Entry**: a separate **"Apps" group** at the sidebar bottom-left, Windows-Start-menu
+ hover-expand list (reuse `InboxHoverPopover` hover-card + the `⌘K` `Command` palette);
+ on mobile it lives in the "更多" sheet. The bottom status pill **collapses to just the
+ green dot + a hover tooltip** for run state (drop the "运行中"/"服务状态" text lines);
+ version badge may tuck into the menu. Do **not** put Files/Terminal in the Capabilities
+ group (Agents/Skills/Harness/Vaults = "configure the agent"; Files/Terminal = "OS tools").
+2. **File Browser scope**: whole-machine Finder, **read + write, no project scoping**
+ (project dirs are themselves human-added, so scoping is an artificial boundary; the
+ agent can already write anywhere). UX guard only: confirm on delete/overwrite — not a
+ scope limit.
+3. **Favorites rail**: a **"项目"** group (the user's pinned sidebar projects → their
+ workdir roots, reuse existing project data) + a **"系统"** group (OS defaults: Home,
+ Desktop, Documents, Downloads, …).
+4. **Editor**: **CodeMirror 6** (over Monaco — mobile support + bundle size + fits the
+ existing Shiki read-only path).
+5. **Terminal stack**: `xterm.js` (+ fit/webgl/attach addons) + FastAPI **WebSocket** +
+ stdlib `os.openpty` (reuse the PTY pattern in `core/agent_auth_service.py`); no new
+ process/dep for the WS itself. **tmux-backed persistent sessions** running tmux's OWN
+ server + OWN socket (e.g. `avibe`), isolated from the user's hand-run tmux. **Graceful
+ fallback** to ephemeral PTY if tmux is absent.
+6. **tmux as a managed dependency**: self-built **static binary** in CI for 4 targets
+ (linux x64/arm64, mac x64/arm64), Avibe-hosted, version-managed via the show-runtime
+ model. `required: false` (optional enhancement). See §7.
+7. **Mobile terminal**: option **B** — an **accessory key bar** (Esc/Tab/Ctrl/arrows/
+ Ctrl-C/pipe; Ctrl as a sticky modifier) + reuse our iOS `visualViewport` keyboard
+ handling + lean on tmux for reconnect. File Browser on mobile is largely free (reuse
+ responsive components + CM6 is mobile-good).
+8. **MVP order**: **File Browser first** (Phase 1, with the Apps shell); Terminal second
+ (Phase 2, with the tmux dependency pipeline).
+
+## 4. Verified current state (file:line — from this session's exploration; re-verify at impl)
+
+File handling:
+- `GET /api/media/{token}` serve, hardened (symlink TOCTOU re-resolve, safe MIME, nosniff,
+ `private` cache) — `vibe/ui_server.py` ~4762; `/meta` ~4820; upload
+ `POST /api/sessions/{id}/attachments` (base64 JSON, 25MB cap) ~4845.
+- Directory listing `POST /api/browse` → `vibe/api.py:browse_directory` ~542 returns
+ **dirs only** (`follow_symlinks=False`); `GET /api/browse/favorites` (api.py ~574,
+ OS-specific quick-access); `POST /api/browse/mkdir` ~4151.
+- `media_objects` (`storage/models.py` ~403): token, canonical `local_path`,
+ file_name/content_type/file_ext, size_bytes/mtime_ns, width_px/height_px; dedup index on
+ (local_path,size,mtime). `storage/media_service.py` registration + `imagesize` probe.
+- Frontend: `DirectoryBrowser`, `FileViewer`/`FileViewerModal`, `ImageViewer`, `FileCard`
+ in `ui/src/components/ui/file-*.tsx`; preview decision `ui/src/lib/filePreview.ts:previewKind`
+ (markdown/json/csv/code/source/text via Shiki + json-view + papaparse); proxy guard
+ `isProxyMediaUrl`; dims `ui/src/lib/mediaProxy.ts`. Upload flow in `Composer.tsx`.
+
+Terminal / server:
+- FastAPI app `vibe/ui_server.py`. WebSocket precedent: `/ws/echo` ~1838 + Show HMR proxies
+ ~1863/1888 with `_show_runtime_websocket_authorized` ~1914. Chat streaming is via an
+ internal unix-socket dispatch server (not SSE in ui_server).
+- PTY precedent: `core/agent_auth_service.py` `os.openpty()` ~1155 + `asyncio.create_subprocess_exec`
+ ~1166; non-blocking read helper `_read_pty_output` (ui_server ~1226) with ANSI/control sanitize.
+- Auth: before-request `enforce_remote_access_cookie` ~1588; local check
+ `_is_local_request` / `_websocket_is_local_request` (rejects `X-Forwarded-*`); remote =
+ `__Host-vibe_remote_session` OIDC cookie (`vibe/remote_access.py:parse_session_cookie` ~783);
+ CSRF `protect_mutating_ui_requests` ~1630. UI server is a SEPARATE uvicorn process; shares
+ SQLite/config; logs to `runtime/ui_stderr.log`. New WS/HTTP routes inherit this auth.
+
+Dependencies system (NOT pluggable — hardcoded, but askill is the exact precedent):
+- `_ALLOWED_DEPENDENCIES` (`vibe/ui_server.py:3478`), `_ALLOWED_DEP_INSTALLS` (`vibe/api.py:3374`).
+- `dependencies_status()` (api.py ~3380) → items `{id, kind: tool|runtime|node, required,
+ installed, version, status}`; askill detect via `resolve_cli_path` + `--version` (~3259),
+ install via `askill.sh` (~3199); node = detect-only.
+- `start_dependency_install_job()` (~3573, if/else per dep) + endpoints
+ `GET /api/dependencies`, `POST /api/dependencies/<dep>/install`,
+ `GET /api/dependencies/<dep>/install/<job_id>` (ui_server ~3481+).
+- UI: `ui/src/components/settings/SettingsDependenciesPage.tsx` (`DEP_META` ~24, install
+ buttons ~99); type `ui/src/context/ApiContext.tsx:DependencyItem` ~854; i18n `dependencies.items`
+ in `ui/src/i18n/{en,zh}.json`.
+- Platform tag `core/show_runtime.py:_runtime_platform_tag` ~1170 (`darwin-arm64`/`linux-x64`…);
+ show-runtime download+checksum+versioned-dir model is the template for the tmux vendor.
+- Base images: `Dockerfile` ~55 apt-get; `scripts/incus_regression.py` ~1260 apt-get (bake tmux here).
+
+## 5. Design — File Browser
+
+Layout: left = directory tree (extend `DirectoryBrowser` to also list files); right = file
+content (read-only → `FileViewer`; editable → CodeMirror 6). Save via a new write API.
+
+New backend APIs (native async FastAPI in `ui_server.py`; path-safety in a shared helper):
+- `GET /api/files/list?path=` → entries with `{name, kind: dir|file|symlink, size, mtime, ext}`
+ (or extend `/api/browse` to include files; prefer a dedicated `fs` surface to keep `browse`
+ picker semantics intact). `show_hidden` flag.
+- `GET /api/files/read?path=` → bytes/text for an arbitrary path (today only token-based media
+ read exists). Reuse the hardened serve logic (canonicalize, regular-file check, size cap,
+ safe content-type, `nosniff`). Cap inline preview like the media route.
+- `PUT /api/files/write` → `{path, content}` save. Atomic write (temp + rename), size cap,
+ optional mtime precondition for conflict detection.
+- `POST /api/files/mkdir|rename|move|delete` → file ops; delete/overwrite require explicit
+ confirm on the client and are audit-logged.
+- Path-safety helper: canonicalize (`Path.resolve`), reject when the resolved target is not a
+ regular file/dir as expected (TOCTOU), normalize `~`. **No allow-root restriction** (scope is
+ whole-machine by decision), but all writes/deletes go through one choke-point that logs.
+
+Frontend:
+- Extend `DirectoryBrowser` to render files alongside dirs (icon by ext, size/mtime).
+- Reuse `FileViewer`/`FileViewerModal` for read-only preview; add an **edit mode** that mounts
+ CodeMirror 6 for editable text/code (lazy-loaded like the preview stack). Save button →
+ `/api/files/write`; dirty-state + conflict handling.
+- Favorites rail: "项目" group from pinned sidebar projects (their workdir roots) + "系统"
+ defaults (reuse `browse_favorites`). Reuse existing project data; no new persistence.
+- New page `ui/src/components/workbench/FileBrowserApp.tsx`, route `/apps/files` (see §10 shell).
+
+## 6. Design — Terminal
+
+- WS endpoint `GET /api/terminal/<session>` (native FastAPI websocket; inherits
+ `enforce_remote_access_cookie`). Protocol: text/binary frames for I/O; a small JSON control
+ channel for resize `{type:"resize", cols, rows}` → `TIOCSWINSZ` on the master fd.
+- Backend: allocate `os.openpty()`, `asyncio.create_subprocess_exec` the launch command, pump
+ master↔websocket (reuse the `agent_auth_service` pattern + `_read_pty_output` style reader on
+ the event loop / threadpool — no per-request `asyncio.run`).
+- **tmux persistence**: launch `tmux -L avibe new-session -A -s <id>` (own socket `-L avibe`,
+ attach-or-create) so the shell lives in tmux and survives WS drops; reconnect re-attaches.
+ Run with a minimal tmux config (status bar off, sane keys) so it reads as a clean terminal,
+ not "a tmux". If tmux missing → spawn `$SHELL -l` directly (ephemeral). tmux is `required:false`.
+- Spawn env: set an explicit UTF-8 locale (`LANG`/`LC_CTYPE`) — do NOT inherit the daemon's
+ likely C/POSIX locale; set `TERM=screen-256color` (or ship terminfo) for inner programs.
+- Lifecycle/reaper: idle timeout, max sessions per user, cleanup of dead servers/sockets.
+- Frontend `TerminalApp.tsx` + `xterm.js` (`@xterm/xterm`, addons fit/webgl/attach), route
+ `/apps/terminal`.
+
+## 7. tmux as a managed dependency
+
+Mechanism (mirrors show-runtime):
+- **Self-build** a static tmux in CI for 4 targets (linux x64/arm64, mac x64/arm64), built
+ **with `utf8proc`** (mac CJK double-width correctness — upstream prebuilts don't guarantee it)
+ and terminfo handled. Host as Avibe release assets + a manifest pinning version + per-platform
+ asset + sha256. (May start by mirroring upstream `tmux/tmux-builds` static binaries to validate
+ fast, but the target is self-build for control over utf8proc/terminfo/signing/version.)
+- **Install**: download the pinned asset for `_runtime_platform_tag`, verify sha256, unpack into
+ a versioned immutable dir under `~/.avibe/runtime/tmux/versions/<ver>/`.
+- **macOS signing (verified this session on arm64)**: an unsigned binary is SIGKILLed (exit 137,
+ "code object is not signed at all"); `codesign -s -` (ad-hoc, free, no Apple cert, no
+ notarization) makes it run. Programmatic `curl`/urllib download does NOT set the
+ `com.apple.quarantine` xattr, so Gatekeeper does not prompt for CLI exec. → On download:
+ verify signature; if not validly signed, ad-hoc sign (`codesign -f -s -`); strip quarantine if
+ present.
+- **Always use the vendored binary** (ignore system tmux): deterministic version (test once),
+ sidesteps tmux client/server protocol skew, we control utf8proc/terminfo/signing. Binary is
+ tiny (~0.6–0.9 MB).
+- **Hosted/Docker/Incus**: also bake tmux into base images (one apt line) — simplest there.
+- **Registration** (low-friction, follows askill): add `"tmux"` to `_ALLOWED_DEPENDENCIES` /
+ `_ALLOWED_DEP_INSTALLS`; add `tmux_status()` (detect `tmux -V`, min-version check, NOT exact pin)
+ + `ensure_tmux_installed(force)` (download/verify/sign); append to `dependencies_status()`
+ (`kind="tool"`, `required=false`); route in `start_dependency_install_job()`; add `DEP_META`
+ + i18n + Settings·Dependencies card.
+
+## 8. Mobile
+
+- Terminal = option B: accessory key bar above the keyboard (Esc/Tab/Ctrl/arrows/Ctrl-C/`|`;
+ Ctrl/Alt as sticky modifiers); reuse the iOS `visualViewport` keyboard handling (see
+ `mobile-responsive-webui.md` / iOS keyboard fix) so the terminal sizes above the keyboard;
+ tmux covers reconnect on network/background drops. C (gestures, customizable keys) is post-v1.
+- File Browser = largely free: responsive layout + CodeMirror 6 is mobile-good. Apps launcher on
+ mobile lives in the "更多" sheet.
+
+## 9. Security
+
+- Does NOT expand the trust boundary: the agent already has machine access, and the Workbench is
+ OIDC + Cloudflare-tunnel gated (`enforce_remote_access_cookie`). These expose an existing
+ capability to the authenticated owner.
+- But a terminal raises the blast radius of any auth bug to "remote shell". Hardening:
+ - opt-in / feature flag;
+ - **never reachable via public `/p/` share links** — Workbench + private `/show` only;
+ - WebSocket `Origin` check (codebase already rejects `X-Forwarded-*`);
+ - audit log of file writes/deletes and terminal commands;
+ - idle timeout on terminal sessions.
+
+## 10. Implementation plan
+
+**Phase 1 — Apps shell + File Browser**
+- Apps shell: sidebar "Apps" group + hover/`⌘K` launcher (reuse `InboxHoverPopover` + `Command`);
+ collapse the status pill to the green dot + tooltip; routes `/apps/*`; mobile entry in "更多".
+- Backend: `fs` APIs (list with files, read-by-path, write, mkdir/rename/move/delete) + shared
+ path-safety choke-point + audit; confirm-on-destructive on the client.
+- Frontend: extend `DirectoryBrowser` (files); `FileBrowserApp`; CodeMirror 6 edit mode; favorites
+ "项目" + "系统". i18n keys; reuse `ui/src/components/ui/` primitives.
+- Tests: path-safety unit tests (canonicalize, regular-file, atomic write); UI `npm run build`.
+
+**Phase 2 — Terminal**
+- tmux dependency pipeline (§7): CI static builds (4 targets) + manifest + version mgmt +
+ download/verify/sign; register in the Dependencies system + Settings card; bake into base images.
+- Terminal backend: `/api/terminal/<session>` WS + PTY + tmux own-socket persistence + resize +
+ lifecycle/reaper + UTF-8 locale + `TERM`.
+- Frontend: `TerminalApp` + `xterm.js` + addons; mobile accessory key bar + iOS viewport reuse.
+- Security: flag, never-on-`/p/`, Origin check, audit, idle timeout.
+- Regression: verify terminal across platforms in the Incus environment.
+
+## 11. Testing & validation
+
+- Backend: focused pytest for path-safety + fs APIs (hermetic, redirect to test-owned dirs;
+ never touch real `$HOME`/state); min-version + sign/locale handling for the tmux vendor.
+- UI: `cd ui && npm run build`. Native async FastAPI for new routes (no `asyncio.run` bridges,
+ not `ui_compat`). `ruff check` on changed Python before push.
+- Cross-platform/user-facing: Incus regression for the terminal especially.
+
+## 12. Related plans
+
+- `dependencies-settings.md` — the Dependencies tab + askill precedent (extend for tmux).
+- show-runtime vendor/version model — template for the tmux managed binary.
+- `file-preview-component.md` — the `FileViewer` stack being reused/extended.
+- `mobile-responsive-webui.md` + iOS keyboard fix — reused for the mobile terminal.
+- `agent-run-terminal-lifecycle.md` — DISTINCT: that is CLI `vibe agent run` session lifecycle,
+ not this Web terminal app.
diff --git a/docs/plans/terminal-session-state-machine.md b/docs/plans/terminal-session-state-machine.md
new file mode 100644
index 000000000..76d92b869
--- /dev/null
+++ b/docs/plans/terminal-session-state-machine.md
@@ -0,0 +1,80 @@
+# Terminal session state machine (root-cause refactor)
+
+## Why
+
+PR #659's terminal backend drew **four straight review rounds (7–10) of P2 bugs that are all
+the same root cause**: session state was split across three collections kept consistent by
+hand —
+
+- `_connections: dict[str, TerminalConnection]` (attached)
+- `_detached_tmux_sessions: dict[str, float]` (detached, value = detach time)
+- `_reserved_sessions: set[str]` (mid-open)
+
+…and the `max_sessions` cap was computed by summing all three with ad-hoc subtractions
+(`- existing`, `- reconnecting_detached`). Every bug was "these collections got out of sync"
+or "a transition wasn't atomic":
+
+| Round | Symptom | Real cause |
+| --- | --- | --- |
+| 7 | detach not tracked when client exits | transition gap |
+| 8 | cancel-after-spawn leak; concurrent-reconnect overwrite; dead session marked detached | three collections desync |
+| 9 | replace doesn't clear detached; recheck before recording | desync |
+| 10 | open-fail drops detached; superseded marked detached | desync + cap arithmetic |
+
+A second, smaller entanglement: `_cleanup_connection()` did **two jobs at once** — released
+the OS client (fd + signal) *and* mutated `_detached_tmux_sessions`. That coupling is why
+every caller (open/close/reaper/shutdown) had to reason about bookkeeping side effects.
+
+## The fix (one model, one owner per concern)
+
+**1. One registry, one entry per id, explicit phase.**
+
+```
+_Phase = OPENING | ATTACHED | DETACHED
+_Session(session_id, phase, persistent, connection?, detached_at?)
+self._sessions: dict[str, _Session] # the ONLY collection
+```
+
+- Capacity = `len(self._sessions)`. A reconnect (id already present) reuses its slot; only a
+ brand-new id is checked against the cap. **No subtraction arithmetic** → the round-8/9/10
+ cap bugs are gone by construction.
+- One dict key per id → **double-counting is structurally impossible**.
+- DETACHED→OPENING→ATTACHED is the *same* entry transitioning in place → no "stale second
+ entry / forgot to clear the other collection" class.
+
+**2. Separate OS teardown from registry bookkeeping.**
+
+- `_teardown_client(connection, *, kill_session)` — fd + signal only, never touches
+ `_sessions`.
+- All `_sessions` transitions happen in `open` / `close` / `reap_idle` / `shutdown`, under
+ the lock, as explicit moves with **compare-and-set identity checks**.
+
+## How each prior bug becomes impossible
+
+- **Concurrent reconnect**: `open` rejects when the slot is already `OPENING`; a second open
+ can never mutate someone else's OPENING entry.
+- **Superseded client marked detached**: `close` only transitions when
+ `slot.connection is connection` (identity CAS); a newer connection owning the id is left
+ untouched.
+- **Open-fail drops a live detached session**: failure path (`_abandon_open`) reconciles the
+ OPENING slot against `tmux has-session` — re-tracks DETACHED if the session is alive,
+ drops the placeholder otherwise.
+- **Cancel-after-spawn leak**: same failure path tears the spawned child down and reconciles.
+- **Detach vs. shell-exit**: `close` records DETACHED only when `persistent and
+ has-session`.
+
+## Scope / safety
+
+- Internal only. Public API (`open`→`TerminalConnection`, `close`, `resize`,
+ `handle_websocket`, `shutdown`, `reap_idle`, `start_reaper`) is unchanged; `ui_server`
+ and the WS pumps are untouched. No external reference to the old private collections.
+- The accumulated terminal tests (round-trip, reconnect-replaces, reserve-during-spawn,
+ ready-frame-fail, cancel-releases-slot, detach tracking, superseded, open-fail-preserves-
+ detached) are the regression net; internal-state assertions are re-pointed at `_sessions`.
+
+## Files
+
+- `core/terminal_service.py` — the refactor.
+- `tests/test_terminal_backend.py` — re-point internal assertions; keep behavior tests.
+
+The symlink-over-target P1 (file_browser) is a separate, genuine fix handled in parallel.
diff --git a/pyproject.toml b/pyproject.toml
index 6d05e0fa4..8b77b5de2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -89,7 +89,7 @@ version-file = "vibe/_version.py"
[tool.hatch.build]
# Include generated assets even though they are in .gitignore (build artifacts)
-artifacts = ["ui/dist/**", "vibe/show_runtime_manifest.json"]
+artifacts = ["ui/dist/**", "vibe/show_runtime_manifest.json", "vibe/tmux_runtime_manifest.json"]
[tool.hatch.build.targets.wheel]
packages = ["vibe", "config", "core", "modules", "storage"]
@@ -109,6 +109,7 @@ include = [
"main.py",
"ui/dist/**",
"vibe/show_runtime_manifest.json",
+ "vibe/tmux_runtime_manifest.json",
"README.md",
"LICENSE",
]
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index bdd4b3035..46e09620b 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -1257,7 +1257,7 @@ def cmd_build_base(args: argparse.Namespace) -> int:
"""\
set -euo pipefail
apt-get update
- apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo
+ apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo tmux
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
# Install the agent backends under the service user's home so the
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
new file mode 100644
index 000000000..8b1344240
--- /dev/null
+++ b/tests/test_file_browser_backend.py
@@ -0,0 +1,1220 @@
+from __future__ import annotations
+
+import errno
+import logging
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from core import file_browser_service as fs
+from core.file_browser_service import FileBrowserError
+from tests.ui_server_test_helpers import csrf_headers
+from vibe.ui_server import app
+
+
+def test_resolve_safe_path_expands_home_and_requires_absolute(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.setenv("HOME", str(home))
+
+ assert fs.resolve_safe_path("~/docs").is_absolute()
+ assert fs.resolve_safe_path("~/docs") == home / "docs"
+ with pytest.raises(FileBrowserError) as exc:
+ fs.resolve_safe_path("relative/path")
+ assert exc.value.code == "invalid_path"
+
+
+def test_list_directory_includes_dirs_files_hidden_and_unfollowed_symlink(tmp_path):
+ root = tmp_path / "root"
+ root.mkdir()
+ (root / "b.txt").write_text("b", encoding="utf-8")
+ (root / "a-dir").mkdir()
+ (root / ".hidden").write_text("h", encoding="utf-8")
+ os.symlink(root / "b.txt", root / "link")
+
+ visible = fs.list_directory(str(root), show_hidden=False)
+ assert [(item["name"], item["kind"]) for item in visible["entries"]] == [
+ ("a-dir", "dir"),
+ ("b.txt", "file"),
+ ("link", "symlink"),
+ ]
+ assert visible["entries"][1]["size"] == 1
+ assert visible["entries"][1]["ext"] == "txt"
+
+ all_entries = fs.list_directory(str(root), show_hidden=True)
+ assert ".hidden" in {item["name"] for item in all_entries["entries"]}
+
+ assert fs.metadata(str(root / "link"))["kind"] == "symlink"
+
+
+def test_list_directory_truncates_scan_over_hidden_entries(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_LIST_ENTRIES", 5)
+ root = tmp_path / "root"
+ root.mkdir()
+ for index in range(12):
+ (root / f".hidden-{index}").write_text("hidden", encoding="utf-8")
+ (root / "a.txt").write_text("a", encoding="utf-8")
+ (root / "b.txt").write_text("b", encoding="utf-8")
+
+ result = fs.list_directory(str(root), show_hidden=False)
+
+ assert result["truncated"] is True
+
+
+def test_list_truncated_includes_limit(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_LIST_ENTRIES", 3)
+ root = tmp_path / "root"
+ root.mkdir()
+ for index in range(6):
+ (root / f".hidden-{index}").write_text("hidden", encoding="utf-8")
+
+ truncated = fs.list_directory(str(root), show_hidden=False)
+
+ assert truncated["truncated"] is True
+ assert truncated["entries"] == []
+ assert truncated["limit"] == 3
+
+ visible = tmp_path / "visible"
+ visible.mkdir()
+ (visible / "a.txt").write_text("a", encoding="utf-8")
+ not_truncated = fs.list_directory(str(visible), show_hidden=False)
+ assert not_truncated["truncated"] is False
+ assert "limit" not in not_truncated
+
+
+def test_list_directory_exact_visible_cap_is_not_truncated(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_LIST_ENTRIES", 3)
+ root = tmp_path / "root"
+ root.mkdir()
+ for index in range(3):
+ (root / f"{index}.txt").write_text(str(index), encoding="utf-8")
+
+ result = fs.list_directory(str(root), show_hidden=False)
+
+ assert [item["name"] for item in result["entries"]] == ["0.txt", "1.txt", "2.txt"]
+ assert result["truncated"] is False
+ assert "limit" not in result
+
+
+def test_list_directory_over_visible_cap_is_truncated_after_full_page(tmp_path, monkeypatch):
+ monkeypatch.setattr(fs, "MAX_LIST_ENTRIES", 3)
+ root = tmp_path / "root"
+ root.mkdir()
+ for index in range(4):
+ (root / f"{index}.txt").write_text(str(index), encoding="utf-8")
+
+ result = fs.list_directory(str(root), show_hidden=False)
+
+ assert len(result["entries"]) == 3
+ assert result["truncated"] is True
+ assert result["limit"] == 3
+
+
+def test_entry_ops_handle_cyclic_symlink(tmp_path):
+ link = tmp_path / "loop"
+ link.symlink_to(link)
+
+ assert fs.metadata(str(link))["kind"] == "symlink"
+
+ fs.delete_path(str(link))
+
+ assert not link.is_symlink()
+
+
+def test_list_rejects_traversal_to_non_directory(tmp_path):
+ root = tmp_path / "root"
+ root.mkdir()
+ file_path = root / "file.txt"
+ file_path.write_text("x", encoding="utf-8")
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.list_directory(str(root / ".." / "root" / "file.txt"))
+ assert exc.value.code == "not_dir"
+
+
+def test_write_refuses_to_follow_symlink(tmp_path):
+ root = tmp_path / "root"
+ root.mkdir()
+ real = root / "real.txt"
+ real.write_text("original", encoding="utf-8")
+ link = root / "link.txt"
+ os.symlink(real, link)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(link), "hacked")
+ assert exc.value.code == "is_symlink"
+ # The symlink's target must be left untouched (no write-through).
+ assert real.read_text(encoding="utf-8") == "original"
+
+
+def test_content_inline_headers_attachment_and_size_cap(tmp_path):
+ text_path = tmp_path / "note.txt"
+ text_path.write_text("hello", encoding="utf-8")
+ html_path = tmp_path / "page.html"
+ html_path.write_text("<script></script>", encoding="utf-8")
+ large_path = tmp_path / "large.txt"
+ large_path.write_bytes(b"x" * (fs.MAX_FILE_BYTES + 1))
+
+ text = fs.file_content(str(text_path))
+ assert text.mime == "text/plain"
+ assert text.disposition == "inline"
+ assert text.data == b"hello"
+
+ html = fs.file_content(str(html_path))
+ assert html.disposition == "attachment"
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.file_content(str(large_path))
+ assert exc.value.code == "too_large"
+
+
+def test_content_refuses_toctou_symlink_swap(tmp_path):
+ target = tmp_path / "target.txt"
+ target.write_text("x", encoding="utf-8")
+ other = tmp_path / "other.txt"
+ other.write_text("other", encoding="utf-8")
+
+ def resolve_then_swap(raw: str) -> Path:
+ resolved = fs.resolve_safe_path(raw)
+ target.unlink()
+ target.symlink_to(other)
+ return resolved
+
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(fs, "_resolve_existing_path", resolve_then_swap)
+ with pytest.raises(FileBrowserError) as exc:
+ fs.file_content(str(target))
+ assert exc.value.code == "not_found"
+
+
+def test_rename_no_replace_moves_when_target_absent(tmp_path):
+ src = tmp_path / "a.txt"
+ src.write_text("A", encoding="utf-8")
+ dst = tmp_path / "b.txt"
+
+ fs._rename_no_replace(src, dst)
+
+ assert dst.read_text(encoding="utf-8") == "A"
+ assert not src.exists()
+
+
+def test_rename_refuses_to_clobber_target_appearing_after_precheck(tmp_path, monkeypatch):
+ # TOCTOU guard: even if the existence pre-check is blind to the destination (it was
+ # created in the race window), the atomic no-replace rename must refuse rather than
+ # silently clobber the file that appeared.
+ src = tmp_path / "src.txt"
+ src.write_text("SRC", encoding="utf-8")
+ dst = tmp_path / "dst.txt"
+ dst.write_text("DST", encoding="utf-8")
+
+ real_exists = fs._exists_no_follow
+ monkeypatch.setattr(fs, "_exists_no_follow", lambda p: False if Path(p) == dst else real_exists(p))
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.rename_path(str(src), "dst.txt")
+
+ assert exc.value.code == "exists"
+ assert dst.read_text(encoding="utf-8") == "DST" # not clobbered
+ assert src.read_text(encoding="utf-8") == "SRC" # source intact
+
+
+def test_delete_refuses_filesystem_root(monkeypatch):
+ # A recursive delete of "/" (or a drive root) must be refused before it can rmtree the
+ # machine. Resolver + rmtree are stubbed so the test is safe even if the guard regresses.
+ monkeypatch.setattr(fs, "_resolve_existing_entry_path", lambda raw: Path("/"))
+ rmtree_calls: list = []
+ monkeypatch.setattr(fs.shutil, "rmtree", lambda *args, **kwargs: rmtree_calls.append(args))
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path("/", recursive=True)
+
+ assert exc.value.code == "invalid_path"
+ assert rmtree_calls == [] # the guard fired before any rmtree
+
+
+def test_mutation_entry_paths_reject_dotdot_final_component(tmp_path):
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ child = parent / "child"
+ child.mkdir()
+ source = tmp_path / "source.txt"
+ source.write_text("source", encoding="utf-8")
+ rmtree_calls: list[tuple] = []
+
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(fs.shutil, "rmtree", lambda *args, **kwargs: rmtree_calls.append(args))
+ for raw_path in ("/tmp/..", str(child / "..")):
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path(raw_path, recursive=True)
+ assert exc.value.code == "invalid_path"
+
+ with pytest.raises(FileBrowserError) as rename_exc:
+ fs.rename_path(str(child / ".."), "renamed")
+ assert rename_exc.value.code == "invalid_path"
+
+ with pytest.raises(FileBrowserError) as move_source_exc:
+ fs.move_path(str(child / ".."), str(tmp_path / "moved-source"))
+ assert move_source_exc.value.code == "invalid_path"
+
+ with pytest.raises(FileBrowserError) as move_target_exc:
+ fs.move_path(str(source), str(child / ".."))
+ assert move_target_exc.value.code == "invalid_path"
+
+ assert rmtree_calls == []
+
+
+def test_nested_delete_and_rename_still_work_for_normal_entries(tmp_path):
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ child = nested / "child.txt"
+ child.write_text("child", encoding="utf-8")
+
+ renamed = fs.rename_path(str(child), "renamed.txt")
+ renamed_path = Path(renamed["path"])
+
+ assert renamed_path.read_text(encoding="utf-8") == "child"
+ fs.delete_path(str(nested), recursive=True)
+ assert not nested.exists()
+
+
+def test_move_symlink_over_directory_is_refused(tmp_path):
+ # overwrite=True must not let a non-directory replace a directory. is_file() follows
+ # symlinks, so a symlink-to-dir (or broken link) slipped past the old guard and the move
+ # then backed up + deleted the real directory's contents. No-follow guard refuses it.
+ other_dir = tmp_path / "other"
+ other_dir.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(other_dir) # a symlink whose target is a directory
+ target_dir = tmp_path / "data"
+ target_dir.mkdir()
+ (target_dir / "keep.txt").write_text("keep", encoding="utf-8")
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(link), str(target_dir), overwrite=True)
+
+ assert exc.value.code == "exists"
+ assert target_dir.is_dir()
+ assert (target_dir / "keep.txt").read_text(encoding="utf-8") == "keep" # contents not erased
+ assert link.is_symlink()
+
+
+def test_rename_same_name_is_noop(tmp_path):
+ src = tmp_path / "same.txt"
+ src.write_text("SRC", encoding="utf-8")
+
+ result = fs.rename_path(str(src), "same.txt")
+
+ assert result == {"ok": True, "path": str(src)}
+ assert src.read_text(encoding="utf-8") == "SRC"
+
+ dst = tmp_path / "other.txt"
+ dst.write_text("DST", encoding="utf-8")
+ with pytest.raises(FileBrowserError) as exc:
+ fs.rename_path(str(src), "other.txt")
+
+ assert exc.value.code == "exists"
+ assert src.read_text(encoding="utf-8") == "SRC"
+ assert dst.read_text(encoding="utf-8") == "DST"
+
+
+def test_rename_to_different_hard_link_of_same_inode_is_conflict(tmp_path):
+ source = tmp_path / "source.txt"
+ source.write_text("source", encoding="utf-8")
+ target = tmp_path / "target.txt"
+ os.link(source, target)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.rename_path(str(source), "target.txt")
+
+ assert exc.value.code == "exists"
+ assert source.read_text(encoding="utf-8") == "source"
+ assert target.read_text(encoding="utf-8") == "source"
+ assert fs._same_entry_no_follow(source, target)
+
+
[email protected](sys.platform != "darwin", reason="case-only rename behavior depends on case-insensitive filesystem")
+def test_rename_case_only_same_inode_is_allowed_on_case_insensitive_fs(tmp_path):
+ source = tmp_path / "case.txt"
+ source.write_text("case", encoding="utf-8")
+ target = tmp_path / "CASE.txt"
+ if not target.exists() or not fs._same_entry_no_follow(source, target):
+ pytest.skip("temporary filesystem is case-sensitive")
+
+ result = fs.rename_path(str(source), "CASE.txt")
+
+ assert result == {"ok": True, "path": str(target)}
+ assert target.read_text(encoding="utf-8") == "case"
+
+
+def test_rename_no_replace_refuses_existing_directory_target(tmp_path, monkeypatch):
+ src = tmp_path / "src"
+ src.mkdir()
+ dst = tmp_path / "dst"
+ dst.mkdir()
+
+ def target_exists(*_args, **_kwargs):
+ raise FileExistsError(str(dst))
+
+ real_exists = fs._exists_no_follow
+ monkeypatch.setattr(fs, "_glibc_renameat2_noreplace", target_exists)
+ monkeypatch.setattr(fs, "_exists_no_follow", lambda p: False if Path(p) == dst else real_exists(p))
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs._rename_no_replace(src, dst)
+
+ assert exc.value.code == "exists"
+ assert src.is_dir()
+ assert dst.is_dir()
+
+
+def test_write_is_atomic_and_detects_mtime_conflict(tmp_path):
+ path = tmp_path / "doc.txt"
+ first = fs.write_file(str(path), "first")
+ assert path.read_text(encoding="utf-8") == "first"
+
+ fs.write_file(str(path), "second", expected_mtime=first["mtime"])
+ assert path.read_text(encoding="utf-8") == "second"
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(path), "stale", expected_mtime=first["mtime"])
+ assert exc.value.code == "conflict"
+
+ with pytest.raises(FileBrowserError) as large_exc:
+ fs.write_file(str(tmp_path / "large.txt"), "x" * (fs.MAX_FILE_BYTES + 1))
+ assert large_exc.value.code == "too_large"
+ assert not list(tmp_path.glob(".large.txt.*.tmp"))
+
+
+def test_write_maps_mkstemp_permission_error(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+
+ def deny_tempfile(*_args, **_kwargs):
+ raise PermissionError("denied")
+
+ monkeypatch.setattr(fs.tempfile, "mkstemp", deny_tempfile)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(path), "blocked")
+
+ assert exc.value.code == "permission_denied"
+ assert exc.value.status_code == 403
+ assert not path.exists()
+
+
+def test_write_maps_mkstemp_os_error(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+
+ def fail_tempfile(*_args, **_kwargs):
+ raise OSError("disk failure")
+
+ monkeypatch.setattr(fs.tempfile, "mkstemp", fail_tempfile)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(path), "blocked")
+
+ assert exc.value.code == "fs_error"
+ assert not path.exists()
+
+
+def test_write_normal_path_still_succeeds(tmp_path):
+ path = tmp_path / "doc.txt"
+
+ result = fs.write_file(str(path), "ok")
+
+ assert result["ok"] is True
+ assert path.read_text(encoding="utf-8") == "ok"
+
+
+def test_write_long_legal_basename_uses_bounded_temp_name(tmp_path, monkeypatch):
+ name = "a" * 250
+ path = tmp_path / name
+ try:
+ path.touch()
+ except OSError as exc:
+ if exc.errno != errno.ENAMETOOLONG:
+ raise
+ name = "a" * 120
+ path = tmp_path / name
+ path.touch()
+ path.write_text("old", encoding="utf-8")
+ temp_prefixes: list[str] = []
+ real_mkstemp = fs.tempfile.mkstemp
+
+ def capture_mkstemp(*args, **kwargs):
+ temp_prefixes.append(kwargs["prefix"])
+ assert len(kwargs["prefix"].encode()) + 8 + len(kwargs["suffix"].encode()) <= 255
+ return real_mkstemp(*args, **kwargs)
+
+ monkeypatch.setattr(fs.tempfile, "mkstemp", capture_mkstemp)
+
+ result = fs.write_file(str(path), "new")
+
+ assert result["ok"] is True
+ assert path.read_text(encoding="utf-8") == "new"
+ assert temp_prefixes == [fs._WRITE_TEMP_PREFIX]
+
+
+def test_write_preserves_existing_file_mode(tmp_path):
+ path = tmp_path / "script.sh"
+ path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ path.chmod(0o755)
+
+ fs.write_file(str(path), "#!/bin/sh\necho ok\n")
+
+ assert path.read_text(encoding="utf-8") == "#!/bin/sh\necho ok\n"
+ assert path.stat().st_mode & 0o777 == 0o755
+
+
+def test_write_serializes_expected_mtime_check_and_replace(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+ path.write_text("base", encoding="utf-8")
+ os.utime(path, ns=(1_000_000_000, 1_000_000_000))
+ expected_mtime = fs._mtime_seconds(path.stat())
+ real_replace = fs.os.replace
+ first_replace_entered = threading.Event()
+ release_first_replace = threading.Event()
+ replace_calls: list[str] = []
+ replace_calls_lock = threading.Lock()
+ results: list[dict[str, object]] = []
+ errors: list[FileBrowserError] = []
+
+ def blocking_replace(src: str, dst: Path) -> None:
+ with replace_calls_lock:
+ call_index = len(replace_calls)
+ replace_calls.append(Path(src).name)
+ if call_index == 0:
+ first_replace_entered.set()
+ assert release_first_replace.wait(2)
+ real_replace(src, dst)
+
+ def write_content(content: str) -> None:
+ try:
+ results.append(fs.write_file(str(path), content, expected_mtime=expected_mtime))
+ except FileBrowserError as exc:
+ errors.append(exc)
+
+ monkeypatch.setattr(fs.os, "replace", blocking_replace)
+ first = threading.Thread(target=write_content, args=("first",))
+ first.start()
+ assert first_replace_entered.wait(2)
+
+ second = threading.Thread(target=write_content, args=("second",))
+ second.start()
+ time.sleep(0.1)
+ assert len(replace_calls) == 1
+
+ release_first_replace.set()
+ first.join(2)
+ second.join(2)
+
+ assert not first.is_alive()
+ assert not second.is_alive()
+ assert [error.code for error in errors] == ["conflict"]
+ assert len(results) == 1
+ assert len(replace_calls) == 1
+ assert path.read_text(encoding="utf-8") == "first"
+
+
+def test_mutating_ops_mkdir_rename_move_delete(tmp_path, caplog):
+ caplog.set_level(logging.INFO, logger="core.file_browser_service")
+ folder = tmp_path / "folder"
+ assert fs.make_directory(str(folder)) == {"ok": True}
+
+ with pytest.raises(FileBrowserError) as exists_exc:
+ fs.make_directory(str(folder))
+ assert exists_exc.value.code == "exists"
+
+ file_path = folder / "old.txt"
+ file_path.write_text("x", encoding="utf-8")
+ renamed = fs.rename_path(str(file_path), "new.txt")
+ new_path = Path(renamed["path"])
+ assert new_path.exists()
+
+ with pytest.raises(FileBrowserError) as invalid_name:
+ fs.rename_path(str(new_path), "../bad")
+ assert invalid_name.value.code == "invalid_name"
+
+ moved = tmp_path / "moved.txt"
+ assert fs.move_path(str(new_path), str(moved)) == {"ok": True}
+ assert moved.exists()
+
+ other = tmp_path / "other.txt"
+ other.write_text("other", encoding="utf-8")
+ with pytest.raises(FileBrowserError) as overwrite_exc:
+ fs.move_path(str(moved), str(other))
+ assert overwrite_exc.value.code == "exists"
+ fs.move_path(str(moved), str(other), overwrite=True)
+ assert other.read_text(encoding="utf-8") == "x"
+
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ (nested / "child.txt").write_text("child", encoding="utf-8")
+ with pytest.raises(FileBrowserError) as non_recursive:
+ fs.delete_path(str(nested))
+ assert non_recursive.value.code == "not_empty"
+ fs.delete_path(str(nested), recursive=True)
+ assert not nested.exists()
+ assert any("file_browser.delete" in record.message for record in caplog.records)
+
+
+def test_delete_non_recursive_directory_maps_not_empty_only_for_not_empty_errno(tmp_path):
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ (nested / "child.txt").write_text("child", encoding="utf-8")
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path(str(nested), recursive=False)
+
+ assert exc.value.code == "not_empty"
+ assert exc.value.status_code == 409
+
+
+def test_delete_non_recursive_directory_maps_permission_denied(tmp_path, monkeypatch):
+ folder = tmp_path / "folder"
+ folder.mkdir()
+
+ def fail_rmdir(self: Path) -> None:
+ if self == folder:
+ raise PermissionError(errno.EACCES, "permission denied", str(self))
+ return real_rmdir(self)
+
+ real_rmdir = Path.rmdir
+ monkeypatch.setattr(Path, "rmdir", fail_rmdir)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path(str(folder), recursive=False)
+
+ assert exc.value.code == "permission_denied"
+ assert exc.value.status_code == 403
+
+
+def test_delete_non_recursive_directory_maps_concurrent_missing_to_not_found(tmp_path, monkeypatch):
+ folder = tmp_path / "folder"
+ folder.mkdir()
+
+ def fail_rmdir(self: Path) -> None:
+ if self == folder:
+ raise FileNotFoundError(errno.ENOENT, "missing", str(self))
+ return real_rmdir(self)
+
+ real_rmdir = Path.rmdir
+ monkeypatch.setattr(Path, "rmdir", fail_rmdir)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path(str(folder), recursive=False)
+
+ assert exc.value.code == "not_found"
+ assert exc.value.status_code == 404
+
+
+def test_delete_non_recursive_directory_maps_generic_oserror_to_fs_error(tmp_path, monkeypatch):
+ folder = tmp_path / "folder"
+ folder.mkdir()
+
+ def fail_rmdir(self: Path) -> None:
+ if self == folder:
+ raise OSError(errno.EIO, "io error", str(self))
+ return real_rmdir(self)
+
+ real_rmdir = Path.rmdir
+ monkeypatch.setattr(Path, "rmdir", fail_rmdir)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.delete_path(str(folder), recursive=False)
+
+ assert exc.value.code == "fs_error"
+ assert exc.value.status_code == 400
+
+
+def test_move_overwrite_restores_destination_when_move_fails(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+ destination.write_text("destination", encoding="utf-8")
+
+ def fail_move(_src: Path, _dst: Path, *, on_target_placed=None) -> None:
+ raise OSError("simulated cross-device failure")
+
+ monkeypatch.setattr(fs, "_move_to_absent_target", fail_move)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert source.read_text(encoding="utf-8") == "source"
+ assert destination.read_text(encoding="utf-8") == "destination"
+ assert not list(tmp_path.glob(".destination.txt.avibe-overwrite-*"))
+
+
+def test_move_overwrite_uses_bounded_backup_name_for_long_destination(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ source.write_text("source", encoding="utf-8")
+ long_name = "d" * 255
+ destination = tmp_path / long_name
+ destination.write_text("destination", encoding="utf-8")
+ reserved: list[Path] = []
+ real_reserve_backup_path = fs._reserve_backup_path
+
+ def capture_reserve(target: Path) -> Path:
+ backup = real_reserve_backup_path(target)
+ reserved.append(backup)
+ return backup
+
+ monkeypatch.setattr(fs, "_reserve_backup_path", capture_reserve)
+
+ assert fs.move_path(str(source), str(destination), overwrite=True) == {"ok": True}
+
+ assert destination.read_text(encoding="utf-8") == "source"
+ assert len(reserved) == 1
+ assert reserved[0].parent == tmp_path
+ assert reserved[0].name.startswith(".avibe-overwrite-")
+ assert len(reserved[0].name) < 64
+ assert long_name not in reserved[0].name
+ assert not reserved[0].exists()
+
+
+def test_move_symlink_onto_its_target_is_refused(tmp_path):
+ real = tmp_path / "real.txt"
+ real.write_bytes(b"original bytes")
+ link = tmp_path / "link"
+ link.symlink_to(real)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(link), str(real), overwrite=True)
+
+ assert exc.value.code == "invalid_move"
+ assert real.read_bytes() == b"original bytes"
+ assert real.is_file()
+ assert not real.is_symlink()
+ assert link.is_symlink()
+
+ other_real = tmp_path / "other-real.txt"
+ other_real.write_text("other", encoding="utf-8")
+ other_link = tmp_path / "other-link"
+ other_link.symlink_to(other_real)
+ destination = tmp_path / "destination.txt"
+ destination.write_text("destination", encoding="utf-8")
+
+ assert fs.move_path(str(other_link), str(destination), overwrite=True) == {"ok": True}
+ assert destination.is_symlink()
+ assert destination.resolve() == other_real
+ assert other_real.read_text(encoding="utf-8") == "other"
+
+
+def test_move_directory_into_own_descendant_is_refused_before_copy(tmp_path, monkeypatch):
+ source = tmp_path / "a"
+ destination_parent = source / "b"
+ destination = destination_parent / "c"
+ destination_parent.mkdir(parents=True)
+ (source / "keep.txt").write_text("keep", encoding="utf-8")
+ copytree_calls: list[tuple[Path, Path]] = []
+
+ def fail_copytree(src: Path, dst: Path, **_kwargs):
+ copytree_calls.append((Path(src), Path(dst)))
+ raise AssertionError("copytree should not run for an invalid self-descendant move")
+
+ monkeypatch.setattr(fs.shutil, "copytree", fail_copytree)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination))
+
+ assert exc.value.code == "invalid_path"
+ assert exc.value.status_code == 400
+ assert source.is_dir()
+ assert (source / "keep.txt").read_text(encoding="utf-8") == "keep"
+ assert copytree_calls == []
+
+
+def test_move_directory_to_sibling_still_succeeds(tmp_path):
+ source = tmp_path / "a"
+ source.mkdir()
+ (source / "keep.txt").write_text("keep", encoding="utf-8")
+ destination = tmp_path / "d"
+
+ assert fs.move_path(str(source), str(destination)) == {"ok": True}
+ assert not source.exists()
+ assert (destination / "keep.txt").read_text(encoding="utf-8") == "keep"
+
+
+def test_move_directory_onto_itself_is_noop(tmp_path):
+ # An exact self-move stays an idempotent no-op — the into-itself guard must only reject
+ # moves into a descendant, not a move onto the source's own path.
+ folder = tmp_path / "a"
+ folder.mkdir()
+ (folder / "keep.txt").write_text("keep", encoding="utf-8")
+
+ assert fs.move_path(str(folder), str(folder)) == {"ok": True}
+ assert (folder / "keep.txt").read_text(encoding="utf-8") == "keep"
+
+
+def test_move_no_overwrite_refuses_target_appearing_after_precheck(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+ destination.write_text("destination", encoding="utf-8")
+
+ real_exists = fs._exists_no_follow
+ monkeypatch.setattr(fs, "_exists_no_follow", lambda p: False if Path(p) == destination else real_exists(p))
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=False)
+
+ assert exc.value.code == "exists"
+ assert source.read_text(encoding="utf-8") == "source"
+ assert destination.read_text(encoding="utf-8") == "destination"
+
+
+def test_move_no_overwrite_hard_link_fallback_rolls_back_when_unlink_fails(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+
+ monkeypatch.setattr(fs, "_glibc_renameat2_noreplace", lambda _src, _dst: (_ for _ in ()).throw(AttributeError()))
+ real_unlink = fs.os.unlink
+
+ def fail_source_unlink(path, *args, **kwargs):
+ if Path(path) == source:
+ raise OSError("cannot unlink source")
+ return real_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(fs.os, "unlink", fail_source_unlink)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=False)
+
+ assert exc.value.code == "fs_error"
+ assert source.exists()
+ assert source.read_text(encoding="utf-8") == "source"
+ assert not destination.exists()
+
+
+def test_move_no_overwrite_hard_link_fallback_still_moves(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+
+ monkeypatch.setattr(fs, "_glibc_renameat2_noreplace", lambda _src, _dst: (_ for _ in ()).throw(AttributeError()))
+
+ assert fs.move_path(str(source), str(destination), overwrite=False) == {"ok": True}
+ assert destination.read_text(encoding="utf-8") == "source"
+ assert not source.exists()
+
+
+def test_move_cross_filesystem_copies_then_removes_source(tmp_path, monkeypatch):
+ # A cross-filesystem move raises EXDEV from the no-replace rename; the move must then
+ # copy the source to a destination-side temp, atomically place it (still no-replace),
+ # and only then remove the original source — never lose data.
+ source = tmp_path / "src.txt"
+ source.write_text("DATA", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst) # temp -> destination succeeds within one filesystem
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+
+ assert fs.move_path(str(source), str(destination), overwrite=False) == {"ok": True}
+ assert destination.read_text(encoding="utf-8") == "DATA"
+ assert not source.exists()
+ # No overwrite-temp siblings left behind.
+ assert not list(tmp_path.glob(".dst.txt.avibe-overwrite-*"))
+
+
+def test_move_cross_filesystem_rolls_back_target_when_source_removal_fails(tmp_path, monkeypatch):
+ source = tmp_path / "src.txt"
+ source.write_text("DATA", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ real_remove_backup_path = fs._remove_backup_path
+
+ def fail_source_removal(path: Path) -> None:
+ if Path(path) == source:
+ raise PermissionError(errno.EACCES, "permission denied", str(path))
+ real_remove_backup_path(path)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+ monkeypatch.setattr(fs, "_remove_backup_path", fail_source_removal)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=False)
+
+ assert exc.value.code == "fs_error"
+ assert source.read_text(encoding="utf-8") == "DATA"
+ assert not destination.exists()
+ assert not list(tmp_path.glob(".dst.txt.avibe-overwrite-*"))
+
+
+def test_move_cross_filesystem_directory_keeps_target_when_source_removal_partially_fails(tmp_path, monkeypatch):
+ source = tmp_path / "src"
+ (source / "nested").mkdir(parents=True)
+ (source / "nested" / "keep.txt").write_text("complete", encoding="utf-8")
+ (source / "partial.txt").write_text("will be removed first", encoding="utf-8")
+ destination = tmp_path / "dst"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ real_remove_backup_path = fs._remove_backup_path
+
+ def fail_source_removal(path: Path) -> None:
+ if Path(path) == source:
+ (source / "partial.txt").unlink()
+ raise PermissionError(errno.EACCES, "permission denied", str(path))
+ real_remove_backup_path(path)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+ monkeypatch.setattr(fs, "_remove_backup_path", fail_source_removal)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=False)
+
+ assert exc.value.code == "fs_error"
+ assert not (source / "partial.txt").exists()
+ assert (destination / "partial.txt").read_text(encoding="utf-8") == "will be removed first"
+ assert (destination / "nested" / "keep.txt").read_text(encoding="utf-8") == "complete"
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_move_cross_filesystem_directory_still_moves(tmp_path, monkeypatch):
+ source = tmp_path / "src"
+ (source / "nested").mkdir(parents=True)
+ (source / "nested" / "keep.txt").write_text("complete", encoding="utf-8")
+ destination = tmp_path / "dst"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+
+ assert fs.move_path(str(source), str(destination), overwrite=False) == {"ok": True}
+ assert not source.exists()
+ assert (destination / "nested" / "keep.txt").read_text(encoding="utf-8") == "complete"
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_move_overwrite_absent_cross_filesystem_still_moves(tmp_path, monkeypatch):
+ source = tmp_path / "src.txt"
+ source.write_text("DATA", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+
+ assert fs.move_path(str(source), str(destination), overwrite=True) == {"ok": True}
+ assert destination.read_text(encoding="utf-8") == "DATA"
+ assert not source.exists()
+ assert not list(tmp_path.glob(".dst.txt.avibe-overwrite-*"))
+
+
+def test_move_overwrite_absent_cross_filesystem_rolls_back_target_when_source_removal_fails(
+ tmp_path, monkeypatch
+):
+ source = tmp_path / "src.txt"
+ source.write_text("DATA", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ real_remove_backup_path = fs._remove_backup_path
+
+ def fail_source_removal(path: Path) -> None:
+ if Path(path) == source:
+ raise PermissionError(errno.EACCES, "permission denied", str(path))
+ real_remove_backup_path(path)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+ monkeypatch.setattr(fs, "_remove_backup_path", fail_source_removal)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert source.read_text(encoding="utf-8") == "DATA"
+ assert not destination.exists()
+ assert not list(tmp_path.glob(".dst.txt.avibe-overwrite-*"))
+
+
+def test_move_overwrite_cross_filesystem_file_restores_backup_when_source_unlink_fails(tmp_path, monkeypatch):
+ source = tmp_path / "src.txt"
+ source.write_text("DATA", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+ destination.write_text("old destination", encoding="utf-8")
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ real_remove_backup_path = fs._remove_backup_path
+
+ def fail_source_removal(path: Path) -> None:
+ if Path(path) == source:
+ raise PermissionError(errno.EACCES, "permission denied", str(path))
+ real_remove_backup_path(path)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+ monkeypatch.setattr(fs, "_remove_backup_path", fail_source_removal)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert source.read_text(encoding="utf-8") == "DATA"
+ assert destination.read_text(encoding="utf-8") == "old destination"
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_move_overwrite_preserves_foreign_target_created_after_backup(tmp_path, monkeypatch):
+ source = tmp_path / "src.txt"
+ source.write_text("source", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+ destination.write_text("old destination", encoding="utf-8")
+
+ def foreign_target_conflict(src: Path, dst: Path, *, on_target_placed=None) -> None:
+ destination.write_text("foreign target", encoding="utf-8")
+ raise fs.ConflictError("exists", "Destination already exists")
+
+ monkeypatch.setattr(fs, "_move_to_absent_target", foreign_target_conflict)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "exists"
+ assert destination.read_text(encoding="utf-8") == "foreign target"
+ backups = list(tmp_path.glob(".avibe-overwrite-*"))
+ assert len(backups) == 1
+ assert backups[0].read_text(encoding="utf-8") == "old destination"
+ assert source.read_text(encoding="utf-8") == "source"
+
+
+def test_move_overwrite_restores_backup_when_move_fails_before_target_placed(tmp_path, monkeypatch):
+ source = tmp_path / "src.txt"
+ source.write_text("source", encoding="utf-8")
+ destination = tmp_path / "dst.txt"
+ destination.write_text("old destination", encoding="utf-8")
+
+ def fail_before_target_placed(src: Path, dst: Path, *, on_target_placed=None) -> None:
+ raise PermissionError(errno.EACCES, "permission denied", str(dst))
+
+ monkeypatch.setattr(fs, "_move_to_absent_target", fail_before_target_placed)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert destination.read_text(encoding="utf-8") == "old destination"
+ assert source.read_text(encoding="utf-8") == "source"
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_move_overwrite_cross_filesystem_directory_keeps_target_when_source_removal_partially_fails(
+ tmp_path, monkeypatch
+):
+ source = tmp_path / "src"
+ (source / "nested").mkdir(parents=True)
+ (source / "nested" / "keep.txt").write_text("complete", encoding="utf-8")
+ (source / "partial.txt").write_text("will be removed first", encoding="utf-8")
+ destination = tmp_path / "dst"
+ destination.mkdir()
+ (destination / "old.txt").write_text("old destination", encoding="utf-8")
+
+ real_rename = fs._os_rename_noreplace
+ calls = {"n": 0}
+
+ def fake_rename(src: Path, dst: Path) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise OSError(errno.EXDEV, "cross-device link")
+ real_rename(src, dst)
+
+ real_remove_backup_path = fs._remove_backup_path
+
+ def fail_source_removal(path: Path) -> None:
+ if Path(path) == source:
+ (source / "partial.txt").unlink()
+ raise PermissionError(errno.EACCES, "permission denied", str(path))
+ real_remove_backup_path(path)
+
+ monkeypatch.setattr(fs, "_os_rename_noreplace", fake_rename)
+ monkeypatch.setattr(fs, "_remove_backup_path", fail_source_removal)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.move_path(str(source), str(destination), overwrite=True)
+
+ assert exc.value.code == "fs_error"
+ assert not (source / "partial.txt").exists()
+ assert not (destination / "old.txt").exists()
+ assert (destination / "partial.txt").read_text(encoding="utf-8") == "will be removed first"
+ assert (destination / "nested" / "keep.txt").read_text(encoding="utf-8") == "complete"
+ assert not list(tmp_path.glob(".avibe-overwrite-*"))
+
+
+def test_symlink_mutations_operate_on_link_not_target(tmp_path):
+ target = tmp_path / "target.txt"
+ target.write_text("target", encoding="utf-8")
+ link = tmp_path / "link.txt"
+ link.symlink_to(target)
+
+ renamed = fs.rename_path(str(link), "renamed.txt")
+ renamed_link = Path(renamed["path"])
+ assert renamed_link.is_symlink()
+ assert target.read_text(encoding="utf-8") == "target"
+
+ fs.delete_path(str(renamed_link))
+ assert not renamed_link.exists()
+ assert target.read_text(encoding="utf-8") == "target"
+
+
+def test_http_routes_return_contract_and_headers(tmp_path):
+ file_path = tmp_path / "note.txt"
+ file_path.write_text("hello", encoding="utf-8")
+ client = app.test_client()
+
+ list_response = client.get(f"/api/files/list?path={tmp_path}&show_hidden=0")
+ assert list_response.status_code == 200
+ assert list_response.get_json()["entries"][0]["name"] == "note.txt"
+
+ meta_response = client.get(f"/api/files/meta?path={file_path}")
+ assert meta_response.get_json()["mime"] == "text/plain"
+
+ content_response = client.get(f"/api/files/content?path={file_path}")
+ assert content_response.status_code == 200
+ assert content_response.content == b"hello"
+ assert content_response.headers["X-Content-Type-Options"] == "nosniff"
+ assert content_response.headers["Content-Disposition"].startswith("inline;")
+
+ download_response = client.get(f"/api/files/content?path={file_path}&download=1")
+ assert download_response.headers["Content-Disposition"].startswith("attachment;")
+
+
+def test_http_routes_map_structured_errors_and_enforce_csrf(tmp_path):
+ client = app.test_client()
+ missing = client.get(f"/api/files/meta?path={tmp_path / 'missing.txt'}")
+ assert missing.status_code == 404
+ assert missing.get_json() == {
+ "ok": False,
+ "error": {"code": "not_found", "message": "Path not found"},
+ }
+
+ write_path = tmp_path / "new.txt"
+ blocked = client.put("/api/files/write", json={"path": str(write_path), "content": "x"})
+ assert blocked.status_code == 403
+
+ ok = client.put(
+ "/api/files/write",
+ json={"path": str(write_path), "content": "x"},
+ headers=csrf_headers(client),
+ )
+ assert ok.status_code == 200
+ assert ok.get_json()["ok"] is True
+ assert write_path.read_text(encoding="utf-8") == "x"
+
+
+def test_http_delete_and_move_string_false_flags_are_not_truthy(tmp_path):
+ client = app.test_client()
+ headers = csrf_headers(client)
+
+ folder = tmp_path / "folder"
+ folder.mkdir()
+ (folder / "child.txt").write_text("child", encoding="utf-8")
+ delete_response = client.post(
+ "/api/files/delete",
+ json={"path": str(folder), "recursive": "false"},
+ headers=headers,
+ )
+ assert delete_response.status_code == 409
+ assert folder.exists()
+
+ source = tmp_path / "source.txt"
+ destination = tmp_path / "destination.txt"
+ source.write_text("source", encoding="utf-8")
+ destination.write_text("destination", encoding="utf-8")
+ move_response = client.post(
+ "/api/files/move",
+ json={"src": str(source), "dst": str(destination), "overwrite": "false"},
+ headers=headers,
+ )
+ assert move_response.status_code == 409
+ assert source.read_text(encoding="utf-8") == "source"
+ assert destination.read_text(encoding="utf-8") == "destination"
+
+
+def test_startup_reconcile_skips_tmux_when_env_set(monkeypatch):
+ from vibe import api
+
+ monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: {"ok": True, "installed": True})
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+
+ import core.show_runtime as srt_mod
+ import core.tmux_runtime as tmux_mod
+
+ class _Mgr:
+ def status(self):
+ return {"installed": False, "node_available": False, "node_version": None}
+
+ monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())
+
+ calls = []
+ monkeypatch.delenv("VIBE_INSTALL_SKIP_TMUX", raising=False)
+ monkeypatch.setattr(tmux_mod, "ensure_tmux_installed", lambda force=False: calls.append(force) or {"ok": True})
+ out_without_skip = api.reconcile_startup_dependencies()
+ assert out_without_skip["tmux"] == {"ok": True}
+ assert calls == [False]
+
+ monkeypatch.setenv("VIBE_INSTALL_SKIP_TMUX", "yes")
+ monkeypatch.setattr(tmux_mod, "ensure_tmux_installed", lambda force=False: pytest.fail("tmux install should be skipped"))
+ out_with_skip = api.reconcile_startup_dependencies()
+
+ assert out_with_skip["tmux"] == {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_TMUX"}
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 8836bc5da..d7c2d449d 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -572,7 +572,8 @@ def test_dependencies_status_shape(monkeypatch):
out = api.dependencies_status()
assert out["ok"]
by = {d["id"]: d for d in out["deps"]}
- assert list(by) == ["askill", "avault", "show-runtime", "node"]
+ assert list(by) == ["askill", "avault", "show-runtime", "tmux", "node"]
+ assert "tmux" in by and by["tmux"]["required"] is False # tmux is the optional terminal backend
assert by["askill"]["status"] == "ready" and by["askill"]["version"] == "0.1.13" and by["askill"]["required"]
assert by["askill"]["latest_version"] is None and by["askill"]["has_update"] is False
assert by["avault"]["status"] == "ready" and by["avault"]["version"] == "0.0.1" and by["avault"]["required"]
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 7547d32a9..5f73b131f 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -1,6 +1,8 @@
import json
from dataclasses import dataclass
+import pytest
+
from config import paths
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir, show_cli_event_token, show_page_payload
@@ -14,6 +16,27 @@ class _FakeShowRuntimeResult:
reason: str | None = None
+def _stub_runtime_prepare_dependencies(monkeypatch, *, askill_result=None, avault_result=None, tmux_result=None):
+ calls = {"askill": [], "avault": [], "tmux": []}
+
+ def fake_askill(offline=False):
+ calls["askill"].append({"offline": offline})
+ return askill_result or {"ok": True, "installed": True}
+
+ def fake_avault(offline=False):
+ calls["avault"].append({"offline": offline})
+ return avault_result or {"ok": True, "installed": True}
+
+ def fake_tmux(offline=False, force=False):
+ calls["tmux"].append({"offline": offline, "force": force})
+ return tmux_result or {"ok": True, "installed": True}
+
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", fake_askill)
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
+ monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", fake_tmux)
+ return calls
+
+
def test_show_without_subcommand_prints_help(capsys):
parser = cli.build_parser()
args = parser.parse_args(["show"])
@@ -40,8 +63,7 @@ def test_runtime_prepare_cli_reports_warning_only_failure(monkeypatch, capsys):
return {"ok": False, "reason": "runtime_node_missing"}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
- monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
- monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ calls = _stub_runtime_prepare_dependencies(monkeypatch)
assert cli.cmd_runtime(args) == 0
payload = json.loads(capsys.readouterr().out)
@@ -49,6 +71,8 @@ def test_runtime_prepare_cli_reports_warning_only_failure(monkeypatch, capsys):
assert payload["reason"] == "runtime_node_missing"
assert payload["askill"] == {"ok": True, "installed": True}
assert payload["avault"] == {"ok": True, "installed": True}
+ assert payload["tmux"] == {"ok": True, "installed": True}
+ assert calls["tmux"] == [{"offline": False, "force": False}]
def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
@@ -62,10 +86,10 @@ def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
return {"ok": True}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
- monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
- monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ calls = _stub_runtime_prepare_dependencies(monkeypatch)
assert cli.cmd_runtime(args) == 0
+ assert calls["tmux"] == [{"offline": False, "force": False}]
def test_runtime_manager_from_args_preserves_offline_environment(monkeypatch, tmp_path):
@@ -88,17 +112,17 @@ def test_runtime_prepare_cli_strict_fails_when_prepare_fails(monkeypatch, capsys
return {"ok": False, "reason": "runtime_archive_download_failed"}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
- monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
- monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ calls = _stub_runtime_prepare_dependencies(monkeypatch)
assert cli.cmd_runtime(args) == 1
assert "runtime_archive_download_failed" in capsys.readouterr().err
+ assert calls["tmux"] == [{"offline": False, "force": False}]
def test_runtime_prepare_cli_skips_avault_offline(monkeypatch, capsys):
parser = cli.build_parser()
args = parser.parse_args(["runtime", "prepare", "--offline", "--json"])
- seen = {"askill": None, "avault": None}
+ seen = {"askill": None, "avault": None, "tmux": None}
class FakeRuntimeManager:
def prepare(self, *, force=False, offline=None):
@@ -113,14 +137,58 @@ def test_runtime_prepare_cli_skips_avault_offline(monkeypatch, capsys):
seen["avault"] = offline
return {"ok": True, "skipped": True, "reason": "offline"}
+ def fake_tmux(offline=False, force=False):
+ seen["tmux"] = {"offline": offline, "force": force}
+ return {"ok": True, "skipped": True, "reason": "offline"}
+
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", fake_askill)
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
+ monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", fake_tmux)
assert cli.cmd_runtime(args) == 0
payload = json.loads(capsys.readouterr().out)
- assert seen == {"askill": True, "avault": True}
+ assert seen == {"askill": True, "avault": True, "tmux": {"offline": True, "force": False}}
assert payload["avault"] == {"ok": True, "skipped": True, "reason": "offline"}
+ assert payload["tmux"] == {"ok": True, "skipped": True, "reason": "offline"}
+
+
+def test_runtime_prepare_cli_prints_status_skipped_tmux_as_skipped(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "prepare"])
+
+ class FakeRuntimeManager:
+ def prepare(self, *, force=False, offline=None):
+ return {"ok": True}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ _stub_runtime_prepare_dependencies(
+ monkeypatch,
+ tmux_result={"ok": True, "status": "skipped", "reason": "terminal_disabled"},
+ )
+
+ assert cli.cmd_runtime(args) == 0
+ captured = capsys.readouterr()
+ assert "tmux: skipped (terminal_disabled)." in captured.out
+ assert "tmux ready." not in captured.out
+
+
+def test_runtime_prepare_tmux_respects_terminal_disabled(monkeypatch):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")
+ monkeypatch.delenv("VIBE_INSTALL_SKIP_TMUX", raising=False)
+ monkeypatch.setattr("core.tmux_runtime.ensure_tmux_installed", lambda force=False: pytest.fail("tmux install should be skipped"))
+
+ assert cli._ensure_tmux_during_prepare() == {"ok": True, "status": "skipped", "reason": "terminal_disabled"}
+
+
+def test_runtime_prepare_tmux_runs_when_terminal_enabled(monkeypatch):
+ calls = []
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.delenv("VIBE_INSTALL_SKIP_TMUX", raising=False)
+ monkeypatch.setattr("core.tmux_runtime.ensure_tmux_installed", lambda force=False: calls.append(force) or {"ok": True})
+
+ assert cli._ensure_tmux_during_prepare(force=True) == {"ok": True}
+ assert calls == [True]
def _save_config() -> V2Config:
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
new file mode 100644
index 000000000..de88f8d46
--- /dev/null
+++ b/tests/test_terminal_backend.py
@@ -0,0 +1,1141 @@
+from __future__ import annotations
+
+import asyncio
+import errno
+import json
+import os
+import signal
+import struct
+
+import pytest
+
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="terminal PTY tests require POSIX")
+
+fcntl = pytest.importorskip("fcntl")
+termios = pytest.importorskip("termios")
+
+from starlette.websockets import WebSocketDisconnect
+
+from core import terminal_service
+from core.terminal_service import (
+ TerminalService,
+ _Phase,
+ _Session,
+ _tmux_launch_command,
+ _tmux_socket_name,
+ sanitize_session_id,
+)
+from vibe import ui_server
+from vibe.ui_server import app
+
+
+class _FakeWebSocket:
+ def __init__(self, messages: list[dict]) -> None:
+ self._messages = list(messages)
+ self.sent_bytes: list[bytes] = []
+ self.sent_text: list[str] = []
+
+ async def receive(self) -> dict:
+ if not self._messages:
+ await asyncio.sleep(0.05)
+ return {"type": "websocket.disconnect", "code": 1000}
+ message = self._messages.pop(0)
+ if delay := message.pop("delay", None):
+ await asyncio.sleep(delay)
+ return message
+
+ async def send_bytes(self, payload: bytes) -> None:
+ self.sent_bytes.append(payload)
+
+ async def send_text(self, payload: str) -> None:
+ self.sent_text.append(payload)
+
+
+class _RecordingWebSocket:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, int | None]] = []
+
+ async def accept(self) -> None:
+ self.calls.append(("accept", None))
+
+ async def close(self, code: int = 1000) -> None:
+ self.calls.append(("close", code))
+
+
+def test_terminal_ephemeral_pty_round_trip(monkeypatch, tmp_path):
+ asyncio.run(_terminal_ephemeral_pty_round_trip(monkeypatch, tmp_path))
+
+
+async def _terminal_ephemeral_pty_round_trip(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("LANG", "C")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ websocket = _FakeWebSocket(
+ [
+ {"type": "websocket.receive", "bytes": b"printf READY\\\\n; exit 7\n", "delay": 0.1},
+ {"type": "websocket.disconnect", "code": 1000, "delay": 0.5},
+ ]
+ )
+
+ await service.handle_websocket(websocket, "term_1")
+ await service.shutdown()
+
+ assert json.loads(websocket.sent_text[0]) == {"type": "ready", "persistent": False}
+ output = b"".join(websocket.sent_bytes)
+ assert b"READY" in output
+ assert json.loads(websocket.sent_text[-1]) == {"type": "exit", "code": 7}
+
+
+def test_terminal_websocket_cancels_siblings_on_pump_failure(monkeypatch, tmp_path):
+ asyncio.run(_terminal_websocket_cancels_siblings_on_pump_failure(monkeypatch, tmp_path))
+
+
+async def _terminal_websocket_cancels_siblings_on_pump_failure(monkeypatch, tmp_path):
+ # If a pump dies with anything other than WebSocketDisconnect (e.g. EBADF when a fast
+ # reconnect/shutdown closes the PTY fd), handle_websocket must still cancel the sibling
+ # tasks instead of letting them outlive the torn-down connection.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+
+ input_cancelled = asyncio.Event()
+
+ async def exploding_output(_websocket, _connection):
+ raise OSError(errno.EBADF, "Bad file descriptor")
+
+ async def blocking_input(_websocket, _connection):
+ try:
+ await asyncio.Event().wait() # only a cancel ends this
+ except asyncio.CancelledError:
+ input_cancelled.set()
+ raise
+
+ monkeypatch.setattr(service, "_pump_output", exploding_output)
+ monkeypatch.setattr(service, "_pump_input", blocking_input)
+
+ try:
+ with pytest.raises(OSError) as exc:
+ await service.handle_websocket(_FakeWebSocket([]), "term_leak")
+ assert exc.value.errno == errno.EBADF
+ # The sibling input pump was cancelled (not leaked), and no terminal-* task is left
+ # pending after the connection tore down.
+ assert input_cancelled.is_set()
+ leaked = [
+ task
+ for task in asyncio.all_tasks()
+ if task is not asyncio.current_task() and "terminal-" in task.get_name() and not task.done()
+ ]
+ assert leaked == []
+ finally:
+ await service.shutdown()
+
+
+def test_shutdown_kills_whole_tmux_server_including_untracked(monkeypatch):
+ asyncio.run(_shutdown_kills_whole_tmux_server_including_untracked(monkeypatch))
+
+
+async def _shutdown_kills_whole_tmux_server_including_untracked(monkeypatch):
+ # A persistent session orphaned by a prior crashed/restarted process is on our tmux socket
+ # but absent from this process's registry. Shutdown must kill the whole server on our
+ # private socket — not just tracked entries — so `vibe stop` leaves no detached shell.
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+ commands: list[tuple] = []
+
+ class _FakeProcess:
+ async def wait(self) -> int:
+ return 0
+
+ async def fake_spawn(*args, **_kwargs):
+ commands.append(tuple(args))
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ # Empty registry: this process tracks nothing, so only a whole-server kill can reap orphans.
+ await service.shutdown()
+
+ socket = terminal_service._tmux_socket_name()
+ kill_cmds = [cmd for cmd in commands if "kill-server" in cmd]
+ assert kill_cmds, commands
+ cmd = kill_cmds[0]
+ assert "-L" in cmd and socket in cmd
+ # kill-server must be the COMMAND (trailing token after the global flags), and /dev/null
+ # must be the argument consumed by -f — not itself parsed as the command. This guards the
+ # arg ORDER, not just membership: `tmux -L <sock> -f /dev/null kill-server`.
+ assert cmd[-1] == "kill-server"
+ assert cmd[cmd.index("/dev/null") - 1] == "-f"
+
+
+def test_open_spawns_with_start_new_session_not_preexec(monkeypatch, tmp_path):
+ asyncio.run(_open_spawns_with_start_new_session_not_preexec(monkeypatch, tmp_path))
+
+
+async def _open_spawns_with_start_new_session_not_preexec(monkeypatch, tmp_path):
+ # A Python preexec_fn can deadlock the forked child if another thread holds a lock at fork
+ # time; the process group must be created via start_new_session (C-level setsid) instead.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+
+ captured: dict = {}
+
+ class _FakeProcess:
+ returncode = None
+ pid = 4321
+
+ async def wait(self) -> int:
+ return 0
+
+ async def fake_spawn(*_args, **kwargs):
+ captured.update(kwargs)
+ return _FakeProcess()
+
+ opened_fds: list[int] = []
+
+ def fake_openpty():
+ master = os.open(os.devnull, os.O_RDWR)
+ slave = os.open(os.devnull, os.O_RDWR)
+ opened_fds.extend([master, slave])
+ return master, slave
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+ monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+ try:
+ await service.open("spawn")
+ assert captured.get("start_new_session") is True
+ assert "preexec_fn" not in captured
+ finally:
+ await service.shutdown()
+ for fd in opened_fds:
+ terminal_service._close_fd(fd)
+
+
+def test_terminal_reconnect_replaces_session(monkeypatch, tmp_path):
+ asyncio.run(_terminal_reconnect_replaces_session(monkeypatch, tmp_path))
+
+
+async def _terminal_reconnect_replaces_session(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ try:
+ first = await service.open("dup")
+ second = await service.open("dup")
+ # Reconnecting the same id reuses one slot; the old connection is
+ # replaced (and its shell terminated), not orphaned past max_sessions.
+ assert len(service._sessions) == 1
+ assert service._sessions["dup"].connection is second
+ assert first.process.returncode is not None
+ finally:
+ await service.shutdown()
+
+
+def test_reconnect_clears_detached_bookkeeping(monkeypatch, tmp_path):
+ asyncio.run(_reconnect_clears_detached_bookkeeping(monkeypatch, tmp_path))
+
+
+async def _reconnect_clears_detached_bookkeeping(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+ await _set_tmux_has_session(monkeypatch, True)
+
+ class _FakeProcess:
+ returncode = None
+ pid = None
+
+ async def wait(self) -> int:
+ return 0
+
+ async def fake_spawn(*_args, **_kwargs):
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+
+ opened_fds: list[int] = []
+
+ def fake_openpty():
+ master = os.open(os.devnull, os.O_RDWR)
+ slave = os.open(os.devnull, os.O_RDWR)
+ opened_fds.extend([master, slave])
+ return master, slave
+
+ monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ existing = _make_persistent_connection("id", process=_LiveProcess())
+ service._sessions["id"] = _Session("id", _Phase.ATTACHED, persistent=True, connection=existing)
+
+ try:
+ spawned = await service.open("id")
+ # One entry per id: the reconnect transitions the slot in place — ATTACHED to the new
+ # client, never simultaneously DETACHED. The old three-collection desync (an id in
+ # both _connections and _detached_tmux_sessions) is structurally impossible now.
+ assert list(service._sessions) == ["id"]
+ assert service._sessions["id"].phase is _Phase.ATTACHED
+ assert service._sessions["id"].connection is spawned
+ finally:
+ await service.shutdown()
+ for fd in opened_fds:
+ terminal_service._close_fd(fd)
+
+
+def test_terminal_resize_applies_winsize(monkeypatch, tmp_path):
+ asyncio.run(_terminal_resize_applies_winsize(monkeypatch, tmp_path))
+
+
+async def _terminal_resize_applies_winsize(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ connection = await service.open("resize")
+ try:
+ await service.resize(connection, cols=100, rows=35)
+ packed = fcntl.ioctl(connection.master_fd, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0))
+ rows, cols, _, _ = struct.unpack("HHHH", packed)
+ assert (rows, cols) == (35, 100)
+ finally:
+ await service.close(connection)
+ await service.shutdown()
+
+
+def test_terminal_tmux_launch_command_uses_safe_session():
+ cmd = _tmux_launch_command("/tmp/tmux", sanitize_session_id("../bad session!"))
+
+ assert cmd[0:3] == ["/tmp/tmux", "-L", _tmux_socket_name()]
+ assert cmd[3:] == [
+ "-f",
+ "/dev/null",
+ "new-session",
+ "-A",
+ "-s",
+ "bad_session",
+ ";",
+ "set-option",
+ "-g",
+ "status",
+ "off",
+ ]
+ assert _tmux_socket_name().startswith("avibe-")
+
+
+def test_terminal_open_reserves_session_slot_during_spawn(monkeypatch, tmp_path):
+ asyncio.run(_terminal_open_reserves_session_slot_during_spawn(monkeypatch, tmp_path))
+
+
+async def _terminal_open_reserves_session_slot_during_spawn(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+ spawn_started = asyncio.Event()
+ release_spawn = asyncio.Event()
+ original_spawn = asyncio.create_subprocess_exec
+
+ async def delayed_spawn(*args, **kwargs):
+ spawn_started.set()
+ await release_spawn.wait()
+ return await original_spawn(*args, **kwargs)
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", delayed_spawn)
+
+ first_task = asyncio.create_task(service.open("first"))
+ await spawn_started.wait()
+ with pytest.raises(terminal_service.TerminalServiceError):
+ await service.open("second")
+
+ release_spawn.set()
+ connection = await first_task
+ try:
+ assert service._sessions["first"].connection is connection
+ finally:
+ await service.shutdown()
+
+
+def test_open_releases_reserved_slot_on_cancel(monkeypatch, tmp_path):
+ asyncio.run(_open_releases_reserved_slot_on_cancel(monkeypatch, tmp_path))
+
+
+async def _open_releases_reserved_slot_on_cancel(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+ spawn_started = asyncio.Event()
+ original_spawn = asyncio.create_subprocess_exec
+
+ # Track the PTY master fds so we can assert the cancelled spawn closed its own.
+ opened_masters: list[int] = []
+ real_openpty = terminal_service.os.openpty
+ closed_fds: list[int] = []
+ real_close_fd = terminal_service._close_fd
+
+ def tracking_openpty():
+ master, slave = real_openpty()
+ opened_masters.append(master)
+ return master, slave
+
+ def tracking_close_fd(fd: int) -> None:
+ closed_fds.append(fd)
+ real_close_fd(fd)
+
+ monkeypatch.setattr(terminal_service.os, "openpty", tracking_openpty)
+ monkeypatch.setattr(terminal_service, "_close_fd", tracking_close_fd)
+
+ async def delayed_spawn(*_args, **_kwargs):
+ spawn_started.set()
+ await asyncio.sleep(60)
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", delayed_spawn)
+
+ open_task = asyncio.create_task(service.open("cancelled"))
+ await spawn_started.wait()
+ open_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await open_task
+
+ assert "cancelled" not in service._sessions # the OPENING placeholder was reconciled away
+ # The PTY master opened for the cancelled spawn must be closed, not leaked.
+ assert opened_masters, "openpty was not called"
+ assert opened_masters[0] in closed_fds
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", original_spawn)
+ connection = await service.open("next")
+ try:
+ assert service._sessions["next"].connection is connection
+ finally:
+ await service.shutdown()
+
+
+def test_ready_frame_failure_closes_connection(monkeypatch, tmp_path):
+ asyncio.run(_ready_frame_failure_closes_connection(monkeypatch, tmp_path))
+
+
+async def _ready_frame_failure_closes_connection(monkeypatch, tmp_path):
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+
+ class _DisconnectingWebSocket(_FakeWebSocket):
+ async def send_text(self, payload: str) -> None:
+ raise RuntimeError("client dropped before ready")
+
+ with pytest.raises(RuntimeError, match="client dropped"):
+ await service.handle_websocket(_DisconnectingWebSocket([]), "drop")
+
+ try:
+ assert service._sessions == {}
+ finally:
+ await service.shutdown()
+
+
+def test_detached_session_tracked_when_client_exits(monkeypatch, tmp_path):
+ asyncio.run(_detached_session_tracked_when_client_exits(monkeypatch, tmp_path))
+
+
+class _ExitedProcess:
+ returncode = 0
+ pid = None
+
+ async def wait(self) -> int:
+ return 0
+
+
+class _LiveProcess:
+ returncode = None
+ pid = None
+
+ async def wait(self) -> int:
+ return 0
+
+
+def _make_persistent_connection(
+ session_id: str,
+ *,
+ process=None,
+) -> "terminal_service.TerminalConnection":
+ fd = os.open(os.devnull, os.O_RDWR)
+ return terminal_service.TerminalConnection(
+ session_id=session_id,
+ process=process or _ExitedProcess(),
+ master_fd=fd,
+ persistent=True,
+ attached_at=0.0,
+ last_seen=0.0,
+ )
+
+
+async def _set_tmux_has_session(monkeypatch, exists: bool) -> None:
+ async def _has_session(_session_id: str) -> bool:
+ return exists
+
+ monkeypatch.setattr(terminal_service, "_tmux_has_session", _has_session)
+
+
+def test_detached_session_tracked_when_client_exits(monkeypatch, tmp_path):
+ asyncio.run(_detached_session_tracked_when_client_exits(monkeypatch, tmp_path))
+
+
+async def _detached_session_tracked_when_client_exits(monkeypatch, tmp_path):
+ # A persistent (tmux) connection whose client process has already exited — e.g. the
+ # user hit tmux's detach key — must transition to DETACHED WHEN THE SESSION IS STILL
+ # ALIVE, or it goes uncounted against max_sessions, unreaped, and unkilled.
+ await _set_tmux_has_session(monkeypatch, True)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ conn = _make_persistent_connection("detached", process=_ExitedProcess())
+ service._sessions["detached"] = _Session("detached", _Phase.ATTACHED, persistent=True, connection=conn)
+
+ await service.close(conn)
+
+ assert service._sessions["detached"].phase is _Phase.DETACHED
+
+
+def test_dead_session_not_tracked_when_shell_exits(monkeypatch, tmp_path):
+ asyncio.run(_dead_session_not_tracked_when_shell_exits(monkeypatch, tmp_path))
+
+
+async def _dead_session_not_tracked_when_shell_exits(monkeypatch, tmp_path):
+ # When the shell inside tmux exits (rather than a detach), the client process exits AND
+ # the tmux session is gone — it must NOT be left tracked, or a dead id counts against
+ # max_sessions until the idle timeout.
+ await _set_tmux_has_session(monkeypatch, False)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ conn = _make_persistent_connection("ended", process=_ExitedProcess())
+ service._sessions["ended"] = _Session("ended", _Phase.ATTACHED, persistent=True, connection=conn)
+
+ await service.close(conn)
+
+ assert "ended" not in service._sessions
+
+
+def test_detach_not_recorded_when_session_gone_despite_live_client(monkeypatch, tmp_path):
+ asyncio.run(_detach_not_recorded_when_session_gone_despite_live_client(monkeypatch, tmp_path))
+
+
+async def _detach_not_recorded_when_session_gone_despite_live_client(monkeypatch, tmp_path):
+ await _set_tmux_has_session(monkeypatch, False)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ conn = _make_persistent_connection("raced", process=_LiveProcess())
+ service._sessions["raced"] = _Session("raced", _Phase.ATTACHED, persistent=True, connection=conn)
+
+ await service.close(conn)
+
+ assert "raced" not in service._sessions
+
+
+def test_superseded_close_leaves_live_session(monkeypatch, tmp_path):
+ asyncio.run(_superseded_close_leaves_live_session(monkeypatch, tmp_path))
+
+
+async def _superseded_close_leaves_live_session(monkeypatch, tmp_path):
+ # A fast reconnect already registered a new connection for this id; the OLD connection's
+ # close must not touch the registry — no double-count, and the reaper must not later kill
+ # the session out from under the live client.
+ await _set_tmux_has_session(monkeypatch, True)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ live = _make_persistent_connection("id", process=_LiveProcess())
+ service._sessions["id"] = _Session("id", _Phase.ATTACHED, persistent=True, connection=live)
+ superseded = _make_persistent_connection("id", process=_ExitedProcess())
+
+ await service.close(superseded)
+
+ assert service._sessions["id"].connection is live
+ assert service._sessions["id"].phase is _Phase.ATTACHED
+ await service.shutdown()
+
+
+def test_open_failure_preserves_detached_session(monkeypatch, tmp_path):
+ asyncio.run(_open_failure_preserves_detached_session(monkeypatch, tmp_path))
+
+
+async def _open_failure_preserves_detached_session(monkeypatch, tmp_path):
+ # Reconnecting to a DETACHED session whose spawn then fails must leave the (still-alive)
+ # tmux session tracked as DETACHED — never drop it into an untracked orphan.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+ await _set_tmux_has_session(monkeypatch, True)
+
+ async def failing_spawn(*_args, **_kwargs):
+ raise OSError("spawn failed")
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", failing_spawn)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+ service._sessions["id"] = _Session("id", _Phase.DETACHED, persistent=True, detached_at=1.0)
+
+ with pytest.raises(OSError, match="spawn failed"):
+ await service.open("id")
+
+ assert service._sessions["id"].phase is _Phase.DETACHED
+ await service.shutdown()
+
+
+def test_abandoned_open_kills_orphan_tmux_session(monkeypatch, tmp_path):
+ asyncio.run(_abandoned_open_kills_orphan_tmux_session(monkeypatch, tmp_path))
+
+
+async def _abandoned_open_kills_orphan_tmux_session(monkeypatch, tmp_path):
+ # When the OPENING slot is gone (service shutting down) after a persistent child spawned,
+ # _abandon_open must KILL the tmux session, not merely detach it — otherwise a terminal
+ # opened during `vibe stop` leaves an orphaned tmux server.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+
+ killed: list[str] = []
+
+ async def fake_kill(session_id: str) -> None:
+ killed.append(session_id)
+
+ monkeypatch.setattr(terminal_service, "_kill_tmux_session", fake_kill)
+
+ opened_fds: list[int] = []
+
+ def fake_openpty():
+ master = os.open(os.devnull, os.O_RDWR)
+ slave = os.open(os.devnull, os.O_RDWR)
+ opened_fds.extend([master, slave])
+ return master, slave
+
+ monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+
+ class _FakeProcess:
+ returncode = None
+ pid = None
+
+ def send_signal(self, signum: int) -> None:
+ pass
+
+ async def wait(self) -> int:
+ return 0
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+
+ async def fake_spawn(*_args, **_kwargs):
+ service._sessions.clear() # simulate shutdown winning the race mid-spawn
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+
+ try:
+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):
+ await service.open("orphan")
+ assert "orphan" in killed # the orphaned tmux session was killed, not just detached
+ finally:
+ for fd in opened_fds:
+ terminal_service._close_fd(fd)
+
+
+def test_reaper_retracks_dead_client_with_live_session(monkeypatch, tmp_path):
+ asyncio.run(_reaper_retracks_dead_client_with_live_session(monkeypatch, tmp_path))
+
+
+async def _reaper_retracks_dead_client_with_live_session(monkeypatch, tmp_path):
+ # A tmux client can exit (returncode set) while its session is still alive (the user
+ # detached). If the reaper sees it before close() runs, it must reconcile via has-session
+ # and re-track it as DETACHED — not silently drop a live, uncounted session.
+ await _set_tmux_has_session(monkeypatch, True)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ conn = _make_persistent_connection("d", process=_ExitedProcess())
+ service._sessions["d"] = _Session("d", _Phase.ATTACHED, persistent=True, connection=conn)
+
+ await service.reap_idle()
+
+ assert service._sessions["d"].phase is _Phase.DETACHED
+
+
+def test_forget_finished_keeps_persistent_dead_session(monkeypatch, tmp_path):
+ asyncio.run(_forget_finished_keeps_persistent_dead_session(monkeypatch, tmp_path))
+
+
+async def _forget_finished_keeps_persistent_dead_session(monkeypatch, tmp_path):
+ # open()'s synchronous GC must not drop a persistent (tmux) session whose client process
+ # exited — its tmux session may still be alive (a prefix-key detach), so dropping it here
+ # would untrack a live session. Ephemeral dead clients have no session and are dropped.
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=4)
+ pconn = _make_persistent_connection("p", process=_ExitedProcess())
+ service._sessions["p"] = _Session("p", _Phase.ATTACHED, persistent=True, connection=pconn)
+ efd = os.open(os.devnull, os.O_RDWR)
+ econn = terminal_service.TerminalConnection("e", _ExitedProcess(), efd, False, 0.0, 0.0)
+ service._sessions["e"] = _Session("e", _Phase.ATTACHED, persistent=False, connection=econn)
+
+ service._forget_finished_locked()
+
+ assert "p" in service._sessions # persistent dead kept (reaper finalize reconciles via has-session)
+ assert "e" not in service._sessions # ephemeral dead dropped (no tmux session to preserve)
+ terminal_service._close_fd(pconn.master_fd)
+ terminal_service._close_fd(efd)
+
+
+def test_reaper_keeps_detached_registered_until_kill_completes(monkeypatch, tmp_path):
+ asyncio.run(_reaper_keeps_detached_registered_until_kill_completes(monkeypatch, tmp_path))
+
+
+async def _reaper_keeps_detached_registered_until_kill_completes(monkeypatch, tmp_path):
+ # An expired DETACHED session must stay registered (counted) while its async kill runs,
+ # and only be removed once the kill completes — so a reconnect in that gap isn't dropped
+ # from the cap or silently killed.
+ gate = asyncio.Event()
+ killed: list[str] = []
+
+ async def gated_kill(session_id: str) -> None:
+ killed.append(session_id)
+ await gate.wait()
+
+ monkeypatch.setattr(terminal_service, "_kill_tmux_session", gated_kill)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ service._sessions["d"] = _Session("d", _Phase.DETACHED, persistent=True, detached_at=0.0)
+
+ reap_task = asyncio.create_task(service.reap_idle())
+ await asyncio.sleep(0.02) # reaper marks CLOSING and parks in the gated kill
+
+ assert killed == ["d"]
+ assert "d" in service._sessions # still registered during the kill
+ assert service._sessions["d"].phase is _Phase.CLOSING
+
+ gate.set()
+ await reap_task
+ assert "d" not in service._sessions # removed once the kill completed
+
+
+def test_reconnect_during_closing_is_rejected(monkeypatch, tmp_path):
+ asyncio.run(_reconnect_during_closing_is_rejected(monkeypatch, tmp_path))
+
+
+async def _reconnect_during_closing_is_rejected(monkeypatch, tmp_path):
+ # While a session is tearing down (CLOSING) — e.g. the reaper is awaiting its kill — a
+ # reconnect must be rejected with session_opening, not allowed to reattach to a session
+ # that is about to be killed. The client retries once teardown finishes.
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ conn = _make_persistent_connection("c", process=_ExitedProcess())
+ service._sessions["c"] = _Session("c", _Phase.CLOSING, persistent=True, connection=conn)
+
+ try:
+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):
+ await service.open("c")
+ finally:
+ service._sessions.clear()
+ terminal_service._close_fd(conn.master_fd)
+
+
+def test_reconnect_window_session_killed_on_shutdown(monkeypatch, tmp_path):
+ asyncio.run(_reconnect_window_session_killed_on_shutdown(monkeypatch, tmp_path))
+
+
+async def _reconnect_window_session_killed_on_shutdown(monkeypatch, tmp_path):
+ # When a reconnect overwrites a persistent session's slot with an OPENING placeholder, the
+ # placeholder must carry persistent=True so a shutdown landing in that window still kills
+ # the replaced tmux session instead of leaking it after `vibe stop`.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+
+ killed: list[str] = []
+
+ async def fake_kill(session_id: str) -> None:
+ killed.append(session_id)
+
+ monkeypatch.setattr(terminal_service, "_kill_tmux_session", fake_kill)
+
+ opened_fds: list[int] = []
+
+ def fake_openpty():
+ master = os.open(os.devnull, os.O_RDWR)
+ slave = os.open(os.devnull, os.O_RDWR)
+ opened_fds.extend([master, slave])
+ return master, slave
+
+ monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+
+ spawn_started = asyncio.Event()
+ gate = asyncio.Event()
+
+ class _FakeProcess:
+ returncode = None
+ pid = None
+
+ def send_signal(self, signum: int) -> None:
+ pass
+
+ async def wait(self) -> int:
+ return 0
+
+ async def gated_spawn(*_args, **_kwargs):
+ spawn_started.set()
+ await gate.wait()
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", gated_spawn)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ old = _make_persistent_connection("s", process=_LiveProcess())
+ service._sessions["s"] = _Session("s", _Phase.ATTACHED, persistent=True, connection=old)
+
+ reopen = asyncio.create_task(service.open("s"))
+ await spawn_started.wait() # reconnect overwrote the slot with OPENING and parked mid-spawn
+
+ assert service._sessions["s"].phase is _Phase.OPENING
+ assert service._sessions["s"].persistent is True # placeholder stays visible to shutdown
+
+ # shutdown() now also kills the whole tmux server; stub that out so it doesn't block on the
+ # gated open-spawn above. This test asserts the tracked per-session kill (_kill_tmux_session).
+ async def fake_kill_server() -> None:
+ pass
+
+ monkeypatch.setattr(terminal_service, "_kill_tmux_server", fake_kill_server)
+ await service.shutdown()
+ assert "s" in killed # shutdown killed the replaced tmux session rather than leaking it
+
+ gate.set()
+ with pytest.raises(terminal_service.TerminalServiceError):
+ await reopen
+ for fd in opened_fds:
+ terminal_service._close_fd(fd)
+
+
+def test_teardown_client_is_idempotent_on_fd(monkeypatch, tmp_path):
+ asyncio.run(_teardown_client_is_idempotent_on_fd(monkeypatch, tmp_path))
+
+
+async def _teardown_client_is_idempotent_on_fd(monkeypatch, tmp_path):
+ # A superseded connection can be torn down twice (open() replaces it, then the old
+ # websocket's close() runs). The second teardown must NOT close the fd again — the number
+ # may have been reused by the replacement terminal's PTY, and closing it would kill the
+ # new terminal. First teardown closes once + poisons master_fd to -1; repeat is a no-op.
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ closed: list[int] = []
+ real_close = terminal_service._close_fd
+ monkeypatch.setattr(terminal_service, "_close_fd", lambda fd: (closed.append(fd), real_close(fd)) and None)
+
+ fd = os.open(os.devnull, os.O_RDWR)
+ conn = terminal_service.TerminalConnection("x", _ExitedProcess(), fd, False, 0.0, 0.0)
+
+ await service._teardown_client(conn, kill_session=False)
+ assert conn.master_fd == -1 # poisoned
+ assert closed == [fd] # real fd closed exactly once
+
+ await service._teardown_client(conn, kill_session=False) # stale repeat teardown
+ assert closed == [fd] # closed nothing the second time
+
+
+def test_closing_session_still_counts_against_cap(monkeypatch, tmp_path):
+ asyncio.run(_closing_session_still_counts_against_cap(monkeypatch, tmp_path))
+
+
+async def _closing_session_still_counts_against_cap(monkeypatch, tmp_path):
+ # During a real close(), the session must keep counting toward max_sessions across the
+ # async teardown window — a concurrent open for a different id must not slip past the cap
+ # while the closing session's tmux state is still being reconciled.
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: "/usr/bin/tmux")
+ gate = asyncio.Event()
+
+ async def gated_has_session(_session_id: str) -> bool:
+ await gate.wait()
+ return True
+
+ monkeypatch.setattr(terminal_service, "_tmux_has_session", gated_has_session)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+ conn = _make_persistent_connection("a", process=_ExitedProcess())
+ service._sessions["a"] = _Session("a", _Phase.ATTACHED, persistent=True, connection=conn)
+
+ close_task = asyncio.create_task(service.close(conn))
+ await asyncio.sleep(0.02) # let close() reach CLOSING and park in the gated has-session
+ try:
+ with pytest.raises(terminal_service.TerminalServiceError, match="too_many_sessions"):
+ await service.open("b")
+ finally:
+ gate.set()
+ await close_task
+
+ # The session was alive (has-session True), so it settled to DETACHED — still one slot.
+ assert service._sessions["a"].phase is _Phase.DETACHED
+ await service.shutdown()
+
+
+def test_open_cleans_up_process_when_registration_fails(monkeypatch, tmp_path):
+ asyncio.run(_open_cleans_up_process_when_registration_fails(monkeypatch, tmp_path))
+
+
+async def _open_cleans_up_process_when_registration_fails(monkeypatch, tmp_path):
+ # If the OPENING slot is taken away after the child has spawned but before it is
+ # registered (e.g. the service shuts down, or a forced supersession), the spawned
+ # process must still be torn down — otherwise it lives outside the registry where
+ # shutdown/reaping can never reach it.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+
+ signals: list[int] = []
+
+ class _FakeProcess:
+ returncode = None
+ pid = None
+
+ def send_signal(self, signum: int) -> None:
+ signals.append(signum)
+
+ async def wait(self) -> int:
+ return 0
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)
+
+ async def fake_spawn(*_args, **_kwargs):
+ # Drop the OPENING placeholder mid-spawn so the child can never be registered.
+ service._sessions.clear()
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+
+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):
+ await service.open("orphan")
+
+ assert "orphan" not in service._sessions
+ assert signal.SIGTERM in signals # the spawned shell was terminated, not leaked
+
+
+def test_concurrent_reconnect_is_rejected(monkeypatch, tmp_path):
+ asyncio.run(_concurrent_reconnect_is_rejected(monkeypatch, tmp_path))
+
+
+async def _concurrent_reconnect_is_rejected(monkeypatch, tmp_path):
+ # Two opens for the same id must serialize: while the first is closing the old
+ # connection and spawning the replacement, the second must be rejected with
+ # session_opening rather than racing and overwriting the first's registration.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ first = await service.open("dup")
+
+ spawn_started = asyncio.Event()
+ spawn_gate = asyncio.Event()
+ original_spawn = asyncio.create_subprocess_exec
+
+ async def gated_spawn(*args, **kwargs):
+ spawn_started.set()
+ await spawn_gate.wait()
+ return await original_spawn(*args, **kwargs)
+
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", gated_spawn)
+
+ reopen = asyncio.create_task(service.open("dup"))
+ await spawn_started.wait() # reopen has reserved "dup" and is parked mid-spawn
+ try:
+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):
+ await service.open("dup")
+ finally:
+ spawn_gate.set()
+ replacement = await reopen
+ try:
+ assert service._sessions["dup"].connection is replacement
+ assert first.session_id == "dup"
+ finally:
+ await service.shutdown()
+
+
+def test_spawn_env_drops_c_lc_all(monkeypatch):
+ # LC_ALL overrides LANG/LC_CTYPE; an inherited C/POSIX LC_ALL must be dropped so the
+ # UTF-8 fallback actually takes effect.
+ monkeypatch.setenv("LC_ALL", "C")
+ monkeypatch.delenv("LANG", raising=False)
+ monkeypatch.delenv("LC_CTYPE", raising=False)
+
+ env = terminal_service._spawn_env()
+
+ assert "LC_ALL" not in env
+ assert env["LANG"].endswith("UTF-8")
+ assert env["LC_CTYPE"].endswith("UTF-8")
+
+
+def test_spawn_env_keeps_real_lc_all(monkeypatch):
+ monkeypatch.setenv("LC_ALL", "en_US.UTF-8")
+
+ env = terminal_service._spawn_env()
+
+ assert env["LC_ALL"] == "en_US.UTF-8"
+
+
+def test_spawn_env_drops_inherited_tmux_context(monkeypatch):
+ # The Avibe daemon may itself run inside tmux. Every spawned terminal (vendored tmux
+ # client or plain fallback shell) must NOT inherit that pane's TMUX/TMUX_PANE, or it
+ # targets the operator's tmux socket and nests/targets the wrong server.
+ monkeypatch.setenv("TMUX", "/tmp/tmux-501/default,1234,0")
+ monkeypatch.setenv("TMUX_PANE", "%3")
+
+ env = terminal_service._spawn_env()
+
+ # Use .get(...) is None rather than "x not in env": a failed membership assert would dump
+ # the entire spawned environment (API keys included) into the test log.
+ assert env.get("TMUX") is None
+ assert env.get("TMUX_PANE") is None
+
+
+def test_sanitize_session_id_allows_only_contract_chars():
+ assert sanitize_session_id("../bad session!") == "bad_session"
+ assert sanitize_session_id("abc-DEF_123") == "abc-DEF_123"
+
+
+def test_terminal_websocket_disabled_when_flag_off(monkeypatch, tmp_path):
+ # The terminal is ON by default; an explicit VIBE_UI_ENABLE_TERMINAL=0 disables it.
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={"host": "127.0.0.1", "origin": "http://127.0.0.1"},
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc:
+ websocket.receive_text()
+
+ assert exc.value.code == 1008
+
+
+def test_terminal_websocket_disabled_accepts_before_policy_close(monkeypatch):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")
+ websocket = _RecordingWebSocket()
+
+ asyncio.run(ui_server.terminal_websocket(websocket, "test"))
+
+ assert websocket.calls == [("accept", None), ("close", 1008)]
+
+
+def test_terminal_websocket_unsupported_accepts_before_policy_close(monkeypatch):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", False)
+ websocket = _RecordingWebSocket()
+
+ asyncio.run(ui_server.terminal_websocket(websocket, "test"))
+
+ assert websocket.calls == [("accept", None), ("close", 1008)]
+
+
+def test_terminal_websocket_rejects_forwarded_request(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={
+ "host": "127.0.0.1",
+ "origin": "http://127.0.0.1",
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
+def test_terminal_websocket_rejects_unauthorized_remote_request(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={
+ "host": "127.0.0.1",
+ "origin": "http://127.0.0.1",
+ "x-vibe-test-remote-addr": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
+def test_terminal_websocket_rejects_cross_origin(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={"host": "127.0.0.1", "origin": "http://evil.example"},
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
+def test_terminal_websocket_rejects_local_origin_from_different_port(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={"host": "127.0.0.1", "origin": "http://127.0.0.1:3000"},
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
+def test_terminal_websocket_accepts_local_origin_from_same_port(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ accepted = False
+
+ async def fake_handle_websocket(websocket, session_id):
+ nonlocal accepted
+ accepted = True
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={"host": "127.0.0.1:5123", "origin": "http://127.0.0.1:5123"},
+ ):
+ pass
+
+ assert accepted is True
+
+
+def test_terminal_service_ignores_invalid_limit_env(monkeypatch):
+ monkeypatch.setattr(ui_server, "_terminal_service", None)
+ monkeypatch.setenv(ui_server.TERMINAL_IDLE_TIMEOUT_ENV, "1h")
+ monkeypatch.setenv(ui_server.TERMINAL_MAX_SESSIONS_ENV, "many")
+
+ service = ui_server.get_terminal_service()
+
+ try:
+ assert service.idle_timeout_seconds == 3600
+ assert service.max_sessions == 8
+ finally:
+ monkeypatch.setattr(ui_server, "_terminal_service", None)
diff --git a/tests/test_tmux_runtime.py b/tests/test_tmux_runtime.py
new file mode 100644
index 000000000..1cda1299c
--- /dev/null
+++ b/tests/test_tmux_runtime.py
@@ -0,0 +1,305 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import stat
+import io
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from core import tmux_runtime
+from core.tmux_runtime import TmuxRuntimeManager
+
+
+def _write_tmux_archive(tmp_path: Path, *, text: str = "#!/bin/sh\necho tmux 3.6b\n") -> Path:
+ root = tmp_path / "archive-root"
+ root.mkdir()
+ binary = root / "tmux"
+ binary.write_text(text, encoding="utf-8")
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ archive = tmp_path / "tmux-test.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(binary, arcname="tmux")
+ return archive
+
+
+def _write_manifest(tmp_path: Path, archive: Path, *, sha256: str | None = None, size: int | None = None) -> Path:
+ digest = sha256 or hashlib.sha256(archive.read_bytes()).hexdigest()
+ manifest = {
+ "schema_version": 1,
+ "tmux_version": "3.6b",
+ "source": "test",
+ "source_url": "file://test",
+ "requires_utf8proc": True,
+ "terminfo": "bundled-or-system",
+ "archives": {
+ tmux_runtime._runtime_platform_tag(): {
+ "name": archive.name,
+ "url": archive.as_uri(),
+ "sha256": digest,
+ "size": archive.stat().st_size if size is None else size,
+ "bin_path": "tmux",
+ }
+ },
+ }
+ manifest_path = tmp_path / "tmux_runtime_manifest.json"
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
+ return manifest_path
+
+
+def test_platform_tag_mapping(monkeypatch: pytest.MonkeyPatch) -> None:
+ cases = [
+ ("macosx-14.0-arm64", "ignored", "darwin-arm64"),
+ ("macosx-13.0-x86_64", "ignored", "darwin-x64"),
+ ("macosx-14.0-universal2", "arm64", "darwin-arm64"),
+ ("linux-x86_64", "ignored", "linux-x64"),
+ ("linux-aarch64", "ignored", "linux-arm64"),
+ ]
+ for raw_platform, machine, expected in cases:
+ monkeypatch.setattr(tmux_runtime, "get_platform", lambda value=raw_platform: value)
+ monkeypatch.setattr(tmux_runtime.platform, "machine", lambda value=machine: value)
+ assert tmux_runtime._runtime_platform_tag() == expected
+
+
+def test_download_verify_install_and_idempotent_reinstall(tmp_path: Path) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ first = manager.ensure()
+ assert first["ok"] is True
+ assert first["changed"] is True
+ installed_path = Path(first["path"])
+ assert installed_path.name == "tmux"
+ assert installed_path.is_file()
+ assert manager.resolve_binary() == installed_path
+
+ second = manager.ensure()
+ assert second["ok"] is True
+ assert second["changed"] is False
+ assert Path(second["path"]) == installed_path
+
+
+def test_bad_checksum_is_rejected(tmp_path: Path) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive, sha256="0" * 64)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ result = manager.ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "tmux_archive_checksum_mismatch"
+ assert manager.resolve_binary() is None
+
+
+def test_install_rejects_non_runnable_binary(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest_path = _write_manifest(tmp_path, archive)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest_path)
+ manifest = manager._load_manifest()
+ assert manifest is not None
+ archive_spec = manager._manifest_archive_for_platform(manifest)
+ assert archive_spec is not None
+ install_dir = manager._manifest_install_dir(manifest, archive_spec)
+ install_dir.mkdir(parents=True)
+ sentinel = install_dir / "old-install"
+ sentinel.write_text("keep me", encoding="utf-8")
+
+ monkeypatch.setattr(tmux_runtime, "_tmux_binary_runnable", lambda _binary: False)
+
+ result = manager.ensure(force=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "tmux_binary_not_runnable"
+ assert sentinel.read_text(encoding="utf-8") == "keep me"
+
+
+def test_resolve_tmux_binary_returns_none_when_absent(tmp_path: Path) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ assert manager.resolve_binary() is None
+
+
+def test_tmux_status_shape(tmp_path: Path) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ status = manager.status()
+
+ assert status["id"] == "tmux"
+ assert status["installed"] is False
+ assert status["version"] == "3.6b"
+ assert status["status"] == "missing"
+ assert status["manifest"]["requires_utf8proc"] is True
+ assert status["archive"]["bin_path"] == "tmux"
+
+
+def test_macos_codesign_path_is_used(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ manifest = _write_manifest(tmp_path, archive)
+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+ calls: list[list[str]] = []
+
+ monkeypatch.setattr(tmux_runtime, "sys_platform", lambda: "darwin")
+ sign_checks = iter([False, True])
+ monkeypatch.setattr(tmux_runtime, "_codesign_valid", lambda _path: next(sign_checks))
+ monkeypatch.setattr(tmux_runtime, "_strip_quarantine", lambda _path: {"ok": True, "changed": False})
+ monkeypatch.setattr(tmux_runtime.shutil, "which", lambda name: f"/usr/bin/{name}" if name == "codesign" else None)
+
+ def fake_run(argv: list[str], **_kwargs: object):
+ calls.append(argv)
+
+ class Proc:
+ returncode = 0
+ stdout = "tmux 3.6b\n" if argv[-1] == "-V" else ""
+ stderr = ""
+
+ return Proc()
+
+ monkeypatch.setattr(tmux_runtime.subprocess, "run", fake_run)
+
+ result = manager.ensure()
+
+ assert result["ok"] is True
+ assert result["signing"]["changed"] is True
+ assert calls[0][:4] == ["/usr/bin/codesign", "-f", "-s", "-"]
+ assert calls[0][4].endswith("/tmux")
+
+
+def test_safe_extract_tar_omits_filter_before_python_312(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ destination = tmp_path / "extract"
+ destination.mkdir()
+ calls: list[object] = []
+
+ class VersionInfo(tuple):
+ major = 3
+ minor = 11
+
+ with tarfile.open(archive, "r:gz") as tar:
+ original_extractall = tar.extractall
+
+ def capture_extractall(path, members=None, *, numeric_owner=False, filter=None):
+ calls.append(filter)
+ return original_extractall(path, members=members, numeric_owner=numeric_owner)
+
+ monkeypatch.setattr(tmux_runtime.sys, "version_info", VersionInfo((3, 11, 0)))
+ monkeypatch.setattr(tar, "extractall", capture_extractall)
+ tmux_runtime._safe_extract_tar(tar, destination)
+
+ assert calls == [None]
+ assert (destination / "tmux").is_file()
+
+
+def test_safe_extract_tar_uses_data_filter_on_python_312_plus(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ archive = _write_tmux_archive(tmp_path)
+ destination = tmp_path / "extract"
+ destination.mkdir()
+ calls: list[object] = []
+
+ class VersionInfo(tuple):
+ major = 3
+ minor = 12
+
+ with tarfile.open(archive, "r:gz") as tar:
+ original_extractall = tar.extractall
+
+ def capture_extractall(path, members=None, *, numeric_owner=False, filter=None):
+ calls.append(filter)
+ return original_extractall(path, members=members, numeric_owner=numeric_owner, filter=filter)
+
+ monkeypatch.setattr(tmux_runtime.sys, "version_info", VersionInfo((3, 12, 0)))
+ monkeypatch.setattr(tar, "extractall", capture_extractall)
+ tmux_runtime._safe_extract_tar(tar, destination)
+
+ assert calls == ["data"]
+ assert (destination / "tmux").is_file()
+
+
+def test_safe_extract_tar_rejects_symlink_assisted_dotdot_member(tmp_path: Path) -> None:
+ archive = tmp_path / "tmux-symlink-dotdot-escape.tar.gz"
+ destination = tmp_path / "extract"
+ destination.mkdir()
+ outside = tmp_path / "victim"
+
+ with tarfile.open(archive, "w:gz") as tar:
+ link = tarfile.TarInfo("link")
+ link.type = tarfile.SYMTYPE
+ link.linkname = "."
+ tar.addfile(link)
+
+ payload = b"escaped"
+ member = tarfile.TarInfo("link/../victim")
+ member.size = len(payload)
+ member.mode = 0o644
+ tar.addfile(member, io.BytesIO(payload))
+
+ with tarfile.open(archive, "r:gz") as tar:
+ with pytest.raises(ValueError, match="Unsafe tmux archive member path"):
+ tmux_runtime._safe_extract_tar(tar, destination)
+
+ assert not outside.exists()
+ assert not (destination / "victim").exists()
+ assert not (destination / "link").exists()
+
+
+def test_safe_extract_tar_rejects_root_escaping_hard_link(tmp_path: Path) -> None:
+ archive = tmp_path / "tmux-hardlink-escape.tar.gz"
+ victim = tmp_path / "victim"
+ victim.write_text("victim", encoding="utf-8")
+ original_victim_stat = victim.stat()
+ destination = tmp_path / "extract"
+ destination.mkdir()
+
+ with tarfile.open(archive, "w:gz") as tar:
+ directory = tarfile.TarInfo("sub")
+ directory.type = tarfile.DIRTYPE
+ directory.mode = 0o755
+ tar.addfile(directory)
+ hard_link = tarfile.TarInfo("sub/tmux")
+ hard_link.type = tarfile.LNKTYPE
+ hard_link.linkname = "../victim"
+ hard_link.mode = 0o755
+ tar.addfile(hard_link)
+
+ with tarfile.open(archive, "r:gz") as tar:
+ with pytest.raises(ValueError, match="Unsafe tmux archive link target"):
+ tmux_runtime._safe_extract_tar(tar, destination)
+
+ assert not (destination / "sub" / "tmux").exists()
+ assert victim.stat().st_nlink == original_victim_stat.st_nlink
+
+
+def test_safe_extract_tar_allows_root_relative_in_tree_hard_link(tmp_path: Path) -> None:
+ source = tmp_path / "source"
+ source.mkdir()
+ binary = source / "tmux-real"
+ binary.write_text("#!/bin/sh\necho tmux 3.6b\n", encoding="utf-8")
+ binary.chmod(0o755)
+ archive = tmp_path / "tmux-hardlink-safe.tar.gz"
+ destination = tmp_path / "extract"
+ destination.mkdir()
+
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(binary, arcname="tmux-real")
+ directory = tarfile.TarInfo("sub")
+ directory.type = tarfile.DIRTYPE
+ directory.mode = 0o755
+ tar.addfile(directory)
+ hard_link = tarfile.TarInfo("sub/tmux")
+ hard_link.type = tarfile.LNKTYPE
+ hard_link.linkname = "tmux-real"
+ hard_link.mode = 0o755
+ tar.addfile(hard_link)
+
+ with tarfile.open(archive, "r:gz") as tar:
+ tmux_runtime._safe_extract_tar(tar, destination)
+
+ installed = destination / "sub" / "tmux"
+ assert installed.read_text(encoding="utf-8") == "#!/bin/sh\necho tmux 3.6b\n"
+ assert (destination / "tmux-real").stat().st_ino == installed.stat().st_ino
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index 87158ea50..0e240aa0e 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -16,6 +16,7 @@ from vibe import api
from vibe import remote_access
from vibe import ui_server
from vibe.ui_server import app
+from starlette.websockets import WebSocketDisconnect
_FakeSnicaddr = namedtuple("snicaddr", ["family", "address", "netmask", "broadcast", "ptp"])
@@ -608,6 +609,27 @@ def test_remote_host_allows_valid_remote_session(monkeypatch, tmp_path):
assert response.status_code != 302
+def test_remote_session_info_includes_authenticated_subject(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get("/api/session", base_url="https://alex.avibe.bot")
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "remote": True,
+ "authenticated": True,
+ "email": "[email protected]",
+ "sub": "user-1",
+ }
+
+
def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "[email protected]", subject: str = "user-1") -> str:
import json
import urllib.parse
@@ -1678,6 +1700,199 @@ def test_setup_host_request_from_self_is_treated_as_local(monkeypatch, tmp_path)
assert response.status_code == 200
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_rejects_setup_host_origin_from_different_port(monkeypatch, tmp_path):
+ # A private setup-host request is treated as local (accepted without a session
+ # cookie), so the terminal Origin check must still pin it to the exact scheme+port —
+ # otherwise a same-host page served on another port could open a cross-origin
+ # terminal socket. Regression guard for the setup-host CSWSH gap: before passing the
+ # config into _websocket_is_local_request, this request fell through to the remote
+ # host-only relaxation and the mismatched port was accepted.
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "192.168.2.3")
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={
+ "host": "192.168.2.3:5123",
+ "origin": "http://192.168.2.3:3000",
+ "x-vibe-test-remote-addr": "192.168.2.5",
+ },
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_accepts_setup_host_origin_from_same_port(monkeypatch, tmp_path):
+ # The exact-origin counterpart: a setup-host terminal request whose Origin matches the
+ # request scheme+port must still be accepted (the fix must not over-reject LAN setup).
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "192.168.2.3")
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
+
+ accepted = False
+
+ async def fake_handle_websocket(websocket, session_id):
+ nonlocal accepted
+ accepted = True
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+
+ with app.test_client().websocket_connect(
+ "/api/terminal/test",
+ headers={
+ "host": "192.168.2.3:5123",
+ "origin": "http://192.168.2.3:5123",
+ "x-vibe-test-remote-addr": "192.168.2.5",
+ },
+ ):
+ pass
+
+ assert accepted is True
+
+
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_rejects_remote_same_host_different_origin(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with client.websocket_connect(
+ "wss://alex.avibe.bot/api/terminal/test",
+ headers={
+ "host": "alex.avibe.bot",
+ "origin": "https://alex.avibe.bot:8443",
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
[email protected]("origin", ["https://alex.avibe.bot", "https://alex.avibe.bot:443"])
+def test_terminal_websocket_accepts_remote_exact_trusted_origin(monkeypatch, tmp_path, origin):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ accepted = False
+
+ async def fake_handle_websocket(websocket, session_id):
+ nonlocal accepted
+ accepted = True
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ with client.websocket_connect(
+ "wss://alex.avibe.bot/api/terminal/test",
+ headers={
+ "host": "alex.avibe.bot",
+ "origin": origin,
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert accepted is True
+
+
+def test_terminal_effective_session_id_scopes_remote_subjects():
+ client_id = "shared-session"
+
+ user_one_first = ui_server._terminal_effective_session_id(client_id, "user-1")
+ user_one_second = ui_server._terminal_effective_session_id(client_id, "user-1")
+ user_two = ui_server._terminal_effective_session_id(client_id, "user-2")
+
+ assert user_one_first == user_one_second
+ assert user_one_first != user_two
+ assert user_one_first.endswith("-shared-session")
+ assert ui_server._terminal_effective_session_id(client_id, None) == client_id
+
+
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_scopes_remote_session_id_by_authenticated_subject(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ handled_session_ids: list[str] = []
+
+ async def fake_handle_websocket(websocket, session_id):
+ handled_session_ids.append(session_id)
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+
+ def connect_as(subject: str) -> None:
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, f"{subject}@example.com", subject),
+ domain="alex.avibe.bot",
+ )
+ with client.websocket_connect(
+ "wss://alex.avibe.bot/api/terminal/shared-session",
+ headers={
+ "host": "alex.avibe.bot",
+ "origin": "https://alex.avibe.bot",
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ connect_as("user-1")
+ connect_as("user-1")
+ connect_as("user-2")
+
+ assert handled_session_ids[0] == handled_session_ids[1]
+ assert handled_session_ids[0] != handled_session_ids[2]
+ assert all(session_id.endswith("-shared-session") for session_id in handled_session_ids)
+
+
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_keeps_local_session_id_unscoped(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config_with_setup_host(tmp_path, "192.168.2.3")
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
+ handled_session_ids: list[str] = []
+
+ async def fake_handle_websocket(websocket, session_id):
+ handled_session_ids.append(session_id)
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+
+ with app.test_client().websocket_connect(
+ "/api/terminal/local-session",
+ headers={
+ "host": "192.168.2.3:5123",
+ "origin": "http://192.168.2.3:5123",
+ "x-vibe-test-remote-addr": "192.168.2.5",
+ },
+ ):
+ pass
+
+ assert handled_session_ids == ["local-session"]
+
+
def test_setup_host_with_public_peer_is_not_local(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config_with_setup_host(tmp_path, "192.168.2.3")
diff --git a/ui/package-lock.json b/ui/package-lock.json
index 536dd0a99..f7a9521eb 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -8,6 +8,7 @@
"name": "ui",
"version": "0.0.0",
"dependencies": {
+ "@codemirror/language-data": "^6.5.2",
"@lexical/react": "^0.45.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
@@ -16,7 +17,10 @@
"@radix-ui/react-slot": "^1.2.4",
"@shikijs/langs": "^4.2.0",
"@shikijs/themes": "^4.2.0",
+ "@uiw/react-codemirror": "^4.25.10",
"@uiw/react-json-view": "^2.0.0-alpha.43",
+ "@xterm/addon-fit": "^0.11.0",
+ "@xterm/xterm": "^6.0.0",
"agentation": "^3.0.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -325,10 +329,423 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@codemirror/autocomplete": {
+ "version": "6.20.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
+ "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/commands": {
+ "version": "6.10.4",
+ "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.4.tgz",
+ "integrity": "sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.7.0",
+ "@codemirror/view": "^6.27.0",
+ "@lezer/common": "^1.1.0"
+ }
+ },
+ "node_modules/@codemirror/lang-angular": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz",
+ "integrity": "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.1.2",
+ "@codemirror/language": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.3"
+ }
+ },
+ "node_modules/@codemirror/lang-cpp": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz",
+ "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/cpp": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-css": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
+ "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.2",
+ "@lezer/css": "^1.1.7"
+ }
+ },
+ "node_modules/@codemirror/lang-go": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-go/-/lang-go-6.0.1.tgz",
+ "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.6.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/go": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-html": {
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
+ "integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/lang-css": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.0.0",
+ "@codemirror/language": "^6.4.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/css": "^1.1.0",
+ "@lezer/html": "^1.3.12"
+ }
+ },
+ "node_modules/@codemirror/lang-java": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz",
+ "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/java": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-javascript": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
+ "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.6.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/javascript": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-jinja": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz",
+ "integrity": "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.2.0",
+ "@lezer/lr": "^1.4.0"
+ }
+ },
+ "node_modules/@codemirror/lang-json": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz",
+ "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/json": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-less": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-less/-/lang-less-6.0.2.tgz",
+ "integrity": "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-css": "^6.2.0",
+ "@codemirror/language": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-liquid": {
+ "version": "6.3.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz",
+ "integrity": "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.1"
+ }
+ },
+ "node_modules/@codemirror/lang-markdown": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.0.tgz",
+ "integrity": "sha512-0K40bZ35jpHya6FriukbgaleaqzBLZfOh7HuzqbMxBXkbYMJDxfF39c23xOgxFezR+3G+tR2/Mup+Xk865OMvw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.7.1",
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/language": "^6.3.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/common": "^1.2.1",
+ "@lezer/markdown": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-php": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-php/-/lang-php-6.0.2.tgz",
+ "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/php": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-python": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz",
+ "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.3.2",
+ "@codemirror/language": "^6.8.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.1",
+ "@lezer/python": "^1.1.4"
+ }
+ },
+ "node_modules/@codemirror/lang-rust": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz",
+ "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/rust": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-sass": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz",
+ "integrity": "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-css": "^6.2.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.2",
+ "@lezer/sass": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-sql": {
+ "version": "6.10.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz",
+ "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-vue": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz",
+ "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.1.2",
+ "@codemirror/language": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.1"
+ }
+ },
+ "node_modules/@codemirror/lang-wast": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz",
+ "integrity": "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-xml": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz",
+ "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.4.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/xml": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-yaml": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz",
+ "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.2.0",
+ "@lezer/lr": "^1.0.0",
+ "@lezer/yaml": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/language": {
+ "version": "6.12.4",
+ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
+ "integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.23.0",
+ "@lezer/common": "^1.5.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0",
+ "style-mod": "^4.0.0"
+ }
+ },
+ "node_modules/@codemirror/language-data": {
+ "version": "6.5.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/language-data/-/language-data-6.5.2.tgz",
+ "integrity": "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-angular": "^0.1.0",
+ "@codemirror/lang-cpp": "^6.0.0",
+ "@codemirror/lang-css": "^6.0.0",
+ "@codemirror/lang-go": "^6.0.0",
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/lang-java": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.0.0",
+ "@codemirror/lang-jinja": "^6.0.0",
+ "@codemirror/lang-json": "^6.0.0",
+ "@codemirror/lang-less": "^6.0.0",
+ "@codemirror/lang-liquid": "^6.0.0",
+ "@codemirror/lang-markdown": "^6.0.0",
+ "@codemirror/lang-php": "^6.0.0",
+ "@codemirror/lang-python": "^6.0.0",
+ "@codemirror/lang-rust": "^6.0.0",
+ "@codemirror/lang-sass": "^6.0.0",
+ "@codemirror/lang-sql": "^6.0.0",
+ "@codemirror/lang-vue": "^0.1.1",
+ "@codemirror/lang-wast": "^6.0.0",
+ "@codemirror/lang-xml": "^6.0.0",
+ "@codemirror/lang-yaml": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/legacy-modes": "^6.4.0"
+ }
+ },
+ "node_modules/@codemirror/legacy-modes": {
+ "version": "6.5.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.3.tgz",
+ "integrity": "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0"
+ }
+ },
+ "node_modules/@codemirror/lint": {
+ "version": "6.9.7",
+ "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
+ "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.42.0",
+ "crelt": "^1.0.5"
+ }
+ },
+ "node_modules/@codemirror/search": {
+ "version": "6.7.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.1.tgz",
+ "integrity": "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.37.0",
+ "crelt": "^1.0.5"
+ }
+ },
+ "node_modules/@codemirror/state": {
+ "version": "6.7.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.0.tgz",
+ "integrity": "sha512-Zbl9NyscLMZkfXPQnNAIIAFftidrA1UbcJEIMp24C0Bukc2I5T8wJS0wsXYsnDOqCFJUeJ1BITGNs5CqPDSmSg==",
+ "license": "MIT",
+ "dependencies": {
+ "@marijn/find-cluster-break": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/theme-one-dark": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
+ "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/highlight": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/view": {
+ "version": "6.43.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.3.tgz",
+ "integrity": "sha512-MwEwCAr/o0agJefhC2+reBv5kfOQpMcDRUNQrRYZgWlhH8IwQcerMZrpqWyUFSyO0ebgN2cnh/w87F7G4BGSng==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.7.0",
+ "crelt": "^1.0.6",
+ "style-mod": "^4.1.0",
+ "w3c-keyname": "^2.2.4"
+ }
+ },
"node_modules/@emnapi/core": {
- "version": "1.11.0",
- "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.0.tgz",
- "integrity": "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==",
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
+ "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -339,9 +756,9 @@
}
},
"node_modules/@emnapi/runtime": {
- "version": "1.11.0",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.0.tgz",
- "integrity": "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==",
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
+ "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -971,6 +1388,189 @@
"yjs": ">=13.5.22"
}
},
+ "node_modules/@lezer/common": {
+ "version": "1.5.2",
+ "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
+ "integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
+ "license": "MIT"
+ },
+ "node_modules/@lezer/cpp": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.6.tgz",
+ "integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/css": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.3.tgz",
+ "integrity": "sha512-RzBo8r+/6QJeow7aPHIpGVIH59xTcJXp399820gZoMo9noQDRVpJLheIBUicYwKcsbOYoBRoLZlf2720dG/4Tg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/go": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@lezer/go/-/go-1.0.1.tgz",
+ "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/highlight": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
+ "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/html": {
+ "version": "1.3.13",
+ "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
+ "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/java": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.3.tgz",
+ "integrity": "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/javascript": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
+ "integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.1.3",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/json": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz",
+ "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/lr": {
+ "version": "1.4.10",
+ "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
+ "integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/markdown": {
+ "version": "1.6.4",
+ "resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.6.4.tgz",
+ "integrity": "sha512-N0SxazMj4k65DBfaf1azqtMZd6u7MqluP84/NZnB/io8Td9aleFmAhz9hcbvSfsxT5tdYlJ5qgv5aMJGY4zEtA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.5.0",
+ "@lezer/highlight": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/php": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@lezer/php/-/php-1.0.5.tgz",
+ "integrity": "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.1.0"
+ }
+ },
+ "node_modules/@lezer/python": {
+ "version": "1.1.19",
+ "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz",
+ "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/rust": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@lezer/rust/-/rust-1.0.2.tgz",
+ "integrity": "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/sass": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@lezer/sass/-/sass-1.1.0.tgz",
+ "integrity": "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/xml": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz",
+ "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/yaml": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz",
+ "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.4.0"
+ }
+ },
+ "node_modules/@marijn/find-cluster-break": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",
+ "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",
+ "license": "MIT"
+ },
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz",
@@ -2736,6 +3336,59 @@
"url": "https://opencollective.com/typescript-eslint"
}
},
+ "node_modules/@uiw/codemirror-extensions-basic-setup": {
+ "version": "4.25.10",
+ "resolved": "https://registry.npmjs.org/@uiw/codemirror-extensions-basic-setup/-/codemirror-extensions-basic-setup-4.25.10.tgz",
+ "integrity": "sha512-P3vytLlpE62KYSWrMUnwDCv2lvaQDuDZzyj03mHntuHo5bSl34fRZpjTY3kQTPGuXHxkGSYpoPFFj+hMTqaaMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/commands": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/search": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://jaywcjlove.github.io/#/sponsor"
+ },
+ "peerDependencies": {
+ "@codemirror/autocomplete": ">=6.0.0",
+ "@codemirror/commands": ">=6.0.0",
+ "@codemirror/language": ">=6.0.0",
+ "@codemirror/lint": ">=6.0.0",
+ "@codemirror/search": ">=6.0.0",
+ "@codemirror/state": ">=6.0.0",
+ "@codemirror/view": ">=6.0.0"
+ }
+ },
+ "node_modules/@uiw/react-codemirror": {
+ "version": "4.25.10",
+ "resolved": "https://registry.npmjs.org/@uiw/react-codemirror/-/react-codemirror-4.25.10.tgz",
+ "integrity": "sha512-DzgSMwM5qzB7v1FIb4gEeriYt67iiay756/HIOM9mAbeOVK0MO7rqefHf0O5c0269pJKMW7AH9FjclExD23V9w==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.18.6",
+ "@codemirror/commands": "^6.1.0",
+ "@codemirror/state": "^6.1.1",
+ "@codemirror/theme-one-dark": "^6.0.0",
+ "@uiw/codemirror-extensions-basic-setup": "4.25.10",
+ "codemirror": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://jaywcjlove.github.io/#/sponsor"
+ },
+ "peerDependencies": {
+ "@babel/runtime": ">=7.11.0",
+ "@codemirror/state": ">=6.0.0",
+ "@codemirror/theme-one-dark": ">=6.0.0",
+ "@codemirror/view": ">=6.0.0",
+ "codemirror": ">=6.0.0",
+ "react": ">=17.0.0",
+ "react-dom": ">=17.0.0"
+ }
+ },
"node_modules/@uiw/react-json-view": {
"version": "2.0.0-alpha.43",
"resolved": "https://registry.npmjs.org/@uiw/react-json-view/-/react-json-view-2.0.0-alpha.43.tgz",
@@ -2782,6 +3435,21 @@
}
}
},
+ "node_modules/@xterm/addon-fit": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
+ "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
+ "license": "MIT"
+ },
+ "node_modules/@xterm/xterm": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",
+ "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
+ "license": "MIT",
+ "workspaces": [
+ "addons/*"
+ ]
+ },
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
@@ -3119,6 +3787,21 @@
"react-dom": "^18 || ^19 || ^19.0.0-rc"
}
},
+ "node_modules/codemirror": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
+ "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/commands": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/search": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0"
+ }
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -3176,6 +3859,12 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/crelt": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
+ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",
+ "license": "MIT"
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -6094,6 +6783,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/style-mod": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
+ "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
+ "license": "MIT"
+ },
"node_modules/style-to-js": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
@@ -6841,6 +7536,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/w3c-keyname": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
+ "license": "MIT"
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/ui/package.json b/ui/package.json
index 897606d24..81697f5b7 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -14,6 +14,7 @@
"validate:theme": "node scripts/validate-theme.mjs"
},
"dependencies": {
+ "@codemirror/language-data": "^6.5.2",
"@lexical/react": "^0.45.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
@@ -22,7 +23,10 @@
"@radix-ui/react-slot": "^1.2.4",
"@shikijs/langs": "^4.2.0",
"@shikijs/themes": "^4.2.0",
+ "@uiw/react-codemirror": "^4.25.10",
"@uiw/react-json-view": "^2.0.0-alpha.43",
+ "@xterm/addon-fit": "^0.11.0",
+ "@xterm/xterm": "^6.0.0",
"agentation": "^3.0.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 7ca8b3f94..62eaec801 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -11,6 +11,8 @@ import { VaultsPage } from './components/workbench/VaultsPage';
import { ChatPage } from './components/workbench/ChatPage';
import { ProjectsPage } from './components/workbench/ProjectsPage';
import { MorePage } from './components/workbench/MorePage';
+import { AppsFileBrowserPage } from './components/workbench/AppsFileBrowserPage';
+import { AppsTerminalPage } from './components/workbench/AppsTerminalPage';
import { Dashboard } from './components/Dashboard';
import { ChannelList } from './components/steps/ChannelList';
import { UserList } from './components/steps/UserList';
@@ -284,6 +286,11 @@ function AppRoutes() {
<Route path="/vaults" element={<VaultsPage />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/more" element={<MorePage />} />
+ {/* Apps layer — File Browser (Phase 1) + Terminal (Phase 2). The
+ sidebar Apps launcher opens these; /apps lands on the file browser. */}
+ <Route path="/apps" element={<Navigate to="/apps/files" replace />} />
+ <Route path="/apps/files" element={<AppsFileBrowserPage />} />
+ <Route path="/apps/terminal" element={<AppsTerminalPage />} />
<Route path="/chat/:sessionId" element={<ChatPage />} />
{/* Control Panel mode — existing pages moved under /admin/* */}
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index b1d8df6fe..fae8caa2b 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -12,6 +12,7 @@ import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from './ThemeToggle';
import { VersionBadge } from './VersionBadge';
import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
+import { AppsLauncher } from './AppsLauncher';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
import { Button } from './ui/button';
@@ -404,26 +405,20 @@ export const AppShell: React.FC = () => {
{/* Bottom: Status (with embedded version badge) + toggles + hostname */}
<div className="flex flex-col gap-3">
- <div
- className={clsx(
- 'flex items-center gap-2.5 rounded-lg border px-3 py-2.5',
- isRunning
- ? 'border-mint/30 bg-mint/[0.08]'
- : 'border-border bg-foreground/[0.02]'
- )}
- >
+ {/* Apps launcher + a compact run-state dot (hover shows the status
+ text) + version. The old status pill's two text lines collapsed
+ into the dot — the green/grey dot already conveys running vs
+ stopped, freeing this corner for the Apps entry. */}
+ <div className="flex items-center gap-2">
+ <AppsLauncher />
<span
+ title={isRunning ? t('common.running') : t('common.stopped')}
+ aria-label={isRunning ? t('common.running') : t('common.stopped')}
className={clsx(
- 'size-2 shrink-0 rounded-full',
+ 'size-2.5 shrink-0 rounded-full',
isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
)}
/>
- <div className="min-w-0 flex-1">
- <div className="text-[12px] font-medium text-foreground">
- {isRunning ? t('common.running') : t('common.stopped')}
- </div>
- <div className="text-[10px] text-muted">{t('appShell.statusLabel')}</div>
- </div>
<VersionBadge openUpward />
</div>
diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsx
new file mode 100644
index 000000000..440807554
--- /dev/null
+++ b/ui/src/components/AppsLauncher.tsx
@@ -0,0 +1,123 @@
+import { useEffect, useRef, useState } from 'react';
+import { useLocation, useNavigate } from 'react-router-dom';
+import { ChevronUp, FolderTree, LayoutGrid, TerminalSquare } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import type { LucideIcon } from 'lucide-react';
+
+// The "Apps" layer launcher — a Start-menu-style list that opens on hover (and
+// on click, for touch/keyboard) from the sidebar's bottom-left. File Browser and
+// Terminal are the first two apps; Show Pages will become pinnable here later.
+// Mirrors the InboxHoverPopover open/close timer dance so the menu survives the
+// cursor crossing the gap between the trigger and the floating panel.
+type AppItem = { to: string; labelKey: string; descKey: string; icon: LucideIcon; soon?: boolean };
+
+const APPS: AppItem[] = [
+ { to: '/apps/files', labelKey: 'apps.fileBrowser.label', descKey: 'apps.fileBrowser.desc', icon: FolderTree },
+ { to: '/apps/terminal', labelKey: 'apps.terminal.label', descKey: 'apps.terminal.desc', icon: TerminalSquare },
+];
+
+export const AppsLauncher: React.FC = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const [open, setOpen] = useState(false);
+ const closeTimer = useRef<number | null>(null);
+ const active = location.pathname.startsWith('/apps');
+
+ const openMenu = () => {
+ if (closeTimer.current !== null) {
+ window.clearTimeout(closeTimer.current);
+ closeTimer.current = null;
+ }
+ setOpen(true);
+ };
+ const queueClose = () => {
+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
+ closeTimer.current = window.setTimeout(() => {
+ setOpen(false);
+ closeTimer.current = null;
+ }, 180);
+ };
+ useEffect(
+ () => () => {
+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
+ },
+ [],
+ );
+ // Dismiss when navigation lands on a new route (tapping an app navigates).
+ useEffect(() => {
+ setOpen(false);
+ }, [location.pathname]);
+
+ const go = (to: string) => {
+ setOpen(false);
+ navigate(to);
+ };
+
+ return (
+ <div className="relative flex-1" onMouseEnter={openMenu} onMouseLeave={queueClose}>
+ <button
+ type="button"
+ onClick={() => (open ? setOpen(false) : openMenu())}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ className={clsx(
+ 'group flex w-full items-center gap-2.5 rounded-lg border px-3 py-2.5 text-[13px] font-medium transition-colors',
+ active || open
+ ? 'border-mint/30 bg-mint/[0.08] text-foreground shadow-[0_0_16px_-4px_rgba(91,255,160,0.5)]'
+ : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ <LayoutGrid className={clsx('size-4', active || open ? 'text-mint' : 'text-muted group-hover:text-foreground')} />
+ <span className="flex-1 text-left">{t('apps.title')}</span>
+ <ChevronUp className={clsx('size-3.5 shrink-0 text-muted transition-transform', !open && 'rotate-180')} />
+ </button>
+
+ {open && (
+ <div
+ role="menu"
+ aria-label={t('apps.title')}
+ onMouseEnter={openMenu}
+ onMouseLeave={queueClose}
+ className="absolute bottom-full left-0 z-50 mb-2 flex w-[256px] flex-col gap-1 rounded-2xl border border-border-strong bg-surface-2 p-2 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"
+ >
+ <div className="px-2 pb-0.5 pt-1 font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted">
+ {t('apps.title')}
+ </div>
+ {APPS.map((app) => {
+ const Icon = app.icon;
+ const isActive = location.pathname.startsWith(app.to);
+ return (
+ <button
+ key={app.to}
+ type="button"
+ role="menuitem"
+ onClick={() => go(app.to)}
+ className={clsx(
+ 'flex items-start gap-2.5 rounded-lg px-2.5 py-2 text-left transition',
+ isActive ? 'bg-mint/[0.08]' : 'hover:bg-foreground/[0.04]',
+ )}
+ >
+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border border-border bg-foreground/[0.03]">
+ <Icon className="size-4 text-mint" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="flex items-center gap-1.5 text-[12.5px] font-semibold text-foreground">
+ {t(app.labelKey)}
+ {app.soon && (
+ <span className="rounded-full border border-border bg-foreground/[0.04] px-1.5 py-0.5 font-mono text-[9px] font-medium text-muted">
+ {t('apps.soon')}
+ </span>
+ )}
+ </span>
+ <span className="line-clamp-2 text-[11px] leading-relaxed text-muted">{t(app.descKey)}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsx
index bdba7872a..b22af9ef1 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx
@@ -10,6 +10,7 @@ import {
Loader2,
RefreshCw,
ShieldCheck,
+ SquareTerminal,
Terminal,
WandSparkles,
} from 'lucide-react';
@@ -36,6 +37,7 @@ const DEP_META: Record<string, DepMeta> = {
askill: { icon: WandSparkles, tileCls: 'bg-mint-soft', iconCls: 'text-mint' },
avault: { icon: KeyRound, tileCls: 'bg-gold-soft', iconCls: 'text-gold' },
'show-runtime': { icon: LayoutDashboard, tileCls: 'bg-cyan-soft', iconCls: 'text-cyan' },
+ tmux: { icon: SquareTerminal, tileCls: 'bg-surface-3', iconCls: 'text-foreground' },
node: { icon: Hexagon, tileCls: 'bg-violet-soft', iconCls: 'text-violet' },
};
@@ -108,7 +110,8 @@ export const SettingsDependenciesPage: React.FC = () => {
{deps.map((d) => {
const meta = DEP_META[d.id] ?? DEP_META.node;
const installing = busy === d.id;
- const showAction = d.id === 'askill' || d.id === 'avault' || d.id === 'show-runtime';
+ const showAction =
+ d.id === 'askill' || d.id === 'avault' || d.id === 'show-runtime' || d.id === 'tmux';
return (
<SettingsResourceRow
key={d.id}
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
new file mode 100644
index 000000000..2e913395c
--- /dev/null
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -0,0 +1,369 @@
+import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronRight, Download, File as FileIcon, Folder, FolderPlus, Loader2, RefreshCw, Star } from 'lucide-react';
+import clsx from 'clsx';
+
+import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { previewKind } from '../../lib/filePreview';
+import {
+ contentUrl,
+ fileBrowserErrorMessage,
+ fileMeta,
+ isPlainEntryName,
+ joinPath,
+ listDir,
+ makeDir,
+ pathCrumbs,
+ systemFavorites,
+ type Favorite,
+ type FsEntry,
+ type FsListing,
+} from '../../lib/filesApi';
+import { Button } from '../ui/button';
+
+// Lazy-load the editor so CodeMirror + @codemirror/language-data stay out of the
+// main bundle until a text file is actually opened.
+const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));
+
+type Selected = { path: string; name: string; kind: string; mime: string | null; mtime: number | null; size: number | null };
+
+// Above this size, offer a download instead of loading the file into CodeMirror
+// (mirrors the in-page preview cap; the backend allows /api/files/content up to 25MB).
+const MAX_EDIT_BYTES = 1024 * 1024;
+
+// Whole-machine Finder: favorites rail (pinned projects + OS defaults), a
+// breadcrumb + dir/file list (left), and a content pane (right) that views or
+// edits the selected file. Backend contract: src/lib/filesApi.ts → /api/files/*.
+export const AppsFileBrowserPage: React.FC = () => {
+ const { t } = useTranslation();
+ const { projects } = useWorkbenchProjectsTree();
+ const [cwd, setCwd] = useState('');
+ const [listing, setListing] = useState<FsListing | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [showHidden, setShowHidden] = useState(false);
+ const [sysFavs, setSysFavs] = useState<Favorite[]>([]);
+ const [selected, setSelected] = useState<Selected | null>(null);
+
+ // Tokens to drop stale async responses. navSeq guards directory listings; selSeq guards
+ // file-metadata selections. Every navigation bumps BOTH, so a slow earlier listDir() can't
+ // overwrite cwd/listing with a stale directory AND a pending fileMeta() can't repopulate the
+ // pane with a file after the user has moved to another directory (breadcrumb/favorite/toggle).
+ const navSeq = useRef(0);
+ const selSeq = useRef(0);
+ const navigate = useCallback(
+ (path: string) => {
+ const seq = ++navSeq.current;
+ selSeq.current += 1; // navigating away invalidates any in-flight file selection
+ setLoading(true);
+ setError(null);
+ listDir(path, showHidden)
+ .then((r) => {
+ if (seq !== navSeq.current) return; // a newer navigation superseded this response
+ setCwd(r.path);
+ setListing(r);
+ })
+ .catch((e: unknown) => {
+ if (seq === navSeq.current) setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.listFailed')));
+ })
+ .finally(() => {
+ if (seq === navSeq.current) setLoading(false);
+ });
+ },
+ [showHidden],
+ );
+
+ useEffect(() => {
+ systemFavorites().then(setSysFavs).catch(() => {});
+ }, []);
+
+ // Pick an initial directory once: first pinned project, else the home favorite.
+ useEffect(() => {
+ if (cwd) return;
+ if (projects === null) return;
+ const initial = projects?.[0]?.folder_path || sysFavs.find((f) => f.key === 'home')?.path;
+ if (initial) navigate(initial);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [projects, sysFavs]);
+
+ // Re-list the current dir when the hidden toggle flips.
+ useEffect(() => {
+ if (cwd) navigate(cwd);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [showHidden]);
+
+ const openEntry = (entry: FsEntry) => {
+ const seq = ++selSeq.current;
+ const full = joinPath(cwd, entry.name);
+ if (entry.kind === 'dir') {
+ setSelected(null);
+ navigate(full);
+ } else {
+ fileMeta(full)
+ .then((m) => {
+ if (seq !== selSeq.current) return; // a newer click superseded this metadata fetch
+ setSelected({ path: full, name: entry.name, kind: m.kind, mime: m.mime, mtime: m.mtime, size: m.size });
+ })
+ .catch((e: unknown) => {
+ if (seq === selSeq.current) setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.openFailed')));
+ });
+ }
+ };
+
+ const newFolder = async () => {
+ const raw = window.prompt(t('apps.fileBrowser.newFolderPrompt'));
+ if (raw == null) return;
+ const name = raw.trim();
+ if (name === '') return;
+ // The prompt collects a name, not a path: reject separators / '.' / '..' before
+ // joining, so "New folder" can't silently create a dir outside the current folder.
+ if (!isPlainEntryName(name)) {
+ setError(t('apps.fileBrowser.errors.invalid_name'));
+ return;
+ }
+ try {
+ await makeDir(joinPath(cwd, name));
+ navigate(cwd);
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.createFolderFailed')));
+ }
+ };
+
+ const projectFavs = useMemo(
+ () =>
+ (projects || [])
+ .filter((p) => !!p.folder_path)
+ .map((p) => ({ label: p.display_name, path: p.folder_path as string })),
+ [projects],
+ );
+ const crumbs = cwd ? pathCrumbs(cwd) : [];
+
+ return (
+ <div className="flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]">
+ <div>
+ <h1 className="text-[18px] font-semibold text-foreground">{t('apps.fileBrowser.label')}</h1>
+ <p className="text-[12px] text-muted">{t('apps.fileBrowser.tagline')}</p>
+ </div>
+
+ <div className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">
+ {/* Left: breadcrumb toolbar + favorites + listing */}
+ <div className="flex w-full min-w-0 flex-col md:w-[320px] md:border-r md:border-border">
+ <div className="flex items-center gap-1.5 border-b border-border px-2.5 py-2">
+ <div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">
+ {crumbs.map((c, i) => (
+ <span key={c.path} className="flex shrink-0 items-center">
+ {i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
+ <button
+ type="button"
+ onClick={() => {
+ setSelected(null);
+ navigate(c.path);
+ }}
+ className="max-w-[120px] truncate rounded px-1 py-0.5 text-[12px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"
+ >
+ {c.label}
+ </button>
+ </span>
+ ))}
+ </div>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('apps.fileBrowser.refresh')}
+ onClick={() => cwd && navigate(cwd)}
+ >
+ <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />
+ </Button>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('apps.fileBrowser.newFolder')}
+ disabled={!cwd}
+ onClick={() => void newFolder()}
+ >
+ <FolderPlus className="size-3.5" />
+ </Button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="flex flex-col gap-0.5 border-b border-border p-2">
+ {projectFavs.length > 0 && (
+ <div className="px-1 pb-0.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">
+ {t('apps.fileBrowser.projects')}
+ </div>
+ )}
+ {projectFavs.map((f) => (
+ <FavRow
+ key={f.path}
+ icon={<Star className="size-3.5 text-mint" />}
+ label={f.label}
+ active={cwd === f.path}
+ onClick={() => {
+ setSelected(null);
+ navigate(f.path);
+ }}
+ />
+ ))}
+ {sysFavs.length > 0 && (
+ <div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">
+ {t('apps.fileBrowser.system')}
+ </div>
+ )}
+ {sysFavs.map((f) => (
+ <FavRow
+ key={f.path}
+ icon={<Folder className="size-3.5 text-muted" />}
+ label={f.path.split('/').filter(Boolean).pop() || f.path}
+ active={cwd === f.path}
+ onClick={() => {
+ setSelected(null);
+ navigate(f.path);
+ }}
+ />
+ ))}
+ </div>
+
+ {error && (
+ <div className="m-2 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2.5 py-1.5 text-[11.5px] text-destructive">
+ {error}
+ </div>
+ )}
+ {listing?.truncated && (
+ <div className="mx-2 mt-2 rounded-md border border-border bg-foreground/[0.03] px-2.5 py-1.5 text-[11.5px] text-muted">
+ {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? listing.entries.length })}
+ </div>
+ )}
+ <div className="flex flex-col gap-0.5 p-2">
+ {loading && !listing && (
+ <div className="grid place-items-center py-6">
+ <Loader2 className="size-4 animate-spin text-muted" />
+ </div>
+ )}
+ {listing?.entries.length === 0 && !loading && (
+ <div className="px-2 py-6 text-center text-[12px] text-muted">{t('apps.fileBrowser.empty')}</div>
+ )}
+ {listing?.entries.map((entry) => (
+ <button
+ key={entry.name}
+ type="button"
+ onClick={() => openEntry(entry)}
+ className={clsx(
+ 'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
+ selected?.path === joinPath(cwd, entry.name)
+ ? 'bg-mint/[0.08] text-foreground'
+ : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ {entry.kind === 'dir' ? (
+ <Folder className="size-4 shrink-0 text-muted" />
+ ) : (
+ <FileIcon className="size-4 shrink-0 text-muted" />
+ )}
+ <span className="flex-1 truncate">{entry.name}</span>
+ {entry.kind === 'dir' && <ChevronRight className="size-3.5 shrink-0 text-muted" />}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <label className="flex items-center gap-2 border-t border-border px-3 py-2 text-[11.5px] text-muted">
+ <input
+ type="checkbox"
+ checked={showHidden}
+ onChange={(e) => setShowHidden(e.target.checked)}
+ className="size-3.5"
+ />
+ {t('apps.fileBrowser.showHidden')}
+ </label>
+ </div>
+
+ {/* Right: content pane (desktop) */}
+ <div className="hidden min-w-0 flex-1 md:flex">
+ <ContentPane selected={selected} />
+ </div>
+ </div>
+
+ {/* Mobile: content opens below the list when a file is selected */}
+ {selected && (
+ <div className="flex min-h-[50vh] flex-col overflow-hidden rounded-xl border border-border bg-surface md:hidden">
+ <ContentPane selected={selected} />
+ </div>
+ )}
+ </div>
+ );
+};
+
+const FavRow: React.FC<{ icon: React.ReactNode; label: string; active: boolean; onClick: () => void }> = ({
+ icon,
+ label,
+ active,
+ onClick,
+}) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className={clsx(
+ 'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
+ active ? 'bg-mint/[0.08] text-foreground' : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ <span className="shrink-0">{icon}</span>
+ <span className="flex-1 truncate">{label}</span>
+ </button>
+);
+
+const ContentPane: React.FC<{ selected: Selected | null }> = ({ selected }) => {
+ const { t } = useTranslation();
+ if (!selected) {
+ return (
+ <div className="grid flex-1 place-items-center p-6 text-center text-[12.5px] text-muted">
+ {t('apps.fileBrowser.selectHint')}
+ </div>
+ );
+ }
+ const mime = selected.mime || '';
+ if (mime.startsWith('image/')) {
+ return (
+ <div className="grid min-h-0 flex-1 place-items-center overflow-auto bg-foreground/[0.02] p-4">
+ <img src={contentUrl(selected.path)} alt={selected.name} className="max-h-full max-w-full object-contain" />
+ </div>
+ );
+ }
+ // A symlink reports size:null (server lstat()s the link, not its target), but
+ // /api/files/content follows it — so a symlink pointing at a large file would slip past
+ // the size cap and load its whole target into CodeMirror. Treat symlinks and any
+ // unknown-size entry as non-editable; the download link below can still follow them.
+ const tooLargeToEdit =
+ selected.kind === 'symlink' || selected.size == null || selected.size > MAX_EDIT_BYTES;
+ if (previewKind(selected.name, selected.mime || undefined) && !tooLargeToEdit) {
+ return (
+ <Suspense
+ fallback={<div className="grid flex-1 place-items-center text-[12px] text-muted">{t('common.loading')}</div>}
+ >
+ {/* key by path: remount per file so an in-flight save/load can never apply its
+ result to a different file (stale clean/dirty baseline or wrong expected_mtime). */}
+ <FileEditorPane key={selected.path} path={selected.path} filename={selected.name} mtime={selected.mtime} />
+ </Suspense>
+ );
+ }
+ return (
+ <div className="grid flex-1 place-items-center p-6 text-center">
+ <div className="flex flex-col items-center gap-3">
+ <FileIcon className="size-8 text-muted" />
+ <div className="text-[12.5px] text-muted">
+ {tooLargeToEdit ? t('apps.fileBrowser.tooLarge') : t('apps.fileBrowser.noPreview')}
+ </div>
+ <a
+ href={contentUrl(selected.path, true)}
+ className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ <Download className="size-3.5" /> {t('apps.fileBrowser.download')}
+ </a>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/AppsTerminalPage.tsx b/ui/src/components/workbench/AppsTerminalPage.tsx
new file mode 100644
index 000000000..2634b3b09
--- /dev/null
+++ b/ui/src/components/workbench/AppsTerminalPage.tsx
@@ -0,0 +1,72 @@
+import { Suspense, lazy, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useApi } from '../../context/ApiContext';
+
+// Lazy so xterm.js stays out of the main bundle until the Terminal is opened.
+const TerminalView = lazy(() => import('./TerminalView').then((m) => ({ default: m.TerminalView })));
+
+// A process-unique in-memory fallback id, generated once per page load. Used only when
+// localStorage is unavailable, so privacy-restricted/embedded browsers don't all collapse
+// onto one shared tmux session (which would expose terminal state/commands across clients).
+const FALLBACK_SESSION_ID = `wb-${Math.random().toString(36).slice(2, 10)}`;
+
+// A stable per-browser session id so the tmux-backed session reconnects to the same shell
+// after a refresh / network drop (persistence). Falls back to the in-memory id above when
+// localStorage is unavailable. The key is scoped to the signed-in account so a different
+// remote (OIDC) user in the same browser can't inherit — and reconnect to — the previous
+// user's live shell; local/unauthenticated sessions (identity == null) share one key.
+function getSessionId(identity: string | null): string {
+ const KEY = identity ? `avibe.terminal.sessionId.${encodeURIComponent(identity)}` : 'avibe.terminal.sessionId';
+ try {
+ let id = window.localStorage.getItem(KEY);
+ if (!id) {
+ id = `wb-${Math.random().toString(36).slice(2, 10)}`;
+ window.localStorage.setItem(KEY, id);
+ }
+ return id;
+ } catch {
+ return FALLBACK_SESSION_ID;
+ }
+}
+
+export const AppsTerminalPage: React.FC = () => {
+ const { t } = useTranslation();
+ const { getAuthSession } = useApi();
+ // Resolve the signed-in identity first, then derive the (account-scoped) session id, so we
+ // never briefly mount the terminal under the wrong key. email is null for local/unauth.
+ const [sessionId, setSessionId] = useState<string | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ const resolve = (identity: string | null) => {
+ if (!cancelled) setSessionId(getSessionId(identity));
+ };
+ getAuthSession()
+ // Prefer the stable OIDC subject; email can be absent or shared across subjects, which
+ // would collide or fall back to the shared key. (Backend surfaces sub on /api/session.)
+ .then((session) => resolve(session.remote && session.authenticated ? session.sub || session.email : null))
+ .catch(() => resolve(null));
+ return () => {
+ cancelled = true;
+ };
+ }, [getAuthSession]);
+ return (
+ <div className="flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]">
+ <div>
+ <h1 className="text-[18px] font-semibold text-foreground">{t('apps.terminal.label')}</h1>
+ <p className="text-[12px] text-muted">{t('apps.terminal.tagline')}</p>
+ </div>
+ <div className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">
+ {sessionId == null ? (
+ <div className="grid flex-1 place-items-center text-[12px] text-muted">{t('common.loading')}</div>
+ ) : (
+ <Suspense
+ fallback={<div className="grid flex-1 place-items-center text-[12px] text-muted">{t('common.loading')}</div>}
+ >
+ <TerminalView sessionId={sessionId} />
+ </Suspense>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsx
new file mode 100644
index 000000000..396d6f0bf
--- /dev/null
+++ b/ui/src/components/workbench/FileEditorPane.tsx
@@ -0,0 +1,126 @@
+import { Suspense, lazy, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Loader2, Save } from 'lucide-react';
+import { languages } from '@codemirror/language-data';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+import { fileBrowserErrorMessage, readText, writeFile } from '../../lib/filesApi';
+
+// CodeMirror 6 is heavy; lazy-load it so it stays out of the main bundle (same
+// approach as the file-viewer modal). @uiw/react-codemirror's default export is
+// the editor component.
+const CodeMirror = lazy(() => import('@uiw/react-codemirror'));
+
+async function loadLanguageExtension(filename: string): Promise<any[]> {
+ const ext = filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : '';
+ if (!ext) return [];
+ const desc = (languages as any[]).find((lang) => lang.extensions?.includes(ext));
+ if (!desc) return [];
+ try {
+ return [await desc.load()];
+ } catch {
+ return [];
+ }
+}
+
+// Read + edit + save one text/code file. Read-only is just `editable={false}`.
+export const FileEditorPane: React.FC<{ path: string; filename: string; mtime: number | null }> = ({
+ path,
+ filename,
+ mtime,
+}) => {
+ const { t } = useTranslation();
+ const [text, setText] = useState<string | null>(null);
+ const [original, setOriginal] = useState('');
+ const [langExt, setLangExt] = useState<any[]>([]);
+ const [savedMtime, setSavedMtime] = useState<number | null>(mtime);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ setText(null);
+ setSavedMtime(mtime);
+ readText(path)
+ .then((body) => {
+ if (cancelled) return;
+ setText(body);
+ setOriginal(body);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.loadFailed')));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ void loadLanguageExtension(filename).then((ext) => {
+ if (!cancelled) setLangExt(ext);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [path, filename, mtime]);
+
+ const dirty = text !== null && text !== original;
+
+ async function save() {
+ if (text === null || saving) return;
+ setSaving(true);
+ setError(null);
+ try {
+ const result = await writeFile(path, text, savedMtime);
+ setOriginal(text);
+ setSavedMtime(result.mtime);
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.saveFailed')));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex items-center gap-2 border-b border-border px-3 py-2">
+ <span className="flex-1 truncate font-mono text-[12px] text-foreground">{filename}</span>
+ {dirty && <span className="size-1.5 shrink-0 rounded-full bg-mint" title={t('apps.fileBrowser.unsaved')} />}
+ <Button
+ type="button"
+ size="sm"
+ variant="brand"
+ disabled={!dirty || saving || text === null}
+ onClick={() => void save()}
+ className="h-7 gap-1.5 px-2.5 text-[12px]"
+ >
+ {saving ? <Loader2 className="size-3 animate-spin" /> : <Save className="size-3" />}
+ {t('apps.fileBrowser.save')}
+ </Button>
+ </div>
+
+ {error && (
+ <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive">
+ {error}
+ </div>
+ )}
+
+ <div className={clsx('min-h-0 flex-1 overflow-auto', loading && 'grid place-items-center')}>
+ {loading ? (
+ <Loader2 className="size-5 animate-spin text-muted" />
+ ) : text === null ? null : (
+ <Suspense fallback={<div className="p-4 text-[12px] text-muted">{t('common.loading')}</div>}>
+ <CodeMirror
+ value={text}
+ height="100%"
+ extensions={langExt}
+ onChange={(value: string) => setText(value)}
+ basicSetup={{ lineNumbers: true, highlightActiveLine: true }}
+ />
+ </Suspense>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/MorePage.tsx b/ui/src/components/workbench/MorePage.tsx
index cd9359c5c..b858815ef 100644
--- a/ui/src/components/workbench/MorePage.tsx
+++ b/ui/src/components/workbench/MorePage.tsx
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { ArrowRight, Link as LinkIcon, LogOut, SlidersHorizontal } from 'lucide-react';
+import { ArrowRight, FolderTree, Link as LinkIcon, LogOut, SlidersHorizontal, SquareTerminal } from 'lucide-react';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
@@ -67,6 +67,40 @@ export const MorePage: React.FC = () => {
<ArrowRight className="size-[18px] shrink-0 text-cyan" />
</Link>
+ {/* Apps — the desktop sidebar's Apps launcher, surfaced for mobile where
+ there is no sidebar. */}
+ <div className="flex flex-col gap-2">
+ <div className="px-1 font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted">
+ {t('apps.title')}
+ </div>
+ <Link
+ to="/apps/files"
+ className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3.5 transition hover:bg-foreground/[0.04]"
+ >
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/[0.12]">
+ <FolderTree className="size-[18px] text-mint" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[15px] font-semibold">{t('apps.fileBrowser.label')}</span>
+ <span className="block truncate text-[11.5px] text-muted">{t('apps.fileBrowser.desc')}</span>
+ </span>
+ <ArrowRight className="size-[18px] shrink-0 text-muted" />
+ </Link>
+ <Link
+ to="/apps/terminal"
+ className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3.5 transition hover:bg-foreground/[0.04]"
+ >
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-foreground/[0.05]">
+ <SquareTerminal className="size-[18px] text-foreground" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[15px] font-semibold">{t('apps.terminal.label')}</span>
+ <span className="block truncate text-[11.5px] text-muted">{t('apps.terminal.desc')}</span>
+ </span>
+ <ArrowRight className="size-[18px] shrink-0 text-muted" />
+ </Link>
+ </div>
+
{/* Appearance — reuse the existing toggles as touch rows. */}
<div className="rounded-xl border border-border bg-surface">
<div className="flex items-center gap-3 px-4 py-3">
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
new file mode 100644
index 000000000..4a2c63b15
--- /dev/null
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -0,0 +1,237 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Terminal } from '@xterm/xterm';
+import { FitAddon } from '@xterm/addon-fit';
+import '@xterm/xterm/css/xterm.css';
+import clsx from 'clsx';
+import { RotateCw } from 'lucide-react';
+
+import { Button } from '../ui/button';
+
+// xterm.js wired to the /api/terminal/{id} WebSocket. Protocol (locked with the
+// backend): client sends raw stdin as BINARY frames and JSON control as TEXT
+// frames ({type:"resize",cols,rows}); server sends PTY output as BINARY and
+// {type:"ready"|"exit"} as TEXT. Lazy-loaded by AppsTerminalPage so xterm stays
+// out of the main bundle.
+type Status = 'connecting' | 'ready' | 'closed' | 'disabled' | 'error';
+
+const ENC = new TextEncoder();
+const MAX_BUSY_RETRIES = 3; // auto-retry a transient "busy" (1013) close this many times
+
+// Accessory key bar for phones (their soft keyboards lack these). Each button sends the raw
+// byte sequence the PTY expects; Ctrl is a sticky modifier. Labels go through i18n (the
+// control sequences stay here).
+const KEYS: { labelKey: string; seq?: string; ctrl?: boolean }[] = [
+ { labelKey: 'apps.terminal.keys.esc', seq: '\x1b' },
+ { labelKey: 'apps.terminal.keys.tab', seq: '\t' },
+ { labelKey: 'apps.terminal.keys.ctrl', ctrl: true },
+ { labelKey: 'apps.terminal.keys.up', seq: '\x1b[A' },
+ { labelKey: 'apps.terminal.keys.down', seq: '\x1b[B' },
+ { labelKey: 'apps.terminal.keys.left', seq: '\x1b[D' },
+ { labelKey: 'apps.terminal.keys.right', seq: '\x1b[C' },
+ { labelKey: 'apps.terminal.keys.interrupt', seq: '\x03' },
+ { labelKey: 'apps.terminal.keys.pipe', seq: '|' },
+];
+
+function buildWsUrl(sessionId: string): string {
+ const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
+ return `${proto}://${window.location.host}/api/terminal/${encodeURIComponent(sessionId)}`;
+}
+
+export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) => {
+ const { t } = useTranslation();
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const termRef = useRef<Terminal | null>(null);
+ const wsRef = useRef<WebSocket | null>(null);
+ const ctrlStickyRef = useRef(false);
+ const busyRetriesRef = useRef(0);
+ const retryTimerRef = useRef<number | null>(null);
+ const [status, setStatus] = useState<Status>('connecting');
+ const [persistent, setPersistent] = useState(false);
+ const [exitCode, setExitCode] = useState<number | null>(null);
+ const [reconnectKey, setReconnectKey] = useState(0);
+
+ useEffect(() => {
+ const term = new Terminal({
+ fontSize: 13,
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
+ cursorBlink: true,
+ theme: { background: '#0b0b12' },
+ allowProposedApi: true,
+ });
+ const fit = new FitAddon();
+ term.loadAddon(fit);
+ termRef.current = term;
+ if (containerRef.current) {
+ term.open(containerRef.current);
+ try {
+ fit.fit();
+ } catch {
+ /* container not measured yet */
+ }
+ }
+
+ const onData = term.onData((data: string) => {
+ const ws = wsRef.current;
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
+ let out = data;
+ if (ctrlStickyRef.current && data.length === 1) {
+ out = String.fromCharCode(data.toUpperCase().charCodeAt(0) & 0x1f);
+ ctrlStickyRef.current = false;
+ }
+ ws.send(ENC.encode(out));
+ });
+ const onResize = term.onResize(({ cols, rows }: { cols: number; rows: number }) => {
+ const ws = wsRef.current;
+ if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'resize', cols, rows }));
+ });
+
+ setStatus('connecting');
+ setExitCode(null);
+ const ws = new WebSocket(buildWsUrl(sessionId));
+ ws.binaryType = 'arraybuffer';
+ wsRef.current = ws;
+ ws.onopen = () => {
+ try {
+ fit.fit();
+ } catch {
+ /* noop */
+ }
+ };
+ ws.onmessage = (ev: MessageEvent) => {
+ if (typeof ev.data === 'string') {
+ try {
+ const msg = JSON.parse(ev.data) as { type?: string; persistent?: boolean; code?: number };
+ if (msg.type === 'ready') {
+ busyRetriesRef.current = 0; // a successful attach resets the transient-retry budget
+ setStatus('ready');
+ setPersistent(!!msg.persistent);
+ } else if (msg.type === 'exit') {
+ setExitCode(typeof msg.code === 'number' ? msg.code : null);
+ setStatus('closed');
+ }
+ } catch {
+ /* ignore malformed control frame */
+ }
+ return;
+ }
+ term.write(new Uint8Array(ev.data as ArrayBuffer));
+ };
+ ws.onclose = (ev: CloseEvent) => {
+ // 1013 = transient "try again shortly" (the session id is mid-open/teardown, or the cap
+ // is momentarily full). Auto-retry a few times with a short backoff before surfacing an
+ // error, so a reconnect that races a CLOSING teardown recovers on its own.
+ if (ev.code === 1013 && busyRetriesRef.current < MAX_BUSY_RETRIES) {
+ busyRetriesRef.current += 1;
+ setStatus('connecting');
+ retryTimerRef.current = window.setTimeout(
+ () => setReconnectKey((k) => k + 1),
+ 250 * busyRetriesRef.current,
+ );
+ return;
+ }
+ setStatus((prev) =>
+ prev === 'closed' ? prev : ev.code === 1008 ? 'disabled' : prev === 'ready' ? 'closed' : 'error',
+ );
+ };
+
+ const ro = new ResizeObserver(() => {
+ try {
+ fit.fit();
+ } catch {
+ /* noop */
+ }
+ });
+ if (containerRef.current) ro.observe(containerRef.current);
+
+ return () => {
+ if (retryTimerRef.current != null) window.clearTimeout(retryTimerRef.current);
+ ro.disconnect();
+ onData.dispose();
+ onResize.dispose();
+ // Detach handlers before closing. A closing socket's onclose can fire asynchronously
+ // *after* its replacement has already reported 'ready' (reconnect / effect remount);
+ // left attached, the stale onclose would mark the live terminal 'closed' or schedule a
+ // spurious 1013 reconnect. The torn-down terminal is being disposed, so its remaining
+ // frames are moot — dropping them at this single chokepoint is the root fix.
+ ws.onopen = null;
+ ws.onmessage = null;
+ ws.onclose = null;
+ try {
+ ws.close();
+ } catch {
+ /* noop */
+ }
+ term.dispose();
+ wsRef.current = null;
+ termRef.current = null;
+ };
+ }, [sessionId, reconnectKey]);
+
+ const sendKey = (k: { seq?: string; ctrl?: boolean }) => {
+ if (k.ctrl) {
+ ctrlStickyRef.current = !ctrlStickyRef.current;
+ return;
+ }
+ const ws = wsRef.current;
+ if (k.seq && ws && ws.readyState === WebSocket.OPEN) ws.send(ENC.encode(k.seq));
+ termRef.current?.focus();
+ };
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex items-center gap-2 border-b border-border px-3 py-1.5 text-[11.5px] text-muted">
+ <span
+ className={clsx(
+ 'size-2 shrink-0 rounded-full',
+ status === 'ready' ? 'bg-mint' : status === 'connecting' ? 'bg-amber-400' : 'bg-muted',
+ )}
+ />
+ <span>
+ {t(`apps.terminal.status.${status}`)}
+ {status === 'closed' && exitCode != null ? ` · ${t('apps.terminal.exitCode', { code: exitCode })}` : ''}
+ </span>
+ {status === 'ready' && persistent && (
+ <span className="rounded-full border border-border px-1.5 text-[10px]">{t('apps.terminal.persistent')}</span>
+ )}
+ {(status === 'closed' || status === 'error') && (
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="ml-auto h-6 gap-1 px-2 text-[11px]"
+ onClick={() => {
+ busyRetriesRef.current = 0;
+ setReconnectKey((k) => k + 1);
+ }}
+ >
+ <RotateCw className="size-3" /> {t('apps.terminal.reconnect')}
+ </Button>
+ )}
+ </div>
+
+ {status === 'disabled' ? (
+ <div className="grid flex-1 place-items-center p-6 text-center text-[12.5px] text-muted">
+ <div className="max-w-md">{t('apps.terminal.disabled')}</div>
+ </div>
+ ) : (
+ <div ref={containerRef} className="min-h-0 flex-1 overflow-hidden bg-[#0b0b12] p-1.5" />
+ )}
+
+ {status !== 'disabled' && (
+ <div className="flex gap-1 overflow-x-auto border-t border-border bg-surface px-2 py-1.5 md:hidden">
+ {KEYS.map((k) => (
+ <button
+ key={k.labelKey}
+ type="button"
+ onClick={() => sendKey(k)}
+ className="shrink-0 rounded-md border border-border-strong px-2.5 py-1.5 font-mono text-[12px] text-foreground active:bg-foreground/[0.08]"
+ >
+ {t(k.labelKey)}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index df8adb0a6..e70567e57 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -886,7 +886,9 @@ export type RunningAgentsResult =
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
- | { remote: true; authenticated: true; email: string };
+ // sub is the stable OIDC subject; prefer it over email for per-account scoping (email can
+ // be absent or shared across subjects).
+ | { remote: true; authenticated: true; email: string; sub?: string };
export type LogEntry = {
timestamp: string;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 39af18a27..79fa1671e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -243,6 +243,10 @@
"label": "Show Page runtime",
"detail": "Renders visual Show Pages on your machine."
},
+ "tmux": {
+ "label": "tmux",
+ "detail": "Persistent terminal runtime for reconnectable Web Terminal sessions."
+ },
"node": {
"label": "Node.js",
"detail": "Shared prerequisite for the runtimes above."
@@ -592,6 +596,78 @@
"cloudflared_stop_failed": "The connector could not be stopped. Try again later, or manually stop the cloudflared process.",
"cloudflared_process_unknown": "Avibe found a connector-like process but could not verify ownership. To avoid killing the wrong process, it did not change it. Check the cloudflared process manually and retry."
},
+ "apps": {
+ "title": "Apps",
+ "soon": "Soon",
+ "fileBrowser": {
+ "label": "File Browser",
+ "desc": "Browse, view, and edit files on this machine.",
+ "placeholder": "The File Browser is being built. You'll be able to browse the whole machine, open files, and edit and save them right here.",
+ "tagline": "Whole machine · view and edit",
+ "selectHint": "Select a file to view or edit it.",
+ "empty": "This folder is empty.",
+ "noPreview": "No in-app preview for this file type.",
+ "download": "Download",
+ "tooLarge": "This file is too large to edit in the browser. Download it to view it instead.",
+ "refresh": "Refresh",
+ "newFolder": "New folder",
+ "newFolderPrompt": "New folder name",
+ "projects": "Projects",
+ "system": "System",
+ "showHidden": "Show hidden files",
+ "save": "Save",
+ "unsaved": "Unsaved changes",
+ "conflict": "This file changed on disk since you opened it. Reload before saving to avoid overwriting it.",
+ "listTruncated": "Only the first {{count}} entries are shown.",
+ "errors": {
+ "conflict": "This file changed on disk since you opened it. Reload before saving to avoid overwriting it.",
+ "not_found": "Path not found.",
+ "permission_denied": "Permission denied.",
+ "too_large": "This file is too large.",
+ "file_not_utf8": "This file isn't valid UTF-8 text, so it can't be edited safely — download it instead.",
+ "not_dir": "Path is not a folder.",
+ "not_file": "Path is not a regular file.",
+ "is_symlink": "Symbolic links cannot be edited here.",
+ "invalid_path": "Enter a valid absolute path.",
+ "invalid_name": "Enter a valid name.",
+ "exists": "Path already exists.",
+ "fs_error": "File system operation failed.",
+ "listFailed": "Couldn't list this folder.",
+ "openFailed": "Couldn't open this item.",
+ "createFolderFailed": "Couldn't create the folder.",
+ "loadFailed": "Couldn't load this file.",
+ "saveFailed": "Couldn't save this file."
+ }
+ },
+ "terminal": {
+ "label": "Terminal",
+ "desc": "A real shell in your browser.",
+ "placeholder": "The Terminal arrives in Phase 2: a real shell with tmux-backed persistent sessions.",
+ "tagline": "A real shell, in your browser.",
+ "persistent": "Persistent",
+ "reconnect": "Reconnect",
+ "exitCode": "exit {{code}}",
+ "disabled": "Terminal unavailable: it may be turned off on the server (VIBE_UI_ENABLE_TERMINAL=0) or this session isn't authorized.",
+ "status": {
+ "connecting": "Connecting…",
+ "ready": "Connected",
+ "closed": "Session ended",
+ "disabled": "Disabled",
+ "error": "Disconnected"
+ },
+ "keys": {
+ "esc": "Esc",
+ "tab": "Tab",
+ "ctrl": "Ctrl",
+ "up": "↑",
+ "down": "↓",
+ "left": "←",
+ "right": "→",
+ "interrupt": "^C",
+ "pipe": "|"
+ }
+ }
+ },
"appShell": {
"title": "Avibe OS",
"subtitle": "Agent OS · Workbench",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1a95f8d1c..7cc132003 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -243,6 +243,10 @@
"label": "Show Page 运行时",
"detail": "在你本机渲染可视化 Show 页面。"
},
+ "tmux": {
+ "label": "tmux",
+ "detail": "持久终端运行时,用于可重连的 Web Terminal 会话。"
+ },
"node": {
"label": "Node.js",
"detail": "上述运行时的共同前置依赖。"
@@ -592,6 +596,78 @@
"cloudflared_stop_failed": "连接器暂时无法停止。请稍后重试,或在系统进程里手动结束 cloudflared。",
"cloudflared_process_unknown": "检测到一个无法确认归属的连接器进程。为避免误杀其它进程,Avibe 没有自动处理。请手动检查 cloudflared 进程后再启动。"
},
+ "apps": {
+ "title": "应用",
+ "soon": "即将上线",
+ "fileBrowser": {
+ "label": "文件浏览器",
+ "desc": "浏览、查看、编辑这台机器上的文件。",
+ "placeholder": "文件浏览器正在搭建中。很快你就能在这里浏览整机文件、打开文件、直接编辑并保存。",
+ "tagline": "整机 · 查看与编辑",
+ "selectHint": "选择一个文件来查看或编辑。",
+ "empty": "这个文件夹是空的。",
+ "noPreview": "这种文件类型暂不支持应用内预览。",
+ "download": "下载",
+ "tooLarge": "文件太大,无法在浏览器里编辑。请下载后查看。",
+ "refresh": "刷新",
+ "newFolder": "新建文件夹",
+ "newFolderPrompt": "新文件夹名称",
+ "projects": "项目",
+ "system": "系统",
+ "showHidden": "显示隐藏文件",
+ "save": "保存",
+ "unsaved": "有未保存的修改",
+ "conflict": "打开后该文件在磁盘上已被改动。请先重新加载再保存,以免覆盖。",
+ "listTruncated": "当前只显示前 {{count}} 个条目。",
+ "errors": {
+ "conflict": "打开后该文件在磁盘上已被改动。请先重新加载再保存,以免覆盖。",
+ "not_found": "找不到这个路径。",
+ "permission_denied": "没有权限访问。",
+ "too_large": "这个文件太大。",
+ "file_not_utf8": "该文件不是有效的 UTF-8 文本,无法安全编辑,请改为下载。",
+ "not_dir": "这个路径不是文件夹。",
+ "not_file": "这个路径不是普通文件。",
+ "is_symlink": "这里不能编辑符号链接。",
+ "invalid_path": "请输入有效的绝对路径。",
+ "invalid_name": "请输入有效名称。",
+ "exists": "这个路径已存在。",
+ "fs_error": "文件系统操作失败。",
+ "listFailed": "无法列出这个文件夹。",
+ "openFailed": "无法打开这个项目。",
+ "createFolderFailed": "无法创建文件夹。",
+ "loadFailed": "无法加载这个文件。",
+ "saveFailed": "无法保存这个文件。"
+ }
+ },
+ "terminal": {
+ "label": "终端",
+ "desc": "在浏览器里跑真实 shell。",
+ "placeholder": "终端将在第二阶段上线:真实 shell,配 tmux 持久化会话。",
+ "tagline": "在浏览器里跑真实 shell。",
+ "persistent": "持久会话",
+ "reconnect": "重新连接",
+ "exitCode": "退出码 {{code}}",
+ "disabled": "终端不可用:可能在服务端被关掉(VIBE_UI_ENABLE_TERMINAL=0),或当前会话未获授权。",
+ "status": {
+ "connecting": "连接中…",
+ "ready": "已连接",
+ "closed": "会话已结束",
+ "disabled": "未开启",
+ "error": "已断开"
+ },
+ "keys": {
+ "esc": "Esc",
+ "tab": "Tab",
+ "ctrl": "Ctrl",
+ "up": "↑",
+ "down": "↓",
+ "left": "←",
+ "right": "→",
+ "interrupt": "^C",
+ "pipe": "|"
+ }
+ }
+ },
"appShell": {
"title": "Avibe OS",
"subtitle": "Agent操作系统 · 工作台",
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
new file mode 100644
index 000000000..752e96a15
--- /dev/null
+++ b/ui/src/lib/filesApi.ts
@@ -0,0 +1,192 @@
+// Client for the whole-machine File Browser backend (`/api/files/*`). Reuses the
+// shared `apiFetch`, which attaches the CSRF header to mutating verbs and routes
+// remote-auth-expiry redirects. Backend contract: `core/file_browser_service.py`.
+import { apiFetch } from './apiFetch';
+
+export type FsEntry = {
+ name: string;
+ kind: 'dir' | 'file' | 'symlink';
+ size: number | null;
+ mtime: number | null;
+ ext: string;
+};
+
+export type FsListing = {
+ ok: true;
+ path: string;
+ parent: string | null;
+ entries: FsEntry[];
+ truncated?: boolean;
+ limit?: number;
+};
+
+export type FsMeta = {
+ ok: true;
+ name: string;
+ ext: string;
+ kind: 'dir' | 'file' | 'symlink';
+ size: number | null;
+ mtime: number | null;
+ mime: string | null;
+};
+
+export type Favorite = { key: string; path: string };
+
+export class FilesApiError extends Error {
+ code: string;
+ constructor(code: string, message: string) {
+ super(message);
+ this.code = code;
+ this.name = 'FilesApiError';
+ }
+}
+
+export function fileBrowserErrorMessage(error: unknown, t: (key: string) => string, fallback: string): string {
+ if (error instanceof FilesApiError) {
+ // Every error code (backend not_found/permission_denied/... and the client-side
+ // file_not_utf8) maps 1:1 to apps.fileBrowser.errors.<code>; fall back to the raw
+ // message when no localized string exists.
+ const key = `apps.fileBrowser.errors.${error.code}`;
+ const translated = t(key);
+ return translated === key ? error.message : translated;
+ }
+ return error instanceof Error ? error.message : fallback;
+}
+
+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 || {};
+ throw new FilesApiError(err.code || String(res.status), err.message || 'Request failed');
+ }
+ return data as T;
+}
+
+function isWindowsPath(p: string): boolean {
+ // Windows iff a drive root (C:\ or C:/) or a UNC path (\\server). A lone backslash is a
+ // legal POSIX filename character (e.g. /tmp/a\b), so its mere presence must NOT flip us to
+ // Windows mode — that would make joinPath build /tmp/a\b\child and break descendant access.
+ return /^[A-Za-z]:[\\/]/.test(p) || /^\\\\/.test(p);
+}
+
+export function joinPath(base: string, name: string): string {
+ const sep = isWindowsPath(base) ? '\\' : '/';
+ return base.endsWith('/') || base.endsWith('\\') ? `${base}${name}` : `${base}${sep}${name}`;
+}
+
+// A user-entered entry name must be a single path component, so joinPath(base, name)
+// can only ever address a child of `base`. Reject separators and '.'/'..'/empty —
+// otherwise input like '../scratch' or 'sub/new' would mutate a sibling/nested folder.
+// Mirrors the backend rename_path name validator.
+export function isPlainEntryName(name: string): boolean {
+ const trimmed = name.trim();
+ return trimmed !== '' && trimmed !== '.' && trimmed !== '..' && !trimmed.includes('/') && !trimmed.includes('\\');
+}
+
+export function pathCrumbs(path: string): { label: string; path: string }[] {
+ // Windows: split on either separator and keep the root intact.
+ if (isWindowsPath(path)) {
+ const normalized = path.replace(/\//g, '\\');
+ if (/^\\\\/.test(normalized)) {
+ // UNC: the root is the share (\\server\share) — you can't navigate above it, and the
+ // leading \\ must be preserved or breadcrumb targets become invalid (server\, server\share).
+ const parts = normalized.replace(/^\\+/, '').split('\\').filter(Boolean); // [server, share, dir, ...]
+ const server = parts.shift() ?? '';
+ const share = parts.shift();
+ const root = share ? `\\\\${server}\\${share}` : `\\\\${server}`;
+ const out: { label: string; path: string }[] = [{ label: root, path: root }];
+ let cur = root;
+ for (const part of parts) {
+ cur = `${cur}\\${part}`;
+ out.push({ label: part, path: cur });
+ }
+ return out;
+ }
+ const parts = normalized.split('\\').filter(Boolean);
+ const drive = parts.shift() ?? '';
+ const out: { label: string; path: string }[] = [{ label: `${drive}\\`, path: `${drive}\\` }];
+ let cur = `${drive}\\`;
+ for (const part of parts) {
+ cur = cur.endsWith('\\') ? `${cur}${part}` : `${cur}\\${part}`;
+ out.push({ label: part, path: cur });
+ }
+ return out;
+ }
+ const parts = path.split('/').filter(Boolean);
+ const out: { label: string; path: string }[] = [{ label: '/', path: '/' }];
+ let cur = '';
+ for (const part of parts) {
+ cur += `/${part}`;
+ out.push({ label: part, path: cur });
+ }
+ return out;
+}
+
+export async function listDir(path: string, showHidden = false): Promise<FsListing> {
+ const res = await apiFetch(
+ `/api/files/list?path=${encodeURIComponent(path)}&show_hidden=${showHidden ? '1' : '0'}`,
+ );
+ return parse<FsListing>(res);
+}
+
+export async function fileMeta(path: string): Promise<FsMeta> {
+ return parse<FsMeta>(await apiFetch(`/api/files/meta?path=${encodeURIComponent(path)}`));
+}
+
+export function contentUrl(path: string, download = false): string {
+ return `/api/files/content?path=${encodeURIComponent(path)}${download ? '&download=1' : ''}`;
+}
+
+export async function readText(path: string): Promise<string> {
+ const res = await apiFetch(contentUrl(path));
+ if (!res.ok) {
+ await parse(res); // throws a FilesApiError
+ }
+ const body = await res.arrayBuffer();
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(body);
+ } catch (error) {
+ if (error instanceof TypeError) {
+ throw new FilesApiError('file_not_utf8', "This file isn't valid UTF-8 text.");
+ }
+ throw error;
+ }
+}
+
+export async function writeFile(
+ path: string,
+ content: string,
+ expectedMtime?: number | null,
+): Promise<{ ok: true; mtime: number }> {
+ const res = await apiFetch('/api/files/write', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path, content, expected_mtime: expectedMtime ?? undefined }),
+ });
+ return parse<{ ok: true; mtime: number }>(res);
+}
+
+export async function makeDir(path: string): Promise<{ ok: true }> {
+ return parse(
+ await apiFetch('/api/files/mkdir', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path }),
+ }),
+ );
+}
+
+export async function deletePath(path: string, recursive = false): Promise<{ ok: true }> {
+ return parse(
+ await apiFetch('/api/files/delete', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path, recursive }),
+ }),
+ );
+}
+
+export async function systemFavorites(): Promise<Favorite[]> {
+ const data = await parse<{ ok: true; favorites: Favorite[] }>(await apiFetch('/api/browse/favorites'));
+ return data.favorites || [];
+}
diff --git a/uv.lock b/uv.lock
index e7900b83a..35c8671e0 100644
--- a/uv.lock
+++ b/uv.lock
@@ -304,6 +304,7 @@ dependencies = [
{ name = "anyio" },
{ name = "apscheduler" },
{ name = "claude-agent-sdk" },
+ { name = "cryptography" },
{ name = "discord-py" },
{ name = "fastapi" },
{ name = "httpx", extra = ["socks"] },
@@ -339,6 +340,7 @@ requires-dist = [
{ name = "anyio", specifier = ">=4.0.0" },
{ name = "apscheduler", specifier = ">=3.10.4" },
{ name = "claude-agent-sdk", specifier = ">=0.2.93" },
+ { name = "cryptography", specifier = ">=42.0" },
{ name = "discord-py", specifier = ">=2.4.0" },
{ name = "fastapi", specifier = ">=0.110" },
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
diff --git a/vibe/api.py b/vibe/api.py
index 900310468..dae59143a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -3934,7 +3934,7 @@ def reconcile_askill_auto_update() -> dict:
# Dependencies aggregate + manual install jobs (askill / show runtime)
# =============================================================================
-_ALLOWED_DEP_INSTALLS = {"askill", "avault", "show-runtime"}
+_ALLOWED_DEP_INSTALLS = {"askill", "avault", "show-runtime", "tmux"}
_STARTUP_DEPENDENCY_RECONCILE_LOCK = threading.Lock()
_DEFAULT_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 3
_MAX_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 10
@@ -3997,6 +3997,23 @@ def dependencies_status() -> dict:
}
)
+ try:
+ from core.tmux_runtime import tmux_status
+
+ tmux = tmux_status()
+ except Exception as exc: # noqa: BLE001
+ tmux = {"installed": False, "version": None, "status": "missing", "reason": str(exc)}
+ deps.append(
+ {
+ "id": "tmux",
+ "kind": "tool",
+ "required": False,
+ "installed": bool(tmux.get("installed")),
+ "version": tmux.get("version"),
+ "status": "ready" if tmux.get("installed") else "missing",
+ }
+ )
+
# Node present but below the Show Runtime minimum (node_supported is False)
# is not actually usable — don't show it green while runtime repair fails.
node_ok = bool(srt.get("node_available")) and srt.get("node_supported") is not False
@@ -4029,6 +4046,22 @@ def _prepare_show_runtime_job() -> dict:
return {"ok": False, "message": str(exc), "output": None}
+def _prepare_tmux_job() -> dict:
+ try:
+ from core.tmux_runtime import ensure_tmux_installed
+
+ payload = ensure_tmux_installed(force=True)
+ ok = bool(payload.get("ok"))
+ return {
+ **payload,
+ "ok": ok,
+ "message": "tmux runtime ready." if ok else (payload.get("message") or payload.get("reason") or "tmux install failed"),
+ "output": payload.get("output"),
+ }
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc), "output": None}
+
+
def _startup_dependency_reconcile_enabled() -> bool:
value = os.environ.get("VIBE_STARTUP_DEPENDENCY_RECONCILE")
return value is None or value.strip().lower() not in {"0", "false", "no", "off"}
@@ -4099,6 +4132,7 @@ def reconcile_startup_dependencies() -> dict:
"askill": {"ok": False, "status": "unknown"},
"avault": {"ok": False, "status": "unknown"},
"show_runtime": {"ok": False, "status": "unknown"},
+ "tmux": {"ok": False, "status": "unknown"},
}
try:
try:
@@ -4148,6 +4182,20 @@ def reconcile_startup_dependencies() -> dict:
logger.warning("Startup dependency reconcile failed to prepare Show Runtime: %s", exc, exc_info=True)
result["show_runtime"] = {"ok": False, "status": "failed", "reason": str(exc)}
+ if os.environ.get("VIBE_UI_ENABLE_TERMINAL", "").strip().lower() in {"0", "false", "no", "off"}:
+ # Terminal explicitly disabled — don't download the optional tmux runtime.
+ result["tmux"] = {"ok": True, "status": "skipped", "reason": "terminal_disabled"}
+ elif os.environ.get("VIBE_INSTALL_SKIP_TMUX", "").strip().lower() in _TRUTHY_ENV_VALUES:
+ result["tmux"] = {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_TMUX"}
+ else:
+ try:
+ from core.tmux_runtime import ensure_tmux_installed
+
+ result["tmux"] = ensure_tmux_installed(force=False)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Startup dependency reconcile failed to ensure tmux runtime: %s", exc, exc_info=True)
+ result["tmux"] = {"ok": False, "status": "failed", "reason": str(exc)}
+
result["duration_ms"] = int((time.monotonic() - started_at) * 1000)
result["ok"] = (
bool(result["askill"].get("ok"))
@@ -4198,8 +4246,12 @@ def start_dependency_install_job(dep: str) -> dict:
result = ensure_askill_installed(force=True)
elif dep == "avault":
result = ensure_avault_installed(force=True)
- else:
+ elif dep == "show-runtime":
result = _prepare_show_runtime_job()
+ elif dep == "tmux":
+ result = _prepare_tmux_job()
+ else:
+ result = {"ok": False, "message": f"Unknown dependency: {dep}", "output": None}
ok = bool(result.get("ok"))
with _AGENT_INSTALL_JOB_LOCK:
current = _AGENT_INSTALL_JOBS.get(job_id)
diff --git a/vibe/cli.py b/vibe/cli.py
index 550abe69f..23e3275d0 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -63,6 +63,8 @@ from storage.settings_service import make_scope_id
logger = logging.getLogger(__name__)
UV_TOOL_PACKAGE_NAMES = (PACKAGE_NAME, LEGACY_PACKAGE_NAME)
+_TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
+_FALSY_ENV_VALUES = {"0", "false", "no", "off"}
WATCH_STARTUP_STABLE_RUNNING_SECONDS = 1.5
WATCH_STARTUP_JITTER_BUFFER_SECONDS = 1.0
@@ -6293,9 +6295,11 @@ def cmd_runtime(args) -> int:
offline = True if getattr(args, "offline", False) else None
payload = manager.prepare(force=getattr(args, "force", False), offline=offline)
askill = _ensure_askill_during_prepare(offline=bool(offline))
+ tmux = _ensure_tmux_during_prepare(offline=bool(offline), force=getattr(args, "force", False))
avault = _ensure_avault_during_prepare(offline=bool(offline))
payload["askill"] = askill
payload["avault"] = avault
+ payload["tmux"] = tmux
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
@@ -6319,6 +6323,12 @@ def cmd_runtime(args) -> int:
print("avault installed." if avault.get("changed") else "avault ready.")
else:
print(f"avault not ready: {avault.get('message') or 'install failed'}", file=sys.stderr)
+ if tmux.get("skipped") or tmux.get("status") == "skipped":
+ print(f"tmux: skipped ({tmux.get('reason') or 'skipped'}).")
+ elif tmux.get("ok"):
+ print("tmux installed." if tmux.get("changed") else "tmux ready.")
+ else:
+ print(f"tmux not ready: {tmux.get('message') or tmux.get('reason') or 'install failed'}", file=sys.stderr)
return 1 if getattr(args, "strict", False) and not payload.get("ok") else 0
if command == "clean":
payload = manager.clean(keep_previous=getattr(args, "keep_previous", 1))
@@ -6376,7 +6386,7 @@ def _ensure_askill_during_prepare(offline: bool = False) -> dict:
"""
if offline:
return {"ok": True, "skipped": True, "reason": "offline"}
- if os.environ.get("VIBE_INSTALL_SKIP_ASKILL", "").strip().lower() in {"1", "true", "yes", "on"}:
+ if os.environ.get("VIBE_INSTALL_SKIP_ASKILL", "").strip().lower() in _TRUTHY_ENV_VALUES:
return {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_ASKILL"}
try:
return api.ensure_askill_installed(force=True)
@@ -6384,11 +6394,31 @@ def _ensure_askill_during_prepare(offline: bool = False) -> dict:
return {"ok": False, "message": str(exc)}
+def _ensure_tmux_during_prepare(offline: bool = False, force: bool = False) -> dict:
+ """Ensure optional tmux alongside managed runtimes.
+
+ tmux powers persistent Web Terminal sessions, but absence must never block
+ prepare or upgrades: the terminal backend will fall back to ephemeral PTY.
+ """
+ if offline:
+ return {"ok": True, "skipped": True, "reason": "offline"}
+ if os.environ.get("VIBE_UI_ENABLE_TERMINAL", "").strip().lower() in _FALSY_ENV_VALUES:
+ return {"ok": True, "status": "skipped", "reason": "terminal_disabled"}
+ if os.environ.get("VIBE_INSTALL_SKIP_TMUX", "").strip().lower() in _TRUTHY_ENV_VALUES:
+ return {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_TMUX"}
+ try:
+ from core.tmux_runtime import ensure_tmux_installed
+
+ return ensure_tmux_installed(force=force)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
def _ensure_avault_during_prepare(offline: bool = False) -> dict:
"""Ensure avault (the Vault custody core) alongside other local deps."""
if offline:
return {"ok": True, "skipped": True, "reason": "offline"}
- if os.environ.get("VIBE_INSTALL_SKIP_AVAULT", "").strip().lower() in {"1", "true", "yes", "on"}:
+ if os.environ.get("VIBE_INSTALL_SKIP_AVAULT", "").strip().lower() in _TRUTHY_ENV_VALUES:
return {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_AVAULT"}
try:
return api.ensure_avault_installed(force=True)
diff --git a/vibe/tmux_runtime_manifest.json b/vibe/tmux_runtime_manifest.json
new file mode 100644
index 000000000..903a38a01
--- /dev/null
+++ b/vibe/tmux_runtime_manifest.json
@@ -0,0 +1,38 @@
+{
+ "schema_version": 1,
+ "tmux_version": "3.6b",
+ "source": "tmux/tmux-builds",
+ "source_url": "https://github.com/tmux/tmux-builds/releases/tag/v3.6b",
+ "requires_utf8proc": true,
+ "terminfo": "bundled-or-system",
+ "archives": {
+ "darwin-arm64": {
+ "name": "tmux-3.6b-macos-arm64.tar.gz",
+ "url": "https://github.com/tmux/tmux-builds/releases/download/v3.6b/tmux-3.6b-macos-arm64.tar.gz",
+ "sha256": "88323402bd28d21103239caf009b130086ebf334807de485d4a1e1c7188ee810",
+ "size": 623837,
+ "bin_path": "tmux"
+ },
+ "darwin-x64": {
+ "name": "tmux-3.6b-macos-x86_64.tar.gz",
+ "url": "https://github.com/tmux/tmux-builds/releases/download/v3.6b/tmux-3.6b-macos-x86_64.tar.gz",
+ "sha256": "073f6e2c2baa7eb5d643563600ee6052ca8619f3ec5a0cfdf99c56397fb72c94",
+ "size": 650495,
+ "bin_path": "tmux"
+ },
+ "linux-arm64": {
+ "name": "tmux-3.6b-linux-arm64.tar.gz",
+ "url": "https://github.com/tmux/tmux-builds/releases/download/v3.6b/tmux-3.6b-linux-arm64.tar.gz",
+ "sha256": "fd4a2206c5e468dd2ee4e9a65f2d40e0762551965d7fdbe849c494ab14f513e9",
+ "size": 956861,
+ "bin_path": "tmux"
+ },
+ "linux-x64": {
+ "name": "tmux-3.6b-linux-x86_64.tar.gz",
+ "url": "https://github.com/tmux/tmux-builds/releases/download/v3.6b/tmux-3.6b-linux-x86_64.tar.gz",
+ "sha256": "002a6f4fd52212600fa0d72d865dcf328e5b8b6e83c179788144d8587b75677a",
+ "size": 958795,
+ "bin_path": "tmux"
+ }
+ }
+}
diff --git a/vibe/ui_compat.py b/vibe/ui_compat.py
index bdcd45a69..2a3d4e1dc 100644
--- a/vibe/ui_compat.py
+++ b/vibe/ui_compat.py
@@ -276,6 +276,9 @@ class CompatTestClient:
def post(self, url: str, **kwargs: Any) -> CompatTestResponse:
return self.request("POST", url, **kwargs)
+ def put(self, url: str, **kwargs: Any) -> CompatTestResponse:
+ return self.request("PUT", url, **kwargs)
+
def patch(self, url: str, **kwargs: Any) -> CompatTestResponse:
return self.request("PATCH", url, **kwargs)
@@ -406,6 +409,43 @@ class CompatApp(FastAPI):
def test_client(self) -> CompatTestClient:
return CompatTestClient(self)
+ async def dispatch_native_request(
+ self,
+ starlette_request: FastAPIRequest,
+ func: Callable[..., Any],
+ ) -> Response:
+ """Run a native FastAPI endpoint through the shared UI request hooks.
+
+ New async FastAPI routes can avoid the legacy ``@app.route`` shim while
+ still inheriting the remote-access, CSRF, and response hooks registered
+ through ``before_request`` / ``after_request`` during the migration.
+ """
+ remote_addr = _test_remote_addr_from_scope(starlette_request.scope)
+ if remote_addr:
+ starlette_request.scope["vibe_remote_addr"] = remote_addr
+ compat_request = CompatRequest(starlette_request)
+ token_request = _request_var.set(compat_request)
+ token_g = _g_var.set(type("CompatG", (), {})())
+ try:
+ response: Response | None = None
+ try:
+ for before in self._before_request_handlers:
+ result = await run_maybe_async(before)
+ if result is not None:
+ response = normalize_response(result)
+ break
+ if response is None:
+ compat_request._json_payload = await _read_json_payload(starlette_request)
+ response = normalize_response(await run_maybe_async(func))
+ except Exception as exc:
+ response = await self._handle_compat_exception(exc)
+ for after in reversed(self._after_request_handlers):
+ response = normalize_response(await run_maybe_async(after, response))
+ return response
+ finally:
+ _g_var.reset(token_g)
+ _request_var.reset(token_request)
+
@contextlib.contextmanager
def test_request_context(
self,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3749c72b0..17c862ef1 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -40,6 +40,7 @@ from core.show_pages import (
show_event_write_token,
)
from core.show_session_events import show_event_payload_session_mismatch
+from core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_id
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.i18n import get_supported_languages, t
from vibe.runtime import get_ui_dist_path, get_working_dir
@@ -106,6 +107,10 @@ _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH = (
f"/_show-runtime/react-refresh-shim-{_SHOW_RUNTIME_PUBLIC_SHIM_VERSION}.js"
)
_SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES = 1024
+TERMINAL_ENABLED_ENV = "VIBE_UI_ENABLE_TERMINAL"
+TERMINAL_IDLE_TIMEOUT_ENV = "VIBE_UI_TERMINAL_IDLE_TIMEOUT_SECONDS"
+TERMINAL_MAX_SESSIONS_ENV = "VIBE_UI_TERMINAL_MAX_SESSIONS"
+_TRUE_BOOL_STRINGS = {"1", "true", "yes", "on"}
STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")
LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")
@@ -140,6 +145,22 @@ LOG_SOURCES = (
)
+def _env_int(name: str, default: int) -> int:
+ try:
+ return int(os.environ.get(name, str(default)))
+ except (TypeError, ValueError):
+ logger.warning("Ignoring invalid integer env var %s", name)
+ return default
+
+
+def _parse_explicit_bool(value: Any) -> bool:
+ if value is True:
+ return True
+ if isinstance(value, str):
+ return value.strip().lower() in _TRUE_BOOL_STRINGS
+ return False
+
+
def _recover_stale_session_status(session_id: str) -> bool:
"""Clear a persisted ``running`` dot after the controller proves idle.
@@ -639,6 +660,16 @@ def _env_flag_enabled(name: str) -> bool:
return os.environ.get(name, "").lower() in {"1", "true", "yes", "on"}
+def _terminal_enabled() -> bool:
+ # The Web Terminal is ON by default; set VIBE_UI_ENABLE_TERMINAL to a falsy
+ # value (0/false/no/off) to turn it off. The WebSocket auth gate still
+ # authorizes every connection regardless of this flag.
+ raw = os.environ.get(TERMINAL_ENABLED_ENV)
+ if raw is None or raw.strip() == "":
+ return True
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
+
+
def _has_loopback_only_docker_port_binding() -> bool:
bind_host = os.environ.get("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST")
if not bind_host:
@@ -1003,9 +1034,33 @@ def _remote_access_public_host(config: V2Config) -> str | None:
return _normalized_host(parsed.hostname)
+def _remote_access_public_origin(config: V2Config) -> str | None:
+ public_url = (config.remote_access.vibe_cloud.public_url or "").strip()
+ if not public_url:
+ return ""
+ parsed = urlparse(public_url)
+ if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password:
+ return None
+ return f"{parsed.scheme}://{parsed.netloc.lower().rstrip('.')}"
+
+
+def _origin_identity(value: str) -> tuple[str, str, int | None] | None:
+ parsed = urlparse(value)
+ if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password:
+ return None
+ return (parsed.scheme.lower(), _normalized_host(parsed.hostname), _origin_port(parsed.netloc, parsed.scheme))
+
+
+def _remote_access_public_origin_matches(origin: str, config: V2Config) -> bool:
+ trusted_origin = _remote_access_public_origin(config)
+ if not trusted_origin:
+ return False
+ return _origin_identity(origin) == _origin_identity(trusted_origin)
+
+
def _remote_access_public_url_invalid(config: V2Config) -> bool:
cloud = config.remote_access.vibe_cloud
- return bool(cloud.enabled and not _remote_access_public_host(config))
+ return bool(cloud.enabled and not _remote_access_public_origin(config))
def _remote_access_snapshot(config: V2Config) -> dict[str, Any]:
@@ -2043,6 +2098,52 @@ async def public_show_runtime_hmr_websocket(websocket: WebSocket, share_id: str)
await websocket.close(code=1011)
[email protected]("/api/terminal/{session_id}")
+async def terminal_websocket(websocket: WebSocket, session_id: str):
+ if not _terminal_enabled():
+ await websocket.accept()
+ await websocket.close(code=1008)
+ return
+ if not TERMINAL_SUPPORTED:
+ # POSIX-only — no PTY/tmux on native Windows.
+ await websocket.accept()
+ await websocket.close(code=1008)
+ return
+ # CSWSH guard. Local trusted terminal sockets have no cookie gate, so the
+ # Origin must match the exact socket. Remote terminals are cookie-authenticated,
+ # so pin them to the configured public origin as well.
+ if not _terminal_origin_allowed(websocket):
+ await websocket.close(code=1008)
+ return
+ if not _show_runtime_websocket_authorized(websocket):
+ await websocket.close(code=1008)
+ return
+
+ await websocket.accept()
+ remote_addr = _websocket_client_host(websocket) or "unknown"
+ remote_subject = _remote_access_websocket_subject(websocket)
+ effective_session_id = _terminal_effective_session_id(session_id, remote_subject)
+ session_ref = _terminal_session_log_ref(effective_session_id)
+ logger.info("terminal.session_open session_ref=%s remote_addr=%s", session_ref, remote_addr)
+ try:
+ service = get_terminal_service()
+ service.start_reaper()
+ await service.handle_websocket(websocket, effective_session_id)
+ except TerminalServiceError as exc:
+ # Transient "try again shortly" conditions (not server faults): too_many_sessions (cap
+ # full) and session_opening (the id is mid-open or mid-teardown). Close with 1013 so
+ # the client can auto-retry instead of surfacing a hard error.
+ transient = str(exc) in {"too_many_sessions", "session_opening"}
+ await websocket.close(code=1013 if transient else 1011)
+ except WebSocketDisconnect:
+ return
+ except Exception:
+ logger.debug("Terminal websocket failed", exc_info=True)
+ await websocket.close(code=1011)
+ finally:
+ logger.info("terminal.session_close session_ref=%s remote_addr=%s", session_ref, remote_addr)
+
+
def _show_runtime_websocket_authorized(websocket: WebSocket) -> bool:
config = _load_remote_access_config()
if config is None:
@@ -2051,14 +2152,94 @@ def _show_runtime_websocket_authorized(websocket: WebSocket) -> bool:
return True
if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
return False
+ return _remote_access_websocket_session_payload(websocket, config) is not None
+
+
+def _remote_access_websocket_session_payload(websocket: WebSocket, config: V2Config | None) -> dict[str, Any] | None:
+ if config is None or _websocket_is_local_request(websocket, config):
+ return None
+ if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
+ return None
from vibe import remote_access
if not config.remote_access.vibe_cloud.enabled or not config.remote_access.vibe_cloud.session_secret:
- return False
+ return None
return remote_access.parse_session_cookie(
config,
websocket.cookies.get(remote_access.SESSION_COOKIE_NAME),
- ) is not None
+ )
+
+
+def _remote_access_websocket_subject(websocket: WebSocket) -> str | None:
+ payload = _remote_access_websocket_session_payload(websocket, _load_remote_access_config())
+ if not payload:
+ return None
+ subject = str(payload.get("sub") or "").strip()
+ email = str(payload.get("email") or "").strip()
+ return subject or email or None
+
+
+def _terminal_effective_session_id(client_session_id: str, remote_subject: str | None) -> str:
+ safe_client_id = sanitize_session_id(client_session_id)
+ if not remote_subject:
+ return safe_client_id
+ subject_hash = hashlib.sha256(remote_subject.encode("utf-8")).hexdigest()[:16]
+ return f"{subject_hash}-{safe_client_id[:63]}"
+
+
+def _terminal_session_log_ref(effective_session_id: str) -> str:
+ return hashlib.sha256(effective_session_id.encode("utf-8")).hexdigest()[:16]
+
+
+def _terminal_origin_allowed(websocket: WebSocket) -> bool:
+ origin = _request_origin(websocket.headers.get("origin"))
+ if not origin:
+ return False
+ parsed_origin = urlparse(origin)
+ if _normalized_host(parsed_origin.netloc) != _websocket_normalized_host(websocket):
+ return False
+ # Mirror _show_runtime_websocket_authorized's local classification: loopback AND
+ # private setup-host requests are both accepted without a cookie, so both must clear
+ # the exact scheme+port check below. Without the config, _websocket_is_local_request
+ # cannot recognize a setup-host request as local and we would fall through to the
+ # remote host-only relaxation, letting a same-host page on a different scheme/port
+ # open a cross-origin terminal socket. Remote (public-host + cookie) requests only
+ # need the host match already verified above.
+ config = _load_remote_access_config()
+ if not _websocket_is_local_request(websocket, config):
+ if config is None:
+ return False
+ return _remote_access_public_origin_matches(origin, config)
+ origin_port = _origin_port(parsed_origin.netloc, parsed_origin.scheme)
+ request_port = _origin_port(websocket.headers.get("host"), websocket.url.scheme)
+ return origin_port == request_port and _terminal_origin_scheme_matches_socket(
+ parsed_origin.scheme,
+ websocket.url.scheme,
+ )
+
+
+def _origin_port(netloc: str | None, scheme: str | None) -> int | None:
+ if not netloc:
+ return None
+ parsed = urlparse(f"//{netloc}")
+ try:
+ explicit_port = parsed.port
+ except ValueError:
+ return None
+ if explicit_port is not None:
+ return explicit_port
+ normalized_scheme = (scheme or "").lower()
+ if normalized_scheme in {"https", "wss"}:
+ return 443
+ if normalized_scheme in {"http", "ws"}:
+ return 80
+ return None
+
+
+def _terminal_origin_scheme_matches_socket(origin_scheme: str | None, socket_scheme: str | None) -> bool:
+ origin_secure = (origin_scheme or "").lower() == "https"
+ socket_secure = (socket_scheme or "").lower() == "wss"
+ return origin_secure == socket_secure
def _websocket_is_local_request(websocket: WebSocket, config: V2Config | None = None) -> bool:
@@ -3105,6 +3286,7 @@ def api_session():
"remote": True,
"authenticated": True,
"email": str(payload.get("email", "")),
+ "sub": str(payload.get("sub", "")),
}
)
# Identity payload must never be cached by intermediaries (Cloudflare etc.).
@@ -3692,7 +3874,7 @@ def backend_restart(name):
return jsonify(api.restart_backend(name, metadata=metadata))
-_ALLOWED_DEPENDENCIES = {"askill", "show-runtime"}
+_ALLOWED_DEPENDENCIES = {"askill", "show-runtime", "tmux"}
@app.route("/api/dependencies")
@@ -4944,6 +5126,179 @@ def search_messages_list():
return jsonify(result)
+# =============================================================================
+# Workbench: File Browser
+# =============================================================================
+
+
+def _file_browser_error_response(exc: Exception):
+ from core.file_browser_service import FileBrowserError
+
+ if isinstance(exc, FileBrowserError):
+ return jsonify({"ok": False, "error": {"code": exc.code, "message": exc.message}}), exc.status_code
+ logger.exception("file browser request failed")
+ return jsonify({"ok": False, "error": {"code": "internal_error", "message": "Internal server error"}}), 500
+
+
+async def _dispatch_native_ui_request(starlette_request: FastAPIRequest, handler: Callable[[], Any]):
+ return await app.dispatch_native_request(starlette_request, handler)
+
+
[email protected]("/api/files/list", include_in_schema=False)
+async def files_list(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.list_directory,
+ request.args.get("path") or "",
+ show_hidden=request.args.get("show_hidden") == "1",
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/meta", include_in_schema=False)
+async def files_meta(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ try:
+ return jsonify(await asyncio.to_thread(file_browser_service.metadata, request.args.get("path") or ""))
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/content", include_in_schema=False)
+async def files_content(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ try:
+ content = await asyncio.to_thread(
+ file_browser_service.file_content,
+ request.args.get("path") or "",
+ download=request.args.get("download") == "1",
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+ return FastAPIResponse(
+ content=content.data,
+ media_type=content.mime,
+ headers={
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ "Cache-Control": "private, no-store",
+ "Content-Disposition": f"{content.disposition}; filename*=UTF-8''{quote(content.path.name)}",
+ },
+ )
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/write", include_in_schema=False)
+async def files_write(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.write_file,
+ payload.get("path") or "",
+ payload.get("content"),
+ expected_mtime=payload.get("expected_mtime"),
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/mkdir", include_in_schema=False)
+async def files_mkdir(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(await asyncio.to_thread(file_browser_service.make_directory, payload.get("path") or ""))
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/rename", include_in_schema=False)
+async def files_rename(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.rename_path,
+ payload.get("path") or "",
+ payload.get("new_name") or "",
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/move", include_in_schema=False)
+async def files_move(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.move_path,
+ payload.get("src") or "",
+ payload.get("dst") or "",
+ overwrite=_parse_explicit_bool(payload.get("overwrite")),
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/files/delete", include_in_schema=False)
+async def files_delete(starlette_request: FastAPIRequest):
+ async def handler():
+ from core import file_browser_service
+
+ payload = request.json or {}
+ try:
+ return jsonify(
+ await asyncio.to_thread(
+ file_browser_service.delete_path,
+ payload.get("path") or "",
+ recursive=_parse_explicit_bool(payload.get("recursive")),
+ )
+ )
+ except Exception as exc:
+ return _file_browser_error_response(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
# Content types the media proxy is willing to serve ``inline``. Anything else —
# text/html, image/svg+xml, xml, application/octet-stream, unknown — is forced to
# ``attachment`` so a preview-open of agent-produced ACTIVE content can't execute
@@ -7372,6 +7727,7 @@ def _reconcile_remote_access_for_ui_start(config: V2Config | None) -> None:
_inbox_bridge_task: "asyncio.Task | None" = None
_startup_dependency_reconcile_task: "asyncio.Task | None" = None
+_terminal_service: TerminalService | None = None
async def _start_inbox_bridge() -> None:
@@ -7399,6 +7755,32 @@ app.add_event_handler("startup", _start_inbox_bridge)
app.add_event_handler("shutdown", _stop_inbox_bridge)
+def get_terminal_service() -> TerminalService:
+ global _terminal_service
+ if _terminal_service is None:
+ _terminal_service = TerminalService(
+ idle_timeout_seconds=_env_int(TERMINAL_IDLE_TIMEOUT_ENV, 3600),
+ max_sessions=_env_int(TERMINAL_MAX_SESSIONS_ENV, 8),
+ )
+ return _terminal_service
+
+
+async def _start_terminal_service() -> None:
+ if _terminal_enabled():
+ get_terminal_service().start_reaper()
+
+
+async def _stop_terminal_service() -> None:
+ global _terminal_service
+ service, _terminal_service = _terminal_service, None
+ if service is not None:
+ await service.shutdown()
+
+
+app.add_event_handler("startup", _start_terminal_service)
+app.add_event_handler("shutdown", _stop_terminal_service)
+
+
async def _reconcile_startup_dependencies_task() -> None:
start = time.monotonic()
try: