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): "Open Terminal Here" from the Files app (#840)

Call White3400bd90e244
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index 586b6e6d4..e6891d9a2 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -108,6 +108,43 @@ def _expanded_absolute_path(raw: str) -> Path:
return expanded
+def resolve_existing_directory(raw: str) -> Path:
+ """Resolve an absolute path to an existing directory WITHOUT following a symlink on the
+ final component.
+
+ Same hardening family as the upload-destination check (``_resolve_upload_directory``) and
+ the list/write/rename mutations: expand ``~``, require absolute, canonicalize the PARENT
+ strictly, append the final component without following a symlink there, then require the
+ result to be a real directory. Raises ``FileBrowserError`` / ``NotFoundError`` on any
+ violation. Shared by the terminal service's "Open Terminal Here" start directory.
+ """
+ resolve_safe_path(raw) # reject blank / relative / uncanonicalizable early
+ expanded = _expanded_absolute_path(raw)
+ if expanded.parent == expanded:
+ directory = expanded # a filesystem root is a valid, already-canonical directory
+ else:
+ if expanded.name in {"", ".", ".."} or _raw_final_component(raw) in {".", ".."}:
+ raise NotFoundError("Directory not found")
+ try:
+ parent = expanded.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise NotFoundError("Directory not found") from exc
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ directory = parent / expanded.name
+ try:
+ stat_result = directory.lstat()
+ except FileNotFoundError as exc:
+ raise NotFoundError("Directory not found") 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 not stat.S_ISDIR(stat_result.st_mode):
+ raise FileBrowserError("not_dir", "Path is not a directory", 400)
+ return directory
+
+
def _resolve_existing_path(raw: str) -> Path:
resolved = resolve_safe_path(raw)
try:
@@ -694,36 +731,18 @@ def _validate_new_name(new_name: str) -> str:
def _resolve_upload_directory(raw_dir: str) -> Path:
+ # Shares the no-follow directory resolver; only remaps its errors to the upload API's
+ # historical contract (an unusable destination reads as "not found", not invalid_path).
try:
- resolve_safe_path(raw_dir)
- expanded = _expanded_absolute_path(raw_dir)
- except FileBrowserError as exc:
+ return resolve_existing_directory(raw_dir)
+ except NotFoundError as exc:
raise NotFoundError("Destination directory not found") from exc
-
- if expanded.parent == expanded:
- directory = expanded
- else:
- if expanded.name in {"", ".", ".."} or _raw_final_component(raw_dir) in {".", ".."}:
- raise NotFoundError("Destination directory not found")
- try:
- parent = expanded.parent.resolve(strict=True)
- except FileNotFoundError as exc:
+ except FileBrowserError as exc:
+ if exc.code == "invalid_path":
raise NotFoundError("Destination directory not found") from exc
- except (OSError, RuntimeError, ValueError) as exc:
- raise FileBrowserError("fs_error", str(exc), 400) from exc
- directory = parent / expanded.name
-
- try:
- stat_result = directory.lstat()
- except FileNotFoundError as exc:
- raise NotFoundError("Destination directory not found") 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 not stat.S_ISDIR(stat_result.st_mode):
- raise FileBrowserError("not_dir", "Destination is not a directory", 400)
- return directory
+ if exc.code == "not_dir":
+ raise FileBrowserError("not_dir", "Destination is not a directory", 400) from exc
+ raise
def _open_stable_upload_directory(directory: Path) -> int | None:
diff --git a/core/terminal_service.py b/core/terminal_service.py
index 82e31930f..76be4d1c0 100644
--- a/core/terminal_service.py
+++ b/core/terminal_service.py
@@ -127,9 +127,11 @@ class TerminalService:
elif session.persistent:
await _kill_tmux_session(session.session_id)
- async def handle_websocket(self, websocket: WebSocket, raw_session_id: str) -> None:
+ async def handle_websocket(
+ self, websocket: WebSocket, raw_session_id: str, *, initial_cwd: str | None = None
+ ) -> None:
session_id = sanitize_session_id(raw_session_id)
- connection = await self.open(session_id)
+ connection = await self.open(session_id, initial_cwd=initial_cwd)
try:
await websocket.send_text(json.dumps({"type": "ready", "persistent": connection.persistent}))
except BaseException:
@@ -197,7 +199,7 @@ class TerminalService:
await asyncio.gather(output_task, input_task, wait_task, return_exceptions=True)
await self.close(connection)
- async def open(self, session_id: str) -> TerminalConnection:
+ async def open(self, session_id: str, *, initial_cwd: str | None = None) -> 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
@@ -232,14 +234,32 @@ class TerminalService:
if replaced is not None:
await self._teardown_client(replaced, kill_session=False)
+ # A validated, enterable start directory for a brand-new session ("Open Terminal
+ # Here"); None (unset, invalid, or inaccessible) falls back to home. An unusable cwd
+ # must never fail the connection. See _resolve_initial_cwd.
+ start_dir = _resolve_initial_cwd(initial_cwd)
+
persistent = False
tmux_binary = resolve_tmux_binary()
if tmux_binary:
cmd = _tmux_launch_command(tmux_binary, session_id)
persistent = True
+ if start_dir is not None and await _tmux_has_session(session_id):
+ # A brand-new tmux session (launched with -f /dev/null, so no default-path)
+ # takes its start directory from the client process cwd set below; an existing
+ # session ignores the client cwd on reattach. Clear start_dir when the session
+ # already exists so a reconnect never re-steers a live/detached session —
+ # reattach semantics stay exactly as before. (Passing the directory as the
+ # client cwd, rather than as a tmux `-c` argument, also keeps it out of tmux's
+ # command-sequence parsing, where a trailing ';' would be a separator.)
+ start_dir = None
else:
cmd = [os.environ.get("SHELL") or "/bin/bash", "-l"]
+ # For a new tmux session this becomes its start directory (via the client cwd); for the
+ # plain-shell fallback it is the shell's own cwd. Falls back to home when unset.
+ spawn_cwd = start_dir or str(Path.home())
+
master_fd, slave_fd = os.openpty()
try:
process = await asyncio.create_subprocess_exec(
@@ -247,7 +267,7 @@ class TerminalService:
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
- cwd=str(Path.home()),
+ cwd=spawn_cwd,
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
@@ -594,6 +614,35 @@ def sanitize_session_id(raw_session_id: str) -> str:
return safe or "terminal"
+def _resolve_initial_cwd(raw: str | None) -> str | None:
+ """Validate a requested start directory for a NEW terminal session.
+
+ Reuses the file browser's directory hardening (absolute, expanded/canonicalized, existing,
+ a real directory, no symlink followed on the final component) and then checks the process
+ can actually enter it (search/execute permission). That extra check matters because the
+ hardening only lstats the final component, so a directory that exists but is unenterable
+ (e.g. a 0700 directory owned by another user under a listable parent) would otherwise reach
+ the spawn and raise there — closing the socket instead of falling back. Anything invalid —
+ unset, relative, missing, a file, a symlink, or inaccessible — yields None so the caller
+ falls back to the default cwd. Never raises: an unusable cwd must not fail the terminal
+ connection, so it is logged at debug and dropped. Imported lazily since this only runs for an
+ "Open Terminal Here" open, keeping the normal terminal-open path free of the dependency.
+ """
+ if not raw:
+ return None
+ try:
+ from core import file_browser_service
+
+ resolved = file_browser_service.resolve_existing_directory(raw)
+ if not os.access(resolved, os.X_OK):
+ logger.debug("terminal initial cwd not searchable; using default")
+ return None
+ return str(resolved)
+ except Exception:
+ logger.debug("terminal initial cwd rejected; using default", exc_info=True)
+ return None
+
+
def _tmux_launch_command(tmux_binary: str, session_id: str) -> list[str]:
return [
tmux_binary,
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index bc31d9bc6..330ec6de6 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -1498,7 +1498,7 @@ def test_terminal_websocket_accepts_local_origin_from_same_port(monkeypatch, tmp
accepted = False
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
nonlocal accepted
accepted = True
@@ -1513,6 +1513,27 @@ def test_terminal_websocket_accepts_local_origin_from_same_port(monkeypatch, tmp
assert accepted is True
+def test_terminal_websocket_threads_cwd_query_param(monkeypatch, tmp_path):
+ # "Open Terminal Here" passes the start dir as a ?cwd= query param; the route must forward it
+ # to the service as initial_cwd (validation/fallback happens inside the service).
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ seen: dict = {}
+
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
+ seen["initial_cwd"] = initial_cwd
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+
+ with app.test_client().websocket_connect(
+ "/api/terminal/test?cwd=%2Fhome%2Falex%2Fproj",
+ headers={"host": "127.0.0.1:5123", "origin": "http://127.0.0.1:5123"},
+ ):
+ pass
+
+ assert seen.get("initial_cwd") == "/home/alex/proj"
+
+
def test_terminal_delete_terminates_scoped_local_session(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -1646,3 +1667,186 @@ def test_terminal_service_ignores_invalid_limit_env(monkeypatch):
assert service.max_sessions == 8
finally:
monkeypatch.setattr(ui_server, "_terminal_service", None)
+
+
+# ---------------------------------------------------------------------------
+# "Open Terminal Here" — a new session may start in a validated initial cwd.
+# ---------------------------------------------------------------------------
+
+
+async def _capture_terminal_open(monkeypatch, tmp_path, *, tmux, has_session, initial_cwd):
+ """Open one terminal session and return the captured spawn {cmd, cwd}.
+
+ Stubs the PTY + subprocess so the test observes exactly what open() would launch: the
+ argv (for the tmux -c start-directory) and the subprocess cwd (for the plain-shell
+ fallback). No real shell or tmux is started.
+ """
+ (tmp_path / "home").mkdir(exist_ok=True)
+ 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: "/usr/bin/tmux" if tmux else None)
+ if tmux:
+ await _set_tmux_has_session(monkeypatch, has_session)
+
+ async def _noop_kill(_session_id):
+ return None
+
+ async def _noop_kill_server():
+ return None
+
+ monkeypatch.setattr(terminal_service, "_kill_tmux_session", _noop_kill)
+ monkeypatch.setattr(terminal_service, "_kill_tmux_server", _noop_kill_server)
+
+ captured: dict = {}
+ 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
+
+ class _FakeProcess:
+ returncode = None
+ pid = None
+
+ def send_signal(self, _signum: int) -> None:
+ pass
+
+ async def wait(self) -> int:
+ return 0
+
+ async def fake_spawn(*args, **kwargs):
+ captured["cmd"] = list(args)
+ captured["cwd"] = kwargs.get("cwd")
+ return _FakeProcess()
+
+ monkeypatch.setattr(terminal_service.os, "openpty", fake_openpty)
+ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", fake_spawn)
+
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ try:
+ await service.open("openhere", initial_cwd=initial_cwd)
+ return captured
+ finally:
+ await service.shutdown()
+ for fd in opened_fds:
+ terminal_service._close_fd(fd)
+
+
+def _resolved(path) -> "terminal_service.Path":
+ # macOS puts tmp_path under a /var -> /private/var symlink; compare canonicalized paths.
+ return terminal_service.Path(path).resolve()
+
+
+def test_new_session_applies_initial_cwd_plain_shell(monkeypatch, tmp_path):
+ asyncio.run(_new_session_applies_initial_cwd_plain_shell(monkeypatch, tmp_path))
+
+
+async def _new_session_applies_initial_cwd_plain_shell(monkeypatch, tmp_path):
+ # A valid initial cwd becomes the plain-shell fallback's spawn cwd (the shell starts there).
+ workdir = tmp_path / "workdir"
+ workdir.mkdir()
+ captured = await _capture_terminal_open(
+ monkeypatch, tmp_path, tmux=False, has_session=False, initial_cwd=str(workdir)
+ )
+ assert _resolved(captured["cwd"]) == workdir.resolve()
+
+
+def test_invalid_initial_cwd_falls_back_to_home_plain_shell(monkeypatch, tmp_path):
+ asyncio.run(_invalid_initial_cwd_falls_back_to_home_plain_shell(monkeypatch, tmp_path))
+
+
+async def _invalid_initial_cwd_falls_back_to_home_plain_shell(monkeypatch, tmp_path):
+ # A missing directory must NOT fail the connection — it silently falls back to home.
+ missing = tmp_path / "does-not-exist"
+ captured = await _capture_terminal_open(
+ monkeypatch, tmp_path, tmux=False, has_session=False, initial_cwd=str(missing)
+ )
+ assert _resolved(captured["cwd"]) == (tmp_path / "home").resolve()
+
+
+def test_symlink_final_component_initial_cwd_rejected(monkeypatch, tmp_path):
+ asyncio.run(_symlink_final_component_initial_cwd_rejected(monkeypatch, tmp_path))
+
+
+async def _symlink_final_component_initial_cwd_rejected(monkeypatch, tmp_path):
+ # No-follow on the final component: a symlink pointing at a real directory is refused as a
+ # start dir (same hardening as the files API), so it falls back to home.
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real, target_is_directory=True)
+ captured = await _capture_terminal_open(
+ monkeypatch, tmp_path, tmux=False, has_session=False, initial_cwd=str(link)
+ )
+ assert _resolved(captured["cwd"]) == (tmp_path / "home").resolve()
+
+
+def test_tmux_new_session_starts_in_initial_cwd(monkeypatch, tmp_path):
+ asyncio.run(_tmux_new_session_starts_in_initial_cwd(monkeypatch, tmp_path))
+
+
+async def _tmux_new_session_starts_in_initial_cwd(monkeypatch, tmp_path):
+ # A brand-new tmux session (has-session False) takes its start directory from the client
+ # process cwd — the launch command stays the plain `new-session` (no cwd baked into the tmux
+ # command string, so a directory name is never parsed as tmux syntax).
+ workdir = tmp_path / "proj"
+ workdir.mkdir()
+ captured = await _capture_terminal_open(
+ monkeypatch, tmp_path, tmux=True, has_session=False, initial_cwd=str(workdir)
+ )
+ assert "-c" not in captured["cmd"]
+ assert _resolved(captured["cwd"]) == workdir.resolve()
+
+
+def test_tmux_reattach_ignores_initial_cwd(monkeypatch, tmp_path):
+ asyncio.run(_tmux_reattach_ignores_initial_cwd(monkeypatch, tmp_path))
+
+
+async def _tmux_reattach_ignores_initial_cwd(monkeypatch, tmp_path):
+ # Reattaching an EXISTING tmux session (has-session True) must not steer it: the client cwd
+ # falls back to home, so the session keeps its own cwd — reattach semantics are unchanged.
+ workdir = tmp_path / "proj"
+ workdir.mkdir()
+ captured = await _capture_terminal_open(
+ monkeypatch, tmp_path, tmux=True, has_session=True, initial_cwd=str(workdir)
+ )
+ assert "-c" not in captured["cmd"]
+ assert _resolved(captured["cwd"]) == (tmp_path / "home").resolve()
+
+
+def test_resolve_initial_cwd_rejects_inaccessible_dir(tmp_path):
+ # A directory that exists but the process cannot enter (no search/execute bit) must be
+ # rejected so it falls back to the default cwd instead of failing the spawn. Root bypasses
+ # permission bits, so skip there.
+ if hasattr(os, "geteuid") and os.geteuid() == 0:
+ import pytest as _pytest
+
+ _pytest.skip("root bypasses directory permission bits")
+ locked = tmp_path / "locked"
+ locked.mkdir()
+ os.chmod(locked, 0o000)
+ try:
+ assert terminal_service._resolve_initial_cwd(str(locked)) is None
+ finally:
+ os.chmod(locked, 0o700) # restore so tmp_path teardown can remove it
+
+ usable = tmp_path / "usable"
+ usable.mkdir()
+ assert _resolved(terminal_service._resolve_initial_cwd(str(usable))) == usable.resolve()
+
+
+def test_resolve_initial_cwd_rejects_non_directories(tmp_path):
+ # Blank/None, a regular file, and a symlinked final component all fall back (None).
+ assert terminal_service._resolve_initial_cwd(None) is None
+ assert terminal_service._resolve_initial_cwd("") is None
+ a_file = tmp_path / "file.txt"
+ a_file.write_text("x", encoding="utf-8")
+ assert terminal_service._resolve_initial_cwd(str(a_file)) is None
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real, target_is_directory=True)
+ assert terminal_service._resolve_initial_cwd(str(link)) is None
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index 9d4ebb862..c7ef47dd2 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -1876,7 +1876,7 @@ def test_terminal_websocket_accepts_setup_host_origin_from_same_port(monkeypatch
accepted = False
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
nonlocal accepted
accepted = True
@@ -1905,7 +1905,7 @@ def test_terminal_websocket_accepts_setup_host_from_trusted_proxy(monkeypatch, t
accepted = False
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
nonlocal accepted
accepted = True
@@ -1942,7 +1942,7 @@ def test_terminal_websocket_accepts_trusted_public_origin_from_proxy_when_remote
accepted = False
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
nonlocal accepted
accepted = True
@@ -2055,7 +2055,7 @@ def test_terminal_websocket_accepts_remote_exact_trusted_origin(monkeypatch, tmp
config = _save_config(tmp_path)
accepted = False
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
nonlocal accepted
accepted = True
@@ -2100,7 +2100,7 @@ def test_terminal_websocket_scopes_remote_session_id_by_authenticated_subject(mo
config = _save_config(tmp_path)
handled_session_ids: list[str] = []
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
handled_session_ids.append(session_id)
monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
@@ -2139,7 +2139,7 @@ def test_terminal_websocket_keeps_local_session_id_unscoped(monkeypatch, tmp_pat
_mock_interface(monkeypatch, "192.168.2.3", 24)
handled_session_ids: list[str] = []
- async def fake_handle_websocket(websocket, session_id):
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
handled_session_ids.append(session_id)
monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index 957981fe9..f614f584e 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -22,6 +22,7 @@ import {
Pencil,
RefreshCw,
Search,
+ SquareTerminal,
Trash2,
Upload,
X,
@@ -289,6 +290,20 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
[wm, routerNavigate],
);
+ // Open a terminal rooted at a folder ("Open Terminal Here"): desktop opens a Terminal window
+ // whose first tab starts in `dir`; mobile — which has no window layer — navigates to the terminal
+ // route with the dir in router state. Mirrors openInEditor.
+ const openTerminalHere = useCallback(
+ (dir: string) => {
+ if (window.matchMedia('(min-width: 768px)').matches) {
+ wm.openApp('terminal', { params: { cwd: dir } });
+ } else {
+ routerNavigate('/apps/terminal', { state: { cwd: dir } });
+ }
+ },
+ [wm, routerNavigate],
+ );
+
// Open: dir → navigate (and leave search); image / PDF / Office / Markdown → the standalone Preview
// window (desktop) or the in-page overlay (mobile, which has no window layer); editable text/code
// file (within the size cap) → Editor (desktop window / mobile route); anything else → download.
@@ -634,7 +649,9 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
const showInitialSpinner = inSearch ? searchBusy && searchResults === null : loading && !listing;
const showEmpty = inSearch ? !searchBusy && (searchResults?.length ?? 0) === 0 : !!listing && rows.length === 0 && newEntry === null;
- const menuItemCount = menu ? (menu.item ? (menu.item.entry.kind === 'dir' ? 3 : 4) : 2) : 0;
+ // Row: file = Open/Download/Rename/Delete (4); dir = Open/Open Terminal Here/Rename/Delete (4).
+ // Blank: New File/New Folder (+ Open Terminal Here when a folder is loaded).
+ const menuItemCount = menu ? (menu.item ? 4 : cwd ? 3 : 2) : 0;
return (
<div className={windowed ? 'relative flex h-full w-full flex-col bg-surface' : 'relative flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'}>
@@ -953,6 +970,17 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
void openItem(it);
}}
/>
+ {menu.item.entry.kind === 'dir' && (
+ <ContextMenuItem
+ icon={<SquareTerminal className="size-3.5 text-mint" />}
+ label={t('apps.fileBrowser.openTerminalHere')}
+ onClick={() => {
+ const it = menu.item as RowItem;
+ closeMenu();
+ openTerminalHere(it.full);
+ }}
+ />
+ )}
{menu.item.entry.kind !== 'dir' && (
<ContextMenuItem
icon={<Download className="size-3.5 text-mint" />}
@@ -993,6 +1021,16 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
startNewEntry('folder');
}}
/>
+ {cwd && (
+ <ContextMenuItem
+ icon={<SquareTerminal className="size-3.5 text-mint" />}
+ label={t('apps.fileBrowser.openTerminalHere')}
+ onClick={() => {
+ closeMenu();
+ openTerminalHere(cwd);
+ }}
+ />
+ )}
</>
)}
</ContextMenu>
diff --git a/ui/src/components/workbench/AppsTerminalPage.tsx b/ui/src/components/workbench/AppsTerminalPage.tsx
index cc7348acf..791fd0677 100644
--- a/ui/src/components/workbench/AppsTerminalPage.tsx
+++ b/ui/src/components/workbench/AppsTerminalPage.tsx
@@ -1,13 +1,30 @@
+import { useMemo } from 'react';
+import { useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { TerminalTabs } from './TerminalTabs';
+// A start directory handed to the terminal when navigating in from the File Browser on mobile
+// ("Open Terminal Here"). Carried in router state — like the window params `wm.openApp` passes —
+// so absolute paths stay out of the URL. Opening the route directly (tab bar / link, no such
+// navigation) carries no cwd and just opens the default terminal.
+function readCwd(state: unknown): string | null {
+ if (!state || typeof state !== 'object') return null;
+ const cwd = (state as Record<string, unknown>).cwd;
+ return typeof cwd === 'string' && cwd ? cwd : null;
+}
+
// The Terminal app. `windowed` fills its AppWindow body; the route adds the page header.
// The multi-tab UI + per-tab session/slot lifecycle lives in the reusable TerminalTabs
// (so the editor's integrated terminal can mount the same thing later). Design: `iwYIX`.
// windowId + params thread through for windowed mounts so the tab layout persists across reloads.
export const AppsTerminalPage: React.FC<{ windowed?: boolean; windowId?: string; params?: Record<string, unknown> }> = ({ windowed = false, windowId, params }) => {
const { t } = useTranslation();
+ const location = useLocation();
+ // "Open Terminal Here" on mobile: the target dir rides in router state (windowed mounts read it
+ // from `params.cwd` instead). location.key is unique per navigation, so TerminalTabs opens
+ // exactly one tab per launch and leaves the persistent first tab as a reattach.
+ const launchCwd = useMemo(() => readCwd(location.state), [location.state]);
if (windowed) {
return (
@@ -24,7 +41,7 @@ export const AppsTerminalPage: React.FC<{ windowed?: boolean; windowId?: string;
<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">
- <TerminalTabs />
+ <TerminalTabs launchCwd={launchCwd} launchKey={launchCwd ? location.key : undefined} />
</div>
</div>
);
diff --git a/ui/src/components/workbench/TerminalTabs.tsx b/ui/src/components/workbench/TerminalTabs.tsx
index a4d290a79..b5a7376ed 100644
--- a/ui/src/components/workbench/TerminalTabs.tsx
+++ b/ui/src/components/workbench/TerminalTabs.tsx
@@ -31,7 +31,7 @@ function getSessionId(identity: string | null, key?: string): string {
}
}
-type Tab = { key: number; slot: number | null; title?: string };
+type Tab = { key: number; slot: number | null; title?: string; cwd?: string };
// The Terminal's persisted snapshot (via useWindowState): just the tab count + any custom titles.
// Windowed terminal sessions are ephemeral by design (slot-based ids, DELETEd on pagehide), so we
@@ -57,7 +57,16 @@ function deleteTerminalSession(sid: string, slot: number, keepalive = false): vo
// - windowed: every tab is an ephemeral, slot-bounded session, disposed on close.
// - route (non-windowed): the FIRST tab keeps the persistent localStorage session (so it
// reconnects across reloads); extra tabs are slot-bounded like the windowed ones.
-export const TerminalTabs: React.FC<{ windowed?: boolean; windowId?: string; params?: Record<string, unknown> }> = ({ windowed = false, windowId, params }) => {
+export const TerminalTabs: React.FC<{
+ windowed?: boolean;
+ windowId?: string;
+ params?: Record<string, unknown>;
+ // Route (non-windowed) "Open Terminal Here" launch: open ONE extra slot-backed tab in this
+ // directory per distinct `launchKey`, leaving the persistent first tab (a reattach) untouched.
+ // Windowed mounts instead read their first tab's cwd from `params.cwd`.
+ launchCwd?: string | null;
+ launchKey?: string;
+}> = ({ windowed = false, windowId, params, launchCwd, launchKey }) => {
const { t } = useTranslation();
const { getAuthSession } = useApi();
const [identity, setIdentity] = useState<string | null | undefined>(undefined); // undefined = resolving
@@ -75,7 +84,11 @@ export const TerminalTabs: React.FC<{ windowed?: boolean; windowId?: string; par
title: typeof rt?.title === 'string' ? rt.title : undefined,
}));
}
- return [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null }];
+ // A windowed terminal launched from "Open Terminal Here" starts its first (only) tab in that
+ // directory. The route terminal's first tab stays the persistent reattach (slot null); its cwd
+ // tab is appended by the launch effect below instead.
+ const firstCwd = windowed && typeof params?.cwd === 'string' ? (params.cwd as string) : undefined;
+ return [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null, cwd: firstCwd }];
});
const [active, setActive] = useState<number>(() => tabs[0]?.key ?? 0);
// Whether sessions actually persist (tmux available) — reported by TerminalView's ready frame.
@@ -110,6 +123,18 @@ export const TerminalTabs: React.FC<{ windowed?: boolean; windowId?: string; par
};
}, [getAuthSession]);
+ // Route (mobile) "Open Terminal Here": each navigation carries a distinct launchKey. Open exactly
+ // one slot-backed tab in launchCwd and focus it, without disturbing the persistent first tab.
+ // Deduped by key so a re-render (or a StrictMode double-invoke in dev) never opens duplicates.
+ const handledLaunchRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (windowed || !launchCwd || !launchKey || handledLaunchRef.current === launchKey) return;
+ handledLaunchRef.current = launchKey;
+ const tab: Tab = { key: ++tabSeq.current, slot: acquireTerminalSlot(), cwd: launchCwd };
+ setTabs((ts) => [...ts, tab]);
+ setActive(tab.key);
+ }, [windowed, launchCwd, launchKey]);
+
const sessionIdFor = (tab: Tab): string | null =>
identity === undefined ? null : getSessionId(identity, tab.slot != null ? `${TAB_TOKEN}-w${tab.slot}` : undefined);
@@ -274,6 +299,7 @@ export const TerminalTabs: React.FC<{ windowed?: boolean; windowId?: string; par
<Suspense fallback={loading}>
<TerminalView
sessionId={sid}
+ cwd={tab.cwd}
onPersistent={setPersistent}
onStatus={(s) => setStatuses((m) => (m[tab.key] === s ? m : { ...m, [tab.key]: s }))}
/>
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index c51d9fff5..b0d1adb94 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -43,17 +43,22 @@ const KEYS: { labelKey: string; seq?: string; ctrl?: boolean }[] = [
{ labelKey: 'apps.terminal.keys.pipe', seq: '|' },
];
-function buildWsUrl(sessionId: string): string {
+function buildWsUrl(sessionId: string, cwd?: string | null): string {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
- return `${proto}://${window.location.host}/api/terminal/${encodeURIComponent(sessionId)}`;
+ const base = `${proto}://${window.location.host}/api/terminal/${encodeURIComponent(sessionId)}`;
+ // `cwd` starts a NEW session in that directory ("Open Terminal Here"). The backend validates it
+ // and ignores it when reattaching an existing session, so it's harmless to resend on reconnect.
+ return cwd ? `${base}?cwd=${encodeURIComponent(cwd)}` : base;
}
export const TerminalView: React.FC<{
sessionId: string;
+ /** Start directory for a newly created session (from "Open Terminal Here"). Stable per tab. */
+ cwd?: string | null;
onPersistent?: (persistent: boolean) => void;
/** Report connection status up so the tab bar can show one combined status + persistence chip. */
onStatus?: (status: TerminalStatus, exitCode: number | null) => void;
-}> = ({ sessionId, onPersistent, onStatus }) => {
+}> = ({ sessionId, cwd, onPersistent, onStatus }) => {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
@@ -155,7 +160,7 @@ export const TerminalView: React.FC<{
});
setStatus('connecting');
setExitCode(null);
- const ws = new WebSocket(buildWsUrl(sessionId));
+ const ws = new WebSocket(buildWsUrl(sessionId, cwd));
ws.binaryType = 'arraybuffer';
wsRef.current = ws;
ws.onopen = () => {
@@ -231,7 +236,7 @@ export const TerminalView: React.FC<{
wsRef.current = null;
termRef.current = null;
};
- }, [sessionId, reconnectKey]);
+ }, [sessionId, cwd, reconnectKey]);
const sendKey = (k: { seq?: string; ctrl?: boolean }) => {
if (k.ctrl) {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fd71f4b44..1253fccb9 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -729,6 +729,7 @@
"uploadNoFolders": "Folders can't be uploaded — drop files only.",
"uploadError": "{{name}}: {{message}}",
"open": "Open",
+ "openTerminalHere": "Open Terminal Here",
"rename": "Rename",
"delete": "Delete",
"confirmDelete": "Delete \"{{name}}\"? This can't be undone.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b3bf793c4..3bd53af28 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -729,6 +729,7 @@
"uploadNoFolders": "无法上传文件夹,只能拖放文件。",
"uploadError": "{{name}}:{{message}}",
"open": "打开",
+ "openTerminalHere": "在此处打开终端",
"rename": "重命名",
"delete": "删除",
"confirmDelete": "删除“{{name}}”?此操作无法撤销。",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8777c7f08..41c9dbeca 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2424,10 +2424,14 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
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)
+ # Optional start directory for a brand-new session ("Open Terminal Here" from the Files
+ # app). Validated server-side in the terminal service; an invalid/absent value silently
+ # falls back to the default cwd and reattaching an existing session ignores it entirely.
+ initial_cwd = websocket.query_params.get("cwd") or None
try:
service = get_terminal_service()
service.start_reaper()
- await service.handle_websocket(websocket, effective_session_id)
+ await service.handle_websocket(websocket, effective_session_id, initial_cwd=initial_cwd)
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