Skip to content

Console pages and layouts ​

Plugins can do more than send chat messages — they can contribute admin pages to Remote Console. Zhin uses Server-Driven Blueprints as its first-class authoring model (covering 90% of plugins), while providing a static frontend asset mounting protocol for the 10% heavy-interaction plugins (such as the Sandbox chat simulator).

Like commands, pages live in a convention directory, pages/, and are discovered automatically.

Most plugins (ledger, reminders, RSS, calendar, group moderation, content review, platform adapters) only need stat cards (stat-cards) + tables/lists (table) + filter forms (filter-form) + action buttons (action-bar). Declare a pure TypeScript definePageBlueprint in pages/<name>/index.ts and let Console UI render it uniformly:

  • Zero .tsx, zero esbuild pre-bundling, zero lib/pages/*.bundle.js, zero React version coupling;
  • Multi-surface projection: the exact same Blueprint renders in Web Console, projects into cross-platform IM card messages (with interactive buttons) via projectBlueprintToImCard, and renders into terminal CLI TUI panels via projectBlueprintToCliPanel!
ts
// pages/index/index.ts
import { definePage, definePageBlueprint } from '@zhin.js/console-contract';

export const meta = definePage({
  title: 'My Plugin',
  titleI18n: { 'zh-CN': '我的插件' },
  icon: 'Box',
  order: 10,
});

export default definePageBlueprint({
  kind: 'custom',
  subtitle: 'Plugin runtime overview and quick actions',
  statusQuery: 'status',
  widgets: [
    {
      type: 'stat-cards',
      title: 'Key Metrics',
      cards: [
        { key: 'total', label: 'Total Records', tone: 'accent' },
        { key: 'active', label: 'Active Today', tone: 'success' },
      ],
    },
    {
      type: 'action-bar',
      title: 'Quick Actions',
      actions: [
        { action: 'refresh-cache', label: 'Refresh Cache', variant: 'primary' },
      ],
    },
    {
      type: 'table',
      title: 'Recent Items',
      dataKey: 'items',
      rowKey: 'id',
      emptyText: 'No records yet',
      columns: [
        { key: 'id', label: 'ID' },
        { key: 'title', label: 'Title' },
      ],
    },
  ],
});
  • The default export is a definePageBlueprint(...) descriptor (or a React component for heavy-interaction .tsx pages).
  • The named export meta declares title, icon and order.
  • Only pages/<name>/index.ts (or index.tsx for heavy-interaction plugins) is a page; other files in the folder can be imported as helpers.

Start the bot, open Console, and the page appears in the navigation.

Multi-surface projection (Web Console / IM Card / CLI TUI) ​

@zhin.js/console-contract includes zero-dependency projectors so commands or CLI tools can reuse your page Blueprint and status payload directly:

ts
import {
  projectBlueprintToImCard,
  projectBlueprintToCliPanel,
} from '@zhin.js/console-contract';
import blueprint, { meta } from '../pages/index/index.js';

// 1. Project into cross-platform IM card segments (Segment[], with interactive action buttons)
const segments = projectBlueprintToImCard(blueprint, statusData, {
  title: meta.title,
  commandPrefix: '/my-plugin ',
});

// 2. Project into a terminal CLI TUI panel (ANSI box-drawing table and stat cards)
const ansiPanel = projectBlueprintToCliPanel(blueprint, statusData, {
  title: meta.title,
  width: 72,
});

Page metadata ​

Every meta field is optional; definePage throws on unknown keys:

FieldDefaultDescription
titleGenerated from the folder name (foo-bar → Foo Bar)Navigation and header title
titleI18nnoneExplicit titles for zh-CN / en, e.g. { en: 'My Plugin' }; missing entries retain title
iconnoneA lucide-style icon name, e.g. 'Box', 'Workflow'
order100Navigation order; lower comes first
hideInNavfalseHide from navigation
requiredPermissions[]Permissions required to access: built-in ones (such as status.view) or plugin-defined names
requiredRoles[]Role names required to access (such as operator)
section—Console navigation section: overview / conversations / features / plugins / ops / access; omitted → the Console decides (ADR 0052)
keywords—Search aliases for the command palette: one list of strings, or lists per language ({ 'zh-CN': ['抽奖'], en: ['lottery'] }; only zh-CN / en). Used with the title and plugin name to find the page in the command palette (ADR 0063)

Navigation and the page list are filtered per caller. A global owner sees every page. Other users see only pages whose requirements their roles meet (plugin-defined permission names are granted by level, see Plugin permission levels). Signed-out callers see only pages with no requirements. For users and roles, see Console users and permissions.

Console selects titleI18n using its independent interface language. This only changes navigation and breadcrumb display, never routes, permissions or page content. Plugins localize their own components; third-party titles without translations remain unchanged.

Page addresses ​

Address = plugin path + page name:

FileOwning pluginAddress
pages/index/index.tsxsandbox/sandbox
pages/reports/index.tsxyour bot (root)/p-reports
pages/index/index.tsxyour bot (root)/

index maps to the plugin path itself; other pages map to p-<name>. Two pages resolving to the same address fail at startup. Implementation: pageRoute in packages/console/plugin-contract/src/page.ts.

pages/ has two reserved names:

  • pages/nav/index.tsx: the navigation area
  • pages/footer/index.tsx: the footer

Default-export a React component; no meta needed. When both .ts and .tsx exist for a slot, .tsx wins. Projects created by npm create zhin-app already include both as examples.

Example: the Sandbox chat page ​

The Sandbox adapter (plugins/adapters/sandbox) provides both an adapter and a page, so its package.json#zhin declares two Features:

json
{
  "zhin": {
    "protocol": 1,
    "type": "plugin",
    "entry": "./plugin.ts",
    "runtime": "trusted",
    "features": [
      { "package": "@zhin.js/adapter", "api": "^2.0.0" },
      { "package": "@zhin.js/page", "api": "^1.0.0" }
    ]
  }
}
  • @zhin.js/adapter discovers the adapter under adapters/, providing the WebSocket /sandbox connection.
  • @zhin.js/page discovers pages/index/index.tsx, which is why Console shows a /sandbox chat page.

The page's SandboxChat component connects to /sandbox over WebSocket (address and token in pages/sandboxTransport.ts). Sending a message in the page is equivalent to a real platform receiving one: it goes through middleware, command matching and the AI. So you can fully debug commands, component rendering and the Agent without any real platform. Sandbox displays outbound HTML directly instead of converting it to an image or text — see Middleware & components.

The plugin entry itself needs nothing; the page and adapter are discovered automatically:

ts
// plugins/adapters/sandbox/plugin.ts
import { definePlugin } from 'zhin.js';

export default definePlugin({
  name: 'sandbox',
  metadata: { displayName: 'Sandbox Adapter' },
});

Page data: plugin RPC ​

When a page needs to show a plugin's runtime status or offer a few buttons, the plugin can register its own Console RPC instead of opening a WebSocket or an HTTP route.

In setup, the plugin registers a read-only status and, if needed, a few limited actions:

ts
// plugin.ts
import { definePlugin } from 'zhin.js';
import { definePluginConsoleRpc, PluginConsoleRpcError, pluginConsoleRpcToken } from 'zhin.js/plugin-runtime';

export default definePlugin({
  name: 'ambient',
  setup(context) {
    context.resources.provide(pluginConsoleRpcToken, definePluginConsoleRpc({
      status: {
        page: 'index', // same access rules as pages/index
        handler: async () => ({
          mode: 'shadow',
          recent: recentJudgments(10).map(j => ({ at: j.at, spoke: j.engaged })),
        }),
      },
      actions: {
        'clear-cooldown': {
          page: 'index',
          handler: async ({ group }) => {
            if (typeof group !== 'string') throw new PluginConsoleRpcError('invalid_input', 'Pick a group');
            return { cleared: clearCooldown(group) };
          },
        },
      },
    }));
  },
});

Pages call it with pluginRpc from @zhin.js/client. pluginId is the plugin's PluginId (for example root/ambient), the same value as owner in the page list:

tsx
import { pluginRpc } from '@zhin.js/client';

const status = await pluginRpc<{ mode: string }>('root/ambient', 'status');
await pluginRpc('root/ambient', 'clear-cooldown', { group: '123' });

Requests go through the existing POST /api/console/request, with the type plugin.<pluginId>.status or plugin.<pluginId>.<action>. Action names may use only lowercase letters, digits and -, and status is reserved.

Besides status, you can register a few read-only queries under queries. They follow the same rules as status (page, demo and requiredPermissions all work). A query and an action can't share a name:

ts
definePluginConsoleRpc({
  queries: {
    history: { page: 'index', handler: async () => ({ days: last7Days() }) },
  },
});

Access rules:

  • Follows the page: with page set, the caller must meet that page's requiredPermissions and requiredRoles, plus any the method declares itself. If the page isn't loaded in the current generation, the call is refused.
  • A global owner can call every method.
  • Other users and API tokens are checked per method: they must meet the method's own requirements and the page's. Plugin permissions are granted by level (see Plugin permission levels). Otherwise the call returns 403.
  • Fallback when nothing is declared: a read method with no requirements (and no page requirements) needs feature.view; an action that declares no requirements of its own needs feature.configure, with the page's requirements on top. A page's requirements never grant an action by themselves.
  • Adapter plugins: for a plugin that owns an adapter (root/<adapter>), a role bound to that adapter (or, for account methods that name an id, to that account) also counts; one bound to another adapter never does. Account methods (endpoint-add and the rest) also accept endpoint.manage at their target; only holders of endpoint.manage can confirm the first migration of the account list.
  • Any one of: holding one of the permissions in anyOfPermissions is enough (on top of requiredPermissions). Use it when a new permission sits beside an older one, for example approval cards accept ops:approve or the older tool_approvals:resolve.
ts
actions: {
  'clear-cooldown': {
    page: 'index',                          // the page's requirements apply first
    requiredPermissions: ['ambient:write'], // then this one lets ordinary users run it
    handler: async ({ group }) => ({ cleared: clearCooldown(String(group)) }),
  },
},

Ordinary users see what you return, so:

  • Return only the few fields the page needs. Don't return log records, prompts, chat text or secrets.
  • The result must be JSON and at most 256 KB. The request's data must be a JSON object of at most 64 KB.
  • A handler that doesn't return within 10 seconds times out, and its signal is aborted.
  • To show users why something failed, throw PluginConsoleRpcError. Its message is shown as is. Any other error shows only a generic failure message.

Plugin RPC doesn't change configuration. Use config:patch for that.

Plugin permission levels ​

Plugin-defined permission names are written <plugin>:<action> (such as rss:read, rss:write, ops:approve). Each has a level, and built-in roles grant them by level (viewer → read, operator → read + operate, admin / owner → all; see Plugin permission levels in the Console guide). Without a declaration the level comes from the suffix: :read / :view are read; :approve / :manage / :admin / :write / :config are manage; anything else is operate.

When the inferred level is wrong for your plugin, declare it in the permissions of definePluginConsoleRpc:

ts
definePluginConsoleRpc({
  permissions: [
    { id: 'rss:read', level: 'read', description: 'View feeds' },
    // Operators add and remove feeds: undeclared, `:write` would infer manage (admins only)
    { id: 'rss:write', level: 'operate', description: 'Edit feeds' },
  ],
  status: { page: 'index', requiredPermissions: ['rss:read'], handler: readStatus },
  actions: { add: { page: 'index', requiredPermissions: ['rss:write'], handler: addFeed } },
});
  • Declare the names your plugin's pages and methods use. When several plugins declare one name with different levels, the strictest wins (manage > operate > read), so a later plugin cannot lower another plugin's gate.
  • Names that appear only in page metadata, with no RPC, use the inferred level.
  • level must be read, operate or manage; a malformed or duplicate id throws at setup time.

Built-in status: ambient engagement and skills assistant ​

Ambient engagement (群聊插话) and the skills assistant (技能助手) are provided by the Host itself, not by a plugin, so they sit under the root plugin:

MethodCallPermission needed
plugin.root.ambientpluginRpc('root', 'ambient')ambient:read
plugin.root.skillspluginRpc('root', 'skills')skills:read

A global owner doesn't need these permissions; they are plugin-defined names granted by level: *:read goes to viewer and above (see Plugin permission levels). Both queries are read-only and take no input.

The data lives only in memory: the last 24 hours, at most 2000 entries, cleared on restart. It never includes chat text, prompts, judge reasons or secrets. All times are millisecond timestamps.

plugin.root.ambient returns:

ts
interface AmbientStatus {
  enabled: boolean;                       // at least one group is configured
  mode: 'off' | 'shadow' | 'active';      // shadow: judge without speaking
  groups: number | 'all';                 // configured groups, or 'all' for '*'
  judges: string[];                       // judge models in order (provider/model)
  last24h: { spoke: number; watched: number; stayed_quiet: number; skipped: number };
  decisionShadow: { agreed: number; disagreed: number }; // ai.decisions.ambient shadow vs the chat-model judge
  recent: Array<{                         // newest first, at most 20
    at: number;
    group: string;                        // platform:groupId
    outcome: 'spoke' | 'watched' | 'stayed_quiet' | 'skipped';
    skipReason?: 'cooldown' | 'hourly_cap' | 'judge_interval' | 'no_context' | 'judge_failed';
    confidence?: number;                  // 0..1, two decimals
    judge?: 'decision' | 'chat-model';
  }>;
  updatedAt: number | null;
}

watched means the judge would have spoken but shadow mode kept it quiet.

plugin.root.skills returns call statistics for structured decisions (choosing skills, tools, memory, sub-agents, approvals and ambient engagement):

ts
interface SkillsStatus {
  tasks: Array<{                          // one row per task, sorted by name
    task: 'skills' | 'tools' | 'memory' | 'agents' | 'approval' | 'ambient';
    mode: 'off' | 'shadow' | 'active';    // mode of the latest call
    calls: number; selected: number; abstained: number; shadow: number; failed: number;
    averageMs: number;
    inputTokens: number; outputTokens: number;
    lastModel?: string;
    lastAt: number;
  }>;
  totals: { calls: number; inputTokens: number; outputTokens: number };
  recent: Array<{                         // newest first, at most 20
    at: number; task: string; mode: string;
    outcome: 'selected' | 'abstained' | 'failed' | 'shadow';
    durationMs: number;
    model?: string;
    reason?: string;                      // machine-readable failure/abstain reason, never free text
  }>;
  updatedAt: number | null;
}

Built-in queries: decision replay ​

The decision replay on the Bot status (机器人状态) page (ADR 0036 slice C) is also provided by the Host. It reads the ai_decision_events decision audit table: one row each time the bot decides whether to call the model, whether to speak, or whether to call a tool. Rows from one turn share a turn_id.

MethodCallPermission needed
plugin.root.decisionspluginRpc('root', 'decisions', { ... })decisions:read
plugin.root.decision-turnpluginRpc('root', 'decision-turn', { turnId })decisions:read
plugin.root.decisions-exportpluginRpc('root', 'decisions-export', { since, until, ... })decisions:read

All three are read-only. Times are millisecond timestamps. kind and outcome only accept the ADR 0036 enums; a typo returns invalid_input rather than an empty result.

  • decisions: the list, newest first. Optional input: platform, sceneId, kind, outcome, reasonCode (e.g. cold_field_mention_only_on, for rows that share a kind), since (inclusive), before (exclusive), limit (default 50, at most 200). Returns { persistent, items, nextBefore }. When nextBefore isn't null, pass it back as before for the next page.
  • decision-turn: one turn's timeline, oldest first. Returns { turnId, startedAt, endedAt, truncated, events }. A turn with no rows (or past retention) returns not_found.
  • decisions-export: exports a time window. since and until are required (both inclusive, at most 31 days), and the list filters can be added. Pages come back oldest first as { table, exportedAt, window, filters, count, nextSince, events }. When nextSince isn't null, pass it back as since; the pages' events joined in order are the full export.

Each row uses the table's column names (id, ts, turn_id, instance_id, platform, scene_id, user_id, kind, outcome, reason_code, reason_detail, payload, actor, actor_id), with payload as an object. Rows are redacted when written: no secrets, cookies, tokens or full prompts.

A single result is capped at 256 KB, so the list and export are paged by size. Rows from the same millisecond always land on the same page, so paging by timestamp never skips or repeats a row. Without a database (persistent: false) only the last 200 in-process rows are visible.

Rows are kept for 14 days by default; change it with ai.audit.retentionDays. Expired rows are removed at startup and then hourly. For the switches, see the control plane below.

Built-in queries: usage stats ​

plugin.root.usage-stats (pluginRpc('root', 'usage-stats', { ... }), permission control:read) is read-only and feeds token-usage charts. It reads data/agent-traces/*.jsonl with the same aggregation as zhin usage report.

  • Input (all optional): since / until (epoch ms; until defaults to now, since to 7 days before it), bucket ('hour' or 'day'; default day when the range is over 2 days, else hour), session (substring of the session key, or a glob with *). Ranges over 31 days return invalid_input.
  • Output: range (with the host timeZone), totals, byModel (by input tokens, descending), bySession (top 50), series (one entry per bucket in range, zero-filled, ascending), segments (summed history / fixed / user context estimates), filesRead, malformedLines. totals, byModel, bySession and series carry cacheReadTokens, cacheWriteTokens and cacheShare (0 to 1); totals.cacheShareByCall is the p50 / p90 of per-call cache share.
  • Dimension fields (from schemaVersion: 2; older data degrades gracefully):
    • schemaVersion: integer version of the response shape (currently 2). Older instances omit it; treat that as 1 and hide the new tabs.
    • byModel[] also carries driverLabel (display name of the service's Driver, e.g. "OpenAI compatible") and profileId / profileName (only when every call of the row is attributed to the same model Profile — a single unattributed call leaves them out; after a model fallback, calls go to the Profile switched to; profileName only when the Profile has a name). Use them to tell services with the same name apart.
    • byAgent[]: totals per Agent — agent, label, kind (main / agent / unrecorded), turns, calls, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, cacheShare. Each (sub-)turn's calls count toward its own model_selection; traces that recorded no model selection go to agent: '@unrecorded' ("not recorded"), the main assistant is agent: '@main'. Token columns add up to totals; turns counts (sub-)turns — a turn with a sub-agent counts once for the main assistant and once for the sub-agent — so the rows' turns can add up to more than totals.turns.
    • byPurpose[]: totals per purpose — purpose (chat, agent, summary, ambient, perception, …; agent:<name> counts as agent) with a readable label; other fields as in byAgent. Each (sub-)turn node is classified by its own model_selection.purpose (not the root turn's); unrecorded calls use @unrecorded. Tokens and turns follow the same rules as byAgent.
    • bySession[] also carries structured name parts: scopeKind (group / private / channel / schedule / internal / http / a2a / mcp), sceneLabel (group name, user name, the schedule job's label while the instance still knows the job, else its id, … without a type word) and shortKey (the short session key, same rule as zhin usage report). displayName is unchanged (a pre-built Chinese label); a Console should build the label from scopeKind + sceneLabel in its own language and append shortKey when names collide.
    • bySession[] also carries endpoint (the account recorded in the trace) and accountLabel (that account's current name, matched by the platform the trace recorded — the client adapter name — and the account id / name; absent once the account is gone or when its name is just the raw account id). For hashed session keys (personal-session:v1:…), which carry no address, platform comes from the trace's recorded origin. Top-level sessionsTotal counts every session in range and othersTotals sums the sessions beyond the top 50 (sessions, turns and the token fields).
    • Input compare: 'previous' also sums the window of the same length right before since and returns previous: { since, until, truncated, totals } (totals only, no breakdown). The previous window is shifted by its length in milliseconds (since - (until - since) to since), not aligned to calendar days, and the session filter applies to it too. The current and the previous window are each limited to 31 days (at most 62 days are scanned per request), so "last 30 days" gets a complete previous period; only a previous window that had to be cut short (e.g. at timestamp 0) is marked truncated: true — the Console should then say the previous period is partial. Any other compare value returns invalid_input.
  • The permission is still control:read; the new fields are display names and groupings of data already returned, with no prompt or message content.
  • Only counts, session keys and provider / model / Profile / Agent / account names are returned, never message text. Results are cached in memory for 60 s (at most 32 entries; a different compare is a separate entry) and dropped when the generation changes.

Built-in actions: control plane ​

The control plane on the Bot status (机器人状态) page (ADR 0036 slice D) is also provided by the Host. It is the one place to make the bot go quiet right away.

MethodCallPermission needed
plugin.root.controlpluginRpc('root', 'control')control:read
plugin.root.control-setpluginRpc('root', 'control-set', { expectedRevision, instance?, sessions? })control:write (an action; owners can always call it)

Four switches:

SwitchEffect
emergency_stopNo model calls and no outbound messages (including proactive ones such as scheduled notices); only the audit and Console reads remain
mutedDoesn't speak: incoming messages, ambient engagement and scene event wakes never reach the model
read_onlyNo writes: no model calls, no outbound messages
mention_onlyOnly messages that @ the bot (match the trigger) or private chats reach the model; ambient engagement and scene event wakes are skipped

There are two levels: the instance default (instance) and per-session overrides (sessions, by platform + sceneId; sceneId looks like group:123, the same key as the session profile). An override can only be stricter: false in a session just removes that override and never relaxes an instance switch. The order is emergency_stop → instance muted → session muted → read_only → mention_only → normal speak / ambient / scene event policy, and the first match wins. The control plane runs before the session profile's can-speak check, so a blocked message skips that check and ambient judging. If a switch changes while a turn is running, the bot checks again before sending, and any of the first three switches stops the message.

  • control: returns { revision, instance, sessions, temporary, updatedAt, updatedBy, persistent, available, precedence }. temporary[] holds overrides added by policy (for now only the cold-field mention_only, see below); each has platform, sceneId, switch, source (cold_field), actor (policy), since and expiresAt. It doesn't count towards revision. available: false means the saved state can't be read right now. Until it can, every check acts as emergency_stop (fail closed) and writes are refused.
  • control-set: changes only the switches you send. expectedRevision is required (read it with control first); if it doesn't match you get conflict and nothing is overwritten. On success it returns the new state and changed (how many scopes actually changed). Sending mention_only: false explicitly (per session clears that session, at instance level clears all) also clears cold-field temporary overrides, writing one control_change / cold_field_mention_only_cleared row (actor=operator) per session.

Each block writes a kind=control_gate row (reason_code is control_emergency_stop, control_muted_instance, control_muted_session, control_read_only or control_mention_only). Each change writes one kind=control_change row per changed scope with actor=operator and the before and after values in payload; both show up in the decision replay. The switches are saved in the ai_control_state table and survive a restart; without a database they live only in the process.

The model has no tool that can read or change these switches: it can't unmute itself or turn off emergency_stop. The dangerous-tool hard gate is slice E and isn't covered here.

Built-in operations: welcome and leave records ​

The per-session ops config (ADR 0037 phase 1, slice A) is also served by the Host. The Console page comes later; only the RPC exists for now.

MethodCallPermission
plugin.root.session-opspluginRpc('root', 'session-ops')control:read
plugin.root.session-ops-previewpluginRpc('root', 'session-ops-preview', { platform, sceneId, template? })control:read
plugin.root.session-ops-setpluginRpc('root', 'session-ops-set', { expectedRevision, defaults?, sessions? })control:write (an action; owners can always call it)

The config is keyed by platform + sceneId (like group:123, the same key as the session profile) and is stored apart from the session profile:

FieldMeaningDefault
welcome.enabledSend a welcome (per session only)false
welcome.templateTemplate; variables {members} (mentions each one), {nickname}, {group}, {rules_url}; unknown variables are kept as written欢迎 {members} 加入{group}!
welcome.mergeWindowMsJoins inside this window share one welcome; 0 turns merging off60000
welcome.maxPerHourMost welcomes per session per hour10
welcome.rulesUrlValue of {rules_url}empty
leave.recordRecord leaves in the audit logtrue
leave.notifyPost a message when someone leaves (stored only for now, nothing is sent)false
coldField.enabledCold field (slice C): turn it on (per session only)false
coldField.thresholdHow many group messages in a row, not addressed and not engaged by ambient, before a temporary mention_only (1–1000)20
coldField.durationMsHow long the temporary mention_only lasts (1 minute – 24 hours)1800000
ops.cooldownMsGroup-ops cooldown (slice E): one hard-gate approval card per platform + sceneId + action (the tool's local name, e.g. kick_member) within this time; 0 turns it off, max 24 hours. Settable as instance default and per session60000
  • session-ops: returns { revision, defaults, sessions, updatedAt, updatedBy, persistent, available }; each session has overrides (fields set explicitly) and effective (merged with the instance defaults).
  • session-ops-preview: renders only. It doesn't send and doesn't write to the audit log. It uses the last real join seen in that session (in memory) or a sample member, and returns { text, parts, unknownVars, sample, members, enabled }. Pass template to preview a template you haven't saved.
  • session-ops-set: defaults takes only the template and numbers (no switches). In sessions[], the fields you send replace the old values, null falls back to the instance default, and reset: true removes the session's config. expectedRevision is required; a mismatch returns conflict. Every scope that actually changed writes one kind=config_change, actor=operator row.

Group-ops cooldown (ADR 0037 §3, slice E): before the hard gate creates a new approval card, it checks the cooldown. The timer starts when the card is created, whether it is later approved, denied or times out. Calling the same action again during the cooldown is refused without a new card; the model is told it is cooling down and how many milliseconds remain. That writes kind=ops_cooldown, outcome=deny, reason_code=ops_cooldown_hit (payload has action, target, remainingMs, platform, sceneId) plus a tool_hard_gate deny row with the same turn_id. Outside a cooldown it writes ops_cooldown_passed and goes on to approval. A card an operator already approved in the Console still runs for the same arguments (that card started the timer). The timers live in process memory and reset on restart; the cooldown only throttles cards, dangerous tools still need a human approval every time.

Cold field (ADR 0037 §1.3, slice C): only group messages count. An unaddressed group message that went through ambient judging and wasn't engaged (including ambient's own cooldown / cap skips) adds 1. Being addressed, an ambient engagement or the bot speaking on its own (a scene event wake reply, a template welcome, an announcement) resets it. Messages with ambient off, or blocked earlier by the control plane or the session profile, neither count nor reset. At coldField.threshold the session gets a temporary mention_only (actor=policy, expiresAt = now + durationMs), written as kind=control_change, reason_code=cold_field_mention_only_on; it is removed automatically when it expires, writing cold_field_mention_only_expired. Temporary overrides are stored apart from the operator's switches, only ever make things stricter, never change a manual switch, and show up in control's temporary[]. While one is active, skipped entries still write control_gate with reason_detail policy:mention_only. Counters and temporary overrides live in process memory and reset on restart. A session that is already mention_only doesn't get another one.

A welcome goes: join → merge window → hourly cap → control plane (a template welcome counts as addressed: mention_only, including the cold-field override, doesn't block it; the stop switches still do) → session-profile speak check → send. A blocked welcome is only audited and never sent later; a failed send isn't retried. Once welcome.enabled is on for a session, scene event wakes no longer run the model for joins, so the template welcome isn't doubled. Rows use kind=member_lifecycle with welcome_sent / welcome_merged / welcome_rate_limited / welcome_disabled / member_leave_recorded; blocks by the control plane or the session profile keep their control_* / cannot_speak_* codes. The config lives in the ai_session_ops table; if it can't be read, no welcome is sent and leaves are still recorded.

Built-in: announcements (draft → approve → send) ​

Announcements (ADR 0037 phase 1, slice B) are Host RPCs; the Console page comes later. Reads need control:read; create, edit and submit need control:write; approve, reject and resend need the approver permission ops:approve (slice E), so control:write alone cannot approve. ops:approve also lists and settles dangerous-tool approval cards (see Dangerous-tool approval cards).

MethodCallPermission
plugin.root.announcementspluginRpc('root', 'announcements', { platform, sceneId, status? })control:read
plugin.root.announcementpluginRpc('root', 'announcement', { id })control:read
plugin.root.announcement-createpluginRpc('root', 'announcement-create', { platform, sceneId, content, endpoint? })control:write (action)
plugin.root.announcement-editpluginRpc('root', 'announcement-edit', { id, expectedRevision, content })control:write (action)
plugin.root.announcement-submitpluginRpc('root', 'announcement-submit', { id, expectedRevision })control:write (action)
plugin.root.announcement-approvepluginRpc('root', 'announcement-approve', { id, expectedRevision })ops:approve (action)
plugin.root.announcement-rejectpluginRpc('root', 'announcement-reject', { id, expectedRevision, reason? })ops:approve (action)
plugin.root.announcement-resendpluginRpc('root', 'announcement-resend', { id, expectedRevision })ops:approve (action)

Status only moves forward: draft → pending → approved → sent, with rejected / expired / failed on the side. Editing the text (in any non-final status) goes back to draft and recomputes contentHash; a pending announcement expires after 24 hours. The model can only create drafts with the announcement_draft tool (risk: safe); it can't submit, approve, or send.

  • announcement-approve sends right away and returns the status after sending plus send.result (sent / failed). Order: hash check → control plane (judged as addressed, so mention_only doesn't block) → session-profile speak check → hard gate (this approval counts as the hard-gate approval, no second approval card) → the platform's group-notice API.
  • A blocked or failed send becomes failed with a reason. It isn't queued or retried; announcement-resend puts it back to pending and it needs another approval. If the text no longer matches the approved hash, it's refused (announcement_hash_mismatch).
  • Every action needs expectedRevision; a mismatch returns conflict and nothing is overwritten. Each transition writes one kind=announcement row (announcement_drafted / _submitted / _approved / _rejected / _expired / _sent / _send_failed / _resend / _hash_mismatch); blocks by the control plane or session profile keep their control_* / cannot_speak_* codes. Data lives in the ai_announcements table.

Built-in: session events (reminders) ​

Session events (ADR 0037 phase 1 slice D) have Host RPCs; the Console page is built separately. Reads need control:read; create, update, and cancel need control:write.

MethodCallPermission needed
plugin.root.session-eventspluginRpc('root', 'session-events', { platform, sceneId, status? })control:read
plugin.root.session-eventpluginRpc('root', 'session-event', { id })control:read
plugin.root.session-event-createpluginRpc('root', 'session-event-create', { platform, sceneId, title, at, remindBefore?, template?, endpoint? })control:write (action)
plugin.root.session-event-updatepluginRpc('root', 'session-event-update', { id, expectedRevision, title?, at?, remindBefore?, template? })control:write (action)
plugin.root.session-event-cancelpluginRpc('root', 'session-event-cancel', { id, expectedRevision })control:write (action)
  • at is a millisecond timestamp (stored in UTC; {at} is shown in the instance time zone TZ, default Asia/Shanghai). remindBefore is an array of lead times in milliseconds, at most 5, each up to 30 days. There's always a reminder at at itself; remindBefore only adds earlier ones. Lead times that are already in the past when you create or update the event count as fired. title is at most 60 characters; template can use {title} {at} {in}, and an empty one uses the default 【日程提醒】{title}:{at}({in}).
  • Status: scheduled → done (every reminder fired) / cancelled. Updating and cancelling only happen here, including events the model created; the model can only create events for the current group or channel with the session_event_create tool (risk: safe).
  • When a reminder is due, reminders for the same session in the same minute become one message. Order: inbound_wake (schedule_wake_fired) → control plane (judged as addressed, so mention_only, including the cold-field override, doesn't block; the stop switches still do) → session-profile speak check → template sent as is (no model call). A blocked or failed reminder still counts as fired: it isn't resent or retried.
  • After a restart, reminders missed by more than 10 minutes aren't sent and are logged as schedule_wake_missed; ones within 10 minutes are sent.
  • Every write needs expectedRevision; a mismatch returns conflict and nothing is overwritten. Audit rows use kind=schedule: schedule_event_created / _updated / _cancelled, schedule_wake_fired (sent alone) / schedule_wake_merged (sent merged) / schedule_wake_missed; blocks by the control plane or session profile keep their control_* / cannot_speak_* codes. Data lives in the ai_session_events table (not schedule-jobs.json).

Built-in actions: group moderation rules (draft → approve in group → active) ​

Group moderation rules (ADR 0039 slice B) are an "approve once" violation ladder, such as "remind advertisers first, then mute for 10 minutes". Reads need control:read, drafting / disabling need control:write, and approving / rejecting need ops:approve.

MethodCallPermission
plugin.root.group-rulespluginRpc('root', 'group-rules', { platform, sceneId, status? })control:read
plugin.root.group-rulepluginRpc('root', 'group-rule', { id })control:read
plugin.root.group-rule-createpluginRpc('root', 'group-rule-create', { platform, sceneId, trigger, ladder, windowMs?, exempt?, content })control:write (action)
plugin.root.group-rule-disablepluginRpc('root', 'group-rule-disable', { id, expectedRevision, reason? })control:write (action)
plugin.root.group-rule-approvepluginRpc('root', 'group-rule-approve', { id, expectedRevision, contentHash? })ops:approve (action)
plugin.root.group-rule-rejectpluginRpc('root', 'group-rule-reject', { id, expectedRevision, reason? })ops:approve (action)
  • sceneId must be group:<id>; trigger is advertising / abuse / flood; each ladder stage is { action: 'remind' | 'warn' | 'mute' | 'suggest_kick', durationSec? }, with mutes between 60 seconds and 24 hours; windowMs (the cool-down) defaults to 30 minutes.
  • group-rule-create drafts the rule and submits it right away (pending), posting a preview card to that group. The model only has the rule_draft tool (risk: safe, group chats only): the person asking must be the group owner or an admin (judged from the live platform role on their message); otherwise it is refused and rule_draft_forbidden is recorded.
  • Commands in the group (they only work in the rule's own group; send them with this account's command prefix, none by default — the preview card already spells them with the group account's prefix): rule approve <code>, rule reject <code>, rule disable <code|trigger>, rules (lists the group's rules; anyone can read it). The code is the first 8 characters of the content_hash on the card; changing any part of the rule changes the code, so an old card can't approve new content. Approvers are the group owner / admins plus ai.agent.toolHardGate.imApproval.approverIds; in the Console it is ops:approve.
  • Status only moves forward: draft → pending → active, with rejected / expired (not approved within 24 hours) / disabled on the side. A group has at most one active rule per trigger; approving a new one disables the old one (rule_superseded). Disabling needs no approval; to relax a rule, disable it and draft a new one.
  • Each transition writes kind=group_rule (rule_drafted / _submitted / _approved / _rejected / _expired / _disabled / _superseded / _hash_mismatch, rule_draft_forbidden). Data lives in the ai_group_rules table; final-state rules are deleted after 30 days or beyond 50 per group (pruned at startup and hourly).
  • Enforcement (slice C): when a detector reports a hit, the group's active rule runs its current stage and writes kind=rule_enforcement:
    • remind / warn: a template reminder that @-mentions the member (no model call), gated by the control plane (emergency_stop / muted / read_only block it) and the session profile; rule_hit_remind / rule_hit_warn.
    • mute: runs automatically, no card — the rule's approval is the hard-gate approval for this mute (the tool_approval row has via: rule, approvalId = the rule id, actor = the approver). It still passes the control plane's emergency_stop / read_only and ops_cooldown; rule_hit_mute.
    • suggest_kick: never kicks on its own. It raises a member approval card (with the evidence and the rule code) and kicks only once a human approves; repeat hits within the cool-down raise no new card; rule_hit_kick_suggested.
    • Owners / admins or whitelisted members: rule_hit_exempt. The bot is not an admin: rule_hit_bot_not_admin, with one notice per group per day.
    • Ladder: a repeat within the quiet window moves up one stage; past the last stage, the last stage repeats; messages sent before the reminder was delivered do not count as repeats; an action that did not happen (blocked, cooling down, platform error) does not move the ladder. Progress is kept in memory only (capped, expired entries pruned) and resets on restart.
    • flood (repeat spam): detected locally, no model call. It fires when one member sends the same or a highly similar message 3 times within 60 seconds (several members each saying the line once does not count). Text is compared after stripping whitespace, punctuation and case; lines of 6+ characters also match at a character-bigram similarity ≥ 0.8; pure images / faces are compared by a content digest; reply quotes are ignored. A hit is handed to the group's active flood rule and writes an extra rule_hit_flood row (same turn_id as the action row); with no active rule nothing happens. Detection lives in memory only (≤ 20 fingerprints per member, ≤ 5 000 tracked members, pruned after the window) and writes nothing to disk.
    • advertising / abuse: judged by the content-moderation plugin (LLM review) and reported to the enforcer through groupRuleViolationToken (@zhin.js/core/runtime); the plugin no longer mutes or kicks by itself. Migration (a deliberate tightening): the first message in a group on the plugin's groupModeration list creates one pending rule each for ads and abuse from the default template "remind → warn → mute 600 s, 30-minute quiet window" (drafted by content-moderation) and posts its preview card; auto-mute resumes only after an owner / admin confirms it once, and until then the plugin only reminds / warns. A group that already has a rule of that trigger in any state (including rejected / disabled) gets no new one. An ad posted within 10 minutes of joining now raises a kick approval card (referencing the active or pending advertising rule, without moving the ladder, audited with newcomer: true) instead of an unattended kick.

Built-in actions: dangerous-tool approval cards ​

Calls stopped by the hard gate (ADR 0036 §3) leave an approval card here. The approver permission is ops:approve (ADR 0037 §3, slice E), separate from control:write. The older permissions still work so existing tokens keep working; holding either one is enough.

MethodCallPermission
plugin.root.tool-approvalspluginRpc('root', 'tool-approvals')tool_approvals:read or ops:approve
plugin.root.resolve-tool-approvalpluginRpc('root', 'resolve-tool-approval', { id, decision: 'approve' | 'deny' })ops:approve or tool_approvals:resolve (action; owners can always call it)

Built-in actions: self-change approval (ADR 0040) ​

Controlled self-changes drafted by the bot (see Letting the bot change itself). The list carries metadata only; file bodies and config values are served to approvers through the detail call.

MethodCallPermission
plugin.root.self-changespluginRpc('root', 'self-changes')tool_approvals:read or ops:approve (pending / recent changes and staging usage usageBytes, no bodies)
plugin.root.self-change-detailpluginRpc('root', 'self-change-detail', { id })ops:approve only (unified diff per file, ≤ 64 KB combined across all files, cut by line; config patch values redacted like audit payloads; full trial checks and skippedChecks; bodiesAvailable: false once slimmed)
plugin.root.resolve-self-changepluginRpc('root', 'resolve-self-change', { id, decision: 'approve' | 'reject' })ops:approve (action)
plugin.root.mark-self-change-handledpluginRpc('root', 'mark-self-change-handled', { id })ops:approve (action; a failed change was dealt with)

Page UI guidelines ​

The Console follows one set of rules for information density, typography, spacing and responsive layout (the "设计规则" addendum of ADR 0063). They are mandatory for the Console's own pages; for third-party plugin pages they are recommended, plus a small set of hard-floor rules; the official plugins in this repository (zhinjs/zhin plugins/**) follow them in full since ADR 0063 P2 and serve as reference implementations (see the end of this section).

Recommended: compose the Console's components instead of styling things yourself. Pages written as a pure blueprint (definePageBlueprint) are rendered by the Console and need no extra work: the renderers now use the unified component library (ADR 0063 P2) and follow the rules automatically. For hand-written .tsx pages, compose the Console's components and use its semantic tokens rather than hard-coding font sizes, radii, shadows or padding, or arbitrary Tailwind values (p-[…] and the like), and do not use native <button>, <select> or <table> in place of components. If you use Tailwind, keep spacing to the 8 standard keys 1, 2, 3, 4, 6, 8, 12 and 16 (the 8-step scale from 0.25 to 4rem); other keys such as p-5 or gap-2.5 are off the scale. Why:

  • your page looks like part of the same product when it sits next to the Console's own pages;
  • the type scale, spacing, narrow-screen layout changes (tables turning into cards, for example), touch target sizes, focus styles and light/dark mode all come with the components, and your page follows when the Console adjusts its styles later.

The unified component library is @zhin.js/console-ui (with a precompiled styles.css; see its README). The renderers of declarative, adapter and comment review pages use it (ADR 0063 P2); hand-written pages follow "Page shell and components" below. @zhin.js/client/ui was removed in ADR 0063 P4, see "Upgrading from @zhin.js/client/ui".

Its tokens/tokens.mjs is the single source of the scale (ADR 0063 P1b): spacing space-1…space-8 is the Tailwind keys 1, 2, 3, 4, 6, 8, 12, 16 (space-5 is p-6), font sizes label / body / section / title / display, weights regular / medium / strong, radii r-0…r-4 / full, shadows e-1…e-3; content width is reading (60rem, settings and forms) or data (120rem, lists and tables, the default). Hand-written pages that use Tailwind can import the generated @zhin.js/console-ui/theme.css, so off-scale keys simply do not exist; @zhin.js/console-ui/audit is the same layout audit and can be run against your own pages.

Use colors by role (ADR 0063 D23–D25, zhinjs/console#125): the brand color brand (#76EEC6 light, #7FFFD4 dark, the same under every palette) is only for the one solid primary button of a view, Button variant="primary"; as text or a thin line (links, selection) use brand-text. States use only the signal colors signal-*-fill (fills and marks) and signal-*-text (text), and steady states (running, succeeded, 0 failures) get no color; charts use chart-1…chart-8. Dangerous actions on a page use variant="destructive" (ghost) or destructive-outline; the solid red destructive-solid appears only in confirmation dialogs. Motion uses only --console-motion-fast / -base / -slow and --console-ease-out.

Custom UI is allowed. Interfaces the components cannot cover (charts, canvases, games, workspaces) may be designed your own way, but please follow the same rules as far as you can.

Hard floor (required). With or without the component library, a plugin page must:

  1. never scroll the whole page horizontally, at any width;
  2. keep its content inside the page container and never cover the Console's top bar, navigation, page header or global overlays;
  3. show a visible focus style on interactive elements;
  4. give interactive controls a touch target of at least 44×44px at phone widths;
  5. use the Console's theme tokens for background and text, so it stays readable in both the light and the dark theme.

zhin plugin check reports deviations from the recommendations as hints (never errors; they do not block a build or publish), each with how to switch to a component or token; see "Page checks in zhin plugin check" below.

Official and third-party plugins. Third-party plugins are recommended to follow all of the rules above; only the hard floor is required, and zhin plugin check reports everything else as hints. Official plugins follow every rule and serve as reference implementations: zhin plugin check rules 1–6 and the layout audit covering every rule (type scale, spacing, radius / border / shadow, responsive behaviour and the hard floor) are errors in zhinjs/zhin CI for the official plugins on the gate list, just as for the Console's own pages (plugins not yet on it are only reported). There are no exceptions by default; where one is truly needed, a single check can be waived only with an ignore comment in the source that names the check and the reason, and it goes through review. Every official plugin with pages is on the gate list (ADR 0063 P2 acceptance), so you can look at them when writing your own pages.

Page checks in zhin plugin check ​

zhin plugin check checks a plugin's pages/** (scripts and .css / .scss / .less, without tests and declaration files). Each hint says what it means and how to fix it:

RuleWhat it checksUse instead
1Native <select> (JSX or createElement('select'))Select from @zhin.js/console-ui (SearchableSelect when it needs search)
2Custom page header: <h1>, or PageHeader / PluginPage imported from @zhin.js/client/ui (removed; importing it fails the build)Put the title in definePage({ title }) and header actions in usePageChrome(); start sections at <h2>
3Fixed content width: width / max-width of at least 640px or 40rem (styles, CSS, max-w-[…] / w-[…], max-w-2xl and up, max-w-prose, max-w-screen-*), or setting --console-content-max yourselfRemove it and leave it to the shell; use definePage({ fullWidth: true }) for full width
4Raw style values: literal font size, font weight, radius, shadow, padding, margin or gap in a style attribute, a style object whose name ends in style / styles, a CSS string or a stylesheet (0, keywords such as auto / none, and var(--console-…) are fine)Components, or var(--console-…) semantic tokens
5Off-scale Tailwind classes: arbitrary values (p-[…], rounded-[…], text-[…]; references to Console tokens such as p-(--console-…) are fine), off-scale spacing keys (p-5, gap-2.5), default shadow / shadow-sm … shadow-2xlSpacing keys 1, 2, 3, 4, 6, 8, 12, 16, radius 0–4 / full, shadows e1–e3, or components
6Native <button>, <input>, <textarea>, <table>, <dialog>Button, Input, Textarea, Table, Dialog

Rule 3 is an approximation: a static check cannot tell which element is the page's root container, so a fixed width of at least 640px / 40rem is taken to set the content width.

Waivers. To keep a pattern on purpose, add a comment at the end of the line or on the line above, naming the rule and the reason (several rules separated by commas):

tsx
{/* zhin-ui-ignore 6: native <button> inside the canvas; focus and touch size meet the floor */}
<button className="canvas-tool" />

