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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(apps): windowed Apps — Mac windows + Dock + Monaco editor (#679)
Call White30a69bd49e8c
diff --git a/core/terminal_service.py b/core/terminal_service.pyindex b79a5f4de..93f3c332f 100644--- a/core/terminal_service.py+++ b/core/terminal_service.py@@ -88,6 +88,7 @@ class TerminalService:# 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._terminating: set[str] = set()self._lock = asyncio.Lock()self._reaper_task: asyncio.Task | None = Noneself._closed = False@@ -204,6 +205,8 @@ class TerminalService:async with self._lock:self._forget_finished_locked()current = self._sessions.get(session_id)+ if session_id in self._terminating:+ raise TerminalServiceError("session_opening")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@@ -221,7 +224,8 @@ class TerminalService:# 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)+ opening_slot = _Session(session_id, _Phase.OPENING, persistent=was_persistent)+ self._sessions[session_id] = opening_slotregistered = Falsespawned: TerminalConnection | None = Nonetry:@@ -269,7 +273,7 @@ class TerminalService:)async with self._lock:slot = self._sessions.get(session_id)- if slot is not None and slot.phase is _Phase.OPENING:+ if slot is opening_slot and slot.phase is _Phase.OPENING:slot.phase = _Phase.ATTACHEDslot.connection = spawnedslot.persistent = persistent@@ -281,33 +285,71 @@ class TerminalService:return spawnedexcept BaseException:if not registered:- await self._abandon_open(session_id, spawned)+ await self._abandon_open(session_id, opening_slot, 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 def _abandon_open(+ self,+ session_id: str,+ opening_slot: _Session,+ spawned: TerminalConnection | None,+ ) -> None:+ # Reconcile an open that never registered. The slot object is the open-attempt token:+ # a same-id slot created later is not ours, so a stale abandon must not remove it or+ # kill its tmux session by id.+ terminating_open = False+ killed_session = Falseasync 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):+ owns_slot = slot is opening_slot and slot.phase in (_Phase.OPENING, _Phase.CLOSING)+ terminating_open = owns_slot and slot.phase is _Phase.CLOSING+ slot_missing = slot is None+ try:+ kill_spawned_session = slot_missing or terminating_open+ if spawned is not None:+ await self._teardown_client(spawned, kill_session=kill_spawned_session)+ killed_session = kill_spawned_session and spawned.persistent+ # 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.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()- )+ slot = self._sessions.get(session_id)+ owns_slot = slot is opening_slot and slot.phase in (_Phase.OPENING, _Phase.CLOSING)+ current_terminating_open = owns_slot and slot.phase is _Phase.CLOSING+ terminating_open = terminating_open or current_terminating_open+ if not owns_slot:+ return+ if current_terminating_open:+ if not killed_session:+ await _kill_tmux_session(session_id)+ killed_session = True+ return++ alive = await _tmux_has_session(session_id)+ needs_terminate_kill = False+ async with self._lock:+ slot = self._sessions.get(session_id)+ if slot is opening_slot and slot.phase is _Phase.CLOSING:+ terminating_open = True+ needs_terminate_kill = not killed_session+ elif slot is opening_slot and slot.phase is _Phase.OPENING:+ if alive:+ opening_slot.phase = _Phase.DETACHED+ opening_slot.connection = None+ opening_slot.persistent = True+ opening_slot.detached_at = time.monotonic()+ else:+ self._sessions.pop(session_id, None)+ if needs_terminate_kill:+ await _kill_tmux_session(session_id)+ killed_session = True+ finally:+ if terminating_open:+ async with self._lock:+ if self._sessions.get(session_id) is opening_slot:+ self._sessions.pop(session_id, None)+ self._terminating.discard(session_id)async def close(self, connection: TerminalConnection) -> None:async with self._lock:@@ -324,6 +366,42 @@ class TerminalService:returnawait self._finalize_connection(connection)+ async def terminate(self, session_id: str) -> bool:+ """End a terminal session by id and remove it from capacity accounting.++ Used by windowed terminals whose UI lifetime is intentionally ephemeral. A+ normal websocket close detaches from tmux for reconnect durability; this path+ kills the backing session so closing a window frees the backend slot.+ """++ safe_session_id = sanitize_session_id(session_id)+ async with self._lock:+ if safe_session_id in self._terminating:+ return False+ slot = self._sessions.get(safe_session_id)+ tracked = slot is not None+ self._terminating.add(safe_session_id)+ terminating_slot = slot+ connection = slot.connection if slot is not None else None+ pending_open = slot is not None and slot.phase is _Phase.OPENING+ if slot is not None:+ slot.phase = _Phase.CLOSING++ try:+ if pending_open:+ return tracked+ if connection is not None:+ await self._teardown_client(connection, kill_session=True)+ else:+ await _kill_tmux_session(safe_session_id)+ finally:+ async with self._lock:+ if not (pending_open and self._sessions.get(safe_session_id) is terminating_slot):+ if terminating_slot is not None and self._sessions.get(safe_session_id) is terminating_slot:+ self._sessions.pop(safe_session_id, None)+ self._terminating.discard(safe_session_id)+ return tracked+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 thediff --git a/docs/plans/apps-windowing-redesign.md b/docs/plans/apps-windowing-redesign.mdnew file mode 100644index 000000000..60b1ff7e5--- /dev/null+++ b/docs/plans/apps-windowing-redesign.md@@ -0,0 +1,90 @@+# Apps Layer v2 — Windowing Redesign++## Background++The Apps layer v1 (File Browser + Terminal, PR #659) shipped as **full-page** routes+with an invented sidebar treatment. On review the owner asked for a major UX/UI rework:+apps should behave like a real OS — open in **draggable, resizable, multi-instance+windows** managed by a **Dock**. Design was done and **LOCKED** in `design.pen`+(canonical frame: `Apps · Dock on REAL Workbench`, id `NbPMq`).++Hard rule learned during design: **base everything on the REAL current layout**+(`ui/src/components/AppShell.tsx`, `workbench/WorkbenchSidebar.tsx`, `workbench/ChatPage.tsx`,+`workbench/Composer.tsx`) — not an imagined one.++## Goal++Turn Files / Terminal / Editor into windowed OS-style apps with a unified Dock, and+upgrade the editor to the Monaco (VS Code) kernel, without regressing the existing+backend (`/api/files/*`, terminal WS) shipped in #659.++## Locked design++1. **Windowing.** A reusable `<AppWindow>` (Mac chrome: traffic lights close/min/max,+ centered title, rounded + drop-shadow) that is **draggable (titlebar), resizable+ (edges/corner), maximizable, focus-to-raise (z-order), minimizable**. A+ `WindowManager` context owns the open-window list, z-order, focus, min/restore,+ and per-app multi-instance. Windows render in a portal layer above the workbench+ main area (not over the sidebar). Bounds clamp to the viewport.+2. **Dock = unified launcher + window manager.** One surface = pinned app list ++ running indicators (dot under icon) + minimized-window thumbnails (right of a+ divider, click to restore). Anchored **bottom-LEFT**, **rises ABOVE the bottom-left+ "Apps" button** (clear of the centered Chat composer). Interaction:+ **hover Apps = transient preview float; click Apps = pin/unpin toggle.** Reuse the+ existing hover-popover pattern (`InboxHoverPopover`) for the hover/close-delay.+3. **Sidebar bottom** (in `AppShell.tsx`, real layout): replace the single+ `[AppsLauncher][dot][VersionBadge]` row with **row 1 = [Apps (LEFT) | 设置 (right)]**+ two buttons, **row 2 = [VersionBadge … green run-dot]**. Apps stays left (Dock anchor);+ the old `AppsLauncher` popover is superseded by the Dock. Keep the "Open Control Panel"+ mode-switch link below. 设置 button = the control-panel / settings entry.+4. **Terminal app** (port `AppsTerminalPage`/`TerminalView` into a window body): full-width+ xterm (v1 squished-strip bug is gone once it fills the window), session tabs,+ `tmux·persistent` badge, accessory key bar. Backend unchanged.+5. **File Browser app** (port `AppsFileBrowserPage`): Finder-like list (type icon + size ++ modified + selection), favorites/projects rail, toolbar **New File + New Folder ++ breadcrumbs + search + status bar**. (New File already added backend-side? verify;+ v1 had New Folder only.)+6. **Editor = Monaco (VS Code kernel).** Replaces the CodeMirror look in `FileEditorPane`.+ - **Lazy-load**: `React.lazy(() => import(...Monaco...))` so Monaco is NOT in the main+ bundle — it loads only when an Editor window opens. Use `vite-plugin-monaco-editor`+ to trim language workers to what we support. Self-host (Avibe serves UI from the+ user's machine — local transfer, no CDN).+ - **Caching**: content-hash immutable chunks (Vite default) + a **Service Worker+ precache** (Workbox `injectManifest`, `revision:null`, cache-first) that warms+ Monaco in the background after the workbench loads → instant + offline subsequent+ opens. Optional: prefetch on hover of the Dock's Editor icon. `cleanupOutdatedCaches`+ on version bump.+ - **Mobile**: Monaco has no official touch support. Add a mobile UI layer = **reuse the+ Terminal accessory key bar** (symbol keys `(){}[];` Tab Esc) + explicit Copy-all /+ Select-all buttons + a touch-selection shim. Gate the heavy editor / show a lighter+ path on very small screens if needed.++## Implementation phases++- **P1 — Windowing foundation.** `WindowManager` context + `<AppWindow>` (drag/resize/+ maximize/focus/minimize) + window portal layer. Headless of any specific app (a demo+ body). Unit/interaction sanity.+- **P2 — Dock.** Dock component (launcher + running + minimized thumbnails), anchored+ bottom-left, hover-preview + click-pin, wired to WindowManager. Replace the sidebar+ `AppsLauncher` trigger; keep `AppsLauncher` removal behind the Dock.+- **P3 — Port apps into windows.** Files + Terminal bodies moved into `<AppWindow>`+ (route → window, or keep routes as deep-links that open a window). Multi-instance.+- **P4 — Monaco editor.** Lazy-loaded Monaco in the editor window + VS Code theme; SW+ precache; mobile accessory layer. Swap `FileEditorPane`'s CodeMirror.+- **P5 — Sidebar bottom + mobile.** `[Apps|设置]` + `[ver·dot]` rows in `AppShell`; mobile+ Dock-as-bottom-bar + full-screen single app.+- **P6 — Polish.** Minimize→Dock animation, multi-window expose, keyboard (⌘`/⌘W),+ empty/restore states, i18n (en/zh), `npm run build` green.++## Evidence layers++UI build (`npm run build`) per phase; reuse #659 backend tests (file browser / terminal)+unchanged; manual workbench sanity in local Incus regression; visual diff vs design.pen+`NbPMq` / app-window frames.++## Notes++- ~95% frontend (`ui/src/**`) → lead-owned per the standing split; backend reuses #659.+- design.pen frames: `X7d3Ev` AppWindow, `iwYIX` Terminal, `nknn2` Files, `dnYPx` Editor,+ `RFMRw` Dock states, `NbPMq` Dock-on-real-workbench (canonical). Exports in+ `/tmp/avibe-apps-design/`.diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.pyindex de88f8d46..4dabcfc24 100644--- a/tests/test_terminal_backend.py+++ b/tests/test_terminal_backend.py@@ -16,6 +16,15 @@ termios = pytest.importorskip("termios")from starlette.websockets import WebSocketDisconnect+from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)from core import terminal_servicefrom core.terminal_service import (TerminalService,@@ -25,6 +34,8 @@ from core.terminal_service import (_tmux_socket_name,sanitize_session_id,)+from tests.ui_server_test_helpers import csrf_headers+from vibe import remote_accessfrom vibe import ui_serverfrom vibe.ui_server import app@@ -62,6 +73,28 @@ class _RecordingWebSocket:self.calls.append(("close", code))+def _save_remote_config(tmp_path) -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.public_url = "https://alex.avibe.bot"+ cloud.client_id = "vr_client_123"+ cloud.instance_id = "inst_123"+ cloud.session_secret = "session-secret"+ config.save()+ return config++def test_terminal_ephemeral_pty_round_trip(monkeypatch, tmp_path):asyncio.run(_terminal_ephemeral_pty_round_trip(monkeypatch, tmp_path))@@ -511,6 +544,313 @@ async def _detached_session_tracked_when_client_exits(monkeypatch, tmp_path):assert service._sessions["detached"].phase is _Phase.DETACHED+def test_terminate_drops_only_target_session_and_frees_capacity(monkeypatch, tmp_path):+ asyncio.run(_terminate_drops_only_target_session_and_frees_capacity(monkeypatch, tmp_path))+++async def _terminate_drops_only_target_session_and_frees_capacity(monkeypatch, tmp_path):+ killed: list[str] = []++ async def fake_kill(session_id: str) -> None:+ killed.append(session_id)++ monkeypatch.setattr(terminal_service, "_kill_tmux_session", fake_kill)+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)+ monkeypatch.setattr(terminal_service.Path, "home", lambda: tmp_path / "home")+ (tmp_path / "home").mkdir()++ 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):+ 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)+ service._sessions["a"] = _Session("a", _Phase.DETACHED, persistent=True, detached_at=1.0)+ service._sessions["b"] = _Session("b", _Phase.DETACHED, persistent=True, detached_at=1.0)++ try:+ assert await service.terminate("a") is True++ assert killed == ["a"]+ assert "a" not in service._sessions+ assert service._sessions["b"].phase is _Phase.DETACHED++ # The target was removed from _sessions, so the cap has room for one new id.+ # If terminate only killed tmux but left "a" registered, this open fails with+ # too_many_sessions because "a" + "b" still fill max_sessions=2.+ conn = await service.open("c")+ assert conn.session_id == "c"+ assert set(service._sessions) == {"b", "c"}++ assert await service.terminate("missing") is False+ finally:+ await service.shutdown()+ for fd in opened_fds:+ terminal_service._close_fd(fd)+++def test_open_rejects_same_id_while_terminate_is_in_progress(monkeypatch):+ asyncio.run(_open_rejects_same_id_while_terminate_is_in_progress(monkeypatch))+++async def _open_rejects_same_id_while_terminate_is_in_progress(monkeypatch):+ 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["a"] = _Session("a", _Phase.DETACHED, persistent=True, detached_at=1.0)++ terminate_task = asyncio.create_task(service.terminate("a"))+ await asyncio.sleep(0.02)+ try:+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):+ await service.open("a")+ finally:+ gate.set()+ await terminate_task++ assert killed == ["a"]+ assert "a" not in service._sessions+++def test_terminate_keeps_opening_session_reserved_until_abandon_settles(monkeypatch, tmp_path):+ asyncio.run(_terminate_keeps_opening_session_reserved_until_abandon_settles(monkeypatch, tmp_path))+++async def _terminate_keeps_opening_session_reserved_until_abandon_settles(monkeypatch, tmp_path):+ # Windowed terminal ids come from a small reusable slot pool. If DELETE releases an id+ # while the original websocket open is still abandoning, the next window can reuse the id+ # and the stale abandon can tear down that newer terminal's tmux session.+ (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] = []+ kill_started = asyncio.Event()++ async def fake_kill(session_id: str) -> None:+ killed.append(session_id)+ kill_started.set()++ 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()+ release_stale_spawn = asyncio.Event()+ spawn_calls = 0++ 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):+ nonlocal spawn_calls+ spawn_calls += 1+ if spawn_calls == 1:+ spawn_started.set()+ await release_stale_spawn.wait()+ return _FakeProcess()++ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", gated_spawn)++ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)+ stale_open = asyncio.create_task(service.open("slot-1"))+ await spawn_started.wait()++ terminate_task = asyncio.create_task(service.terminate("slot-1"))+ kill_wait = asyncio.create_task(kill_started.wait())+ done, pending = await asyncio.wait({kill_wait, terminate_task}, timeout=1, return_when=asyncio.FIRST_COMPLETED)+ assert done+ for task in pending:+ task.cancel()+ await asyncio.gather(*pending, return_exceptions=True)++ try:+ reused_before_stale_settled: terminal_service.TerminalConnection | None = None+ try:+ reused_before_stale_settled = await service.open("slot-1")+ except terminal_service.TerminalServiceError as exc:+ assert str(exc) == "session_opening"++ release_stale_spawn.set()+ with pytest.raises(terminal_service.TerminalServiceError, match="session_opening"):+ await stale_open+ assert await terminate_task is True++ replacement = reused_before_stale_settled or await service.open("slot-1")+ assert service._sessions["slot-1"].connection is replacement+ assert service._sessions["slot-1"].phase is _Phase.ATTACHED+ if reused_before_stale_settled is not None:+ # If the implementation ever allows same-id reuse before the stale open settles,+ # the stale abandon still must not kill that newer tmux session by id.+ assert killed == ["slot-1"]+ finally:+ release_stale_spawn.set()+ await asyncio.gather(stale_open, terminate_task, return_exceptions=True)+ await service.shutdown()+ for fd in opened_fds:+ terminal_service._close_fd(fd)+++def test_terminate_during_abandon_recheck_clears_terminating(monkeypatch, tmp_path):+ asyncio.run(_terminate_during_abandon_recheck_clears_terminating(monkeypatch, tmp_path))+++async def _terminate_during_abandon_recheck_clears_terminating(monkeypatch, tmp_path):+ # DELETE can arrive while a cancelled open is already abandoning: _abandon_open has+ # sampled the slot as OPENING, released the lock, and is awaiting teardown/has-session.+ # It must re-read the slot before settling so the mid-abandon CLOSING transition clears+ # _terminating and frees the reusable window terminal id.+ (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")++ 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:+ self.returncode = -signum++ def kill(self) -> None:+ self.returncode = -signal.SIGKILL++ async def wait(self) -> int:+ return self.returncode or 0++ spawn_started = asyncio.Event()+ release_spawn = asyncio.Event()++ async def gated_spawn(*_args, **_kwargs):+ spawn_started.set()+ await release_spawn.wait()+ return _FakeProcess()++ monkeypatch.setattr(terminal_service.asyncio, "create_subprocess_exec", gated_spawn)++ async def fake_has_session(_session_id: str) -> bool:+ return True++ monkeypatch.setattr(terminal_service, "_tmux_has_session", fake_has_session)++ killed: list[str] = []++ async def fake_kill(session_id: str) -> None:+ killed.append(session_id)++ monkeypatch.setattr(terminal_service, "_kill_tmux_session", fake_kill)++ service = TerminalService(idle_timeout_seconds=60, max_sessions=1)+ teardown_started = asyncio.Event()+ release_teardown = asyncio.Event()+ teardown_calls = 0++ async def gated_teardown(+ connection: terminal_service.TerminalConnection,+ *,+ kill_session: bool,+ ) -> None:+ nonlocal teardown_calls+ teardown_calls += 1+ if teardown_calls == 1:+ teardown_started.set()+ await release_teardown.wait()+ fd, connection.master_fd = connection.master_fd, -1+ if fd >= 0:+ terminal_service._close_fd(fd)+ if kill_session and connection.persistent:+ await fake_kill(connection.session_id)+ if connection.process.returncode is None:+ connection.process.send_signal(signal.SIGHUP if connection.persistent else signal.SIGTERM)++ monkeypatch.setattr(service, "_teardown_client", gated_teardown)++ stale_open = asyncio.create_task(service.open("slot-race"))+ await spawn_started.wait()+ await service._lock.acquire()+ try:+ release_spawn.set()+ await asyncio.sleep(0)+ stale_open.cancel()+ finally:+ service._lock.release()++ await teardown_started.wait()+ terminate_task = asyncio.create_task(service.terminate("slot-race"))+ assert await terminate_task is True+ assert service._sessions["slot-race"].phase is _Phase.CLOSING+ assert "slot-race" in service._terminating++ release_teardown.set()+ with pytest.raises(asyncio.CancelledError):+ await stale_open++ assert "slot-race" not in service._terminating+ assert "slot-race" not in service._sessions+ assert killed == ["slot-race"]++ replacement = await service.open("slot-race")+ try:+ assert service._sessions["slot-race"].connection is replacement+ assert service._sessions["slot-race"].phase is _Phase.ATTACHED+ finally:+ await service.shutdown()+ for fd in opened_fds:+ terminal_service._close_fd(fd)++def test_dead_session_not_tracked_when_shell_exits(monkeypatch, tmp_path):asyncio.run(_dead_session_not_tracked_when_shell_exits(monkeypatch, tmp_path))@@ -1127,6 +1467,127 @@ def test_terminal_websocket_accepts_local_origin_from_same_port(monkeypatch, tmpassert accepted is True+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))+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ terminated: list[str] = []++ class _FakeService:+ async def terminate(self, session_id: str) -> bool:+ terminated.append(session_id)+ return True++ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: _FakeService())++ client = app.test_client()+ response = client.delete(+ "/api/terminal/local-session",+ headers=csrf_headers(client, "http://127.0.0.1:5123"),+ )++ assert response.status_code == 204+ assert terminated == ["local-session"]+++def test_terminal_delete_rejects_disallowed_origin_without_terminating(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ terminated: list[str] = []++ class _FakeService:+ async def terminate(self, session_id: str) -> bool:+ terminated.append(session_id)+ return True++ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: _FakeService())++ client = app.test_client()+ headers = csrf_headers(client, "http://127.0.0.1:5123")+ headers["Origin"] = "http://127.0.0.1:3000"+ response = client.delete("/api/terminal/local-session", base_url="http://127.0.0.1:5123", headers=headers)++ assert response.status_code == 403+ assert terminated == []+++def test_terminal_delete_rejects_forwarded_origin_proxy_without_terminating(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ _save_remote_config(tmp_path)+ terminated: list[str] = []++ class _FakeService:+ async def terminate(self, session_id: str) -> bool:+ terminated.append(session_id)+ return True++ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: _FakeService())++ client = app.test_client()+ headers = csrf_headers(client, "http://127.0.0.1:5123")+ # The generic HTTP CSRF guard accepts this loopback-origin-proxy shape because+ # _current_origin honors the forwarded host/proto. Terminal disposal still must+ # apply the stricter terminal Origin guard, which rejects forwarded metadata.+ headers.update(+ {+ "Origin": "https://vibe.example",+ "X-Forwarded-Proto": "https",+ "X-Forwarded-Host": "vibe.example",+ }+ )+ response = client.delete("/api/terminal/local-session", base_url="http://127.0.0.1:5123", headers=headers)++ assert response.status_code == 403+ assert terminated == []+++def test_terminal_delete_scopes_remote_subject_and_rejects_cross_subject(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ config = _save_remote_config(tmp_path)+ user_one_effective = ui_server._terminal_effective_session_id("shared-session", "user-1")+ terminated: list[str] = []++ class _FakeService:+ async def terminate(self, session_id: str) -> bool:+ terminated.append(session_id)+ return session_id == user_one_effective++ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: _FakeService())++ user_two_client = app.test_client()+ user_two_client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),+ domain="alex.avibe.bot",+ )+ headers = csrf_headers(user_two_client, "https://alex.avibe.bot")+ response = user_two_client.delete(+ "/api/terminal/shared-session",+ base_url="https://alex.avibe.bot",+ headers=headers,+ environ_base={"REMOTE_ADDR": "203.0.113.10"},+ )+ malicious_response = user_two_client.delete(+ f"/api/terminal/{user_one_effective}",+ base_url="https://alex.avibe.bot",+ headers=headers,+ environ_base={"REMOTE_ADDR": "203.0.113.10"},+ )++ assert response.status_code == 404+ assert malicious_response.status_code == 404+ assert terminated == [+ ui_server._terminal_effective_session_id("shared-session", "user-2"),+ ui_server._terminal_effective_session_id(user_one_effective, "user-2"),+ ]+ assert user_one_effective not in terminated++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")diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex c3ddfe893..5fc375abc 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -8,10 +8,10 @@"name": "ui","version": "0.0.0","dependencies": {- "@codemirror/language-data": "^6.5.2","@hpke/core": "^1.9.0","@hpke/dhkem-x25519": "^1.8.0","@lexical/react": "^0.45.0",+ "@monaco-editor/react": "^4.7.0","@noble/curves": "^2.2.0","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-label": "^2.1.8",@@ -20,7 +20,6 @@"@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",@@ -35,6 +34,7 @@"lexical": "^0.45.0","lexical-beautiful-mentions": "^0.1.48","lucide-react": "^0.562.0",+ "monaco-editor": "^0.55.1","papaparse": "^5.5.3","qrcode.react": "^4.2.0","react": "^19.2.0",@@ -335,419 +335,6 @@"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.1","resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",@@ -1427,189 +1014,29 @@"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==",+ "node_modules/@monaco-editor/loader": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.7.0.tgz",+ "integrity": "sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==","license": "MIT","dependencies": {- "@lezer/common": "^1.2.0",- "@lezer/highlight": "^1.0.0",- "@lezer/lr": "^1.0.0"+ "state-local": "^1.0.6"}},- "node_modules/@lezer/yaml": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz",- "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==",+ "node_modules/@monaco-editor/react": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.7.0.tgz",+ "integrity": "sha512-cyzXQCtO47ydzxpQtCGSQGOC8Gk3ZUeBXFAxD+CWXYFo5OqZyZUonFl0DwUlTyAfRHntBfw2p3w4s9R6oe1eCA==","license": "MIT","dependencies": {- "@lezer/common": "^1.2.0",- "@lezer/highlight": "^1.0.0",- "@lezer/lr": "^1.4.0"+ "@monaco-editor/loader": "^1.5.0"+ },+ "peerDependencies": {+ "monaco-editor": ">= 0.25.0 < 1",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.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",@@ -3427,59 +2854,6 @@"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",@@ -4011,21 +3385,6 @@"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",@@ -4083,12 +3442,6 @@"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",@@ -4185,6 +3538,15 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/dompurify": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.7.tgz",+ "integrity": "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },"node_modules/electron-to-chromium": {"version": "1.5.267","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz",@@ -5437,6 +4799,18 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/marked": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",+ "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/mdast-util-find-and-replace": {"version": "3.0.2","resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",@@ -6309,6 +5683,16 @@"node": "*"}},+ "node_modules/monaco-editor": {+ "version": "0.55.1",+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz",+ "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==",+ "license": "MIT",+ "dependencies": {+ "dompurify": "3.2.7",+ "marked": "14.0.0"+ }+ },"node_modules/motion-dom": {"version": "12.26.2","resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.26.2.tgz",@@ -7062,6 +6446,12 @@"dev": true,"license": "MIT"},+ "node_modules/state-local": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz",+ "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==",+ "license": "MIT"+ },"node_modules/std-env": {"version": "4.1.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",@@ -7096,12 +6486,6 @@"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",@@ -7966,12 +7350,6 @@"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.jsonindex ed2854041..701ecda4c 100644--- a/ui/package.json+++ b/ui/package.json@@ -15,10 +15,10 @@"validate:theme": "node scripts/validate-theme.mjs"},"dependencies": {- "@codemirror/language-data": "^6.5.2","@hpke/core": "^1.9.0","@hpke/dhkem-x25519": "^1.8.0","@lexical/react": "^0.45.0",+ "@monaco-editor/react": "^4.7.0","@noble/curves": "^2.2.0","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-label": "^2.1.8",@@ -27,7 +27,6 @@"@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",@@ -42,6 +41,7 @@"lexical": "^0.45.0","lexical-beautiful-mentions": "^0.1.48","lucide-react": "^0.562.0",+ "monaco-editor": "^0.55.1","papaparse": "^5.5.3","qrcode.react": "^4.2.0","react": "^19.2.0",diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 62eaec801..c3777c038 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -11,8 +11,6 @@ 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';@@ -36,8 +34,18 @@ import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';import { ComposerBridgeProvider } from './context/ComposerBridgeContext';import { AgentationToggle } from './components/AgentationToggle';-import { useEffect, useRef, useState } from 'react';+import { lazy, Suspense, useEffect, useRef, useState } from 'react';import type { ReactNode } from 'react';++// Apps layer pages are lazy: they share their chunk with the windowed app bodies+// (registry.tsx) instead of being pulled into the main entry by these routes, so+// the file browser / xterm code loads only when an app actually opens.+const AppsFileBrowserPage = lazy(() =>+ import('./components/workbench/AppsFileBrowserPage').then((m) => ({ default: m.AppsFileBrowserPage })),+);+const AppsTerminalPage = lazy(() =>+ import('./components/workbench/AppsTerminalPage').then((m) => ({ default: m.AppsTerminalPage })),+);import { hasConfiguredPlatformCredentials } from './lib/platforms';import { useTranslation } from 'react-i18next';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';@@ -265,6 +273,13 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {return children;};+// Brief fallback while a lazy Apps route chunk loads (the pages render their own+// loading state once mounted).+const AppsRouteFallback = () => {+ const { t } = useTranslation();+ return <div className="grid min-h-[40vh] place-items-center text-[12px] text-muted">{t('common.loading')}</div>;+};+function AppRoutes() {return (<>@@ -289,8 +304,22 @@ function AppRoutes() {{/* Apps layer — File Browser (Phase 1) + Terminal (Phase 2). Thesidebar 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="/apps/files"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <AppsFileBrowserPage />+ </Suspense>+ }+ />+ <Route+ path="/apps/terminal"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <AppsTerminalPage />+ </Suspense>+ }+ /><Route path="/chat/:sessionId" element={<ChatPage />} />{/* Control Panel mode — existing pages moved under /admin/* */}diff --git a/ui/src/apps/registry.tsx b/ui/src/apps/registry.tsxnew file mode 100644index 000000000..d779c764d--- /dev/null+++ b/ui/src/apps/registry.tsx@@ -0,0 +1,82 @@+import { Suspense, lazy } from 'react';+import { CodeXml, Folder, SquareTerminal } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { LucideIcon } from 'lucide-react';++// The catalogue of windowed apps. The WindowManager + Dock are headless of any+// specific app; everything app-specific (title, icon, default window size, body)+// lives here so adding an app is one registry entry. App bodies are lazy-loaded+// so opening the workbench doesn't pull file-browser / xterm code into the main+// bundle — each loads only when its window first opens.++export type AppId = 'files' | 'terminal' | 'editor';++export interface AppDefinition {+ id: AppId;+ /** i18n key for the window title / Dock label. */+ titleKey: string;+ icon: LucideIcon;+ /** Tint for the Dock tile + window title icon — a CSS var token name. */+ accent: string;+ defaultSize: { width: number; height: number };+ /** The window body. Receives the owning window id and its launch params. */+ Component: React.FC<{ windowId: string; params?: Record<string, unknown> }>;+}++const Loading: React.FC = () => {+ const { t } = useTranslation();+ return <div className="grid h-full w-full place-items-center bg-surface text-[12px] text-muted">{t('common.loading')}</div>;+};++const FilesBody = lazy(() =>+ import('../components/workbench/AppsFileBrowserPage').then((m) => ({ default: m.AppsFileBrowserPage })),+);+const TerminalBody = lazy(() =>+ import('../components/workbench/AppsTerminalPage').then((m) => ({ default: m.AppsTerminalPage })),+);+const EditorBody = lazy(() =>+ import('../components/workbench/EditorApp').then((m) => ({ default: m.EditorApp })),+);++export const APP_REGISTRY: Record<AppId, AppDefinition> = {+ files: {+ id: 'files',+ titleKey: 'apps.fileBrowser.label',+ icon: Folder,+ accent: '--cyan',+ defaultSize: { width: 920, height: 600 },+ Component: ({ windowId }) => (+ <Suspense fallback={<Loading />}>+ <FilesBody windowed windowId={windowId} />+ </Suspense>+ ),+ },+ terminal: {+ id: 'terminal',+ titleKey: 'apps.terminal.label',+ icon: SquareTerminal,+ accent: '--mint',+ defaultSize: { width: 820, height: 540 },+ Component: () => (+ <Suspense fallback={<Loading />}>+ {/* Each windowed terminal takes a bounded, reused session slot internally so+ it gets its own backend session without leaking ids (see AppsTerminalPage). */}+ <TerminalBody windowed />+ </Suspense>+ ),+ },+ editor: {+ id: 'editor',+ titleKey: 'apps.editor.label',+ icon: CodeXml,+ accent: '--violet',+ defaultSize: { width: 1000, height: 640 },+ Component: ({ windowId, params }) => (+ <Suspense fallback={<Loading />}>+ <EditorBody windowId={windowId} params={params} />+ </Suspense>+ ),+ },+};++export const APP_LIST: AppDefinition[] = [APP_REGISTRY.files, APP_REGISTRY.terminal, APP_REGISTRY.editor];diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex fae8caa2b..0ede25952 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,6 +1,6 @@import React, { useEffect, useState } from 'react';import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';-import { ArrowLeft, ArrowRight, Bot, ChevronDown, FolderTree, Globe, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, MonitorPlay, PlugZap, Plus, Settings, SlidersHorizontal, Sparkles, X } from 'lucide-react';+import { ArrowLeft, Bot, ChevronDown, FolderTree, Globe, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, MonitorPlay, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';@@ -13,6 +13,8 @@ import { ThemeToggle } from './ThemeToggle';import { VersionBadge } from './VersionBadge';import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';import { AppsLauncher } from './AppsLauncher';+import { WindowManagerProvider } from '../context/WindowManagerContext';+import { WindowLayer } from './apps/WindowLayer';import { NewSessionSheet } from './workbench/NewSessionSheet';import { SearchPalette } from './workbench/search/SearchPalette';import { Button } from './ui/button';@@ -370,6 +372,7 @@ export const AppShell: React.FC = () => {// fought iOS's own scroll-into-view and threw the input off-screen. iOS instead// pans the locked page to lift the focused composer above the keyboard.// Desktop: normal document flow.+ <WindowManagerProvider><div className="flex h-[var(--app-shell-h)] flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:min-h-screen md:overflow-visible"><aside className="fixed inset-y-0 left-0 z-30 hidden w-[240px] flex-col border-r border-border bg-surface md:flex"><div className="flex h-full flex-col justify-between gap-6 px-4 py-5">@@ -403,23 +406,33 @@ export const AppShell: React.FC = () => {{shellMode === 'workbench' && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}</div>- {/* Bottom: Status (with embedded version badge) + toggles + hostname */}+ {/* Bottom (design.pen NbPMq): row 1 = [Apps | Settings] two equal+ buttons; row 2 = [version … run-dot]. Admin keeps its quick-toggles+ + hostname between the rows. */}<div className="flex flex-col gap-3">- {/* 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">+ {/* Row 1 — Apps (Dock trigger, left) paired with the mode switch+ (right). The Dock rises ABOVE the Apps button, clear of the+ centered Chat composer. Workbench → Settings (control panel);+ Control Panel → Back to Workbench, the mint counterpart. */}+ <div className="flex items-stretch 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.5 shrink-0 rounded-full',- isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'- )}- />- <VersionBadge openUpward />+ {shellMode === 'workbench' ? (+ <Link+ to="/admin/dashboard"+ className="group flex flex-1 items-center justify-center gap-2 rounded-lg border border-border-strong px-3 py-2.5 text-[13px] font-medium text-foreground transition-colors hover:bg-foreground/[0.04]"+ >+ <Settings className="size-4 text-muted group-hover:text-foreground" />+ <span>{t('appShell.openControlPanel')}</span>+ </Link>+ ) : (+ <Link+ to="/"+ className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-mint/30 bg-mint/[0.06] px-3 py-2.5 text-[13px] font-semibold text-mint transition hover:bg-mint/[0.12]"+ >+ <ArrowLeft className="size-3.5" />+ <span>{t('appShell.backToWorkbench')}</span>+ </Link>+ )}</div>{/* Language / theme / account quick-toggles only show in the@@ -440,27 +453,19 @@ export const AppShell: React.FC = () => {</div>)}- {/* Mode switch — flips between Workbench (`/`) and Control Panel- (`/admin/*`). Distinct visual hierarchy from the toggle row- above so users notice it as a destination, not a quick toggle. */}- {shellMode === 'workbench' ? (- <Link- to="/admin/dashboard"- className="flex items-center justify-center gap-2 rounded-lg border border-border-strong px-3 py-2.5 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"- >- <SlidersHorizontal className="size-3.5" />- <span>{t('appShell.openControlPanel')}</span>- <ArrowRight className="size-3 text-muted" />- </Link>- ) : (- <Link- to="/"- className="flex items-center justify-center gap-2 rounded-lg border border-mint/30 bg-mint/[0.06] px-3 py-2.5 text-[12px] font-semibold text-mint transition hover:bg-mint/[0.12]"- >- <ArrowLeft className="size-3.5" />- <span>{t('appShell.backToWorkbench')}</span>- </Link>- )}+ {/* Row 2 — version + a compact run-state dot at the very bottom. The+ green/grey dot conveys running vs stopped (hover shows the text). */}+ <div className="flex items-center gap-2">+ <VersionBadge openUpward />+ <span+ title={isRunning ? t('common.running') : t('common.stopped')}+ aria-label={isRunning ? t('common.running') : t('common.stopped')}+ className={clsx(+ 'ml-auto size-2.5 shrink-0 rounded-full',+ isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'+ )}+ />+ </div></div></div></aside>@@ -554,6 +559,11 @@ export const AppShell: React.FC = () => {both Workbench and Control Panel; the sidebar field is the workbenchentry point. */}<SearchPalette open={searchOpen} onClose={() => setSearchOpen(false)} />++ {/* App windows float over the workbench main area (desktop). The Dock (P2)+ and the AppsLauncher bridge open windows via the WindowManager. */}+ <WindowLayer /></div>+ </WindowManagerProvider>);};diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsxindex 440807554..75f6713de 100644--- a/ui/src/components/AppsLauncher.tsx+++ b/ui/src/components/AppsLauncher.tsx@@ -1,41 +1,39 @@import { useEffect, useRef, useState } from 'react';-import { useLocation, useNavigate } from 'react-router-dom';-import { ChevronUp, FolderTree, LayoutGrid, TerminalSquare } from 'lucide-react';+import { ChevronUp, LayoutGrid, Pin } 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 },-];+import { Dock } from './apps/Dock';+// The sidebar bottom-left "Apps" button that reveals the Dock.+// - hover → the Dock floats up ABOVE the button (transient preview; the cursor+// can move straight onto it). Mirrors InboxHoverPopover's timer dance.+// - click → pin / unpin toggle (sticky). Unpinning hides it immediately even if+// the cursor is still on the button (suppressed until it leaves).export const AppsLauncher: React.FC = () => {const { t } = useTranslation();- const navigate = useNavigate();- const location = useLocation();- const [open, setOpen] = useState(false);+ const [pinned, setPinned] = useState(false);+ const [hovering, setHovering] = useState(false);const closeTimer = useRef<number | null>(null);- const active = location.pathname.startsWith('/apps');+ // Set on unpin so the lingering hover doesn't immediately re-open the panel;+ // cleared once the cursor actually leaves the trigger+panel.+ const suppressHover = useRef(false);++ const visible = pinned || hovering;- const openMenu = () => {+ const openHover = () => {+ if (suppressHover.current) return;if (closeTimer.current !== null) {window.clearTimeout(closeTimer.current);closeTimer.current = null;}- setOpen(true);+ setHovering(true);};const queueClose = () => {if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);closeTimer.current = window.setTimeout(() => {- setOpen(false);+ setHovering(false);+ suppressHover.current = false;closeTimer.current = null;}, 180);};@@ -45,77 +43,50 @@ export const AppsLauncher: React.FC = () => {},[],);- // 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);+ const onClick = () => {+ if (pinned) {+ setPinned(false);+ setHovering(false);+ suppressHover.current = true;+ } else {+ setPinned(true);+ }};return (- <div className="relative flex-1" onMouseEnter={openMenu} onMouseLeave={queueClose}>+ <div className="relative flex-1" onMouseEnter={openHover} onMouseLeave={queueClose}><buttontype="button"- onClick={() => (open ? setOpen(false) : openMenu())}+ onClick={onClick}aria-haspopup="menu"- aria-expanded={open}+ aria-expanded={visible}+ aria-pressed={pinned}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)]'+ visible+ ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-[0_0_16px_-4px_rgba(63,224,229,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')} />+ <LayoutGrid className={clsx('size-4', visible ? 'text-cyan' : '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')} />+ {pinned ? (+ <Pin className="size-3.5 shrink-0 rotate-45 fill-cyan text-cyan" />+ ) : (+ <ChevronUp className={clsx('size-3.5 shrink-0 text-muted transition-transform', !visible && 'rotate-180')} />+ )}</button>- {open && (+ {visible && (<divrole="menu"aria-label={t('apps.title')}- onMouseEnter={openMenu}+ onMouseEnter={openHover}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)]"+ className="absolute bottom-full left-0 z-50 mb-2">- <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>- );- })}+ <Dock /></div>)}</div>diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsxnew file mode 100644index 000000000..4f6cac8ce--- /dev/null+++ b/ui/src/components/apps/AppWindow.tsx@@ -0,0 +1,210 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';++import { APP_REGISTRY } from '../../apps/registry';+import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';+import { clampToLayer, resizeBounds, type ResizeDir } from '../../lib/windowBounds';++const RESIZE_HANDLES: { dir: ResizeDir; className: string }[] = [+ { dir: 'n', className: 'left-2 right-2 top-0 h-1.5 cursor-ns-resize' },+ { dir: 's', className: 'left-2 right-2 bottom-0 h-1.5 cursor-ns-resize' },+ { dir: 'e', className: 'top-2 bottom-2 right-0 w-1.5 cursor-ew-resize' },+ { dir: 'w', className: 'top-2 bottom-2 left-0 w-1.5 cursor-ew-resize' },+ { dir: 'ne', className: 'top-0 right-0 size-3 cursor-nesw-resize' },+ { dir: 'nw', className: 'top-0 left-0 size-3 cursor-nwse-resize' },+ { dir: 'se', className: 'bottom-0 right-0 size-3 cursor-nwse-resize' },+ { dir: 'sw', className: 'bottom-0 left-0 size-3 cursor-nesw-resize' },+];++export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; layerHeight: number }> = ({+ win,+ layerWidth,+ layerHeight,+}) => {+ const { t } = useTranslation();+ const wm = useWindowManager();+ const def = APP_REGISTRY[win.appId];+ const rootRef = useRef<HTMLDivElement | null>(null);+ const draggingRef = useRef(false);+ // Closing plays a scale-down exit whose animationEnd drives the real unmount (the+ // CSS owns the timing). Minimizing is a pure mounted hide (see className) so the+ // window body — terminal session, editor buffer — stays alive and intact.+ const [exitKind, setExitKind] = useState<'close' | null>(null);++ // Keep a visible window reachable when the geometry around it changes without a+ // drag: the layer shrinking, or the window being restored / un-maximized after the+ // layer shrank (the gesture clamps can't fire in those cases). Deliberately not+ // keyed on win.bounds — a drag clamps itself, and re-running here would fight it.+ useEffect(() => {+ // Skip while hidden, and when the layer reports 0×0 — it's `hidden md:block`, so+ // below the md breakpoint the ResizeObserver sees no size; clamping to a zero layer+ // would shove a normal window to a negative origin and persist that off-screen.+ if (win.minimized || win.maximized || layerWidth === 0 || layerHeight === 0) return;+ const c = clampToLayer(win.bounds, layerWidth, layerHeight);+ if (c.x !== win.bounds.x || c.y !== win.bounds.y) wm.setBounds(win.id, c);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [win.minimized, win.maximized, layerWidth, layerHeight]);++ // Pull DOM focus to this window when it BECOMES the focused (top) window without a+ // pointer click already placing focus inside it — i.e. opened via openApp, or+ // activated / restored from the Dock (which only raise z-order). The keyboard chord+ // routes by document.activeElement, so otherwise a Dock-activated or freshly-opened+ // window wouldn't receive ⌘W/⌘M. The `contains` guard avoids yanking focus from an+ // inner field the user just clicked (pointerdown already focuses those).+ useEffect(() => {+ if (win.minimized || wm.focusedId !== win.id) return;+ if (rootRef.current?.contains(document.activeElement)) return;+ rootRef.current?.focus({ preventScroll: true });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [wm.focusedId, win.minimized]);++ // One pointer gesture (move or resize): attach window-level listeners on down,+ // tear them down on up. Capturing `win.bounds` at gesture start keeps the math+ // stable even as state updates re-render mid-drag.+ const startGesture = (e: React.PointerEvent, kind: 'move' | ResizeDir) => {+ if (win.maximized) return;+ e.preventDefault();+ e.stopPropagation();+ wm.focus(win.id);+ // Give the window real DOM focus so keyboard chords (⌘W/⌘M) target it — the+ // titlebar/handle stops propagation, so the root's own focus handler won't run.+ rootRef.current?.focus({ preventScroll: true });+ draggingRef.current = true;+ const startX = e.clientX;+ const startY = e.clientY;+ const start = { ...win.bounds };+ const onMove = (ev: PointerEvent) => {+ const dx = ev.clientX - startX;+ const dy = ev.clientY - startY;+ if (kind === 'move') {+ wm.setBounds(win.id, clampToLayer({ ...start, x: start.x + dx, y: start.y + dy }, layerWidth, layerHeight));+ } else {+ // Clamp resize results too: dragging the N/W edge inward past the min size+ // moves the origin, which could otherwise push the titlebar off-screen.+ wm.setBounds(win.id, clampToLayer(resizeBounds(start, kind, dx, dy), layerWidth, layerHeight));+ }+ };+ const onUp = () => {+ draggingRef.current = false;+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };+ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ };++ const Body = def.Component;+ const Icon = def.icon;+ const focused = wm.focusedId === win.id;++ const style: React.CSSProperties = win.maximized+ ? { left: 0, top: 0, width: layerWidth, height: layerHeight, zIndex: win.z }+ : { left: win.bounds.x, top: win.bounds.y, width: win.bounds.width, height: win.bounds.height, zIndex: win.z };++ const lights: { key: string; color: string; glyph: string; onClick: () => void; label: string }[] = [+ {+ key: 'close',+ color: '#ff5f57',+ glyph: '×',+ // A dirty editor body can veto the close (confirm) before the exit animation.+ onClick: () => {+ if (wm.confirmClose(win.id)) setExitKind((k) => k ?? 'close');+ },+ label: t('common.close'),+ },+ // Minimize is a mounted hide (no exit animation): the body keeps running and+ // `inert` on the root pulls focus out, so nothing is trapped in a hidden window.+ { key: 'min', color: '#febc2e', glyph: '–', onClick: () => wm.minimize(win.id), label: t('apps.window.minimize') },+ { key: 'max', color: '#28c840', glyph: '+', onClick: () => wm.toggleMaximize(win.id), label: t('apps.window.maximize') },+ ];++ return (+ <div+ ref={rootRef}+ role="dialog"+ aria-label={t(def.titleKey)}+ // Keyboard chords resolve their target window from the DOM-focused element via+ // this id, so they act on the window you're actually typing in (not just the top).+ data-window-id={win.id}+ // Minimized windows stay mounted (to preserve their body state) but go fully+ // inert: hidden from assistive tech, out of the tab order, non-interactive —+ // and React/the browser moves focus out automatically.+ inert={win.minimized}+ tabIndex={-1}+ onPointerDown={(e) => {+ wm.focus(win.id);+ // Give the window DOM focus (so ⌘W/⌘M target it) — but don't steal focus from+ // an inner control/editor/terminal the click lands in (xterm's screen isn't a+ // textarea, so it needs an explicit exemption or terminal input would break).+ const tgt = e.target as HTMLElement;+ if (!tgt.closest('input,textarea,select,button,a,[contenteditable="true"],.monaco-editor,.xterm')) {+ rootRef.current?.focus({ preventScroll: true });+ }+ }}+ onAnimationEnd={(e) => {+ // Only the root's own close animation drives the unmount (ignore the+ // entrance, and any child animation bubbling up). Minimize doesn't animate+ // here — it's a CSS transition on the className, not a keyframe.+ if (e.target !== e.currentTarget || exitKind !== 'close') return;+ wm.close(win.id);+ }}+ className={clsx(+ 'group/win absolute flex flex-col overflow-hidden border bg-surface-2 outline-none',+ 'origin-center transition-[transform,opacity] duration-200 ease-out',+ win.maximized ? 'rounded-none' : 'rounded-xl',+ exitKind === 'close' ? 'animate-appwindow-out' : 'animate-appwindow-in',+ // Minimize = mounted hide: the body stays alive (terminal/editor state+ // preserved) while the window scales away and stops taking pointer events.+ win.minimized ? 'pointer-events-none scale-90 opacity-0' : 'pointer-events-auto',+ focused+ ? 'border-border-strong shadow-[0_28px_60px_-12px_rgba(0,0,0,0.7)]'+ : 'border-border shadow-[0_16px_40px_-16px_rgba(0,0,0,0.6)]',+ )}+ style={style}+ >+ {/* Titlebar: traffic lights (left) + centered title. Drag handle = the bar. */}+ <div+ onPointerDown={(e) => startGesture(e, 'move')}+ onDoubleClick={() => wm.toggleMaximize(win.id)}+ className="flex h-9 shrink-0 select-none items-center gap-3 border-b border-border px-3.5"+ >+ <div className="flex items-center gap-2">+ {lights.map((l) => (+ <button+ key={l.key}+ type="button"+ aria-label={l.label}+ title={l.label}+ onPointerDown={(e) => e.stopPropagation()}+ onClick={l.onClick}+ className="grid size-3 place-items-center rounded-full text-[9px] font-bold leading-none text-black/55 opacity-100"+ style={{ backgroundColor: l.color }}+ >+ <span className="opacity-0 transition-opacity group-hover/win:opacity-100">{l.glyph}</span>+ </button>+ ))}+ </div>+ <div className="flex flex-1 items-center justify-center gap-1.5 overflow-hidden">+ <Icon className="size-3.5 shrink-0" style={{ color: `var(${def.accent})` }} />+ <span className="truncate text-[13px] font-semibold text-foreground">{win.title ?? t(def.titleKey)}</span>+ </div>+ {/* Right spacer balances the traffic lights so the title stays centered. */}+ <div className="w-[52px] shrink-0" />+ </div>++ <div className="min-h-0 flex-1 overflow-hidden">+ <Body windowId={win.id} params={win.params} />+ </div>++ {!win.maximized &&+ RESIZE_HANDLES.map((h) => (+ <div+ key={h.dir}+ onPointerDown={(e) => startGesture(e, h.dir)}+ className={clsx('absolute z-10', h.className)}+ />+ ))}+ </div>+ );+};diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsxnew file mode 100644index 000000000..cc058ec40--- /dev/null+++ b/ui/src/components/apps/Dock.tsx@@ -0,0 +1,98 @@+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';++import { APP_LIST, APP_REGISTRY, type AppId } from '../../apps/registry';+import { useWindowManager } from '../../context/WindowManagerContext';++// The unified Dock panel: app launcher + running indicators + minimized-window+// thumbnails. Headless of how it's revealed — the AppsLauncher trigger floats it+// above the bottom-left Apps button (hover = preview, click = pin).+export const Dock: React.FC = () => {+ const { t } = useTranslation();+ const wm = useWindowManager();+ const { windows, focusedId } = wm;+ const focusedApp = windows.find((w) => w.id === focusedId)?.appId;+ const minimized = windows.filter((w) => w.minimized);++ // Click an app: focus its front window, else un-minimize its top window, else+ // launch a fresh one.+ const activate = (appId: AppId) => {+ const own = windows.filter((w) => w.appId === appId);+ const visible = own.filter((w) => !w.minimized);+ if (visible.length > 0) {+ const top = visible.reduce((a, b) => (b.z > a.z ? b : a));+ wm.focus(top.id);+ // Pull DOM focus straight to it: if it was already the top window, wm.focus is a+ // no-op so the focusedId-keyed focus effect won't re-fire, and the chord (routed by+ // document.activeElement) would otherwise stay on this Dock button. The element is+ // already rendered + visible here, so focusing it directly is safe.+ (document.querySelector(`[data-window-id="${top.id}"]`) as HTMLElement | null)?.focus?.({ preventScroll: true });+ } else if (own.length > 0) {+ // Restored from minimized: the element is inert until the next render, so DOM focus is+ // handled by AppWindow's focus-on-becoming-top effect rather than a direct call here.+ wm.restore(own.reduce((a, b) => (b.z > a.z ? b : a)).id);+ } else {+ wm.openApp(appId);+ }+ };++ return (+ <div className="flex items-center gap-2 rounded-2xl border border-border-strong bg-surface-2/95 p-2 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.65)] backdrop-blur-xl">+ {APP_LIST.map((app) => {+ const Icon = app.icon;+ const running = windows.some((w) => w.appId === app.id);+ const active = focusedApp === app.id;+ return (+ <button+ key={app.id}+ type="button"+ title={running ? `${t(app.titleKey)} · ${t('apps.dock.newInstanceHint')}` : t(app.titleKey)}+ aria-label={t(app.titleKey)}+ // Plain click focuses/restores the existing window; a modifier-click+ // (⌘/Ctrl/Alt) always opens another instance — windows are multi-instance,+ // but otherwise there'd be no UI path to a second Files/Terminal window.+ onClick={(e) => (e.metaKey || e.ctrlKey || e.altKey ? wm.openApp(app.id) : activate(app.id))}+ className="flex flex-col items-center gap-1.5"+ >+ <span+ className={clsx(+ 'grid size-12 place-items-center rounded-xl border transition',+ active ? 'border-2 bg-foreground/[0.07]' : 'border-border bg-foreground/[0.03] hover:bg-foreground/[0.07]',+ )}+ style={active ? { borderColor: `var(${app.accent})` } : undefined}+ >+ <Icon className="size-6" style={{ color: `var(${app.accent})` }} />+ </span>+ <span className="size-1.5 rounded-full" style={{ backgroundColor: running ? `var(${app.accent})` : 'transparent' }} />+ </button>+ );+ })}++ {minimized.length > 0 && <div className="mx-1 h-11 w-px shrink-0 bg-border-strong" />}++ {minimized.map((w) => {+ const def = APP_REGISTRY[w.appId];+ const Icon = def.icon;+ return (+ <button+ key={w.id}+ type="button"+ title={w.title ?? t(def.titleKey)}+ aria-label={t('apps.window.restore', { defaultValue: 'Restore' })}+ onClick={() => wm.restore(w.id)}+ className="flex h-[52px] w-[76px] shrink-0 flex-col overflow-hidden rounded-lg border border-border-strong bg-surface transition hover:border-foreground/30"+ >+ <span className="flex items-center gap-1 bg-surface-2 px-1.5 py-1">+ {['#ff5f57', '#febc2e', '#28c840'].map((c) => (+ <span key={c} className="size-1 rounded-full" style={{ backgroundColor: c }} />+ ))}+ </span>+ <span className="flex flex-1 items-center justify-center">+ <Icon className="size-4" style={{ color: `var(${def.accent})` }} />+ </span>+ </button>+ );+ })}+ </div>+ );+};diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsxnew file mode 100644index 000000000..48e2a36f8--- /dev/null+++ b/ui/src/components/apps/WindowLayer.tsx@@ -0,0 +1,81 @@+import { useEffect, useRef, useState } from 'react';++import { useWindowManager } from '../../context/WindowManagerContext';+import { AppWindow } from './AppWindow';++// In the TERMINAL, Ctrl is a control-character stream — ^W deletes a word, ^M is+// carriage return — so the window chord must never hijack Ctrl there (xterm focuses a+// hidden textarea inside its `.xterm` root). The editor is the opposite: Monaco has no+// useful Ctrl+W, so we WANT Ctrl+W to close its window (guarded for unsaved edits)+// rather than be swallowed and bypass the prompt — hence the exemption is terminal-only.+function inTerminalSurface(el: Element | null): boolean {+ return el instanceof HTMLElement && !!el.closest('.xterm');+}++// The portal layer that hosts app windows. Covers the workbench main area (right+// of the 240px sidebar on desktop). The layer itself is pointer-events-none so+// empty space passes clicks through to the workbench underneath; each AppWindow+// re-enables pointer events on itself (minimized windows stay mounted but inert,+// so their terminal/editor state survives a minimize). Desktop-only — mobile opens+// apps full screen (P5), so no free-floating windows there.+export const WindowLayer: React.FC = () => {+ const { windows, close, minimize, confirmClose } = useWindowManager();+ const ref = useRef<HTMLDivElement | null>(null);+ const [size, setSize] = useState({ w: 0, h: 0 });++ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const measure = () => setSize({ w: el.clientWidth, h: el.clientHeight });+ measure();+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ // ⌘W / Ctrl+W closes — ⌘M / Ctrl+M minimizes — the window the keyboard is actually+ // in, resolved from the DOM-focused element's `data-window-id`. NOT the top z-order+ // window: focus can tab or programmatically move into a lower window, and acting on+ // the top one would then close/minimize the wrong window (a dirty editor or terminal+ // the user isn't in). When focus isn't inside any window — the chat composer, another+ // page — the chord falls through to the browser. Inside the terminal only Meta counts,+ // so its Ctrl control-chars (^W/^M) reach the shell (see inTerminalSurface).+ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ if (!(e.metaKey || e.ctrlKey) || e.altKey) return;+ const active = document.activeElement;+ const winEl = active instanceof Element ? active.closest('[data-window-id]') : null;+ if (!winEl || !ref.current?.contains(winEl)) return;+ if (e.ctrlKey && !e.metaKey && inTerminalSurface(active)) return;+ const targetId = winEl.getAttribute('data-window-id');+ if (!targetId) return;+ const key = e.key.toLowerCase();+ if (key === 'w') {+ e.preventDefault();+ if (confirmClose(targetId)) close(targetId);+ } else if (key === 'm') {+ e.preventDefault();+ minimize(targetId);+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [close, minimize, confirmClose]);++ // Render every window — minimized ones stay mounted (hidden + inert via AppWindow)+ // so their app body keeps its state. The layer is only aria-hidden when nothing is+ // actually shown.+ const anyShown = windows.some((w) => !w.minimized);++ return (+ <div+ ref={ref}+ aria-hidden={!anyShown}+ className="pointer-events-none fixed inset-y-0 left-0 right-0 z-20 hidden md:left-[240px] md:block"+ >+ {windows.map((w) => (+ <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} />+ ))}+ </div>+ );+};diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsxindex 2e913395c..c1f51604e 100644--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx@@ -4,6 +4,7 @@ import { ChevronRight, Download, File as FileIcon, Folder, FolderPlus, Loader2,import clsx from 'clsx';import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';+import { useWindowManager } from '../../context/WindowManagerContext';import { previewKind } from '../../lib/filePreview';import {contentUrl,@@ -21,8 +22,8 @@ import {} 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.+// Lazy-load the editor so Monaco stays 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 };@@ -34,7 +35,10 @@ 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 = () => {+export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: string }> = ({+ windowed = false,+ windowId,+}) => {const { t } = useTranslation();const { projects } = useWorkbenchProjectsTree();const [cwd, setCwd] = useState('');@@ -139,13 +143,27 @@ export const AppsFileBrowserPage: React.FC = () => {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={+ windowed+ ? 'flex h-full w-full flex-col'+ : 'flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'+ }+ >+ {!windowed && (+ <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">+ <div+ className={+ windowed+ ? 'flex min-h-0 flex-1 overflow-hidden bg-surface'+ : '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">@@ -283,14 +301,17 @@ export const AppsFileBrowserPage: React.FC = () => {{/* Right: content pane (desktop) */}<div className="hidden min-w-0 flex-1 md:flex">- <ContentPane selected={selected} />+ <ContentPane selected={selected} windowed={windowed} windowId={windowId} /></div></div>- {/* Mobile: content opens below the list when a file is selected */}+ {/* Mobile: content opens below the list when a file is selected. This pane is+ md:hidden but still mounted on desktop — and windows only ever render on+ desktop — so it must NOT take `windowId`, or its (clean) editor's close guard+ would clobber the visible desktop editor's (dirty) guard for the same window. */}{selected && (<div className="flex min-h-[50vh] flex-col overflow-hidden rounded-xl border border-border bg-surface md:hidden">- <ContentPane selected={selected} />+ <ContentPane selected={selected} windowed={windowed} /></div>)}</div>@@ -316,8 +337,13 @@ const FavRow: React.FC<{ icon: React.ReactNode; label: string; active: boolean;</button>);-const ContentPane: React.FC<{ selected: Selected | null }> = ({ selected }) => {+const ContentPane: React.FC<{ selected: Selected | null; windowed: boolean; windowId?: string }> = ({+ selected,+ windowed,+ windowId,+}) => {const { t } = useTranslation();+ const wm = useWindowManager();if (!selected) {return (<div className="grid flex-1 place-items-center p-6 text-center text-[12.5px] text-muted">@@ -346,7 +372,25 @@ const ContentPane: React.FC<{ selected: Selected | null }> = ({ selected }) => {>{/* key by path: remount per file so an in-flight save/load can never apply itsresult 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} />+ <FileEditorPane+ key={selected.path}+ path={selected.path}+ filename={selected.name}+ mtime={selected.mtime}+ windowId={windowId}+ // Inside a window, offer to pop the file out into its own Editor window.+ // Carry the editor's live mtime (it may have saved since this row opened),+ // not the row's stale metadata, so the new window won't false-conflict.+ onPopOut={+ windowed+ ? (live) =>+ wm.openApp('editor', {+ title: selected.name,+ params: { path: selected.path, filename: selected.name, mtime: live.mtime },+ })+ : undefined+ }+ /></Suspense>);}diff --git a/ui/src/components/workbench/AppsTerminalPage.tsx b/ui/src/components/workbench/AppsTerminalPage.tsxindex 2634b3b09..b96452d90 100644--- a/ui/src/components/workbench/AppsTerminalPage.tsx+++ b/ui/src/components/workbench/AppsTerminalPage.tsx@@ -1,7 +1,9 @@-import { Suspense, lazy, useEffect, useState } from 'react';+import { Suspense, lazy, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useApi } from '../../context/ApiContext';+import { apiFetch } from '../../lib/apiFetch';+import { acquireTerminalSlot, releaseTerminalSlot } from '../../lib/terminalSlots';// 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 })));@@ -11,12 +13,20 @@ const TerminalView = lazy(() => import('./TerminalView').then((m) => ({ default:// 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 per-tab token mixed into WINDOWED terminal session ids. The slot pool is module-local+// (so it's per browser tab), but the localStorage base id is shared across tabs in the same+// profile — so two tabs would both resolve their first windowed terminal to `<base>-w0` and+// fight over (reconnect/replace/DELETE) one backend session. This discriminator keeps each+// tab's windowed terminals distinct. The route terminal is intentionally shared/persistent+// across tabs (its own shell), so it does NOT use this.+const TAB_TOKEN = Math.random().toString(36).slice(2, 8);+// 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 {+function getSessionId(identity: string | null, windowKey?: string): string {const KEY = identity ? `avibe.terminal.sessionId.${encodeURIComponent(identity)}` : 'avibe.terminal.sessionId';try {let id = window.localStorage.getItem(KEY);@@ -24,22 +34,72 @@ function getSessionId(identity: string | null): string {id = `wb-${Math.random().toString(36).slice(2, 10)}`;window.localStorage.setItem(KEY, id);}- return id;+ // A windowed terminal appends its (per-instance, life-stable) window id, so two+ // terminal windows — or a window and the /apps/terminal route — don't share one+ // backend session. The service evicts a session's previous client on attach, so a+ // shared id would make them disconnect each other.+ return windowKey ? `${id}-${windowKey}` : id;} catch {- return FALLBACK_SESSION_ID;+ return windowKey ? `${FALLBACK_SESSION_ID}-${windowKey}` : FALLBACK_SESSION_ID;}}-export const AppsTerminalPage: React.FC = () => {+// `windowed` renders just the terminal filling its parent (an AppWindow body) — no+// page header / viewport-height wrapper, since the window chrome supplies the title.+// A windowed terminal also takes a bounded, reused session slot so each window gets+// its own backend session without minting unbounded session ids.+export const AppsTerminalPage: React.FC<{ windowed?: boolean }> = ({ windowed = false }) => {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);+ const resolvedSessionIdRef = useRef<string | null>(null);+ const slotRef = useRef<number | null>(null);++ // Slot + backend-session lifecycle is tied to MOUNT, not to identity: acquire a bounded+ // slot for a windowed terminal on mount (so open/close churn reuses session ids instead+ // of exhausting the backend cap), and dispose the backend session + release the slot only+ // on unmount = window close. Keeping this OUT of the identity effect below is the point:+ // an ApiContext re-render hands `getAuthSession` a fresh identity, and if disposal lived+ // in that effect's cleanup it would DELETE a live terminal on every such refresh.+ useEffect(() => {+ if (!windowed) return;+ const slot = acquireTerminalSlot();+ slotRef.current = slot;+ return () => {+ slotRef.current = null;+ const sid = resolvedSessionIdRef.current;+ if (sid) {+ // Only return the slot to the pool once the backend session is actually GONE.+ // apiFetch resolves on non-2xx and network errors are swallowed, but a failed+ // DELETE (auth/origin/CSRF/server error) means the session may still be alive+ // (only detached via the WS close) — reusing the slot would then mint the same id+ // and reconnect a new window to the old shell, leaking its commands/state. 404 =+ // already gone, so that's safe to release too. On any other failure keep the slot+ // reserved (lost for this page, but the pool just hands out the next free index).+ void apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, { method: 'DELETE', credentials: 'same-origin' })+ .then((res) => {+ if (res.ok || res.status === 404) releaseTerminalSlot(slot);+ })+ .catch(() => undefined);+ } else {+ releaseTerminalSlot(slot);+ }+ };+ }, [windowed]);++ // Resolve the (account-scoped) session id from the signed-in identity. May re-run when the+ // identity source changes; it only updates the id — it never disposes a session (that's the+ // mount-scoped effect above) — so a context refresh can't kill a live terminal.useEffect(() => {let cancelled = false;const resolve = (identity: string | null) => {- if (!cancelled) setSessionId(getSessionId(identity));+ if (cancelled) return;+ const slot = slotRef.current;+ const nextSessionId = getSessionId(identity, windowed && slot != null ? `${TAB_TOKEN}-w${slot}` : undefined);+ resolvedSessionIdRef.current = nextSessionId;+ setSessionId(nextSessionId);};getAuthSession()// Prefer the stable OIDC subject; email can be absent or shared across subjects, which@@ -49,24 +109,48 @@ export const AppsTerminalPage: React.FC = () => {return () => {cancelled = true;};- }, [getAuthSession]);+ }, [getAuthSession, windowed]);++ // The React-cleanup DELETE above frees the session on an in-app window close, but it+ // doesn't run on a tab close / refresh. Dispose on `pagehide` too, with `keepalive` so+ // the request survives the unload — otherwise the windowed (per-tab id) session can't be+ // reattached or deleted on the next load and lingers until the backend idle reaper.+ useEffect(() => {+ if (!windowed) return;+ const dispose = () => {+ const sid = resolvedSessionIdRef.current;+ if (!sid) return;+ void apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, {+ method: 'DELETE',+ credentials: 'same-origin',+ keepalive: true,+ }).catch(() => undefined);+ };+ window.addEventListener('pagehide', dispose);+ return () => window.removeEventListener('pagehide', dispose);+ }, [windowed]);++ const loading = <div className="grid h-full w-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>;+ const content =+ sessionId == null ? (+ loading+ ) : (+ <Suspense fallback={loading}>+ <TerminalView sessionId={sessionId} />+ </Suspense>+ );++ if (windowed) {+ return <div className="h-full w-full overflow-hidden bg-surface">{content}</div>;+ }+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 className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">{content}</div></div>);};diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxnew file mode 100644index 000000000..4c0b626fd--- /dev/null+++ b/ui/src/components/workbench/EditorApp.tsx@@ -0,0 +1,46 @@+import { Suspense, lazy } from 'react';+import { useTranslation } from 'react-i18next';+import { FileCode2 } from 'lucide-react';++// The Editor window body. Reuses FileEditorPane (Monaco) so the standalone Editor+// app and the in-Files edit pane share one editor. Files opens a file here via+// `openApp('editor', { params: { path, filename, mtime } })`; with no file it+// shows a tasteful empty state.+const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));++export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unknown> }> = ({ windowId, params }) => {+ const { t } = useTranslation();+ const path = typeof params?.path === 'string' ? params.path : null;+ const mtime = typeof params?.mtime === 'number' ? params.mtime : null;+ const filename =+ typeof params?.filename === 'string'+ ? params.filename+ : path+ ? path.split('/').filter(Boolean).pop() ?? path+ : '';++ if (!path) {+ return (+ <div className="grid h-full w-full place-items-center bg-surface-2 p-6 text-center">+ <div className="flex max-w-xs flex-col items-center gap-3">+ <div className="grid size-14 place-items-center rounded-2xl border border-border bg-foreground/[0.03]">+ <FileCode2 className="size-7 text-violet" />+ </div>+ <div className="text-[14px] font-semibold text-foreground">{t('apps.editor.empty')}</div>+ <p className="text-[12.5px] text-muted">{t('apps.editor.emptyHint')}</p>+ </div>+ </div>+ );+ }++ return (+ <div className="h-full w-full bg-surface-2">+ <Suspense+ fallback={<div className="grid h-full w-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}+ >+ {/* key by path: remount per file so a stale load/save can't apply to a different file. */}+ <FileEditorPane key={path} path={path} filename={filename} mtime={mtime} windowId={windowId} />+ </Suspense>+ </div>+ );+};diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsxindex 396d6f0bf..62f5a8198 100644--- a/ui/src/components/workbench/FileEditorPane.tsx+++ b/ui/src/components/workbench/FileEditorPane.tsx@@ -1,39 +1,93 @@-import { Suspense, lazy, useEffect, useState } from 'react';+import { Suspense, lazy, useEffect, useId, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Loader2, Save } from 'lucide-react';-import { languages } from '@codemirror/language-data';+import { Loader2, PanelRightOpen, Save } from 'lucide-react';import clsx from 'clsx';+import { useTheme } from '../../context/ThemeContext';+import { useWindowCloseGuard } from '../../context/WindowManagerContext';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'));+// Monaco (the VS Code kernel) is heavy; lazy-load it so it stays out of the main+// bundle and only loads when a file is actually opened for editing.+const MonacoEditor = lazy(() => import('./MonacoEditor'));-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 [];- }+// Map a filename to a Monaco language id. Monaco colours unknown languages as+// plaintext, so this only needs to cover the common cases; the heavy semantic+// languages (ts/js/json/css/html) also have workers wired in MonacoEditor.+const LANGUAGE_BY_EXT: Record<string, string> = {+ ts: 'typescript',+ tsx: 'typescript',+ cts: 'typescript',+ mts: 'typescript',+ js: 'javascript',+ jsx: 'javascript',+ cjs: 'javascript',+ mjs: 'javascript',+ json: 'json',+ jsonc: 'json',+ css: 'css',+ scss: 'scss',+ less: 'less',+ html: 'html',+ htm: 'html',+ xml: 'xml',+ svg: 'xml',+ md: 'markdown',+ markdown: 'markdown',+ py: 'python',+ rb: 'ruby',+ go: 'go',+ rs: 'rust',+ java: 'java',+ kt: 'kotlin',+ c: 'c',+ h: 'c',+ cpp: 'cpp',+ cc: 'cpp',+ hpp: 'cpp',+ cs: 'csharp',+ php: 'php',+ swift: 'swift',+ sh: 'shell',+ bash: 'shell',+ zsh: 'shell',+ yml: 'yaml',+ yaml: 'yaml',+ toml: 'ini',+ ini: 'ini',+ cfg: 'ini',+ sql: 'sql',+ dockerfile: 'dockerfile',+ graphql: 'graphql',+ lua: 'lua',+};++function monacoLanguage(filename: string): string | undefined {+ const lower = filename.toLowerCase();+ if (lower === 'dockerfile') return 'dockerfile';+ const ext = lower.includes('.') ? lower.split('.').pop()! : '';+ return LANGUAGE_BY_EXT[ext];}-// 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,-}) => {+// Read + edit + save one text/code file. Read-only is just `readOnly`. When+// `onPopOut` is provided (the in-Files editor pane), a button pops the file out+// into a standalone Editor window. Pop-out reports the editor's *live* mtime so+// the new window saves against the current revision (this pane may have saved+// since the row was opened), not the stale metadata the row carried.+export const FileEditorPane: React.FC<{+ path: string;+ filename: string;+ mtime: number | null;+ readOnly?: boolean;+ onPopOut?: (live: { mtime: number | null }) => void;+ /** The owning window id, when this editor lives in a window — enables the unsaved-close guard. */+ windowId?: string;+}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId }) => {const { t } = useTranslation();+ const { resolvedTheme } = useTheme();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);@@ -57,18 +111,28 @@ export const FileEditorPane: React.FC<{ path: string; filename: string; mtime: n.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;+ const dirty = !readOnly && text !== null && text !== original;+ const language = monacoLanguage(filename);+ // Monaco reuses models by `path`, so each editor INSTANCE needs a unique model URI.+ // Otherwise two panes on the same file share one model while keeping separate+ // original/savedMtime — e.g. the full-page /apps/files route mounts both the desktop+ // and the md:hidden mobile ContentPane (both windowId-less), so a save in one leaves the+ // other looking dirty and false-conflicting. Prefix a per-instance id; keep the file+ // extension so Monaco's TS worker still picks JSX/TSX for .tsx/.jsx.+ const editorUid = useId();+ const monacoPath = `${editorUid.replace(/:/g, '')}/${path.replace(/^\/+/, '')}`;++ // Veto closing the owning window while there are unsaved edits (the close unmounts+ // this pane and the buffer only lives in React state). No-op for the full-page route.+ useWindowCloseGuard(windowId, dirty ? t('apps.editor.confirmDiscardClose') : null);async function save() {- if (text === null || saving) return;+ if (text === null || saving || readOnly) return;setSaving(true);setError(null);try {@@ -87,17 +151,35 @@ export const FileEditorPane: React.FC<{ path: string; filename: string; mtime: n<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>+ {onPopOut && (+ <Button+ type="button"+ size="icon"+ variant="ghost"+ className="size-7 shrink-0 text-muted"+ aria-label={t('apps.editor.openInWindow')}+ // Block pop-out while dirty: the new window reloads from disk, so+ // popping out unsaved edits would silently drop them. Save first.+ title={dirty ? t('apps.editor.saveBeforePopOut') : t('apps.editor.openInWindow')}+ disabled={dirty}+ onClick={() => onPopOut({ mtime: savedMtime })}+ >+ <PanelRightOpen className="size-3.5" />+ </Button>+ )}+ {!readOnly && (+ <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 && (@@ -106,17 +188,18 @@ export const FileEditorPane: React.FC<{ path: string; filename: string; mtime: n</div>)}- <div className={clsx('min-h-0 flex-1 overflow-auto', loading && 'grid place-items-center')}>+ <div className={clsx('min-h-0 flex-1', 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+ <MonacoEditorvalue={text}- height="100%"- extensions={langExt}- onChange={(value: string) => setText(value)}- basicSetup={{ lineNumbers: true, highlightActiveLine: true }}+ language={language}+ path={monacoPath}+ readOnly={readOnly}+ dark={resolvedTheme === 'dark'}+ onChange={(value) => setText(value)}/></Suspense>)}diff --git a/ui/src/components/workbench/MonacoEditor.tsx b/ui/src/components/workbench/MonacoEditor.tsxnew file mode 100644index 000000000..260712920--- /dev/null+++ b/ui/src/components/workbench/MonacoEditor.tsx@@ -0,0 +1,217 @@+import { useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { ClipboardCopy, TextSelect } from 'lucide-react';+import * as monaco from 'monaco-editor';+import { Editor, loader, type OnChange, type OnMount } from '@monaco-editor/react';++import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';+import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';+import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';+import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';+import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';++// The VS Code kernel. ALL monaco imports live in THIS module so that+// `React.lazy(() => import('./MonacoEditor'))` keeps monaco-editor + its language+// workers out of the main entry chunk — they load only when an editor first opens+// (verified: monaco is its own content-hashed chunk in `npm run build`).+//+// Self-hosted: Avibe serves the UI from the user's own machine, so the workers are+// emitted as local chunks (no CDN). We register the bundled instance with+// @monaco-editor/react via loader.config() instead of letting it fetch the AMD+// build remotely. Worker set is trimmed to the languages that ship a worker —+// editor service + json + ts/js + css + html; everything else (markdown, python,+// go, rust, yaml, …) uses Monaco's worker-less Monarch tokenizer and still+// highlights without a dedicated worker.+self.MonacoEnvironment = {+ getWorker(_workerId: string, label: string): Worker {+ switch (label) {+ case 'json':+ return new jsonWorker();+ case 'css':+ case 'scss':+ case 'less':+ return new cssWorker();+ case 'html':+ case 'handlebars':+ case 'razor':+ return new htmlWorker();+ case 'typescript':+ case 'javascript':+ return new tsWorker();+ default:+ return new editorWorker();+ }+ },+};++loader.config({ monaco });++// One-time global setup, run on first mount of any editor.+let configured = false;+function setupMonaco(): void {+ if (configured) return;+ configured = true;++ // An avibe-flavoured dark theme: vs-dark, but with the editor surface matched to+ // the window's --surface-2 so Monaco blends into the AppWindow chrome instead of+ // sitting on its own near-black slab.+ monaco.editor.defineTheme('avibe-dark', {+ base: 'vs-dark',+ inherit: true,+ rules: [],+ colors: {+ 'editor.background': '#11111c',+ 'editorGutter.background': '#11111c',+ 'minimap.background': '#11111c',+ 'editorLineNumber.foreground': '#4b5163',+ 'editorLineNumber.activeForeground': '#9ba3b8',+ 'editorWidget.background': '#0e0e18',+ 'editor.lineHighlightBackground': '#ffffff0a',+ 'editor.selectionBackground': '#3fe0e533',+ 'editorIndentGuide.background1': '#ffffff12',+ },+ });++ // This is a whole-machine file editor, not a project IDE: a lone file would+ // otherwise light up with false "cannot find module" / "duplicate identifier"+ // semantic errors. Keep syntax checking, drop semantic validation for ts/js.+ // (0.55 moved the language namespaces to the top level — monaco.typescript.)+ for (const defaults of [monaco.typescript.typescriptDefaults, monaco.typescript.javascriptDefaults]) {+ defaults.setDiagnosticsOptions({ noSemanticValidation: true, noSyntaxValidation: false });+ }+}++// Symbol keys phones can't easily reach (mirrors the Terminal accessory bar).+const SYMBOL_KEYS = ['(', ')', '{', '}', '[', ']', ';', ':', '=', '"', "'", '`', '|', '/', '\\', '-', '_'];++export interface MonacoEditorProps {+ value: string;+ /** Monaco language id (e.g. `typescript`); falls back to plaintext when omitted. */+ language?: string;+ /**+ * Model path/URI for the file. Monaco's TS/JS worker keys JSX/TSX script kind off+ * the model URI's extension, so `.tsx`/`.jsx` files need a path here or they parse as+ * plain TS/JS and show bogus syntax errors. Should be unique per open editor.+ */+ path?: string;+ readOnly?: boolean;+ /** Resolved app theme — drives the dark VS Code theme vs the light one. */+ dark?: boolean;+ onChange?: (value: string) => void;+}++export default function MonacoEditor({ value, language, path, readOnly, dark = true, onChange }: MonacoEditorProps) {+ const { t } = useTranslation();+ const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);++ const handleMount: OnMount = (editor) => {+ editorRef.current = editor;+ };+ const handleChange: OnChange = (next) => onChange?.(next ?? '');++ // Accessory actions operate on the live editor instance.+ const insert = (text: string) => {+ const editor = editorRef.current;+ if (!editor || readOnly) return;+ editor.focus();+ const selection = editor.getSelection();+ if (selection) editor.executeEdits('accessory', [{ range: selection, text, forceMoveMarkers: true }]);+ };+ const indent = () => {+ const editor = editorRef.current;+ if (!editor || readOnly) return;+ editor.focus();+ // The `tab` command honours the model's insertSpaces / tabSize settings.+ editor.trigger('accessory', 'tab', null);+ };+ const dismissKeyboard = () => {+ // On phones Esc has no real editor meaning; use it to drop focus and hide the+ // soft keyboard so the user can read the file.+ (document.activeElement as HTMLElement | null)?.blur();+ };+ const selectAll = () => {+ const editor = editorRef.current;+ if (!editor) return;+ editor.focus();+ editor.getAction('editor.action.selectAll')?.run();+ };+ const copyAll = () => {+ const editor = editorRef.current;+ if (!editor) return;+ void navigator.clipboard?.writeText(editor.getValue());+ };++ const accessoryBtn =+ '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]';++ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="min-h-0 flex-1">+ <Editor+ theme={dark ? 'avibe-dark' : 'light'}+ path={path}+ language={language}+ value={value}+ onChange={handleChange}+ onMount={handleMount}+ beforeMount={setupMonaco}+ loading={+ <div className="grid h-full w-full place-items-center bg-surface-2 text-[12px] text-muted">+ {t('common.loading')}+ </div>+ }+ options={{+ readOnly,+ fontSize: 13,+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',+ minimap: { enabled: false },+ scrollBeyondLastLine: false,+ automaticLayout: true,+ tabSize: 2,+ renderWhitespace: 'selection',+ smoothScrolling: true,+ cursorBlinking: 'smooth',+ padding: { top: 10, bottom: 10 },+ scrollbar: { useShadows: false },+ }}+ />+ </div>++ {/* Mobile accessory bar — Monaco has no touch affordances, so phones get the+ symbol keys + select/copy helpers, the same pattern as TerminalView. */}+ <div className="flex items-center gap-1 overflow-x-auto border-t border-border bg-surface px-2 py-1.5 md:hidden">+ {!readOnly &&+ SYMBOL_KEYS.map((key) => (+ <button key={key} type="button" onClick={() => insert(key)} className={accessoryBtn}>+ {key}+ </button>+ ))}+ {!readOnly && (+ <button type="button" onClick={indent} className={accessoryBtn}>+ {t('apps.terminal.keys.tab')}+ </button>+ )}+ <button type="button" onClick={dismissKeyboard} className={accessoryBtn}>+ {t('apps.terminal.keys.esc')}+ </button>+ <span className="mx-0.5 h-5 w-px shrink-0 bg-border-strong" />+ <button+ type="button"+ onClick={selectAll}+ className="flex shrink-0 items-center gap-1 rounded-md border border-border-strong px-2.5 py-1.5 text-[12px] text-foreground active:bg-foreground/[0.08]"+ >+ <TextSelect className="size-3.5" />+ {t('apps.editor.selectAll')}+ </button>+ <button+ type="button"+ onClick={copyAll}+ className="flex shrink-0 items-center gap-1 rounded-md border border-border-strong px-2.5 py-1.5 text-[12px] text-foreground active:bg-foreground/[0.08]"+ >+ <ClipboardCopy className="size-3.5" />+ {t('apps.editor.copyAll')}+ </button>+ </div>+ </div>+ );+}diff --git a/ui/src/context/WindowManagerContext.tsx b/ui/src/context/WindowManagerContext.tsxnew file mode 100644index 000000000..8ca93a7dd--- /dev/null+++ b/ui/src/context/WindowManagerContext.tsx@@ -0,0 +1,202 @@+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';++import { APP_REGISTRY, type AppId } from '../apps/registry';++// One open app window. Bounds are in CSS px relative to the window LAYER (the+// workbench main area, right of the sidebar). z drives stacking + focus order.+export interface WindowBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface WindowInstance {+ id: string;+ appId: AppId;+ /** Optional per-instance title override (e.g. an open file path); falls back to the app's titleKey. */+ title?: string;+ /** Per-instance launch params surfaced to the app body (e.g. the file an Editor window opens). */+ params?: Record<string, unknown>;+ bounds: WindowBounds;+ z: number;+ minimized: boolean;+ maximized: boolean;+ // Bounds captured before a maximize, restored on un-maximize.+ restoreBounds?: WindowBounds;+}++export interface OpenAppOptions {+ title?: string;+ bounds?: Partial<WindowBounds>;+ params?: Record<string, unknown>;+}++export interface WindowManagerValue {+ windows: WindowInstance[];+ /** The current top window id (highest z, not minimized), or null. */+ focusedId: string | null;+ openApp: (appId: AppId, opts?: OpenAppOptions) => string;+ close: (id: string) => void;+ focus: (id: string) => void;+ minimize: (id: string) => void;+ /** Un-minimize and bring to front. */+ restore: (id: string) => void;+ toggleMaximize: (id: string) => void;+ /** Patch a window's bounds (used by drag + resize). */+ setBounds: (id: string, bounds: Partial<WindowBounds>) => void;+ /**+ * Register (or clear, by passing null) a guard a window body uses to veto closing.+ * The getter returns a confirm message when closing would lose work, else null.+ */+ setCloseGuard: (id: string, getMessage: (() => string | null) | null) => void;+ /** Run a window's close guard (confirm if it has a message); true = may close. */+ confirmClose: (id: string) => boolean;+}++const WindowManagerContext = createContext<WindowManagerValue | null>(null);++const DEFAULT_SIZE = { width: 760, height: 520 };+// Cascade each new window down-right from the last so stacks stay reachable.+const CASCADE_STEP = 32;+const CASCADE_WRAP = 6;++export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [windows, setWindows] = useState<WindowInstance[]>([]);+ const idSeq = useRef(0);+ const zSeq = useRef(0);+ const openCount = useRef(0);+ // Per-window close guards: a body (e.g. a dirty editor) registers a getter that+ // returns a confirm message when closing would lose work. Held in a ref so it+ // never triggers re-renders.+ const closeGuards = useRef(new Map<string, () => string | null>());++ const setCloseGuard = useCallback((id: string, getMessage: (() => string | null) | null) => {+ if (getMessage) closeGuards.current.set(id, getMessage);+ else closeGuards.current.delete(id);+ }, []);++ const confirmClose = useCallback((id: string): boolean => {+ const message = closeGuards.current.get(id)?.();+ return !message || window.confirm(message);+ }, []);++ const focus = useCallback((id: string) => {+ setWindows((prev) => {+ const target = prev.find((w) => w.id === id);+ if (!target) return prev;+ const nextZ = ++zSeq.current;+ // Already on top → no churn.+ if (target.z === nextZ - 1 && prev.every((w) => w.id === id || w.z < target.z)) return prev;+ return prev.map((w) => (w.id === id ? { ...w, z: nextZ } : w));+ });+ }, []);++ const openApp = useCallback<WindowManagerValue['openApp']>((appId, opts) => {+ const def = APP_REGISTRY[appId];+ const size = { ...DEFAULT_SIZE, ...def?.defaultSize };+ const i = openCount.current++ % CASCADE_WRAP;+ const id = `win-${++idSeq.current}`;+ const z = ++zSeq.current;+ const bounds: WindowBounds = {+ x: 40 + i * CASCADE_STEP,+ y: 32 + i * CASCADE_STEP,+ width: size.width,+ height: size.height,+ ...opts?.bounds,+ };+ setWindows((prev) => [+ ...prev,+ {+ id,+ appId,+ title: opts?.title,+ params: opts?.params,+ bounds,+ z,+ minimized: false,+ maximized: false,+ },+ ]);+ return id;+ }, []);++ const close = useCallback((id: string) => {+ closeGuards.current.delete(id);+ setWindows((prev) => prev.filter((w) => w.id !== id));+ }, []);++ const minimize = useCallback((id: string) => {+ setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, minimized: true } : w)));+ }, []);++ const restore = useCallback(+ (id: string) => {+ setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, minimized: false } : w)));+ focus(id);+ },+ [focus],+ );++ const toggleMaximize = useCallback((id: string) => {+ setWindows((prev) =>+ prev.map((w) => {+ if (w.id !== id) return w;+ if (w.maximized) {+ return { ...w, maximized: false, bounds: w.restoreBounds ?? w.bounds, restoreBounds: undefined };+ }+ return { ...w, maximized: true, restoreBounds: w.bounds };+ }),+ );+ focus(id);+ }, [focus]);++ const setBounds = useCallback((id: string, patch: Partial<WindowBounds>) => {+ setWindows((prev) => prev.map((w) => (w.id === id ? { ...w, bounds: { ...w.bounds, ...patch } } : w)));+ }, []);++ const focusedId = useMemo(() => {+ const visible = windows.filter((w) => !w.minimized);+ if (visible.length === 0) return null;+ return visible.reduce((top, w) => (w.z > top.z ? w : top)).id;+ }, [windows]);++ const value = useMemo<WindowManagerValue>(+ () => ({+ windows,+ focusedId,+ openApp,+ close,+ focus,+ minimize,+ restore,+ toggleMaximize,+ setBounds,+ setCloseGuard,+ confirmClose,+ }),+ [windows, focusedId, openApp, close, focus, minimize, restore, toggleMaximize, setBounds, setCloseGuard, confirmClose],+ );++ return <WindowManagerContext.Provider value={value}>{children}</WindowManagerContext.Provider>;+};++export function useWindowManager(): WindowManagerValue {+ const ctx = useContext(WindowManagerContext);+ if (!ctx) throw new Error('useWindowManager must be used within a WindowManagerProvider');+ return ctx;+}++// A window body calls this to veto its own close while there's unsaved work: pass+// the owning window id and a confirm message (or null when clean). No-ops for a+// non-windowed (full-page) mount, where windowId is undefined.+export function useWindowCloseGuard(windowId: string | undefined, message: string | null): void {+ const { setCloseGuard } = useWindowManager();+ const messageRef = useRef(message);+ messageRef.current = message;+ useEffect(() => {+ if (!windowId) return;+ setCloseGuard(windowId, () => messageRef.current);+ return () => setCloseGuard(windowId, null);+ }, [windowId, setCloseGuard]);+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 8db092f19..f9d43629b 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -601,6 +601,25 @@"apps": {"title": "Apps","soon": "Soon",+ "editor": {+ "label": "Editor",+ "desc": "A fast code editor for files on this machine.",+ "empty": "No file open",+ "emptyHint": "Open a file from Files to edit it here.",+ "openInWindow": "Open in editor window",+ "saveBeforePopOut": "Save before opening in a window",+ "confirmDiscardClose": "Discard unsaved changes and close this window?",+ "selectAll": "Select all",+ "copyAll": "Copy all"+ },+ "dock": {+ "newInstanceHint": "⌘-click for a new window"+ },+ "window": {+ "minimize": "Minimize",+ "maximize": "Maximize",+ "restore": "Restore"+ },"fileBrowser": {"label": "File Browser","desc": "Browse, view, and edit files on this machine.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex d7ea889c3..c2898055d 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -601,6 +601,25 @@"apps": {"title": "应用","soon": "即将上线",+ "editor": {+ "label": "编辑器",+ "desc": "本机文件的快速代码编辑器。",+ "empty": "未打开文件",+ "emptyHint": "从「文件」中打开一个文件,在这里编辑。",+ "openInWindow": "在编辑器窗口中打开",+ "saveBeforePopOut": "请先保存,再在新窗口中打开",+ "confirmDiscardClose": "放弃未保存的更改并关闭此窗口?",+ "selectAll": "全选",+ "copyAll": "全部复制"+ },+ "dock": {+ "newInstanceHint": "⌘ 点击可新建窗口"+ },+ "window": {+ "minimize": "最小化",+ "maximize": "最大化",+ "restore": "还原"+ },"fileBrowser": {"label": "文件浏览器","desc": "浏览、查看、编辑这台机器上的文件。",diff --git a/ui/src/index.css b/ui/src/index.cssindex a58b04952..bf4aa83e3 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -431,6 +431,20 @@ pre,animation: slide-in 0.2s ease-out;}+/* App windows (Apps layer): a subtle scale+fade on open/restore, and a+ scale-down toward the Dock on minimize/close. Short enough to read as+ responsiveness, not a transition you wait on. */+@keyframes appwindow-in {+ from { opacity: 0; transform: scale(0.97) translateY(6px); }+ to { opacity: 1; transform: scale(1) translateY(0); }+}+@keyframes appwindow-out {+ from { opacity: 1; transform: scale(1) translateY(0); }+ to { opacity: 0; transform: scale(0.94) translateY(12px); }+}+.animate-appwindow-in { animation: appwindow-in 140ms ease-out; }+.animate-appwindow-out { animation: appwindow-out 130ms ease-in forwards; }+/* Chat compose "thinking" indicator — three dots fading in sequence while wewait for the agent's first streamed chunk (workbench ChatPage). */@keyframes vr-typing {diff --git a/ui/src/lib/terminalSlots.test.ts b/ui/src/lib/terminalSlots.test.tsnew file mode 100644index 000000000..23232a953--- /dev/null+++ b/ui/src/lib/terminalSlots.test.ts@@ -0,0 +1,33 @@+import { afterEach, describe, expect, it } from 'vitest';++import { acquireTerminalSlot, releaseTerminalSlot, _resetTerminalSlots } from './terminalSlots';++afterEach(() => _resetTerminalSlots());++describe('terminal session slots', () => {+ it('hands out distinct slots so concurrent terminals never collide', () => {+ expect(acquireTerminalSlot()).toBe(0);+ expect(acquireTerminalSlot()).toBe(1);+ expect(acquireTerminalSlot()).toBe(2);+ });++ it('reuses a released slot — the pool stays bounded by concurrency, not churn', () => {+ const a = acquireTerminalSlot(); // 0+ const b = acquireTerminalSlot(); // 1+ expect([a, b]).toEqual([0, 1]);+ releaseTerminalSlot(a);+ // The next terminal must reuse slot 0, not grow to 2 — otherwise opening and+ // closing terminals would leak session ids until the backend cap is exhausted.+ expect(acquireTerminalSlot()).toBe(0);+ expect(acquireTerminalSlot()).toBe(2); // 1 still held, 0 just retaken+ });++ it('fills the lowest free slot after releases in any order', () => {+ [0, 1, 2, 3].forEach(() => acquireTerminalSlot());+ releaseTerminalSlot(2);+ releaseTerminalSlot(0);+ expect(acquireTerminalSlot()).toBe(0);+ expect(acquireTerminalSlot()).toBe(2);+ expect(acquireTerminalSlot()).toBe(4);+ });+});diff --git a/ui/src/lib/terminalSlots.ts b/ui/src/lib/terminalSlots.tsnew file mode 100644index 000000000..c4d6f6409--- /dev/null+++ b/ui/src/lib/terminalSlots.ts@@ -0,0 +1,30 @@+// Bounded session slots for windowed terminals.+//+// Each windowed terminal needs its own backend session id (so two terminal windows+// — or a window and the /apps/terminal route — don't evict each other's attached+// client). Keying that off the ever-increasing window id would mint an unbounded+// number of session ids: the backend keeps detached tmux sessions in its capacity+// accounting (cap ~8) until an idle timeout, so opening/closing terminal windows+// would exhaust the service even with no terminal open.+//+// Instead we hand each live windowed terminal the lowest free slot index and return+// it on close, so the number of distinct windowed session ids never exceeds the+// number of terminals open at once. Module-level (per page load); the route terminal+// doesn't take a slot — it keeps its persistent, localStorage-backed id.+const inUse = new Set<number>();++export function acquireTerminalSlot(): number {+ let i = 0;+ while (inUse.has(i)) i += 1;+ inUse.add(i);+ return i;+}++export function releaseTerminalSlot(slot: number): void {+ inUse.delete(slot);+}++// Test-only: reset the shared pool between cases.+export function _resetTerminalSlots(): void {+ inUse.clear();+}diff --git a/ui/src/lib/windowBounds.test.ts b/ui/src/lib/windowBounds.test.tsnew file mode 100644index 000000000..97e3e2fd9--- /dev/null+++ b/ui/src/lib/windowBounds.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import { clampToLayer, resizeBounds, EDGE_KEEP, TITLE_KEEP, MIN_H, MIN_W } from './windowBounds';++// Geometry behind the windowing fixes: a window's grabbable titlebar must stay+// reachable no matter how it is moved (drag), resized, or how the layer shrinks.+// Each "would strand the titlebar without clampToLayer" case asserts BOTH the raw+// bug (origin lands off the layer) and that clampToLayer corrects it — so dropping+// the clamp, on any of those paths, fails here.+describe('clampToLayer', () => {+ const LAYER_W = 1200;+ const LAYER_H = 800;+ const maxX = LAYER_W - EDGE_KEEP; // window's left edge can't pass this+ const maxY = LAYER_H - TITLE_KEEP - 28; // titlebar can't drop below this++ it('leaves a fully on-screen window untouched', () => {+ const b = { x: 200, y: 150, width: 600, height: 400 };+ expect(clampToLayer(b, LAYER_W, LAYER_H)).toEqual(b);+ });++ it('preserves size — only the origin is ever clamped', () => {+ const out = clampToLayer({ x: 5000, y: 5000, width: 640, height: 480 }, LAYER_W, LAYER_H);+ expect(out.width).toBe(640);+ expect(out.height).toBe(480);+ });++ it('pulls a window dragged past the right/bottom edge back into reach', () => {+ const out = clampToLayer({ x: 1180, y: 1180, width: 500, height: 400 }, LAYER_W, LAYER_H);+ expect(out.x).toBe(maxX);+ expect(out.y).toBe(maxY);+ });++ it('keeps the titlebar on-screen when the layer shrinks under a window (re-clamp on resize)', () => {+ // A window comfortably placed on a wide display...+ const wide = { x: 1400, y: 700, width: 520, height: 360 };+ // ...is entirely outside a now-narrow/short layer; without re-clamping, Dock+ // activation would just focus this unreachable instance.+ const narrowW = 900;+ const narrowH = 600;+ const out = clampToLayer(wide, narrowW, narrowH);+ expect(out.x).toBe(narrowW - EDGE_KEEP);+ expect(out.y).toBe(narrowH - TITLE_KEEP - 28);+ });++ it("won't let a window be pushed off the top/left either", () => {+ const out = clampToLayer({ x: -900, y: -50, width: 500, height: 400 }, LAYER_W, LAYER_H);+ expect(out.x).toBe(EDGE_KEEP - 500); // keep EDGE_KEEP of the right side reachable+ expect(out.y).toBe(TITLE_KEEP);+ });+});++describe('resizeBounds + clampToLayer (north/west edge past the minimum size)', () => {+ const LAYER_W = 1200;+ const LAYER_H = 800;+ const maxY = LAYER_H - TITLE_KEEP - 28;+ const maxX = LAYER_W - EDGE_KEEP;++ it('clamps the dragged-down north edge so the titlebar cannot leave the bottom', () => {+ // Window taller than the layer (user grew it). Drag the TOP edge down far past+ // the min height: the north resize anchors the bottom and slides the origin down.+ const start = { x: 100, y: 200, width: 500, height: 900 };+ const raw = resizeBounds(start, 'n', 0, 700);+ expect(raw.height).toBe(MIN_H); // collapsed to the minimum+ // The bug, uncorrected: the new origin sits below the reachable band.+ expect(raw.y).toBeGreaterThan(maxY);+ // The fix: clampToLayer pulls the titlebar back to the bottom keep-line.+ expect(clampToLayer(raw, LAYER_W, LAYER_H).y).toBe(maxY);+ });++ it('clamps the dragged-right west edge so the titlebar cannot leave the right', () => {+ // Wide window whose right edge runs off the layer (user grew it). Dragging the+ // LEFT edge right past the min width anchors the right edge and slides x toward+ // it — far enough to push the origin (and traffic lights) off the right side.+ const start = { x: 600, y: 100, width: 1000, height: 400 };+ const raw = resizeBounds(start, 'w', 1300, 0);+ expect(raw.width).toBe(MIN_W);+ expect(raw.x).toBeGreaterThan(maxX);+ expect(clampToLayer(raw, LAYER_W, LAYER_H).x).toBe(maxX);+ });++ it('enforces the minimum window size when shrinking from the east/south', () => {+ const start = { x: 0, y: 0, width: 500, height: 500 };+ const out = resizeBounds(start, 'se', -5000, -5000);+ expect(out.width).toBe(MIN_W);+ expect(out.height).toBe(MIN_H);+ });+});diff --git a/ui/src/lib/windowBounds.ts b/ui/src/lib/windowBounds.tsnew file mode 100644index 000000000..6cb6db199--- /dev/null+++ b/ui/src/lib/windowBounds.ts@@ -0,0 +1,40 @@+import type { WindowBounds } from '../context/WindowManagerContext';++export type ResizeDir = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';++export const MIN_W = 360;+export const MIN_H = 240;+// Keep at least this much of the window (incl. the grabbable titlebar) reachable,+// so a move, a resize, or the layer shrinking can never strand the titlebar fully+// off-screen and leave the window unrecoverable without a refresh.+export const EDGE_KEEP = 120;+export const TITLE_KEEP = 8;++// Clamp window bounds so the (grabbable) titlebar stays reachable. Only the origin+// is clamped; the size is preserved so a window never silently changes dimensions.+// Used by every path that can move a window: drag, resize, and layer re-clamp.+export function clampToLayer(b: WindowBounds, layerW: number, layerH: number): WindowBounds {+ return {+ ...b,+ x: Math.min(Math.max(b.x, EDGE_KEEP - b.width), layerW - EDGE_KEEP),+ y: Math.min(Math.max(b.y, TITLE_KEEP), layerH - TITLE_KEEP - 28),+ };+}++// New bounds for a resize gesture, measured from a fixed gesture start. The N/W+// edges move the origin (the opposite edge stays anchored), which is why the+// result still has to be run through clampToLayer before it is applied.+export function resizeBounds(start: WindowBounds, dir: ResizeDir, dx: number, dy: number): WindowBounds {+ let { x, y, width, height } = start;+ if (dir.includes('e')) width = Math.max(MIN_W, start.width + dx);+ if (dir.includes('s')) height = Math.max(MIN_H, start.height + dy);+ if (dir.includes('w')) {+ width = Math.max(MIN_W, start.width - dx);+ x = start.x + (start.width - width);+ }+ if (dir.includes('n')) {+ height = Math.max(MIN_H, start.height - dy);+ y = start.y + (start.height - height);+ }+ return { x, y, width, height };+}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 4d982e86b..223ab3c22 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -20,6 +20,7 @@ from collections import OrderedDictfrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Path+from types import SimpleNamespacefrom typing import Any, Callablefrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplit@@ -2144,7 +2145,41 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):logger.info("terminal.session_close session_ref=%s remote_addr=%s", session_ref, remote_addr)-def _show_runtime_websocket_authorized(websocket: WebSocket) -> bool:[email protected]("/api/terminal/<session_id>", methods=["DELETE"])+async def terminal_session_delete(session_id: str):+ if not _terminal_enabled():+ return jsonify({"ok": False, "error": "terminal_disabled"}), 403+ if not TERMINAL_SUPPORTED:+ return jsonify({"ok": False, "error": "terminal_unsupported"}), 403++ terminal_request = _terminal_http_request_adapter()+ if not _terminal_origin_allowed(terminal_request):+ return jsonify({"ok": False, "error": "terminal_origin_forbidden"}), 403+ if not _show_runtime_websocket_authorized(terminal_request):+ return jsonify({"ok": False, "error": "terminal_unauthorized"}), 403++ remote_subject = _remote_access_websocket_subject(terminal_request)+ effective_session_id = _terminal_effective_session_id(session_id, remote_subject)+ session_ref = _terminal_session_log_ref(effective_session_id)+ terminated = await get_terminal_service().terminate(effective_session_id)+ if not terminated:+ logger.info("terminal.session_delete_absent session_ref=%s", session_ref)+ return jsonify({"ok": False, "error": "terminal_session_not_found"}), 404+ logger.info("terminal.session_delete session_ref=%s", session_ref)+ return Response(status=204)+++def _terminal_http_request_adapter() -> SimpleNamespace:+ scheme = "wss" if request.is_secure else "ws"+ return SimpleNamespace(+ headers=request.headers,+ cookies=request.cookies,+ client=SimpleNamespace(host=request.remote_addr or ""),+ url=SimpleNamespace(scheme=scheme),+ )+++def _show_runtime_websocket_authorized(websocket: Any) -> bool:config = _load_remote_access_config()if config is None:return _websocket_is_local_request(websocket)@@ -2155,7 +2190,7 @@ def _show_runtime_websocket_authorized(websocket: WebSocket) -> bool: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:+def _remote_access_websocket_session_payload(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:if config is None or _websocket_is_local_request(websocket, config):return Noneif _websocket_normalized_host(websocket) != _remote_access_public_host(config):@@ -2170,7 +2205,7 @@ def _remote_access_websocket_session_payload(websocket: WebSocket, config: V2Con)-def _remote_access_websocket_subject(websocket: WebSocket) -> str | None:+def _remote_access_websocket_subject(websocket: Any) -> str | None:payload = _remote_access_websocket_session_payload(websocket, _load_remote_access_config())if not payload:return None@@ -2191,7 +2226,7 @@ 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:+def _terminal_origin_allowed(websocket: Any) -> bool:origin = _request_origin(websocket.headers.get("origin"))if not origin:return False@@ -2242,7 +2277,7 @@ def _terminal_origin_scheme_matches_socket(origin_scheme: str | None, socket_schreturn origin_secure == socket_secure-def _websocket_is_local_request(websocket: WebSocket, config: V2Config | None = None) -> bool:+def _websocket_is_local_request(websocket: Any, config: V2Config | None = None) -> bool:if _websocket_has_forwarded_metadata(websocket):return Falseclient_host = _websocket_client_host(websocket)@@ -2259,7 +2294,7 @@ def _websocket_is_local_request(websocket: WebSocket, config: V2Config | None =return _websocket_is_setup_host_request(websocket, config)-def _websocket_has_forwarded_metadata(websocket: WebSocket) -> bool:+def _websocket_has_forwarded_metadata(websocket: Any) -> bool:forwarded_headers = ("Forwarded","X-Forwarded-For",@@ -2277,14 +2312,14 @@ def _websocket_has_forwarded_metadata(websocket: WebSocket) -> bool:return any(websocket.headers.get(header) for header in forwarded_headers)-def _websocket_client_host(websocket: WebSocket) -> str:+def _websocket_client_host(websocket: Any) -> str:client_host = websocket.client.host if websocket.client else ""if client_host == "testclient":return websocket.headers.get(TEST_REMOTE_ADDR_HEADER) or client_hostreturn client_host-def _websocket_peer_address(websocket: WebSocket) -> ipaddress._BaseAddress | None:+def _websocket_peer_address(websocket: Any) -> ipaddress._BaseAddress | None:client_host = _websocket_client_host(websocket).strip()if not client_host or client_host in {"localhost", "testclient"}:return None@@ -2296,7 +2331,7 @@ def _websocket_peer_address(websocket: WebSocket) -> ipaddress._BaseAddress | Noreturn mapped or address-def _websocket_is_trusted_docker_peer(websocket: WebSocket) -> bool:+def _websocket_is_trusted_docker_peer(websocket: Any) -> bool:if not _env_flag_enabled("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS"):return Falseif not _has_loopback_only_docker_port_binding():@@ -2308,7 +2343,7 @@ def _websocket_is_trusted_docker_peer(websocket: WebSocket) -> bool:return address in _trusted_docker_loopback_peer_addresses()-def _websocket_is_trusted_docker_loopback_request(websocket: WebSocket) -> bool:+def _websocket_is_trusted_docker_loopback_request(websocket: Any) -> bool:if _websocket_has_forwarded_metadata(websocket):return Falseif not _is_loopback_host(websocket.headers.get("host")):@@ -2316,12 +2351,12 @@ def _websocket_is_trusted_docker_loopback_request(websocket: WebSocket) -> bool:return _websocket_is_trusted_docker_peer(websocket)-def _websocket_is_private_peer(websocket: WebSocket) -> bool:+def _websocket_is_private_peer(websocket: Any) -> bool:address = _websocket_peer_address(websocket)return address is not None and _is_private_address(address)-def _websocket_peer_shares_setup_host_network(websocket: WebSocket, setup_address: ipaddress._BaseAddress) -> bool:+def _websocket_peer_shares_setup_host_network(websocket: Any, setup_address: ipaddress._BaseAddress) -> bool:peer = _websocket_peer_address(websocket)if peer is None:return False@@ -2336,7 +2371,7 @@ def _websocket_peer_shares_setup_host_network(websocket: WebSocket, setup_addresreturn peer in network-def _websocket_is_wildcard_setup_host_request(websocket: WebSocket, config: V2Config | None) -> bool:+def _websocket_is_wildcard_setup_host_request(websocket: Any, config: V2Config | None) -> bool:if config is None:return Falsesetup_host = _normalized_host(getattr(config.ui, "setup_host", ""))@@ -2363,7 +2398,7 @@ def _websocket_is_wildcard_setup_host_request(websocket: WebSocket, config: V2Coreturn _websocket_peer_shares_setup_host_network(websocket, host_address)-def _websocket_is_setup_host_request(websocket: WebSocket, config: V2Config | None) -> bool:+def _websocket_is_setup_host_request(websocket: Any, config: V2Config | None) -> bool:if config is None:return Falsesetup_host = _normalized_host(getattr(config.ui, "setup_host", ""))@@ -2390,7 +2425,7 @@ def _websocket_is_setup_host_request(websocket: WebSocket, config: V2Config | Noreturn True-def _websocket_normalized_host(websocket: WebSocket) -> str:+def _websocket_normalized_host(websocket: Any) -> str:return _normalized_host(websocket.headers.get("x-forwarded-host") or websocket.headers.get("host"))