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): §7.1j Phase 2.5 — icon self-serve (scaffold guidance + upload editor + copy) (#916)

Call White7e12bf5d7d1d
diff --git a/core/show_pages.py b/core/show_pages.py
index ee21066a8..1aa7ad7cf 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -351,7 +351,10 @@ class ShowPageStore:
)
return _page_from_row(row), created
- def _is_archived(self, session_id: str) -> bool:
+ def is_archived(self, session_id: str) -> bool:
+ """Whether the session is archived (terminal). Archived sessions reject Show Page
+ mutations with ``session_archived`` — see ``ensure_active`` / ``update_visibility``
+ / ``set_share_id`` here and the icon-upload guard in ``vibe.api``."""
with self.engine.connect() as conn:
status = conn.execute(
select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
@@ -366,7 +369,7 @@ class ShowPageStore:
# default (private) page row for an archived session — that would leave
# ``/show/<id>/`` enabled for a terminal session. The in-txn check below
# is the atomic authority for the concurrent-archive race.
- if visibility != VISIBILITY_OFFLINE and self._is_archived(session_id):
+ if visibility != VISIBILITY_OFFLINE and self.is_archived(session_id):
raise ShowPageError(
"Cannot republish the Show Page of an archived session.",
code="session_archived",
@@ -404,7 +407,7 @@ class ShowPageStore:
# Same guard as update_visibility, before ``ensure`` materializes a page:
# an archived session is terminal, so its share link can't be rotated /
# re-enabled (and a stale/direct call must not create a default page).
- if self._is_archived(session_id):
+ if self.is_archived(session_id):
raise ShowPageError(
"Cannot rotate the share link of an archived session.",
code="session_archived",
@@ -443,7 +446,7 @@ class ShowPageStore:
# default page for an archived (terminal) session. The in-txn re-reads
# below are the atomic authority for the concurrent-archive / concurrent
# visibility-flip race.
- if self._is_archived(session_id):
+ if self.is_archived(session_id):
raise ShowPageError(
"Cannot change the share link of an archived session.",
code="session_archived",
@@ -706,14 +709,13 @@ def _extract_icon_path(page_dir: Path) -> str | None:
# Workspace-conventional favicon locations, tried IN ORDER when the page declares no
# usable <link rel="icon"> (§7.1h): most agent-built pages ship no link tag at all, so
-# these give them an icon from the common spots — root first, then Vite's public/.
-_CONVENTIONAL_ICON_RELATIVES: tuple[str, ...] = (
- "favicon.svg",
- "favicon.ico",
- "favicon.png",
- "public/favicon.svg",
- "public/favicon.ico",
- "public/favicon.png",
+# these give them an icon from the common spots — root first, then Vite's public/. The
+# extension order (svg vector first, down to raster) covers EVERY uploadable/servable
+# favicon type so an icon uploaded via POST .../icon (§7.1j, which writes favicon.<ext>)
+# is resolved here regardless of its type.
+_CONVENTIONAL_ICON_EXTS: tuple[str, ...] = ("svg", "ico", "png", "webp", "jpg", "jpeg")
+_CONVENTIONAL_ICON_RELATIVES: tuple[str, ...] = tuple(
+ f"{prefix}favicon.{ext}" for prefix in ("", "public/") for ext in _CONVENTIONAL_ICON_EXTS
)
@@ -842,6 +844,141 @@ def read_show_page_icon(session_id: str, expected_version: str) -> tuple[bytes,
return data, content_type
+# --- Icon self-serve upload (§7.1j) -------------------------------------------------
+# A user can upload an image from the App Library as a page's icon. The upload writes
+# the workspace-root CONVENTIONAL favicon (favicon.<ext>) that resolve_show_page_icon
+# already picks up (§7.1h) — so the SERVER chooses the on-disk name and the client
+# never supplies a path. It is the inverse of the read side and shares the same cap +
+# whitelist; index.html is never edited, so an explicit usable <link rel=icon> still
+# WINS (§7.1f resolution order) — the editor just covers the common no-link case.
+#
+# Public so the ui_server upload route can size the multipart parser / Content-Length
+# guard from the same number write_show_page_icon re-checks the actual bytes against.
+SHOW_PAGE_ICON_MAX_UPLOAD_BYTES = _ICON_MAX_BYTES # 2 MiB
+# Accepted upload content-types -> the single canonical on-disk extension. The owner's
+# whitelist (§7.1j) is svg/png/ico/jpg/jpeg/webp — a subset of the servable set (no gif).
+_ICON_UPLOAD_CONTENT_TYPE_EXT = {
+ "image/svg+xml": "svg",
+ "image/png": "png",
+ "image/x-icon": "ico",
+ "image/vnd.microsoft.icon": "ico",
+ "image/jpeg": "jpg",
+ "image/webp": "webp",
+}
+# Accepted filename extensions -> canonical on-disk extension (jpeg folds to jpg).
+_ICON_UPLOAD_NAME_EXT = {
+ "svg": "svg",
+ "png": "png",
+ "ico": "ico",
+ "jpg": "jpg",
+ "jpeg": "jpg",
+ "webp": "webp",
+}
+
+
+def _canonical_upload_icon_ext(filename: str | None, content_type: str | None) -> str | None:
+ """The one on-disk extension for an uploaded icon, or None if it isn't whitelisted.
+
+ Derived from the content-type first, then the filename suffix (jpeg→jpg). A
+ recognizable, whitelisted signal that DISAGREES with the other is refused (a PNG
+ announced as ``image/svg+xml`` is suspicious), so the server writes exactly the type
+ it validated. Falling back to the filename is limited to a BLANK or generic
+ (``application/octet-stream``) content-type: an EXPLICIT, non-generic type that isn't
+ a whitelisted image is a rejection signal (a ``text/html`` body named ``logo.svg`` is
+ not an icon), not something to accept on the extension alone. None → the route answers
+ 415 rather than guessing an extension."""
+ raw_type = (content_type or "").split(";", 1)[0].strip().lower()
+ type_ext = _ICON_UPLOAD_CONTENT_TYPE_EXT.get(raw_type)
+ if type_ext is None and raw_type and raw_type != "application/octet-stream":
+ return None # an explicit, non-image content-type → reject, don't trust the name
+ name_ext = _ICON_UPLOAD_NAME_EXT.get(Path(filename or "").suffix.lower().lstrip("."))
+ if type_ext and name_ext and type_ext != name_ext:
+ return None
+ return type_ext or name_ext
+
+
+def _unlink_quietly(path: Path) -> None:
+ """Remove a directory ENTRY (a symlink is unlinked itself, never followed), ignoring
+ a missing / again-racing target. Used to clear old favicon.* before an atomic write."""
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+
+
+def _write_root_favicon_atomically(page_dir: Path, ext: str, data: bytes) -> None:
+ """Write ``<page_dir>/favicon.<ext>`` as the SOLE conventional root icon, safely, and
+ WITHOUT destroying the existing icon unless the replacement actually lands.
+
+ The new bytes go to a fresh ``O_EXCL | O_NOFOLLOW`` temp and are atomically
+ ``os.replace``d onto ``favicon.<ext>`` FIRST — so a failure while opening/writing the
+ temp or replacing (e.g. disk full mid-upload) raises with every existing favicon still
+ in place (no data loss — §7.1j review P2). ONLY AFTER the new file lands are the
+ OTHER-extension root ``favicon.*`` removed, leaving exactly one conventional source
+ (e.g. a prior ``favicon.svg`` after uploading ``favicon.png``, which would otherwise
+ shadow it in the resolver's svg>ico>png>… order). ``os.replace`` swaps the final NAME
+ without following a symlink raced back in, and no reader sees a half-written icon.
+ Threat model: the racing party is the user's own agent with local FS access, so the
+ swap guards are defense-in-depth, not a boundary — but a symlinked/partial favicon
+ must never become servable."""
+ target = page_dir / f"favicon.{ext}"
+ tmp = page_dir / f".favicon.{ext}.{secrets.token_hex(8)}.tmp"
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
+ fd = os.open(tmp, flags, 0o644)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ # Atomic: overwrites any existing favicon.<ext> in place (a symlink at the name is
+ # replaced, not followed). Old favicons of every extension are still intact here.
+ os.replace(tmp, target)
+ except BaseException:
+ _unlink_quietly(tmp)
+ raise
+ # The replacement has landed — now drop the OTHER-extension root favicons so exactly
+ # one conventional source remains. Done last so a failed write above never orphans the
+ # page icon-less. EXCEPT a root favicon the page explicitly links from index.html:
+ # deleting it would 404 the page's own <link rel=icon> (which still WINS in the
+ # resolver — we never edit index.html), so preserve that one (§7.1j review P2).
+ linked = _extract_icon_path(page_dir)
+ for servable_ext in SHOW_PAGE_ICON_CONTENT_TYPES:
+ if servable_ext == ext:
+ continue
+ sibling_rel = f"favicon.{servable_ext}"
+ if sibling_rel == linked:
+ continue
+ _unlink_quietly(page_dir / sibling_rel)
+
+
+def write_show_page_icon(
+ session_id: str, data: bytes, *, filename: str | None, content_type: str | None
+) -> str | None:
+ """Write an uploaded image as the page's workspace-root conventional favicon, and
+ return the FRESH ``icon_version`` (§7.1j icon self-serve).
+
+ The SERVER derives the on-disk name (``favicon.<ext>``) from the whitelisted
+ content-type/extension — the client NEVER supplies a path — enforces the 2 MiB cap,
+ and writes atomically without following a symlink (see
+ :func:`_write_root_favicon_atomically`). ``index.html`` is not touched, so a usable
+ explicit ``<link rel=icon>`` still WINS in :func:`resolve_show_page_icon` and the
+ returned version reflects whatever now resolves. Raises :class:`ShowPageError`
+ (mapped to a 4xx by the route) for a malformed id / non-whitelisted type / empty or
+ oversized payload; never a 500."""
+ validate_session_id(session_id)
+ ext = _canonical_upload_icon_ext(filename, content_type)
+ if ext is None:
+ raise ShowPageError(
+ "The icon must be an SVG, PNG, ICO, JPEG, or WebP image.", code="invalid_icon_type"
+ )
+ if not data:
+ raise ShowPageError("The icon file is empty.", code="icon_required")
+ if len(data) > SHOW_PAGE_ICON_MAX_UPLOAD_BYTES:
+ raise ShowPageError("The icon file is too large (max 2 MiB).", code="icon_too_large")
+ page_dir = show_page_dir(session_id)
+ page_dir.mkdir(parents=True, exist_ok=True)
+ _write_root_favicon_atomically(page_dir, ext, data)
+ return show_page_icon_version(session_id)
+
+
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)
@@ -917,6 +1054,15 @@ def _default_index_html(session_id: str) -> str:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Show Page {escaped}</title>
+ <!-- App icon (Avibe Dock / App Library): to give this app an icon, place a
+ favicon FILE in this workspace — either `favicon.svg` (or .png/.ico) at the
+ workspace root, or a `<link rel="icon" href="./your-icon.svg">` in this
+ <head> pointing at a RELATIVE file here. Avibe reads that static FILE to
+ render the app tile. Do NOT inject the icon from JavaScript at runtime
+ (e.g. appending a <link> in a script): the icon is resolved from the file
+ on disk, so a script-created one is never picked up. You can also upload one
+ from the App Library (the AI page's expanded panel), which writes the
+ workspace-root favicon for you. -->
<!-- PWA: let a user "Add to Home Screen" this Show Page as a standalone app.
We declare it standalone-capable but DELIBERATELY ship no apple-touch-icon
or apple-mobile-web-app-title here. A page customizes its installed icon
diff --git a/docs/plans/dock-pinned-show-page-apps.md b/docs/plans/dock-pinned-show-page-apps.md
index 070124306..85c11e2eb 100644
--- a/docs/plans/dock-pinned-show-page-apps.md
+++ b/docs/plans/dock-pinned-show-page-apps.md
@@ -130,6 +130,7 @@ 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 /api/show-pages/{session_id}/icon (multipart file) → { ok, ...page } # §7.1j
```
- `POST pins` appends `show:<sid>` to the end of `order`; captures
@@ -144,6 +145,16 @@ GET|HEAD /api/show-pages/{session_id}/icon → 200 image bytes | 404 # §7.1
`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.
+- `POST /api/show-pages/{sid}/icon` (§7.1j, **multipart**): uploads an image as the
+ page's workspace-root conventional favicon. The **server** chooses the on-disk name
+ — `favicon.<ext>`, `ext` derived from a whitelisted content-type/extension
+ (`svg,png,ico,jpg,jpeg,webp`) — so the client NEVER supplies a path; 2 MiB cap;
+ write-safe (removes sibling root `favicon.*` so one source remains, no symlink
+ follow, atomic replace); index.html is never edited. Returns the refreshed page
+ payload (incl. the new `icon_version`). Errors are structured 4xx (`invalid_icon_type`
+ 415, `icon_too_large` 413, `icon_required` 400, `show_page_not_found` 404) — never a
+ 500. An explicit usable `<link rel=icon>` in index.html still WINS over the uploaded
+ conventional file (§7.1f resolution order); the editor covers the common no-link case.
## 5. Frontend Changes (map to real files)
@@ -641,6 +652,49 @@ alongside §7.1h item 3), in `AppWindow.tsx` + `WindowManagerContext.tsx`:
vitest DOM-structure coverage. The real gesture FEEL is verified by the owner
via CDP on the regression env post-merge (residual manual check).
+### 7.1j Phase 2.5 — icon self-serve (owner 2026-07-15 23:04)
+
+1. **Scaffold head comment** (English, in the default Show Page template's
+ `<head>`): to give the app an icon, place a favicon FILE (e.g.
+ `favicon.svg` at the workspace root or a `<link rel="icon">` to a relative
+ file) — do NOT inject icons dynamically via JS; the file becomes the app
+ icon in the Dock / App Library. Rationale: the rule lives in the artifact
+ agents actually edit (no prompt verbosity); closes the JS-injection blind
+ spot at the source.
+2. **Icon editor beside the page rename** (AI view expanded panel): shorten
+ the name input; add current-icon preview + upload/replace control. Upload
+ writes the workspace-root conventional favicon file (server-chosen fixed
+ name `favicon.<ext>`; replaces siblings to keep one source). New authed
+ endpoint `POST /api/show-pages/<sid>/icon` (multipart): extension+type
+ whitelist, 2MiB cap, write-safe (no symlink follow, fixed name — client
+ never names paths), returns fresh `icon_version`. Ledger: an explicit
+ usable `<link rel=icon>` still wins over the uploaded conventional file
+ (we do not edit user HTML).
+3. **Copy**: the Library 移出 button text → 「移出 App」 (en aligned, e.g.
+ "Remove App").
+
+**Hardening (review round 1, 2026-07-16 — #916):** four Codex findings, all fixed:
+- **Preserve the old icon until the new write lands (P2):** the write reorders to
+ temp → atomic `os.replace` → *then* remove the other-extension root `favicon.*`, so a
+ failed/partial write (e.g. disk full) never deletes the user's existing icon first.
+- **Cross-surface freshness (P2):** a successful upload broadcasts a `session.activity`
+ `show_event`, so every already-mounted inventory (Dock, WindowLayer, mobile drawer,
+ ⌘K search) reloads and picks up the new `icon_version` — not just the Library instance
+ that ran the upload (its optimistic `mergePage` is local).
+- **Preserve the too-large path (P3):** the Content-Length guard's `too_large` keeps its
+ `icon_too_large`/413 mapping instead of collapsing to a generic `invalid_icon`/400.
+- **Reject explicit non-image content types (P3):** an explicit, non-generic MIME that is
+ not a whitelisted image is refused even when the filename extension is whitelisted;
+ filename fallback is limited to blank / `application/octet-stream` types.
+
+**Hardening (review round 2, 2026-07-16 — #916):** two more P2 findings, fixed:
+- **Preserve an explicitly-linked root favicon (P2):** the sibling cleanup skips a root
+ `favicon.*` that `index.html` links via `<link rel=icon>` — deleting it would 404 the
+ page's own favicon while the explicit link keeps winning in the resolver.
+- **Reject icon uploads for archived sessions (P2):** `upload_show_page_icon` rejects an
+ archived session with `session_archived` (the store's `is_archived` check is promoted to
+ public), matching every other Show Page mutator's archived guard.
+
### 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 fa887ee2d..df46d54ae 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -719,6 +719,14 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):
# Must NOT link the workbench manifest — its start_url "/" would hijack the
# installed Home Screen icon back to the workbench instead of this page.
assert 'rel="manifest"' not in index_html
+ # §7.1j: the App-icon self-serve guidance lives in the artifact the agent edits.
+ # It must tell the author to give the app its Dock / App Library icon via a static
+ # FILE (favicon at root or a relative <link rel=icon>), NOT a JS-injected one —
+ # closing the JS-injection blind spot at the source. This <head> comment holds a
+ # `<link rel="icon">` EXAMPLE, but it is inside an HTML comment, so the scaffold
+ # still resolves to no icon (see test_extract_icon_path_stock_scaffold_index_is_null).
+ assert "App icon (Avibe Dock / App Library)" in index_html
+ assert "Do NOT inject the icon from JavaScript" in index_html
main_tsx = (page_dir / "src" / "main.tsx").read_text(encoding="utf-8")
assert "globalThis.__AVIBE_SHOW__" in main_tsx
assert "declare global" in main_tsx
@@ -1252,6 +1260,224 @@ def test_read_workspace_file_safely_refuses_non_regular_fifo(tmp_path):
assert _read_workspace_file_safely(fifo, 100, cap=True) is None
+# --- Icon self-serve upload (§7.1j) -------------------------------------------------
+
+# (upload filename, content-type) -> the canonical on-disk extension the server writes.
+_ICON_UPLOAD_CASES = (
+ ("icon.svg", "image/svg+xml", "svg"),
+ ("icon.png", "image/png", "png"),
+ ("icon.ico", "image/x-icon", "ico"),
+ ("icon.jpg", "image/jpeg", "jpg"),
+ ("icon.jpeg", "image/jpeg", "jpg"), # jpeg folds to the single canonical jpg
+ ("icon.webp", "image/webp", "webp"),
+)
+
+
[email protected]("filename, content_type, canonical", _ICON_UPLOAD_CASES)
+def test_write_show_page_icon_happy_path_per_extension(monkeypatch, tmp_path, filename, content_type, canonical):
+ # Each whitelisted type writes the SERVER-chosen workspace-root favicon.<ext> (the
+ # client never supplies a path) and becomes the resolved, servable icon (§7.1j).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ version = write_show_page_icon("sesup", b"<bytes>", filename=filename, content_type=content_type)
+
+ page_dir = show_page_dir("sesup")
+ target = page_dir / f"favicon.{canonical}"
+ assert target.is_file() and target.read_bytes() == b"<bytes>"
+ resolved = resolve_show_page_icon("sesup")
+ assert resolved is not None and resolved[0] == target.resolve()
+ assert isinstance(version, str) and version # a fresh non-empty token
+
+
+def test_write_show_page_icon_derives_ext_from_filename_when_type_generic(monkeypatch, tmp_path):
+ # Browsers sometimes send a generic/blank content-type for .ico/.svg; the filename
+ # extension is the fallback signal, still whitelisted.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import show_page_dir, write_show_page_icon
+
+ write_show_page_icon("sesgen", b"i", filename="brand.ico", content_type="application/octet-stream")
+ assert (show_page_dir("sesgen") / "favicon.ico").is_file()
+
+
+def test_write_show_page_icon_rejects_non_whitelisted_type(monkeypatch, tmp_path):
+ # A non-image type (or extension) is refused with a clear code and writes NOTHING.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import show_page_dir, write_show_page_icon
+
+ with pytest.raises(ShowPageError) as excinfo:
+ write_show_page_icon("sesbad", b"<html>", filename="evil.html", content_type="text/html")
+ assert excinfo.value.code == "invalid_icon_type"
+ # A content-type that disagrees with a whitelisted extension is also refused.
+ with pytest.raises(ShowPageError):
+ write_show_page_icon("sesbad", b"x", filename="icon.svg", content_type="image/png")
+ # A whitelisted extension can't smuggle an explicit non-image content-type through.
+ with pytest.raises(ShowPageError):
+ write_show_page_icon("sesbad", b"x", filename="logo.svg", content_type="text/html")
+ assert not any((show_page_dir("sesbad")).glob("favicon.*"))
+
+
+def test_write_show_page_icon_rejects_empty_and_oversized(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_pages._ICON_MAX_BYTES", 8)
+ monkeypatch.setattr("core.show_pages.SHOW_PAGE_ICON_MAX_UPLOAD_BYTES", 8)
+ from core.show_pages import write_show_page_icon
+
+ with pytest.raises(ShowPageError) as empty:
+ write_show_page_icon("sescap", b"", filename="i.svg", content_type="image/svg+xml")
+ assert empty.value.code == "icon_required"
+ with pytest.raises(ShowPageError) as big:
+ write_show_page_icon("sescap", b"x" * 9, filename="i.svg", content_type="image/svg+xml")
+ assert big.value.code == "icon_too_large"
+
+
+def test_write_show_page_icon_removes_sibling_root_favicons(monkeypatch, tmp_path):
+ # Exactly ONE conventional source must remain, so a stale root favicon.svg can't
+ # shadow the freshly-uploaded favicon.ico in the resolver's svg>ico>png order.
+ # Sibling root variants go; a public/ copy (tried only after root) is left alone.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ page_dir = show_page_dir("sessib")
+ (page_dir / "public").mkdir(parents=True)
+ (page_dir / "favicon.svg").write_text("<svg>old</svg>", encoding="utf-8")
+ (page_dir / "favicon.png").write_bytes(b"oldpng")
+ (page_dir / "public" / "favicon.svg").write_text("<svg>pub</svg>", encoding="utf-8")
+
+ write_show_page_icon("sessib", b"NEWICO", filename="new.ico", content_type="image/x-icon")
+
+ assert not (page_dir / "favicon.svg").exists()
+ assert not (page_dir / "favicon.png").exists()
+ assert (page_dir / "favicon.ico").read_bytes() == b"NEWICO"
+ assert (page_dir / "public" / "favicon.svg").exists() # a non-sibling copy is untouched
+ resolved = resolve_show_page_icon("sessib")
+ assert resolved is not None and resolved[0] == (page_dir / "favicon.ico").resolve()
+
+
+def test_write_show_page_icon_preserves_explicitly_linked_root_favicon(monkeypatch, tmp_path):
+ # The sibling cleanup must NOT delete a root favicon the page explicitly links from
+ # index.html when a different extension is uploaded — the explicit link keeps winning
+ # (we never edit index.html), so deleting it would 404 the page's own favicon (P2).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ page_dir = ensure_show_page_dir("seskeep")
+ (page_dir / "index.html").write_text('<link rel="icon" href="favicon.png">', encoding="utf-8")
+ (page_dir / "favicon.png").write_bytes(b"LINKED-PNG")
+
+ write_show_page_icon("seskeep", b"<svg>UP</svg>", filename="i.svg", content_type="image/svg+xml")
+
+ # The explicitly-linked favicon.png survives; the uploaded favicon.svg is written but
+ # dormant, and the explicit link still resolves.
+ assert (page_dir / "favicon.png").read_bytes() == b"LINKED-PNG"
+ assert (page_dir / "favicon.svg").read_bytes() == b"<svg>UP</svg>"
+ resolved = resolve_show_page_icon("seskeep")
+ assert resolved is not None and resolved[0] == (page_dir / "favicon.png").resolve()
+
+
+def test_write_show_page_icon_does_not_follow_symlink_at_target(monkeypatch, tmp_path):
+ # A symlink placed at the favicon name must NOT be written through: the write
+ # unlinks it first and lands a fresh regular file, so an outside target is
+ # untouched and the served icon is the uploaded bytes (defense-in-depth, §7.1j).
+ if not hasattr(os, "O_NOFOLLOW"):
+ pytest.skip("O_NOFOLLOW / symlink semantics not available on this platform")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ page_dir = show_page_dir("seslnk")
+ page_dir.mkdir(parents=True)
+ outside = tmp_path / "outside.svg"
+ outside.write_text("<svg>SECRET-OUTSIDE</svg>", encoding="utf-8")
+ os.symlink(outside, page_dir / "favicon.svg")
+
+ write_show_page_icon("seslnk", b"<svg>MINE</svg>", filename="i.svg", content_type="image/svg+xml")
+
+ favicon = page_dir / "favicon.svg"
+ assert not favicon.is_symlink() # the symlink entry was replaced, not followed
+ assert favicon.read_bytes() == b"<svg>MINE</svg>"
+ assert outside.read_text(encoding="utf-8") == "<svg>SECRET-OUTSIDE</svg>" # never written through
+ resolved = resolve_show_page_icon("seslnk")
+ assert resolved is not None and resolved[0] == favicon.resolve()
+
+
+def test_write_show_page_icon_preserves_old_favicon_on_write_failure(monkeypatch, tmp_path):
+ # A failure while the replacement lands (e.g. disk full during os.replace) must NOT
+ # destroy the user's existing icon — old favicons stay until the new one succeeds, and
+ # the other-ext cleanup only runs afterwards, so a prior favicon.png survives (§7.1j P2).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ page_dir = show_page_dir("sesfail")
+ page_dir.mkdir(parents=True)
+ (page_dir / "favicon.png").write_bytes(b"OLD-PNG")
+
+ def _boom(*_args, **_kwargs):
+ raise OSError("disk full")
+
+ monkeypatch.setattr("core.show_pages.os.replace", _boom)
+
+ with pytest.raises(OSError):
+ write_show_page_icon("sesfail", b"<svg>NEW</svg>", filename="i.svg", content_type="image/svg+xml")
+
+ # The old icon (a different extension) survives and still resolves; no temp is orphaned.
+ assert (page_dir / "favicon.png").read_bytes() == b"OLD-PNG"
+ assert not (page_dir / "favicon.svg").exists()
+ assert not list(page_dir.glob(".favicon.*.tmp"))
+ resolved = resolve_show_page_icon("sesfail")
+ assert resolved is not None and resolved[0] == (page_dir / "favicon.png").resolve()
+
+
+def test_write_show_page_icon_version_changes_on_replace(monkeypatch, tmp_path):
+ # Re-uploading different bytes changes icon_version (the content-versioned URL busts
+ # the cache); identical bytes keep it stable — the freshness invariant on the write.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import write_show_page_icon
+
+ v1 = write_show_page_icon("sesver", b"<svg>1</svg>", filename="i.svg", content_type="image/svg+xml")
+ v2 = write_show_page_icon("sesver", b"<svg>2-longer</svg>", filename="i.svg", content_type="image/svg+xml")
+ assert v1 and v2 and v1 != v2
+ v3 = write_show_page_icon("sesver", b"<svg>2-longer</svg>", filename="i.svg", content_type="image/svg+xml")
+ assert v3 == v2 # identical bytes → identical token (cache hit)
+
+
+def test_write_show_page_icon_explicit_link_still_wins(monkeypatch, tmp_path):
+ # Ledger (§7.1j): we never edit index.html, so a USABLE explicit <link rel=icon>
+ # keeps winning in resolve order over the uploaded conventional favicon — the
+ # editor only covers the common no-link case.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.show_pages import resolve_show_page_icon, show_page_dir, write_show_page_icon
+
+ page_dir = ensure_show_page_dir("sesuplink")
+ (page_dir / "index.html").write_text('<link rel="icon" href="brand.svg">', encoding="utf-8")
+ (page_dir / "brand.svg").write_text("<svg>brand</svg>", encoding="utf-8")
+
+ write_show_page_icon("sesuplink", b"<svg>uploaded</svg>", filename="i.svg", content_type="image/svg+xml")
+
+ # The uploaded favicon.svg exists on disk, but the explicit link still resolves.
+ assert (page_dir / "favicon.svg").read_bytes() == b"<svg>uploaded</svg>"
+ resolved = resolve_show_page_icon("sesuplink")
+ assert resolved is not None and resolved[0] == (page_dir / "brand.svg").resolve()
+
+
+def test_canonical_upload_icon_ext_rules():
+ from core.show_pages import _canonical_upload_icon_ext
+
+ # Content-type is authoritative; filename is the fallback; jpeg folds to jpg.
+ assert _canonical_upload_icon_ext("x.png", "image/png") == "png"
+ assert _canonical_upload_icon_ext("x.JPEG", None) == "jpg"
+ assert _canonical_upload_icon_ext(None, "image/webp") == "webp"
+ assert _canonical_upload_icon_ext("x.ico", "image/vnd.microsoft.icon") == "ico"
+ # Not whitelisted, or a recognizable type/extension that disagree → None (415).
+ assert _canonical_upload_icon_ext("x.gif", "image/gif") is None # gif is servable, not uploadable
+ assert _canonical_upload_icon_ext("x.txt", "text/plain") is None
+ assert _canonical_upload_icon_ext("x.svg", "image/png") is None # mismatch
+ # An EXPLICIT non-image content-type is rejected even with a whitelisted extension;
+ # only a blank / generic (octet-stream) type falls back to the filename (Codex P3).
+ assert _canonical_upload_icon_ext("logo.svg", "text/html") is None
+ assert _canonical_upload_icon_ext("logo.svg", "application/octet-stream") == "svg"
+ assert _canonical_upload_icon_ext("logo.svg", "") == "svg"
+
+
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 ba1fc4a9c..db66067e0 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -19,6 +19,7 @@ from core.show_pages import (
)
from core.show_runtime import ShowRuntimeManager, _runtime_platform_tag, _safe_extract_tar, set_show_runtime_manager_for_tests
from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_config
+from tests.ui_server_test_helpers import csrf_headers
from vibe import remote_access, ui_server
from vibe.ui_server import app
@@ -110,7 +111,7 @@ def _create_show_page_record(session_id: str, visibility: str) -> str | None:
store.close()
-def _create_agent_session(session_id: str) -> None:
+def _create_agent_session(session_id: str, *, status: str = "active") -> None:
from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -130,7 +131,7 @@ def _create_agent_session(session_id: str) -> None:
agent_variant="default",
session_anchor="anchor_" + session_id,
native_session_id="",
- status="active",
+ status=status,
metadata_json="{}",
created_at=now,
updated_at=now,
@@ -584,6 +585,138 @@ def test_show_page_icon_endpoint_404_when_target_missing(monkeypatch, tmp_path):
assert response.status_code == 404
+def test_show_page_icon_upload_happy_path(monkeypatch, tmp_path):
+ # §7.1j: a multipart upload writes the workspace-root favicon and returns the
+ # refreshed payload (fresh icon_version) so the Web UI merges it like any other
+ # show-page mutation. The server chose the on-disk name from the type — the client
+ # only sent bytes + a filename.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private") # index.html has no <link rel=icon>
+ published: list = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data))
+ )
+ client = app.test_client()
+
+ response = client.post(
+ "/api/show-pages/ses123/icon",
+ files={"file": ("logo.svg", b"<svg>UPLOADED</svg>", "image/svg+xml")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["ok"] is True
+ assert body["session_id"] == "ses123"
+ assert isinstance(body["icon_version"], str) and body["icon_version"]
+ # The server chose favicon.svg at the workspace root and wrote the exact bytes.
+ assert (ensure_show_page_dir("ses123") / "favicon.svg").read_bytes() == b"<svg>UPLOADED</svg>"
+ # Every already-mounted inventory (Dock, WindowLayer, mobile drawer, search) reloads:
+ # a session.activity show_event is broadcast so they pick up the new icon (§7.1j P2).
+ assert ("session.activity", {"session_id": "ses123", "scope_id": None, "event": "show_event"}) in published
+
+
+def test_show_page_icon_upload_length_guard_maps_too_large(monkeypatch, tmp_path):
+ # The Content-Length guard rejects an oversized body (413) BEFORE the multipart parser
+ # runs; that too_large must surface as icon_too_large/413, not collapse to a generic
+ # invalid_icon/400 like a non-multipart body would (§7.1j review P3).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ from core.file_browser_service import FileBrowserError
+
+ def _too_large(*_args, **_kwargs):
+ raise FileBrowserError("too_large", "File is too large", 413)
+
+ monkeypatch.setattr("vibe.ui_server._validate_file_upload_content_length", _too_large)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/show-pages/ses123/icon",
+ files={"file": ("logo.svg", b"<svg/>", "image/svg+xml")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json()["error"]["code"] == "icon_too_large"
+
+
+def test_show_page_icon_upload_rejects_bad_type(monkeypatch, tmp_path):
+ # A non-image type is a clean 415 (never a 500); nothing is written.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ client = app.test_client()
+
+ response = client.post(
+ "/api/show-pages/ses123/icon",
+ files={"file": ("evil.html", b"<html></html>", "text/html")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 415
+ assert response.get_json()["error"]["code"] == "invalid_icon_type"
+ assert not list(ensure_show_page_dir("ses123").glob("favicon.*"))
+
+
+def test_show_page_icon_upload_unknown_page_is_404(monkeypatch, tmp_path):
+ # Uploading to a session with no Show Page is a structured 404, not a 500.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/show-pages/sesnone/icon",
+ files={"file": ("logo.svg", b"<svg/>", "image/svg+xml")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 404
+ assert response.get_json()["error"]["code"] == "show_page_not_found"
+
+
+def test_show_page_icon_upload_rejects_archived_session(monkeypatch, tmp_path):
+ # An archived session's page is terminal — the other mutators reject it with
+ # session_archived, so a direct icon upload must too, not write into the workspace
+ # (§7.1j review P2). Create the page first (while no session row exists → not archived),
+ # then insert the archived session row.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("sesarch", "private")
+ _create_agent_session("sesarch", status="archived")
+ client = app.test_client()
+
+ response = client.post(
+ "/api/show-pages/sesarch/icon",
+ files={"file": ("logo.svg", b"<svg/>", "image/svg+xml")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["error"]["code"] == "session_archived"
+ assert not (ensure_show_page_dir("sesarch") / "favicon.svg").exists()
+
+
+def test_show_page_icon_upload_requires_remote_login(monkeypatch, tmp_path):
+ # Auth parity with the rest of /api: a remote request without a session is bounced
+ # by the same before-request hook (never reaches the handler, so nothing is written).
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+
+ response = app.test_client().post(
+ "/api/show-pages/ses123/icon",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ files={"file": ("logo.svg", b"<svg/>", "image/svg+xml")},
+ follow_redirects=False,
+ )
+
+ assert response.status_code != 200
+ assert not (ensure_show_page_dir("ses123") / "favicon.svg").exists()
+
+
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
diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsx
index b4a100603..f42a43f60 100644
--- a/ui/src/components/ShowPagesPage.tsx
+++ b/ui/src/components/ShowPagesPage.tsx
@@ -6,6 +6,7 @@ import {
ChevronUp,
Copy,
ExternalLink,
+ ImageUp,
Link2,
Loader2,
Minus,
@@ -56,6 +57,7 @@ interface RowProps {
onToggleExpand: () => void;
onToggleInstall: (next: boolean) => void;
onRename: (title: string | null) => Promise<void>;
+ onUploadIcon: (file: File) => Promise<void>;
onSetVisibility: (visibility: Visibility) => void;
onRotate: () => void;
onCopy: () => void;
@@ -73,6 +75,7 @@ function ShowPageRow({
onToggleExpand,
onToggleInstall,
onRename,
+ onUploadIcon,
onSetVisibility,
onRotate,
onCopy,
@@ -190,7 +193,12 @@ function ShowPageRow({
<div className="bg-surface-2 px-5 pb-6 pt-2">
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_300px]">
<div className="flex flex-col gap-5">
- <InlineTitleRename page={page} disabled={busy} onRename={onRename} />
+ {/* Name + app-icon editor side by side (§7.1j): the name field is
+ intentionally narrow now, leaving room for the icon preview + upload. */}
+ <div className="flex flex-wrap items-start gap-x-6 gap-y-4">
+ <InlineTitleRename page={page} disabled={busy} onRename={onRename} />
+ <IconEditor page={page} disabled={busy} onUploadIcon={onUploadIcon} />
+ </div>
<div className="flex flex-col gap-2">
<span className={LABEL}>{t('showPages.visibilityLabel')}</span>
@@ -368,10 +376,10 @@ const InlineTitleRename: React.FC<{
}}
placeholder={t('chat.titlePlaceholder')}
aria-label={t('showPages.nameLabel')}
- className="h-9 max-w-[360px] px-3 text-[13px]"
+ className="h-9 w-[240px] max-w-full px-3 text-[13px]"
/>
) : (
- <div className="flex max-w-[360px] items-center gap-2 rounded-lg border border-border bg-foreground/[0.03] px-3 py-2">
+ <div className="flex w-[240px] max-w-full items-center gap-2 rounded-lg border border-border bg-foreground/[0.03] px-3 py-2">
<span className="min-w-0 flex-1 truncate text-[13px] text-foreground">
{page.title?.trim() || t('chat.untitled')}
</span>
@@ -391,6 +399,63 @@ const InlineTitleRename: React.FC<{
);
};
+// Image types the picker accepts, aligned with the server's upload whitelist (§7.1j).
+// The server derives the on-disk name from the type/extension; the client only sends
+// the bytes + filename, so no path is ever composed here.
+const ICON_UPLOAD_ACCEPT = 'image/svg+xml,image/png,image/x-icon,image/vnd.microsoft.icon,image/jpeg,image/webp,.svg,.png,.ico,.jpg,.jpeg,.webp';
+
+// The app-icon preview + upload/replace control, sitting beside the name field in the
+// expanded panel (§7.1j). The preview reuses the shared avatar tile (icon-or-letter,
+// content-versioned), so on a successful upload the returned icon_version flows through
+// the inventory and the preview refetches with no extra wiring.
+const IconEditor: React.FC<{
+ page: ShowPage;
+ disabled: boolean;
+ onUploadIcon: (file: File) => Promise<void>;
+}> = ({ page, disabled, onUploadIcon }) => {
+ const { t } = useTranslation();
+ const [uploading, setUploading] = useState(false);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const hasIcon = Boolean(page.icon_version);
+
+ const pick = () => {
+ if (disabled || uploading) return;
+ inputRef.current?.click();
+ };
+ const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ event.target.value = ''; // let the same file be re-picked after a failed attempt
+ if (!file) return;
+ setUploading(true);
+ void onUploadIcon(file)
+ .catch(() => undefined)
+ .finally(() => setUploading(false));
+ };
+
+ return (
+ <div className="flex flex-col gap-2">
+ <span className={LABEL}>{t('showPages.iconLabel')}</span>
+ <div className="flex items-center gap-2">
+ <ShowPageAvatarTile sessionId={page.session_id} title={page.title || ''} iconVersion={page.icon_version} />
+ <Button type="button" variant="secondary" size="sm" onClick={pick} disabled={disabled || uploading}>
+ {uploading ? <Loader2 className="size-3.5 animate-spin" /> : <ImageUp className="size-3.5" />}
+ {hasIcon ? t('showPages.icon.replace') : t('showPages.icon.upload')}
+ </Button>
+ <input
+ ref={inputRef}
+ type="file"
+ accept={ICON_UPLOAD_ACCEPT}
+ className="hidden"
+ onChange={onChange}
+ aria-hidden
+ tabIndex={-1}
+ />
+ </div>
+ <span className="max-w-[240px] text-[11px] text-muted">{t('showPages.icon.hint')}</span>
+ </div>
+ );
+};
+
// The full Show Pages inventory view (the "AI" tab): search + visibility filter +
// rows that OPEN the page as an app window on click, each with a state-aware
// install toggle (添加到 App ↔ 移出) and an explicit chevron for the share-link
@@ -403,6 +468,7 @@ export function ShowPagesView({
setVisibility,
rotate,
rename,
+ uploadIcon,
onShareIdSaved,
reload,
onOpenApp,
@@ -499,6 +565,7 @@ export function ShowPagesView({
onToggleExpand={() => setExpandedId((id) => (id === page.session_id ? null : page.session_id))}
onToggleInstall={(next) => (next ? pin(page.session_id) : unpin(page.session_id))}
onRename={(title) => rename(page, title)}
+ onUploadIcon={(file) => uploadIcon(page, file)}
onSetVisibility={(visibility) => setVisibility(page, visibility)}
onRotate={() => rotate(page)}
onCopy={() => copy(page)}
diff --git a/ui/src/components/useShowPages.test.ts b/ui/src/components/useShowPages.test.ts
index b63eca120..50a0cc2ae 100644
--- a/ui/src/components/useShowPages.test.ts
+++ b/ui/src/components/useShowPages.test.ts
@@ -9,6 +9,7 @@ const page = (title: string | null): ShowPage => ({
platform: null,
agent: null,
path: '/tmp/show',
+ icon_version: null,
active_url: null,
private_url: null,
public_url: null,
diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.ts
index 404e32c10..1f3a0fdca 100644
--- a/ui/src/components/useShowPages.ts
+++ b/ui/src/components/useShowPages.ts
@@ -206,7 +206,24 @@ export function useShowPages() {
}
};
- return { pages, loading, loaded, busyId, setVisibility, rotate, rename, onShareIdSaved, reload };
+ // Upload a new app icon (§7.1j). The server writes the workspace-root favicon and
+ // returns the refreshed payload; merging it updates `icon_version`, so the
+ // content-versioned icon URL changes and every avatar surface refetches on its own.
+ const uploadIcon = async (page: ShowPage, file: File) => {
+ if (busyId) return;
+ setBusyId(page.session_id);
+ try {
+ const res = await api.uploadShowPageIcon(page.session_id, file);
+ mergePage(res);
+ showToast(t('showPages.icon.toast.updated'));
+ } catch {
+ // ApiContext surfaces a toast on failure.
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ return { pages, loading, loaded, busyId, setVisibility, rotate, rename, uploadIcon, onShareIdSaved, reload };
}
export type ShowPagesController = ReturnType<typeof useShowPages>;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index e6b26f7ce..39f0f843b 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -407,6 +407,9 @@ export type ApiContextType = {
rotateShowPageShare: (sessionId: string) => Promise<any>;
/** Set a custom public link suffix (public pages only); rejects on a taken/invalid id. */
setShowPageShareId: (sessionId: string, shareId: string) => Promise<any>;
+ /** Upload an image as the page's workspace-root favicon (multipart); resolves to the
+ * refreshed page payload carrying the fresh `icon_version` (§7.1j). */
+ uploadShowPageIcon: (sessionId: string, file: File) => Promise<any>;
/** The workbench Dock document (resident-tile order + pinned Show Pages). */
getDock: () => Promise<DockResponse>;
/** Pin a session's Show Page to the Dock as an app (idempotent). */
@@ -2160,6 +2163,18 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
ensureShowPage: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/ensure`, {}),
rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
setShowPageShareId: (sessionId, shareId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/share-id`, { share_id: shareId }),
+ uploadShowPageIcon: async (sessionId, file) => {
+ // Multipart POST: the server names the on-disk file, so we send only the bytes
+ // and a filename hint. `requestJson` adds CSRF + surfaces errors like everything
+ // else; letting the browser set the multipart Content-Type/boundary (no JSON).
+ const form = new FormData();
+ form.append('file', file, file.name);
+ const { payloadJson } = await requestJson(
+ `/api/show-pages/${encodeURIComponent(sessionId)}/icon`,
+ { method: 'POST', body: form },
+ );
+ return payloadJson;
+ },
getDock: () => getJson('/api/dock'),
pinDockShowPage: (sessionId) => postJson('/api/dock/pins', { session_id: sessionId }),
unpinDockShowPage: (sessionId) => deleteJson(`/api/dock/pins/${encodeURIComponent(sessionId)}`),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 5067d05f3..66f957bc2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -176,6 +176,15 @@
"emptyFiltered": "No Show Pages match this filter.",
"nameLabel": "Name",
"rename": "Rename",
+ "iconLabel": "Icon",
+ "icon": {
+ "upload": "Upload",
+ "replace": "Replace",
+ "hint": "SVG, PNG, ICO, JPEG, or WebP · up to 2 MiB. Shown in the Dock and App Library.",
+ "toast": {
+ "updated": "App icon updated"
+ }
+ },
"visibilityLabel": "Visibility",
"visibilityOffline": "Offline",
"liveLink": "Live link",
@@ -231,7 +240,7 @@
"system": "system",
"dock": "Dock",
"undock": "Undock",
- "remove": "Remove",
+ "remove": "Remove App",
"reorder": "Reorder",
"empty": "No apps match your search."
},
@@ -646,6 +655,10 @@
"missing_share_id": "Enter a custom link first.",
"not_public": "Make the Show Page public first to change its link.",
"session_archived": "This session is archived, so its Show Page can't be changed.",
+ "invalid_icon_type": "The icon must be an SVG, PNG, ICO, JPEG, or WebP image.",
+ "icon_too_large": "That icon is too large. Use an image up to 2 MiB.",
+ "icon_required": "Choose an icon file to upload.",
+ "icon_write_failed": "Couldn't save the icon. Please try again.",
"project_no_folder": "This project has no local folder configured.",
"project_not_found": "Project not found.",
"remote_access_host_mismatch": "This address can't open the Avibe control panel. Open it from your https://<your-slug>.avibe.bot link, or http://127.0.0.1:5123 on the machine running Avibe.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 11c449d15..76e85bc0b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -176,6 +176,15 @@
"emptyFiltered": "没有符合该筛选条件的展示页面。",
"nameLabel": "名称",
"rename": "重命名",
+ "iconLabel": "图标",
+ "icon": {
+ "upload": "上传",
+ "replace": "更换",
+ "hint": "SVG、PNG、ICO、JPEG 或 WebP,最大 2 MiB。显示在 Dock 与应用库中。",
+ "toast": {
+ "updated": "应用图标已更新"
+ }
+ },
"visibilityLabel": "可见性",
"visibilityOffline": "下线",
"liveLink": "访问链接",
@@ -231,7 +240,7 @@
"system": "系统",
"dock": "固定到 Dock",
"undock": "取消固定",
- "remove": "移出",
+ "remove": "移出 App",
"reorder": "重新排序",
"empty": "没有匹配的应用。"
},
@@ -646,6 +655,10 @@
"missing_share_id": "请先输入自定义链接。",
"not_public": "请先把展示页面设为公开,再修改链接。",
"session_archived": "该会话已归档,无法修改它的展示页面。",
+ "invalid_icon_type": "图标必须是 SVG、PNG、ICO、JPEG 或 WebP 图片。",
+ "icon_too_large": "图标太大了,请使用不超过 2 MiB 的图片。",
+ "icon_required": "请选择要上传的图标文件。",
+ "icon_write_failed": "无法保存图标,请重试。",
"project_no_folder": "这个项目没有配置本地文件夹。",
"project_not_found": "找不到这个项目。",
"remote_access_host_mismatch": "这个地址无法打开 Avibe 控制台。请用你的 https://<你的子域>.avibe.bot 链接打开,或在运行 Avibe 的机器上访问 http://127.0.0.1:5123。",
diff --git a/vibe/api.py b/vibe/api.py
index f0f4cefa3..de7973257 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1183,6 +1183,41 @@ def set_show_page_share_id(session_id: str, share_id: str) -> dict:
return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
+def upload_show_page_icon(
+ session_id: str, data: bytes, *, filename: str | None, content_type: str | None
+) -> dict:
+ """Write an uploaded image as the page's workspace-root favicon; return the
+ refreshed page payload so the Web UI merges it like any other show-page mutation
+ (the fresh ``icon_version`` flows through ``show_page_payload``) — §7.1j.
+
+ 404 (``show_page_not_found``) when the session has no Show Page; ``session_archived``
+ when the session is archived (mirrors the other Show Page mutators — an archived,
+ terminal session's page cannot be changed); the write itself raises ``ShowPageError``
+ (→ 4xx) for a malformed id / bad type / empty / oversized payload. Never edits
+ ``index.html``.
+ """
+ from core.show_pages import ShowPageError, ShowPageStore, show_page_payload, write_show_page_icon
+
+ config = V2Config.load()
+ store = ShowPageStore()
+ try:
+ page = store.get(session_id)
+ if page is None:
+ raise ShowPageError("This session has no Show Page.", code="show_page_not_found")
+ if store.is_archived(session_id):
+ # Archiving leaves the page offline and terminal; the other mutators guard it
+ # with session_archived, so a direct icon upload must not slip past that.
+ raise ShowPageError(
+ "This session is archived, so its Show Page can't be changed.",
+ code="session_archived",
+ )
+ write_show_page_icon(session_id, data, filename=filename, content_type=content_type)
+ payload = show_page_payload(page, config=config)
+ finally:
+ store.close()
+ return {"ok": True, **_apply_session_meta([payload])[0]}
+
+
def get_dock() -> dict:
"""The workbench Dock document — resident-tile order + pinned Show Pages."""
from core.dock_store import load_dock
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index db8162926..0d65f7693 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -41,6 +41,7 @@ from core.show_pages import (
SHOW_CLI_EVENT_TOKEN_HEADER,
SHOW_EVENT_WRITE_TOKEN_COOKIE,
SHOW_EVENT_WRITE_TOKEN_HEADER,
+ SHOW_PAGE_ICON_MAX_UPLOAD_BYTES,
show_cli_event_token,
show_event_write_token,
)
@@ -6403,6 +6404,90 @@ async def files_upload(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
+def _show_page_icon_upload_error(code: str, message: str):
+ # Structured 4xx for the icon upload (§7.1j) — mirrors _dock_error_response so the
+ # Web UI's shared handler localizes via errors.<code> and falls back to `message`.
+ # Every failure is a client/policy error (bad type/size, missing file, unknown
+ # page), so the endpoint answers a clear 4xx — never a 500.
+ status = {
+ "show_page_not_found": 404,
+ "session_not_found": 404,
+ "icon_too_large": 413,
+ "invalid_icon_type": 415,
+ }.get(code, 400)
+ return (
+ jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}),
+ status,
+ )
+
+
[email protected]("/api/show-pages/{session_id}/icon", include_in_schema=False)
+async def show_page_icon_upload(session_id: str, starlette_request: FastAPIRequest):
+ # Icon self-serve upload (§7.1j): the multipart sibling of the GET icon endpoint
+ # (that one is a compat @app.route; the compat layer parses JSON, not multipart, so
+ # the upload is a native FastAPI route reusing the shared file-upload machinery —
+ # parser cap + Content-Length guard). Auth/CSRF ride the native dispatch hooks.
+ # Contract: a structured 4xx on ANY bad input, never a 500 (the icon is decorative).
+ async def handler():
+ from core.file_browser_service import FileBrowserError
+ from core.show_pages import ShowPageError
+ from vibe import api
+ from vibe.sse_broker import broker
+
+ try:
+ _validate_file_upload_content_length(starlette_request.headers, SHOW_PAGE_ICON_MAX_UPLOAD_BYTES)
+ form = await _parse_file_upload_form(
+ starlette_request, max_file_bytes=SHOW_PAGE_ICON_MAX_UPLOAD_BYTES
+ )
+ try:
+ upload = form.get("file")
+ if not isinstance(upload, StarletteUploadFile):
+ raise ShowPageError("An icon file is required.", code="icon_required")
+ await upload.seek(0)
+ data = await upload.read()
+ result = await asyncio.to_thread(
+ api.upload_show_page_icon,
+ session_id,
+ data,
+ filename=upload.filename,
+ content_type=upload.content_type,
+ )
+ # Broadcast so EVERY already-mounted inventory (Dock, WindowLayer, mobile
+ # drawer, app search) reloads and picks up the new icon_version — the
+ # optimistic mergePage only updates the Library instance that uploaded
+ # (§7.1j review P2). Reuses the existing "show page changed → reload"
+ # signal that those surfaces already listen for.
+ broker.publish(
+ "session.activity",
+ {"session_id": session_id, "scope_id": None, "event": "show_event"},
+ )
+ return jsonify(result)
+ finally:
+ await form.close()
+ except MultiPartException as exc:
+ message = str(exc)
+ code = "icon_too_large" if "too large" in message.lower() else "invalid_icon"
+ return _show_page_icon_upload_error(code, message)
+ except StarletteHTTPException as exc:
+ return _show_page_icon_upload_error("invalid_icon", str(exc.detail))
+ except FileBrowserError as exc:
+ # _parse_file_upload_form raises this for a non-multipart body; the
+ # Content-Length guard raises it with code "too_large" (413) BEFORE parsing a
+ # very large body — that must keep the documented icon_too_large/413 path
+ # instead of collapsing to a generic 400 (§7.1j review P3).
+ code = "icon_too_large" if exc.code == "too_large" else "invalid_icon"
+ return _show_page_icon_upload_error(code, exc.message)
+ except ShowPageError as exc:
+ return _show_page_icon_upload_error(getattr(exc, "code", "invalid_icon"), str(exc))
+ except Exception:
+ # A genuine server-side write fault (disk full, permission). The icon is
+ # decorative, so answer a clear 4xx (never 500 per §7.1j) and log the cause.
+ logger.exception("show page icon upload failed")
+ return _show_page_icon_upload_error("icon_write_failed", "Could not save the icon; please try again.")
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.post("/api/files/mkdir", include_in_schema=False)
async def files_mkdir(starlette_request: FastAPIRequest):
async def handler():