Use // zhin-ui-ignore 4: … in scripts and /* zhin-ui-ignore 4: … */ in stylesheets. A comment on a line of its own waives the next line with code; a comment after code waives its own line; only the named rules are waived. Comments without a rule or a reason, or that waive nothing, are reported too. Waivers for the Playwright layout audit go on the element itself: data-zhin-ui-ignore="<audit check>: <reason>" (applies to the element and its descendants; the audit tool defines the check names).

The gate for official plugins. The official plugins in this repository treat these checks as errors in CI:

  • The gate list is scripts/plugin-ui-gate.json: violations of plugins in gated fail, plugins in pending are only reported and state the condition for joining; every official plugin with pages/ must be in one of them. All official plugins are now in gated and pending is empty (ADR 0063 P2 acceptance); a new official plugin with pages joins gated directly.
  • pnpm check:plugin runs rules 1–6 (in the PR contracts stage) and pnpm check:plugin-ui-audit runs the full Playwright audit (in full validation; the audit tool is @zhin.js/console-ui/audit and needs @zhin.js/console-ui built; declarative blueprints, adapter pages and comment review pages are rendered by the @zhin.js/client renderer mount module packages/console/client/audit/mount-plugin-page.tsx, replaceable with --mount-module or ZHIN_UI_AUDIT_MOUNT_MODULE; a gated page that fails to mount fails the gate). Both use the same list and list violations and every waiver by plugin and check in the run summary.
  • The list cannot switch a check off for a plugin or a file; waivers are only the inline comments above, reviewed with the PR.

