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): custom public link suffix (CLI + chat + settings) (#643)

Call Whitea24b6e26abf1
diff --git a/core/show_pages.py b/core/show_pages.py
index 3dfaf1d34..9b86ef5d9 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -11,6 +11,7 @@ from typing import Any
from urllib.parse import urljoin
from sqlalchemy import insert, or_, select, update
+from sqlalchemy.exc import IntegrityError
from config import paths
from config.v2_config import V2Config
@@ -30,6 +31,13 @@ SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"
SHOW_CLI_EVENT_TOKEN_HEADER = "X-Vibe-Show-Cli-Token"
SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS = 30
_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
+# A custom public share suffix lands directly in the ``/p/<share_id>/`` URL, so
+# keep it to URL-safe slug characters: start and end alphanumeric, with dash and
+# underscore allowed in between. 3–64 chars balances "memorable" against trivial
+# squatting/guessing of an already-public page.
+SHARE_ID_MIN_LENGTH = 3
+SHARE_ID_MAX_LENGTH = 64
+_SHARE_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{1,62}[A-Za-z0-9]$")
_LIKE_ESCAPE = "\\"
@@ -65,6 +73,20 @@ def validate_session_id(session_id: str) -> str:
return value
+def validate_share_id(share_id: str) -> str:
+ value = (share_id or "").strip()
+ if not value:
+ raise ShowPageError("A custom link is required.", code="missing_share_id")
+ if not _SHARE_ID_PATTERN.fullmatch(value):
+ raise ShowPageError(
+ "A custom link may contain only letters, numbers, dash, and underscore, "
+ f"must start and end with a letter or number, and be {SHARE_ID_MIN_LENGTH}–"
+ f"{SHARE_ID_MAX_LENGTH} characters long.",
+ code="invalid_share_id",
+ )
+ return value
+
+
def show_page_dir(session_id: str) -> Path:
return paths.get_show_page_dir(validate_session_id(session_id))
@@ -378,6 +400,81 @@ class ShowPageStore:
assert updated is not None
return updated, previous_share_id
+ def set_share_id(self, session_id: str, share_id: str) -> tuple[ShowPage, str | None]:
+ """Set a custom public share suffix; return (page, previous_share_id).
+
+ A custom suffix is just a chosen value for the same ``share_id`` that
+ ``rotate_share`` would otherwise randomize, so this mirrors that method:
+ archived sessions are terminal (guarded before ``ensure`` materializes a
+ page), and the suffix can only be set while the page is public. Setting a
+ new value revokes the previous public URL, exactly like a rotate.
+ """
+ session_id = validate_session_id(session_id)
+ new_share_id = validate_share_id(share_id)
+ # Pre-guard before ``ensure`` so a stale/direct call never materializes a
+ # default page for an archived (terminal) session. The in-txn re-reads
+ # below are the atomic authority for the concurrent-archive / concurrent
+ # visibility-flip race.
+ if self._is_archived(session_id):
+ raise ShowPageError(
+ "Cannot change the share link of an archived session.",
+ code="session_archived",
+ )
+ self.ensure(session_id)
+ now = _utc_now_iso()
+ previous_share_id: str | None = None
+ try:
+ with self.engine.begin() as conn:
+ # Read visibility, archive status, and the current suffix in the
+ # SAME transaction as the write so a concurrent flip to private/
+ # offline, an archive, or another session claiming the suffix
+ # can't slip between the check and the update; raising rolls back.
+ row = (
+ conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))
+ .mappings()
+ .first()
+ )
+ if row is None or row["visibility"] != VISIBILITY_PUBLIC:
+ raise ShowPageError(
+ "A custom link can only be set while the Show Page is public.",
+ code="not_public",
+ )
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if status == "archived":
+ raise ShowPageError(
+ "Cannot change the share link of an archived session.",
+ code="session_archived",
+ )
+ previous_share_id = row["share_id"]
+ if new_share_id != previous_share_id:
+ # Idempotent when unchanged (skips the write, so no self-
+ # collision and no updated_at churn). Otherwise reject a
+ # suffix held by another session; the unique constraint is
+ # the final authority (IntegrityError below).
+ taken_by = conn.execute(
+ select(show_pages.c.session_id).where(show_pages.c.share_id == new_share_id).limit(1)
+ ).scalar_one_or_none()
+ if taken_by is not None and taken_by != session_id:
+ raise ShowPageError(
+ "That custom link is already taken. Pick another.",
+ code="share_id_taken",
+ )
+ conn.execute(
+ update(show_pages)
+ .where(show_pages.c.session_id == session_id)
+ .values(share_id=new_share_id, updated_at=now)
+ )
+ except IntegrityError:
+ raise ShowPageError(
+ "That custom link is already taken. Pick another.",
+ code="share_id_taken",
+ )
+ updated = self.get(session_id)
+ assert updated is not None
+ return updated, previous_share_id
+
def _unique_share_id(self) -> str:
for _ in range(20):
candidate = _new_share_id()
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 84f4fca07..5f0db4a60 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -155,6 +155,221 @@ def test_rotate_share_requires_public(monkeypatch, tmp_path):
store.close()
+def _expect_show_page_error(fn, code):
+ try:
+ fn()
+ except ShowPageError as exc:
+ assert exc.code == code, f"expected {code}, got {exc.code}"
+ else:
+ raise AssertionError(f"expected ShowPageError({code})")
+
+
+def test_set_share_id_sets_custom_public_suffix(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+
+ store = ShowPageStore()
+ try:
+ store.ensure("ses123")
+ public_page = store.update_visibility("ses123", "public")
+ random_share_id = public_page.share_id
+ assert random_share_id
+
+ updated, previous = store.set_share_id("ses123", "q3-roadmap")
+ assert updated.share_id == "q3-roadmap"
+ assert previous == random_share_id
+ # The custom suffix resolves; the auto-generated one is revoked.
+ assert store.get_by_share_id("q3-roadmap").session_id == "ses123"
+ assert store.get_by_share_id(random_share_id) is None
+ # public_url reflects the custom suffix.
+ assert show_page_payload(public_page) # original payload still builds
+ assert show_page_payload(updated)["public_url"].endswith("/p/q3-roadmap/")
+
+ # A custom suffix survives a private/public round-trip (not regenerated).
+ store.update_visibility("ses123", "private")
+ back = store.update_visibility("ses123", "public")
+ assert back.share_id == "q3-roadmap"
+ finally:
+ store.close()
+
+
+def test_set_share_id_requires_public(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+
+ store = ShowPageStore()
+ try:
+ store.ensure("ses123") # defaults to private
+ _expect_show_page_error(lambda: store.set_share_id("ses123", "my-demo"), "not_public")
+ finally:
+ store.close()
+
+
+def test_set_share_id_rejects_taken_suffix(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+
+ store = ShowPageStore()
+ try:
+ store.update_visibility("ses-a", "public")
+ store.update_visibility("ses-b", "public")
+ store.set_share_id("ses-a", "shared-demo")
+ _expect_show_page_error(lambda: store.set_share_id("ses-b", "shared-demo"), "share_id_taken")
+ # The original owner keeps the suffix.
+ assert store.get_by_share_id("shared-demo").session_id == "ses-a"
+ finally:
+ store.close()
+
+
+def test_set_share_id_rejects_invalid_format(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+
+ store = ShowPageStore()
+ try:
+ store.update_visibility("ses123", "public")
+ for bad in ["no", "-bad", "bad-", "a b", "a/b", "汉字"]:
+ _expect_show_page_error(lambda b=bad: store.set_share_id("ses123", b), "invalid_share_id")
+ _expect_show_page_error(lambda: store.set_share_id("ses123", " "), "missing_share_id")
+ finally:
+ store.close()
+
+
+def test_set_share_id_is_idempotent(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+
+ store = ShowPageStore()
+ try:
+ store.update_visibility("ses123", "public")
+ first, _ = store.set_share_id("ses123", "stable-link")
+ again, previous = store.set_share_id("ses123", "stable-link")
+ assert again.share_id == "stable-link"
+ assert previous == "stable-link"
+ # Re-saving the same value is a no-op, not a self-collision rewrite.
+ assert again.updated_at == first.updated_at
+ finally:
+ store.close()
+
+
+def test_set_share_id_rejects_archived_session(monkeypatch, tmp_path):
+ 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
+ from storage import messages_service
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ ensure_sqlite_state()
+
+ store = ShowPageStore()
+ try:
+ # Make it public while no session row exists (so not archived yet).
+ store.update_visibility("ses-arch", "public")
+ now = messages_service._utc_now_iso()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_arch", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses-arch",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_arch",
+ native_session_id="",
+ status="archived",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ _expect_show_page_error(lambda: store.set_share_id("ses-arch", "later-name"), "session_archived")
+ finally:
+ store.close()
+
+
+def test_show_update_set_share_id_cli(monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ # Keep the CLI hermetic: skip the best-effort session prewarm side effect.
+ monkeypatch.setattr(cli, "_prewarm_show_page_session_best_effort", lambda *a, **k: None)
+
+ store = ShowPageStore()
+ try:
+ store.update_visibility("ses123", "public")
+ store.update_visibility("ses-other", "public")
+ finally:
+ store.close()
+
+ parser = cli.build_parser()
+ ok_args = parser.parse_args(["show", "update", "--session-id", "ses123", "--share-id", "demo-link", "--json"])
+ assert cli.cmd_show_update(ok_args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["share_id"] == "demo-link"
+ assert payload["public_url"].endswith("/p/demo-link/")
+
+ # A taken suffix on another public page exits 1 with a machine-readable code.
+ taken_args = parser.parse_args(["show", "update", "--session-id", "ses-other", "--share-id", "demo-link", "--json"])
+ assert cli.cmd_show_update(taken_args) == 1
+ error = json.loads(capsys.readouterr().err)
+ assert error["code"] == "share_id_taken"
+
+
+def test_show_update_share_id_archived_creates_no_page(monkeypatch, tmp_path, capsys):
+ 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
+ from storage import messages_service
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ ensure_sqlite_state()
+ monkeypatch.setattr(cli, "_prewarm_show_page_session_best_effort", lambda *a, **k: None)
+
+ now = messages_service._utc_now_iso()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_arch_cli", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses-arch-cli",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_arch_cli",
+ native_session_id="",
+ status="archived",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ args = cli.build_parser().parse_args(
+ ["show", "update", "--session-id", "ses-arch-cli", "--share-id", "demo", "--json"]
+ )
+ assert cli.cmd_show_update(args) == 1
+ assert json.loads(capsys.readouterr().err)["code"] == "session_archived"
+
+ # The failed command must NOT have materialized a Show Page row for the
+ # archived session (the CLI no longer pre-ensures before the store guard).
+ store = ShowPageStore()
+ try:
+ assert store.get("ses-arch-cli") is None
+ finally:
+ store.close()
+
+
def test_store_lists_pages_by_updated_time_and_visibility(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsx
index 735547c98..fe7be8354 100644
--- a/ui/src/components/ShowPagesPage.tsx
+++ b/ui/src/components/ShowPagesPage.tsx
@@ -21,7 +21,8 @@ import clsx from 'clsx';
import { useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
import { copyTextToClipboard } from '../lib/utils';
-import { copyHref, displayLink } from '../lib/showPageLinks';
+import { copyHref, displayLink, type ShowPageLinkInfo } from '../lib/showPageLinks';
+import { ShowPageShareIdField } from './workbench/ShowPageShareIdField';
import { SearchField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
@@ -69,9 +70,10 @@ interface RowProps {
onSetVisibility: (visibility: Visibility) => void;
onRotate: () => void;
onCopy: () => void;
+ onShareIdSaved: (payload: ShowPageLinkInfo) => void;
}
-function ShowPageRow({ page, expanded, busy, copied, onToggle, onSetVisibility, onRotate, onCopy }: RowProps) {
+function ShowPageRow({ page, expanded, busy, copied, onToggle, onSetVisibility, onRotate, onCopy, onShareIdSaved }: RowProps) {
const { t, i18n } = useTranslation();
const status = STATUS[page.visibility];
const { Icon } = status;
@@ -226,14 +228,27 @@ function ShowPageRow({ page, expanded, busy, copied, onToggle, onSetVisibility,
)}
{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 className="flex flex-col gap-3">
+ <div className="flex flex-col gap-2">
+ <span className={LABEL}>{t('showPages.shareId.label')}</span>
+ <div className="max-w-[360px]">
+ <ShowPageShareIdField
+ sessionId={page.session_id}
+ shareId={page.share_id}
+ disabled={busy}
+ onSaved={onShareIdSaved}
+ />
+ </div>
+ </div>
+ <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>
</div>
) : null}
@@ -323,6 +338,13 @@ export function ShowPagesPage() {
}
};
+ // The custom-link field owns its own request/validation; the page only merges
+ // the returned payload (new share_id, updated_at) and confirms.
+ const onShareIdSaved = (next: ShowPageLinkInfo) => {
+ mergePage(next as ShowPage);
+ showToast(t('showPages.shareId.toast.saved'));
+ };
+
const copy = async (page: ShowPage) => {
const href = copyHref(page);
if (!href) return;
@@ -414,6 +436,7 @@ export function ShowPagesPage() {
onSetVisibility={(visibility) => setVisibility(page, visibility)}
onRotate={() => rotate(page)}
onCopy={() => copy(page)}
+ onShareIdSaved={onShareIdSaved}
/>
))}
</div>
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index f150de537..4287ccd2e 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -10,6 +10,7 @@ import { useApi } from '../../context/ApiContext';
import { copyTextToClipboard } from '../../lib/utils';
import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';
import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+import { ShowPageShareIdField } from './ShowPageShareIdField';
type ShowPagePayload = ShowPageLinkInfo & {
url_available: boolean;
@@ -204,6 +205,23 @@ export const ShowPageShareControl: React.FC<{
</p>
</div>
+ {payload && isPublic && (
+ <div>
+ <div className="mb-1.5 text-sm">{t('chat.showPage.customLink')}</div>
+ <ShowPageShareIdField
+ sessionId={sessionId}
+ shareId={payload.share_id}
+ disabled={busy}
+ onSaved={(res) => {
+ // Authoritative server state, same handling as a visibility
+ // change: apply it and invalidate any in-flight refresh read.
+ setPayload(res as ShowPagePayload);
+ reqSeq.current += 1;
+ }}
+ />
+ </div>
+ )}
+
{payload && isPublic && !payload.url_available && (
<div className="rounded-md border border-border px-2.5 py-2 text-xs text-muted">
{t('chat.showPage.publicUnavailable')}
diff --git a/ui/src/components/workbench/ShowPageShareIdField.tsx b/ui/src/components/workbench/ShowPageShareIdField.tsx
new file mode 100644
index 000000000..7557c044d
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageShareIdField.tsx
@@ -0,0 +1,130 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Check, Loader2 } from 'lucide-react';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+import { Input } from '../ui/input';
+import { ApiError, useApi } from '../../context/ApiContext';
+import { isValidShareId, SHARE_ID_MAX_LENGTH, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+
+// Editable custom suffix for a public Show Page's /p/<share_id>/ URL. Shared by
+// the in-chat share popover and the admin Show Pages page so both surfaces get
+// the same validation, error mapping, and save affordance. The caller renders
+// its own label (each surface has its own label style) and gates rendering on
+// public visibility; this owns the input row + helper/error line.
+export const ShowPageShareIdField: React.FC<{
+ sessionId: string;
+ shareId: string | null;
+ // External busy (e.g. a visibility change in flight) disables the field.
+ disabled?: boolean;
+ // Receives the updated payload so the caller can refresh its link/iframe.
+ onSaved: (payload: ShowPageLinkInfo) => void;
+}> = ({ sessionId, shareId, disabled, onSaved }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const current = shareId ?? '';
+ const [draft, setDraft] = useState(current);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [saved, setSaved] = useState(false);
+ const savedTimer = useRef<number | null>(null);
+
+ // Resync when the saved suffix changes elsewhere (a rotate, or a save from the
+ // other surface): the prefilled draft should track the authoritative value.
+ useEffect(() => {
+ setDraft(shareId ?? '');
+ setError(null);
+ }, [shareId]);
+
+ useEffect(
+ () => () => {
+ if (savedTimer.current) window.clearTimeout(savedTimer.current);
+ },
+ [],
+ );
+
+ const trimmed = draft.trim();
+ const changed = trimmed !== current;
+ const clientValid = isValidShareId(trimmed);
+ // Flag a format problem only once the user has typed something new and
+ // invalid — never yell at the untouched prefilled value or an empty field.
+ const formatError = changed && trimmed.length > 0 && !clientValid;
+ const canSave = changed && clientValid && !busy && !disabled;
+
+ const save = async () => {
+ if (!canSave) return;
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await api.setShowPageShareId(sessionId, trimmed);
+ onSaved(res);
+ setSaved(true);
+ if (savedTimer.current) window.clearTimeout(savedTimer.current);
+ savedTimer.current = window.setTimeout(() => setSaved(false), 1600);
+ } catch (err) {
+ // The server is the authority on uniqueness; map its code to a field-level
+ // message (a global toast also fires from the shared error handler).
+ const code = err instanceof ApiError ? err.code : null;
+ setError(
+ code === 'share_id_taken'
+ ? t('showPages.shareId.errors.taken')
+ : code === 'invalid_share_id' || code === 'missing_share_id'
+ ? t('showPages.shareId.errors.invalid')
+ : t('showPages.shareId.errors.generic'),
+ );
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const isError = !!error || formatError;
+ const message = error ?? (formatError ? t('showPages.shareId.errors.invalid') : t('showPages.shareId.hint'));
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-1.5">
+ <span className="shrink-0 font-mono text-xs text-muted">/p/</span>
+ <Input
+ value={draft}
+ spellCheck={false}
+ autoCapitalize="none"
+ autoCorrect="off"
+ maxLength={SHARE_ID_MAX_LENGTH}
+ disabled={busy || disabled}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ void save();
+ }
+ }}
+ placeholder={current || t('showPages.shareId.placeholder')}
+ aria-label={t('showPages.shareId.label')}
+ aria-invalid={isError || undefined}
+ className="h-8 flex-1 text-xs"
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-8 shrink-0"
+ disabled={!canSave}
+ onClick={() => void save()}
+ >
+ {busy ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : saved ? (
+ <Check className="size-3.5" />
+ ) : (
+ t('common.save')
+ )}
+ </Button>
+ </div>
+ <p className={clsx('text-[11px] leading-snug', isError ? 'text-destructive' : 'text-muted')}>{message}</p>
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 034a9d796..736145818 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -41,6 +41,8 @@ export type ApiContextType = {
/** Create the session's Show Page if absent; resolves to `{ existed, ... }`. */
ensureShowPage: (sessionId: string) => Promise<any>;
rotateShowPageShare: (sessionId: string) => Promise<any>;
+ /** Set a custom public link suffix (public pages only); rejects on a taken/invalid id. */
+ setShowPageShareId: (sessionId: string, shareId: string) => Promise<any>;
getBindCodes: () => Promise<any>;
createBindCode: (type: string, expiresAt?: string) => Promise<any>;
deleteBindCode: (code: string) => Promise<any>;
@@ -1569,6 +1571,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
setShowPageVisibility: (sessionId, visibility) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/visibility`, { visibility }),
ensureShowPage: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/ensure`, {}),
rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
+ setShowPageShareId: (sessionId, shareId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/share-id`, { share_id: shareId }),
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
deleteBindCode: (code) => deleteJson(`/api/bind-codes/${encodeURIComponent(code)}`),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 25d54f892..5d616916e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -141,6 +141,17 @@
"shareLink": "Share link",
"rotate": "Rotate link",
"rotateHint": "Generates a new link and disables the current one.",
+ "shareId": {
+ "label": "Custom link",
+ "hint": "3–64 letters, numbers, dash, or underscore. Must be unique.",
+ "placeholder": "my-page",
+ "toast": { "saved": "Custom link updated" },
+ "errors": {
+ "taken": "That custom link is already taken. Pick another.",
+ "invalid": "Use 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",
+ "generic": "Couldn't update the custom link."
+ }
+ },
"cloudOff": "Avibe Cloud is off — this link only opens on this device.",
"connectCloud": "Connect Avibe Cloud",
"details": "Details",
@@ -518,6 +529,11 @@
"retry": "Retry"
},
"errors": {
+ "share_id_taken": "That custom link is already taken. Pick another.",
+ "invalid_share_id": "A custom link may use only 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",
+ "missing_share_id": "Enter a custom link first.",
+ "not_public": "Make the Show Page public first to change its link.",
+ "session_archived": "This session is archived, so its Show Page can't be changed.",
"project_no_folder": "This project has no local folder configured.",
"project_not_found": "Project not found.",
"remote_access_host_mismatch": "This address can't open the Avibe control panel. Open it from your https://<your-slug>.avibe.bot link, or http://127.0.0.1:5123 on the machine running Avibe.",
@@ -1805,6 +1821,7 @@
"visibilityPrivate": "Private",
"publicDesc": "Anyone with the link can view",
"privateDesc": "Only you can view",
+ "customLink": "Custom link",
"offlineNote": "This Show Page is offline and can't be shared right now.",
"publicUnavailable": "Connect Avibe Cloud to get a public link others can open.",
"loadError": "Couldn't load this Show Page.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c3cfb35b8..51aef7869 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -141,6 +141,17 @@
"shareLink": "分享链接",
"rotate": "更换链接",
"rotateHint": "生成新链接并使当前链接立即失效。",
+ "shareId": {
+ "label": "自定义链接",
+ "hint": "3–64 位,可用字母、数字、短横线或下划线,需唯一。",
+ "placeholder": "my-page",
+ "toast": { "saved": "自定义链接已更新" },
+ "errors": {
+ "taken": "这个自定义链接已被占用,换一个。",
+ "invalid": "请使用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",
+ "generic": "更新自定义链接失败。"
+ }
+ },
"cloudOff": "Avibe Cloud 未开启——此链接仅能在本机打开。",
"connectCloud": "连接 Avibe Cloud",
"details": "详情",
@@ -518,6 +529,11 @@
"retry": "重试"
},
"errors": {
+ "share_id_taken": "这个自定义链接已被占用,换一个。",
+ "invalid_share_id": "自定义链接只能用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",
+ "missing_share_id": "请先输入自定义链接。",
+ "not_public": "请先把展示页面设为公开,再修改链接。",
+ "session_archived": "该会话已归档,无法修改它的展示页面。",
"project_no_folder": "这个项目没有配置本地文件夹。",
"project_not_found": "找不到这个项目。",
"remote_access_host_mismatch": "这个地址无法打开 Avibe 控制台。请用你的 https://<你的子域>.avibe.bot 链接打开,或在运行 Avibe 的机器上访问 http://127.0.0.1:5123。",
@@ -1804,6 +1820,7 @@
"visibilityPrivate": "私有",
"publicDesc": "任何人都可以通过链接查看",
"privateDesc": "只有你能查看",
+ "customLink": "自定义链接",
"offlineNote": "这个 Show Page 已离线,暂时无法分享。",
"publicUnavailable": "连接 Avibe Cloud 后才能获得别人可打开的公开链接。",
"loadError": "无法加载这个 Show Page。",
diff --git a/ui/src/lib/showPageLinks.ts b/ui/src/lib/showPageLinks.ts
index 64146b3d3..7d17f8703 100644
--- a/ui/src/lib/showPageLinks.ts
+++ b/ui/src/lib/showPageLinks.ts
@@ -34,3 +34,14 @@ export function displayLink(page: ShowPageLinkInfo): string | null {
const href = liveHref(page);
return href ? href.replace(/^https?:\/\//, '') : null;
}
+
+// Custom public link suffix (the /p/<share_id>/ segment). Mirrors the server
+// rule in core/show_pages.validate_share_id so the field can give instant
+// feedback before the request; the server stays the authority on uniqueness.
+export const SHARE_ID_MIN_LENGTH = 3;
+export const SHARE_ID_MAX_LENGTH = 64;
+const SHARE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{1,62}[A-Za-z0-9]$/;
+
+export function isValidShareId(value: string): boolean {
+ return SHARE_ID_RE.test(value.trim());
+}
diff --git a/vibe/api.py b/vibe/api.py
index 704004dce..d198ccb71 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1089,6 +1089,25 @@ def rotate_show_page_share(session_id: str) -> dict:
return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
+def set_show_page_share_id(session_id: str, share_id: str) -> dict:
+ """Set a custom public link suffix (public pages only).
+
+ Like ``rotate_show_page_share`` but with a caller-chosen value; setting it
+ revokes the previous public URL. Raises ``ShowPageError`` for an invalid /
+ taken suffix or a non-public page, which the route layer maps to a 4xx/409.
+ """
+ from core.show_pages import ShowPageStore, show_page_payload
+
+ config = V2Config.load()
+ store = ShowPageStore()
+ try:
+ updated, previous_share_id = store.set_share_id(session_id, share_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/cli.py b/vibe/cli.py
index 09c5c3fa0..55d60eb62 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -482,7 +482,7 @@ def _show_examples_text() -> str:
list List existing Show Pages across sessions.
path Create or resolve the local workspace.
status Inspect local path, visibility, active URL, and share state.
- update Switch visibility, rotate public share links, or take the page offline.
+ update Switch visibility, set a custom public link, rotate share links, or take the page offline.
mark Add an assistant mark event to the session.
event Record a generic annotation-layer event.
@@ -548,6 +548,7 @@ def _show_update_examples_text() -> str:
Examples:
vibe show update --session-id sesk8m4q2p7x --visibility public
+ vibe show update --session-id sesk8m4q2p7x --share-id q3-roadmap
vibe show update --session-id sesk8m4q2p7x --visibility private
vibe show update --session-id sesk8m4q2p7x --visibility offline
vibe show update --session-id sesk8m4q2p7x --rotate-share
@@ -556,6 +557,8 @@ def _show_update_examples_text() -> str:
private uses the authenticated /show/<session-id>/ URL.
public uses a short /p/<share-id>/ URL and disables the private path.
offline takes the page down without deleting local files.
+ --share-id sets a custom /p/<share-id>/ suffix (3-64 chars, unique);
+ allowed only while public, and it replaces the previous public URL.
--rotate-share is allowed only while the page is public.
"""
)
@@ -4916,11 +4919,6 @@ def cmd_show_update(args):
store = _load_show_page_store()
try:
- existing = store.ensure(args.session_id)
- previous = show_page_payload(existing)
- previous_active_url = previous.get("active_url")
- previous_public_url = previous.get("public_url")
- previous_private_url = previous.get("private_url")
extra: dict = {}
if getattr(args, "rotate_share", False):
@@ -4931,15 +4929,35 @@ def cmd_show_update(args):
"message_detail": "Previous public share URL was revoked.",
}
message = "Public share link rotated."
+ elif getattr(args, "share_id", None) is not None:
+ # ``is not None`` so an explicit empty --share-id reaches
+ # validate_share_id (a clear missing_share_id) instead of falling
+ # through to a confusing visibility error.
+ updated, previous_share_id = store.set_share_id(args.session_id, args.share_id)
+ extra = {
+ "previous_share_id": previous_share_id,
+ }
+ if previous_share_id and previous_share_id != updated.share_id:
+ extra["previous_public_url"] = public_url(previous_share_id)
+ extra["message_detail"] = "Previous public share URL was revoked."
+ message = "Custom public link set."
else:
+ # Read the prior state for the transition message WITHOUT creating a
+ # page first: update_visibility owns the archived guard + ensure, so
+ # an archived/terminal session is rejected before any row (and its
+ # /show/ route) is materialized. rotate_share / set_share_id guard
+ # themselves the same way, so neither needs a pre-ensure either.
+ existing = store.get(args.session_id)
+ previous = show_page_payload(existing) if existing else None
+ previous_visibility = existing.visibility if existing else "private"
updated = store.update_visibility(args.session_id, args.visibility)
message = f"Show Page is now {updated.visibility}."
- if existing.visibility == "private" and updated.visibility == "public":
- extra["previous_private_url"] = previous_private_url
- elif existing.visibility == "public" and updated.visibility == "private":
- extra["previous_public_url"] = previous_public_url
+ if previous_visibility == "private" and updated.visibility == "public":
+ extra["previous_private_url"] = previous["private_url"] if previous else None
+ elif previous_visibility == "public" and updated.visibility == "private":
+ extra["previous_public_url"] = previous["public_url"] if previous else None
elif updated.visibility == "offline":
- extra["previous_active_url"] = previous_active_url
+ extra["previous_active_url"] = previous["active_url"] if previous else None
message = "Show Page has been taken offline. Local files were not deleted."
if updated.visibility != "offline":
@@ -6105,12 +6123,15 @@ def build_parser():
show_update_parser = show_subparsers.add_parser(
"update",
- help="Update visibility or rotate the public share link",
- description="Switch a Show Page between private, public, and offline states, or rotate its public share link.",
+ help="Update visibility, set a custom public link, or rotate the share link",
+ description=(
+ "Switch a Show Page between private, public, and offline states, set a custom "
+ "public link suffix, or rotate its public share link."
+ ),
epilog=_show_update_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe show update --help",
- error_hint="Pass --visibility private|public|offline or --rotate-share.",
+ error_hint="Pass --visibility private|public|offline, --share-id SLUG, or --rotate-share.",
)
show_update_parser.add_argument("--session-id", required=True, help="Agent Session ID for the Show Page.")
show_update_action = show_update_parser.add_mutually_exclusive_group(required=True)
@@ -6119,6 +6140,15 @@ def build_parser():
choices=("private", "public", "offline"),
help="Set the active Show Page visibility.",
)
+ show_update_action.add_argument(
+ "--share-id",
+ metavar="SLUG",
+ help=(
+ "Set a custom public link suffix (the /p/<SLUG>/ segment): 3-64 chars, "
+ "letters/numbers/dash/underscore, must be unique. Allowed only while public; "
+ "replaces the previous public URL."
+ ),
+ )
show_update_action.add_argument(
"--rotate-share",
action="store_true",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8201c4b92..0e5377e23 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2275,8 +2275,15 @@ def settings_get():
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
+ # A conflict (not a malformed request) when the page is in the wrong state or
+ # the chosen suffix is already claimed.
+ status = 409 if code in {"not_public", "share_id_taken"} else 400
+ message = str(exc)
+ # Structured ``error`` so the Web UI's shared handler localizes via
+ # ``errors.<code>`` and falls back to the human message (not the raw code)
+ # for any code without an i18n key; top-level ``code``/``message`` stay for
+ # the CLI/any direct consumer.
+ return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
@app.route("/api/show-pages", methods=["GET"])
@@ -2320,6 +2327,18 @@ def show_page_rotate_share_post(session_id):
return _show_page_error_response(exc)
[email protected]("/api/show-pages/<session_id>/share-id", methods=["POST"])
+def show_page_set_share_id_post(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ return jsonify(api.set_show_page_share_id(session_id, str(payload.get("share_id") or "")))
+ 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()