Files
gabrielvidalandClaude Opus 5.5 840fd8593f feat(plugins): prompt shortcuts leave the core for the prompt-shortcuts plugin
Gabriel's form prompt-shortcuts-into-a-plugin_dkhipt: everything moves —
the owner's library, its editor and audience matrix, the guest sharing,
guests' own shortcuts and prefs, the built-in Changes chip. The core keeps
the composer's chips engine, the always-on notify line and the prompt pills.

Platform hooks (generic, reused by the keyboard-shortcuts move):
- ui.pages[].nav "settings" (+ group, after): a Settings entry routed at
  /settings/p/<id>/<page>, listed in the panel, the drawers, the search and
  the palette, right after the entry `after` names (a core id or another
  plugin page's id; else the end of its group).
- top-level "seed": true: an app plugin installed once from the seed dir at
  start, like provider-* / harness-*.
- composer.shortcuts: "position": "first", runners: [] and hidden kept, 64
  chips; a POSTed action of a provider drops its cache and publishes
  composer-shortcuts (guests too) so every composer refetches.
- frame bridges aiAgentPlugin.pickIcon (the app's glyph picker in a host
  dialog) and iconSvg(keys); a page's init.lang.

The move:
- carryover.prompt_shortcuts: the owner's promptShortcuts (audience made
  explicit, a pre-v4 blob folding the old guest list) → library.json, each
  guest's promptShortcuts + shortcutPrefs → their personal.json, once.
- settings v7 drops promptShortcuts / shortcutPrefs; settings/shortcuts.py,
  /api/me sharedShortcuts and guest-defaults promptShortcuts are gone.
- Settings → Skills & agents (/settings/setup) is its own entry;
  /settings/shortcuts forwards to the plugin's page (#skills → setup), saved
  panel and drawer layouts keep the old slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 01:03:50 +01:00

166 lines
6.7 KiB
Python