Page shell and components ​

Plugin pages do not draw their own header or container. The Console renders the page shell (ADR 0063, decision 2):

The shell ownsThe plugin page owns
Title, description, header actions and the refresh control (RefreshControl: updated hh:mm:ss, manual / 5s / 15s / 30s auto, refresh)Content blocks: sections, tables, forms, stat cards, notices
Content width (--console-content-max), page padding, header actions folded into "More" on phonesThe page's own data and actions (usePluginRpc, pluginRpc)
Under the plugin detail page: plugin name, description and status (the page title becomes the tab label)Confirmation of dangerous actions (built into the components)
  • Declarative pages (definePageBlueprint, defineAdapterPage, defineCommentReviewPage) get the shell automatically: the renderer hands the blueprint's title, description, form-less actions, status badges and refresh setting to the shell and renders only content blocks. The mark field (letter tile) of blueprints and comment review specs was removed in ADR 0063 P4; setting it is a type error, so delete it. Actions with variant: 'danger' render as outline buttons with a confirmation dialog, and get the default text Confirm <action>? when they have no confirm, with no change to the plugin. Without a shell around it (an older Console) the renderer draws the header at the top of its content.
  • Hand-written .tsx pages render only content from their default export, with components from @zhin.js/console-ui (declare it in peerDependencies; the Console provides one shared copy). For header actions or the refresh control call usePageChrome and let the shell place them; it returns false when no shell listens, and the page may then draw them itself:
