Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(apps): Library feedback round — two-layer install/dock model (#902)
Call White2ccc62636a76
diff --git a/core/dock_store.py b/core/dock_store.pyindex d70530968..69e3ced80 100644--- a/core/dock_store.py+++ b/core/dock_store.py@@ -1,22 +1,30 @@-"""Server-side Dock state: which apps are pinned to the workbench Dock, and in-what order the resident tiles sit.+"""Server-side Dock state: which apps are *installed*, and which of them sit in+the workbench Dock (and in what order).The Dock is durable *product* state — it follows the user across devices — notper-browser UI state, so it lives in the shared ``state_meta`` KV under a single-versioned key, alongside the other cross-device workbench state. v1 knows two-kinds of dock item:+versioned key, alongside the other cross-device workbench state. It knows two+kinds of item:- built-in apps, keyed by their app id verbatim (``files`` / ``terminal`` /- ``editor`` / ``library``). They are reorderable but not unpinnable.-- pinned Show Pages, keyed ``show:<session_id>``.+ ``editor`` / ``library``). Always installed; individually dockable/undockable.+- pinned Show Pages, keyed ``show:<session_id>``. A pin IS the install record.-Future item kinds (``app:<id>`` …) slot into the same ``order`` list without a-migration — see docs/plans/dock-pinned-show-page-apps.md §7.+Future item kinds (``app:<id>`` …) slot into the same lists without a migration —+see docs/plans/dock-pinned-show-page-apps.md §7 / §7.1c.-``order`` covers every resident tile, built-ins included. The document is-*reconciled on read* (drop unknown ids, append any missing built-ins/pins) and-*validated on write* (order must be exactly the known id set, no duplicates,-bounded), so a stale or corrupt blob can never desync the Dock.+Two layers (§7.1c):++- ``pins`` — the *installed* AI pages. Built-ins are implicitly installed.+- ``order`` — the *docked* subset: the resident tiles, in user order. It is a+ SUBSET of the known ids {built-ins ∪ pins}; any known id may be absent+ (undocked), built-ins included, and the empty Dock is a valid state.++The document is *reconciled on read* (dedupe pins, drop unknown/duplicate order+ids — but never force-append, so an undocked tile stays undocked) and *validated+on write* (order is a subset of the known ids, no duplicates, bounded). An absent+document seeds the default of every built-in docked; once any document exists it+is authoritative, so a stale or corrupt blob can never desync the Dock."""from __future__ import annotations@@ -49,10 +57,11 @@ BUILTIN_DOCK_IDS: tuple[str, ...] = ("files", "terminal", "editor", "library")# Namespace prefix for a pinned Show Page dock id.SHOW_PREFIX = "show:"-# Defensive cap on the resident-tile count so one corrupt/hostile write can't-# balloon the order list. Expressed as built-ins + a FIXED pin budget (not a flat-# constant) so adding a built-in never shrinks the pin budget or drops an existing-# valid pin on reconcile. Far above any real Dock (built-ins + pinned pages).+# Defensive cap so one corrupt/hostile write can't balloon the installed set or+# the order list. ``MAX_PINNED_PAGES`` is the FIXED install budget (not a flat+# constant) so adding a built-in never shrinks it or drops an existing valid pin+# on reconcile; ``MAX_DOCK_ITEMS`` bounds the docked order (≤ built-ins ∪ pins).+# Far above any real Dock.MAX_PINNED_PAGES = 197MAX_DOCK_ITEMS = len(BUILTIN_DOCK_IDS) + MAX_PINNED_PAGES@@ -105,8 +114,13 @@ def _coerce_doc(raw: Any) -> tuple[list[str], list[dict[str, str]]]:def _reconcile(order: list[str], pins: list[dict[str, str]]) -> dict[str, Any]:- """Canonicalize a dock doc: dedupe pins by session id; drop unknown/duplicate- order ids; append any missing built-ins, then any missing pins, at the end.+ """Canonicalize a dock doc under the two-layer model (§7.1c): dedupe pins by+ session id; drop unknown/duplicate order ids. The order is left as the stored+ SUBSET — built-ins and pins are NOT force-appended, so an undocked tile+ (built-in included) stays undocked and the empty Dock survives a round-trip.++ Dropping an order id whose ``show:<sid>`` has no matching pin keeps the Dock+ pin-consistent (a removed pin cascades out of the order on the next read).Pure — the same algorithm runs client-side (reconcileDock in DockContext),so both ends agree on the canonical shape.@@ -121,12 +135,12 @@ def _reconcile(order: list[str], pins: list[dict[str, str]]) -> dict[str, Any]:deduped_pins.append(pin)# Clamp on read as well as on write: a corrupt or hand-edited stored doc could- # hold more pins than the write paths admit, so bound them here too (built-ins- # are always kept; excess pins beyond the cap are dropped) to keep the Dock —- # and GET /api/dock — from ballooning.- max_pins = max(0, MAX_DOCK_ITEMS - len(BUILTIN_DOCK_IDS))- if len(deduped_pins) > max_pins:- deduped_pins = deduped_pins[:max_pins]+ # hold more pins than the write paths admit, so bound them here too (excess+ # pins beyond the fixed install budget are dropped) to keep the installed set —+ # and GET /api/dock — from ballooning. Same constant the pin path guards on, so+ # the two never disagree about what a read would keep.+ if len(deduped_pins) > MAX_PINNED_PAGES:+ deduped_pins = deduped_pins[:MAX_PINNED_PAGES]pin_ids = [_show_id(pin["session_id"]) for pin in deduped_pins]known = set(BUILTIN_DOCK_IDS) | set(pin_ids)@@ -137,19 +151,18 @@ def _reconcile(order: list[str], pins: list[dict[str, str]]) -> dict[str, Any]:if item in known and item not in seen:result.append(item)seen.add(item)- for builtin in BUILTIN_DOCK_IDS:- if builtin not in seen:- result.append(builtin)- seen.add(builtin)- for pin_id in pin_ids:- if pin_id not in seen:- result.append(pin_id)- seen.add(pin_id)return {"order": result, "pins": deduped_pins}def _load(db_path: Path | None) -> dict[str, Any]:- order, pins = _coerce_doc(get_state_meta(DOCK_STATE_KEY, db_path=db_path))+ raw = get_state_meta(DOCK_STATE_KEY, db_path=db_path)+ if not isinstance(raw, dict):+ # No dock document has ever been stored → seed the default: every built-in+ # docked, nothing installed. Only an ABSENT document seeds; a stored doc is+ # honored as-is (including an empty/partial order — built-ins are+ # undockable now, so "nothing docked" is a legitimate saved state).+ return {"order": list(BUILTIN_DOCK_IDS), "pins": []}+ order, pins = _coerce_doc(raw)return _reconcile(order, pins)@@ -185,9 +198,10 @@ def pin_show_page(session_id: str, *, db_path: Path | None = None) -> dict[str,if any(pin["session_id"] == session_id for pin in doc["pins"]):return doc # already pinned → idempotent no-op (keeps its place + snapshot)- # Enforce the same cap ``set_dock_order`` does, so a new pin can't push the- # order past MAX_DOCK_ITEMS (which would then make every reorder rejected).- if len(doc["order"]) >= MAX_DOCK_ITEMS:+ # Bound the installed set to the same fixed budget reconcile clamps to, so+ # a new pin can't grow ``pins`` past what a read would keep (which would+ # then silently drop the just-added page).+ if len(doc["pins"]) >= MAX_PINNED_PAGES:raise DockError("The Dock is full — unpin an app before pinning another.", code="dock_full")meta = read_session_display_meta([session_id], db_path=db_path)@@ -221,13 +235,25 @@ def unpin_show_page(session_id: str, *, db_path: Path | None = None) -> dict[strreturn doc-def set_dock_order(order: Any, *, db_path: Path | None = None) -> dict[str, Any]:- """Persist a new resident-tile order.-- The order must be exactly the current known id set (built-ins + pinned- pages), with no duplicates and within the size cap. A stale client — one- that omits a pin added by another tab, say — is rejected rather than allowed- to clobber the newer pin. Raises ``DockError`` (``invalid_order`` → 400).+def set_dock_order(order: Any, *, known: Any = None, db_path: Path | None = None) -> dict[str, Any]:+ """Persist the docked subset, in order.++ Under the two-layer model (§7.1c) the order is a SUBSET of the known ids+ (built-ins ∪ pinned pages): every id must be known and unique, but ids may be+ OMITTED — that is how a tile (built-in included) is undocked — and the empty+ order (nothing docked) is valid. An id that is not a real dock item is still+ rejected, so a stale client that references a pin removed by another tab+ can't resurrect it.++ ``known`` is optimistic-concurrency guard: the full id set the client based+ this order on. Because omission now means "undock", a stale tab (loaded before+ another tab installed a page) would otherwise silently undock the newer pin —+ its ``show:<id>`` is simply absent from the stale order, and subset validation+ accepts it. So when the client declares ``known`` and it no longer equals the+ server's current known set, the write is rejected as stale (the client+ re-syncs and retries). When ``known`` is omitted (legacy client) we can't+ tell, so subset validation alone applies. Raises ``DockError``+ (``invalid_order`` / ``stale_order`` → 400)."""if not isinstance(order, list) or not all(isinstance(item, str) for item in order):raise DockError("Dock order must be a list of ids.", code="invalid_order")@@ -238,9 +264,14 @@ def set_dock_order(order: Any, *, db_path: Path | None = None) -> dict[str, Any]with _DOCK_MUTATION_LOCK:doc = _load(db_path)- known = set(BUILTIN_DOCK_IDS) | {_show_id(pin["session_id"]) for pin in doc["pins"]}- if set(order) != known:- raise DockError("Dock order must match the current dock items.", code="invalid_order")+ server_known = set(BUILTIN_DOCK_IDS) | {_show_id(pin["session_id"]) for pin in doc["pins"]}+ if known is not None:+ if not isinstance(known, list) or not all(isinstance(item, str) for item in known):+ raise DockError("Dock known-set must be a list of ids.", code="invalid_order")+ if set(known) != server_known:+ raise DockError("Dock order is based on a stale view of the installed apps.", code="stale_order")+ if not set(order) <= server_known:+ raise DockError("Dock order has an unknown id.", code="invalid_order")doc = {"order": list(order), "pins": doc["pins"]}_save(doc, db_path)diff --git a/docs/plans/dock-pinned-show-page-apps.md b/docs/plans/dock-pinned-show-page-apps.mdindex 7699262ce..39702e9d3 100644--- a/docs/plans/dock-pinned-show-page-apps.md+++ b/docs/plans/dock-pinned-show-page-apps.md@@ -218,6 +218,44 @@ the same objects. Decision: fold it into the App Library.tabs, filters, expanded row w/ visibility+link+suffix mgmt, per-row Docktoggle), both in design.pen right of `NbPMq`.+### 7.1c Phase 2.1 — acceptance-feedback round (owner hands-on, 2026-07-13 23:27; SUPERSEDES the one-bit model)++Owner used the shipped Library and upgraded the model to **two layers**:+**Apps list = "installed" set** · **Dock = the resident subset**. His 7 points,+integrated:++1. **Built-ins are undockable too** (reverses the v1 lock): every tile —+ files/terminal/editor/library — can be unpinned from the Dock via+ right-click or the Apps-view action. Built-ins can NEVER be removed from+ the Apps LIST (no 移出 for them); no lock icons anywhere.+2. **Library tab rename**: "Show Pages / 展示页面" view → **"AI"** (en+zh+ both "AI").+3. **Apps view rows get two distinct actions**: 取消固定/固定到 Dock+ (toggles Dock membership, row STAYS in the list) and — AI-kind rows only —+ **移出** (removes from the Apps list entirely; page itself untouched).+4. **Row click opens the app** (both views).+5. **AI view per-row control**: the Dock switch → an **"添加到 App" button**+ (Button primitive, state-aware: 添加到 App ↔ 移出). It toggles APPS-LIST+ membership; adding also docks by default (keeps the v1 one-gesture feel);+ removing removes from both. (PM default — flag if wrong.)+6. **AI view open affordance**: remove the standalone Open button; an open+ icon sits beside the row title; clicking title/row **opens the app+ window** (reuse the showpage window), NOT a browser tab. Share-link+ management stays in the expanded panel.+7. **Library is itself a listed built-in app** (appears in the Apps view,+ dockable/undockable like the rest), and a **permanent 应用库 entry lives+ in the control-panel sidebar** (undismissable escape hatch; links to the+ existing /apps/library route).++Data model (compatible evolution, no migration): `pins` = installed AI+pages; `order` = docked ids and becomes a **SUBSET** of {built-ins ∪ pins}+(server validation: unique, known ids, subset — no longer set-equality;+reconcile stops force-appending built-ins). Existing docs (all built-ins in+order) remain valid. API surface unchanged: dock/undock = PUT order with/+without the id; install/remove = POST/DELETE pins (POST also appends to+order per §5 default). Empty Dock is allowed; when empty, the Dock popover+shows an App Library shortcut hint (never a dead surface).+### 7.1b Mobile Dock — Option B locked (owner decision 2026-07-13 22:22)- The mobile 更多 tab becomes **Apps** (grid icon). Tapping summons a bottomdiff --git a/tests/test_dock_api.py b/tests/test_dock_api.pyindex db4b967cf..fc09a6d92 100644--- a/tests/test_dock_api.py+++ b/tests/test_dock_api.py@@ -133,54 +133,58 @@ def test_pin_multiple_sessions_all_survive(monkeypatch, tmp_path):assert [pin["session_id"] for pin in dock["pins"]] == ["ses_a", "ses_b", "ses_c"]-def test_pin_rejects_when_dock_is_full(monkeypatch, tmp_path):- # The cap that set_dock_order enforces must also gate new pins, else the order- # can grow past it and every later reorder is rejected.+def test_pin_rejects_when_install_budget_is_full(monkeypatch, tmp_path):+ # The install (pins) budget the reconcile clamp enforces must also gate new+ # pins, else a pin can grow ``pins`` past what a read would keep and the+ # just-added page is silently dropped on the next load.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- monkeypatch.setattr("core.dock_store.MAX_DOCK_ITEMS", 5) # 4 built-ins + room for one pin+ monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pinfor sid in ("ses_full1", "ses_full2"):_seed_session(sid)_make_show_page(sid)- api.pin_dock_show_page("ses_full1") # fills the Dock (4 built-ins + 1 pin = 5)+ api.pin_dock_show_page("ses_full1") # fills the install budget (1 pin)with pytest.raises(DockError) as excinfo:api.pin_dock_show_page("ses_full2")assert excinfo.value.code == "dock_full"def test_load_dock_clamps_oversized_corrupt_pins(monkeypatch, tmp_path):- # A corrupt / hand-edited stored doc with more pins than the cap must be- # bounded on read, not rendered as thousands of tiles.+ # A corrupt / hand-edited stored doc with more pins than the budget must be+ # bounded on read, not rendered as thousands of tiles. The order is honored as+ # stored (empty here) — reconcile no longer force-appends built-ins.from core.chat_discovery import set_state_metafrom core.dock_store import DOCK_STATE_KEYmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- monkeypatch.setattr("core.dock_store.MAX_DOCK_ITEMS", 5) # 4 built-ins + room for one pin+ monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pinset_state_meta(DOCK_STATE_KEY,{"order": [], "pins": [{"session_id": f"ses_{i}", "title_snapshot": "", "pinned_at": ""} for i in range(10)]},)dock = api.get_dock()["dock"]- assert len(dock["pins"]) == 1 # clamped to MAX_DOCK_ITEMS - built-ins- assert len(dock["order"]) == 5 # 4 built-ins + 1 pin+ assert len(dock["pins"]) == 1 # clamped to the install budget+ assert dock["order"] == [] # stored empty order is honored; nothing force-addeddef test_pin_budget_survives_new_builtin():- # Adding library (the 4th built-in) must not shrink the pin budget: the cap is- # built-ins + a fixed budget, so a valid pre-Phase-2 dock (up to 197 pins)+ # Adding library (the 4th built-in) must not shrink the install budget: the+ # budget is a fixed constant, so a valid pre-Phase-2 dock (up to 197 pins)# never loses a pin on reconcile when a built-in is added.- from core.dock_store import BUILTIN_DOCK_IDS, MAX_DOCK_ITEMS+ from core.dock_store import BUILTIN_DOCK_IDS, MAX_DOCK_ITEMS, MAX_PINNED_PAGES- assert MAX_DOCK_ITEMS - len(BUILTIN_DOCK_IDS) == 197+ assert MAX_PINNED_PAGES == 197+ assert MAX_DOCK_ITEMS - len(BUILTIN_DOCK_IDS) == MAX_PINNED_PAGES-def test_load_dock_appends_library_to_pre_phase2_order(monkeypatch, tmp_path):- # A dock doc persisted before ``library`` became a built-in (its ``order``- # lacks it) must gain it on read via the reconcile rule (spec §3: missing- # built-ins appended), without dropping the pin or reordering existing tiles.+def test_reconcile_does_not_readd_undocked_builtin(monkeypatch, tmp_path):+ # Two-layer model (§7.1c): built-ins are undockable, so reconcile must NOT+ # force-append a built-in that a stored doc omits from ``order`` (reverses the+ # pre-Phase-2.1 append rule). Existing tiles keep their order and the pin+ # survives; ``library`` stays undocked (installed, but not in the Dock).from core.chat_discovery import set_state_metafrom core.dock_store import DOCK_STATE_KEY@@ -196,11 +200,32 @@ def test_load_dock_appends_library_to_pre_phase2_order(monkeypatch, tmp_path):dock = api.get_dock()["dock"]- # Existing tiles keep their order, the pin survives, and library is appended.- assert dock["order"] == ["files", "terminal", "editor", _show("ses_legacy"), "library"]+ assert dock["order"] == ["files", "terminal", "editor", _show("ses_legacy")]+ assert "library" not in dock["order"] # NOT force-appendedassert [pin["session_id"] for pin in dock["pins"]] == ["ses_legacy"]+def test_legacy_full_order_doc_still_valid(monkeypatch, tmp_path):+ # A doc persisted with every built-in already in ``order`` (the common+ # post-#899 shape) remains valid and unchanged on read.+ from core.chat_discovery import set_state_meta+ from core.dock_store import DOCK_STATE_KEY++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ order = ["files", "terminal", "editor", "library", _show("ses_keep")]+ set_state_meta(+ DOCK_STATE_KEY,+ {+ "order": order,+ "pins": [{"session_id": "ses_keep", "title_snapshot": "Keep", "pinned_at": "2026-01-01T00:00:00+00:00"}],+ },+ )++ dock = api.get_dock()["dock"]+ assert dock["order"] == order++def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)@@ -270,19 +295,117 @@ def test_set_order_accepts_library_builtin(monkeypatch, tmp_path):assert api.get_dock()["dock"]["order"] == new_order-def test_set_order_rejects_wrong_set(monkeypatch, tmp_path):+def test_set_order_rejects_unknown_id(monkeypatch, tmp_path):+ # Subset validation (§7.1c) still rejects an id that is not a real dock item,+ # so a stale client can't resurrect a pin removed by another tab.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- # Missing a built-in id — not set-equal to the known ids.with pytest.raises(DockError) as excinfo:- api.set_dock_order(["files", "terminal"])+ api.set_dock_order(["files", "terminal", "editor", "show:ghost"])assert excinfo.value.code == "invalid_order"- # An unknown id that isn't a real dock item.++def test_set_order_accepts_proper_subset(monkeypatch, tmp_path):+ # Two-layer model: the order is a SUBSET of the known ids, so omitting a+ # built-in (undocking it) is accepted and persists — no longer rejected as a+ # non-set-equal order.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)++ dock = api.set_dock_order(["files", "terminal"])["dock"] # editor + library undocked+ assert dock["order"] == ["files", "terminal"]+ assert api.get_dock()["dock"]["order"] == ["files", "terminal"]+++def test_set_order_accepts_empty_dock(monkeypatch, tmp_path):+ # Undocking everything (including all built-ins) is legal — the empty Dock is+ # a valid saved state (the popover shows the App Library hint client-side).+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)++ dock = api.set_dock_order([])["dock"]+ assert dock["order"] == []+ assert api.get_dock()["dock"]["order"] == []+++def test_set_order_rejects_stale_known(monkeypatch, tmp_path):+ # Optimistic concurrency: a client whose ``known`` baseline is missing a pin+ # another tab just installed is rejected as stale, so its reorder can't+ # silently undock that newer pin (which install docked by default). Subset+ # validation alone would have accepted the omission.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _seed_session("ses_new", title="New")+ _make_show_page("ses_new")+ api.pin_dock_show_page("ses_new") # server now has show:ses_new installed + docked++ stale_known = list(BUILTIN_DOCK_IDS) # a tab that never saw ses_newwith pytest.raises(DockError) as excinfo:- api.set_dock_order(["files", "terminal", "editor", "show:ghost"])- assert excinfo.value.code == "invalid_order"+ api.set_dock_order(["editor", "files", "terminal", "library"], known=stale_known)+ assert excinfo.value.code == "stale_order"+ # The pin survived: the stale write was rejected, not applied.+ assert _show("ses_new") in api.get_dock()["dock"]["order"]+++def test_set_order_with_matching_known_allows_intentional_undock(monkeypatch, tmp_path):+ # When ``known`` matches the server's installed set, an omitted id is an+ # INTENTIONAL undock (distinct from a stale omission) and is accepted — the+ # page stays installed.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _seed_session("ses_k", title="K")+ _make_show_page("ses_k")+ api.pin_dock_show_page("ses_k")++ known = [*BUILTIN_DOCK_IDS, _show("ses_k")]+ dock = api.set_dock_order(list(BUILTIN_DOCK_IDS), known=known)["dock"] # undock ses_k+ assert _show("ses_k") not in dock["order"]+ assert [pin["session_id"] for pin in dock["pins"]] == ["ses_k"] # still installed+++def test_undocked_builtin_persists_across_reload(monkeypatch, tmp_path):+ # An undocked built-in stays undocked across a reload — reconcile never+ # re-adds it (the whole point of built-ins being undockable now).+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)++ api.set_dock_order(["files", "terminal", "editor"]) # library undocked+ assert "library" not in api.get_dock()["dock"]["order"]+++def test_installed_page_can_be_undocked_but_stays_installed(monkeypatch, tmp_path):+ # The core two-layer invariant: a Show Page can be undocked (removed from+ # ``order``) while REMAINING installed (kept in ``pins``) — install and dock+ # are separate. Its ``show:`` id is absent from the order but the pin persists.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _seed_session("ses_keep", title="Keep")+ _make_show_page("ses_keep")+ api.pin_dock_show_page("ses_keep") # installs + docks++ # Undock it (drop only its show id) while keeping every built-in docked.+ api.set_dock_order(["files", "terminal", "editor", "library"])++ dock = api.get_dock()["dock"]+ assert _show("ses_keep") not in dock["order"] # undocked+ assert [pin["session_id"] for pin in dock["pins"]] == ["ses_keep"] # still installed+++def test_delete_pin_cascades_out_of_order(monkeypatch, tmp_path):+ # DELETE pins (uninstall) removes the page from BOTH pins and order, leaving+ # the other docked tiles intact.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _seed_session("ses_del", title="Del")+ _make_show_page("ses_del")+ api.pin_dock_show_page("ses_del")+ assert _show("ses_del") in api.get_dock()["dock"]["order"]++ dock = api.unpin_dock_show_page("ses_del")["dock"]+ assert _show("ses_del") not in dock["order"]+ assert dock["pins"] == []+ assert dock["order"] == list(BUILTIN_DOCK_IDS) # built-ins untoucheddef test_set_order_rejects_duplicates(monkeypatch, tmp_path):diff --git a/ui/src/apps/LibraryApp.tsx b/ui/src/apps/LibraryApp.tsxindex 348e2fb4b..f2b7dfccc 100644--- a/ui/src/apps/LibraryApp.tsx+++ b/ui/src/apps/LibraryApp.tsx@@ -1,41 +1,79 @@-import { useMemo, useState } from 'react';-import { Lock, PinOff } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { Pin, PinOff, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';import clsx from 'clsx';import { APP_LIST, APP_REGISTRY, type AppDefinition, type AppId } from './registry';import { deriveAppRows, type AppRow } from './appLibrary';import { ShowPageAvatarTile } from './showPageAvatarTile';+import { showPagePrivatePath } from './showPageAvatar';import { useDock } from '../context/DockContext';+import { useWindowManager } from '../context/WindowManagerContext';import { ShowPagesView } from '../components/ShowPagesPage';import { useShowPages, type ShowPage } from '../components/useShowPages';import { Badge } from '../components/ui/badge';+import { Button } from '../components/ui/button';import { SearchField } from '../components/settings/SettingsPrimitives';// The App Library: the app manager, itself a built-in app (§7.1). Two views over-// the same data — the docked set (Apps) and the full Show Pages inventory — with-// ONE state bit between them: being an app ≡ being in the Dock. The Show Pages-// view's per-row Dock switch is the single promote/demote gesture; the Apps view-// only lists + removes. Renders as a window body (desktop) and as a full-screen-// route (mobile), so `windowId`/`params` are accepted but unused.--// The Library never lists itself among the apps it manages.-const LIBRARY_APP_ID: AppId = 'library';-// The client's built-in Dock ids (files / terminal / editor / library), the set-// deriveAppRows classifies against. Mirrors DockContext's BUILTIN_DOCK_IDS.-const BUILTIN_IDS = new Set<string>(APP_LIST.map((app) => app.id));+// the two-layer state (§7.1c): the INSTALLED set (Apps) and the full Show Pages+// inventory (AI). "Installed" (a member of `pins`, plus the always-installed+// built-ins) is now distinct from "docked" (a member of the Dock `order`): every+// row opens the app on click and carries a state-aware dock/undock action that+// keeps it in the list, and AI-kind rows additionally get a 移出 (uninstall).+// Renders as a window body (desktop) and as a full-screen route (mobile), so+// `windowId`/`params` are accepted but unused.++// The client's built-in Dock ids (files / terminal / editor / library), in+// canonical order. Mirrors DockContext's BUILTIN_DOCK_IDS. The Library now lists+// itself among them (§7.1c #7), so nothing is excluded.+const BUILTIN_DOCK_IDS: string[] = APP_LIST.map((app) => app.id);type LibraryTab = 'apps' | 'showpages';+/**+ * Open an app the way the current surface can show it. On desktop that's a+ * workbench window (`openApp`). On mobile there is no window layer: built-ins+ * have in-shell `/apps/*` routes, so navigate there (keeping the AppShell). A+ * Show Page has no in-shell mobile route yet (that lands with the §7.1b mobile+ * Dock), so open its private `/show/` surface in a NEW TAB rather than replacing+ * the current one — this tab keeps the AppShell / Library / Dock chrome instead+ * of dropping the user onto the raw page.+ */+function useOpenApp() {+ const wm = useWindowManager();+ const navigate = useNavigate();+ return useCallback(+ (appId: AppId, opts?: { title?: string; sessionId?: string }) => {+ const desktop = typeof window !== 'undefined' && !!window.matchMedia?.('(min-width: 768px)').matches;+ if (desktop) {+ wm.openApp(appId, {+ title: opts?.title,+ params: opts?.sessionId ? { sessionId: opts.sessionId, title: opts.title } : undefined,+ });+ return;+ }+ if (appId === 'showpage') {+ if (opts?.sessionId) window.open(showPagePrivatePath(opts.sessionId), '_blank', 'noopener,noreferrer');+ } else {+ navigate(`/apps/${appId}`);+ }+ },+ [wm, navigate],+ );+}+export const LibraryApp: React.FC<{ windowId?: string; params?: Record<string, unknown>; initialTab?: LibraryTab }> = ({params,initialTab,}) => {const { t } = useTranslation();const controller = useShowPages();- const { order } = useDock();+ const { order, pins } = useDock();+ const openApp = useOpenApp();// The legacy /admin/show-pages redirect (mobile via prop, desktop window via- // params) can request the Show Pages tab up front; default to Apps otherwise.+ // params) can request the AI (Show Pages) tab up front; default to Apps otherwise.const startTab: LibraryTab = initialTab === 'showpages' || params?.initialTab === 'showpages' ? 'showpages' : 'apps';const [tab, setTab] = useState<LibraryTab>(startTab);@@ -49,7 +87,7 @@ export const LibraryApp: React.FC<{ windowId?: string; params?: Record<string, uif (navTab === 'apps' || navTab === 'showpages') setTab(navTab);}- const appsCount = useMemo(() => deriveAppRows(order, BUILTIN_IDS, LIBRARY_APP_ID).length, [order]);+ const appsCount = useMemo(() => deriveAppRows(BUILTIN_DOCK_IDS, pins, order).length, [pins, order]);return (<div className="flex h-full min-h-0 flex-col bg-surface text-foreground">@@ -58,12 +96,16 @@ export const LibraryApp: React.FC<{ windowId?: string; params?: Record<string, u<TabButtonactive={tab === 'showpages'}onClick={() => setTab('showpages')}- label={t('library.tab.showPages')}+ label={t('library.tab.ai')}count={controller.pages.length}/></div><div className="min-h-0 flex-1">- {tab === 'apps' ? <AppsView pages={controller.pages} /> : <ShowPagesView {...controller} />}+ {tab === 'apps' ? (+ <AppsView pages={controller.pages} openApp={openApp} />+ ) : (+ <ShowPagesView {...controller} onOpenApp={(sessionId, title) => openApp('showpage', { sessionId, title })} />+ )}</div></div>);@@ -97,18 +139,19 @@ interface ResolvedRow {def?: AppDefinition;}-// Apps view: the docked set, in order, minus the Library itself. Built-ins show-// their icon + a locked badge (not removable); pinned Show Pages show a letter-// avatar + a remove-from-Dock action that unpins without deleting the page. No-// per-row toggles, no reorder (that lives on the Dock), no Add App (Phase 3).-const AppsView: React.FC<{ pages: ShowPage[] }> = ({ pages }) => {+// Apps view: the INSTALLED set (built-ins + pinned Show Pages), in canonical+// order. Every row opens the app on click and carries a state-aware Dock toggle+// (固定到 Dock ↔ 取消固定) that never removes it from the list; Show Page rows add a+// 移出 that uninstalls the app (the page itself is untouched). Built-ins have no+// 移出 and no lock — they simply can't leave the list.+const AppsView: React.FC<{ pages: ShowPage[]; openApp: ReturnType<typeof useOpenApp> }> = ({ pages, openApp }) => {const { t } = useTranslation();- const { order, pins, unpin } = useDock();+ const { order, pins, dock, undock, unpin } = useDock();const [query, setQuery] = useState('');const pinBySession = useMemo(() => new Map(pins.map((p) => [p.session_id, p])), [pins]);const pageBySession = useMemo(() => new Map(pages.map((p) => [p.session_id, p])), [pages]);- const rows = useMemo(() => deriveAppRows(order, BUILTIN_IDS, LIBRARY_APP_ID), [order]);+ const rows = useMemo(() => deriveAppRows(BUILTIN_DOCK_IDS, pins, order), [pins, order]);const resolved = useMemo<ResolvedRow[]>(() =>@@ -135,6 +178,14 @@ const AppsView: React.FC<{ pages: ShowPage[] }> = ({ pages }) => {return q ? resolved.filter((item) => item.name.toLowerCase().includes(q)) : resolved;}, [resolved, query]);+ const openRow = (row: AppRow) =>+ row.kind === 'builtin'+ ? openApp(row.builtinId as AppId)+ : openApp('showpage', {+ sessionId: row.sessionId ?? '',+ title: pageBySession.get(row.sessionId ?? '')?.title ?? undefined,+ });+return (<div className="flex h-full min-h-0 flex-col"><div className="flex shrink-0 items-center border-b border-border px-4 py-3 sm:px-5">@@ -156,7 +207,16 @@ const AppsView: React.FC<{ pages: ShowPage[] }> = ({ pages }) => {return (<divkey={row.dockId}- className="flex items-center gap-3 border-b border-border px-4 py-3 last:border-b-0 sm:gap-4 sm:px-5"+ role="button"+ tabIndex={0}+ onClick={() => openRow(row)}+ onKeyDown={(e) => {+ if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) {+ e.preventDefault();+ openRow(row);+ }+ }}+ className="flex w-full cursor-pointer items-center gap-3 border-b border-border px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-foreground/[0.02] sm:gap-4 sm:px-5">{def && Icon ? (<span@@ -173,31 +233,42 @@ const AppsView: React.FC<{ pages: ShowPage[] }> = ({ pages }) => {{subtitle ? <span className="truncate font-mono text-[11px] text-muted">{subtitle}</span> : null}</span>{row.kind === 'builtin' ? (- <Badge variant="outline" className="font-mono text-[10px] uppercase tracking-wide">+ <Badge variant="outline" className="hidden font-mono text-[10px] uppercase tracking-wide sm:inline-flex">{t('library.kind.builtin')}</Badge>) : (- <Badge variant="success">{t('library.kind.showPage')}</Badge>+ <Badge variant="success" className="hidden sm:inline-flex">+ {t('library.kind.showPage')}+ </Badge>)}- {row.removable ? (+ {/* State-aware Dock toggle — the row stays in the list either way. */}+ <Button+ type="button"+ variant={row.docked ? 'secondary' : 'outline'}+ size="xs"+ onClick={(e) => {+ e.stopPropagation();+ void (row.docked ? undock(row.dockId) : dock(row.dockId));+ }}+ >+ {row.docked ? <PinOff /> : <Pin />}+ <span className="hidden sm:inline">{row.docked ? t('library.apps.undock') : t('library.apps.dock')}</span>+ </Button>+ {/* 移出 — uninstall (Show Pages only; the page itself is untouched). */}+ {row.kind === 'showpage' ? (<buttontype="button"title={t('library.apps.remove')}aria-label={t('library.apps.remove')}- onClick={() => row.sessionId && unpin(row.sessionId)}+ onClick={(e) => {+ e.stopPropagation();+ if (row.sessionId) void unpin(row.sessionId);+ }}className="grid size-8 shrink-0 place-items-center rounded-lg text-muted transition-colors hover:bg-destructive/10 hover:text-destructive">- <PinOff size={15} />+ <Trash2 size={15} /></button>- ) : (- <span- className="grid size-8 shrink-0 place-items-center text-muted/60"- title={t('library.apps.locked')}- aria-label={t('library.apps.locked')}- >- <Lock size={14} />- </span>- )}+ ) : null}</div>);})diff --git a/ui/src/apps/appLibrary.test.ts b/ui/src/apps/appLibrary.test.tsindex 972a67e08..55daf8b2a 100644--- a/ui/src/apps/appLibrary.test.ts+++ b/ui/src/apps/appLibrary.test.ts@@ -2,24 +2,45 @@ import { describe, expect, it } from 'vitest';import { deriveAppRows, filterShowPages, type FilterablePage } from './appLibrary';-const BUILTINS = new Set(['files', 'terminal', 'editor', 'library']);--describe('deriveAppRows', () => {- it('keeps the docked set in order, resolving kinds', () => {- const rows = deriveAppRows(['files', 'terminal', 'editor', 'show:s1', 'show:s2'], BUILTINS, 'library');- expect(rows.map((r) => r.dockId)).toEqual(['files', 'terminal', 'editor', 'show:s1', 'show:s2']);- expect(rows.map((r) => r.kind)).toEqual(['builtin', 'builtin', 'builtin', 'showpage', 'showpage']);- expect(rows[3]).toMatchObject({ kind: 'showpage', sessionId: 's1', removable: true });+const BUILTINS = ['files', 'terminal', 'editor', 'library'];+const pin = (id: string) => ({ session_id: id });++describe('deriveAppRows (installed set)', () => {+ it('lists every built-in then every installed page, resolving kinds', () => {+ const rows = deriveAppRows(BUILTINS, [pin('s1'), pin('s2')], ['files', 'show:s1']);+ expect(rows.map((r) => r.dockId)).toEqual(['files', 'terminal', 'editor', 'library', 'show:s1', 'show:s2']);+ expect(rows.map((r) => r.kind)).toEqual(['builtin', 'builtin', 'builtin', 'builtin', 'showpage', 'showpage']);+ expect(rows[4]).toMatchObject({ kind: 'showpage', sessionId: 's1', removable: true });expect(rows[0]).toMatchObject({ kind: 'builtin', builtinId: 'files', removable: false });});- it('excludes the Library app itself from the list', () => {- const rows = deriveAppRows(['files', 'library', 'show:s1'], BUILTINS, 'library');- expect(rows.map((r) => r.dockId)).toEqual(['files', 'show:s1']);+ it('includes the Library itself — it lists itself now (§7.1c)', () => {+ const rows = deriveAppRows(BUILTINS, [], []);+ expect(rows.map((r) => r.dockId)).toContain('library');+ });++ it('flags docked membership from `order`, independent of list membership', () => {+ // files + library + s1 are docked; terminal/editor + s2 are installed but undocked.+ const rows = deriveAppRows(BUILTINS, [pin('s1'), pin('s2')], ['files', 'library', 'show:s1']);+ const byId = Object.fromEntries(rows.map((r) => [r.dockId, r.docked]));+ expect(byId).toMatchObject({+ files: true,+ terminal: false,+ editor: false,+ library: true,+ 'show:s1': true,+ 'show:s2': false,+ });+ });++ it('keeps an undocked built-in in the list (empty order still lists every built-in)', () => {+ const rows = deriveAppRows(BUILTINS, [], []);+ expect(rows.map((r) => r.dockId)).toEqual(BUILTINS);+ expect(rows.every((r) => r.docked === false)).toBe(true);});- it('drops unknown ids and de-duplicates', () => {- const rows = deriveAppRows(['files', 'files', 'app:remote1', 'show:s1'], BUILTINS, 'library');+ it('de-duplicates a pin that repeats', () => {+ const rows = deriveAppRows(['files'], [pin('s1'), pin('s1')], []);expect(rows.map((r) => r.dockId)).toEqual(['files', 'show:s1']);});});diff --git a/ui/src/apps/appLibrary.ts b/ui/src/apps/appLibrary.tsindex 3a16d007f..502d5f370 100644--- a/ui/src/apps/appLibrary.ts+++ b/ui/src/apps/appLibrary.ts@@ -3,7 +3,7 @@// layer (LibraryApp / ShowPagesView) resolves each row's icon, title, and badge// from the registry + loaded Show Pages.-import { dockIdToSession } from '../context/DockContext';+import { showDockId } from '../context/DockContext';export type AppRowKind = 'builtin' | 'showpage';@@ -11,34 +11,46 @@ export interface AppRow {/** The persisted Dock id: a built-in app id verbatim, or `show:<session_id>`. */dockId: string;kind: AppRowKind;- /** Built-in app id (files / terminal / editor …) when kind === 'builtin'. */+ /** Built-in app id (files / terminal / editor / library) when kind === 'builtin'. */builtinId?: string;/** Session id when kind === 'showpage'. */sessionId?: string;- /** Show Pages can be removed from the Dock (the page survives); built-ins can't. */+ /** Whether this app currently sits in the Dock (a member of `order`). */+ docked: boolean;+ /** Can be removed from the Apps LIST entirely (Show Pages yes — the page+ * survives; built-ins never leave the list). */removable: boolean;}/**- * Project the Dock order into the Apps-view rows: the docked set, in order,- * minus the Library app itself (a manager never lists itself) and any ids this- * client doesn't know (a future kind not yet shipped). Built-ins are matched- * against ``builtinIds``; every ``show:<id>`` is a pinned Show Page.+ * Project the two-layer state into the Apps-view rows: the INSTALLED set, not+ * the docked subset (§7.1c). Rows are every built-in (including the Library+ * itself — it now lists itself, dockable like the rest) in canonical order,+ * then every installed Show Page (`pins`) in pin order. Each row carries a+ * ``docked`` flag (is it in ``order`` right now?) that drives the+ * dock/undock toggle; the docked subset no longer decides membership, so an+ * undocked built-in or undocked page still appears in the list.*/-export function deriveAppRows(order: string[], builtinIds: ReadonlySet<string>, selfId: string): AppRow[] {+export function deriveAppRows(+ builtinIds: readonly string[],+ pins: readonly { session_id: string }[],+ order: readonly string[],+): AppRow[] {+ const docked = new Set(order);const rows: AppRow[] = [];const seen = new Set<string>();- for (const dockId of order) {+ for (const id of builtinIds) {+ if (seen.has(id)) continue;+ seen.add(id);+ rows.push({ dockId: id, kind: 'builtin', builtinId: id, docked: docked.has(id), removable: false });+ }+ for (const pin of pins) {+ const sid = pin.session_id;+ if (!sid) continue;+ const dockId = showDockId(sid);if (seen.has(dockId)) continue;seen.add(dockId);- if (dockId === selfId) continue; // the Library app is not listed among the apps it manages- const sessionId = dockIdToSession(dockId);- if (sessionId !== null) {- rows.push({ dockId, kind: 'showpage', sessionId, removable: true });- } else if (builtinIds.has(dockId)) {- rows.push({ dockId, kind: 'builtin', builtinId: dockId, removable: false });- }- // else: an id this client can't resolve (unknown/future kind) → skip it+ rows.push({ dockId, kind: 'showpage', sessionId: sid, docked: docked.has(dockId), removable: true });}return rows;}diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex e59d119b8..99be28450 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -273,6 +273,10 @@ export const AppShell: React.FC = () => {const adminItems: ShellNavItem[] = [{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },+ // Permanent escape hatch to the App Library (a workbench app). Always present,+ // so the Library is reachable from the control panel even when it is undocked+ // (§7.1c #7). Matches any /apps/library path so it stays active on the route.+ { to: '/apps/library', label: t('nav.appLibrary'), icon: LayoutGrid, match: (p) => p.startsWith('/apps/library') },{ to: '/admin/remote-access', label: t('nav.remoteAccess'), icon: Globe },{// 通讯平台: groups everything about connecting messaging platforms — thediff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsxindex 3ca18ee19..c45f7c9e6 100644--- a/ui/src/components/AppsLauncher.tsx+++ b/ui/src/components/AppsLauncher.tsx@@ -4,16 +4,25 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { Dock } from './apps/Dock';+import { ContextMenu, ContextMenuItem } from './ui/context-menu';+import { useWindowManager } from '../context/WindowManagerContext';// The sidebar bottom-left "Apps" button that reveals the Dock.-// - hover → the Dock floats up ABOVE the button (transient preview; the cursor-// can move straight onto it). Mirrors InboxHoverPopover's timer dance.-// - click → pin / unpin toggle (sticky). Unpinning hides it immediately even if-// the cursor is still on the button (suppressed until it leaves).+// - hover → the Dock floats up ABOVE the button (transient preview; the+// cursor can move straight onto it). Mirrors InboxHoverPopover.+// - click → pin / unpin toggle (sticky). Unpinning hides it immediately+// even if the cursor is still on the button.+// - right-click → a context menu with an "Open App Library" escape hatch — a+// third way to reach the Library (alongside the sidebar entry+// and the empty-Dock hint), complementing §7.1c point 7. It+// does NOT touch the hover/pin behavior.export const AppsLauncher: React.FC = () => {const { t } = useTranslation();+ const wm = useWindowManager();const [pinned, setPinned] = useState(false);const [hovering, setHovering] = useState(false);+ // Cursor-positioned right-click menu, on the shared ContextMenu primitive.+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);const closeTimer = useRef<number | null>(null);// Set on unpin so the lingering hover doesn't immediately re-open the panel;// cleared once the cursor actually leaves the trigger+panel.@@ -54,6 +63,11 @@ export const AppsLauncher: React.FC = () => {}};+ const openLibrary = () => {+ wm.openApp('library');+ setMenu(null);+ };+return (// The sidebar aside owns the stacking context (z-10, below the window layer z-20), so the Apps// button is covered by a maximized window like the rest of the sidebar. `relative` is just the@@ -62,6 +76,10 @@ export const AppsLauncher: React.FC = () => {<buttontype="button"onClick={onClick}+ onContextMenu={(e) => {+ e.preventDefault();+ setMenu({ x: e.clientX, y: e.clientY });+ }}aria-haspopup="menu"aria-expanded={visible}aria-pressed={pinned}@@ -92,6 +110,16 @@ export const AppsLauncher: React.FC = () => {<Dock /></div>)}++ {menu && (+ <ContextMenu x={menu.x} y={menu.y} onClose={() => setMenu(null)} width={184} itemCount={1}>+ <ContextMenuItem+ icon={<LayoutGrid className="size-[15px] text-cyan" />}+ label={t('apps.launcher.openLibrary')}+ onClick={openLibrary}+ />+ </ContextMenu>+ )}</div>);};diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsxindex dc5de2427..d51f21f0a 100644--- a/ui/src/components/ShowPagesPage.tsx+++ b/ui/src/components/ShowPagesPage.tsx@@ -1,13 +1,16 @@import { useMemo, useState } from 'react';import {+ AppWindow as AppWindowIcon,Check,ChevronDown,ChevronUp,Copy,ExternalLink,Link2,+ Plus,RefreshCw,RotateCw,+ Trash2,TriangleAlert,} from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -24,7 +27,6 @@ import { ShowPageShareIdField } from './workbench/ShowPageShareIdField';import { SearchField } from './settings/SettingsPrimitives';import { Button } from './ui/button';import { Badge } from './ui/badge';-import { Switch } from './ui/switch';import { SegmentedRadio, type SegmentedTone } from './ui/segmented';const LABEL = 'font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted';@@ -43,9 +45,10 @@ interface RowProps {expanded: boolean;busy: boolean;copied: boolean;- pinned: boolean;- onToggle: () => void;- onTogglePin: (next: boolean) => void;+ installed: boolean;+ onOpen: () => void;+ onToggleExpand: () => void;+ onToggleInstall: (next: boolean) => void;onSetVisibility: (visibility: Visibility) => void;onRotate: () => void;onCopy: () => void;@@ -57,9 +60,10 @@ function ShowPageRow({expanded,busy,copied,- pinned,- onToggle,- onTogglePin,+ installed,+ onOpen,+ onToggleExpand,+ onToggleInstall,onSetVisibility,onRotate,onCopy,@@ -94,26 +98,37 @@ function ShowPageRow({return (<div className={clsx('border-b border-border last:border-b-0', expanded && 'border-y border-mint/30')}>+ {/* The row itself opens the page as an app window (not a browser tab) —+ click the row or its title. Expand (share-link management) is a separate,+ explicit affordance: the chevron on the right. */}<divrole="button"tabIndex={0}- onClick={onToggle}+ onClick={onOpen}onKeyDown={(e) => {if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) {e.preventDefault();- onToggle();+ onOpen();}}}className={clsx(- 'flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left transition-colors sm:gap-4 sm:px-5',+ 'group flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left transition-colors sm:gap-4 sm:px-5',expanded ? 'bg-surface-2' : 'hover:bg-foreground/[0.02]',)}><span className="flex min-w-0 flex-1 items-center gap-3"><ShowPageAvatarTile sessionId={page.session_id} title={page.title || ''} /><span className="min-w-0">- <span className={clsx('block truncate text-[13px] font-semibold text-foreground', !page.title && 'font-mono')}>- {label}+ <span className="flex items-center gap-1.5">+ <span className={clsx('truncate text-[13px] font-semibold text-foreground', !page.title && 'font-mono')}>+ {label}+ </span>+ {/* Open affordance beside the title — the row opens the app window. */}+ <AppWindowIcon+ size={13}+ aria-hidden+ className="shrink-0 text-muted/60 transition-colors group-hover:text-cyan"+ /></span>{sub ? <span className="block truncate text-[11px] text-muted">{sub}</span> : null}</span>@@ -124,29 +139,34 @@ function ShowPageRow({{t(`showPages.status.${page.visibility}`)}</Badge>- {/* The single promote/demote gesture: the Dock switch pins (installs) or- unpins the page. Stop propagation so toggling it never expands the row. */}- <span className="flex shrink-0 flex-col items-center gap-1" onClick={(e) => e.stopPropagation()}>- <Switch checked={pinned} onCheckedChange={onTogglePin} label={t('library.dock.toggle')} />- <span className="font-mono text-[9px] font-bold uppercase tracking-[0.1em] text-muted">{t('library.dock.label')}</span>- </span>+ {/* Install toggle — adds the page to the Apps list (and docks it) or+ removes it from both. Stop propagation so it never opens the app. */}+ <Button+ type="button"+ variant={installed ? 'secondary' : 'accent'}+ size="xs"+ onClick={(e) => {+ e.stopPropagation();+ onToggleInstall(!installed);+ }}+ >+ {installed ? <Trash2 /> : <Plus />}+ <span className="hidden sm:inline">{installed ? t('library.apps.remove') : t('library.ai.add')}</span>+ </Button>+ {/* Explicit expand affordance for the management panel. */}<buttontype="button"- title={t('showPages.open')}- disabled={!href}+ aria-label={t('showPages.details')}+ aria-expanded={expanded}onClick={(e) => {e.stopPropagation();- if (href) window.open(href, '_blank', 'noopener,noreferrer');+ onToggleExpand();}}- className="grid size-8 shrink-0 place-items-center rounded-lg text-muted transition-colors hover:bg-foreground/[0.05] hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted"+ className="grid size-8 shrink-0 place-items-center rounded-lg text-muted transition-colors hover:bg-foreground/[0.05] hover:text-foreground">- <ExternalLink size={15} />+ {expanded ? <ChevronUp size={18} className="text-foreground" /> : <ChevronDown size={18} />}</button>-- <span className="flex w-[20px] shrink-0 justify-end">- {expanded ? <ChevronUp size={18} className="text-foreground" /> : <ChevronDown size={18} className="text-muted" />}- </span></div>{expanded ? (@@ -265,11 +285,21 @@ function ShowPageRow({);}-// The full Show Pages inventory view: search + visibility filter + expandable-// rows, each with the Dock switch that pins/unpins the page. Shared by the App-// Library window and the mobile full-screen route; the caller owns the pages-// state via useShowPages so both projections stay consistent.-export function ShowPagesView({ pages, busyId, setVisibility, rotate, onShareIdSaved, reload }: ShowPagesController) {+// 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+// management panel. Shared by the App Library window and the mobile full-screen+// route; the caller owns the pages state via useShowPages so both projections stay+// consistent, and passes `onOpenApp` so opening reuses the showpage window.+export function ShowPagesView({+ pages,+ busyId,+ setVisibility,+ rotate,+ onShareIdSaved,+ reload,+ onOpenApp,+}: ShowPagesController & { onOpenApp?: (sessionId: string, title?: string) => void }) {const { t } = useTranslation();const { isPinned, pin, unpin } = useDock();const [search, setSearch] = useState('');@@ -334,9 +364,10 @@ export function ShowPagesView({ pages, busyId, setVisibility, rotate, onShareIdSexpanded={expandedId === page.session_id}busy={busyId === page.session_id}copied={copiedId === page.session_id}- pinned={isPinned(page.session_id)}- onToggle={() => setExpandedId((id) => (id === page.session_id ? null : page.session_id))}- onTogglePin={(next) => (next ? pin(page.session_id) : unpin(page.session_id))}+ installed={isPinned(page.session_id)}+ onOpen={() => onOpenApp?.(page.session_id, page.title ?? undefined)}+ onToggleExpand={() => setExpandedId((id) => (id === page.session_id ? null : page.session_id))}+ onToggleInstall={(next) => (next ? pin(page.session_id) : unpin(page.session_id))}onSetVisibility={(visibility) => setVisibility(page, visibility)}onRotate={() => rotate(page)}onCopy={() => copy(page)}diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsxindex 7820bf2e6..3bba082bd 100644--- a/ui/src/components/apps/Dock.tsx+++ b/ui/src/components/apps/Dock.tsx@@ -1,6 +1,6 @@import { useEffect, useMemo, useRef, useState } from 'react';import { Reorder } from 'framer-motion';-import { Copy, ExternalLink, PinOff, Plus, SquarePlus } from 'lucide-react';+import { Copy, ExternalLink, LayoutGrid, PinOff, Plus, SquarePlus } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';@@ -19,12 +19,15 @@ type ResidentItem =// The unified Dock panel: app launcher + running indicators + minimized windows.// Built-in apps and pinned Show Pages share one reorderable row (server-persisted// order); a running app's tile reveals a + (and a right-click menu) to open-// another window. Pinned Show Pages add Open in New Tab / Unpin from Dock; the+// another window. EVERY tile — built-ins included (§7.1c) — can be unpinned from+// the Dock via the right-click menu (it stays installed, so the Apps view can+// re-dock it); pinned Show Pages additionally offer Open in New Tab. When the Dock+// is empty it shows an App Library shortcut rather than a dead surface. The// minimized-window strip trails the row and is not reorderable.export const Dock: React.FC = () => {const { t } = useTranslation();const wm = useWindowManager();- const { order, pins, unpin, setOrder } = useDock();+ const { order, pins, undock, setOrder } = useDock();const { windows, focusedId } = wm;const minimized = windows.filter((w) => w.minimized);@@ -104,8 +107,12 @@ export const Dock: React.FC = () => {setMenu(null);};- const unpinItem = (sessionId: string) => {- void unpin(sessionId);+ // Unpin from the Dock = undock (remove from `order`) for ANY tile, built-ins+ // included. It keeps the app installed (built-ins always; a Show Page stays in+ // the Apps list), so the tile can be re-docked from the Library — uninstalling+ // a page is the separate 移出 action there.+ const undockItem = (dockId: string) => {+ void undock(dockId);setMenu(null);};@@ -118,7 +125,9 @@ export const Dock: React.FC = () => {const menuItemCount = (item: ResidentItem) => {const running = windowsFor(item).length > 0;- return 1 + (running ? 1 : 0) + (item.kind === 'showpage' ? 2 : 0);+ // New Window (+ Show All Windows if running) + [Open in New Tab for a+ // Show Page] + Unpin from Dock (every tile).+ return 1 + (running ? 1 : 0) + (item.kind === 'showpage' ? 1 : 0) + 1;};return (@@ -210,6 +219,22 @@ export const Dock: React.FC = () => {})}</Reorder.Group>+ {/* Empty Dock (every tile undocked) is valid — offer a way back to the App+ Library instead of a dead, empty surface (§7.1c). */}+ {localOrder.length === 0 && (+ <button+ type="button"+ onClick={() => {+ wm.openApp('library');+ setMenu(null);+ }}+ className="flex items-center gap-2 rounded-xl border border-dashed border-border px-3 py-2.5 text-[12px] font-medium text-muted transition-colors hover:border-cyan/60 hover:text-foreground"+ >+ <LayoutGrid className="size-4 shrink-0 text-cyan" />+ <span className="whitespace-nowrap">{t('apps.dock.emptyHint')}</span>+ </button>+ )}+{minimized.length > 0 && <div className="mx-1 h-11 w-px shrink-0 self-center bg-border-strong" />}{/* Minimized windows render as a small window-style thumbnail (a mini titlebar with traffic@@ -267,20 +292,19 @@ export const Dock: React.FC = () => {/>)}{showpage && (- <>- <ContextMenuItem- icon={<ExternalLink className="size-[15px]" />}- label={t('apps.dock.openInNewTab')}- onClick={() => openExternal(showpage.sessionId)}- />- <ContextMenuItem- icon={<PinOff className="size-[15px]" />}- label={t('apps.dock.unpin')}- danger- onClick={() => unpinItem(showpage.sessionId)}- />- </>+ <ContextMenuItem+ icon={<ExternalLink className="size-[15px]" />}+ label={t('apps.dock.openInNewTab')}+ onClick={() => openExternal(showpage.sessionId)}+ />)}+ {/* Unpin (undock) is available on EVERY tile now, built-ins included. */}+ <ContextMenuItem+ icon={<PinOff className="size-[15px]" />}+ label={t('apps.dock.unpin')}+ danger+ onClick={() => undockItem(item.id)}+ /></ContextMenu>);})()}diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex 5e54f8a25..e3f49129a 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -8,7 +8,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { Select } from '../ui/select';import { Switch } from '../ui/switch';import { useApi } from '../../context/ApiContext';-import { useDock } from '../../context/DockContext';+import { showDockId, useDock } from '../../context/DockContext';import { copyTextToClipboard } from '../../lib/utils';import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';@@ -281,14 +281,23 @@ export const ShowPageShareControl: React.FC<{<div className="text-xs text-muted">{t('chat.showPage.pinToDockCaption')}</div></div><Switch- checked={dock.isPinned(sessionId)}+ checked={dock.isDocked(showDockId(sessionId))}onCheckedChange={(next) => {- void (next ? dock.pin(sessionId) : dock.unpin(sessionId));+ // "Pin to Dock" controls DOCK membership (§7.1c two-layer model):+ // ON docks (installing first if this page isn't installed yet —+ // pinning IS installing, §7.2); OFF undocks but keeps it installed+ // (uninstalling is the Library's 移出). Toggling off no longer+ // uninstalls, and undocking elsewhere now unchecks this switch.+ if (next) {+ void (dock.isPinned(sessionId) ? dock.dock(showDockId(sessionId)) : dock.pin(sessionId));+ } else {+ void dock.undock(showDockId(sessionId));+ }}}label={t('chat.showPage.pinToDock')}/></div>- {dock.isPinned(sessionId) && (+ {dock.isDocked(showDockId(sessionId)) && (<div className="mt-2 flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.08] px-2.5 py-1.5 text-xs text-foreground"><Check className="size-3.5 shrink-0 text-mint" /><span className="truncate">diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 7279312d2..c204ebd44 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -375,9 +375,11 @@ export type ApiContextType = {pinDockShowPage: (sessionId: string) => Promise<DockResponse>;/** Unpin a session's Show Page from the Dock (idempotent; leaves the page). */unpinDockShowPage: (sessionId: string) => Promise<DockResponse>;- /** Persist a new resident-tile order (silent on rejection so a stale reorder- * rolls back without a toast). Returns the payload; check ``ok``. */- setDockOrder: (order: string[]) => Promise<DockResponse>;+ /** Persist a new resident-tile (docked-subset) order. ``known`` is the client's+ * baseline id set (built-ins ∪ pins) for optimistic concurrency: a stale+ * reorder is rejected server-side and re-synced without a toast. Returns the+ * payload; check ``ok``. */+ setDockOrder: (order: string[], known?: string[]) => Promise<DockResponse>;getBindCodes: () => Promise<any>;createBindCode: (type: string, expiresAt?: string) => Promise<any>;deleteBindCode: (code: string) => Promise<any>;@@ -2113,17 +2115,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetDock: () => getJson('/api/dock'),pinDockShowPage: (sessionId) => postJson('/api/dock/pins', { session_id: sessionId }),unpinDockShowPage: (sessionId) => deleteJson(`/api/dock/pins/${encodeURIComponent(sessionId)}`),- setDockOrder: async (order) => {- // Suppress the global error toast: a concurrent-reorder rejection (the- // server rejects an order that no longer matches the known id set) is- // handled by the optimistic rollback in DockContext, not a user-facing- // error. The caller inspects ``ok``.+ setDockOrder: async (order, known) => {+ // Suppress the global error toast: a stale-reorder rejection (the server+ // rejects an order whose ``known`` baseline no longer matches its installed+ // set) is handled by the optimistic re-sync in DockContext, not a+ // user-facing error. ``known`` is the client's current id set (built-ins ∪+ // pins), sent so the server can reject a stale tab that would otherwise+ // silently undock a pin another tab installed. The caller inspects ``ok``.const { payloadJson } = await requestJson('/api/dock/order',{method: 'PUT',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ order }),+ body: JSON.stringify(known ? { order, known } : { order }),},'PUT /api/dock/order',{ handleError: false },diff --git a/ui/src/context/DockContext.test.ts b/ui/src/context/DockContext.test.tsindex d0f324ec7..7d14b06e5 100644--- a/ui/src/context/DockContext.test.ts+++ b/ui/src/context/DockContext.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from 'vitest';-import { dockIdToSession, MAX_PINNED_PAGES, reconcileDock, showDockId, type DockDoc } from './DockContext';+import {+ dockIdToSession,+ MAX_PINNED_PAGES,+ reconcileDock,+ seedDefaultDock,+ showDockId,+ type DockDoc,+} from './DockContext';const BUILTINS = ['files', 'terminal', 'editor'];@@ -16,31 +23,45 @@ describe('showDockId / dockIdToSession', () => {});});-describe('reconcileDock', () => {- it('defaults an empty doc to the built-ins in canonical order', () => {+describe('seedDefaultDock', () => {+ it('docks every built-in in canonical order, nothing installed', () => {+ const out = seedDefaultDock(BUILTINS);+ expect(out.order).toEqual(BUILTINS);+ expect(out.pins).toEqual([]);+ });+});++describe('reconcileDock (two-layer subset model)', () => {+ it('keeps an empty order empty — never force-seeds built-ins', () => {+ // The empty Dock is valid: reconcile honors it (only the pre-load default,+ // seedDefaultDock, docks built-ins).const out = reconcileDock({ order: [], pins: [] }, BUILTINS);- expect(out.order).toEqual(['files', 'terminal', 'editor']);+ expect(out.order).toEqual([]);expect(out.pins).toEqual([]);});- it('tolerates null / undefined input', () => {- expect(reconcileDock(null, BUILTINS).order).toEqual(BUILTINS);- expect(reconcileDock(undefined, BUILTINS).order).toEqual(BUILTINS);+ it('tolerates null / undefined input (empty subset)', () => {+ expect(reconcileDock(null, BUILTINS).order).toEqual([]);+ expect(reconcileDock(undefined, BUILTINS).order).toEqual([]);});- it('appends a missing built-in at the end, preserving the stored order', () => {- // 'editor' is absent from the stored order → it is appended last.+ it('does NOT re-add a built-in the stored order omits (undocked stays undocked)', () => {+ // 'editor' absent from the stored order → it stays out of the Dock.const out = reconcileDock({ order: ['terminal', 'files'], pins: [] }, BUILTINS);- expect(out.order).toEqual(['terminal', 'files', 'editor']);+ expect(out.order).toEqual(['terminal', 'files']);+ expect(out.order).not.toContain('editor');});- it('appends a pinned page that is missing from order', () => {+ it('does NOT dock an installed pin that is absent from order', () => {+ // The page is installed (in pins) but undocked (not in order) → order unchanged.const doc: DockDoc = {order: ['files', 'terminal', 'editor'],pins: [{ session_id: 'ses_a', title_snapshot: 'A', pinned_at: 't' }],};const out = reconcileDock(doc, BUILTINS);- expect(out.order).toEqual(['files', 'terminal', 'editor', 'show:ses_a']);+ expect(out.order).toEqual(['files', 'terminal', 'editor']);+ expect(out.order).not.toContain('show:ses_a');+ expect(out.pins).toHaveLength(1); // still installed});it('keeps a valid custom order (pin interleaved with built-ins)', () => {@@ -53,7 +74,7 @@ describe('reconcileDock', () => {it('dedupes pins by session id, keeping the first', () => {const doc: DockDoc = {- order: [],+ order: ['show:ses_a'],pins: [{ session_id: 'ses_a', title_snapshot: 'first', pinned_at: 't1' },{ session_id: 'ses_a', title_snapshot: 'second', pinned_at: 't2' },@@ -93,15 +114,15 @@ describe('reconcileDock', () => {expect(out.order).toEqual(['files', 'terminal', 'editor']);});- it('clamps oversized pins to the fixed pin budget, always keeping the built-ins', () => {+ it('clamps oversized pins to the fixed pin budget', () => {// Far more pins than the budget allows; only the first MAX_PINNED_PAGES survive.// The budget is FIXED (independent of the built-in count), so adding a built-in- // never shrinks it — a valid pre-Phase-2 dock keeps all its pins.+ // never shrinks it — a valid pre-Phase-2 dock keeps all its pins. The order is+ // honored as stored (empty here — nothing docked), never force-populated.const pins = Array.from({ length: 250 }, (_, i) => ({ session_id: `ses_${i}`, title_snapshot: '', pinned_at: '' }));const out = reconcileDock({ order: [], pins }, BUILTINS);expect(out.pins).toHaveLength(MAX_PINNED_PAGES); // 197, regardless of built-in count- expect(out.order).toHaveLength(BUILTINS.length + MAX_PINNED_PAGES);- expect(out.order.slice(0, BUILTINS.length)).toEqual(BUILTINS);+ expect(out.order).toEqual([]); // stored empty order honored});it('is idempotent', () => {diff --git a/ui/src/context/DockContext.tsx b/ui/src/context/DockContext.tsxindex 1b358f48e..166b0f077 100644--- a/ui/src/context/DockContext.tsx+++ b/ui/src/context/DockContext.tsx@@ -4,15 +4,19 @@ import { APP_LIST } from '../apps/registry';import { useApi } from './ApiContext';// The workbench Dock is durable, cross-device *product* state (see-// core/dock_store.py): which apps sit in the Dock and in what order. This-// provider fetches that document once, keeps it reconciled against the apps the-// client actually knows, and exposes optimistic pin/unpin/reorder actions that-// roll back if the server rejects the write.+// core/dock_store.py). Two layers (§7.1c): `pins` is the INSTALLED set of AI+// Show Pages (built-ins are implicitly installed); `order` is the DOCKED subset —+// the resident tiles, in user order, a SUBSET of the known ids. This provider+// fetches the document once, keeps it reconciled against the apps the client+// knows, and exposes optimistic install (pin) / uninstall (unpin) /+// dock / undock / reorder actions that roll back if the server rejects the write.//// A Dock item id is either a built-in app id verbatim (`files` / `terminal` /-// `editor`) or a pinned Show Page as `show:<session_id>`. The built-in id set-// and its canonical order are a contract shared with the backend's-// BUILTIN_DOCK_IDS — both derive from APP_LIST, so keep them in sync.+// `editor` / `library`) or a pinned Show Page as `show:<session_id>`. The+// built-in id set and its canonical order are a contract shared with the+// backend's BUILTIN_DOCK_IDS — both derive from APP_LIST, so keep them in sync.+// Any tile, built-ins included, can be undocked (absent from `order`); the empty+// Dock is a valid state.export type DockPin = {session_id: string;@@ -53,9 +57,11 @@ const BUILTIN_DOCK_IDS: string[] = APP_LIST.map((app) => app.id);* the server applies (core/dock_store._reconcile), so a stale or partial doc* from either side converges to one shape:* - dedupe pins by session id (first wins);- * - drop unknown / duplicate ids from `order`;- * - append any missing built-ins, then any missing pins, at the end.- * Pure: no I/O, safe to unit-test and to run on every read.+ * - clamp pins to the fixed install budget;+ * - drop unknown / duplicate ids from `order`.+ * The order is left as the stored SUBSET — built-ins and pins are NOT+ * force-appended (§7.1c), so an undocked tile stays undocked and the empty Dock+ * round-trips. Pure: no I/O, safe to unit-test and to run on every read.*/export function reconcileDock(doc: DockDoc | null | undefined, builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {const pins: DockPin[] = [];@@ -87,42 +93,48 @@ export function reconcileDock(doc: DockDoc | null | undefined, builtinIds: strinseen.add(id);}}- for (const id of builtinIds) {- if (!seen.has(id)) {- order.push(id);- seen.add(id);- }- }- for (const id of pinIds) {- if (!seen.has(id)) {- order.push(id);- seen.add(id);- }- }return { order, pins: clampedPins };}+/**+ * The pre-load default Dock: every built-in docked, nothing installed — matching+ * the server's seed for a fresh instance. Used only as the initial state before+ * the server document loads (avoids a flash of an empty Dock); once the GET+ * resolves, reconcileDock takes over and an undocked built-in stays undocked.+ */+export function seedDefaultDock(builtinIds: string[] = BUILTIN_DOCK_IDS): DockDoc {+ return { order: [...builtinIds], pins: [] };+}+export interface DockValue {- /** Reconciled resident-tile order (built-in ids + `show:<id>` pins). */+ /** Reconciled docked subset (built-in ids + `show:<id>` pins), in user order. */order: string[];+ /** Installed AI pages (built-ins are implicitly installed, not listed here). */pins: DockPin[];- /** Whether a session's Show Page is currently pinned. */+ /** Whether a session's Show Page is installed (pinned). */isPinned: (sessionId: string) => boolean;+ /** Whether a Dock id (built-in or `show:<id>`) is currently in the Dock. */+ isDocked: (dockId: string) => boolean;/** The pin record for a session, or null. */pinFor: (sessionId: string) => DockPin | null;- /** Pin a session's Show Page (optimistic; idempotent). */+ /** Install a session's Show Page — also docks it (optimistic; idempotent). */pin: (sessionId: string) => Promise<void>;- /** Unpin a session's Show Page (optimistic; idempotent). */+ /** Uninstall a session's Show Page — removes it from install + Dock (optimistic; idempotent). */unpin: (sessionId: string) => Promise<void>;+ /** Add a known tile (built-in or installed page) to the Dock (optimistic; idempotent). */+ dock: (dockId: string) => Promise<void>;+ /** Remove a tile from the Dock, keeping it installed (optimistic; idempotent). */+ undock: (dockId: string) => Promise<void>;/** Persist a new resident-tile order (optimistic; rolls back if rejected). */setOrder: (order: string[]) => Promise<void>;}const DockContext = createContext<DockValue | null>(null);-// Builtins-only default so the Dock renders its resident tiles immediately (no-// flicker) before the server document loads.-const DEFAULT_DOC: DockDoc = reconcileDock({ order: [], pins: [] });+// Every-built-in-docked default so the Dock renders its resident tiles+// immediately (no flicker) before the server document loads. Matches the+// server's fresh-instance seed; reconcileDock takes over once the GET resolves.+const DEFAULT_DOC: DockDoc = seedDefaultDock();export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const api = useApi();@@ -226,24 +238,56 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children);const setOrder = useCallback(- (order: string[]): Promise<void> =>- runMutation({ order, pins: docRef.current.pins }, () => api.setDockOrder(order)),+ (order: string[]): Promise<void> => {+ // Send the client's baseline id set (built-ins ∪ installed pins) so the+ // server can reject a STALE reorder: because omission now means "undock", a+ // tab that hasn't seen a pin another tab just installed would otherwise+ // silently undock it. On rejection runMutation re-syncs from the server.+ const known = [...BUILTIN_DOCK_IDS, ...docRef.current.pins.map((p) => showDockId(p.session_id))];+ return runMutation({ order, pins: docRef.current.pins }, () => api.setDockOrder(order, known));+ },[api, runMutation],);+ // Dock / undock a KNOWN tile (built-in or installed page) by editing the order+ // subset — install membership (pins) is untouched, so undocking keeps the page+ // installed. Both go through setOrder (PUT order), reusing its optimistic ++ // rollback path; idempotent so a redundant toggle makes no request.+ const dock = useCallback(+ (dockId: string): Promise<void> => {+ const cur = docRef.current.order;+ if (cur.includes(dockId)) return Promise.resolve();+ return setOrder([...cur, dockId]);+ },+ [setOrder],+ );++ const undock = useCallback(+ (dockId: string): Promise<void> => {+ const cur = docRef.current.order;+ if (!cur.includes(dockId)) return Promise.resolve();+ return setOrder(cur.filter((id) => id !== dockId));+ },+ [setOrder],+ );+const pinnedSessions = useMemo(() => new Set(doc.pins.map((p) => p.session_id)), [doc.pins]);+ const dockedSet = useMemo(() => new Set(doc.order), [doc.order]);const value = useMemo<DockValue>(() => ({order: doc.order,pins: doc.pins,isPinned: (sessionId: string) => pinnedSessions.has(sessionId),+ isDocked: (dockId: string) => dockedSet.has(dockId),pinFor: (sessionId: string) => doc.pins.find((p) => p.session_id === sessionId) ?? null,pin,unpin,+ dock,+ undock,setOrder,}),- [doc, pinnedSessions, pin, unpin, setOrder],+ [doc, pinnedSessions, dockedSet, pin, unpin, dock, undock, setOrder],);return <DockContext.Provider value={value}>{children}</DockContext.Provider>;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 5420a9b1e..f5145b0a8 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -101,6 +101,7 @@},"nav": {"dashboard": "Dashboard",+ "appLibrary": "App Library","channels": "Groups","users": "Direct Messages","showPages": "Show Pages",@@ -213,7 +214,7 @@"desc": "Your apps and Show Pages","tab": {"apps": "Apps",- "showPages": "Show Pages"+ "ai": "AI"},"searchApps": "Search apps…","searchPages": "Search pages…",@@ -221,15 +222,15 @@"builtin": "Built-in","showPage": "Show Page"},- "dock": {- "label": "Dock",- "toggle": "Show in Dock"- },"apps": {"system": "system",- "remove": "Remove from Dock",- "locked": "Built-in apps can't be removed",+ "dock": "Dock",+ "undock": "Undock",+ "remove": "Remove","empty": "No apps match your search."+ },+ "ai": {+ "add": "Add to Apps"}},"settings": {@@ -732,7 +733,11 @@"newWindow": "New Window","showAllWindows": "Show All Windows","openInNewTab": "Open in New Tab",- "unpin": "Unpin from Dock"+ "unpin": "Unpin from Dock",+ "emptyHint": "Dock is empty · Open App Library"+ },+ "launcher": {+ "openLibrary": "Open App Library"},"window": {"minimize": "Minimize",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2206bbb38..77ac1518b 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -101,6 +101,7 @@},"nav": {"dashboard": "控制台",+ "appLibrary": "应用库","channels": "群组","users": "私聊","showPages": "展示页面",@@ -213,7 +214,7 @@"desc": "你的应用与展示页面","tab": {"apps": "应用",- "showPages": "展示页面"+ "ai": "AI"},"searchApps": "搜索应用…","searchPages": "搜索页面…",@@ -221,15 +222,15 @@"builtin": "内置","showPage": "展示页面"},- "dock": {- "label": "Dock",- "toggle": "显示在 Dock"- },"apps": {"system": "系统",- "remove": "移出 Dock",- "locked": "内置应用不可移除",+ "dock": "固定到 Dock",+ "undock": "取消固定",+ "remove": "移出","empty": "没有匹配的应用。"+ },+ "ai": {+ "add": "添加到 App"}},"settings": {@@ -732,7 +733,11 @@"newWindow": "新建窗口","showAllWindows": "显示所有窗口","openInNewTab": "在新标签页打开",- "unpin": "从 Dock 取消固定"+ "unpin": "从 Dock 取消固定",+ "emptyHint": "Dock 为空 · 打开应用库"+ },+ "launcher": {+ "openLibrary": "打开应用库"},"window": {"minimize": "最小化",diff --git a/vibe/api.py b/vibe/api.pyindex 1e5281231..f0f4cefa3 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1208,12 +1208,14 @@ def unpin_dock_show_page(session_id: str) -> dict:return {"ok": True, "dock": unpin_show_page(session_id)}-def set_dock_order(order: list) -> dict:- """Persist a new resident-tile order. Raises ``DockError`` for an invalid- order (wrong id set / duplicates / too large), mapped to a 400."""+def set_dock_order(order: list, known: list | None = None) -> dict:+ """Persist a new resident-tile (docked-subset) order. ``known`` is the+ client's optimistic-concurrency baseline id set; when it no longer matches the+ server's, the write is rejected as stale so a stale tab can't silently undock a+ newer pin. Raises ``DockError`` for an invalid/stale order, mapped to a 400."""from core.dock_store import set_dock_order as _set_dock_order- return {"ok": True, "dock": _set_dock_order(order)}+ return {"ok": True, "dock": _set_dock_order(order, known=known)}def _vibe_agent_payload(agent, *, brief: bool = False) -> dict:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex a1eb953f7..87ff48bc5 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3606,7 +3606,11 @@ def dock_order_put():payload = request.json or {}try:- return jsonify(api.set_dock_order(payload.get("order")))+ # ``known`` (optional) is the client's baseline id set for optimistic+ # concurrency — set_dock_order rejects the write as stale when it no+ # longer matches the server's, so a stale tab can't silently undock a pin+ # another tab installed.+ return jsonify(api.set_dock_order(payload.get("order"), known=payload.get("known")))except DockError as exc:return _dock_error_response(exc)