"""Settings pages: PWA ui-state, native Claude Code hooks and fresh context."""
import json
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import schemas
from core.config import WORKSPACE
from core.http import _r
from core.state import State
from runs import fresh as fresh_mod
from settings.unsend import SETTINGS_KEY, curve_of
from settings.ui_state import valid_key
from users.caller import CallerDep
router = APIRouter()
# ── UI state (Settings config + notification bookkeeping) ────────────────────
# The PWA persists its small Zustand `persist` stores here instead of the
# browser's localStorage, so config and the notification feed's seen/new state
# follow the user across browsers/devices. The value is the store's opaque
# serialized JSON blob; the backend just holds the string (see ui_state.py).
class UiStateBody(BaseModel):
value: str
# What a guest's namespace may hold. The store is one JSON file rewritten on
# every write — the owner's included — and copied into 14 daily backups, so
# one guest's value must not be what sizes it. The biggest real blob (a
# guest's ``ai-agent-store``) was 230 KB when these were set, 2026-11-15.
GUEST_VALUE_MAX = 1024 * 1024
GUEST_TOTAL_MAX = 2 * 1024 * 1024
GUEST_KEYS_MAX = 32
def _guest_room(deps, caller, full: str, value: str) -> None:
"""413 when ``value`` under ``full`` would take a guest past their room."""
size = len(value.encode("utf-8"))
used, keys = deps.ui_state.usage(f"u.{caller.id}.", but=full)
new = deps.ui_state.get(full) is None
if size > GUEST_VALUE_MAX or used + size > GUEST_TOTAL_MAX \
or (new and keys >= GUEST_KEYS_MAX):
raise HTTPException(413, "ui-state is full")
def _ui_key(caller, key: str) -> str:
"""A guest's ui-state lives under their own prefix: their theme, layout
and notification bookkeeping never touch the owner's (or another
guest's). The owner's keys are unchanged."""
if not valid_key(key):
raise HTTPException(400, "bad key")
return key if caller.is_owner else f"u.{caller.id}.{key}"
@router.get("/api/ui-state/{key}", responses=_r(schemas.UiStateValue))
def get_ui_state(deps: State, caller: CallerDep, key: str):
# (Prompt shortcuts left this store for the prompt-shortcuts plugin on
# 2026-11-27 — plugins/carryover.py moved them; nothing to upgrade here.)
return {"value": deps.ui_state.get(_ui_key(caller, key))}
def _plugin_prefs_blob(raw: str | None) -> str:
if not raw:
return "{}"
try:
st = (json.loads(raw) or {}).get("state") or {}
return json.dumps(st.get("pluginPrefs") or {}, sort_keys=True)
except (ValueError, TypeError, AttributeError):
return "{}"
@router.put("/api/ui-state/{key}", responses=_r(schemas.OkResponse))
def put_ui_state(deps: State, caller: CallerDep, key: str, body: UiStateBody):
full = _ui_key(caller, key)
watch = caller.is_owner and key == SETTINGS_KEY
prev_raw = deps.ui_state.get(full) if watch else None
before = curve_of(prev_raw) if watch else None
before_prefs = _plugin_prefs_blob(prev_raw) if watch else None
if not caller.is_owner:
_guest_room(deps, caller, full, body.value)
deps.ui_state.set(full, body.value)
if watch and curve_of(body.value) != before:
# What guests get (the un-send curve) changed: their clients
# refetch /api/me.
deps.hub.publish({"type": "users"})
if watch and _plugin_prefs_blob(body.value) != before_prefs:
# Operator's default+override plugin prefs changed: connected guests
# refetch /api/plugins to see the updated hubDefault values.
deps.hub.publish({"type": "plugins"})
return {"ok": True}
@router.delete("/api/ui-state/{key}", responses=_r(schemas.OkResponse))
def delete_ui_state(deps: State, caller: CallerDep, key: str):
deps.ui_state.delete(_ui_key(caller, key))
return {"ok": True}
# Claude Code's own hooks, read out of the workspace's .claude/settings.json.
# Read-only on purpose: writing that file from the container is host-level code
# execution (see the trusted-caller note at the top of this module), so the
# page shows them and points at the repo for edits.
CLAUDE_SETTINGS_REL = ".claude/settings.json"
@router.get("/api/claude-hooks", responses=_r(schemas.ClaudeHooksResponse))
def claude_hooks():
"""The native Claude Code hooks registered in the workspace repo, flattened
to one entry per (event, matcher, command). A missing or unparseable
settings file is an empty list, not an error (standalone has no repo)."""
ap = WORKSPACE / CLAUDE_SETTINGS_REL
try:
data = json.loads(ap.read_text(encoding="utf-8")) or {}
except (OSError, ValueError):
return {"path": CLAUDE_SETTINGS_REL, "exists": ap.exists(),
"entries": []}
entries = []
blocks = data.get("hooks")
for event, matchers in (blocks or {}).items():
for m in (matchers if isinstance(matchers, list) else []):
if not isinstance(m, dict):
continue
for h in (m.get("hooks") or []):
if not isinstance(h, dict):
continue
entries.append({"event": str(event),
"matcher": m.get("matcher") or None,
"type": h.get("type") or "command",
"command": h.get("command") or ""})
return {"path": CLAUDE_SETTINGS_REL, "exists": True, "entries": entries}
# ── fresh context (runs/fresh.py) ────────────────────────────────────────────
class FreshContextBody(BaseModel):
enabled: bool | None = None
minSavingsUsd: float | None = None
minSavingsPct: float | None = None
coldUsd: float | None = None
countdown: bool | None = None
confirm: bool | None = None
autoFresh: bool | None = None
model: str | None = None
pointer: bool | None = None
@router.get("/api/fresh-context", responses=_r(schemas.FreshContextSettings))
def fresh_context_get(deps: State):
"""When the reply box nudges toward a fresh context, what compacts, and
the measured assumptions its estimate runs on."""
return {**deps.fresh_store.get(), "assumptions": fresh_mod.ASSUMPTIONS}
@router.put("/api/fresh-context", responses=_r(schemas.FreshContextSettings))
def fresh_context_put(deps: State, body: FreshContextBody):
try:
saved = deps.fresh_store.set(body.model_dump(exclude_none=True))
except ValueError as e:
raise HTTPException(400, str(e))
deps.hub.publish({"type": "fresh-context"})
return {**saved, "assumptions": fresh_mod.ASSUMPTIONS}