tsx
import { useLocale, usePluginRpc } from '@zhin.js/client';
import { Button, Section, usePageChrome } from '@zhin.js/console-ui';

export default function Feeds() {
  const { t } = useLocale();
  const status = usePluginRpc<{ feeds: string[] }>('root/rss', 'status');
  usePageChrome({
    actions: <Button size="sm" variant="outline" onClick={() => void status.refresh()}>{t('立即抓取')}</Button>,
    refresh: { onRefresh: status.refresh, updatedAt: status.lastSuccessAt ?? null, refreshing: status.refreshing },
  });
  return <Section title={t('订阅')}>…</Section>;
}

A page that writes its own <h1>, PageHeader or PluginPage breaks the rule (zhin plugin check reports it). The full component list is in the @zhin.js/console-ui README; its layout components and content blocks switch layout by the width of their own container (container queries, not the viewport):

  • Page and sections: PageShell width tells reading / form pages (reading, 60rem) from data pages (data, 120rem, the default) and full-width pages (full, i.e. definePage({ fullWidth: true })); sections use Section (an <h2> title, one description, section actions), card grids Grid (auto-fit, min is the narrowest column), statistics StatGrid + StatCard (two per row in a narrow container; StatCard takes a unit, a badge and a footer such as a progress meter), list + detail ListDetail (side by side from 90rem, otherwise the detail opens in a side sheet).
  • Tables: below 40rem of its own width Table turns every row into a card, each cell labelled with its column; priority="secondary" columns are left out of the cards, and nothing scrolls sideways.
  • Actions: header actions go through usePageChrome({ menuActions, moreActions }) or PageActions (folded into 「更多」 below 40rem), row actions through RowActions (one labelled main action, the rest in the MoreMenu); every action has a visible label, and dangerous ones are outline buttons with a confirmation dialog.
  • Overlays and touch: selects, popovers and dialogs are bottom drawers at phone width; interactive controls are at least 44px there (checkboxes, radios, switches and inline links get a larger hit area with .console-touch).
  • Status: StatusBadge only colors states that need attention; normal ones are muted.
  • Empty states (ADR 0063 D28): EmptyState is one 64px line-art illustration + one sentence + at most one action, e.g. illustration="tasks" with the action { label: 'New scheduled task', variant: 'primary', onSelect }. The seven illustrations are messages, tasks, logs, table, record, not-found and generic; without copy the illustration's own sentence is used. Do not write a bare "No data".
  • Forms (D29): secondary fields (fallback models, unset slots) use variant="ghost" (Input, Textarea, SelectField, SearchableSelectField, DateField, DateTimeField), which shows a border only on hover or focus. Dates use DateField (value YYYY-MM-DD) and DateTimeField (value YYYY-MM-DDTHH:mm) instead of the browser's native date inputs; values are local-time ISO strings, an empty string when cleared, and the pickers work from the keyboard.
  • Short identifiers and icons (D30, D31): package names, RPC names and IDs use InlineCode (monospace, a very light fill, no border), not bordered chips. Lucide icons use strokeWidth={CONSOLE_ICON_STROKE_WIDTH} (1.75), 16px inside controls and 18px in navigation; icons in lists and toolbars are not put in tinted squares.
  • Fonts (D33): the library only defines the font stacks (Inter / JetBrains Mono first, then system fonts); the Console loads the fonts, so plugin pages do not bring their own.
  • Content blocks (P2): ContentStack, FormField, KeyValueList (one column in a narrow container), ProgressMeter, Sparkline, Timeline, Disclosure (raw IDs and JSON collapsed by default), CodeText, JsonBlock, MediaPreview, RecordCard (Card + KeyValueList) and LoadingBlock. They complement the components above without repeating them: sections, grids, stat cards and table cards are the P1b components.

