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(show-pages): admin Show Pages management page (#382)

Call White86479926628c
diff --git a/docs/plans/admin-show-pages.md b/docs/plans/admin-show-pages.md
new file mode 100644
index 000000000..2b999bb01
--- /dev/null
+++ b/docs/plans/admin-show-pages.md
@@ -0,0 +1,40 @@
+# Admin "Show Pages" management page
+
+## Background
+Show Pages (`core/show_pages.py`) are per-session managed React pages, each `private` / `public` / `offline`. The CLI (`vibe show list/status/update`) manages them, but there is no Web UI. Add a `/admin/show-pages` page + sidebar entry so users can manage every Show Page from the console.
+
+Design is locked in `design.pen` frame **`m7wqzf`** ("vibe-remote — Show Pages (Dark)"); sidebar item added to shared component `kSWgv`.
+
+## Goal (user-approved)
+Admin can: list all Show Pages (private + public + offline), newest-first; per row see a friendly title + current status + live link; switch private↔public, take offline, restore from offline; rotate a public link; copy / open links.
+
+## Design decisions
+- **Status colors:** Public = gold, Private = cyan, Offline = grey/muted. Expanded-row selection glow stays mint (generic "selected" accent, not a status).
+- **Row label = `session.title` if set, else `session_id`** (mono). No channel/scope middle fallback (user decision 2026-06-02). Full `session_id` always shown in the expanded Details.
+- **3-way visibility segmented `[Private | Public | Offline]`** is the core switch (maps to `update --visibility`), covering restore-from-offline.
+- **Public extras:** copy link, open, rotate link (revokes + reissues).
+- **Cloud reachability:** when Avibe Cloud is not connected (`url_available == false`), show a gold warning by the live link; hidden when connected.
+- Row sub-line: `platform · agent` context.
+
+## Backend reuse (no new store logic)
+- `ShowPageStore.list_page()` already filters + orders `updated_at desc` + paginates. `show_page_payload()` returns visibility / urls / `url_available` / `url_guidance` / `share_id` / timestamps. Reuse as-is.
+- New `storage/sessions_service.read_session_titles(session_ids) -> {id: title}` (batch read of `agent_sessions.title`).
+- New `vibe/api.py`: `list_show_pages()`, `set_show_page_visibility(session_id, visibility)`, `rotate_show_page_share(session_id)` — wrap the store + title enrichment, return `{ok, ...}` dicts (mirror `get_vibe_agents` style).
+- New `ui_server.py` routes: `GET /api/show-pages`, `POST /api/show-pages/<sid>/visibility`, `POST /api/show-pages/<sid>/rotate-share`. `ShowPageError` -> mapped error response (mirror `_vibe_agent_result_response`).
+
+## Frontend
+- `AppShell.tsx`: add `adminItems` entry `{ to:'/admin/show-pages', label:t('nav.showPages'), icon: MonitorPlay }` between Users and Settings.
+- `App.tsx`: route `/admin/show-pages -> <ShowPagesPage/>`.
+- `components/ShowPagesPage.tsx`: header + search, visibility filter segmented, table (SESSION / VISIBILITY / LIVE LINK / UPDATED / actions), expandable row -> segmented + copy/open + rotate + Details. Reuse `Badge`/`Button`/ui primitives + `UserList` list/row layout classes. Client-side filter/search; fetch all via `getShowPages`.
+- `context/ApiContext.tsx`: `getShowPages()`, `setShowPageVisibility(sid, vis)`, `rotateShowPageShare(sid)`.
+- `i18n/en.json` + `zh.json`: `nav.showPages` + `showPages.*` keys.
+
+## Build order
+1. Backend: `sessions_service.read_session_titles` + `api` fns + routes + pytest.
+2. Frontend: ApiContext + i18n + AppShell nav + App route + ShowPagesPage; `npm run build`.
+3. Verify the built page side-by-side vs design frame `m7wqzf`.
+
+## Evidence layers
+- unit: pytest for `api.list_show_pages` (title join), visibility update, rotate-share, error mapping (canned sqlite state).
+- build: `npm run build` in `ui/`; `ruff check` on changed Python.
+- manual: render `/admin/show-pages` vs the design frame.
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 1ad1f4111..097068e06 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -12,6 +12,7 @@ from sqlalchemy import Connection, select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.exc import IntegrityError
+from config import paths
from config.v2_sessions import ActivePollInfo, SessionState
from config.v2_settings import _split_scoped_key
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
@@ -48,6 +49,55 @@ def _set_native_once(conn: Connection, row_id: str, encoded_session_id: str) ->
return False
+_BACKEND_LABELS = {"claude": "Claude", "codex": "Codex", "opencode": "OpenCode"}
+
+
+def read_session_display_meta(
+ session_ids: list[str], *, db_path: Path | None = None
+) -> dict[str, dict[str, str | None]]:
+ """Map session id -> display metadata for Show Page rows.
+
+ Returns ``{id: {"title", "platform", "agent"}}``. ``title`` is the user-set
+ ``agent_sessions.title`` (``None`` for IM-dispatch sessions, which always
+ persist ``title=None`` — the UI falls back to the session id). ``agent``
+ falls back to a friendly backend label when no explicit agent name is set.
+ """
+ ids = [str(value) for value in session_ids if str(value or "").strip()]
+ if not ids:
+ return {}
+ engine = create_sqlite_engine(db_path or paths.get_sqlite_state_path())
+ try:
+ with engine.connect() as conn:
+ rows = (
+ conn.execute(
+ select(
+ agent_sessions.c.id,
+ agent_sessions.c.title,
+ agent_sessions.c.agent_name,
+ agent_sessions.c.agent_backend,
+ scopes.c.platform,
+ )
+ .select_from(
+ agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)
+ )
+ .where(agent_sessions.c.id.in_(ids))
+ )
+ .mappings()
+ .all()
+ )
+ finally:
+ engine.dispose()
+ meta: dict[str, dict[str, str | None]] = {}
+ for row in rows:
+ title = str(row["title"] or "").strip() or None
+ platform = str(row["platform"] or "").strip() or None
+ agent_name = str(row["agent_name"] or "").strip()
+ backend = str(row["agent_backend"] or "").strip()
+ agent = agent_name or _BACKEND_LABELS.get(backend, backend or None)
+ meta[str(row["id"])] = {"title": title, "platform": platform, "agent": agent}
+ return meta
+
+
class SQLiteSessionsService:
def __init__(self, db_path: Path):
self.db_path = db_path
diff --git a/tests/test_show_pages_admin_api.py b/tests/test_show_pages_admin_api.py
new file mode 100644
index 000000000..94a6eb140
--- /dev/null
+++ b/tests/test_show_pages_admin_api.py
@@ -0,0 +1,137 @@
+"""Web UI admin Show Pages API: listing (with title join), visibility, rotate."""
+
+import pytest
+
+from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
+from tests.test_ui_remote_access_auth import _save_config
+from vibe import api
+from vibe.ui_server import app
+
+
+def _seed_session(session_id: str, *, title: str | None = None) -> None:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="slack", scope_type="channel", native_id=f"chan_{session_id}", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_" + session_id,
+ native_session_id="",
+ title=title,
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ finally:
+ engine.dispose()
+
+
+def _set_visibility(session_id: str, visibility: str) -> None:
+ ensure_show_page_dir(session_id)
+ store = ShowPageStore()
+ try:
+ store.update_visibility(session_id, visibility)
+ finally:
+ store.close()
+
+
+def test_list_show_pages_orders_newest_first_and_joins_title(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_titled", title="Q2 funnel dashboard")
+ _seed_session("ses_plain")
+ _set_visibility("ses_titled", "public")
+ _set_visibility("ses_plain", "private")
+
+ result = api.list_show_pages()
+
+ assert result["ok"] is True
+ assert result["count"] == 2
+ assert "url_available" in result
+ by_id = {page["session_id"]: page for page in result["pages"]}
+ assert by_id["ses_titled"]["title"] == "Q2 funnel dashboard"
+ assert by_id["ses_titled"]["platform"] == "slack"
+ assert by_id["ses_titled"]["agent"] == "Claude"
+ assert by_id["ses_titled"]["visibility"] == "public"
+ assert by_id["ses_titled"]["share_id"]
+ # IM-dispatch sessions persist title=None; the UI falls back to the id.
+ assert by_id["ses_plain"]["title"] is None
+ assert by_id["ses_plain"]["visibility"] == "private"
+ updated_ats = [page["updated_at"] for page in result["pages"]]
+ assert updated_ats == sorted(updated_ats, reverse=True)
+
+
+def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_x")
+ _set_visibility("ses_x", "private")
+
+ public = api.set_show_page_visibility("ses_x", "public")
+ assert public["ok"] is True
+ assert public["visibility"] == "public"
+ assert public["share_id"]
+
+ offline = api.set_show_page_visibility("ses_x", "offline")
+ assert offline["visibility"] == "offline"
+ assert offline["offline"] is True
+ assert offline["offline_at"]
+
+
+def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_x")
+
+ with pytest.raises(ShowPageError) as excinfo:
+ api.set_show_page_visibility("ses_x", "bogus")
+ assert excinfo.value.code == "invalid_visibility"
+
+
+def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_x")
+ _set_visibility("ses_x", "private")
+
+ with pytest.raises(ShowPageError) as excinfo:
+ api.rotate_show_page_share("ses_x")
+ assert excinfo.value.code == "not_public"
+
+ public = api.set_show_page_visibility("ses_x", "public")
+ rotated = api.rotate_show_page_share("ses_x")
+ assert rotated["ok"] is True
+ assert rotated["share_id"]
+ assert rotated["share_id"] != public["share_id"]
+ assert rotated["previous_share_id"] == public["share_id"]
+
+
+def test_show_pages_list_route_returns_payload(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _seed_session("ses_route", title="Release notes preview")
+ _set_visibility("ses_route", "public")
+
+ response = app.test_client().get("/api/show-pages", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["ok"] is True
+ page = next(item for item in body["pages"] if item["session_id"] == "ses_route")
+ assert page["title"] == "Release notes preview"
+ assert page["visibility"] == "public"
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 9e141f576..23a800632 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -11,6 +11,7 @@ import { ChatPage } from './components/workbench/ChatPage';
import { Dashboard } from './components/Dashboard';
import { ChannelList } from './components/steps/ChannelList';
import { UserList } from './components/steps/UserList';
+import { ShowPagesPage } from './components/ShowPagesPage';
import { SettingsDiagnosticsPage } from './components/settings/SettingsDiagnosticsPage';
import { SettingsBackendsPage } from './components/settings/SettingsBackendsPage';
import { SettingsDependenciesPage } from './components/settings/SettingsDependenciesPage';
@@ -232,6 +233,7 @@ function AppRoutes() {
<Route path="/admin/dashboard" element={<Dashboard />} />
<Route path="/admin/groups" element={<ChannelList isPage />} />
<Route path="/admin/users" element={<UserList />} />
+ <Route path="/admin/show-pages" element={<ShowPagesPage />} />
<Route path="/admin/logs" element={<SettingsLogsPage standalone />} />
{/* No client-side route at /admin/settings: Flask owns GET /settings as
a JSON API. The Flask handler redirects browser-Accept hits to
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 8335f935f..05be3208d 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';
-import { ArrowLeft, ArrowRight, Hash, LayoutDashboard, Settings, SlidersHorizontal, Users } from 'lucide-react';
+import { ArrowLeft, ArrowRight, Hash, LayoutDashboard, MonitorPlay, Settings, SlidersHorizontal, Users } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -97,6 +97,7 @@ export const AppShell: React.FC = () => {
{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },
...(hasChannelPlatforms ? [{ to: '/admin/groups', label: t('nav.channels'), icon: Hash }] : []),
{ to: '/admin/users', label: t('nav.users'), icon: Users },
+ { to: '/admin/show-pages', label: t('nav.showPages'), icon: MonitorPlay },
{
to: '/admin/settings/service',
label: t('nav.settings'),
diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsx
new file mode 100644
index 000000000..346e0b1d8
--- /dev/null
+++ b/ui/src/components/ShowPagesPage.tsx
@@ -0,0 +1,412 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import {
+ Check,
+ ChevronDown,
+ ChevronUp,
+ CloudOff,
+ Copy,
+ ExternalLink,
+ Globe,
+ Link2,
+ Lock,
+ RefreshCw,
+ RotateCw,
+ TriangleAlert,
+ type LucideIcon,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import { useApi } from '../context/ApiContext';
+import { useToast } from '../context/ToastContext';
+import { copyTextToClipboard } from '../lib/utils';
+import { SearchField } from './settings/SettingsPrimitives';
+import { Button } from './ui/button';
+import { Badge } from './ui/badge';
+import { SegmentedRadio, type SegmentedTone } from './ui/segmented';
+
+type Visibility = 'private' | 'public' | 'offline';
+type Filter = 'all' | Visibility;
+
+interface ShowPage {
+ session_id: string;
+ visibility: Visibility;
+ title: string | null;
+ platform: string | null;
+ agent: string | null;
+ path: string;
+ active_url: string | null;
+ private_url: string | null;
+ public_url: string | null;
+ url_available: boolean;
+ share_id: string | null;
+ offline: boolean;
+ offline_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+const LABEL = 'font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted';
+
+const STATUS: Record<
+ Visibility,
+ { Icon: LucideIcon; badge: 'warning' | 'info' | 'secondary'; tone: SegmentedTone; dot: string; tile: string; iconColor: string }
+> = {
+ public: { Icon: Globe, badge: 'warning', tone: 'gold', dot: 'bg-gold', tile: 'border-gold/40 bg-gold/10', iconColor: 'text-gold' },
+ private: { Icon: Lock, badge: 'info', tone: 'cyan', dot: 'bg-cyan', tile: 'border-cyan/40 bg-cyan-soft', iconColor: 'text-cyan' },
+ offline: { Icon: CloudOff, badge: 'secondary', tone: 'muted', dot: 'bg-muted', tile: 'border-border-strong bg-foreground/[0.04]', iconColor: 'text-muted' },
+};
+
+// Same-origin path a Show Page is served at locally — usable even when Avibe
+// Cloud is off, where the cloud-qualified urls in the payload are null.
+function localPath(page: ShowPage): string | null {
+ if (page.visibility === 'private') return `/show/${encodeURIComponent(page.session_id)}/`;
+ if (page.visibility === 'public' && page.share_id) return `/p/${encodeURIComponent(page.share_id)}/`;
+ return null;
+}
+
+function liveHref(page: ShowPage): string | null {
+ return page.active_url || localPath(page);
+}
+
+function copyHref(page: ShowPage): string | null {
+ const href = liveHref(page);
+ if (!href) return null;
+ return href.startsWith('http') ? href : window.location.origin + href;
+}
+
+function displayLink(page: ShowPage): string | null {
+ const href = liveHref(page);
+ return href ? href.replace(/^https?:\/\//, '') : null;
+}
+
+interface RowProps {
+ page: ShowPage;
+ expanded: boolean;
+ busy: boolean;
+ copied: boolean;
+ onToggle: () => void;
+ onSetVisibility: (visibility: Visibility) => void;
+ onRotate: () => void;
+ onCopy: () => void;
+}
+
+function ShowPageRow({ page, expanded, busy, copied, onToggle, onSetVisibility, onRotate, onCopy }: RowProps) {
+ const { t, i18n } = useTranslation();
+ const status = STATUS[page.visibility];
+ const { Icon } = status;
+ const label = page.title || page.session_id;
+ const sub = [page.platform ? t(`platform.${page.platform}.title`, { defaultValue: page.platform }) : null, page.agent]
+ .filter(Boolean)
+ .join(' · ');
+
+ const relative = (iso: string): string => {
+ const then = new Date(iso).getTime();
+ if (Number.isNaN(then)) return '';
+ const seconds = Math.round((then - Date.now()) / 1000);
+ const rtf = new Intl.RelativeTimeFormat(i18n.language, { numeric: 'auto' });
+ const abs = Math.abs(seconds);
+ if (abs < 60) return rtf.format(Math.round(seconds), 'second');
+ if (abs < 3600) return rtf.format(Math.round(seconds / 60), 'minute');
+ if (abs < 86400) return rtf.format(Math.round(seconds / 3600), 'hour');
+ if (abs < 7 * 86400) return rtf.format(Math.round(seconds / 86400), 'day');
+ return new Date(iso).toLocaleDateString(i18n.language, { month: 'short', day: 'numeric' });
+ };
+ const absolute = (iso: string): string => {
+ const date = new Date(iso);
+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString(i18n.language, { dateStyle: 'medium', timeStyle: 'short' });
+ };
+
+ const href = copyHref(page);
+ const shown = displayLink(page);
+
+ return (
+ <div className={clsx('border-b border-border last:border-b-0', expanded && 'border-y border-mint/30')}>
+ <button
+ type="button"
+ onClick={onToggle}
+ className={clsx(
+ 'flex w-full items-center gap-4 px-6 py-3.5 text-left transition-colors',
+ expanded ? 'bg-surface-2' : 'hover:bg-foreground/[0.02]'
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-3">
+ <span className={clsx('flex size-8 shrink-0 items-center justify-center rounded-lg border', status.tile)}>
+ <Icon size={16} className={status.iconColor} />
+ </span>
+ <span className="min-w-0">
+ <span className={clsx('block truncate text-[13px] font-semibold text-foreground', !page.title && 'font-mono')}>
+ {label}
+ </span>
+ {sub ? <span className="block truncate text-[11px] text-muted">{sub}</span> : null}
+ </span>
+ </span>
+
+ <span className="w-[120px] shrink-0">
+ <Badge variant={status.badge}>
+ <span className={clsx('size-1.5 rounded-full', status.dot)} />
+ {t(`showPages.status.${page.visibility}`)}
+ </Badge>
+ </span>
+
+ <span className="hidden w-[280px] shrink-0 items-center gap-1.5 lg:flex">
+ {shown ? (
+ <span className="truncate font-mono text-[12px] text-muted">{shown}</span>
+ ) : (
+ <span className="text-[13px] text-muted">—</span>
+ )}
+ </span>
+
+ <span className="hidden w-[96px] shrink-0 text-[12px] text-muted sm:block">{relative(page.updated_at)}</span>
+
+ <span className="flex w-[24px] shrink-0 justify-end">
+ {expanded ? <ChevronUp size={18} className="text-foreground" /> : <ChevronDown size={18} className="text-muted" />}
+ </span>
+ </button>
+
+ {expanded ? (
+ <div className="bg-surface-2 px-6 pb-6 pt-2">
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_300px]">
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-2">
+ <span className={LABEL}>{t('showPages.visibilityLabel')}</span>
+ <div className="max-w-[360px]">
+ <SegmentedRadio<Visibility>
+ value={page.visibility}
+ tone={status.tone}
+ disabled={busy}
+ ariaLabel={t('showPages.visibilityLabel')}
+ onChange={onSetVisibility}
+ options={[
+ { id: 'private', label: t('showPages.status.private') },
+ { id: 'public', label: t('showPages.status.public') },
+ { id: 'offline', label: t('showPages.status.offline') },
+ ]}
+ />
+ </div>
+ </div>
+
+ {page.visibility === 'offline' ? (
+ <p className="text-[12px] text-muted">{t('showPages.offlineNoLink')}</p>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <span className={LABEL}>{t('showPages.liveLink')}</span>
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2 rounded-lg border border-border bg-foreground/[0.03] px-3 py-2">
+ <Link2 size={14} className={page.visibility === 'public' ? 'text-gold' : 'text-cyan'} />
+ <span className="truncate font-mono text-[12px] text-foreground">{shown}</span>
+ </div>
+ <Button type="button" variant="secondary" size="sm" onClick={onCopy} disabled={!href}>
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ {copied ? t('showPages.copied') : t('showPages.copy')}
+ </Button>
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ disabled={!href}
+ onClick={() => href && window.open(href, '_blank', 'noopener')}
+ >
+ <ExternalLink size={14} />
+ {t('showPages.open')}
+ </Button>
+ </div>
+ {page.visibility === 'public' && !page.url_available ? (
+ <div className="flex flex-wrap items-center gap-1.5 text-[11px]">
+ <TriangleAlert size={13} className="text-gold" />
+ <span className="text-muted">{t('showPages.cloudOff')}</span>
+ <a href="/admin/settings/service" className="font-semibold text-gold hover:underline">
+ {t('showPages.connectCloud')} →
+ </a>
+ </div>
+ ) : null}
+ </div>
+ )}
+
+ {page.visibility === 'public' ? (
+ <div className="flex flex-col gap-2">
+ <span className={LABEL}>{t('showPages.shareLink')}</span>
+ <div className="flex flex-wrap items-center gap-3">
+ <Button type="button" variant="secondary" size="sm" onClick={onRotate} disabled={busy}>
+ <RotateCw size={14} />
+ {t('showPages.rotate')}
+ </Button>
+ <span className="text-[11px] text-muted">{t('showPages.rotateHint')}</span>
+ </div>
+ </div>
+ ) : null}
+ </div>
+
+ <div className="flex flex-col gap-3 rounded-xl border border-border bg-foreground/[0.02] p-4">
+ <span className={LABEL}>{t('showPages.details')}</span>
+ {[
+ { k: t('showPages.detail.session'), v: page.session_id, mono: true },
+ { k: t('showPages.detail.workspace'), v: page.path, mono: true },
+ { k: t('showPages.detail.created'), v: absolute(page.created_at), mono: false },
+ { k: t('showPages.detail.updated'), v: relative(page.updated_at), mono: false },
+ ].map((row) => (
+ <div key={row.k} className="flex flex-col gap-1">
+ <span className={LABEL}>{row.k}</span>
+ <span className={clsx('break-all text-[12px] text-foreground', row.mono && 'font-mono')}>{row.v}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+export function ShowPagesPage() {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [pages, setPages] = useState<ShowPage[]>([]);
+ const [search, setSearch] = useState('');
+ const [filter, setFilter] = useState<Filter>('all');
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const [copiedId, setCopiedId] = useState<string | null>(null);
+ const [refreshTrigger, setRefreshTrigger] = useState(0);
+
+ const load = useCallback(() => {
+ api
+ .getShowPages()
+ .then((res: any) => setPages(Array.isArray(res?.pages) ? res.pages : []))
+ .catch(() => {});
+ }, [api]);
+
+ useEffect(() => {
+ load();
+ }, [load, refreshTrigger]);
+
+ const mergePage = (next: ShowPage) =>
+ setPages((prev) => prev.map((page) => (page.session_id === next.session_id ? { ...page, ...next } : page)));
+
+ const setVisibility = async (page: ShowPage, visibility: Visibility) => {
+ if (page.visibility === visibility || busyId) return;
+ setBusyId(page.session_id);
+ try {
+ const res = await api.setShowPageVisibility(page.session_id, visibility);
+ mergePage(res);
+ showToast(t('showPages.toast.updated'));
+ } catch {
+ // ApiContext surfaces a toast on failure.
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ const rotate = async (page: ShowPage) => {
+ if (busyId) return;
+ setBusyId(page.session_id);
+ try {
+ const res = await api.rotateShowPageShare(page.session_id);
+ mergePage(res);
+ showToast(t('showPages.toast.rotated'));
+ } catch {
+ // handled by ApiContext
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ const copy = async (page: ShowPage) => {
+ const href = copyHref(page);
+ if (!href) return;
+ await copyTextToClipboard(href);
+ setCopiedId(page.session_id);
+ window.setTimeout(() => setCopiedId((id) => (id === page.session_id ? null : id)), 1600);
+ };
+
+ const visible = useMemo(() => {
+ const query = search.trim().toLowerCase();
+ return pages.filter((page) => {
+ if (filter !== 'all' && page.visibility !== filter) return false;
+ if (!query) return true;
+ return (page.title || '').toLowerCase().includes(query) || page.session_id.toLowerCase().includes(query);
+ });
+ }, [pages, filter, search]);
+
+ return (
+ <div className="flex h-full flex-col gap-5">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div className="flex flex-col gap-1.5">
+ <h1 className="text-[28px] font-bold leading-tight tracking-[-0.4px] text-foreground">{t('showPages.title')}</h1>
+ <p className="text-[14px] leading-[1.55] text-muted">{t('showPages.subtitle')}</p>
+ </div>
+ <div className="flex items-center gap-2">
+ <SearchField
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('showPages.searchPlaceholder')}
+ className="w-[280px]"
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => setRefreshTrigger((v) => v + 1)}
+ title={t('common.refresh', { defaultValue: 'Refresh' })}
+ className="px-3"
+ >
+ <RefreshCw size={14} />
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center justify-between gap-3 px-1 py-2">
+ <div className="flex items-center gap-2">
+ <span className="text-[15px] font-semibold text-foreground">{t('showPages.allPages')}</span>
+ <span className="rounded-full bg-foreground/[0.08] px-1.5 py-0.5 font-mono text-[11px] font-bold text-muted">
+ {pages.length}
+ </span>
+ <span className="text-[12px] text-muted">· {t('showPages.sortedRecent')}</span>
+ </div>
+ <SegmentedRadio<Filter>
+ value={filter}
+ onChange={setFilter}
+ ariaLabel={t('showPages.filterAria')}
+ options={[
+ { id: 'all', label: t('showPages.filter.all') },
+ { id: 'private', label: t('showPages.filter.private') },
+ { id: 'public', label: t('showPages.filter.public') },
+ { id: 'offline', label: t('showPages.filter.offline') },
+ ]}
+ />
+ </div>
+
+ <div className="flex-1 overflow-y-auto">
+ {visible.length === 0 ? (
+ <div className="rounded-xl border border-dashed border-border bg-surface-3/60 p-8 text-center text-[13px] text-muted">
+ {pages.length === 0 ? t('showPages.empty') : t('showPages.emptyFiltered')}
+ </div>
+ ) : (
+ <div className="overflow-hidden rounded-xl border border-border bg-background">
+ <div className="flex items-center gap-4 border-b border-border bg-surface px-6 py-3">
+ <span className={clsx(LABEL, 'flex-1')}>{t('showPages.col.session')}</span>
+ <span className={clsx(LABEL, 'w-[120px] shrink-0')}>{t('showPages.col.visibility')}</span>
+ <span className={clsx(LABEL, 'hidden w-[280px] shrink-0 lg:block')}>{t('showPages.col.link')}</span>
+ <span className={clsx(LABEL, 'hidden w-[96px] shrink-0 sm:block')}>{t('showPages.col.updated')}</span>
+ <span className="w-[24px] shrink-0" />
+ </div>
+ {visible.map((page) => (
+ <ShowPageRow
+ key={page.session_id}
+ page={page}
+ expanded={expandedId === page.session_id}
+ busy={busyId === page.session_id}
+ copied={copiedId === page.session_id}
+ onToggle={() => setExpandedId((id) => (id === page.session_id ? null : page.session_id))}
+ onSetVisibility={(visibility) => setVisibility(page, visibility)}
+ onRotate={() => rotate(page)}
+ onCopy={() => copy(page)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/ui/segmented.tsx b/ui/src/components/ui/segmented.tsx
index b4251932a..72cf38752 100644
--- a/ui/src/components/ui/segmented.tsx
+++ b/ui/src/components/ui/segmented.tsx
@@ -22,12 +22,23 @@ export type SegmentedRadioOption<T extends string> = {
label: string;
};
+/** Active-option color. Mint is the default; Show Pages tints by visibility. */
+export type SegmentedTone = 'mint' | 'gold' | 'cyan' | 'muted';
+
+const ACTIVE_TONES: Record<SegmentedTone, string> = {
+ mint: 'border border-mint/30 bg-mint-soft font-bold text-mint',
+ gold: 'border border-gold/40 bg-gold/10 font-bold text-gold',
+ cyan: 'border border-cyan/40 bg-cyan-soft font-bold text-cyan',
+ muted: 'border border-border-strong bg-foreground/[0.06] font-bold text-foreground',
+};
+
export interface SegmentedRadioProps<T extends string> {
value: T;
onChange: (next: T) => void;
options: ReadonlyArray<SegmentedRadioOption<T>>;
ariaLabel: string;
disabled?: boolean;
+ tone?: SegmentedTone;
}
export function SegmentedRadio<T extends string>({
@@ -36,6 +47,7 @@ export function SegmentedRadio<T extends string>({
options,
ariaLabel,
disabled,
+ tone = 'mint',
}: SegmentedRadioProps<T>) {
return (
<div
@@ -60,7 +72,7 @@ export function SegmentedRadio<T extends string>({
className={clsx(
'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
active
- ? 'border border-mint/30 bg-mint-soft font-bold text-mint'
+ ? ACTIVE_TONES[tone]
: 'font-medium text-muted hover:text-foreground',
disabled && 'cursor-not-allowed',
)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 91a714bce..6078eccd9 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -13,6 +13,9 @@ export type ApiContextType = {
saveUsers: (payload: any, platform?: string) => Promise<any>;
toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;
removeUser: (userId: string, platform?: string) => Promise<any>;
+ getShowPages: () => Promise<any>;
+ setShowPageVisibility: (sessionId: string, visibility: string) => Promise<any>;
+ rotateShowPageShare: (sessionId: string) => Promise<any>;
getBindCodes: () => Promise<any>;
createBindCode: (type: string, expiresAt?: string) => Promise<any>;
deleteBindCode: (code: string) => Promise<any>;
@@ -1047,6 +1050,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
saveUsers: (payload, platform) => postJson('/api/users', platform ? { ...payload, platform } : payload),
toggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),
removeUser: (userId, platform) => apiFetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),
+ getShowPages: () => getJson('/api/show-pages'),
+ setShowPageVisibility: (sessionId, visibility) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/visibility`, { visibility }),
+ rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
deleteBindCode: (code) => apiFetch(`/api/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 9aa27a663..919089789 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -71,10 +71,38 @@
"dashboard": "Dashboard",
"channels": "Groups",
"users": "Direct Messages",
+ "showPages": "Show Pages",
"settings": "Settings",
"remoteAccess": "Remote Access",
"doctor": "Doctor"
},
+ "showPages": {
+ "title": "Show Pages",
+ "subtitle": "Every agent session has a Show Page. Make it public, keep it private, or take it offline.",
+ "searchPlaceholder": "Search by title or session…",
+ "allPages": "All pages",
+ "sortedRecent": "Sorted by most recent",
+ "filterAria": "Filter by visibility",
+ "filter": { "all": "All", "private": "Private", "public": "Public", "offline": "Offline" },
+ "status": { "private": "Private", "public": "Public", "offline": "Offline" },
+ "col": { "session": "Session", "visibility": "Visibility", "link": "Live link", "updated": "Updated" },
+ "empty": "No Show Pages yet. They appear here once an agent session creates one.",
+ "emptyFiltered": "No Show Pages match this filter.",
+ "visibilityLabel": "Visibility",
+ "liveLink": "Live link",
+ "offlineNoLink": "This page is offline — bring it back with the control above to get a live link.",
+ "copy": "Copy",
+ "copied": "Copied",
+ "open": "Open",
+ "shareLink": "Share link",
+ "rotate": "Rotate link",
+ "rotateHint": "Generates a new link and disables the current one.",
+ "cloudOff": "Avibe Cloud is off — this link only opens on this device.",
+ "connectCloud": "Connect Avibe Cloud",
+ "details": "Details",
+ "detail": { "session": "Session ID", "workspace": "Workspace", "created": "Created", "updated": "Last updated" },
+ "toast": { "updated": "Show Page updated", "rotated": "Share link rotated" }
+ },
"settings": {
"tabs": {
"service": "Service",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c8b08b579..a5bbcd27b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -71,10 +71,38 @@
"dashboard": "仪表盘",
"channels": "群组",
"users": "私聊",
+ "showPages": "展示页面",
"settings": "设置",
"remoteAccess": "远程访问",
"doctor": "诊断"
},
+ "showPages": {
+ "title": "展示页面",
+ "subtitle": "每个 Agent 会话都有一个展示页面。可以将其公开、保持私有,或下线。",
+ "searchPlaceholder": "按标题或会话搜索…",
+ "allPages": "全部页面",
+ "sortedRecent": "按最近活动排序",
+ "filterAria": "按可见性筛选",
+ "filter": { "all": "全部", "private": "私有", "public": "公开", "offline": "已下线" },
+ "status": { "private": "私有", "public": "公开", "offline": "已下线" },
+ "col": { "session": "会话", "visibility": "可见性", "link": "访问链接", "updated": "更新时间" },
+ "empty": "暂无展示页面。当 Agent 会话创建展示页面后会显示在这里。",
+ "emptyFiltered": "没有符合该筛选条件的展示页面。",
+ "visibilityLabel": "可见性",
+ "liveLink": "访问链接",
+ "offlineNoLink": "该页面已下线——用上方的开关重新上线即可获得访问链接。",
+ "copy": "复制",
+ "copied": "已复制",
+ "open": "打开",
+ "shareLink": "分享链接",
+ "rotate": "更换链接",
+ "rotateHint": "生成新链接并使当前链接立即失效。",
+ "cloudOff": "Avibe Cloud 未开启——此链接仅能在本机打开。",
+ "connectCloud": "连接 Avibe Cloud",
+ "details": "详情",
+ "detail": { "session": "会话 ID", "workspace": "工作区", "created": "创建时间", "updated": "最近更新" },
+ "toast": { "updated": "展示页面已更新", "rotated": "分享链接已更换" }
+ },
"settings": {
"tabs": {
"service": "服务",
diff --git a/vibe/api.py b/vibe/api.py
index 875636286..203215824 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -748,6 +748,81 @@ def get_agent_backend_catalog() -> dict:
return {"backends": agent_backend_catalog_payload()}
+def _apply_session_meta(payloads: list[dict]) -> list[dict]:
+ """Attach title / platform / agent to each Show Page payload from agent_sessions."""
+ from storage.sessions_service import read_session_display_meta
+
+ meta = read_session_display_meta([payload["session_id"] for payload in payloads])
+ for payload in payloads:
+ info = meta.get(payload["session_id"], {})
+ payload["title"] = info.get("title")
+ payload["platform"] = info.get("platform")
+ payload["agent"] = info.get("agent")
+ return payloads
+
+
+def list_show_pages() -> dict:
+ """All Show Pages, newest-first, each enriched with the session title.
+
+ Reuses ``ShowPageStore.list_page`` (already ordered by ``updated_at`` desc)
+ and joins ``agent_sessions.title`` so the UI can label rows by title and
+ fall back to the session id when no title is set.
+ """
+ from core.show_pages import (
+ ShowPageStore,
+ avibe_cloud_connect_guidance,
+ avibe_cloud_url_available,
+ show_page_payload,
+ )
+ config = V2Config.load()
+ store = ShowPageStore()
+ try:
+ result = store.list_page(page_request=None)
+ pages = [show_page_payload(page, config=config) for page in result.items]
+ finally:
+ store.close()
+ _apply_session_meta(pages)
+ return {
+ "ok": True,
+ "count": len(pages),
+ "pages": pages,
+ "url_available": avibe_cloud_url_available(config),
+ "url_guidance": avibe_cloud_connect_guidance(config),
+ }
+
+
+def set_show_page_visibility(session_id: str, visibility: str) -> dict:
+ """Switch a Show Page between private / public / offline.
+
+ Raises ``ShowPageError`` (a ``ValueError``) for invalid input, which the
+ route layer maps to a 4xx response.
+ """
+ from core.show_pages import ShowPageStore, show_page_payload
+
+ config = V2Config.load()
+ store = ShowPageStore()
+ try:
+ updated = store.update_visibility(session_id, visibility)
+ payload = show_page_payload(updated, config=config)
+ finally:
+ store.close()
+ return {"ok": True, **_apply_session_meta([payload])[0]}
+
+
+def rotate_show_page_share(session_id: str) -> dict:
+ """Revoke the current public link and issue a new one (public pages only)."""
+ from core.show_pages import ShowPageStore, show_page_payload
+
+ config = V2Config.load()
+ store = ShowPageStore()
+ try:
+ updated, previous_share_id = store.rotate_share(session_id)
+ payload = show_page_payload(updated, config=config)
+ finally:
+ store.close()
+ return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
+
+
def _vibe_agent_payload(agent, *, brief: bool = False) -> dict:
payload = agent.to_dict()
if brief:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 477c4b915..a3c4eeae5 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1704,6 +1704,42 @@ def settings_get():
return jsonify(api.get_settings(request.args.get("platform") or None))
+def _show_page_error_response(exc):
+ code = getattr(exc, "code", "invalid_show_page_request")
+ status = 409 if code == "not_public" else 400
+ return jsonify({"ok": False, "code": code, "message": str(exc)}), status
+
+
[email protected]("/api/show-pages", methods=["GET"])
+def show_pages_list_get():
+ from vibe import api
+
+ return jsonify(api.list_show_pages())
+
+
[email protected]("/api/show-pages/<session_id>/visibility", methods=["POST"])
+def show_page_visibility_post(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ return jsonify(api.set_show_page_visibility(session_id, str(payload.get("visibility") or "")))
+ except ShowPageError as exc:
+ return _show_page_error_response(exc)
+
+
[email protected]("/api/show-pages/<session_id>/rotate-share", methods=["POST"])
+def show_page_rotate_share_post(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ try:
+ return jsonify(api.rotate_show_page_share(session_id))
+ except ShowPageError as exc:
+ return _show_page_error_response(exc)
+
+
@app.route("/api/csrf-token", methods=["GET"])
def csrf_token_get():
token = request.cookies.get(CSRF_COOKIE_NAME) or _new_csrf_token()