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): page HTML icons + window-close ergonomics (#906)

Call White749012eee1ca
diff --git a/core/show_pages.py b/core/show_pages.py
index 064f0c279..613b5fe7d 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -3,12 +3,15 @@ from __future__ import annotations
import re
import hashlib
import hmac
+import os
import secrets
+import stat as stat_module
from dataclasses import dataclass
from datetime import datetime, timezone
+from html.parser import HTMLParser
from pathlib import Path
from typing import Any
-from urllib.parse import urljoin
+from urllib.parse import unquote, urljoin, urlsplit
from sqlalchemy import insert, or_, select, update
from sqlalchemy.exc import IntegrityError
@@ -31,6 +34,30 @@ SHOW_EVENT_WRITE_TOKEN_COOKIE = "vibe_show_event_token"
SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"
SHOW_CLI_EVENT_TOKEN_HEADER = "X-Vibe-Show-Cli-Token"
SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS = 30
+# Only the head of index.html is scanned for the icon <link> (it lives in <head>,
+# at the top). Bounds the per-page read so a huge inline page can't stall
+# /api/show-pages or allocate a large string (§7.1f review).
+_ICON_INDEX_HEAD_LIMIT = 64 * 1024
+# Hard cap on a servable icon's file size. A page could point <link rel="icon"> at a
+# large in-workspace asset (a screenshot, a generated image with a whitelisted
+# extension); resolving/serving it would read the whole file into memory, and the
+# token hash runs for EVERY row of /api/show-pages. Above the cap the icon is treated
+# as "no icon" (letter avatar) so the inventory can't be made to allocate hundreds of
+# MB. An icon is displayed ~40px — 2 MiB is already very generous (§7.1f review).
+_ICON_MAX_BYTES = 2 * 1024 * 1024
+# Whitelisted image extensions -> Content-Type served by the icon endpoint. A page
+# icon MUST be one of these (§7.1f): anything else is treated as "no icon" so a page
+# can't smuggle an executable/HTML asset through the thumbnail. Shared by the
+# resolver (has-icon policy) and the serving endpoint (content-type) — one source.
+SHOW_PAGE_ICON_CONTENT_TYPES: dict[str, str] = {
+ "svg": "image/svg+xml",
+ "png": "image/png",
+ "ico": "image/x-icon",
+ "jpg": "image/jpeg",
+ "jpeg": "image/jpeg",
+ "webp": "image/webp",
+ "gif": "image/gif",
+}
_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
# A custom public share suffix lands directly in the ``/p/<share_id>/`` URL, so
# keep it to URL-safe slug characters: start and end alphanumeric, with dash and
@@ -495,6 +522,297 @@ def _page_from_row(row: Any) -> ShowPage:
)
+class _IconLinkFinder(HTMLParser):
+ """Capture the first ``<link rel="icon">`` href — and the ``<base href>`` in
+ effect before it — from an HTML document.
+
+ Tolerant, stdlib-only (html.parser, no new deps): a ``<link>`` whose ``rel``
+ token set includes ``icon`` matches (so ``icon`` and ``shortcut icon`` do,
+ ``apple-touch-icon`` does not). ``base_href`` holds the first ``<base href>``
+ seen BEFORE the icon link (a base applies only to later URLs); recording stops
+ once the icon link is found. Pure string extraction — never fetches/resolves.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.icon_href: str | None = None
+ self.base_href: str | None = None
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ if self.icon_href is not None:
+ return
+ name = tag.lower()
+ values = {attr.lower(): (value or "") for attr, value in attrs}
+ if name == "base":
+ if self.base_href is None:
+ href = values.get("href", "").strip()
+ if href:
+ self.base_href = href
+ elif name == "link" and "icon" in values.get("rel", "").lower().split():
+ href = values.get("href", "").strip()
+ if href:
+ self.icon_href = href
+
+
+def _resolve_show_page_icon_href(href: str, base_href: str | None) -> str | None:
+ """Resolve a page's icon href to a same-workspace relative path, or None.
+
+ Resolves with DOCUMENT semantics — the browser percent-decodes the href and any
+ ``<base href>``, treats backslashes as slashes, then joins them the way it
+ resolves ``<img src>`` — so ``<base href="assets/">`` + ``favicon.svg`` becomes
+ ``assets/favicon.svg`` and ``%2e%2e/x`` / ``..\\x`` are caught. Returns None
+ unless the result lands inside the page's own workspace AND names a static,
+ whitelisted image: absolute / root-relative (``/w/…``, ``/icon.svg``) / external /
+ other-scheme / malformed hrefs, parent traversal, runtime API/event paths
+ (``api/`` / ``__show/`` / ``__events``), the generic ``vite.svg`` scaffold mascot,
+ and non-whitelisted extensions all yield None (the letter avatar is preferred).
+ Pure — no I/O.
+ """
+
+ def _normalize(value: str) -> str:
+ return unquote(value).replace("\\", "/")
+
+ def _escapes_workspace(value: str) -> bool:
+ # A ref resolves INSIDE /show/<sid>/ only if it is purely RELATIVE. The
+ # browser roots a leading-"/" ref (``/w/icon.svg``, ``/icon.svg``) or a
+ # ``//host`` ref at the ORIGIN — not the workspace — and a ``..`` segment
+ # climbs out. These must reject up front: otherwise a literal ``/w/…`` would
+ # collide with the synthetic prefix below and be mis-served as if relative.
+ normalized = _normalize(value)
+ if not normalized or normalized.startswith("/"):
+ return True
+ if urlsplit(normalized).scheme: # http:, data:, javascript:, …
+ return True
+ return ".." in normalized.split("/")
+
+ # Resolve href (and any <base>) with document semantics against a synthetic
+ # same-origin workspace root, rejecting non-relative refs first. ANY malformed
+ # URL is treated as "no icon", never raised: _extract_icon_path runs while
+ # building /api/show-pages, so one bad page must fall back to the letter avatar
+ # rather than break the whole Show Pages / Dock inventory request.
+ try:
+ if _escapes_workspace(href):
+ return None
+ if base_href is not None and _escapes_workspace(base_href):
+ return None
+ doc_base = "http://show.invalid/w/"
+ base_url = urljoin(doc_base, _normalize(base_href)) if base_href else doc_base
+ resolved = urlsplit(urljoin(base_url, _normalize(href)))
+ except ValueError:
+ return None # malformed href/base → no icon (never break the inventory)
+ if resolved.scheme != "http" or resolved.netloc != "show.invalid":
+ return None # external / protocol-relative / other scheme (defense in depth)
+ prefix = "/w/"
+ if not resolved.path.startswith(prefix):
+ return None # absolute or ../ traversal escaped the workspace
+ relative = resolved.path[len(prefix) :]
+ if not relative:
+ return None
+ segments = [segment for segment in relative.split("/") if segment]
+ if segments[0].lower() in {"api", "__show", "__events"}:
+ return None # runtime API/event paths are not static icons
+ if any(segment.startswith(".") for segment in segments):
+ # Hidden / dot segments (.git/x.png, .env.svg, assets/.secret.png) are
+ # denied for icons exactly as the Show Page static server denies them
+ # (_is_show_page_dot_path); the icon endpoint must not become a bypass for
+ # that policy. (Sensitive non-image files are already blocked by the image
+ # extension whitelist below; this closes image-extension dot-files.)
+ return None
+ filename = segments[-1]
+ if filename.lower() == "vite.svg":
+ return None # generic scaffold mascot → letter avatar
+ extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
+ if extension not in SHOW_PAGE_ICON_CONTENT_TYPES:
+ return None
+ return relative
+
+
+def _read_fd_fully(fd: int, size: int) -> bytes:
+ """Read exactly ``size`` bytes from ``fd`` (handling short reads)."""
+ chunks: list[bytes] = []
+ remaining = size
+ while remaining > 0:
+ chunk = os.read(fd, remaining)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ return b"".join(chunks)
+
+
+def _read_workspace_file_safely(path: Path, limit: int, *, cap: bool = False) -> bytes | None:
+ """Race/DoS-safe read of a REGULAR workspace file, or None — the ONE chokepoint
+ for reading agent-authored workspace files (index.html, icons).
+
+ Opens ``path`` with getattr-guarded ``O_NOFOLLOW`` (a symlink swapped in after an
+ earlier check is NOT followed) and ``O_NONBLOCK`` (opening a FIFO/device returns
+ immediately instead of BLOCKING on a writer — the fstat below then refuses it,
+ so a swapped-in special file can never hang an ``/api/show-pages`` request; both
+ flags degrade to a plain open where absent, e.g. native Windows). It re-checks on
+ the DESCRIPTOR via ``fstat`` that the target is a REGULAR file, then bounded-reads.
+
+ ``cap=False`` (default): read up to ``limit`` bytes — a HEAD scan of a
+ possibly-large file (index.html, whose ``<head>`` is at the top). ``cap=True``:
+ a file LARGER than ``limit`` is refused (None) — for a file that must be read in
+ FULL within a cap (an icon: hash + serve). Returns None for missing / symlink /
+ non-regular / (capped) oversized / unreadable; never raises, never blocks.
+ """
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
+ try:
+ fd = os.open(path, flags)
+ except OSError:
+ return None
+ try:
+ info = os.fstat(fd)
+ if not stat_module.S_ISREG(info.st_mode):
+ return None # symlink target that isn't regular, FIFO/device swapped in
+ if cap and info.st_size > limit:
+ return None # oversized (e.g. a screenshot advertised as an icon)
+ return _read_fd_fully(fd, info.st_size if cap else min(info.st_size, limit))
+ except OSError:
+ return None
+ finally:
+ os.close(fd)
+
+
+def _extract_icon_path(page_dir: Path) -> str | None:
+ """The page's own favicon as a same-workspace relative path, or None.
+
+ Reads ONLY the head (bounded) of a REGULAR ``<page_dir>/index.html`` — never a
+ symlink/special file, never any other file, never the icon itself — extracts the
+ first ``<link rel="icon">`` href (with any ``<base href>``), and resolves +
+ validates it via :func:`_resolve_show_page_icon_href`. The returned path is served
+ ONLY through ``GET /api/show-pages/<sid>/icon``; callers use its presence as the
+ has-icon signal, never to compose a URL.
+ """
+ # Head scan of a REGULAR index.html through the safe-read chokepoint: an oversized
+ # inline page — or a symlink / special file an agent dropped in (or swapped in
+ # mid-check) — must not stall /api/show-pages or allocate a huge string.
+ raw = _read_workspace_file_safely(page_dir / "index.html", _ICON_INDEX_HEAD_LIMIT)
+ if raw is None:
+ return None
+ html = raw.decode("utf-8", errors="replace")
+ finder = _IconLinkFinder()
+ try:
+ finder.feed(html)
+ except Exception:
+ # Malformed markup: prefer the letter avatar over guessing.
+ return None
+ href = (finder.icon_href or "").strip()
+ if not href:
+ return None
+ return _resolve_show_page_icon_href(href, finder.base_href)
+
+
+def resolve_show_page_icon(session_id: str) -> tuple[Path, str] | None:
+ """The absolute path + Content-Type of a Show Page's own icon, or None.
+
+ The single serving chokepoint for ``GET /api/show-pages/<sid>/icon``: combines
+ :func:`_extract_icon_path` (document-semantics resolution + policy) with the
+ same-workspace realpath guard, regular-file check, and extension whitelist, so
+ the serving layer just streams the file. Returns None for any missing workspace
+ / no icon / policy rejection — the caller answers 404 and the frontend falls
+ back to the letter avatar.
+ """
+ page_dir = show_page_dir(session_id)
+ relative = _extract_icon_path(page_dir)
+ if relative is None:
+ return None
+ try:
+ candidate = (page_dir / relative).resolve()
+ root = page_dir.resolve()
+ # Realpath must stay inside the workspace (defends against an in-workspace
+ # symlink pointing out) and be a regular file of a whitelisted image type.
+ if candidate != root and root not in candidate.parents:
+ return None
+ if not candidate.is_file():
+ return None
+ if candidate.stat().st_size > _ICON_MAX_BYTES:
+ # An oversized "icon" (e.g. a screenshot) → letter avatar; never hashed
+ # or served in full, bounding /api/show-pages + endpoint memory.
+ return None
+ except (ValueError, OSError):
+ # A page-authored href can resolve to a filesystem-invalid path (embedded
+ # NUL, an overlong filename): that is "no icon" (letter avatar), never an
+ # error to surface — this helper must return None rather than raise.
+ return None
+ content_type = SHOW_PAGE_ICON_CONTENT_TYPES.get(candidate.suffix.lower().lstrip("."))
+ if content_type is None:
+ return None
+ return candidate, content_type
+
+
+def show_page_icon_version(session_id: str) -> str | None:
+ """An opaque cache token for a page's servable icon, or None when it has none.
+
+ The token is a short digest of the resolved icon file's CONTENT, so any byte
+ change — overwriting the favicon, repointing ``<link rel="icon">``, or a
+ same-size/same-mtime regeneration — changes the token, and therefore the ``?v=``
+ on the icon URL, with NO update-site enumeration anywhere in the client (the
+ freshness rides the normal payload refresh). Identical bytes yield an identical
+ token, so an unchanged icon stays a cache hit. Carried in the payload as the
+ has-icon signal; the frontend appends it verbatim as ``?v=<token>``. The icon
+ endpoint's ``?v=`` NEVER selects the file — resolution is derived only from the
+ session id + workspace — it is validated as a content assertion at read time
+ (see :func:`read_show_page_icon`).
+ """
+ resolved = resolve_show_page_icon(session_id)
+ if resolved is None:
+ return None
+ candidate, _content_type = resolved
+ # Read through the safe-read chokepoint (cap=True): bounded to the icon cap and
+ # race-safe (a swap to a symlink / huge file / FIFO after resolve is refused, not
+ # followed / buffered / blocked on) — the token path must be as hardened as the
+ # serving path since it runs for EVERY /api/show-pages + `vibe show list` row.
+ data = _read_workspace_file_safely(candidate, _ICON_MAX_BYTES, cap=True)
+ if data is None:
+ return None
+ # Hash the icon's CONTENT so the token changes for ANY byte change — including a
+ # regeneration that preserves path, size, AND mtime (`cp -p`/`rsync`-style copies,
+ # deterministic build artifacts), which an mtime+size identity would miss under
+ # `immutable` caching. Content-addressed: identical bytes → identical token (the
+ # icon is unchanged, so the ?v= URL correctly stays a cache hit); different bytes
+ # → different token → new URL → refetch. Icons are small, so hashing is cheap.
+ return _icon_content_token(data)
+
+
+def _icon_content_token(data: bytes) -> str:
+ """The opaque icon cache token for a byte string — the one algorithm shared by
+ the payload (:func:`show_page_icon_version`) and the read-time enforcement
+ (:func:`read_show_page_icon`), so they can never drift apart."""
+ return hashlib.sha256(data).hexdigest()[:16]
+
+
+def read_show_page_icon(session_id: str, expected_version: str) -> tuple[bytes, str] | None:
+ """Icon bytes + Content-Type for serving, or None — a race-safe, token-enforced
+ read for ``GET /api/show-pages/<sid>/icon?v=<token>``.
+
+ Resolution is still sid-only (:func:`resolve_show_page_icon`); ``?v=`` NEVER
+ selects the file, it is validated as a CONTENT ASSERTION here so the stable URL's
+ ``immutable`` cache is honest (a given URL maps to exactly one byte-content). The
+ read closes the resolve→read TOCTOU: the resolved candidate is opened
+ ``O_NOFOLLOW`` (a symlink swapped in after resolve fails), re-checked on the
+ DESCRIPTOR via ``fstat`` (regular file, still within the size cap — a huge file
+ swapped in is rejected), and bounded-read. Returns None (→ 404 no-store) for a
+ missing/oversized/non-regular target, a swap, or a token mismatch (the content
+ changed since the payload advertised it, or no token was supplied). No exception
+ escapes.
+ """
+ resolved = resolve_show_page_icon(session_id)
+ if resolved is None:
+ return None
+ candidate, content_type = resolved
+ # Race-safe read through the shared chokepoint (cap=True): O_NOFOLLOW open +
+ # fstat regular-file/size-cap re-check on the descriptor + bounded read, so a
+ # symlink / huge file / FIFO swapped in after resolve is refused, not served.
+ data = _read_workspace_file_safely(candidate, _ICON_MAX_BYTES, cap=True)
+ if data is None:
+ return None
+ if not expected_version or _icon_content_token(data) != expected_version:
+ return None # ?v= is a content assertion: mismatch/absent → 404 (no poison)
+ return data, content_type
+
+
def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dict[str, Any]:
path = show_page_dir(page.session_id)
private = private_url(page.session_id, config=config)
@@ -509,6 +827,10 @@ def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dict
"session_id": page.session_id,
"visibility": page.visibility,
"path": str(path),
+ # Opaque cache token (not a path): non-null iff a servable icon exists, and
+ # it changes when the icon file changes so the frontend's ?v=<token> busts
+ # the cache with no update-site enumeration (§7.1f versioned-URL).
+ "icon_version": show_page_icon_version(page.session_id),
"active_url": active_url,
"private_url": private,
"public_url": public,
diff --git a/docs/plans/dock-pinned-show-page-apps.md b/docs/plans/dock-pinned-show-page-apps.md
index 4c0eccd6b..ea8431918 100644
--- a/docs/plans/dock-pinned-show-page-apps.md
+++ b/docs/plans/dock-pinned-show-page-apps.md
@@ -128,11 +128,22 @@ PUT /api/dock/order { order: string[] } → { ok, dock }
DockDoc = { order: string[], pins: DockPin[] }
DockPin = { session_id: string, title_snapshot: string, pinned_at: string }
+
+GET|HEAD /api/show-pages/{session_id}/icon → 200 image bytes | 404 # §7.1f
```
- `POST pins` appends `show:<sid>` to the end of `order`; captures
`title_snapshot` from the session's current title server-side.
- Errors: 404 unknown session / no show page on pin; 400 invalid order.
+- `GET /api/show-pages/{sid}/icon?v=<token>` (§7.1f): serves the page's own HTML
+ icon, resolved server-side with document semantics (`<base href>`), confined to
+ the workspace, whitelisted image extension only. The URL carries the **sid in
+ the path + a server-issued opaque cache token as `?v=`**; the server NEVER
+ derives resolution from the query. 404 on any policy rejection / missing target
+ / malformed input — never a redirect, partial serve, or 500. Headers on 200:
+ `nosniff` + `Content-Security-Policy: sandbox` + `Cache-Control: private,
+ max-age=604800, immutable` (safe because the token versions the URL); 404s are
+ `no-store`. Never boots the Show Runtime.
## 5. Frontend Changes (map to real files)
@@ -345,6 +356,214 @@ shows an App Library shortcut hint (never a dead surface).
- Freshness: rides the existing inventory refresh cycles; no push channel.
- Sequenced AFTER Phase 2.2 (file overlap on Dock/Library surfaces).
+**Implementation reality (2026-07-14, matches shipped code):**
+- The show-runtime scaffold ships **NO `<link rel="icon">`** at all (see
+ `_default_index_html` — it deliberately declares no favicon/apple-touch-icon).
+ So an un-customized page yields `icon_path: null` via the plain "no link"
+ path; there is no `vite.svg` stock link to special-case. The Vite default
+ `href="/vite.svg"` is absolute → already null; a relative `vite.svg` basename
+ is guarded defensively for raw-Vite copies.
+- `icon_path` rules (server, `core/show_pages.py._extract_icon_path`): reads
+ ONLY `<workspace>/index.html`; returns the first `<link rel="icon">` href
+ when it is a same-workspace **relative** path (leading `./` normalized off);
+ null for missing file / no link / absolute (`/…`) / any URI scheme (http:,
+ data:, //…) / parent traversal / the `vite.svg` stock basename.
+- The avatar is **not a single component chokepoint**. The icon-or-letter
+ render + onError→letter fallback lives in one shared `ShowPageAvatarContent`
+ (in `showPageAvatarTile.tsx`). It is adopted by: `ShowPageAvatarTile` (Library
+ Apps rows, Show Pages rows, ⌘K search) and the two bespoke inline tiles that
+ read the same inventory (Dock, mobile drawer). All join the page by session id.
+- **Deferred (follow-up):** the mobile full-screen **ShowPageRoute** header
+ loads the session, not the inventory, so it has no `icon_path` without an
+ extra fetch — it keeps the letter/Lucide icon for now.
+
+**Restructure (owner-adjudicated 2026-07-14, dedicated endpoint — supersedes
+the "server extracts, browser fetches a `/show/` path" shape above):** the
+browser no longer composes any file URL from `icon_path`. All href resolution
+and policy live behind ONE server chokepoint:
+
+```
+GET|HEAD /api/show-pages/{session_id}/icon → 200 image bytes | 404
+```
+
+- **Single chokepoint.** The server resolves the page's `<link rel="icon">`
+ href with full **document semantics** — including a leading `<base href>` —
+ then serves the resolved file. The frontend URL carries ONLY the session id
+ (`showPageIconUrl` → `/api/show-pages/<sid>/icon`); `icon_path` in the
+ payload is now purely a **has-icon signal** (may later shrink to `has_icon`),
+ never composed into a path.
+- **Policy (all → 404, never a redirect / partial serve), in `core/show_pages`:**
+ resolve `href` (percent-decoded, `\`→`/`) against `<base>` then the doc URL;
+ require it stay within the workspace (`http://show.invalid/w/…`); reject the
+ runtime surfaces (`api/`, `__show/`, `__events` first segment), the `vite.svg`
+ stock basename, and parent traversal; **reject any non-relative ref up front** —
+ absolute / root-relative (`/w/…`, `/x`) / protocol-relative (`//host`) / scheme
+ hrefs and bases (a literal `/w/…` must not masquerade as workspace-relative);
+ **treat any malformed URL as "no icon", never raised** (the resolver runs while
+ building `/api/show-pages`, so one bad page falls back to the letter avatar
+ instead of 500ing the whole inventory); require a whitelisted image extension
+ `{svg,png,ico,jpg,jpeg,webp,gif}` (case-insensitive); then realpath-confirm the
+ target is a regular file inside the workspace root.
+- **Serving.** `send_file` with `Content-Type` from the extension whitelist +
+ `X-Content-Type-Options: nosniff` + `Content-Security-Policy: sandbox` +
+ `Cache-Control: private, no-cache`. The URL is stable (session id only), so
+ `no-cache` (revalidate before reuse) rather than a `max-age` fresh window keeps
+ the tile from showing a stale icon after an overwrite / a changed `<link
+ rel=icon>`; `send_file`'s ETag + Last-Modified make an unchanged icon a cheap
+ 304 where conditional GETs are honored, and a changed icon always yields fresh
+ bytes. (The app-wide vault-sandbox hook then composes its `frame-src` onto the
+ CSP, so the wire value is `sandbox; frame-src 'self' https://sandbox.avibe.bot`
+ — the bare `sandbox` directive stays first and effective, rendering a
+ page-authored SVG in an opaque origin with scripts disabled.) Same authed
+ `/api` surface (inherits
+ `enforce_remote_access_cookie`); a remote request without a session is bounced.
+ Resolving/serving an icon **never boots the Show Runtime** (pure static read).
+- **Why.** Three review rounds re-litigated per-rule href policy at the URL
+ layer (traversal, encoded traversal, `api/` exemption, `<base>` semantics);
+ a chokepoint that reasons with document semantics once, and returns bytes-or-404,
+ removes the class instead of patching instances.
+- **Window title-bar** now renders the shared `ShowPageAvatarContent` chip for
+ showpage windows (`AppWindow` gets the window's `icon_path` threaded from the
+ `WindowLayer` inventory join), so it inherits the page favicon like every
+ other surface.
+
+**Hardening (review round 2, 2026-07-14):**
+- **Bytes-or-404, never 500.** The endpoint wraps its body in `except
+ (ShowPageError, ValueError, OSError)` → 404, so a malformed session id
+ (`/api/show-pages/!/icon`, which `validate_session_id` rejects in
+ `store.get`) or a page-authored href that resolves to a filesystem-invalid
+ path (embedded NUL, overlong filename → `Path.resolve()`/`stat` raises) both
+ degrade to the letter avatar. `resolve_show_page_icon` also catches
+ `(ValueError, OSError)` at its own layer so the helper honors its "None for
+ bad input" contract.
+- **Offline pages serve icons.** The visibility gate is dropped (serve for any
+ of the user's own pages — private/public/**offline**): the payload advertises
+ `icon_path` for offline pages and the inventory lists them, so gating would
+ strand offline rows / pinned offline apps on the letter avatar.
+- **404s are `no-store`.** The not-found response carries `Cache-Control:
+ no-store` so a heuristically-cached negative can't keep the letter fallback on
+ the stable URL after the page later adds the icon.
+- **Already-loaded icons revalidate.** `ShowPageAvatarContent` remounts its
+ `<img>` (a refresh nonce as `key`) on each inventory refresh, forcing an
+ already-loaded, stable-URL icon to re-request; the backend `no-cache` then
+ makes it a 304 (unchanged) or fresh bytes (changed), so an overwritten favicon
+ / repointed `<link rel=icon>` reflects without a full reload.
+
+**Versioned URL (owner-approved 2026-07-14 — SUPERSEDES the sid-only + `no-cache`
++ notifier/remount freshness design above).** The icon-freshness theme recurred
+across three review rounds (backend cache header → frontend remount-on-load →
+remount-on-mutation): the "notify→remount at every inventory-update site"
+mechanism is leaky by design (each round found another un-enumerated update
+site). Replaced with a **content-versioned URL**, correct-by-construction:
+
+- **Token.** The payload's has-icon signal becomes `icon_version` (was
+ `icon_path`): a server-issued opaque token — `show_page_icon_version` digests
+ the resolved icon file's **CONTENT** (a same-size/same-mtime regeneration via
+ `cp -p`/deterministic builds still busts it; identical bytes keep the token
+ stable so an unchanged icon stays a cache hit). Non-null iff a servable icon
+ exists. `icon_path` is removed from the payload (the frontend never needed the
+ path).
+- **URL.** `showPageIconUrl(sid, iconVersion)` →
+ `/api/show-pages/<sid>/icon?v=<token>`. Any payload refresh that changed the
+ icon changed the token → a new `src` the `<img>` refetches on its own. No
+ notifier, no remount, no update-site enumeration; freshness rides the normal
+ React re-render. Unchanged icon → same URL → cache hit (flicker-free).
+- **The query never selects the file; it is a read-time CONTENT ASSERTION
+ (owner-adjudicated 2026-07-14, supersedes "the server never reads `?v=`").**
+ Resolution is still sid + workspace only — a `v` value can neither traverse nor
+ change which file is resolved. But `read_show_page_icon` now recomputes the
+ content token of the bytes it is about to serve and returns 404/`no-store` if it
+ does not match the requested `?v=`. This makes `immutable` semantically honest (a
+ URL maps to exactly one byte-content — no cache poisoning across a content
+ revert) and closes the resolve→read TOCTOU in the same code region: the resolved
+ candidate is opened `O_NOFOLLOW` (a symlink swapped in after resolve fails), the
+ size cap is re-checked on the DESCRIPTOR via `fstat` (a huge file swapped in is
+ rejected), then bounded-read. Wording: **"sid in the path selects the file; the
+ `?v=` token never selects it, it is validated as a content assertion after
+ sid-only resolution."** Tests: correct token → 200 immutable; wrong/missing/
+ path-shaped token → 404 (never the file a `v` names); symlink-swap and
+ over-cap-swap rejected on the descriptor path.
+ - _Threat-model note (ledger):_ this endpoint is the OWNER's authed `/api`
+ surface (NOT the public `/p/` share); the racing party is the user's own agent,
+ which already has local FS access — so the read-time hardening is
+ defense-in-depth, not a privilege boundary.
+- **Caching restored.** 200s are `Cache-Control: private, max-age=604800,
+ immutable` — honest now that `?v=` is enforced against the served bytes; 404s
+ stay `no-store`.
+- **Deleted.** `showPageIconRefresh` (notifier) and the `<img>` remount nonce are
+ removed entirely — this round is a net simplification (no dead code).
+- **Freshness invariant (test).** Overwriting the icon, or repointing
+ `<link rel=icon>`, changes `icon_version` in the next payload — asserted
+ directly, so no update-site enumeration exists anywhere.
+- **Serving is materialized bytes-or-404 (test).** The endpoint reads the icon
+ bytes INSIDE its `try` and returns a plain `Response`, not a lazy
+ `FileResponse`: a live-edit race (favicon rebuilt/removed after `resolve()`
+ accepted it) surfaces as an `OSError` → 404 instead of failing while a response
+ streams, and a `Range` header can never produce a 206/416 (a plain Response
+ ignores Range). Icons are small, so buffering is cheap.
+- **Size cap (test).** Because both the token hash (per inventory row) and the
+ materialized serve read the file in full, `resolve_show_page_icon` drops any icon
+ over `_ICON_MAX_BYTES` (2 MiB) to `None` (letter avatar) — a page can't point
+ `<link rel=icon>` at a screenshot/large asset and make `/api/show-pages` allocate
+ hundreds of MB. An icon renders ~40px, so the cap is generous.
+- **One workspace read chokepoint (owner-adjudicated 2026-07-14, tests).** All
+ three reads of agent-authored workspace files — `index.html` head (@64 KiB),
+ the icon token hash (@2 MiB), and the icon serve (@2 MiB) — go through a single
+ portable helper `_read_workspace_file_safely(path, limit, *, cap)`. It opens with
+ getattr-guarded `O_NOFOLLOW` (a swapped-in symlink is not followed; degrades to a
+ plain open on Windows, where the earlier unguarded `os.O_NOFOLLOW` would have
+ `AttributeError`ed → 500) **and** `O_NONBLOCK` (opening a swapped-in FIFO/device
+ returns immediately instead of BLOCKING on a writer — otherwise a hung
+ `/api/show-pages` request is user-visible), then `fstat`s the DESCRIPTOR to refuse
+ a non-regular target (and, with `cap`, an oversized one) before a bounded read.
+ Net simpler (dedupes three fd sites); no raw `read_bytes`/`open` on workspace
+ paths remains in the module. Helper tests: regular OK · symlink refused ·
+ oversize refused · FIFO refused (symlink/FIFO cases skip where the platform lacks
+ the flag/`mkfifo`, so windows-smoke stays green).
+ - _Threat-model note (ledger):_ owner-authed `/api` surface, racing party is the
+ user's own agent with local FS access → the swap/TOCTOU parts are
+ defense-in-depth; the Windows crash and the FIFO-hang-on-inventory were the
+ substantive bits (a hung inventory request is user-visible, not ledger material).
+- **Bounded load-retry (frontend; owner-accepted as-is 2026-07-14 — ledger).**
+ `ShowPageAvatarContent` retries a failed `<img>` up to `MAX_ICON_LOAD_ATTEMPTS`
+ (3) — `onError` remounts it via a per-URL attempt-count `key`, latching to the
+ letter only after the budget. In the versioned-URL model a permanently-absent
+ icon is a null `iconUrl` (letter, no `<img>`, no onError), so onError only ever
+ signals a transient/race failure — exactly the case worth retrying; the budget
+ resets when the URL changes. A longer persistent transient (or an exact
+ content-revert whose token is unchanged) falls back to the letter until a natural
+ remount / payload refresh — accepted for a DECORATIVE surface rather than
+ resurrecting the deleted notifier or adding timers.
+
+### 7.1g Window-close ergonomics (owner approved 2026-07-14 16:03)
+
+Browsers reserve ⌘W (tab close) — not interceptable in a normal tab. Two
+mitigations ship together (the fullscreen Keyboard-Lock capture was offered
+and NOT taken):
+
+- **⌥W closes the focused in-app window** (desktop): same target resolution
+ and guard flow as the existing window chords in WindowLayer
+ (activeElement→data-window-id, close-guard/confirmClose respected,
+ input/terminal exemptions consistent with existing chord handling; use
+ event.code KeyW).
+- **beforeunload guard**: while at least one NON-minimized app window is
+ open (PM default — minimized-only windows do not arm it; flag if wrong),
+ closing/leaving the tab triggers the browser's native confirm. No custom
+ copy (browsers ignore it). Must not interfere with the terminal's
+ existing pagehide cleanup path — verify.
+
+_Implementation note (matches shipped code): ⌥W reuses the existing
+`inTextEntrySurface` exemption (like the Alt+1-9 chord), so inputs, the Monaco
+editor, and the terminal keep Option+W for character entry — macOS emits a
+special char there; ⌥W closes when focus is elsewhere in a window. The
+beforeunload guard arms via the pure `shouldGuardUnload(windows)` predicate and
+is independent of the terminal's `pagehide` keepalive-DELETE, which still runs
+on a confirmed leave. Inside a Show Page **iframe** the bridge (`ShowPageApp`)
+listens on the iframe's `contentWindow` in the CAPTURE phase — the earliest point
+in the event path (window → document → element) — so a page's own
+`stopPropagation()` (even a capture-phase one) cannot swallow ⌥W; only the
+`inTextEntrySurface` exemption suppresses it._
+
### 7.2 Becoming an app: the ladder (owner Q&A 2026-07-13)
Pinning **is** installing — no separate ceremony. Two entrances, one action:
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index fdf25a5c6..c2f1e9463 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -1,11 +1,21 @@
import json
+import os
from dataclasses import dataclass
import pytest
from config import paths
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
-from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir, show_cli_event_token, show_page_payload
+from core.show_pages import (
+ ShowPage,
+ ShowPageError,
+ ShowPageStore,
+ _default_index_html,
+ _extract_icon_path,
+ ensure_show_page_dir,
+ show_cli_event_token,
+ show_page_payload,
+)
from storage.pagination import PageRequest
from vibe import cli
@@ -733,6 +743,409 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):
assert (page_dir / "api" / "health.ts").exists()
+def test_extract_icon_path_custom_relative_href(tmp_path):
+ (tmp_path / "index.html").write_text(
+ '<!doctype html><html><head><link rel="icon" href="./favicon.svg"></head></html>',
+ encoding="utf-8",
+ )
+ # A leading "./" is normalized away; the path stays relative to /show/<sid>/.
+ assert _extract_icon_path(tmp_path) == "favicon.svg"
+
+
+def test_extract_icon_path_relative_subdir_href(tmp_path):
+ (tmp_path / "index.html").write_text('<link rel="icon" href="assets/logo.png">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) == "assets/logo.png"
+
+
+def test_extract_icon_path_shortcut_icon_rel(tmp_path):
+ # rel="shortcut icon" still carries the "icon" token, so it matches.
+ (tmp_path / "index.html").write_text('<link rel="shortcut icon" href="fav.ico">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) == "fav.ico"
+
+
+def test_extract_icon_path_first_icon_wins(tmp_path):
+ (tmp_path / "index.html").write_text(
+ '<link rel="icon" href="first.svg"><link rel="icon" href="second.svg">',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) == "first.svg"
+
+
+def test_extract_icon_path_missing_index_is_null(tmp_path):
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_no_link_is_null(tmp_path):
+ (tmp_path / "index.html").write_text("<html><head><title>x</title></head></html>", encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_apple_touch_icon_ignored(tmp_path):
+ # apple-touch-icon is not rel="icon"; prefer the letter avatar over it.
+ (tmp_path / "index.html").write_text('<link rel="apple-touch-icon" href="touch.png">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_stock_scaffold_index_is_null(tmp_path):
+ # The real scaffold ships NO icon link, so an un-customized page yields null
+ # and the letter avatar is used. This locks that contract to the scaffold.
+ (tmp_path / "index.html").write_text(_default_index_html("ses123"), encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_stock_vite_icons_are_null(tmp_path):
+ # The Vite default favicon ships as an ABSOLUTE href, and even a relative copy
+ # of the generic mascot is treated as stock — both prefer the letter avatar.
+ for href in ("/vite.svg", "./vite.svg", "assets/vite.svg"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_absolute_href_is_null(tmp_path):
+ # Absolute (root-relative) hrefs resolve to the workbench origin, not the
+ # page workspace — only same-workspace relative paths are allowed.
+ (tmp_path / "index.html").write_text('<link rel="icon" href="/favicon.ico">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_external_and_scheme_hrefs_are_null(tmp_path):
+ for href in (
+ "https://cdn.example.com/i.png",
+ "//cdn.example.com/i.png",
+ "data:image/svg+xml,<svg/>",
+ ):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_parent_traversal_is_null(tmp_path):
+ for href in ("../secret.svg", "../../a/b.svg", "a/../../b.svg"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_encoded_and_backslash_traversal_is_null(tmp_path):
+ # The browser normalizes %2e%2e/, encoded slashes, and backslashes before it
+ # resolves the icon URL, so these must be rejected even without a literal "../".
+ for href in (
+ "%2e%2e/other/icon.svg",
+ "..%2fother%2ficon.svg",
+ "..\\other\\icon.svg",
+ "%2fetc%2fpasswd",
+ "sub/%2e%2e/%2e%2e/secret.svg",
+ ):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_skips_symlinked_index(tmp_path):
+ # An agent could point index.html at a large/special file via a symlink; skip it.
+ real = tmp_path / "real.html"
+ real.write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (tmp_path / "index.html").symlink_to(real)
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_reads_only_head_of_large_index(tmp_path):
+ # A huge inline page must not stall the read; the icon <link> in <head> (top) is
+ # still found, and the trailing bulk beyond the head limit is never scanned.
+ head = '<head><link rel="icon" href="favicon.svg"></head>'
+ (tmp_path / "index.html").write_text(head + "<!-- padding -->" * 20000, encoding="utf-8")
+ assert _extract_icon_path(tmp_path) == "favicon.svg"
+
+
+def test_extract_icon_path_resolves_through_base_href(tmp_path):
+ # A <base href="assets/"> BEFORE the icon link makes the browser resolve the
+ # icon as assets/favicon.svg; the resolver must match that document semantics.
+ (tmp_path / "index.html").write_text(
+ '<head><base href="assets/"><link rel="icon" href="favicon.svg"></head>',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) == "assets/favicon.svg"
+
+
+def test_extract_icon_path_base_after_icon_does_not_apply(tmp_path):
+ # A <base> AFTER the icon link does not affect it (document order).
+ (tmp_path / "index.html").write_text(
+ '<head><link rel="icon" href="favicon.svg"><base href="assets/"></head>',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) == "favicon.svg"
+
+
+def test_extract_icon_path_base_escaping_workspace_is_null(tmp_path):
+ for base in ("/other/", "https://cdn.example.com/", "../"):
+ (tmp_path / "index.html").write_text(
+ f'<head><base href="{base}"><link rel="icon" href="favicon.svg"></head>',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) is None, base
+
+
+def test_extract_icon_path_root_relative_hrefs_are_null(tmp_path):
+ # Root-relative / protocol-relative hrefs root at the ORIGIN, not the workspace,
+ # so they reject — including a literal "/w/…" that would otherwise collide with
+ # the synthetic resolution prefix and be mis-served as workspace-relative (Codex).
+ for href in ("/favicon.svg", "/w/icon.svg", "//cdn.example.com/icon.svg"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_root_relative_base_is_null(tmp_path):
+ # A root-relative <base href="/w/"> likewise escapes the workspace.
+ for base in ("/w/", "/", "//cdn.example.com/"):
+ (tmp_path / "index.html").write_text(
+ f'<head><base href="{base}"><link rel="icon" href="favicon.svg"></head>',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) is None, base
+
+
+def test_extract_icon_path_malformed_href_returns_null_not_raises(tmp_path):
+ # A malformed absolute URL (urlsplit raises ValueError) must fall back to the
+ # letter avatar, NEVER propagate: _extract_icon_path runs while building
+ # /api/show-pages, so one bad page must not break the whole inventory (Codex).
+ for href in ("http://[bad]/icon.svg", "http://[bad/icon.svg"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+ # A malformed <base> is equally contained.
+ (tmp_path / "index.html").write_text(
+ '<head><base href="http://[bad]/"><link rel="icon" href="favicon.svg"></head>',
+ encoding="utf-8",
+ )
+ assert _extract_icon_path(tmp_path) is None
+
+
+def test_extract_icon_path_hidden_dot_segments_are_null(tmp_path):
+ # Hidden / dot segments are denied for icons exactly as the Show Page static
+ # server denies them (`_is_show_page_dot_path`); the icon endpoint must not
+ # become a bypass for that policy — even for an image-extension dot-file (Codex).
+ for href in (".env.svg", "assets/.secret.png", ".git/logo.png", ".favicon.svg", "a/.b/c.png"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_runtime_api_hrefs_are_null(tmp_path):
+ for href in ("api/health", "api/health.svg", "__show/events.png", "__events"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_non_image_extensions_are_null(tmp_path):
+ for href in ("icon.txt", "icon.js", "icon.html", "favicon", "noext/"):
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) is None, href
+
+
+def test_extract_icon_path_accepts_whitelisted_image_extensions(tmp_path):
+ cases = {
+ "icon.png": "icon.png",
+ "icon.jpg": "icon.jpg",
+ "icon.jpeg": "icon.jpeg",
+ "icon.webp": "icon.webp",
+ "icon.gif": "icon.gif",
+ "icon.ico": "icon.ico",
+ "logo.SVG": "logo.SVG", # extension is case-insensitive; the path keeps its case
+ }
+ for href, expected in cases.items():
+ (tmp_path / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ assert _extract_icon_path(tmp_path) == expected, href
+
+
+def _icon_page(session_id: str) -> ShowPage:
+ return ShowPage(
+ session_id=session_id,
+ visibility="private",
+ share_id=None,
+ offline_at=None,
+ created_at="2026-01-01T00:00:00Z",
+ updated_at="2026-01-01T00:00:00Z",
+ )
+
+
+def test_show_page_payload_icon_version_is_a_token_when_icon_exists(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ page_dir = ensure_show_page_dir("sesicon")
+ # A page that customized its index.html with its own relative favicon.
+ (page_dir / "index.html").write_text('<link rel="icon" href="./brand.svg">', encoding="utf-8")
+ (page_dir / "brand.svg").write_text("<svg>v1</svg>", encoding="utf-8")
+
+ version = show_page_payload(_icon_page("sesicon"))["icon_version"]
+
+ # An opaque, non-empty token — NOT the path (the frontend never composes a path).
+ assert isinstance(version, str) and version
+ assert "brand.svg" not in version
+
+
+def test_show_page_payload_icon_version_null_for_default_scaffold(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_show_page_dir("sesdefault") # writes the stock scaffold index.html (no icon)
+ assert show_page_payload(_icon_page("sesdefault"))["icon_version"] is None
+
+
+def test_show_page_payload_icon_version_follows_the_file(monkeypatch, tmp_path):
+ # Freshness invariant (§7.1f versioned-URL): the token follows the resolved icon
+ # FILE, so ANY change to the icon content changes the next payload's token with no
+ # client update-site enumeration. Overwrite → new token; repoint <link> → new token.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ page_dir = ensure_show_page_dir("sesfresh")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg>v1</svg>", encoding="utf-8")
+ v1 = show_page_payload(_icon_page("sesfresh"))["icon_version"]
+ assert v1
+
+ # Overwrite the same file with different bytes → the token changes.
+ (page_dir / "favicon.svg").write_text("<svg>v2-longer</svg>", encoding="utf-8")
+ v2 = show_page_payload(_icon_page("sesfresh"))["icon_version"]
+ assert v2 and v2 != v1
+
+ # Repoint <link rel=icon> to a different file → the token changes again.
+ (page_dir / "logo.png").write_bytes(b"\x89PNG\r\n")
+ (page_dir / "index.html").write_text('<link rel="icon" href="logo.png">', encoding="utf-8")
+ v3 = show_page_payload(_icon_page("sesfresh"))["icon_version"]
+ assert v3 and v3 != v2
+
+
+def test_show_page_payload_icon_version_tracks_content_not_just_mtime(monkeypatch, tmp_path):
+ # The token hashes CONTENT, so a regeneration that preserves size AND mtime
+ # (`cp -p`/`rsync`, deterministic build artifacts) STILL changes it — an
+ # mtime+size identity would collide and, under immutable caching, keep serving
+ # the stale icon (Codex). Identical bytes, in contrast, keep the token stable.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ page_dir = ensure_show_page_dir("sesctnt")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ favicon = page_dir / "favicon.svg"
+ favicon.write_text("<svg>AAAA</svg>", encoding="utf-8")
+ stat = favicon.stat()
+ v1 = show_page_payload(_icon_page("sesctnt"))["icon_version"]
+
+ # Same byte length + restored mtime — ONLY the content differs.
+ favicon.write_text("<svg>BBBB</svg>", encoding="utf-8")
+ os.utime(favicon, ns=(stat.st_atime_ns, stat.st_mtime_ns))
+ assert favicon.stat().st_size == stat.st_size
+ assert favicon.stat().st_mtime_ns == stat.st_mtime_ns
+ v2 = show_page_payload(_icon_page("sesctnt"))["icon_version"]
+ assert v1 and v2 and v1 != v2 # content change is caught despite identical mtime+size
+
+ # Restoring the exact bytes restores the token (identical icon → cache hit).
+ favicon.write_text("<svg>AAAA</svg>", encoding="utf-8")
+ assert show_page_payload(_icon_page("sesctnt"))["icon_version"] == v1
+
+
+def test_resolve_show_page_icon_rejects_oversized_icon(monkeypatch, tmp_path):
+ # A page pointing <link rel=icon> at a large in-workspace asset must NOT make
+ # /api/show-pages read it in full per row (or the endpoint materialize it): an
+ # oversized icon is dropped to the letter avatar (None), not hashed/served (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_pages._ICON_MAX_BYTES", 16)
+ from core.show_pages import resolve_show_page_icon
+
+ page_dir = ensure_show_page_dir("sesbig")
+ (page_dir / "index.html").write_text('<link rel="icon" href="big.png">', encoding="utf-8")
+ (page_dir / "big.png").write_bytes(b"x" * 64) # over the (patched) 16-byte cap
+
+ assert resolve_show_page_icon("sesbig") is None
+ assert show_page_payload(_icon_page("sesbig"))["icon_version"] is None
+ # A file at/under the cap is still accepted.
+ (page_dir / "big.png").write_bytes(b"y" * 16)
+ assert resolve_show_page_icon("sesbig") is not None
+
+
+def test_read_show_page_icon_enforces_the_token(monkeypatch, tmp_path):
+ # ?v= is a content assertion: the correct token yields the bytes; a wrong/empty
+ # token is None (→ 404), so `immutable` caching is honest (URL ⇒ one content).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import read_show_page_icon, show_page_icon_version
+
+ page_dir = ensure_show_page_dir("sesread")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg>hi</svg>", encoding="utf-8")
+ token = show_page_icon_version("sesread")
+
+ assert read_show_page_icon("sesread", token) == (b"<svg>hi</svg>", "image/svg+xml")
+ assert read_show_page_icon("sesread", "deadbeefdeadbeef") is None # wrong token
+ assert read_show_page_icon("sesread", "") is None # no token
+
+
+def test_read_show_page_icon_rejects_symlink_swap(monkeypatch, tmp_path):
+ # TOCTOU: a regular file accepted by resolve is replaced by a symlink to a file
+ # OUTSIDE the workspace before the read. The result must be None (never the
+ # swapped-in target) — caught by the re-resolution's within-root guard and, for
+ # a swap in the resolve→open window, by the O_NOFOLLOW open. Even the (stale)
+ # correct token must not serve it.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import read_show_page_icon, show_page_icon_version
+
+ page_dir = ensure_show_page_dir("sesswap")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg>ok</svg>", encoding="utf-8")
+ token = show_page_icon_version("sesswap")
+ outside = tmp_path / "outside_secret.svg"
+ outside.write_text("<svg>SECRET</svg>", encoding="utf-8")
+ (page_dir / "favicon.svg").unlink()
+ os.symlink(outside, page_dir / "favicon.svg")
+
+ assert read_show_page_icon("sesswap", token) is None
+
+
+def test_read_show_page_icon_rejects_oversized_at_read_time(monkeypatch, tmp_path):
+ # TOCTOU: the file grows past the cap AFTER resolve's stat accepted it (a swap
+ # race). The descriptor `fstat` re-checks the cap, so the huge file is rejected
+ # on the fd → None, never buffered. Patch resolve to hand back the over-cap file
+ # (simulating "resolve saw it small") so the read-time gate is exercised alone.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_pages._ICON_MAX_BYTES", 16)
+ from core.show_pages import read_show_page_icon
+
+ page_dir = ensure_show_page_dir("sesgrow")
+ big = page_dir / "big.png"
+ big.write_bytes(b"z" * 64) # over the patched 16-byte cap
+ monkeypatch.setattr("core.show_pages.resolve_show_page_icon", lambda sid: (big, "image/png"))
+
+ assert read_show_page_icon("sesgrow", "anytoken") is None
+
+
+def test_read_workspace_file_safely_regular_head_and_capped(tmp_path):
+ # The shared chokepoint: a regular file reads (head up to `limit`; or full within
+ # `cap`), an over-cap file is refused, a missing file is None.
+ from core.show_pages import _read_workspace_file_safely
+
+ f = tmp_path / "f.txt"
+ f.write_bytes(b"0123456789")
+ assert _read_workspace_file_safely(f, 4) == b"0123" # cap=False → head up to limit
+ assert _read_workspace_file_safely(f, 100) == b"0123456789"
+ assert _read_workspace_file_safely(f, 100, cap=True) == b"0123456789" # full within cap
+ assert _read_workspace_file_safely(f, 4, cap=True) is None # over cap → refused
+ assert _read_workspace_file_safely(tmp_path / "nope.txt", 100) is None # missing
+
+
+def test_read_workspace_file_safely_refuses_symlink(tmp_path):
+ # O_NOFOLLOW refuses a symlink swapped in for a workspace file. Skip where the
+ # flag is absent (native Windows) so windows-smoke stays green.
+ if not hasattr(os, "O_NOFOLLOW"):
+ pytest.skip("O_NOFOLLOW not available on this platform")
+ from core.show_pages import _read_workspace_file_safely
+
+ (tmp_path / "outside.txt").write_bytes(b"SECRET")
+ link = tmp_path / "link.txt"
+ os.symlink(tmp_path / "outside.txt", link)
+ assert _read_workspace_file_safely(link, 100) is None
+ assert _read_workspace_file_safely(link, 100, cap=True) is None
+
+
+def test_read_workspace_file_safely_refuses_non_regular_fifo(tmp_path):
+ # A FIFO (special file) swapped in must be refused by the descriptor fstat, so a
+ # read can never block the inventory. Skip where mkfifo is unavailable (Windows).
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("mkfifo not available on this platform")
+ from core.show_pages import _read_workspace_file_safely
+
+ fifo = tmp_path / "pipe"
+ os.mkfifo(fifo)
+ assert _read_workspace_file_safely(fifo, 100) is None
+ assert _read_workspace_file_safely(fifo, 100, cap=True) is None
+
+
def test_fresh_workspace_scaffolds_placeholder_and_minimal_router(monkeypatch, tmp_path):
# A brand-new Show Page workspace starts as a clean "being generated"
# placeholder for the user, plus a minimal file-based router and one extra page
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index ae075ac05..ba1fc4a9c 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -339,6 +339,273 @@ def test_private_show_page_uses_runtime_when_available(monkeypatch, tmp_path):
assert "x-vibe-csrf-token" not in manager.calls[0][2]
+def _icon_token(session_id: str) -> str:
+ # The correct ?v= token the frontend would send (same source as the payload).
+ from core.show_pages import show_page_icon_version
+
+ return show_page_icon_version(session_id) or ""
+
+
+def test_show_page_icon_endpoint_serves_static_with_hardened_headers(monkeypatch, tmp_path):
+ # §7.1f: the dedicated icon endpoint resolves the page's own <link rel=icon>
+ # against document semantics and streams the file — statically, never booting
+ # the Show Runtime (listing apps would otherwise start a runtime per icon).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg/>", encoding="utf-8")
+ manager = _FakeShowRuntimeManager(body=b"<h1>Runtime Page</h1>")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/api/show-pages/ses123/icon?v={_icon_token('ses123')}", base_url="http://127.0.0.1:5123"
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"<svg/>"
+ assert response.headers["content-type"] == "image/svg+xml"
+ # Hardened static-asset headers: no sniffing, sandboxed, privately cacheable.
+ assert response.headers["X-Content-Type-Options"] == "nosniff"
+ # The route sets `sandbox`; the app-wide vault-sandbox hook then composes its
+ # frame-src onto it. The bare `sandbox` directive stays present + effective
+ # (a page-authored SVG is rendered in an opaque origin with scripts disabled).
+ csp_directives = [d.strip() for d in response.headers["Content-Security-Policy"].split(";")]
+ assert "sandbox" in csp_directives
+ # `immutable` is honest because ?v= is enforced against the served bytes.
+ assert response.headers["Cache-Control"] == "private, max-age=604800, immutable"
+ # Serving the icon never contacted the Show Runtime.
+ assert manager.calls == []
+
+
+def test_show_page_icon_endpoint_enforces_token_without_selecting_the_file(monkeypatch, tmp_path):
+ # §7.1f (token-enforcement): resolution derives ONLY from the sid + workspace —
+ # `?v=` NEVER selects the file. The CORRECT token serves the favicon; a
+ # wrong/missing/path-shaped token is a 404, and NEVER the file a `v` value names
+ # (no traversal, no wrong-file serve). This is the honest-`immutable` guarantee:
+ # a URL maps to exactly one byte-content.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg/>", encoding="utf-8")
+ # Files a hostile query would try to reach if the endpoint ever RESOLVED via ?v=.
+ (page_dir / "secret.svg").write_text("<svg>secret</svg>", encoding="utf-8")
+ (tmp_path / "outside.svg").write_text("<svg>outside</svg>", encoding="utf-8")
+ client = app.test_client()
+
+ ok = client.get(f"/api/show-pages/ses123/icon?v={_icon_token('ses123')}", base_url="http://127.0.0.1:5123")
+ assert ok.status_code == 200
+ assert ok.content == b"<svg/>"
+
+ for query in (
+ "", # missing v
+ "?v=abc123", # a wrong token
+ "?v=../../secret.svg", # traversal-shaped
+ "?v=../../../outside.svg",
+ "?v=%2e%2e%2fsecret.svg", # encoded traversal-shaped
+ "?v=secret.svg", # names a real in-workspace file
+ "?v=" + "z" * 5000, # junk
+ ):
+ response = client.get(f"/api/show-pages/ses123/icon{query}", base_url="http://127.0.0.1:5123")
+ assert response.status_code == 404, query # never resolves a different file
+ assert b"secret" not in response.content, query
+ assert b"outside" not in response.content, query
+
+
+def test_show_page_icon_endpoint_ignores_range_header(monkeypatch, tmp_path):
+ # The icon is a bytes-or-404 chokepoint: a `Range` header must NOT turn it into
+ # a 206/416 partial (the materialized plain Response never honors Range) — it
+ # always serves the full 200 (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg>abcdefghij</svg>", encoding="utf-8")
+
+ response = app.test_client().get(
+ f"/api/show-pages/ses123/icon?v={_icon_token('ses123')}",
+ base_url="http://127.0.0.1:5123",
+ headers={"Range": "bytes=0-3"},
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"<svg>abcdefghij</svg>"
+ assert "Content-Range" not in response.headers
+
+
+def test_show_page_icon_endpoint_404s_when_file_vanishes_after_resolve(monkeypatch, tmp_path):
+ # Live-edit race: resolve_show_page_icon accepts the icon, then the file is
+ # rebuilt/removed before the bytes are read. Because the endpoint materializes
+ # the bytes INSIDE its try, the OSError degrades to the 404 letter fallback —
+ # not a 500 raised while a lazy FileResponse streams (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ vanished = ensure_show_page_dir("ses123") / "vanished.svg" # never created on disk
+ monkeypatch.setattr(
+ "core.show_pages.resolve_show_page_icon",
+ lambda session_id: (vanished, "image/svg+xml"),
+ )
+
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+ assert response.headers.get("Cache-Control") == "no-store"
+
+
+def test_show_page_icon_endpoint_serves_offline_pages(monkeypatch, tmp_path):
+ # An offline page still advertises a token and is listed in the inventory, so its
+ # static icon must serve too — gating by visibility would strand offline rows /
+ # pinned offline apps on the letter avatar despite a real icon (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "offline")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg/>", encoding="utf-8")
+
+ response = app.test_client().get(
+ f"/api/show-pages/ses123/icon?v={_icon_token('ses123')}", base_url="http://127.0.0.1:5123"
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"<svg/>"
+
+
+def test_show_page_icon_endpoint_not_found_is_uncacheable(monkeypatch, tmp_path):
+ # The 404 for a page with no icon carries `no-store` so a heuristically-cached
+ # negative response can't strand the letter fallback once the icon is added (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private") # default scaffold: no icon link
+
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+ assert response.headers.get("Cache-Control") == "no-store"
+
+
+def test_show_page_icon_endpoint_404s_malformed_session_id(monkeypatch, tmp_path):
+ # A session id that fails validate_session_id raises ShowPageError in store.get;
+ # the endpoint must catch it and 404 (letter fallback), never 500 (Codex).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ response = app.test_client().get("/api/show-pages/!/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+
+
+def test_show_page_icon_endpoint_404s_filesystem_invalid_icon(monkeypatch, tmp_path):
+ # A page-authored href that resolves to a filesystem-invalid path (an overlong
+ # filename) makes Path.resolve()/stat raise OSError; the endpoint must 404, never
+ # 500 (Codex). resolve_show_page_icon contains it; the boundary is belt-and-braces.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text(
+ f'<link rel="icon" href="{"a" * 300}.png">', encoding="utf-8"
+ )
+
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+
+
+def test_show_page_icon_endpoint_resolves_through_base_href(monkeypatch, tmp_path):
+ # The endpoint honors <base href> exactly as the browser would: the icon lives
+ # under assets/ and is served, proving the resolver runs server-side (the URL
+ # carries only the session id).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text(
+ '<head><base href="assets/"><link rel="icon" href="logo.png"></head>', encoding="utf-8"
+ )
+ (page_dir / "assets").mkdir()
+ (page_dir / "assets" / "logo.png").write_bytes(b"\x89PNG\r\n")
+
+ response = app.test_client().get(
+ f"/api/show-pages/ses123/icon?v={_icon_token('ses123')}", base_url="http://127.0.0.1:5123"
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"\x89PNG\r\n"
+ assert response.headers["content-type"] == "image/png"
+
+
+def test_show_page_icon_endpoint_404_when_no_icon(monkeypatch, tmp_path):
+ # The default scaffold ships no <link rel=icon>; the endpoint 404s so the tile
+ # falls back to the letter avatar.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private") # default index has no icon link
+
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+
+
+def test_show_page_icon_endpoint_404_on_policy_rejections(monkeypatch, tmp_path):
+ # Every policy rejection collapses to a 404 (never a redirect, never a partial
+ # serve): runtime api/ + __show/ paths, non-image extensions, and traversal
+ # escapes — even when the traversal target really exists on disk.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (tmp_path / "outside_secret.svg").write_text("<svg>secret</svg>", encoding="utf-8")
+ for href in ("api/health", "icon.txt", "../../outside_secret.svg", "__show/events.png"):
+ (page_dir / "index.html").write_text(f'<link rel="icon" href="{href}">', encoding="utf-8")
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+ assert response.status_code == 404, href
+ assert b"secret" not in response.content, href
+
+
+def test_show_page_icon_endpoint_404_when_target_missing(monkeypatch, tmp_path):
+ # A whitelisted, in-workspace href whose file does not exist is a 404 (the
+ # <link> may reference an icon the page never actually shipped).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+
+ response = app.test_client().get("/api/show-pages/ses123/icon", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 404
+
+
+def test_show_page_icon_endpoint_requires_remote_login(monkeypatch, tmp_path):
+ # Auth parity with the rest of /api: a remote request without a session is
+ # bounced, so the icon (which can embed page-authored SVG) is never exposed
+ # anonymously. The icon exists, so a 200 here would be a real regression.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = ensure_show_page_dir("ses123")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.svg">', encoding="utf-8")
+ (page_dir / "favicon.svg").write_text("<svg/>", encoding="utf-8")
+
+ response = app.test_client().get(
+ "/api/show-pages/ses123/icon",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code != 200 # bounced/denied, never served anonymously
+ assert response.content != b"<svg/>"
+
+
def test_private_show_page_materializes_workspace_before_runtime_proxy(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/ui/src/apps/LibraryApp.tsx b/ui/src/apps/LibraryApp.tsx
index 37dac775e..0feedcf12 100644
--- a/ui/src/apps/LibraryApp.tsx
+++ b/ui/src/apps/LibraryApp.tsx
@@ -136,6 +136,8 @@ interface ResolvedRow {
subtitle: string;
/** The built-in app definition (icon + accent) when this row is a built-in. */
def?: AppDefinition;
+ /** The AI page icon's opaque cache token, when it has one (§7.1f). */
+ iconVersion?: string | null;
}
// A drag handle for a docked row (§7.1e). Handle-only drag: the Reorder.Item is
@@ -181,7 +183,7 @@ interface AppLibraryRowProps {
// Reorder.Item) and the search path (static).
const AppLibraryRow: React.FC<AppLibraryRowProps> = ({ item, leading, last, onOpen, onDockToggle, onRemove }) => {
const { t } = useTranslation();
- const { row, name, subtitle, def } = item;
+ const { row, name, subtitle, def, iconVersion } = item;
const Icon = def?.icon;
return (
<div
@@ -208,7 +210,7 @@ const AppLibraryRow: React.FC<AppLibraryRowProps> = ({ item, leading, last, onOp
<Icon className="size-[18px]" />
</span>
) : (
- <ShowPageAvatarTile sessionId={row.sessionId ?? ''} title={name} />
+ <ShowPageAvatarTile sessionId={row.sessionId ?? ''} title={name} iconVersion={iconVersion} />
)}
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-[13px] font-semibold text-foreground">{name}</span>
@@ -346,7 +348,7 @@ const AppsView: React.FC<{ pages: ShowPage[]; openApp: ReturnType<typeof useOpen
.filter(Boolean)
.join(' · ')
: '';
- return { row, name, subtitle };
+ return { row, name, subtitle, iconVersion: page?.icon_version ?? null };
}),
[rows, pageBySession, pinBySession, t],
);
diff --git a/ui/src/apps/ShowPageApp.tsx b/ui/src/apps/ShowPageApp.tsx
index 897321166..a5199c290 100644
--- a/ui/src/apps/ShowPageApp.tsx
+++ b/ui/src/apps/ShowPageApp.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { MonitorX, PinOff } from 'lucide-react';
+import { inTextEntrySurface } from '../components/apps/windowChords';
import { useApi } from '../context/ApiContext';
import { useDock } from '../context/DockContext';
import { useWindowManager } from '../context/WindowManagerContext';
@@ -23,8 +24,9 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u
// 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 { setTitle, close, confirmClose } = useWindowManager();
const { unpin } = useDock();
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
const sessionId = typeof params?.sessionId === 'string' ? params.sessionId : '';
// 'loading' optimistically frames the page (the common case: it exists);
@@ -59,6 +61,51 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u
};
}, [sessionId, api, setTitle, windowId]);
+ // Bridge ⌥W (close window) into the same-origin Show Page iframe: a keydown
+ // inside the iframe dispatches to ITS document and never bubbles to the parent
+ // WindowLayer listener, so without this ⌥W could not close the window while the
+ // user is interacting with the page content (Codex §7.1f review). Re-attach on
+ // each (re)load; text-entry surfaces inside the page keep Option+W for char entry.
+ useEffect(() => {
+ const iframe = iframeRef.current;
+ if (!iframe) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;
+ let active: Element | null = null;
+ try {
+ active = iframe.contentDocument?.activeElement ?? null;
+ } catch {
+ active = null;
+ }
+ if (inTextEntrySurface(active)) return;
+ e.preventDefault();
+ if (confirmClose(windowId)) close(windowId);
+ };
+ const attach = () => {
+ try {
+ // Capture phase (`true`) on the iframe's WINDOW — the EARLIEST target in the
+ // event path (window → document → element). A page that installs its own
+ // capture-phase keydown listener and calls stopPropagation() would run before
+ // a document-level capture listener and still swallow ⌥W; the window capture
+ // runs before that, so only the explicit text-entry exemption above can
+ // suppress the close shortcut (Codex §7.1g review).
+ iframe.contentWindow?.addEventListener('keydown', onKeyDown, true);
+ } catch {
+ // Cross-origin (should not happen for the same-origin /show/ surface).
+ }
+ };
+ attach();
+ iframe.addEventListener('load', attach);
+ return () => {
+ iframe.removeEventListener('load', attach);
+ try {
+ iframe.contentWindow?.removeEventListener('keydown', onKeyDown, true);
+ } catch {
+ // Document already torn down.
+ }
+ };
+ }, [close, confirmClose, windowId]);
+
if (!sessionId || state === 'missing') {
return (
<div className="grid h-full w-full place-items-center bg-surface px-6 text-center">
@@ -94,6 +141,7 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u
// per the standing product decision we do NOT harden it here.
return (
<iframe
+ ref={iframeRef}
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"
diff --git a/ui/src/apps/showPageAvatar.test.ts b/ui/src/apps/showPageAvatar.test.ts
index 5cca79abc..654d3a174 100644
--- a/ui/src/apps/showPageAvatar.test.ts
+++ b/ui/src/apps/showPageAvatar.test.ts
@@ -6,6 +6,7 @@ import {
firstGrapheme,
sessionChatPath,
showPageAvatar,
+ showPageIconUrl,
showPagePrivatePath,
} from './showPageAvatar';
@@ -80,6 +81,24 @@ describe('showPagePrivatePath', () => {
});
});
+describe('showPageIconUrl', () => {
+ it('puts the session id in the path and the server-issued token as ?v=', () => {
+ // The token is an opaque cache key appended verbatim — the endpoint resolves
+ // the icon from the sid + workspace and never reads the query.
+ expect(showPageIconUrl('ses_1', 'abc123')).toBe('/api/show-pages/ses_1/icon?v=abc123');
+ });
+
+ it('url-encodes both the session id and the token', () => {
+ expect(showPageIconUrl('a/b', 'a b/c')).toBe('/api/show-pages/a%2Fb/icon?v=a%20b%2Fc');
+ });
+
+ it('returns null when the page has no icon (the token is the has-icon signal)', () => {
+ expect(showPageIconUrl('ses_1', null)).toBeNull();
+ expect(showPageIconUrl('ses_1', undefined)).toBeNull();
+ expect(showPageIconUrl('ses_1', ' ')).toBeNull();
+ });
+});
+
describe('sessionChatPath', () => {
it('points at the in-app chat route for the session, url-encoded', () => {
expect(sessionChatPath('ses_1')).toBe('/chat/ses_1');
diff --git a/ui/src/apps/showPageAvatar.ts b/ui/src/apps/showPageAvatar.ts
index c2a47cf10..9aade2f5a 100644
--- a/ui/src/apps/showPageAvatar.ts
+++ b/ui/src/apps/showPageAvatar.ts
@@ -46,6 +46,22 @@ export function showPagePrivatePath(sessionId: string): string {
return `/show/${encodeURIComponent(sessionId)}/`;
}
+/** The URL for a page's own HTML icon, served by the dedicated
+ * `GET /api/show-pages/<sid>/icon` endpoint (§7.1f). ALL href resolution + policy
+ * lives server-side; the URL carries the session id in the PATH plus the
+ * server-issued opaque cache token as `?v=<token>`. The server NEVER derives
+ * resolution from the query — the token only VERSIONS the URL so it changes when
+ * the icon file changes, busting the cache with no client update-site enumeration
+ * (any payload refresh that changes the token changes the `src`, so the `<img>`
+ * refetches on its own). `iconVersion` doubles as the has-icon signal: null/blank →
+ * no icon → the caller falls back to the letter avatar (the endpoint also 404s on
+ * any rejection, and the tile's onError falls back). Pure. */
+export function showPageIconUrl(sessionId: string, iconVersion: string | null | undefined): string | null {
+ const token = (iconVersion ?? '').trim();
+ if (!token) return null;
+ return `/api/show-pages/${encodeURIComponent(sessionId)}/icon?v=${encodeURIComponent(token)}`;
+}
+
/** The in-app route to the owning session's Chat page (`/chat/:sessionId`). The Show
* Page window's chat-bubble navigates here (SPA nav, not a new tab) and minimizes the
* window. Pass `{ showChat: true }` to append the `?view=chat` signal that tells
diff --git a/ui/src/apps/showPageAvatarTile.tsx b/ui/src/apps/showPageAvatarTile.tsx
index 47c7accc1..5168d764c 100644
--- a/ui/src/apps/showPageAvatarTile.tsx
+++ b/ui/src/apps/showPageAvatarTile.tsx
@@ -1,22 +1,61 @@
+import { useState } from 'react';
import clsx from 'clsx';
-import { showPageAvatar } from './showPageAvatar';
+import { showPageAvatar, showPageIconUrl } from './showPageAvatar';
-// The icon-free tile for a Show Page: the first grapheme of the title on a tint
-// hashed from the session id (the same letter avatar the Dock renders). Shared
-// by both App Library views so a pinned page reads identically in the Dock, the
-// Apps view, and the Show Pages view.
-export const ShowPageAvatarTile: React.FC<{ sessionId: string; title: string; className?: string }> = ({
- sessionId,
- title,
- className,
-}) => {
+// The icon-or-letter CONTENT of a Show Page avatar, WITHOUT any tile wrapper:
+// the page's own HTML icon (§7.1f) rendered as an <img>, falling back to the
+// letter avatar when there is no icon OR the image fails to load (onError).
+// Shared by ShowPageAvatarTile and the Dock / mobile-drawer / window-title-bar
+// tiles — each provides its own accent-box wrapper — so the icon + fallback rule
+// lives in one place.
+//
+// Freshness needs no notifier/remount machinery: `iconUrl` is content-versioned
+// (`?v=<token>` from the icon file's identity), so a changed icon changes the URL,
+// which is a new `src` the browser fetches on its own.
+//
+// A load failure is retried a bounded number of times before falling back to the
+// letter: `onError` remounts the <img> (a per-URL attempt count is the `key`, so it
+// re-fetches) and only latches to the letter after MAX_ICON_LOAD_ATTEMPTS. In the
+// versioned-URL model a permanently-absent icon arrives as a null `iconUrl` (letter,
+// no <img>, no onError) — so onError only ever signals a TRANSIENT failure (a brief
+// bytes-or-404 race window, a network blip), exactly the case worth retrying. The
+// count is keyed to the URL, so a new versioned URL retries with a fresh budget.
+const MAX_ICON_LOAD_ATTEMPTS = 3;
+export const ShowPageAvatarContent: React.FC<{ iconUrl: string | null; letter: string }> = ({ iconUrl, letter }) => {
+ const [failure, setFailure] = useState<{ url: string; attempts: number } | null>(null);
+ const attempts = failure && failure.url === iconUrl ? failure.attempts : 0;
+ if (iconUrl && attempts < MAX_ICON_LOAD_ATTEMPTS) {
+ return (
+ <img
+ key={`${iconUrl}#${attempts}`}
+ src={iconUrl}
+ alt=""
+ draggable={false}
+ className="size-full object-cover"
+ onError={() => setFailure({ url: iconUrl, attempts: attempts + 1 })}
+ />
+ );
+ }
+ return <>{letter}</>;
+};
+
+// The avatar tile for a Show Page: an accent-tinted rounded box (first grapheme
+// on a session-hashed accent) wrapping the icon-or-letter content. Shared by the
+// App Library views — Apps, Show Pages, and the ⌘K search results — so a page
+// reads identically across them.
+export const ShowPageAvatarTile: React.FC<{
+ sessionId: string;
+ title: string;
+ iconVersion?: string | null;
+ className?: string;
+}> = ({ sessionId, title, iconVersion, className }) => {
const { letter, accentVar } = showPageAvatar(sessionId, title);
return (
<span
aria-hidden
className={clsx(
- 'flex size-9 shrink-0 items-center justify-center rounded-lg border text-[14px] font-bold leading-none',
+ 'flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg border text-[14px] font-bold leading-none',
className,
)}
style={{
@@ -25,7 +64,7 @@ export const ShowPageAvatarTile: React.FC<{ sessionId: string; title: string; cl
borderColor: `color-mix(in srgb, var(${accentVar}) 34%, transparent)`,
}}
>
- {letter}
+ <ShowPageAvatarContent iconUrl={showPageIconUrl(sessionId, iconVersion)} letter={letter} />
</span>
);
};
diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsx
index 18c0d6e88..56325dc9f 100644
--- a/ui/src/components/ShowPagesPage.tsx
+++ b/ui/src/components/ShowPagesPage.tsx
@@ -126,7 +126,7 @@ function ShowPageRow({
title={t('showPages.openApp')}
className="group flex min-w-0 cursor-pointer items-center gap-3 rounded-lg text-left transition-colors hover:bg-foreground/[0.03]"
>
- <ShowPageAvatarTile sessionId={page.session_id} title={page.title || ''} />
+ <ShowPageAvatarTile sessionId={page.session_id} title={page.title || ''} iconVersion={page.icon_version} />
<span className="min-w-0">
<span className="flex items-center gap-1.5">
<span
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index 505f2ff1a..4fc1c6c4d 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -5,6 +5,8 @@ import clsx from 'clsx';
import { ExternalLink, MessageCircle, Minus, Plus, X, type LucideIcon } from 'lucide-react';
import { APP_REGISTRY } from '../../apps/registry';
+import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';
+import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import { clampToLayer, resizeBounds, type ResizeDir } from '../../lib/windowBounds';
@@ -21,11 +23,14 @@ const RESIZE_HANDLES: { dir: ResizeDir; className: string }[] = [
{ 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,
-}) => {
+export const AppWindow: React.FC<{
+ win: WindowInstance;
+ layerWidth: number;
+ layerHeight: number;
+ /** The Show Page icon's opaque cache token for a `showpage` window's title-bar
+ * chip, threaded from the WindowLayer inventory join (§7.1f/g). */
+ iconVersion?: string | null;
+}> = ({ win, layerWidth, layerHeight, iconVersion }) => {
const { t } = useTranslation();
const wm = useWindowManager();
const navigate = useNavigate();
@@ -111,6 +116,11 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
const Body = def.Component;
const Icon = def.icon;
+ // A Show Page window shows the app-avatar chip (favicon when the page has one,
+ // else the letter avatar) as its title-bar icon — the approved design (q4E5yl);
+ // built-in apps keep their registry Lucide icon.
+ const showpageSid = win.appId === 'showpage' ? (win.params?.sessionId as string | undefined) : undefined;
+ const showpageAvatar = showpageSid ? showPageAvatar(showpageSid, win.title ?? '') : null;
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.
@@ -234,7 +244,21 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
))}
</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})` }} />
+ {showpageSid && showpageAvatar ? (
+ <span
+ aria-hidden
+ className="grid size-4 shrink-0 place-items-center overflow-hidden rounded-[4px] border text-[10px] font-bold leading-none"
+ style={{
+ color: `var(${showpageAvatar.accentVar})`,
+ backgroundColor: `color-mix(in srgb, var(${showpageAvatar.accentVar}) 16%, transparent)`,
+ borderColor: `color-mix(in srgb, var(${showpageAvatar.accentVar}) 34%, transparent)`,
+ }}
+ >
+ <ShowPageAvatarContent iconUrl={showPageIconUrl(showpageSid, iconVersion)} letter={showpageAvatar.letter} />
+ </span>
+ ) : (
+ <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 cluster balances the traffic lights so the title stays centered; a
diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsx
index 842d3c543..cf61f712f 100644
--- a/ui/src/components/apps/Dock.tsx
+++ b/ui/src/components/apps/Dock.tsx
@@ -5,7 +5,8 @@ import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { APP_REGISTRY, type AppDefinition, type AppId } from '../../apps/registry';
-import { showPageAvatar, showPagePrivatePath } from '../../apps/showPageAvatar';
+import { showPageAvatar, showPageIconUrl, showPagePrivatePath } from '../../apps/showPageAvatar';
+import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
import { dockIdToSession, useDock } from '../../context/DockContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { ContextMenu, ContextMenuItem } from '../ui/context-menu';
@@ -16,7 +17,7 @@ import { isDragRelease } from './dragClick';
// (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 };
+ | { kind: 'showpage'; id: string; sessionId: string; title: string; iconVersion: string | null };
// The unified Dock panel: app launcher + running indicators + minimized windows.
// Built-in apps and pinned Show Pages share one reorderable row (server-persisted
@@ -48,7 +49,7 @@ export const Dock: React.FC = () => {
const title = page
? page.title?.trim() || t('chat.untitled')
: pinBySession.get(sessionId)?.title_snapshot?.trim() || sessionId;
- return { kind: 'showpage', id, sessionId, title };
+ return { kind: 'showpage', id, sessionId, title, iconVersion: page?.icon_version ?? null };
}
const def = APP_REGISTRY[id as AppId];
return def ? { kind: 'builtin', id, def } : null;
@@ -198,7 +199,7 @@ export const Dock: React.FC = () => {
setMenu({ x: e.clientX, y: e.clientY, item });
}}
className={clsx(
- 'grid size-10 place-items-center rounded-xl border transition',
+ 'grid size-10 place-items-center overflow-hidden rounded-xl border text-[15px] font-bold leading-none transition',
item.kind === 'builtin' &&
(active ? 'border-2 bg-foreground/[0.07]' : 'border-border bg-foreground/[0.03] hover:bg-foreground/[0.07]'),
)}
@@ -222,7 +223,10 @@ export const Dock: React.FC = () => {
{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>
+ <ShowPageAvatarContent
+ iconUrl={item.kind === 'showpage' ? showPageIconUrl(item.sessionId, item.iconVersion) : null}
+ letter={avatar!.letter}
+ />
)}
</button>
diff --git a/ui/src/components/apps/MobileDockDrawer.tsx b/ui/src/components/apps/MobileDockDrawer.tsx
index 5db7247d1..a1f4d4ec1 100644
--- a/ui/src/components/apps/MobileDockDrawer.tsx
+++ b/ui/src/components/apps/MobileDockDrawer.tsx
@@ -4,7 +4,8 @@ import { useTranslation } from 'react-i18next';
import { LayoutGrid, Minus, MoreHorizontal, PinOff, Settings, Sun, UserRound, X } from 'lucide-react';
import { APP_REGISTRY, type AppDefinition, type AppId } from '../../apps/registry';
-import { showPageAvatar } from '../../apps/showPageAvatar';
+import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';
+import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
import { dockIdToSession, useDock } from '../../context/DockContext';
import { useAuthAccount } from '../../lib/useAuthAccount';
import { useShowPageInventory } from '../useShowPages';
@@ -22,7 +23,7 @@ import { mobileRouteForDockId } from './mobileDock';
type ResidentTile =
| { kind: 'builtin'; id: string; def: AppDefinition }
- | { kind: 'showpage'; id: string; sessionId: string; title: string };
+ | { kind: 'showpage'; id: string; sessionId: string; title: string; iconVersion: string | null };
type FooterSheet = 'account' | 'appearance' | 'more';
@@ -74,7 +75,7 @@ export const MobileDockDrawer: React.FC<{ open: boolean; onClose: () => void }>
const title = page
? page.title?.trim() || t('chat.untitled')
: pinBySession.get(sessionId)?.title_snapshot?.trim() || sessionId;
- return { kind: 'showpage', id, sessionId, title };
+ return { kind: 'showpage', id, sessionId, title, iconVersion: page?.icon_version ?? null };
}
const def = APP_REGISTRY[id as AppId];
return def ? { kind: 'builtin', id, def } : null;
@@ -171,14 +172,21 @@ export const MobileDockDrawer: React.FC<{ open: boolean; onClose: () => void }>
className="flex select-none flex-col items-center gap-1.5"
>
<span
- className="grid size-14 place-items-center rounded-2xl border text-[20px] font-bold leading-none"
+ className="grid size-14 place-items-center overflow-hidden rounded-2xl border text-[20px] font-bold leading-none"
style={{
color: `var(${accentVar})`,
backgroundColor: `color-mix(in srgb, var(${accentVar}) ${item.kind === 'builtin' ? 14 : 16}%, transparent)`,
borderColor: `color-mix(in srgb, var(${accentVar}) ${item.kind === 'builtin' ? 30 : 34}%, transparent)`,
}}
>
- {Icon ? <Icon className="size-6" /> : avatar!.letter}
+ {Icon ? (
+ <Icon className="size-6" />
+ ) : (
+ <ShowPageAvatarContent
+ iconUrl={item.kind === 'showpage' ? showPageIconUrl(item.sessionId, item.iconVersion) : null}
+ letter={avatar!.letter}
+ />
+ )}
</span>
<span className="max-w-full truncate text-[11px] font-medium text-muted">{label}</span>
</button>
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index bc7bb133c..47429aac7 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -8,24 +8,8 @@ import { useApi } from '../../context/ApiContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useShowPageInventory } from '../useShowPages';
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');
-}
-
-function inTextEntrySurface(el: Element | null): boolean {
- return (
- el instanceof HTMLElement &&
- !!el.closest(
- 'input, textarea, select, [contenteditable="true"], [role="textbox"], .monaco-editor, .xterm',
- )
- );
-}
+import { inTerminalSurface, inTextEntrySurface } from './windowChords';
+import { shouldGuardUnload } from './windowUnload';
// 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
@@ -40,6 +24,9 @@ export const WindowLayer: React.FC = () => {
const { pages } = useShowPageInventory();
const { windows, close, focus, minimize, openApp, restore, setParams, setTitle, confirmClose } =
useWindowManager();
+ // Any window open and NOT minimized — drives the layer's aria-hidden AND the
+ // beforeunload guard (§7.1g).
+ const anyShown = shouldGuardUnload(windows);
const ref = useRef<HTMLDivElement | null>(null);
const [size, setSize] = useState({ w: 0, h: 0 });
const windowsRef = useRef(windows);
@@ -92,6 +79,47 @@ export const WindowLayer: React.FC = () => {
return () => window.removeEventListener('keydown', onKeyDown);
}, [close, minimize, confirmClose]);
+ // ⌥W closes the focused in-app window — a browser-safe alternative to ⌘W, which
+ // the browser reserves for tab-close (not interceptable). Uses `code` (macOS
+ // Option+W emits a special char in `key`); same target resolution + confirmClose
+ // guard as the ⌘/Ctrl chord above. Text-entry surfaces (inputs, Monaco, terminal)
+ // keep Option+W for character entry — consistent with the Alt+1-9 chord.
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;
+ const active = document.activeElement;
+ if (inTextEntrySurface(active)) return;
+ const winEl = active instanceof Element ? active.closest('[data-window-id]') : null;
+ if (!winEl || !ref.current?.contains(winEl)) return;
+ const targetId = winEl.getAttribute('data-window-id');
+ if (!targetId) return;
+ e.preventDefault();
+ if (confirmClose(targetId)) close(targetId);
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [close, confirmClose]);
+
+ // While any app window is open and visible (not just minimized), guard tab-close
+ // / navigation-away with the browser's native confirm — the window state
+ // (terminals, unsaved editor buffers, running app iframes) would otherwise vanish
+ // silently. No custom copy (browsers ignore it). This is `beforeunload`, distinct
+ // from the terminal's `pagehide` keepalive-DELETE, so that cleanup still runs when
+ // the user confirms leaving.
+ useEffect(() => {
+ if (!anyShown) return;
+ const onBeforeUnload = (e: BeforeUnloadEvent) => {
+ // The window layer is desktop-only (`hidden md:block`); on a narrowed
+ // viewport the windows are hidden, so a stale non-minimized window must not
+ // prompt on tab-close. Gate on the same md breakpoint, checked at unload time.
+ if (!window.matchMedia?.('(min-width: 768px)').matches) return;
+ e.preventDefault();
+ e.returnValue = '';
+ };
+ window.addEventListener('beforeunload', onBeforeUnload);
+ return () => window.removeEventListener('beforeunload', onBeforeUnload);
+ }, [anyShown]);
+
// Alt/Option+1..9 focuses or launches the Nth resident tile in the current
// server-backed Dock order. Use `code`, not `key`: macOS keyboard layouts can
// turn Option+digit into punctuation. Text inputs and terminals keep the chord
@@ -167,8 +195,7 @@ export const WindowLayer: React.FC = () => {
// 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);
+ // actually shown (`anyShown`, computed above).
return (
<div
@@ -182,9 +209,13 @@ export const WindowLayer: React.FC = () => {
// (z-10), so a maximized window covers the whole sidebar, Apps launcher included.
className="pointer-events-none fixed inset-0 z-20 hidden md:block"
>
- {windows.map((w) => (
- <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} />
- ))}
+ {windows.map((w) => {
+ // For a showpage window, join the inventory (already loaded above — no new
+ // fetch) to hand its own HTML icon to the title-bar chip (§7.1f/g).
+ const sid = w.appId === 'showpage' ? (w.params?.sessionId as string | undefined) : undefined;
+ const iconVersion = sid ? pages.find((p) => p.session_id === sid)?.icon_version ?? null : null;
+ return <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} iconVersion={iconVersion} />;
+ })}
</div>
);
};
diff --git a/ui/src/components/apps/windowChords.test.ts b/ui/src/components/apps/windowChords.test.ts
new file mode 100644
index 000000000..e4f20062d
--- /dev/null
+++ b/ui/src/components/apps/windowChords.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { inTerminalSurface, inTextEntrySurface } from './windowChords';
+
+// Mock an Element by its closest() behavior alone — realm-agnostic and jsdom-free.
+// A PLAIN OBJECT is never `instanceof HTMLElement`, so it doubles as the cross-realm
+// (same-origin iframe) case the ⌥W bridge relies on.
+const elWithClosest = (matches: (selector: string) => boolean): Element =>
+ ({ closest: (selector: string) => (matches(selector) ? ({} as Element) : null) }) as unknown as Element;
+
+describe('inTextEntrySurface', () => {
+ it('matches when closest finds a text-entry ancestor', () => {
+ expect(inTextEntrySurface(elWithClosest((s) => s.includes('input')))).toBe(true);
+ });
+
+ it('is false when closest finds nothing, and for null', () => {
+ expect(inTextEntrySurface(elWithClosest(() => false))).toBe(false);
+ expect(inTextEntrySurface(null)).toBe(false);
+ });
+
+ it('is realm-agnostic: a cross-realm element (not instanceof HTMLElement) still matches', () => {
+ // The ⌥W bridge passes iframe elements from another Window. Duck-typing on
+ // closest keeps the input/editor/terminal exemption working there — otherwise
+ // ⌥W would close the Show Page window while the user is typing.
+ expect(inTextEntrySurface(elWithClosest((s) => s.includes('textarea')))).toBe(true);
+ });
+});
+
+describe('inTerminalSurface', () => {
+ it('matches only inside an .xterm root, and is false for null', () => {
+ expect(inTerminalSurface(elWithClosest((s) => s === '.xterm'))).toBe(true);
+ expect(inTerminalSurface(elWithClosest(() => false))).toBe(false);
+ expect(inTerminalSurface(null)).toBe(false);
+ });
+});
diff --git a/ui/src/components/apps/windowChords.ts b/ui/src/components/apps/windowChords.ts
new file mode 100644
index 000000000..892a7432a
--- /dev/null
+++ b/ui/src/components/apps/windowChords.ts
@@ -0,0 +1,29 @@
+// Focus-surface predicates shared by the window keyboard chords (WindowLayer) and
+// the Show Page iframe ⌥W bridge (ShowPageApp). Kept in a leaf module so a
+// lazy-loaded app body can reuse them without importing the WindowLayer component
+// (which would create an import cycle through the app registry).
+//
+// Realm-agnostic by design: the ⌥W bridge passes `iframe.contentDocument.activeElement`
+// from a same-origin Show Page iframe, whose elements live in a DIFFERENT window/realm.
+// `instanceof HTMLElement` is false across realms, so we duck-type on `closest` (present
+// on every Element in any realm) instead — otherwise the input/editor/terminal exemption
+// would never fire inside a Show Page and ⌥W would close the window mid-typing (Codex).
+
+// In the TERMINAL, Ctrl is a control-character stream — ^W deletes a word, ^M is
+// carriage return — so a 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.
+export function inTerminalSurface(el: Element | null): boolean {
+ return !!el?.closest?.('.xterm');
+}
+
+export function inTextEntrySurface(el: Element | null): boolean {
+ // `[contenteditable]:not([contenteditable="false"])` matches every editable form
+ // — `contenteditable`, `="true"`, `="plaintext-only"` — while excluding the
+ // explicitly non-editable `="false"` (Codex): otherwise ⌥W would close the window
+ // while the user types in a `<div contenteditable>` Show Page editor.
+ return !!el?.closest?.(
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], .monaco-editor, .xterm',
+ );
+}
diff --git a/ui/src/components/apps/windowUnload.test.ts b/ui/src/components/apps/windowUnload.test.ts
new file mode 100644
index 000000000..c383f5a44
--- /dev/null
+++ b/ui/src/components/apps/windowUnload.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldGuardUnload } from './windowUnload';
+
+describe('shouldGuardUnload', () => {
+ it('is false when there are no windows', () => {
+ expect(shouldGuardUnload([])).toBe(false);
+ });
+
+ it('is false when every window is minimized', () => {
+ expect(shouldGuardUnload([{ minimized: true }, { minimized: true }])).toBe(false);
+ });
+
+ it('is true when at least one window is not minimized', () => {
+ expect(shouldGuardUnload([{ minimized: false }])).toBe(true);
+ expect(shouldGuardUnload([{ minimized: true }, { minimized: false }])).toBe(true);
+ });
+});
diff --git a/ui/src/components/apps/windowUnload.ts b/ui/src/components/apps/windowUnload.ts
new file mode 100644
index 000000000..682e888e0
--- /dev/null
+++ b/ui/src/components/apps/windowUnload.ts
@@ -0,0 +1,12 @@
+import type { WindowInstance } from '../../context/WindowManagerContext';
+
+/**
+ * Whether the browser's `beforeunload` guard should be armed for the app windows
+ * (§7.1g): true iff at least one window is open AND not minimized. Minimized-only
+ * windows do not arm it (the PM default) — a minimized window carries no visible,
+ * about-to-be-lost surface the user would be surprised to drop on tab-close.
+ * Pure — takes only the `minimized` flag, so it is trivial to unit-test.
+ */
+export function shouldGuardUnload(windows: readonly Pick<WindowInstance, 'minimized'>[]): boolean {
+ return windows.some((win) => !win.minimized);
+}
diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.ts
index b4f1147f4..404e32c10 100644
--- a/ui/src/components/useShowPages.ts
+++ b/ui/src/components/useShowPages.ts
@@ -14,6 +14,10 @@ export interface ShowPage {
platform: string | null;
agent: string | null;
path: string;
+ /** Opaque cache token for the page's own HTML icon (§7.1f): non-null iff a
+ * servable icon exists, and it changes when the icon file changes. Doubles as
+ * the has-icon signal and is appended to the icon URL as `?v=<token>`. */
+ icon_version: string | null;
active_url: string | null;
private_url: string | null;
public_url: string | null;
diff --git a/ui/src/components/workbench/search/AppSearchResults.tsx b/ui/src/components/workbench/search/AppSearchResults.tsx
index efe792688..7166f2d06 100644
--- a/ui/src/components/workbench/search/AppSearchResults.tsx
+++ b/ui/src/components/workbench/search/AppSearchResults.tsx
@@ -53,6 +53,7 @@ export const AppSearchResultSection: React.FC<AppSearchResultSectionProps> = ({
<ShowPageAvatarTile
sessionId={result.sessionId}
title={result.title}
+ iconVersion={result.iconVersion}
className="size-7 rounded-md"
/>
) : (
diff --git a/ui/src/components/workbench/search/appSearch.ts b/ui/src/components/workbench/search/appSearch.ts
index 48ed9624a..86f7353f8 100644
--- a/ui/src/components/workbench/search/appSearch.ts
+++ b/ui/src/components/workbench/search/appSearch.ts
@@ -7,6 +7,8 @@ export type AppSearchResult = {
title: string;
searchTitle: string;
sessionId?: string;
+ /** The AI page icon's opaque cache token, when it has one (§7.1f). */
+ iconVersion?: string | null;
};
export function filterAppSearchResults(results: AppSearchResult[], query: string): AppSearchResult[] {
diff --git a/ui/src/components/workbench/search/useAppSearch.ts b/ui/src/components/workbench/search/useAppSearch.ts
index efe0626ec..de9ae7e5e 100644
--- a/ui/src/components/workbench/search/useAppSearch.ts
+++ b/ui/src/components/workbench/search/useAppSearch.ts
@@ -32,6 +32,7 @@ export function useAppSearchResults(query: string, enabled = true) {
title: liveTitle || t('chat.untitled'),
searchTitle: liveTitle,
sessionId: page.session_id,
+ iconVersion: page.icon_version,
};
}),
],
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 87ff48bc5..de17898fc 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3557,6 +3557,66 @@ def show_page_set_share_id_post(session_id):
return _show_page_error_response(exc)
+def _show_page_icon_not_found():
+ # 404 on any missing page / no icon / policy rejection — the frontend's
+ # onerror -> letter-avatar fallback covers it. No body needed. `no-store` so a
+ # heuristically-cached 404 can't strand the letter fallback on the stable
+ # sid-only URL after the page later adds the icon.
+ response = Response("", status=404, mimetype="text/plain")
+ response.headers["Cache-Control"] = "no-store"
+ return response
+
+
[email protected]("/api/show-pages/<session_id>/icon", methods=["GET", "HEAD"])
+def show_page_icon_get(session_id):
+ # The page's own HTML icon, served as the single chokepoint (§7.1f): ALL href
+ # resolution + policy (document semantics incl. <base>; reject api / traversal /
+ # absolute / root-relative / external / non-image / stock) lives server-side in
+ # resolve_show_page_icon. The `?v=` token NEVER selects the file — resolution is
+ # sid + workspace only — it is validated as a read-time CONTENT ASSERTION so the
+ # stable URL's `immutable` cache is honest. Auth rides the global /api hooks.
+ #
+ # Contract: bytes-or-404, NEVER a 500 — the icon is decorative. A malformed
+ # session id (validate_session_id -> ShowPageError), a page-authored href that
+ # resolves to a filesystem-invalid path (ValueError/OSError), a live-edit swap,
+ # or a token mismatch all degrade to the letter-avatar fallback, never erroring.
+ from core.show_pages import ShowPageError, ShowPageStore, read_show_page_icon
+
+ try:
+ store = ShowPageStore()
+ try:
+ page = store.get(session_id)
+ # Any of the user's own pages — private, public, OR offline — may serve
+ # its static icon: the payload advertises an icon token for all of them
+ # and the inventory lists them, so gating by visibility would strand
+ # offline rows / pinned offline apps on the letter avatar despite an icon.
+ if page is None:
+ return _show_page_icon_not_found()
+ # read_show_page_icon does the race-safe read (O_NOFOLLOW + fstat cap on
+ # the descriptor) and enforces `?v=` as a content assertion — resolution
+ # stays sid-only; the query can never pick a different file.
+ result = read_show_page_icon(page.session_id, request.args.get("v", ""))
+ finally:
+ store.close()
+ if result is None:
+ return _show_page_icon_not_found()
+ data, content_type = result
+ response = Response(data, mimetype=content_type)
+ response.headers["X-Content-Type-Options"] = "nosniff"
+ # A directly-navigated SVG must not execute scripts in the API origin.
+ response.headers["Content-Security-Policy"] = "sandbox"
+ # `immutable` is honest now: `?v=` is enforced against the served bytes, so a
+ # given URL maps to exactly one byte-content — a changed icon gets a new token
+ # → a new URL → a fresh fetch, and the cache can never be poisoned across a
+ # content revert. A plain Response also never honors `Range` (no 206/416).
+ response.headers["Cache-Control"] = "private, max-age=604800, immutable"
+ return response
+ except (ShowPageError, ValueError, OSError):
+ # Enforce the bytes-or-404 contract at the boundary: a bad session id, a bad
+ # page-authored icon, or a file that vanished mid-race must fall back, not 500.
+ return _show_page_icon_not_found()
+
+
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