The rules live in the components, and tokens and breakpoints are defined once in tokens/tokens.mjs; @zhin.js/console-ui's own styles are held to them by the shared stylelint / ESLint rules (@zhin.js/console-ui/stylelint, @zhin.js/console-ui/eslint), which plugins can enable for their own styles too.

Upgrading from @zhin.js/client/ui ​

@zhin.js/client/ui was deprecated in ADR 0063 P2 (@zhin.js/client 1.3.0) and, after a deprecation period of one minor, removed in P4 (@zhin.js/client 1.4.0): importing it fails the build, and the zk- components, zk- class names and --zk-* variables are gone with it. Migrate as follows:

Old export (@zhin.js/client/ui)New home
usePluginRpc, usePluginData, useRpcResource and their types@zhin.js/client root entry
useLocale, detectLocale, translate, formatClock and their types@zhin.js/client root entry
resolvePluginId, resolveSyncPluginId, resolveAdapterConsolePluginId@zhin.js/client root entry
DeclarativePageView, createDeclarativePage, DataTable and the declarative types@zhin.js/client root entry (DataTable now uses the new table component; column fixed and responsiveStack no longer apply, a narrow container shows cards instead)
Conversation helpers such as ConversationPicker, ConversationLabel, useConversationDirectory@zhin.js/client root entry
zk- components such as Button, Badge, Select, Modal, Card, Tabs, InputThe same or matching components of @zhin.js/console-ui; the @zhin.js/client README lists the property differences (for example Button variant="danger" → variant="destructive-outline" plus ConfirmDialog, Select → SelectField, Modal → Dialog)
PluginPage, PageHeaderNone: the page shell owns the header; hand-written pages use usePageChrome
pluginUiStylesNone: the styles come from @zhin.js/console-ui/styles.css, which the Console loads

