Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(apps): pin Show Pages to the Dock as apps (#892)

Call White99abca024e8d
diff --git a/core/dock_store.py b/core/dock_store.py
new file mode 100644
index 000000000..77a2d460d
--- /dev/null
+++ b/core/dock_store.py
@@ -0,0 +1,244 @@
+"""Server-side Dock state: which apps are pinned to the workbench Dock, and in
+what order the resident tiles sit.
+
+The Dock is durable *product* state — it follows the user across devices — not
+per-browser UI state, so it lives in the shared ``state_meta`` KV under a single
+versioned key, alongside the other cross-device workbench state. v1 knows two
+kinds of dock item:
+
+- built-in apps, keyed by their app id verbatim (``files`` / ``terminal`` /
+ ``editor``). They are reorderable but not unpinnable.
+- pinned Show Pages, keyed ``show:<session_id>``.
+
+Future item kinds (``app:<id>`` …) slot into the same ``order`` list without a
+migration — see docs/plans/dock-pinned-show-page-apps.md §7.
+
+``order`` covers every resident tile, built-ins included. The document is
+*reconciled on read* (drop unknown ids, append any missing built-ins/pins) and
+*validated on write* (order must be exactly the known id set, no duplicates,
+bounded), so a stale or corrupt blob can never desync the Dock.
+"""
+
+from __future__ import annotations
+
+import threading
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from core.chat_discovery import get_state_meta, set_state_meta
+from core.show_pages import ShowPageStore, validate_session_id
+from storage.sessions_service import read_session_display_meta
+
+# The single state_meta key holding the whole dock document.
+DOCK_STATE_KEY = "workbench.dock.v1"
+
+# Every Dock mutation funnels through the single local vibe process — multiple
+# devices/tabs are multiple clients of ONE server — so a module lock makes each
+# read-modify-write of the document atomic. Without it, two near-simultaneous
+# pins both load the same doc and the later ``_save`` silently drops the other's
+# pin. This matches the whole ``state_meta`` layer's single-process assumption;
+# it does not (and need not here) guard against multiple OS processes.
+_DOCK_MUTATION_LOCK = threading.Lock()
+
+# Built-in resident apps, in their canonical Dock order. Mirrors the frontend
+# APP_LIST ids (ui/src/apps/registry.tsx); these ids are a stable contract
+# shared across the client/server boundary — keep the two in sync.
+BUILTIN_DOCK_IDS: tuple[str, ...] = ("files", "terminal", "editor")
+
+# Namespace prefix for a pinned Show Page dock id.
+SHOW_PREFIX = "show:"
+
+# Defensive cap on the resident-tile count so one corrupt/hostile write can't
+# balloon the order list. Far above any real Dock (built-ins + pinned pages).
+MAX_DOCK_ITEMS = 200
+
+
+class DockError(ValueError):
+ """A bad Dock request (unknown page to pin, invalid order).
+
+ ``code`` maps to an HTTP status at the route layer: ``*_not_found`` → 404,
+ everything else → 400.
+ """
+
+ def __init__(self, message: str, *, code: str) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+def _show_id(session_id: str) -> str:
+ return f"{SHOW_PREFIX}{session_id}"
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _coerce_doc(raw: Any) -> tuple[list[str], list[dict[str, str]]]:
+ """Pull a well-typed ``(order, pins)`` out of whatever is stored, tolerating a
+ missing key, wrong types, or a corrupt blob (→ empty)."""
+ order: list[str] = []
+ pins: list[dict[str, str]] = []
+ if isinstance(raw, dict):
+ raw_order = raw.get("order")
+ if isinstance(raw_order, list):
+ order = [item for item in raw_order if isinstance(item, str)]
+ raw_pins = raw.get("pins")
+ if isinstance(raw_pins, list):
+ for entry in raw_pins:
+ if not isinstance(entry, dict):
+ continue
+ sid = entry.get("session_id")
+ if not isinstance(sid, str) or not sid:
+ continue
+ pins.append(
+ {
+ "session_id": sid,
+ "title_snapshot": str(entry.get("title_snapshot") or ""),
+ "pinned_at": str(entry.get("pinned_at") or ""),
+ }
+ )
+ return order, pins
+
+
+def _reconcile(order: list[str], pins: list[dict[str, str]]) -> dict[str, Any]:
+ """Canonicalize a dock doc: dedupe pins by session id; drop unknown/duplicate
+ order ids; append any missing built-ins, then any missing pins, at the end.
+
+ Pure — the same algorithm runs client-side (reconcileDock in DockContext),
+ so both ends agree on the canonical shape.
+ """
+ seen_pins: set[str] = set()
+ deduped_pins: list[dict[str, str]] = []
+ for pin in pins:
+ sid = pin["session_id"]
+ if sid in seen_pins:
+ continue
+ seen_pins.add(sid)
+ deduped_pins.append(pin)
+
+ # Clamp on read as well as on write: a corrupt or hand-edited stored doc could
+ # hold more pins than the write paths admit, so bound them here too (built-ins
+ # are always kept; excess pins beyond the cap are dropped) to keep the Dock —
+ # and GET /api/dock — from ballooning.
+ max_pins = max(0, MAX_DOCK_ITEMS - len(BUILTIN_DOCK_IDS))
+ if len(deduped_pins) > max_pins:
+ deduped_pins = deduped_pins[:max_pins]
+
+ pin_ids = [_show_id(pin["session_id"]) for pin in deduped_pins]
+ known = set(BUILTIN_DOCK_IDS) | set(pin_ids)
+
+ result: list[str] = []
+ seen: set[str] = set()
+ for item in order:
+ if item in known and item not in seen:
+ result.append(item)
+ seen.add(item)
+ for builtin in BUILTIN_DOCK_IDS:
+ if builtin not in seen:
+ result.append(builtin)
+ seen.add(builtin)
+ for pin_id in pin_ids:
+ if pin_id not in seen:
+ result.append(pin_id)
+ seen.add(pin_id)
+ return {"order": result, "pins": deduped_pins}
+
+
+def _load(db_path: Path | None) -> dict[str, Any]:
+ order, pins = _coerce_doc(get_state_meta(DOCK_STATE_KEY, db_path=db_path))
+ return _reconcile(order, pins)
+
+
+def _save(doc: dict[str, Any], db_path: Path | None) -> None:
+ set_state_meta(DOCK_STATE_KEY, doc, db_path=db_path)
+
+
+def load_dock(*, db_path: Path | None = None) -> dict[str, Any]:
+ """Return the reconciled Dock document ``{order, pins}``."""
+ return _load(db_path)
+
+
+def pin_show_page(session_id: str, *, db_path: Path | None = None) -> dict[str, Any]:
+ """Pin a session's Show Page to the Dock (idempotent).
+
+ Captures the session's current title as ``title_snapshot`` so the tile stays
+ labelled even after the session is archived. Raises ``ShowPageError`` for a
+ malformed id (→ 400) or ``DockError`` when the session has no Show Page
+ (→ 404). Never creates a page — pinning only records an existing one.
+ """
+ session_id = validate_session_id(session_id)
+ store = ShowPageStore(db_path)
+ try:
+ page = store.get(session_id)
+ finally:
+ store.close()
+ if page is None:
+ raise DockError("This session has no Show Page to pin.", code="show_page_not_found")
+
+ # Serialize the whole read-modify-write so a concurrent pin can't lost-update.
+ with _DOCK_MUTATION_LOCK:
+ doc = _load(db_path)
+ if any(pin["session_id"] == session_id for pin in doc["pins"]):
+ return doc # already pinned → idempotent no-op (keeps its place + snapshot)
+
+ # Enforce the same cap ``set_dock_order`` does, so a new pin can't push the
+ # order past MAX_DOCK_ITEMS (which would then make every reorder rejected).
+ if len(doc["order"]) >= MAX_DOCK_ITEMS:
+ raise DockError("The Dock is full — unpin an app before pinning another.", code="dock_full")
+
+ meta = read_session_display_meta([session_id], db_path=db_path)
+ title = (meta.get(session_id) or {}).get("title") or ""
+ doc["pins"].append(
+ {"session_id": session_id, "title_snapshot": title, "pinned_at": _utc_now_iso()}
+ )
+ doc["order"].append(_show_id(session_id))
+ doc = _reconcile(doc["order"], doc["pins"])
+ _save(doc, db_path)
+ return doc
+
+
+def unpin_show_page(session_id: str, *, db_path: Path | None = None) -> dict[str, Any]:
+ """Remove a pinned Show Page from the Dock (idempotent; never 404s).
+
+ Unpin is Dock-only — it leaves the Show Page itself, its visibility, and any
+ open windows untouched.
+ """
+ sid = (session_id or "").strip()
+ show_id = _show_id(sid)
+ with _DOCK_MUTATION_LOCK:
+ doc = _load(db_path)
+ pinned = any(pin["session_id"] == sid for pin in doc["pins"])
+ if not pinned and show_id not in doc["order"]:
+ return doc # nothing to remove → idempotent no-op
+ pins = [pin for pin in doc["pins"] if pin["session_id"] != sid]
+ order = [item for item in doc["order"] if item != show_id]
+ doc = _reconcile(order, pins)
+ _save(doc, db_path)
+ return doc
+
+
+def set_dock_order(order: Any, *, db_path: Path | None = None) -> dict[str, Any]:
+ """Persist a new resident-tile order.
+
+ The order must be exactly the current known id set (built-ins + pinned
+ pages), with no duplicates and within the size cap. A stale client — one
+ that omits a pin added by another tab, say — is rejected rather than allowed
+ to clobber the newer pin. Raises ``DockError`` (``invalid_order`` → 400).
+ """
+ if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
+ raise DockError("Dock order must be a list of ids.", code="invalid_order")
+ if len(order) > MAX_DOCK_ITEMS:
+ raise DockError("Dock order is too large.", code="invalid_order")
+ if len(order) != len(set(order)):
+ raise DockError("Dock order has duplicate ids.", code="invalid_order")
+
+ with _DOCK_MUTATION_LOCK:
+ doc = _load(db_path)
+ known = set(BUILTIN_DOCK_IDS) | {_show_id(pin["session_id"]) for pin in doc["pins"]}
+ if set(order) != known:
+ raise DockError("Dock order must match the current dock items.", code="invalid_order")
+
+ doc = {"order": list(order), "pins": doc["pins"]}
+ _save(doc, db_path)
+ return doc
diff --git a/tests/test_dock_api.py b/tests/test_dock_api.py
new file mode 100644
index 000000000..d04ca40bb
--- /dev/null
+++ b/tests/test_dock_api.py
@@ -0,0 +1,292 @@
+"""Workbench Dock API: pin/unpin Show Pages, resident-tile order, auth parity.
+
+Mutations are exercised at the ``vibe.api`` layer (like the sibling Show Pages
+admin tests); the route layer is covered for the GET round-trip and, crucially,
+for auth parity — a remote request without a session is bounced to login, so a
+``/api/dock`` route can never be an unauthenticated native endpoint.
+"""
+
+import pytest
+
+from core.dock_store import BUILTIN_DOCK_IDS, DockError
+from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
+from tests.test_ui_remote_access_auth import _remote_peer, _save_config
+from vibe import api
+from vibe.ui_server import app
+
+
+def _seed_session(session_id: str, *, title: str | None = None) -> None:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="slack", scope_type="channel", native_id=f"chan_{session_id}", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_" + session_id,
+ native_session_id="",
+ title=title,
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ finally:
+ engine.dispose()
+
+
+def _make_show_page(session_id: str) -> None:
+ """Create the Show Page row (private) for a seeded session so it can be pinned."""
+ ensure_show_page_dir(session_id)
+ store = ShowPageStore()
+ try:
+ store.update_visibility(session_id, "private")
+ finally:
+ store.close()
+
+
+def _show(session_id: str) -> str:
+ return f"show:{session_id}"
+
+
+def test_dock_default_is_builtins_only(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ result = api.get_dock()
+
+ assert result["ok"] is True
+ assert result["dock"]["order"] == list(BUILTIN_DOCK_IDS)
+ assert result["dock"]["pins"] == []
+
+
+def test_pin_appends_and_captures_title(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_pin", title="Sales Dashboard")
+ _make_show_page("ses_pin")
+
+ dock = api.pin_dock_show_page("ses_pin")["dock"]
+
+ assert dock["order"] == [*BUILTIN_DOCK_IDS, _show("ses_pin")]
+ assert len(dock["pins"]) == 1
+ pin = dock["pins"][0]
+ assert pin["session_id"] == "ses_pin"
+ assert pin["title_snapshot"] == "Sales Dashboard"
+ assert pin["pinned_at"]
+
+ # Survives a reload (persisted to state_meta).
+ assert api.get_dock()["dock"] == dock
+
+
+def test_pin_without_session_title_stores_empty_snapshot(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_plain") # IM-dispatch sessions persist title=None
+ _make_show_page("ses_plain")
+
+ dock = api.pin_dock_show_page("ses_plain")["dock"]
+
+ assert dock["pins"][0]["title_snapshot"] == ""
+
+
+def test_pin_is_idempotent(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_dup", title="Once")
+ _make_show_page("ses_dup")
+
+ first = api.pin_dock_show_page("ses_dup")["dock"]
+ second = api.pin_dock_show_page("ses_dup")["dock"]
+
+ assert first == second
+ assert second["order"].count(_show("ses_dup")) == 1
+ assert len(second["pins"]) == 1
+
+
+def test_pin_multiple_sessions_all_survive(monkeypatch, tmp_path):
+ # Pinning distinct sessions accumulates — a later pin must never drop an
+ # earlier one (the read-modify-write is serialized under a lock so concurrent
+ # pins can't lost-update).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ for sid in ("ses_a", "ses_b", "ses_c"):
+ _seed_session(sid, title=sid.upper())
+ _make_show_page(sid)
+ api.pin_dock_show_page(sid)
+
+ dock = api.get_dock()["dock"]
+ assert dock["order"] == [*BUILTIN_DOCK_IDS, _show("ses_a"), _show("ses_b"), _show("ses_c")]
+ assert [pin["session_id"] for pin in dock["pins"]] == ["ses_a", "ses_b", "ses_c"]
+
+
+def test_pin_rejects_when_dock_is_full(monkeypatch, tmp_path):
+ # The cap that set_dock_order enforces must also gate new pins, else the order
+ # can grow past it and every later reorder is rejected.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ monkeypatch.setattr("core.dock_store.MAX_DOCK_ITEMS", 4) # 3 built-ins + room for one pin
+ for sid in ("ses_full1", "ses_full2"):
+ _seed_session(sid)
+ _make_show_page(sid)
+
+ api.pin_dock_show_page("ses_full1") # fills the Dock (3 built-ins + 1 pin = 4)
+ with pytest.raises(DockError) as excinfo:
+ api.pin_dock_show_page("ses_full2")
+ assert excinfo.value.code == "dock_full"
+
+
+def test_load_dock_clamps_oversized_corrupt_pins(monkeypatch, tmp_path):
+ # A corrupt / hand-edited stored doc with more pins than the cap must be
+ # bounded on read, not rendered as thousands of tiles.
+ from core.chat_discovery import set_state_meta
+ from core.dock_store import DOCK_STATE_KEY
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ monkeypatch.setattr("core.dock_store.MAX_DOCK_ITEMS", 4) # 3 built-ins + room for one pin
+ set_state_meta(
+ DOCK_STATE_KEY,
+ {"order": [], "pins": [{"session_id": f"ses_{i}", "title_snapshot": "", "pinned_at": ""} for i in range(10)]},
+ )
+
+ dock = api.get_dock()["dock"]
+ assert len(dock["pins"]) == 1 # clamped to MAX_DOCK_ITEMS - built-ins
+ assert len(dock["order"]) == 4 # 3 built-ins + 1 pin
+
+
+def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_nopage") # session exists but has no Show Page
+
+ with pytest.raises(DockError) as excinfo:
+ api.pin_dock_show_page("ses_nopage")
+ assert excinfo.value.code == "show_page_not_found"
+
+
+def test_pin_malformed_session_id_raises_show_page_error(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ with pytest.raises(ShowPageError) as excinfo:
+ api.pin_dock_show_page("bad id!")
+ assert excinfo.value.code == "invalid_session_id"
+
+
+def test_unpin_removes_and_is_idempotent(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_u", title="Bye")
+ _make_show_page("ses_u")
+ api.pin_dock_show_page("ses_u")
+
+ dock = api.unpin_dock_show_page("ses_u")["dock"]
+ assert dock["order"] == list(BUILTIN_DOCK_IDS)
+ assert dock["pins"] == []
+
+ # Unpinning again is a harmless no-op (never 404).
+ again = api.unpin_dock_show_page("ses_u")["dock"]
+ assert again == dock
+
+ # Unpinning something never pinned is also a no-op.
+ assert api.unpin_dock_show_page("ses_never")["dock"]["pins"] == []
+
+
+def test_set_order_persists_valid_permutation(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_o", title="Ordered")
+ _make_show_page("ses_o")
+ api.pin_dock_show_page("ses_o")
+
+ new_order = [_show("ses_o"), "editor", "files", "terminal"]
+ dock = api.set_dock_order(new_order)["dock"]
+
+ assert dock["order"] == new_order
+ assert api.get_dock()["dock"]["order"] == new_order
+
+
+def test_set_order_rejects_wrong_set(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ # Missing a built-in id — not set-equal to the known ids.
+ with pytest.raises(DockError) as excinfo:
+ api.set_dock_order(["files", "terminal"])
+ assert excinfo.value.code == "invalid_order"
+
+ # An unknown id that isn't a real dock item.
+ with pytest.raises(DockError) as excinfo:
+ api.set_dock_order(["files", "terminal", "editor", "show:ghost"])
+ assert excinfo.value.code == "invalid_order"
+
+
+def test_set_order_rejects_duplicates(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ with pytest.raises(DockError) as excinfo:
+ api.set_dock_order(["files", "files", "terminal", "editor"])
+ assert excinfo.value.code == "invalid_order"
+
+
+def test_set_order_rejects_non_list(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ with pytest.raises(DockError) as excinfo:
+ api.set_dock_order("files,terminal,editor")
+ assert excinfo.value.code == "invalid_order"
+
+
+def test_dock_route_round_trip_via_client(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ response = app.test_client().get("/api/dock", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["ok"] is True
+ assert body["dock"]["order"] == list(BUILTIN_DOCK_IDS)
+
+
+def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):
+ """Auth parity: the Dock routes inherit ``enforce_remote_access_cookie`` — a
+ remote request without a session is bounced to the OAuth login, never served
+ as an unauthenticated native endpoint."""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ get_resp = app.test_client().get(
+ "/api/dock",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+ assert get_resp.status_code == 302
+ assert get_resp.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+
+ # The mutating routes are gated by the same before-request hook.
+ post_resp = app.test_client().post(
+ "/api/dock/pins",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ json={"session_id": "ses_x"},
+ follow_redirects=False,
+ )
+ assert post_resp.status_code != 200
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 7d6bfbffb..ae075ac05 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -245,6 +245,65 @@ def test_private_show_page_serves_locally(monkeypatch, tmp_path):
assert b"Show Page" in response.content
+def test_public_show_page_serves_from_authed_route(monkeypatch, tmp_path):
+ # Spec amendment (§2.3, 2026-07-13): the authed /show/ surface serves public
+ # pages too, so a Show Page pinned to the Dock while public still opens.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "public")
+
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ assert b"Show Page" in response.content
+
+
+def test_public_show_page_still_requires_remote_login(monkeypatch, tmp_path):
+ # Auth parity: serving public pages here adds no anonymous exposure — the
+ # authed route still bounces a remote request without a session to login
+ # (anonymous access stays on /p/<share_id> only).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "public")
+
+ response = app.test_client().get(
+ "/show/ses123/",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+
+
+def test_offline_show_page_not_served_by_authed_route(monkeypatch, tmp_path):
+ # The amendment serves private + public only; offline still returns the
+ # explanatory offline page (never the live surface).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "offline")
+
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+
+ assert b"This Show Page is offline" in response.content
+ assert b"window.showPage" not in response.content # the live app.js is never served
+
+
+def test_public_show_page_no_slash_redirects_to_canonical(monkeypatch, tmp_path):
+ # The sibling no-trailing-slash canonical redirect must accept public pages
+ # too now that /show/ serves them (amendment §2.3), else the slash-less URL
+ # 404s while the canonical one works.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "public")
+
+ response = app.test_client().get("/show/ses123", base_url="http://127.0.0.1:5123", follow_redirects=False)
+
+ assert response.status_code == 302
+ assert response.headers["Location"].endswith("/show/ses123/")
+
+
def test_private_show_page_uses_runtime_when_available(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -3018,6 +3077,35 @@ def test_private_show_page_hmr_websocket_accepts_setup_host_local_peer(monkeypat
finally:
set_show_runtime_manager_for_tests(None)
+
+def test_public_show_page_hmr_websocket_accepts_local_peer(monkeypatch, tmp_path):
+ # Amendment §2.3: the HMR socket serves public pages too, so a public page's
+ # /show/ HMR socket gets PAST the visibility gate (then fails at the fake
+ # runtime proxy with 1011 — not the 1008 visibility rejection an offline page
+ # would get), keeping live HMR for a page pinned while public.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.ui.setup_host = "192.168.2.3"
+ config.save()
+ _mock_interface(monkeypatch, "192.168.2.3", 24)
+ _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager()
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ with app.test_client().websocket_connect(
+ "/show/ses123/__vite_hmr",
+ headers={
+ "host": "192.168.2.3:5123",
+ "x-vibe-test-remote-addr": "192.168.2.44",
+ },
+ subprotocols=["vite-hmr"],
+ ) as websocket:
+ websocket.receive_text()
+ except Exception as exc:
+ assert getattr(exc, "code", None) == 1011 # accepted past the visibility gate; proxy then fails
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
assert manager.websocket_paths == ["/show/ses123/__vite_hmr"]
@@ -3424,8 +3512,10 @@ def test_public_and_private_paths_are_canonical_by_visibility(monkeypatch, tmp_p
_save_config(tmp_path)
share_id = _create_show_page("ses123", "public")
- private_response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
- assert private_response.status_code == 404
+ # Amendment (§2.3, 2026-07-13): the authed /show/ surface now serves public
+ # pages too (a page pinned while public must open), so this is 200, not 404.
+ authed_response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ assert authed_response.status_code == 200
store = ShowPageStore()
try:
@@ -3433,6 +3523,8 @@ def test_public_and_private_paths_are_canonical_by_visibility(monkeypatch, tmp_p
finally:
store.close()
+ # The anonymous /p/<share_id> surface still serves ONLY public pages — a
+ # private page is never reachable there.
public_response = app.test_client().get(f"/p/{share_id}/", base_url="http://127.0.0.1:5123")
assert public_response.status_code == 404
diff --git a/ui/src/apps/ShowPageApp.tsx b/ui/src/apps/ShowPageApp.tsx
new file mode 100644
index 000000000..897321166
--- /dev/null
+++ b/ui/src/apps/ShowPageApp.tsx
@@ -0,0 +1,104 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { MonitorX, PinOff } from 'lucide-react';
+
+import { useApi } from '../context/ApiContext';
+import { useDock } from '../context/DockContext';
+import { useWindowManager } from '../context/WindowManagerContext';
+import { showPagePrivatePath } from './showPageAvatar';
+
+// A pinned Show Page opened as a workbench app. The body always frames the
+// PRIVATE /show/<session_id>/ surface (authenticated workbench context, live
+// HMR while the agent keeps building the page) — never the public /p/<share>/
+// link, regardless of the page's visibility. Opening the app only READS: it
+// never ensures/creates a page, so a session whose page is gone or archived
+// gets a friendly placeholder, not a dead frame. The letter-avatar + accent
+// helpers live in ./showPageAvatar so the Dock/registry can use them without
+// pulling this (lazy-loaded) window body into the main bundle.
+
+export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, unknown> }> = ({ windowId, params }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ // Destructure the STABLE window-manager callbacks (useCallback-memoized) rather
+ // than the whole context value: the value object changes identity on every
+ // window focus/minimize/drag tick, and depending on it here would re-run this
+ // "read once" effect and re-hit /api/sessions on every such change (Codex).
+ const { setTitle, close } = useWindowManager();
+ const { unpin } = useDock();
+
+ const sessionId = typeof params?.sessionId === 'string' ? params.sessionId : '';
+ // 'loading' optimistically frames the page (the common case: it exists);
+ // 'missing' swaps to the placeholder once we learn the session is gone/archived.
+ const [state, setState] = useState<'loading' | 'ready' | 'missing'>(sessionId ? 'loading' : 'missing');
+
+ // Read the session once (error-suppressed — a gone session must NOT toast) to
+ // upgrade the window title to the LIVE title and to detect missing/archived.
+ useEffect(() => {
+ if (!sessionId) return;
+ let cancelled = false;
+ api
+ .getSession(sessionId, { cache: true, handleError: false })
+ .then((session) => {
+ if (cancelled) return;
+ // handleError:false resolves (does not throw) on a 404, returning the raw
+ // error body — so a response without a real session id, or an archived
+ // session, is the "missing" signal, same as a rejection.
+ if (!session || typeof session.id !== 'string' || session.status === 'archived') {
+ setState('missing');
+ return;
+ }
+ setState('ready');
+ const live = (session.title ?? '').trim();
+ if (live) setTitle(windowId, live);
+ })
+ .catch(() => {
+ if (!cancelled) setState('missing');
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [sessionId, api, setTitle, windowId]);
+
+ if (!sessionId || state === 'missing') {
+ return (
+ <div className="grid h-full w-full place-items-center bg-surface px-6 text-center">
+ <div className="flex max-w-[320px] flex-col items-center gap-3">
+ <span className="grid size-12 place-items-center rounded-2xl border border-border bg-foreground/[0.03] text-muted">
+ <MonitorX className="size-6" />
+ </span>
+ <div className="space-y-1">
+ <div className="text-[14px] font-semibold text-foreground">{t('apps.showPage.missingTitle')}</div>
+ <p className="text-[12.5px] leading-relaxed text-muted">{t('apps.showPage.missingBody')}</p>
+ </div>
+ {sessionId && (
+ <button
+ type="button"
+ onClick={() => {
+ void unpin(sessionId);
+ close(windowId);
+ }}
+ className="mt-1 inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-[12.5px] font-medium text-foreground transition hover:bg-foreground/[0.05]"
+ >
+ <PinOff className="size-3.5" />
+ {t('apps.showPage.unpin')}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // Sandbox is copied verbatim from the ChatPage show-page iframe: the workbench
+ // Show Page frame is intentionally same-origin-trusted (the page authenticates
+ // with the workbench cookie and runs its own same-origin fetches / WebSocket);
+ // per the standing product decision we do NOT harden it here.
+ return (
+ <iframe
+ title={t('chat.showPage.title')}
+ src={showPagePrivatePath(sessionId)}
+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
+ allow="clipboard-write"
+ className="h-full w-full border-0 bg-background"
+ />
+ );
+};
diff --git a/ui/src/apps/registry.tsx b/ui/src/apps/registry.tsx
index f980077e0..e68cc1bbf 100644
--- a/ui/src/apps/registry.tsx
+++ b/ui/src/apps/registry.tsx
@@ -1,15 +1,17 @@
import { Suspense, lazy } from 'react';
-import { CodeXml, Eye, Folder, SquareTerminal } from 'lucide-react';
+import { CodeXml, Eye, Folder, MonitorPlay, SquareTerminal } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { LucideIcon } from 'lucide-react';
+import { showPagePrivatePath } from './showPageAvatar';
+
// 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' | 'preview';
+export type AppId = 'files' | 'terminal' | 'editor' | 'preview' | 'showpage';
export interface AppDefinition {
id: AppId;
@@ -27,6 +29,12 @@ export interface AppDefinition {
* this and follows the workbench theme.
*/
lockTheme?: 'dark';
+ /**
+ * When set, the window title bar shows an "open in new tab" button that opens this URL — the app
+ * has a standalone browser surface (a Show Page's own `/show/<id>/`). Returns undefined when the
+ * params can't resolve one. Only `showpage` defines this in v1.
+ */
+ externalHref?: (params?: Record<string, unknown>) => string | undefined;
}
const Loading: React.FC = () => {
@@ -46,6 +54,7 @@ const EditorBody = lazy(() =>
const PreviewBody = lazy(() =>
import('../components/workbench/AppsPreviewPage').then((m) => ({ default: m.AppsPreviewPage })),
);
+const ShowPageBody = lazy(() => import('./ShowPageApp').then((m) => ({ default: m.ShowPageApp })));
export const APP_REGISTRY: Record<AppId, AppDefinition> = {
files: {
@@ -105,7 +114,28 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {
</Suspense>
),
},
+ // A pinned session Show Page opened as an app. Like `preview` it is NOT in APP_LIST — it has no
+ // permanent launcher tile; a Dock tile appears only while the page is pinned (see DockContext /
+ // Dock.tsx), and the window is param-driven by { sessionId, title }. The window body always frames
+ // the private /show/<id>/ surface, and the title bar offers an open-in-new-tab to the same url.
+ showpage: {
+ id: 'showpage',
+ titleKey: 'apps.showPage.label',
+ icon: MonitorPlay,
+ accent: '--mint',
+ defaultSize: { width: 1040, height: 720 },
+ Component: ({ windowId, params }) => (
+ <Suspense fallback={<Loading />}>
+ <ShowPageBody windowId={windowId} params={params} />
+ </Suspense>
+ ),
+ externalHref: (params) => {
+ const sessionId = params?.sessionId;
+ return typeof sessionId === 'string' && sessionId ? showPagePrivatePath(sessionId) : undefined;
+ },
+ },
};
-// Dock launcher tiles — the resident apps. `preview` is intentionally excluded (opened on demand).
+// Dock launcher tiles — the resident apps. `preview` and `showpage` are intentionally excluded
+// (opened on demand / while pinned).
export const APP_LIST: AppDefinition[] = [APP_REGISTRY.files, APP_REGISTRY.terminal, APP_REGISTRY.editor];
diff --git a/ui/src/apps/showPageAvatar.test.ts b/ui/src/apps/showPageAvatar.test.ts
new file mode 100644
index 000000000..78ca87876
--- /dev/null
+++ b/ui/src/apps/showPageAvatar.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+
+import { SHOW_PAGE_ACCENTS, accentForSession, firstGrapheme, showPageAvatar, showPagePrivatePath } from './showPageAvatar';
+
+describe('firstGrapheme', () => {
+ it('takes the first letter of an ASCII title', () => {
+ expect(firstGrapheme('Sales Dashboard')).toBe('S');
+ });
+
+ it('is grapheme-aware for CJK', () => {
+ expect(firstGrapheme('旅程报告')).toBe('旅');
+ });
+
+ it('trims leading whitespace before taking the first grapheme', () => {
+ expect(firstGrapheme(' Weekly report')).toBe('W');
+ });
+
+ it('returns an empty string for blank input', () => {
+ expect(firstGrapheme('')).toBe('');
+ expect(firstGrapheme(' ')).toBe('');
+ });
+
+ // Negative control: a multi-code-point emoji (ZWJ family / flag) must come back
+ // WHOLE — never a lone surrogate half or a single regional-indicator.
+ it('never splits a multi-code-point grapheme', () => {
+ const family = firstGrapheme('👩‍👧 family time');
+ // The whole cluster is returned, so it is longer than one UTF-16 code unit
+ // and re-extracting its own first grapheme is a fixed point.
+ expect(family.length).toBeGreaterThan(1);
+ expect(firstGrapheme(family)).toBe(family);
+
+ const flag = firstGrapheme('🇯🇵 Tokyo');
+ expect(Array.from(flag).length).toBeGreaterThanOrEqual(1);
+ expect(firstGrapheme(flag)).toBe(flag);
+ });
+});
+
+describe('accentForSession', () => {
+ it('always returns a var from the brand accent set', () => {
+ for (const id of ['ses_a', 'ses_b', 'sesz8jhr3hgyz', '', 'x', '旅', '🚀']) {
+ expect(SHOW_PAGE_ACCENTS as readonly string[]).toContain(accentForSession(id));
+ }
+ });
+
+ it('is deterministic for the same session id', () => {
+ expect(accentForSession('ses_stable')).toBe(accentForSession('ses_stable'));
+ });
+
+ it('spreads distinct ids across more than one accent', () => {
+ const seen = new Set(
+ ['ses_1', 'ses_2', 'ses_3', 'ses_4', 'ses_5', 'ses_6', 'ses_7', 'ses_8'].map(accentForSession),
+ );
+ expect(seen.size).toBeGreaterThan(1);
+ });
+});
+
+describe('showPageAvatar', () => {
+ it('uppercases the first letter and hashes the accent from the session id', () => {
+ const avatar = showPageAvatar('ses_sales', 'sales dashboard');
+ expect(avatar.letter).toBe('S');
+ expect(avatar.accentVar).toBe(accentForSession('ses_sales'));
+ });
+
+ it('falls back to the session id when the title is blank', () => {
+ expect(showPageAvatar('ses_plain', ' ').letter).toBe('S');
+ });
+});
+
+describe('showPagePrivatePath', () => {
+ it('always points at the private /show/ surface, url-encoded', () => {
+ expect(showPagePrivatePath('ses_1')).toBe('/show/ses_1/');
+ expect(showPagePrivatePath('a/b')).toBe('/show/a%2Fb/');
+ });
+});
diff --git a/ui/src/apps/showPageAvatar.ts b/ui/src/apps/showPageAvatar.ts
new file mode 100644
index 000000000..27b4f1524
--- /dev/null
+++ b/ui/src/apps/showPageAvatar.ts
@@ -0,0 +1,47 @@
+// Pure helpers for pinned Show Page apps: the letter avatar (icon-free tile) and
+// the private surface path. Split out of ShowPageApp.tsx so the Dock and the
+// registry can use them WITHOUT statically importing the (lazy-loaded) window
+// component — keeping the app body code-split like every other app body.
+
+// The brand accent set a pinned tile / window hashes into — the same CSS vars
+// the built-in apps use (registry.tsx). A letter avatar on a hashed accent keeps
+// multiple pinned pages distinguishable without an icon pipeline.
+export const SHOW_PAGE_ACCENTS = ['--mint', '--cyan', '--violet', '--gold'] as const;
+
+/** First grapheme of a label, grapheme-aware (keeps CJK, emoji, ZWJ sequences
+ * and combining marks intact). Empty string for blank input. Pure. */
+export function firstGrapheme(text: string): string {
+ const trimmed = (text ?? '').trim();
+ if (!trimmed) return '';
+ // Intl.Segmenter groups a full user-perceived character (e.g. 👩‍👧, é, 🇯🇵);
+ // fall back to code-point iteration, which still never splits a surrogate pair.
+ if (typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function') {
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
+ const first = segmenter.segment(trimmed)[Symbol.iterator]().next();
+ if (!first.done) return first.value.segment;
+ }
+ return Array.from(trimmed)[0] ?? '';
+}
+
+/** Deterministically map a session id to one of the brand accent vars. Pure. */
+export function accentForSession(sessionId: string): string {
+ let hash = 0;
+ for (let i = 0; i < sessionId.length; i += 1) {
+ // FNV-ish rolling hash kept in an unsigned 32-bit range so it is stable
+ // across runs/devices (the accent must not flicker between reloads).
+ hash = (hash * 31 + sessionId.charCodeAt(i)) >>> 0;
+ }
+ return SHOW_PAGE_ACCENTS[hash % SHOW_PAGE_ACCENTS.length];
+}
+
+/** The letter + accent var for a pinned Show Page's avatar tile. Pure. */
+export function showPageAvatar(sessionId: string, title: string): { letter: string; accentVar: string } {
+ const source = title.trim() || sessionId;
+ return { letter: firstGrapheme(source).toUpperCase(), accentVar: accentForSession(sessionId) };
+}
+
+/** The private same-origin route a Show Page is always framed / opened at. Never
+ * the public /p/<share>/ link — the workbench app uses the authed surface. */
+export function showPagePrivatePath(sessionId: string): string {
+ return `/show/${encodeURIComponent(sessionId)}/`;
+}
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index c1b7a3873..bf8c31566 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -15,6 +15,7 @@ import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
import { AppsLauncher } from './AppsLauncher';
import { ErrorBoundary } from './ui/error-boundary';
import { WindowManagerProvider } from '../context/WindowManagerContext';
+import { DockProvider } from '../context/DockContext';
import { WindowLayer } from './apps/WindowLayer';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
@@ -374,6 +375,7 @@ export const AppShell: React.FC = () => {
// pans the locked page to lift the focused composer above the keyboard.
// Desktop: normal document flow.
<WindowManagerProvider>
+ <DockProvider>
<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">
{/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < window
layer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.
@@ -597,6 +599,7 @@ export const AppShell: React.FC = () => {
the sidebar launcher. */}
<WindowLayer />
</div>
+ </DockProvider>
</WindowManagerProvider>
);
};
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index 0d63ca254..24ff3d552 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { Minus, Plus, X, type LucideIcon } from 'lucide-react';
+import { ExternalLink, Minus, Plus, X, type LucideIcon } from 'lucide-react';
import { APP_REGISTRY } from '../../apps/registry';
import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';
@@ -106,6 +106,9 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
const Body = def.Component;
const Icon = def.icon;
const focused = wm.focusedId === win.id;
+ // A standalone-surface app (v1: showpage) exposes an external URL for its own
+ // browser tab; the title bar then shows an open-in-new-tab button.
+ const externalHref = def.externalHref?.(win.params);
const style: React.CSSProperties = win.maximized
? { left: 0, top: 0, width: layerWidth, height: layerHeight, zIndex: win.z }
@@ -225,8 +228,25 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
<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" />
+ {/* Right cluster balances the traffic lights so the title stays centered; a
+ standalone-surface app also gets an open-in-new-tab button here. */}
+ <div className="flex w-[52px] shrink-0 items-center justify-end">
+ {externalHref && (
+ <a
+ href={externalHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={t('apps.window.openInNewTab')}
+ aria-label={t('apps.window.openInNewTab')}
+ // Stop the titlebar drag/focus gesture from starting on this click.
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={(e) => e.stopPropagation()}
+ className="grid size-6 place-items-center rounded-md text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"
+ >
+ <ExternalLink className="size-3.5" />
+ </a>
+ )}
+ </div>
</div>
<div className="min-h-0 flex-1 overflow-hidden">
diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsx
index 71daf339a..7820bf2e6 100644
--- a/ui/src/components/apps/Dock.tsx
+++ b/ui/src/components/apps/Dock.tsx
@@ -1,159 +1,220 @@
-import { useEffect, useState } from 'react';
-import { Copy, Plus, SquarePlus } from 'lucide-react';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Reorder } from 'framer-motion';
+import { Copy, ExternalLink, PinOff, Plus, SquarePlus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { APP_LIST, APP_REGISTRY, type AppId } from '../../apps/registry';
+import { APP_REGISTRY, type AppDefinition, type AppId } from '../../apps/registry';
+import { showPageAvatar, showPagePrivatePath } from '../../apps/showPageAvatar';
+import { dockIdToSession, useDock } from '../../context/DockContext';
import { useWindowManager } from '../../context/WindowManagerContext';
+import { ContextMenu, ContextMenuItem } from '../ui/context-menu';
+
+// A resident Dock tile resolved from a persisted Dock id: either a built-in app
+// (files/terminal/editor) or a pinned Show Page (`show:<session_id>`).
+type ResidentItem =
+ | { kind: 'builtin'; id: string; def: AppDefinition }
+ | { kind: 'showpage'; id: string; sessionId: string; title: string };
// The unified Dock panel: app launcher + running indicators + minimized windows.
-// Headless of how it's revealed — the AppsLauncher trigger floats it above the bottom-left
-// Apps button (hover = preview, click = pin). A running app's tile reveals a + (and right-click
-// menu) to open another window — windows are multi-instance, so this is the explicit path to a
-// second Files/Terminal/Editor. Each app tile carries its name (macOS-style label) and each
-// minimized window shows its title so the user can tell several open windows apart.
+// Built-in apps and pinned Show Pages share one reorderable row (server-persisted
+// order); a running app's tile reveals a + (and a right-click menu) to open
+// another window. Pinned Show Pages add Open in New Tab / Unpin from Dock; the
+// minimized-window strip trails the row and is not reorderable.
export const Dock: React.FC = () => {
const { t } = useTranslation();
const wm = useWindowManager();
+ const { order, pins, unpin, setOrder } = useDock();
const { windows, focusedId } = wm;
- const focusedApp = windows.find((w) => w.id === focusedId)?.appId;
const minimized = windows.filter((w) => w.minimized);
- const [menuApp, setMenuApp] = useState<AppId | null>(null);
-
- // The per-tile context menu is a transient popover — Esc dismisses it (the backdrop handles
- // click-outside). Without this it lingered on screen after the user moved on (Codex).
- useEffect(() => {
- if (!menuApp) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') setMenuApp(null);
+
+ // Cursor-positioned right-click menu, on the shared ContextMenu primitive.
+ const [menu, setMenu] = useState<{ x: number; y: number; item: ResidentItem } | null>(null);
+
+ const pinBySession = useMemo(() => new Map(pins.map((pin) => [pin.session_id, pin])), [pins]);
+
+ const resolveItem = useMemo(() => {
+ return (id: string): ResidentItem | null => {
+ const sessionId = dockIdToSession(id);
+ if (sessionId !== null) {
+ const title = pinBySession.get(sessionId)?.title_snapshot?.trim() || sessionId;
+ return { kind: 'showpage', id, sessionId, title };
+ }
+ const def = APP_REGISTRY[id as AppId];
+ return def ? { kind: 'builtin', id, def } : null;
};
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [menuApp]);
-
- // Click an app: focus its front window, else un-minimize its top window, else launch one.
- const activate = (appId: AppId) => {
- setMenuApp(null); // any tile interaction dismisses a lingering context menu
- const own = windows.filter((w) => w.appId === appId);
+ }, [pinBySession]);
+
+ // Local, drag-mutable copy of the order; framer's Reorder updates it live, and
+ // it re-syncs whenever the server order changes (load / pin / unpin elsewhere).
+ const [localOrder, setLocalOrder] = useState<string[]>(order);
+ useEffect(() => setLocalOrder(order), [order]);
+ const localRef = useRef(localOrder);
+ localRef.current = localOrder;
+
+ // Persist on drop — only when the order actually changed (a plain click can
+ // fire a spurious drag-end), so an unchanged reorder makes no request.
+ const commitOrder = () => {
+ const next = localRef.current;
+ if (next.length === order.length && next.every((id, i) => id === order[i])) return;
+ void setOrder(next);
+ };
+
+ const windowsFor = (item: ResidentItem) =>
+ item.kind === 'builtin'
+ ? windows.filter((w) => w.appId === item.id)
+ : windows.filter((w) => w.appId === 'showpage' && w.params?.sessionId === item.sessionId);
+
+ const focusWindowDom = (id: string) =>
+ (document.querySelector(`[data-window-id="${id}"]`) as HTMLElement | null)?.focus?.({ preventScroll: true });
+
+ const openNew = (item: ResidentItem) => {
+ if (item.kind === 'builtin') wm.openApp(item.id as AppId);
+ else wm.openApp('showpage', { title: item.title, params: { sessionId: item.sessionId, title: item.title } });
+ setMenu(null);
+ };
+
+ // Click a tile: focus its front window, else un-minimize its top window, else
+ // launch one — matched per Show Page by session id (multi-window like built-ins).
+ const activate = (item: ResidentItem) => {
+ setMenu(null);
+ const own = windowsFor(item);
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);
- (document.querySelector(`[data-window-id="${top.id}"]`) as HTMLElement | null)?.focus?.({ preventScroll: true });
+ focusWindowDom(top.id);
} else if (own.length > 0) {
wm.restore(own.reduce((a, b) => (b.z > a.z ? b : a)).id);
} else {
- wm.openApp(appId);
+ openNew(item);
}
};
- const openNew = (appId: AppId) => {
- wm.openApp(appId);
- setMenuApp(null);
- };
- const showAll = (appId: AppId) => {
- const own = windows.filter((w) => w.appId === appId);
+ const showAll = (item: ResidentItem) => {
+ const own = windowsFor(item);
own.filter((w) => w.minimized).forEach((w) => wm.restore(w.id));
const visible = own.filter((w) => !w.minimized);
if (visible.length > 0) wm.focus(visible.reduce((a, b) => (b.z > a.z ? b : a)).id);
- setMenuApp(null);
+ setMenu(null);
+ };
+
+ const openExternal = (sessionId: string) => {
+ window.open(showPagePrivatePath(sessionId), '_blank', 'noopener,noreferrer');
+ setMenu(null);
+ };
+
+ const unpinItem = (sessionId: string) => {
+ void unpin(sessionId);
+ setMenu(null);
+ };
+
+ const focusedApp = windows.find((w) => w.id === focusedId);
+ const isActive = (item: ResidentItem) =>
+ !!focusedApp &&
+ (item.kind === 'builtin'
+ ? focusedApp.appId === item.id
+ : focusedApp.appId === 'showpage' && focusedApp.params?.sessionId === item.sessionId);
+
+ const menuItemCount = (item: ResidentItem) => {
+ const running = windowsFor(item).length > 0;
+ return 1 + (running ? 1 : 0) + (item.kind === 'showpage' ? 2 : 0);
};
return (
<div className="relative">
- {menuApp && <div className="fixed inset-0 z-0" onClick={() => setMenuApp(null)} aria-hidden />}
- <div className="relative flex items-end 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 (
- <div key={app.id} className="group/tile relative flex w-[60px] flex-col items-center gap-1">
- {/* Icon wrapper is the positioning context for the + affordance so it pins to the
- icon's corner (not the wider labelled tile). */}
- <div className="relative">
- <button
- type="button"
- title={t(app.titleKey)}
- aria-label={t(app.titleKey)}
- onClick={(e) => (e.metaKey || e.ctrlKey || e.altKey ? openNew(app.id) : activate(app.id))}
- onContextMenu={(e) => {
- e.preventDefault();
- setMenuApp((cur) => (cur === app.id ? null : app.id));
- }}
- className={clsx(
- 'grid size-10 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-5" style={{ color: `var(${app.accent})` }} />
- </button>
-
- {/* + reveals on hover and directly opens another window (the one-click affordance the
- label advertises). The New Window / Show All Windows menu is the tile's right-click. */}
- <button
- type="button"
- title={t('apps.dock.newWindow')}
- aria-label={t('apps.dock.newWindow')}
- onClick={(e) => {
- e.stopPropagation();
- openNew(app.id);
- }}
- className={clsx(
- 'absolute -right-1 -top-1 grid size-4 place-items-center rounded-full border border-border-strong bg-surface-2 text-muted shadow transition hover:text-foreground',
- menuApp === app.id ? 'opacity-100' : 'opacity-0 group-hover/tile:opacity-100',
- )}
- >
- <Plus className="size-2.5" strokeWidth={3} />
- </button>
- </div>
-
- {/* App name (macOS-style labelled tile) + running indicator. The name also surfaces on
- hover via the icon button's title, in case it's truncated. */}
- <span className="max-w-full truncate text-[10px] leading-tight text-muted">{t(app.titleKey)}</span>
- <span className="size-1 rounded-full" style={{ backgroundColor: running ? `var(${app.accent})` : 'transparent' }} />
-
- {menuApp === app.id && (
- <div
- role="menu"
- // Anchor to the tile's LEFT edge (opens rightward), not centered: the Dock sits at
- // the bottom-left, so a centered menu's left half spilled past the viewport edge and
- // got clipped (Codex). Left-anchored keeps the whole menu on-screen.
- className="absolute bottom-full left-0 z-10 mb-2 w-44 rounded-xl border border-border bg-surface-3 p-1.5 shadow-[0_10px_28px_-8px_rgba(0,0,0,0.7)]"
- >
+ {/* Bound the panel to the viewport and scroll horizontally: with many pinned
+ apps the resident row would otherwise run off-screen (the popover sits at
+ the bottom-left), leaving later tiles unreachable for open/reorder/unpin. */}
+ <div className="relative flex max-w-[min(88vw,880px)] items-end gap-2 overflow-x-auto overscroll-x-contain 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">
+ <Reorder.Group axis="x" values={localOrder} onReorder={setLocalOrder} as="div" className="flex items-end gap-2">
+ {localOrder.map((id) => {
+ const item = resolveItem(id);
+ if (!item) return null;
+ const running = windowsFor(item).length > 0;
+ const active = isActive(item);
+ const label = item.kind === 'builtin' ? t(item.def.titleKey) : item.title;
+ const avatar = item.kind === 'showpage' ? showPageAvatar(item.sessionId, item.title) : null;
+ const BuiltinIcon = item.kind === 'builtin' ? item.def.icon : null;
+ const dotColor = item.kind === 'builtin' ? `var(${item.def.accent})` : `var(${avatar!.accentVar})`;
+
+ return (
+ <Reorder.Item
+ key={id}
+ value={id}
+ as="div"
+ onDragEnd={commitOrder}
+ className="group/tile relative flex w-[60px] cursor-grab flex-col items-center gap-1 active:cursor-grabbing"
+ >
+ {/* Icon wrapper positions the + affordance to the icon's corner. */}
+ <div className="relative">
<button
type="button"
- role="menuitem"
- onClick={() => openNew(app.id)}
- className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[12.5px] font-medium text-foreground transition hover:bg-cyan-soft"
+ title={label}
+ aria-label={label}
+ onClick={(e) => (e.metaKey || e.ctrlKey || e.altKey ? openNew(item) : activate(item))}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setMenu({ x: e.clientX, y: e.clientY, item });
+ }}
+ className={clsx(
+ 'grid size-10 place-items-center rounded-xl border transition',
+ item.kind === 'builtin' &&
+ (active ? 'border-2 bg-foreground/[0.07]' : 'border-border bg-foreground/[0.03] hover:bg-foreground/[0.07]'),
+ )}
+ style={
+ item.kind === 'builtin'
+ ? active
+ ? { borderColor: `var(${item.def.accent})` }
+ : undefined
+ : {
+ // Pinned Show Page: a letter avatar on a hashed accent tint (no icon
+ // pipeline). Border brightens to the full accent when focused.
+ color: `var(${avatar!.accentVar})`,
+ backgroundColor: `color-mix(in srgb, var(${avatar!.accentVar}) 16%, transparent)`,
+ borderWidth: active ? 2 : 1,
+ borderColor: active
+ ? `var(${avatar!.accentVar})`
+ : `color-mix(in srgb, var(${avatar!.accentVar}) 34%, transparent)`,
+ }
+ }
>
- <SquarePlus className="size-[15px] text-cyan" />
- {t('apps.dock.newWindow')}
+ {item.kind === 'builtin' && BuiltinIcon ? (
+ <BuiltinIcon className="size-5" style={{ color: `var(${item.def.accent})` }} />
+ ) : (
+ <span className="text-[15px] font-bold leading-none">{avatar!.letter}</span>
+ )}
</button>
+
+ {/* + reveals on hover and opens another window directly. */}
<button
type="button"
- role="menuitem"
- onClick={() => showAll(app.id)}
- disabled={!running}
- className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[12.5px] text-muted transition hover:bg-foreground/[0.05] disabled:opacity-40 disabled:hover:bg-transparent"
+ title={t('apps.dock.newWindow')}
+ aria-label={t('apps.dock.newWindow')}
+ onClick={(e) => {
+ e.stopPropagation();
+ openNew(item);
+ }}
+ // Don't let a press on + start a tile drag.
+ onPointerDown={(e) => e.stopPropagation()}
+ className="absolute -right-1 -top-1 grid size-4 place-items-center rounded-full border border-border-strong bg-surface-2 text-muted opacity-0 shadow transition hover:text-foreground group-hover/tile:opacity-100"
>
- <Copy className="size-[15px]" />
- {t('apps.dock.showAllWindows')}
+ <Plus className="size-2.5" strokeWidth={3} />
</button>
</div>
- )}
- </div>
- );
- })}
+
+ <span className="max-w-full truncate text-[10px] leading-tight text-muted">{label}</span>
+ <span className="size-1 rounded-full" style={{ backgroundColor: running ? dotColor : 'transparent' }} />
+ </Reorder.Item>
+ );
+ })}
+ </Reorder.Group>
{minimized.length > 0 && <div className="mx-1 h-11 w-px shrink-0 self-center bg-border-strong" />}
{/* Minimized windows render as a small window-style thumbnail (a mini titlebar with traffic
lights + the app icon) with the title stacked BELOW it — matching the app tiles' layout so
- the whole row stays vertically consistent, and so a title never stretches the tile wide.
- (A true live thumbnail isn't practical — editor/terminal render to canvas — so the icon +
- title carry the identification.) */}
+ the whole row stays vertically consistent. Not reorderable. */}
{minimized.map((w) => {
const def = APP_REGISTRY[w.appId];
const Icon = def.icon;
@@ -183,6 +244,46 @@ export const Dock: React.FC = () => {
);
})}
</div>
+
+ {menu &&
+ (() => {
+ // Bind the target to a const so the discriminated-union narrowing
+ // survives into the item onClick closures (a mutable `menu.item` would
+ // widen back to ResidentItem inside them).
+ const item = menu.item;
+ const showpage = item.kind === 'showpage' ? item : null;
+ return (
+ <ContextMenu x={menu.x} y={menu.y} onClose={() => setMenu(null)} width={196} itemCount={menuItemCount(item)}>
+ <ContextMenuItem
+ icon={<SquarePlus className="size-[15px] text-cyan" />}
+ label={t('apps.dock.newWindow')}
+ onClick={() => openNew(item)}
+ />
+ {windowsFor(item).length > 0 && (
+ <ContextMenuItem
+ icon={<Copy className="size-[15px]" />}
+ label={t('apps.dock.showAllWindows')}
+ onClick={() => showAll(item)}
+ />
+ )}
+ {showpage && (
+ <>
+ <ContextMenuItem
+ icon={<ExternalLink className="size-[15px]" />}
+ label={t('apps.dock.openInNewTab')}
+ onClick={() => openExternal(showpage.sessionId)}
+ />
+ <ContextMenuItem
+ icon={<PinOff className="size-[15px]" />}
+ label={t('apps.dock.unpin')}
+ danger
+ onClick={() => unpinItem(showpage.sessionId)}
+ />
+ </>
+ )}
+ </ContextMenu>
+ );
+ })()}
</div>
);
};
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index 4287ccd2e..5e54f8a25 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -1,12 +1,14 @@
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, Copy, Loader2, Plus, Share2 } from 'lucide-react';
+import { Check, Copy, LayoutGrid, Loader2, Plus, Share2 } from 'lucide-react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Select } from '../ui/select';
+import { Switch } from '../ui/switch';
import { useApi } from '../../context/ApiContext';
+import { useDock } from '../../context/DockContext';
import { copyTextToClipboard } from '../../lib/utils';
import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';
import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';
@@ -16,6 +18,9 @@ type ShowPagePayload = ShowPageLinkInfo & {
url_available: boolean;
url_guidance: string | null;
offline: boolean;
+ // The live session title (joined server-side by ensureShowPage); labels the
+ // pinned-app confirmation. Null for untitled IM-dispatch sessions.
+ title?: string | null;
};
// Share affordance shown only while the Show Page is open (the in-chat view).
@@ -33,6 +38,7 @@ export const ShowPageShareControl: React.FC<{
}> = ({ sessionId, onPayloadChange, onOpenChange }) => {
const { t } = useTranslation();
const api = useApi();
+ const dock = useDock();
const [open, setOpen] = useState(false);
const [payload, setPayload] = useState<ShowPagePayload | null>(null);
const [loading, setLoading] = useState(false);
@@ -259,6 +265,41 @@ export const ShowPageShareControl: React.FC<{
)}
</>
)}
+
+ {/* Pin to Dock — records the session's Show Page as a Dock app. Deliberately
+ OUTSIDE the visibility branches: pinning is independent of public/private
+ (a private page can be pinned) and never changes visibility or deletes the
+ page. Shown whenever the page exists (the popover ensured it on open). */}
+ {payload && (
+ <div className="border-t border-border pt-3">
+ <div className="flex items-center gap-3">
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg border border-border bg-foreground/[0.03] text-cyan">
+ <LayoutGrid className="size-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">{t('chat.showPage.pinToDock')}</div>
+ <div className="text-xs text-muted">{t('chat.showPage.pinToDockCaption')}</div>
+ </div>
+ <Switch
+ checked={dock.isPinned(sessionId)}
+ onCheckedChange={(next) => {
+ void (next ? dock.pin(sessionId) : dock.unpin(sessionId));
+ }}
+ label={t('chat.showPage.pinToDock')}
+ />
+ </div>
+ {dock.isPinned(sessionId) && (
+ <div className="mt-2 flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.08] px-2.5 py-1.5 text-xs text-foreground">
+ <Check className="size-3.5 shrink-0 text-mint" />
+ <span className="truncate">
+ {t('chat.showPage.pinnedConfirm', {
+ title: (payload.title ?? '').trim() || t('chat.showPage.title'),
+ })}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
</PopoverContent>
</Popover>
);
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 4b41cb61e..7279312d2 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -3,6 +3,11 @@ import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch } from '../lib/apiFetch';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
+import type { DockDoc } from './DockContext';
+
+// The workbench Dock API response shape ({ ok, dock }); the Dock document type
+// itself lives with the DockProvider that owns reconciliation.
+export type DockResponse = { ok: boolean; dock: DockDoc };
// One backend's *global* instructions file, surfaced by the Global Prompts
// editor. ``backend`` is an agent backend id (claude / opencode / codex).
@@ -364,6 +369,15 @@ export type ApiContextType = {
rotateShowPageShare: (sessionId: string) => Promise<any>;
/** Set a custom public link suffix (public pages only); rejects on a taken/invalid id. */
setShowPageShareId: (sessionId: string, shareId: string) => Promise<any>;
+ /** The workbench Dock document (resident-tile order + pinned Show Pages). */
+ getDock: () => Promise<DockResponse>;
+ /** Pin a session's Show Page to the Dock as an app (idempotent). */
+ pinDockShowPage: (sessionId: string) => Promise<DockResponse>;
+ /** Unpin a session's Show Page from the Dock (idempotent; leaves the page). */
+ unpinDockShowPage: (sessionId: string) => Promise<DockResponse>;
+ /** Persist a new resident-tile order (silent on rejection so a stale reorder
+ * rolls back without a toast). Returns the payload; check ``ok``. */
+ setDockOrder: (order: string[]) => Promise<DockResponse>;
getBindCodes: () => Promise<any>;
createBindCode: (type: string, expiresAt?: string) => Promise<any>;
deleteBindCode: (code: string) => Promise<any>;
@@ -502,7 +516,7 @@ export type ApiContextType = {
listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string; q?: string; cache?: boolean }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
forkSession: (sessionId: string) => Promise<WorkbenchSession>;
- getSession: (sessionId: string, params?: { cache?: boolean }) => Promise<WorkbenchSession>;
+ getSession: (sessionId: string, params?: { cache?: boolean; handleError?: boolean }) => Promise<WorkbenchSession>;
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
@@ -2096,6 +2110,26 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
ensureShowPage: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/ensure`, {}),
rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
setShowPageShareId: (sessionId, shareId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/share-id`, { share_id: shareId }),
+ getDock: () => getJson('/api/dock'),
+ pinDockShowPage: (sessionId) => postJson('/api/dock/pins', { session_id: sessionId }),
+ unpinDockShowPage: (sessionId) => deleteJson(`/api/dock/pins/${encodeURIComponent(sessionId)}`),
+ setDockOrder: async (order) => {
+ // Suppress the global error toast: a concurrent-reorder rejection (the
+ // server rejects an order that no longer matches the known id set) is
+ // handled by the optimistic rollback in DockContext, not a user-facing
+ // error. The caller inspects ``ok``.
+ const { payloadJson } = await requestJson(
+ '/api/dock/order',
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ order }),
+ },
+ 'PUT /api/dock/order',
+ { handleError: false },
+ );
+ return payloadJson;
+ },
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
deleteBindCode: (code) => deleteJson(`/api/bind-codes/${encodeURIComponent(code)}`),
@@ -2261,8 +2295,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
postJson(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {}),
getSession: (sessionId, params) =>
params?.cache === false
- ? getJson(`/api/sessions/${encodeURIComponent(sessionId)}`)
- : getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ ? getJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { handleError: params?.handleError })
+ : getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`, undefined, { handleError: params?.handleError }),
getSessionBootstrap: (sessionId) =>
getJson(`/api/sessions/${encodeURIComponent(sessionId)}/bootstrap`),
updateSession: async (sessionId, payload) => {
diff --git a/ui/src/context/DockContext.test.ts b/ui/src/context/DockContext.test.ts
new file mode 100644
index 000000000..fb4fd36b4
--- /dev/null
+++ b/ui/src/context/DockContext.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest';
+
+import { dockIdToSession, reconcileDock, showDockId, type DockDoc } from './DockContext';
+
+const BUILTINS = ['files', 'terminal', 'editor'];
+
+describe('showDockId / dockIdToSession', () => {
+ it('round-trips a session id', () => {
+ expect(showDockId('ses_1')).toBe('show:ses_1');
+ expect(dockIdToSession('show:ses_1')).toBe('ses_1');
+ });
+
+ it('returns null for a non-Show dock id', () => {
+ expect(dockIdToSession('files')).toBeNull();
+ expect(dockIdToSession('editor')).toBeNull();
+ });
+});
+
+describe('reconcileDock', () => {
+ it('defaults an empty doc to the built-ins in canonical order', () => {
+ const out = reconcileDock({ order: [], pins: [] }, BUILTINS);
+ expect(out.order).toEqual(['files', 'terminal', 'editor']);
+ expect(out.pins).toEqual([]);
+ });
+
+ it('tolerates null / undefined input', () => {
+ expect(reconcileDock(null, BUILTINS).order).toEqual(BUILTINS);
+ expect(reconcileDock(undefined, BUILTINS).order).toEqual(BUILTINS);
+ });
+
+ it('appends a missing built-in at the end, preserving the stored order', () => {
+ // 'editor' is absent from the stored order → it is appended last.
+ const out = reconcileDock({ order: ['terminal', 'files'], pins: [] }, BUILTINS);
+ expect(out.order).toEqual(['terminal', 'files', 'editor']);
+ });
+
+ it('appends a pinned page that is missing from order', () => {
+ const doc: DockDoc = {
+ order: ['files', 'terminal', 'editor'],
+ pins: [{ session_id: 'ses_a', title_snapshot: 'A', pinned_at: 't' }],
+ };
+ const out = reconcileDock(doc, BUILTINS);
+ expect(out.order).toEqual(['files', 'terminal', 'editor', 'show:ses_a']);
+ });
+
+ it('keeps a valid custom order (pin interleaved with built-ins)', () => {
+ const doc: DockDoc = {
+ order: ['show:ses_a', 'editor', 'files', 'terminal'],
+ pins: [{ session_id: 'ses_a', title_snapshot: 'A', pinned_at: 't' }],
+ };
+ expect(reconcileDock(doc, BUILTINS).order).toEqual(['show:ses_a', 'editor', 'files', 'terminal']);
+ });
+
+ it('dedupes pins by session id, keeping the first', () => {
+ const doc: DockDoc = {
+ order: [],
+ pins: [
+ { session_id: 'ses_a', title_snapshot: 'first', pinned_at: 't1' },
+ { session_id: 'ses_a', title_snapshot: 'second', pinned_at: 't2' },
+ ],
+ };
+ const out = reconcileDock(doc, BUILTINS);
+ expect(out.pins).toHaveLength(1);
+ expect(out.pins[0].title_snapshot).toBe('first');
+ expect(out.order.filter((id) => id === 'show:ses_a')).toHaveLength(1);
+ });
+
+ it('drops duplicate ids in order', () => {
+ const doc: DockDoc = { order: ['files', 'files', 'terminal', 'editor'], pins: [] };
+ expect(reconcileDock(doc, BUILTINS).order).toEqual(['files', 'terminal', 'editor']);
+ });
+
+ it('ignores malformed pins without crashing', () => {
+ const doc = {
+ order: ['files', 'terminal', 'editor'],
+ // Missing / non-string session_id, and a non-string snapshot to coerce.
+ pins: [{ title_snapshot: 'x' }, { session_id: 42 }, { session_id: 'ses_ok', title_snapshot: null }],
+ } as unknown as DockDoc;
+ const out = reconcileDock(doc, BUILTINS);
+ expect(out.pins).toEqual([{ session_id: 'ses_ok', title_snapshot: '', pinned_at: '' }]);
+ });
+
+ // Negative control: an id that is neither a built-in nor a live pin must NOT
+ // survive reconciliation — a stale `show:<gone>` or a bogus id is dropped.
+ it('drops unknown ids (stale pins and bogus entries)', () => {
+ const doc: DockDoc = {
+ order: ['files', 'show:ghost', 'bogus', 'terminal', 'editor'],
+ pins: [],
+ };
+ const out = reconcileDock(doc, BUILTINS);
+ expect(out.order).not.toContain('show:ghost');
+ expect(out.order).not.toContain('bogus');
+ expect(out.order).toEqual(['files', 'terminal', 'editor']);
+ });
+
+ it('clamps oversized pins to the cap, always keeping the built-ins', () => {
+ // Far more pins than the 200 cap allows; only the first (cap - built-ins) survive.
+ const pins = Array.from({ length: 250 }, (_, i) => ({ session_id: `ses_${i}`, title_snapshot: '', pinned_at: '' }));
+ const out = reconcileDock({ order: [], pins }, BUILTINS);
+ expect(out.pins).toHaveLength(200 - BUILTINS.length); // 197
+ expect(out.order).toHaveLength(200);
+ expect(out.order.slice(0, BUILTINS.length)).toEqual(BUILTINS);
+ });
+
+ it('is idempotent', () => {
+ const doc: DockDoc = {
+ order: ['show:ses_a', 'files'],
+ pins: [{ session_id: 'ses_a', title_snapshot: 'A', pinned_at: 't' }],
+ };
+ const once = reconcileDock(doc, BUILTINS);
+ const twice = reconcileDock(once, BUILTINS);
+ expect(twice).toEqual(once);
+ });
+});
diff --git a/ui/src/context/DockContext.tsx b/ui/src/context/DockContext.tsx
new file mode 100644
index 000000000..df04fd8b3
--- /dev/null
+++ b/ui/src/context/DockContext.tsx
@@ -0,0 +1,253 @@
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+
+import { APP_LIST } from '../apps/registry';
+import { useApi } from './ApiContext';
+
+// The workbench Dock is durable, cross-device *product* state (see
+// core/dock_store.py): which apps sit in the Dock and in what order. This
+// provider fetches that document once, keeps it reconciled against the apps the
+// client actually knows, and exposes optimistic pin/unpin/reorder actions that
+// roll back if the server rejects the write.
+//
+// A Dock item id is either a built-in app id verbatim (`files` / `terminal` /
+// `editor`) or a pinned Show Page as `show:<session_id>`. The built-in id set
+// and its canonical order are a contract shared with the backend's
+// BUILTIN_DOCK_IDS — both derive from APP_LIST, so keep them in sync.
+
+export type DockPin = {
+ session_id: string;
+ title_snapshot: string;
+ pinned_at: string;
+};
+
+export type DockDoc = {
+ order: string[];
+ pins: DockPin[];
+};
+
+export const SHOW_DOCK_PREFIX = 'show:';
+
+// Defensive cap on resident tiles, mirroring the backend MAX_DOCK_ITEMS — so a
+// corrupt/oversized server (or optimistic) doc can't render unbounded tiles.
+export const MAX_DOCK_ITEMS = 200;
+
+/** The Dock id for a pinned Show Page session. */
+export function showDockId(sessionId: string): string {
+ return `${SHOW_DOCK_PREFIX}${sessionId}`;
+}
+
+/** The session id inside a `show:<id>` Dock id, or null for a non-Show item. */
+export function dockIdToSession(dockId: string): string | null {
+ return dockId.startsWith(SHOW_DOCK_PREFIX) ? dockId.slice(SHOW_DOCK_PREFIX.length) : null;
+}
+
+// The resident built-in tiles, in canonical order. Mirrors the backend
+// BUILTIN_DOCK_IDS; `preview` is intentionally absent (opened on demand, never
+// resident), exactly like `showpage`.
+const BUILTIN_DOCK_IDS: string[] = APP_LIST.map((app) => app.id);
+
+/**
+ * Canonicalize a Dock document against the known built-in ids — the same rule
+ * the server applies (core/dock_store._reconcile), so a stale or partial doc
+ * from either side converges to one shape:
+ * - dedupe pins by session id (first wins);
+ * - drop unknown / duplicate ids from `order`;
+ * - append any missing built-ins, then any missing pins, at the end.
+ * Pure: no I/O, safe to unit-test and to run on every read.
+ */
+export function reconcileDock(doc: DockDoc | null | undefined, builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {
+ const pins: DockPin[] = [];
+ const seenPins = new Set<string>();
+ for (const pin of doc?.pins ?? []) {
+ if (!pin || typeof pin.session_id !== 'string' || !pin.session_id || seenPins.has(pin.session_id)) continue;
+ seenPins.add(pin.session_id);
+ pins.push({
+ session_id: pin.session_id,
+ title_snapshot: typeof pin.title_snapshot === 'string' ? pin.title_snapshot : '',
+ pinned_at: typeof pin.pinned_at === 'string' ? pin.pinned_at : '',
+ });
+ }
+
+ // Clamp on read (mirrors the backend): built-ins are always kept; excess pins
+ // beyond the cap are dropped so a corrupt/oversized doc stays bounded.
+ const maxPins = Math.max(0, MAX_DOCK_ITEMS - builtinIds.length);
+ const clampedPins = pins.length > maxPins ? pins.slice(0, maxPins) : pins;
+
+ const pinIds = clampedPins.map((pin) => showDockId(pin.session_id));
+ const known = new Set<string>([...builtinIds, ...pinIds]);
+
+ const order: string[] = [];
+ const seen = new Set<string>();
+ for (const id of doc?.order ?? []) {
+ if (known.has(id) && !seen.has(id)) {
+ order.push(id);
+ seen.add(id);
+ }
+ }
+ for (const id of builtinIds) {
+ if (!seen.has(id)) {
+ order.push(id);
+ seen.add(id);
+ }
+ }
+ for (const id of pinIds) {
+ if (!seen.has(id)) {
+ order.push(id);
+ seen.add(id);
+ }
+ }
+ return { order, pins: clampedPins };
+}
+
+export interface DockValue {
+ /** Reconciled resident-tile order (built-in ids + `show:<id>` pins). */
+ order: string[];
+ pins: DockPin[];
+ /** Whether a session's Show Page is currently pinned. */
+ isPinned: (sessionId: string) => boolean;
+ /** The pin record for a session, or null. */
+ pinFor: (sessionId: string) => DockPin | null;
+ /** Pin a session's Show Page (optimistic; idempotent). */
+ pin: (sessionId: string) => Promise<void>;
+ /** Unpin a session's Show Page (optimistic; idempotent). */
+ unpin: (sessionId: string) => Promise<void>;
+ /** Persist a new resident-tile order (optimistic; rolls back if rejected). */
+ setOrder: (order: string[]) => Promise<void>;
+}
+
+const DockContext = createContext<DockValue | null>(null);
+
+// Builtins-only default so the Dock renders its resident tiles immediately (no
+// flicker) before the server document loads.
+const DEFAULT_DOC: DockDoc = reconcileDock({ order: [], pins: [] });
+
+export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const api = useApi();
+ const [doc, setDoc] = useState<DockDoc>(DEFAULT_DOC);
+ // Latest committed doc for the async actions' rollback (avoids stale closures).
+ const docRef = useRef(doc);
+ docRef.current = doc;
+ // Dock writes are serialized. Each mutation shows its optimistic doc at once
+ // (responsiveness), then queues the server request so requests run in action
+ // order — never overlapping. A monotonic counter marks the latest mutation and
+ // only its response is applied; because the queue runs requests sequentially,
+ // that latest response already reflects every earlier write, so the UI
+ // converges to the server state instead of dropping a superseded-but-successful
+ // pin (Codex). The same counter guards the one-time initial load, so a slow GET
+ // can't clobber a just-pinned page.
+ const mutationSeqRef = useRef(0);
+ const queueRef = useRef<Promise<unknown>>(Promise.resolve());
+
+ const apply = useCallback((next: DockDoc) => setDoc(reconcileDock(next)), []);
+
+ const runMutation = useCallback(
+ (optimistic: DockDoc, request: () => Promise<{ ok?: boolean; dock?: DockDoc } | undefined>): Promise<void> => {
+ const seq = (mutationSeqRef.current += 1);
+ apply(optimistic);
+ const task = async () => {
+ try {
+ const res = await request();
+ if (mutationSeqRef.current !== seq) return; // superseded → the newer mutation is authoritative
+ if (res?.dock && res.ok !== false) {
+ setDoc(reconcileDock(res.dock)); // success → adopt the server doc
+ return;
+ }
+ // else: server rejected (ok:false, e.g. a stale order) → fall through to re-sync
+ } catch {
+ if (mutationSeqRef.current !== seq) return; // superseded
+ // network error → fall through to re-sync
+ }
+ // The latest mutation failed. Re-sync the authoritative doc from the
+ // server rather than rolling back to a captured `prev`: an earlier
+ // superseded failure may have been baked into this optimistic state, so a
+ // `prev` rollback could re-introduce a phantom tile (Codex). Still
+ // seq-guarded so a newer mutation still wins.
+ try {
+ const fresh = await api.getDock();
+ if (mutationSeqRef.current === seq && fresh?.dock) setDoc(reconcileDock(fresh.dock));
+ } catch {
+ // Offline: best-effort; the next successful load or mutation reconciles.
+ }
+ };
+ // Chain regardless of the previous task's outcome so one failure can't stall the queue.
+ const next = queueRef.current.then(task, task);
+ queueRef.current = next;
+ return next;
+ },
+ [api, apply],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ const loadSeq = mutationSeqRef.current;
+ api
+ .getDock()
+ .then((res) => {
+ // Drop the initial snapshot if a mutation started before it resolved, so a
+ // slow GET can't clobber a just-pinned page (Codex).
+ if (cancelled || mutationSeqRef.current !== loadSeq) return;
+ if (res?.dock) setDoc(reconcileDock(res.dock));
+ })
+ // A failed load (offline / auth) leaves the builtins-only default in place.
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [api]);
+
+ const pin = useCallback(
+ (sessionId: string): Promise<void> => {
+ const prev = docRef.current;
+ if (prev.pins.some((p) => p.session_id === sessionId)) return Promise.resolve(); // already pinned
+ return runMutation(
+ {
+ order: [...prev.order, showDockId(sessionId)],
+ pins: [...prev.pins, { session_id: sessionId, title_snapshot: '', pinned_at: '' }],
+ },
+ () => api.pinDockShowPage(sessionId),
+ );
+ },
+ [api, runMutation],
+ );
+
+ const unpin = useCallback(
+ (sessionId: string): Promise<void> =>
+ runMutation(
+ {
+ order: docRef.current.order.filter((id) => id !== showDockId(sessionId)),
+ pins: docRef.current.pins.filter((p) => p.session_id !== sessionId),
+ },
+ () => api.unpinDockShowPage(sessionId),
+ ),
+ [api, runMutation],
+ );
+
+ const setOrder = useCallback(
+ (order: string[]): Promise<void> =>
+ runMutation({ order, pins: docRef.current.pins }, () => api.setDockOrder(order)),
+ [api, runMutation],
+ );
+
+ const pinnedSessions = useMemo(() => new Set(doc.pins.map((p) => p.session_id)), [doc.pins]);
+
+ const value = useMemo<DockValue>(
+ () => ({
+ order: doc.order,
+ pins: doc.pins,
+ isPinned: (sessionId: string) => pinnedSessions.has(sessionId),
+ pinFor: (sessionId: string) => doc.pins.find((p) => p.session_id === sessionId) ?? null,
+ pin,
+ unpin,
+ setOrder,
+ }),
+ [doc, pinnedSessions, pin, unpin, setOrder],
+ );
+
+ return <DockContext.Provider value={value}>{children}</DockContext.Provider>;
+};
+
+export function useDock(): DockValue {
+ const ctx = useContext(DockContext);
+ if (!ctx) throw new Error('useDock must be used within a DockProvider');
+ return ctx;
+}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 80bbda114..7a8403b16 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -705,18 +705,27 @@
"dock": {
"newInstanceHint": "⌘-click for a new window",
"newWindow": "New Window",
- "showAllWindows": "Show All Windows"
+ "showAllWindows": "Show All Windows",
+ "openInNewTab": "Open in New Tab",
+ "unpin": "Unpin from Dock"
},
"window": {
"minimize": "Minimize",
"maximize": "Maximize",
- "restore": "Restore"
+ "restore": "Restore",
+ "openInNewTab": "Open in New Tab"
},
"preview": {
"label": "Preview",
"openInEditor": "Open in Editor",
"empty": "No file to preview."
},
+ "showPage": {
+ "label": "Show Page",
+ "missingTitle": "This app isn't available",
+ "missingBody": "The Show Page for this session is missing or was archived. It may come back if the session does.",
+ "unpin": "Unpin from Dock"
+ },
"fileBrowser": {
"label": "Files",
"desc": "Browse, view, and edit files on this machine.",
@@ -2173,6 +2182,9 @@
"offlineNote": "This Show Page is offline and can't be shared right now.",
"publicUnavailable": "Connect Avibe Cloud to get a public link others can open.",
"loadError": "Couldn't load this Show Page.",
+ "pinToDock": "Pin to Dock",
+ "pinToDockCaption": "Opens as an app from the Dock",
+ "pinnedConfirm": "Pinned — “{{title}}” is in your Dock",
"addToHomeTitle": "Add to Home Screen",
"addToHomeBodySafari": "Tap here to open in a new tab, then Share → “Add to Home Screen”.",
"addToHomeBodyPwa": "Copy the link above and open it in Safari, then tap Share → “Add to Home Screen”."
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index cff74093f..042636a60 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -705,18 +705,27 @@
"dock": {
"newInstanceHint": "⌘ 点击可新建窗口",
"newWindow": "新建窗口",
- "showAllWindows": "显示所有窗口"
+ "showAllWindows": "显示所有窗口",
+ "openInNewTab": "在新标签页打开",
+ "unpin": "从 Dock 取消固定"
},
"window": {
"minimize": "最小化",
"maximize": "最大化",
- "restore": "还原"
+ "restore": "还原",
+ "openInNewTab": "在新标签页打开"
},
"preview": {
"label": "预览",
"openInEditor": "用编辑器打开",
"empty": "没有可预览的文件。"
},
+ "showPage": {
+ "label": "Show Page",
+ "missingTitle": "无法打开此应用",
+ "missingBody": "这个会话的 Show Page 已丢失或被归档,若会话恢复它可能会重新出现。",
+ "unpin": "从 Dock 取消固定"
+ },
"fileBrowser": {
"label": "文件",
"desc": "浏览、查看、编辑这台机器上的文件。",
@@ -2173,6 +2182,9 @@
"offlineNote": "这个 Show Page 已离线,暂时无法分享。",
"publicUnavailable": "连接 Avibe Cloud 后才能获得别人可打开的公开链接。",
"loadError": "无法加载这个 Show Page。",
+ "pinToDock": "固定到 Dock",
+ "pinToDockCaption": "作为应用从 Dock 打开",
+ "pinnedConfirm": "已固定 —「{{title}}」已在你的 Dock 中",
"addToHomeTitle": "添加到主屏幕",
"addToHomeBodySafari": "点此处在新页面中打开,再点「分享」 →「添加到主屏幕」。",
"addToHomeBodyPwa": "复制上方链接,在 Safari 中打开,再点分享 →「添加到主屏幕」。"
diff --git a/vibe/api.py b/vibe/api.py
index f1653887c..1e5281231 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1183,6 +1183,39 @@ def set_show_page_share_id(session_id: str, share_id: str) -> dict:
return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
+def get_dock() -> dict:
+ """The workbench Dock document — resident-tile order + pinned Show Pages."""
+ from core.dock_store import load_dock
+
+ return {"ok": True, "dock": load_dock()}
+
+
+def pin_dock_show_page(session_id: str) -> dict:
+ """Pin a session's Show Page to the Dock (idempotent).
+
+ Raises ``ShowPageError`` (malformed id → 400) or ``DockError`` (no Show Page
+ → 404), which the route layer maps to a 4xx response.
+ """
+ from core.dock_store import pin_show_page
+
+ return {"ok": True, "dock": pin_show_page(session_id)}
+
+
+def unpin_dock_show_page(session_id: str) -> dict:
+ """Unpin a Show Page from the Dock (idempotent; leaves the page untouched)."""
+ from core.dock_store import unpin_show_page
+
+ return {"ok": True, "dock": unpin_show_page(session_id)}
+
+
+def set_dock_order(order: list) -> dict:
+ """Persist a new resident-tile order. Raises ``DockError`` for an invalid
+ order (wrong id set / duplicates / too large), mapped to a 400."""
+ from core.dock_store import set_dock_order as _set_dock_order
+
+ return {"ok": True, "dock": _set_dock_order(order)}
+
+
def _vibe_agent_payload(agent, *, brief: bool = False) -> dict:
payload = agent.to_dict()
if brief:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ca31b83b4..a1eb953f7 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2379,7 +2379,10 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
store = ShowPageStore()
try:
page = store.get(session_id)
- if page is None or page.visibility != "private":
+ # Amendment (§2.3, 2026-07-13): the authed /show/ surface serves public
+ # pages too, so a public page framed in the Dock app must also get live
+ # HMR. Mirror the serve route's private+public visibility gate here.
+ if page is None or page.visibility not in {"private", "public"}:
await websocket.close(code=1008)
return
finally:
@@ -3554,6 +3557,60 @@ def show_page_set_share_id_post(session_id):
return _show_page_error_response(exc)
+def _dock_error_response(exc):
+ code = getattr(exc, "code", "invalid_dock_request")
+ # A missing Show Page (nothing to pin) is a 404; a malformed id or a bad
+ # order is a 400. Structured ``error`` so the Web UI's shared handler can
+ # localize via ``errors.<code>`` and fall back to the human message.
+ status = 404 if code in {"show_page_not_found", "session_not_found"} else 400
+ message = str(exc)
+ return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
+
+
[email protected]("/api/dock", methods=["GET"])
+def dock_get():
+ from vibe import api
+
+ return jsonify(api.get_dock())
+
+
[email protected]("/api/dock/pins", methods=["POST"])
+def dock_pin_post():
+ from core.dock_store import DockError
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ return jsonify(api.pin_dock_show_page(str(payload.get("session_id") or "")))
+ except (DockError, ShowPageError) as exc:
+ return _dock_error_response(exc)
+
+
[email protected]("/api/dock/pins/<session_id>", methods=["DELETE"])
+def dock_unpin_delete(session_id):
+ from core.dock_store import DockError
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ try:
+ return jsonify(api.unpin_dock_show_page(session_id))
+ except (DockError, ShowPageError) as exc:
+ return _dock_error_response(exc)
+
+
[email protected]("/api/dock/order", methods=["PUT"])
+def dock_order_put():
+ from core.dock_store import DockError
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ return jsonify(api.set_dock_order(payload.get("order")))
+ except DockError as exc:
+ return _dock_error_response(exc)
+
+
@app.route("/api/csrf-token", methods=["GET"])
def csrf_token_get():
token = request.cookies.get(CSRF_COOKIE_NAME) or _new_csrf_token()
@@ -8907,7 +8964,10 @@ def redirect_private_show_page_to_canonical_path(session_id):
page = store.get(session_id)
if page is None:
return _show_page_not_found_response()
- if page.visibility not in {"private", "offline"}:
+ # Amendment (§2.3, 2026-07-13): the authed /show/ surface serves public
+ # pages too, so the sibling no-trailing-slash canonical redirect must
+ # accept public as well (offline still redirects to its offline page).
+ if page.visibility not in {"private", "public", "offline"}:
return _show_page_not_found_response()
return redirect(f"/show/{quote(session_id, safe='')}/")
finally:
@@ -8934,7 +8994,15 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_not_found_response()
if page.visibility == "offline":
return _show_page_offline_response()
- if page.visibility != "private":
+ # Amendment (2026-07-13, docs/plans/dock-pinned-show-page-apps.md §2.3): the
+ # authed workbench `/show/<id>/` surface serves BOTH private and public
+ # pages, so a Show Page pinned to the Dock while public still opens (a
+ # pinned public page must not open a broken window). This is no new
+ # exposure — the route stays behind workbench auth, and a public page is
+ # already anonymously readable via `/p/<share_id>`, which remains the only
+ # anonymous surface. `offline` (handled above) and any unexpected
+ # visibility still fall through to not-found.
+ if page.visibility not in {"private", "public"}:
return _show_page_not_found_response()
if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):
return _show_page_file_not_found_response()