Other interfaces removed in ADR 0063 P4 ​

These were deprecated in P1b / P2 and, after a deprecation period of at least one minor, removed in P4 (@zhin.js/client 1.4.0, @zhin.js/console-ui 1.2.0, @zhin.js/console-contract 1.4.0):

RemovedChange
adapterConsoleStyles, conversationPickerStyles of @zhin.js/client (empty strings during the deprecation period)Delete the imports and the <style> elements that inject them; the styles come from @zhin.js/console-ui/styles.css
zk- class names (zk-root, zk-page, zk-card, zk-account-editor-host, …) and --zk-* variablesUse @zhin.js/console-ui components and --console-* tokens; find the adapter page's account editor by [data-adapter-account-editor]
mark of blueprints (definePageBlueprint / DeclarativePageSpec) and comment review specs (defineCommentReviewPage)Delete it; the shell renders the header and there is no letter tile
Button variant="default" of @zhin.js/console-uivariant="soft", or no variant (soft is the default)
Old token aliases of @zhin.js/console-ui: --console-radius-sm/md/lg/xl/2xl, --console-shadow-*, --console-space-page-x/-y, --console-space-section/-stack/-card(-sm), --console-control-height-sm/-lg, --console-border-width, --console-focus-width, --console-duration-fast/-page, --console-text-caption/-code/-body-sm/-section-sm/-title-compact, --radiusUse the new names, listed in the "令牌" (tokens) section of the @zhin.js/console-ui README; the stylelint rule console/no-deprecated-tokens (@zhin.js/console-ui/stylelint) points at each old name in a stylesheet and names its successor

Third-party plugins that are already built bundle the @zhin.js/client they use, so removing @zhin.js/client/ui, the zk- components and mark does not break them; they keep their old look until their authors upgrade the dependencies and rebuild, which is when the table above applies. @zhin.js/console-ui is different: it is a shared singleton provided by the Console, so once the Console moves to 1.2 a button still written as variant="default" loses the soft look (it falls back to the button's base style), and stylesheets that read an old token name such as var(--console-radius-md) no longer get it from the component library and may get no value (unless they give a fallback). Move to the new names now. Rule 2 of zhin plugin check still points out PageHeader / PluginPage imported from @zhin.js/client/ui.

Adapter Console pages ​

Every built-in platform adapter (plugins/adapters/*) ships a pure .ts pages/index/index.ts that declares a zero-bundle Blueprint using defineAdapterPage(adapterKey) from @zhin.js/console-contract (no @zhin.js/client or React dependency required); the server side uses createAdapterConsoleRpc(spec) from @zhin.js/adapter:

ts
// pages/index/index.ts
import { defineAdapterPage, definePage } from '@zhin.js/console-contract';

export const meta = definePage({
  title: 'Telegram',
  icon: 'Send',
  order: 74,
  requiredPermissions: ['telegram:read'],
});

export default defineAdapterPage('telegram');

From the page you can:

  • see the adapter's running endpoints from Host endpoint.list and run endpoint.test for connectivity;
  • read the owning Adapter’s account directory and runtime state from plugin.<pluginId>.status, with sensitive fields masked;
  • manage accounts through endpoint-add / endpoint-update / endpoint-start / endpoint-stop / endpoint-remove / endpoint-replace; Host persistence uses CAS and leaves startup files and .env unchanged;
  • consume LoginAssist tasks from login.list with login.submit / login.cancel (QR code, slider, SMS, device confirmation);
  • render adapter-specific actions from status.actions (for example QQ QR binding and public/private selection).

Permissions are per adapter: page reads need <adapterKey>:read (level read); writes (account changes and custom actions) need <adapterKey>:write, declared at level operate by default so operator can maintain accounts (set writePermissionLevel: 'manage' to keep it with admins). Roles bound to that adapter count too, and endpoint.manage on the adapter also allows account changes. A global owner is unrestricted. An administrator holding endpoint.manage must review and confirm the existing account list before its first migration. Without a persistence management port, runtime.canManage is false or the request explicitly fails as unavailable; there is no configuration-file fallback.

Each mutation supplies the directory’s expectedGeneration and expectedRevision and targets an instanceId; the first migration adds confirmMigration: true only after user confirmation. New and replacement accounts are saved disabled; connection updates reconnect only the target account. Refresh to verify conflicts or unknown commit outcomes rather than automatically retrying. Persistence acknowledgment and asynchronous startup or cleanup completion are separate states.

Keep createAdapterConsoleRpc specs limited to public field metadata. Fields marked env: true or secret: true are masked; env no longer grants file-writing behavior. Editing submits only fields declared mutable by the platform; blank or masked secrets retain their current value. Replacement requires a complete new configuration. extraStatus should expose only a few state values (for example bindState or scanUrl), never logs, chat text or secrets.

Comment review pages ​

Reply-drafting adapters that go "AI drafts → human approves → send" (Bilibili, Juejin) also use pure .ts Blueprints: pages/index/index.ts calls defineCommentReviewPage(spec) from @zhin.js/console-contract and gets the account section, login status, draft cards (edit / send / discard draft) and consistent error and stale-data notices. The spec only describes what differs per platform: platform name and zh/en copy, the resource noun, field mappers for the account and draft resource, plus optional QR login and polling settings. The server provides plugin.<pluginId>.status / edit / send / drop, still implemented per adapter in its own src/console.ts. See the @zhin.js/client README for the full field list.

Saving settings from a page (config:patch) ​

When a page changes a few settings, use config:patch to write exact paths instead of overwriting a whole section with config:set. Everything else in zhin.config.yml, including comments, is kept; the YAML/Config page stays available for advanced users.

ts
const { revision } = await wsManager.getConfigSource();
const result = await wsManager.patchConfig({
  instanceKey: 'typesafe',          // omit to use the Host allowlist
  expectedRevision: revision,
  patches: [
    { op: 'set', path: ['ai', 'decisions', 'skills', 'mode'], value: 'shadow' },
    { op: 'remove', path: ['typesafe', 'timeoutMs'] },
  ],
});
if (result.status === 'saved' && result.restartRequired) showRestartHint(result.message);
if (result.status === 'conflict') showLatest(result.current, result.revision); // never overwrites someone else's change
if (result.status === 'invalid') showErrors(result.errors);

Which paths can be written

CallWritable scope
With instanceKeyThe instance's own block [instanceKey, ...], plus Host sub-paths declared in the plugin schema.json root under x-zhin-config.patchPaths
Without instanceKeyHOST_CONFIG_PATCH_PATHS (exported by @zhin.js/console-protocol; currently ai.trigger.ambient)

Declaring cross-scope ownership in a plugin (the TypeSafe decision provider, for example):

json
{
  "type": "object",
  "x-zhin-config": { "patchPaths": ["ai.decisions"] },
  "properties": { "...": {} }
}

patchPaths may only name Host config paths at least two levels deep (such as ai.decisions). It cannot claim plugin, http, plugins, a whole Host key or another plugin's block. A path outside the scope is rejected and nothing is written.

Rules

  • expectedRevision is required; read it from config:get-source. If the file changed in the meantime the result is status: 'conflict' with the latest revision and the current value at each path; nothing is overwritten silently.
  • Every touched top-level section is validated against its schema before writing. Failures return status: 'invalid' with full paths (e.g. $.ai.trigger.ambient.mode) and nothing is written.
  • On success restartRequired says whether Host config changed: when true the file is saved but the process must restart for it to take effect, and message says so.
  • A successful write publishes config:updated with paths (the paths written) and the new revision.
  • Requires agent.configure (feature.configure when instanceKey targets plugin configuration). At most 32 patches per call and 16 segments per path.
  • Plugin status and actions use plugin RPC (plugin.<PluginId>.status / plugin.<PluginId>.<action>); don't use it to write config.

How it works ​

Console pages follow two paths: Pure Blueprints (90% of plugins) and Heavy-Interaction Static Bundles (10% of plugins, such as Sandbox):

  • Pure Blueprint (.ts): Node evaluates only the pure-data blueprint descriptor, completely skipping esbuild bundling and .bundle.js artifacts. GET /console/api/pages embeds the blueprint JSON directly in the page manifest, and renderConsoleShell (in @zhin.js/pagemanager) renders stat cards, filter forms, action bars, and tables in the browser via createBlueprintPage from @zhin.js/client. Blueprint modules are stripped of types one by one with esbuild transform (no bundling); page meta is parsed with TypeScript in a short-lived worker thread that ends after about 2 seconds idle, so a long-running instance does not keep the TypeScript compiler loaded.
  • Heavy-Interaction Static Assets (.tsx): Only pages/*/index.tsx (such as plugins/adapters/sandbox) uses static .bundle.js mounting or TypeScriptClientBuilder bundling; the Node process never calls import() on browser React code at runtime. Bare imports on ALLOWED_ESM_CANONICAL (react, react-dom, etc.) are rewritten to /esm/<enc>.mjs so the entire Console shares a single React instance.
  • Routes and Shell: The Console shell renderer lives in @zhin.js/pagemanager (packages/console/pagemanager/src/shell/page-renderer.ts) and is wired by packages/im/zhin/src/instance/console/host.ts. GET /console is the page index, GET /console/api/pages returns the page manifest, and other paths match pages and serve the Console shell; no match returns 404, insufficient permission 403.

Next steps ​