You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/25 02:34:50 UTC
(maka) 02/02: feat(tui): add live JavaScript apps with safe replacement and recovery
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit b02749e3b4051f787a221dc72cc6761f3a36d9b4
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Fri Sep 25 10:33:27 2026 +0800
feat(tui): add live JavaScript apps with safe replacement and recovery
Expose ctx.tui presenters, typed builders and change streams. Exercise a Board plugin installed into a running TUI, including persistence, retirement and activation replacement. Revoke stale controls without losing drafts or uncertain writes, subscribe before rereading, and close cancelled stream documents.
Validation: 460 relevant nextest tests pass with default resource weighting; workspace all-targets Clippy, format, Biome and SDK acceptance type checks pass.
Generated-by: Claude Code
Generated-by: Codex
---
crates/cli/tests/fixtures/board-plugin/host.mjs | 227 +++++++++++++++++++
crates/cli/tests/integration/tui.rs | 1 +
crates/cli/tests/integration/tui/board.rs | 216 ++++++++++++++++++
crates/js-runtime/src/plugin/sdk.js | 287 ++++++++++++++++++------
crates/tui/src/apps.rs | 153 ++++++++++++-
crates/tui/src/apps/drafts.rs | 4 +
crates/tui/src/apps/instance.rs | 10 +-
crates/tui/src/apps/io.rs | 89 ++++----
crates/tui/src/apps/region.rs | 8 +-
crates/tui/src/apps/saved.rs | 1 +
crates/tui/src/apps/tree.rs | 5 +-
crates/tui/src/view/form.rs | 3 +-
packages/plugin-sdk/README.md | 12 +
packages/plugin-sdk/README.zh-CN.md | 12 +
packages/plugin-sdk/src/host.ts | 2 +
packages/plugin-sdk/src/terminal-view.ts | 84 +++++++
packages/plugin-sdk/tsconfig.acceptance.json | 1 +
17 files changed, 992 insertions(+), 123 deletions(-)
diff --git a/crates/cli/tests/fixtures/board-plugin/host.mjs b/crates/cli/tests/fixtures/board-plugin/host.mjs
new file mode 100644
index 0000000000..65d039d2e1
--- /dev/null
+++ b/crates/cli/tests/fixtures/board-plugin/host.mjs
@@ -0,0 +1,227 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// A board of cards in three columns, installed into a running Maka whose
+// binary knows nothing about it: the TUI shows it through the terminal app
+// contract alone.
+
+/** @typedef {'todo' | 'doing' | 'done'} Column */
+/** @typedef {{id: string, title: string, column: Column, note: string}} Card */
+
+/** @param {import('../../../../../packages/plugin-sdk/src/host.js').HostContext} ctx */
+export default async function activate(ctx) {
+ const { tui } = ctx;
+ const columns = /** @type {const} */ (['todo', 'doing', 'done']);
+ /** @type {Record<Column, [string, string, string]>} */
+ const titles = {
+ todo: ['To do', '待办', '待辦'],
+ doing: ['Doing', '进行中', '進行中'],
+ done: ['Done', '完成', '完成'],
+ };
+ /** @returns {Promise<{revision: number | null, cards: Card[]}>} */
+ const load = async () => {
+ const record = await ctx.storage.read('cards');
+ const value = /** @type {{cards: Card[]} | null} */ (
+ record?.data.kind === 'present' ? record.data.value : null
+ );
+ return { revision: record?.revision ?? null, cards: value?.cards ?? [] };
+ };
+ const changed = await tui.changes('board-changed');
+ /** Writes the whole board if nobody wrote it since `revision`.
+ * @param {number | null} revision
+ * @param {Card[]} cards
+ */
+ const store = async (revision, cards) => {
+ await ctx.storage.batch([
+ { key: 'cards', expectedRevision: revision, data: { kind: 'present', value: { cards } } },
+ ]);
+ changed();
+ };
+ /** @param {Column} column @param {number} step */
+ const move = (column, step) =>
+ columns[Math.min(2, Math.max(0, columns.indexOf(column) + step))] ?? column;
+ /** A card identity no card on the board has. @param {Card[]} cards */
+ const fresh = (cards) =>
+ `c${Math.max(0, ...cards.map((item) => Number(item.id.slice(1)) || 0)) + 1}`;
+
+ await tui.app(
+ 'board',
+ {
+ async read(route, cx) {
+ const { revision, cards } = await load();
+ const stamp = String(revision ?? 0);
+ const card =
+ route &&
+ typeof route === 'object' &&
+ 'card' in route &&
+ cards.find((item) => item.id === route.card);
+ if (card) {
+ const index = columns.indexOf(card.column);
+ const actions = [
+ tui.action('save', cx.t('Save', '保存', '儲存'), { fields: ['title', 'note'] }),
+ tui.action('delete', cx.t('Delete', '删除', '刪除'), {
+ confirm: {
+ title: cx.t('Delete this card?', '删除这张卡片?', '刪除這張卡片?'),
+ message: cx.t(
+ 'It leaves the board for good.',
+ '它会从看板上永久移除。',
+ '它會從看板上永久移除。',
+ ),
+ destructive: true,
+ },
+ }),
+ ];
+ const buttons = [tui.button('save', 'save', 'primary')];
+ if (index > 0) {
+ actions.push(tui.action('left', cx.t('Move back', '后退一列', '後退一欄')));
+ buttons.push(tui.button('left', 'left'));
+ }
+ if (index < 2) {
+ actions.push(tui.action('right', cx.t('Move on', '前进一列', '前進一欄')));
+ buttons.push(tui.button('right', 'right'));
+ }
+ buttons.push(tui.button('delete', 'delete', 'destructive'));
+ return {
+ title: card.title,
+ revision: stamp,
+ fields: [tui.line('title', card.title, 200), tui.area('note', card.note, 4000)],
+ actions,
+ root: tui.column('root', [
+ tui.text('column', cx.t(...titles[card.column]), 'accent'),
+ tui.stack('form', [
+ tui.input('title', 'title', cx.t('Title', '标题', '標題')),
+ tui.input('note', 'note', cx.t('Note', '备注', '備註')),
+ ]),
+ tui.row('controls', buttons),
+ ]),
+ };
+ }
+ const lanes = columns.map((column) =>
+ tui.column(
+ column,
+ [
+ tui.spans('title', [
+ [cx.t(...titles[column]), 'strong'],
+ [` ${cards.filter((item) => item.column === column).length}`, 'subtle'],
+ ]),
+ ...cards
+ .filter((item) => item.column === column)
+ .map((item) =>
+ tui.link(
+ `card-${item.id}`,
+ item.title,
+ { card: item.id },
+ item.note ? { detail: item.note } : {},
+ ),
+ ),
+ ],
+ 0,
+ ),
+ );
+ return {
+ title: cx.t('Board', '看板', '看板'),
+ revision: stamp,
+ fields: [
+ tui.line('new', '', 200, { placeholder: cx.t('A new card', '新卡片', '新卡片') }),
+ ],
+ actions: [tui.action('add', cx.t('Add', '添加', '新增'), { fields: ['new'] })],
+ root: tui.column('root', [
+ tui.row('lanes', lanes),
+ tui.rule('divider'),
+ tui.row('adding', [
+ tui.input('new', 'new', cx.t('Card', '卡片', '卡片')),
+ tui.button('add', 'add', 'primary'),
+ ]),
+ ]),
+ };
+ },
+ async submit(submission, cx) {
+ const { revision, cards } = await load();
+ if (String(revision ?? 0) !== submission.revision) return { kind: 'conflict' };
+ const route = submission.route;
+ const id = route && typeof route === 'object' && 'card' in route ? route.card : null;
+ switch (submission.action) {
+ case 'add': {
+ const title = String(submission.fields.new ?? '').trim();
+ if (!title)
+ return {
+ kind: 'rejected',
+ message: cx.t('Name the card.', '请填写卡片名称。', '請填寫卡片名稱。'),
+ };
+ await store(revision, [
+ ...cards,
+ { id: fresh(cards), title, column: 'todo', note: '' },
+ ]);
+ return { kind: 'applied', route: null };
+ }
+ case 'save':
+ await store(
+ revision,
+ cards.map((item) =>
+ item.id === id
+ ? {
+ ...item,
+ title: String(submission.fields.title).trim() || item.title,
+ note: String(submission.fields.note),
+ }
+ : item,
+ ),
+ );
+ return { kind: 'applied', route: submission.route };
+ case 'left':
+ case 'right':
+ await store(
+ revision,
+ cards.map((item) =>
+ item.id === id
+ ? { ...item, column: move(item.column, submission.action === 'left' ? -1 : 1) }
+ : item,
+ ),
+ );
+ return { kind: 'applied', route: null };
+ case 'delete':
+ await store(
+ revision,
+ cards.filter((item) => item.id !== id),
+ );
+ return { kind: 'applied', route: null };
+ default:
+ return { kind: 'rejected', message: 'Unknown action' };
+ }
+ },
+ },
+ {
+ title: { fallback: 'Board', translations: { 'zh-CN': '看板', 'zh-TW': '看板' } },
+ context: 'application',
+ icon: { glyph: '▦', ascii: 'B' },
+ changes: 'board-changed',
+ },
+ );
+
+ // Another writer: anything that adds a card through the plugin's API.
+ await ctx.remote.method('add', async (input) => {
+ const { revision, cards } = await load();
+ await store(revision, [
+ ...cards,
+ { id: fresh(cards), title: String(input), column: 'todo', note: '' },
+ ]);
+ return (await load()).cards.length;
+ });
+ await ctx.remote.method('cards', async () => (await load()).cards);
+}
diff --git a/crates/cli/tests/integration/tui.rs b/crates/cli/tests/integration/tui.rs
index e94dfe7ef0..cfacaaa829 100644
--- a/crates/cli/tests/integration/tui.rs
+++ b/crates/cli/tests/integration/tui.rs
@@ -20,6 +20,7 @@
#![cfg(unix)]
mod attachments;
+mod board;
mod branch;
mod changes;
mod connection_test;
diff --git a/crates/cli/tests/integration/tui/board.rs b/crates/cli/tests/integration/tui/board.rs
new file mode 100644
index 0000000000..9a9d8593dd
--- /dev/null
+++ b/crates/cli/tests/integration/tui/board.rs
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_protocol::{
+ Operation,
+ plugin::{RemoteBinding, RemoteRequest, RemoteResult},
+};
+use serde_json::{Value, json};
+
+/// A JavaScript plugin the binary has never heard of, installed while the
+/// TUI runs: its app appears in the sidebar, works like any built-in one,
+/// and redraws when someone else changes its data.
+#[test]
+fn a_javascript_plugin_installed_at_runtime_brings_its_own_app_into_the_running_tui() {
+ let directory = tempfile::tempdir().unwrap();
+ let package = directory.path().join("board-plugin");
+ std::fs::create_dir(&package).unwrap();
+ std::fs::write(
+ package.join("host.mjs"),
+ include_str!("../../fixtures/board-plugin/host.mjs"),
+ )
+ .unwrap();
+ std::fs::write(
+ package.join("maka.extension.json"),
+ json!({"schemaVersion":1, "id":"example.board",
+ "runtime":{"entry":"host.mjs", "sdkVersion":1}})
+ .to_string(),
+ )
+ .unwrap();
+ let mut host = super::super::candidate::CandidateFixture::new(directory.path().join("root"));
+ host.child = Some(
+ Command::new(env!("CARGO_BIN_EXE_maka"))
+ .args(["host", "serve", "--root"])
+ .arg(&host.root)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit())
+ .spawn()
+ .unwrap(),
+ );
+ host.wait_for_registration();
+ let runtime = tokio::runtime::Runtime::new().unwrap();
+ let (client, _listener) = runtime.block_on(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let client = support::model_client(
+ &host.root,
+ &format!("http://{}/v1", listener.local_addr().unwrap()),
+ )
+ .await;
+ client
+ .create_session(
+ maka_protocol::session::decode_session_create_input(&json!({
+ "sessionId":"scratch", "name":"Scratch",
+ "workspace":{"kind":"host_path","path":directory.path()},
+ "modelTarget":{"kind":"default"}
+ }))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ (client, listener)
+ });
+ let mut tui = Pty::spawn(&["--root", host.root.to_str().unwrap()]);
+ tui.resize(170, 40);
+ tui.wait_for("Scratch");
+ assert!(!tui.screen.snapshot().unwrap().screen.contains("Board"));
+
+ runtime.block_on(async {
+ client
+ .request(
+ Operation::PluginPackageInstall,
+ json!({"sourcePath":package}),
+ )
+ .await
+ .unwrap();
+ client
+ .request(
+ Operation::PluginCompositionApply,
+ json!({"operations":[{"type":"insert","rootId":"profile",
+ "entry":{"id":"board","packageId":"example.board"}}]}),
+ )
+ .await
+ .unwrap();
+ });
+ // Nobody tells the TUI: the Host announces the new view by itself.
+ tui.wait_for("Board");
+ tui.click_text("Board");
+ // Empty lanes still share the width, so the first card moves nothing.
+ tui.wait_until(|screen| {
+ screen.contains("To do 0")
+ && !screen.contains("To do 0 Doing")
+ && screen.contains("A new card")
+ });
+ tui.click_page_text("A new card");
+ tui.send(b"\x1b[200~Write the tests\x1b[201~");
+ tui.wait_for("Write the tests");
+ tui.click_page_text("Add");
+ tui.wait_until(|screen| screen.contains("To do 1") && screen.contains("A new card"));
+ tui.click_page_text("Write the tests");
+ tui.wait_for("Move on");
+ tui.click_page_text("Move on");
+ tui.wait_until(|screen| screen.contains("To do 0") && screen.contains("Doing 1"));
+
+ // Another writer adds a card; the open board redraws without a keystroke.
+ let count = runtime.block_on(remote(&client, "add", json!("From elsewhere")));
+ assert_eq!(count, 2);
+ tui.wait_until(|screen| screen.contains("To do 1") && screen.contains("From elsewhere"));
+
+ // Retirement cancels the live changes stream and revokes the open page.
+ runtime.block_on(toggle(&client, true));
+ tui.wait_for("This app is no longer available.");
+ runtime.block_on(toggle(&client, false));
+ tui.wait_until(|screen| {
+ screen.contains("From elsewhere")
+ && screen.contains("Doing 1")
+ && !screen.contains("This app is no longer available.")
+ });
+ // The replacement activation has its own stream and the durable board.
+ assert_eq!(
+ runtime.block_on(remote(&client, "add", json!("After restart"))),
+ 3
+ );
+ tui.wait_until(|screen| screen.contains("To do 2") && screen.contains("After restart"));
+ tui.close_terminal();
+ tui.finish();
+
+ let cards = runtime.block_on(remote(&client, "cards", Value::Null));
+ let placed: Vec<_> = cards
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|card| {
+ (
+ card["title"].as_str().unwrap(),
+ card["column"].as_str().unwrap(),
+ )
+ })
+ .collect();
+ assert_eq!(
+ placed,
+ [
+ ("Write the tests", "doing"),
+ ("From elsewhere", "todo"),
+ ("After restart", "todo"),
+ ]
+ );
+ client.disconnect();
+}
+
+async fn toggle(client: &maka_client::Client, disabled: bool) {
+ client
+ .request(
+ Operation::PluginCompositionApply,
+ json!({"operations":[{"type":"update","entryId":"board","patch":{"disabled":disabled}}]}),
+ )
+ .await
+ .unwrap();
+}
+
+async fn remote(client: &maka_client::Client, method: &str, input: Value) -> Value {
+ let binding = RemoteBinding::Package {
+ package_id: "example.board".into(),
+ method: method.into(),
+ session_id: None,
+ };
+ let RemoteResult::Bound { target, .. } = client
+ .plugin_remote(RemoteRequest::Bind {
+ binding: binding.clone(),
+ })
+ .await
+ .unwrap()
+ else {
+ panic!("bound")
+ };
+ let RemoteResult::Document { document } = client
+ .plugin_remote(RemoteRequest::OpenDocument)
+ .await
+ .unwrap()
+ else {
+ panic!("document")
+ };
+ let result = client
+ .plugin_remote(RemoteRequest::Call {
+ binding,
+ target,
+ document,
+ input,
+ })
+ .await
+ .unwrap();
+ client
+ .plugin_remote(RemoteRequest::CloseDocument { document })
+ .await
+ .unwrap();
+ let RemoteResult::Value { value } = result else {
+ panic!("value")
+ };
+ value
+}
diff --git a/crates/js-runtime/src/plugin/sdk.js b/crates/js-runtime/src/plugin/sdk.js
index 568061431c..42060614aa 100644
--- a/crates/js-runtime/src/plugin/sdk.js
+++ b/crates/js-runtime/src/plugin/sdk.js
@@ -365,10 +365,232 @@
await host('authorization.close', { handle });
}
};
+
+ /** Terminal apps: a Remote method that answers terminal view requests,
+ * with builders for the view tree the terminal renders. */
+ const terminal = (remote) => {
+ const pick = (locale, en, zhCN, zhTW) => {
+ const language = String(locale ?? '').toLowerCase();
+ if (language === 'zh-tw' || language === 'zh-hant') return zhTW ?? zhCN ?? en;
+ if (language.startsWith('zh')) return zhCN ?? en;
+ return en;
+ };
+ const view = ({ title, revision, fields = [], actions = [], root }) => ({
+ version: 4,
+ title,
+ revision: String(revision),
+ fields,
+ actions,
+ root,
+ });
+ const item = (key, title, target, extra = {}) => ({
+ kind: 'item',
+ key,
+ title,
+ target,
+ ...extra,
+ });
+ const text = (key, value, tone = 'normal') => ({
+ kind: 'text',
+ key,
+ spans: [{ text: String(value), tone }],
+ });
+ return Object.freeze({
+ /** Serves `handlers` as the terminal view `descriptor` describes. */
+ app: (name, handlers, descriptor, options = {}) =>
+ remote.method(
+ name,
+ async (input, caller) => {
+ const locale = input?.locale ?? 'en';
+ const cx = Object.freeze({
+ locale,
+ caller,
+ t: (en, zhCN, zhTW) => pick(locale, en, zhCN, zhTW),
+ });
+ switch (input?.kind) {
+ case 'read': {
+ const result = await handlers.read(input.route ?? null, cx);
+ return { kind: 'view', view: result?.version ? result : view(result) };
+ }
+ case 'submit': {
+ const { route = null, revision, action, fields = {}, grant = null } = input;
+ return await handlers.submit({ route, revision, action, fields, grant }, cx);
+ }
+ case 'recover': {
+ if (typeof handlers.recover !== 'function') {
+ throw Object.assign(new Error('This view declares no recovery'), {
+ code: 'invalid',
+ });
+ }
+ return await handlers.recover(input.route ?? null, cx);
+ }
+ default:
+ throw Object.assign(new Error('Unknown terminal request'), { code: 'invalid' });
+ }
+ },
+ { ...options, terminalView: { version: 4, ...descriptor } },
+ ),
+ /** A changes stream for a descriptor's `changes`; calling the
+ * returned function tells every open view it is stale. */
+ changes: async (name) => {
+ const waiting = new Set();
+ const registration = await remote.stream(name, () => {
+ let pending = 0;
+ let wake;
+ const listener = () => {
+ pending += 1;
+ wake?.();
+ };
+ waiting.add(listener);
+ let stopped = false;
+ return {
+ async next() {
+ while (!stopped && pending === 0) {
+ await new Promise((resolve) => {
+ wake = resolve;
+ });
+ wake = undefined;
+ }
+ if (stopped) return { done: true, value: undefined };
+ pending = 0;
+ return { done: false, value: null };
+ },
+ cancel() {
+ stopped = true;
+ waiting.delete(listener);
+ wake?.();
+ },
+ close() {
+ waiting.delete(listener);
+ },
+ };
+ });
+ const notify = () => {
+ for (const listener of waiting) listener();
+ };
+ notify.close = () => registration.close();
+ return notify;
+ },
+ view,
+ column: (key, children, gap = 1) => ({ kind: 'column', key, gap, children }),
+ stack: (key, children) => ({ kind: 'column', key, gap: 0, children }),
+ row: (key, children, gap = 2) => ({ kind: 'row', key, gap, children }),
+ text,
+ spans: (key, spans) => ({
+ kind: 'text',
+ key,
+ spans: spans.map(([value, tone = 'normal']) => ({ text: String(value), tone })),
+ }),
+ heading: (key, value) => text(key, value, 'strong'),
+ rule: (key) => ({ kind: 'rule', key }),
+ scroll: (key, rows, child) => ({ kind: 'scroll', key, rows, child }),
+ split: (key, ratio, left, right) => ({ kind: 'split', key, ratio, left, right }),
+ tabs: (key, current, tabs) => ({ kind: 'tabs', key, current, tabs }),
+ link: (key, title, route, extra) => item(key, title, { kind: 'route', route }, extra),
+ act: (key, title, action, extra) => item(key, title, { kind: 'action', action }, extra),
+ open: (key, title, session, extra) => item(key, title, { kind: 'session', session }, extra),
+ button: (key, action, role = 'normal', label) => ({
+ kind: 'button',
+ key,
+ action,
+ role,
+ ...(label === undefined ? {} : { label }),
+ }),
+ input: (key, field, label = '') => ({ kind: 'input', key, field, label }),
+ progress: (key, value, max, label = '') => ({ kind: 'progress', key, value, max, label }),
+ markdown: (key, value) => ({ kind: 'markdown', key, text: String(value) }),
+ code: (key, value) => ({ kind: 'code', key, text: String(value) }),
+ slot: (key, name, context = null) => ({ kind: 'slot', key, name, context }),
+ action: (id, label, extra = {}) => ({ id, label, ...extra }),
+ toggle: (id, value) => ({ id, control: { kind: 'toggle', value: Boolean(value) } }),
+ line: (id, value = '', maxBytes = 256, extra = {}) => ({
+ id,
+ control: { kind: 'text', value: String(value), max_bytes: maxBytes, ...extra },
+ }),
+ area: (id, value = '', maxBytes = 8192, extra = {}) => ({
+ id,
+ control: {
+ kind: 'text',
+ value: String(value),
+ max_bytes: maxBytes,
+ multiline: true,
+ ...extra,
+ },
+ }),
+ choice: (id, value, options) => ({
+ id,
+ control: {
+ kind: 'choice',
+ value,
+ options: options.map(([option, label]) => ({ value: option, label })),
+ },
+ }),
+ });
+ };
return Object.freeze({
async activate(identity, config) {
if (phase !== 'new') throw new Error('Plugin already initialized');
phase = 'loading';
+ const remote = Object.freeze({
+ method: (name, invoke, options) =>
+ register('remote_method', { ...options, name }, (input, call) =>
+ remoteResult(() => invoke(input, call)),
+ ),
+ stream: (name, open, options) =>
+ register('remote_stream', { ...options, name }, (input, call) =>
+ remoteResult(async () => {
+ if (streams.size >= 32) throw new Error('Client stream capacity exceeded');
+ const handle = 'stream-' + ++streamSequence;
+ let stopped = false;
+ let stop;
+ const cancelled = new Promise((resolve) => {
+ stop = resolve;
+ });
+ const stream = {
+ value: undefined,
+ pending: undefined,
+ closing: undefined,
+ cancelledValue: false,
+ cancel() {
+ stopped = true;
+ stop();
+ if (stream.value && !stream.cancelledValue) {
+ stream.cancelledValue = true;
+ stream.value.cancel();
+ }
+ },
+ };
+ const streamSignal = Object.freeze({
+ get aborted() {
+ return stopped || call.signal.aborted;
+ },
+ wait: () => Promise.race([cancelled, call.signal.wait()]),
+ throwIfAborted() {
+ if (this.aborted) throw new Error('Client stream cancelled');
+ },
+ });
+ streams.set(handle, stream);
+ invocations.set(handle, stream.cancel);
+ try {
+ stream.value = await open(input, Object.freeze({ ...call, signal: streamSignal }));
+ if (
+ !stream.value ||
+ typeof stream.value.next !== 'function' ||
+ typeof stream.value.cancel !== 'function' ||
+ typeof stream.value.close !== 'function'
+ ) {
+ throw new Error('Invalid Client stream');
+ }
+ if (stopped) stream.cancel();
+ return handle;
+ } catch (error) {
+ streams.delete(handle);
+ invocations.delete(handle);
+ throw error;
+ }
+ }),
+ ),
+ });
const context = Object.freeze({
identity: Object.freeze(identity),
signal,
@@ -460,69 +682,8 @@
});
},
}),
- remote: Object.freeze({
- method: (name, invoke, options) =>
- register('remote_method', { ...options, name }, (input, call) =>
- remoteResult(() => invoke(input, call)),
- ),
- stream: (name, open, options) =>
- register('remote_stream', { ...options, name }, (input, call) =>
- remoteResult(async () => {
- if (streams.size >= 32) throw new Error('Client stream capacity exceeded');
- const handle = 'stream-' + ++streamSequence;
- let stopped = false;
- let stop;
- const cancelled = new Promise((resolve) => {
- stop = resolve;
- });
- const stream = {
- value: undefined,
- pending: undefined,
- closing: undefined,
- cancelledValue: false,
- cancel() {
- stopped = true;
- stop();
- if (stream.value && !stream.cancelledValue) {
- stream.cancelledValue = true;
- stream.value.cancel();
- }
- },
- };
- const streamSignal = Object.freeze({
- get aborted() {
- return stopped || call.signal.aborted;
- },
- wait: () => Promise.race([cancelled, call.signal.wait()]),
- throwIfAborted() {
- if (this.aborted) throw new Error('Client stream cancelled');
- },
- });
- streams.set(handle, stream);
- invocations.set(handle, stream.cancel);
- try {
- stream.value = await open(
- input,
- Object.freeze({ ...call, signal: streamSignal }),
- );
- if (
- !stream.value ||
- typeof stream.value.next !== 'function' ||
- typeof stream.value.cancel !== 'function' ||
- typeof stream.value.close !== 'function'
- ) {
- throw new Error('Invalid Client stream');
- }
- if (stopped) stream.cancel();
- return handle;
- } catch (error) {
- streams.delete(handle);
- invocations.delete(handle);
- throw error;
- }
- }),
- ),
- }),
+ remote,
+ tui: terminal(remote),
prompt: Object.freeze({
section: (definition) => {
const { text: value, ...metadata } = definition;
diff --git a/crates/tui/src/apps.rs b/crates/tui/src/apps.rs
index 7c45bfd778..18e4084336 100644
--- a/crates/tui/src/apps.rs
+++ b/crates/tui/src/apps.rs
@@ -343,28 +343,53 @@ impl Apps {
fn bind(&mut self) {
let locale = self.locale.clone();
for (key, instance) in &mut self.instances {
- let Some(entry) = self.directory.iter().find(|entry| key.serves(entry)) else {
+ let entry = self.directory.iter().find(|entry| key.serves(entry));
+ let changed = instance.live.is_some()
+ && instance.live.as_ref() != entry.map(|entry| &entry.target);
+ if changed {
+ instance.disconnect();
+ if self
+ .consent
+ .as_ref()
+ .is_some_and(|(holder, _)| holder == key)
+ {
+ self.consent = None;
+ }
+ if self
+ .confirming
+ .as_ref()
+ .is_some_and(|(holder, _)| holder == key)
+ {
+ self.confirming = None;
+ }
+ }
+ let Some(entry) = entry else {
+ if instance.view.is_some() && !instance.keeps() {
+ instance.message = Some(Notice::Local("extensions-unavailable"));
+ }
continue;
};
match &instance.entry {
None => {
instance.entry = Some(entry.clone());
+ instance.live = Some(entry.target.clone());
instance.read(&locale);
}
// A fresh registration of the same entry serves a clean view;
// a kept one resumes only on an explicit request.
Some(current)
- if current.target.entry_id == entry.target.entry_id
- && !instance.keeps()
- && instance.idle() =>
+ if current.target.entry_id == entry.target.entry_id || !instance.keeps() =>
{
- let fresh = current.target != entry.target;
- instance.entry = Some(entry.clone());
- if fresh || instance.stale {
- instance.read(&locale);
+ let fresh = instance.live.is_none() || current.target != entry.target;
+ instance.live = Some(entry.target.clone());
+ if !instance.keeps() && instance.idle() {
+ instance.entry = Some(entry.clone());
+ if fresh || instance.stale {
+ instance.read(&locale);
+ }
}
}
- _ => {}
+ _ => instance.message = Some(Notice::Local("extensions-unavailable")),
}
}
// New entries may fill slots of views already open.
@@ -769,6 +794,7 @@ impl App {
&& (!instance.blocked || instance.unresolved.is_some())
&& self.app_visible(key)
&& connected
+ && instance.live.is_some()
}
_ => false,
};
@@ -788,6 +814,15 @@ impl App {
if !connected || !self.app_visible(key) {
return false;
}
+ if instance.live.is_none()
+ && apps.loaded
+ && !matches!(
+ command,
+ Command::Discard | Command::ConfirmDiscard | Command::CancelDiscard
+ )
+ {
+ return false;
+ }
match command {
Command::ResumeDraft => {
instance.blocked
@@ -868,6 +903,9 @@ impl App {
Message::Instance(key, command) => (key, command),
};
let apps = &mut self.apps;
+ let replacement = matches!(command, Command::Discard | Command::ConfirmDiscard)
+ .then(|| apps.entry(&key).cloned())
+ .flatten();
let instance = apps.instances.get_mut(&key)?;
instance.applied = None;
if matches!(
@@ -1003,6 +1041,8 @@ impl App {
instance.editors.clear();
instance.history.clear();
instance.route = instance.origin.clone();
+ instance.live = replacement.as_ref().map(|entry| entry.target.clone());
+ instance.entry = replacement;
instance.arrive();
instance.read(&locale);
}
@@ -1018,13 +1058,14 @@ impl App {
self.apps
.instances
.iter()
- .filter(|(key, _)| self.app_visible(key))
+ .filter(|(key, instance)| instance.live.is_some() && self.app_visible(key))
.filter_map(|(key, instance)| {
let entry = instance.entry.as_ref()?;
Some(io::Watch {
package: entry.package_id.clone(),
method: entry.descriptor.changes.clone()?,
session: key.session.clone(),
+ activation: instance.live.as_ref()?.activation.clone(),
})
})
.collect()
@@ -1069,7 +1110,11 @@ impl App {
let Some(entry) = &instance.entry else {
continue;
};
- if entry.package_id != watch.package
+ if instance
+ .live
+ .as_ref()
+ .is_none_or(|target| target.activation != watch.activation)
+ || entry.package_id != watch.package
|| entry.descriptor.changes.as_deref() != Some(watch.method.as_str())
|| key.session != watch.session
{
@@ -1685,6 +1730,77 @@ pub(crate) mod tests {
assert!(next(&mut app).is_none());
}
+ #[test]
+ fn retirement_revokes_the_open_view_and_preserves_drafts_for_explicit_recovery() {
+ for dirty in [false, true] {
+ let mut app = app();
+ instance_mut(&mut app)
+ .entry
+ .as_mut()
+ .unwrap()
+ .descriptor
+ .changes = Some("changes".into());
+ if dirty {
+ app.apps_action(command(Command::View(Intent::Toggle("enabled".into()))));
+ }
+ assert_eq!(app.apps_watches().len(), 1);
+ app.apps.directory.clear();
+ app.apps.bind();
+ app.apps_action(save());
+ assert!(
+ app.apps_requests().is_empty(),
+ "retired controls cannot submit"
+ );
+ assert!(
+ app.apps_watches().is_empty(),
+ "retired subscriptions must close"
+ );
+ assert!(!app.apps_enabled(&save()));
+ assert_eq!(instance(&app).drafts["enabled"], json!(!dirty));
+ if dirty {
+ assert_eq!(app.apps.checkpoints("root").len(), 1);
+ assert!(!app.apps_enabled(&command(Command::ResumeDraft)));
+ } else {
+ assert!(draw(&mut app, 100, 30).contains("This app is no longer available."));
+ }
+ let replacement = projection();
+ app.apps.directory.push(replacement.clone());
+ app.apps.bind();
+ if dirty {
+ assert!(
+ app.apps_requests().is_empty(),
+ "replacement must not discard a draft"
+ );
+ assert!(!app.apps_enabled(&save()));
+ assert!(app.apps_enabled(&command(Command::ResumeDraft)));
+ assert_eq!(instance(&app).drafts["enabled"], json!(false));
+ } else {
+ let request = next(&mut app).unwrap();
+ assert!(
+ matches!(&request.work, Work::Call { entry, input: Input::Read { .. } }
+ if entry.target == replacement.target)
+ );
+ app.apps_complete(request, Ok(Output::Reply(Reply::View { view: form() })));
+ assert!(app.apps_enabled(&save()));
+ assert!(!draw(&mut app, 100, 30).contains("This app is no longer available."));
+ }
+ }
+ let mut app = app();
+ app.apps_action(command(Command::View(Intent::Toggle("enabled".into()))));
+ let mut replacement = projection();
+ replacement.target.entry_id = "another-owner".into();
+ app.apps.directory = vec![replacement.clone()];
+ app.apps.bind();
+ assert!(!app.apps_enabled(&command(Command::ResumeDraft)));
+ assert_eq!(app.apps.checkpoints("root").len(), 1);
+ app.apps_action(command(Command::Discard));
+ let request = next(&mut app).unwrap();
+ assert!(
+ matches!(&request.work, Work::Call { entry, input: Input::Read { .. } }
+ if entry.target == replacement.target)
+ );
+ }
+
#[test]
fn disconnect_revokes_controls_preserves_drafts_and_tiny_layout_has_no_stale_clicks() {
let mut app = app();
@@ -2164,8 +2280,23 @@ pub(crate) mod tests {
package: "example.notes".into(),
method: "notes-changed".into(),
session: Some("session".into()),
+ activation: instance(&app)
+ .entry
+ .as_ref()
+ .unwrap()
+ .target
+ .activation
+ .clone(),
};
assert_eq!(app.apps_watches(), [watch.clone()].into());
+ app.apps_changed(&io::Watch {
+ activation: uuid::Uuid::new_v4().to_string(),
+ ..watch.clone()
+ });
+ assert!(
+ next(&mut app).is_none(),
+ "late changes cannot refresh a replacement"
+ );
app.apps_changed(&watch);
let read = next(&mut app).expect("an untouched view reads again");
app.apps_complete(read, Ok(Output::Reply(Reply::View { view: form() })));
diff --git a/crates/tui/src/apps/drafts.rs b/crates/tui/src/apps/drafts.rs
index 01ed7d596e..a007a8e072 100644
--- a/crates/tui/src/apps/drafts.rs
+++ b/crates/tui/src/apps/drafts.rs
@@ -263,6 +263,10 @@ mod tests {
app
}
fn reload(app: &mut App, view: View) {
+ // The shell discovers the current owner before offering Resume.
+ if !app.apps.loaded {
+ assert!(next(app).is_none());
+ }
app.apps_action(command(Command::ResumeDraft));
let request = next(app).unwrap();
assert!(!request.needs_checkpoint());
diff --git a/crates/tui/src/apps/instance.rs b/crates/tui/src/apps/instance.rs
index c48498fce6..cf95ae4c9d 100644
--- a/crates/tui/src/apps/instance.rs
+++ b/crates/tui/src/apps/instance.rs
@@ -83,6 +83,9 @@ pub struct Instance {
/// The binding this instance reads through; none until the directory
/// names the entry that serves its key.
pub(super) entry: Option<TerminalViewProjection>,
+ /// The directory still serves this owner. A retired entry remains only
+ /// as provenance for preserved drafts and uncertain submissions.
+ pub(super) live: Option<maka_plugins::remote::Target>,
/// Where the view starts: null for a page, a slot's context for a filler.
pub(super) origin: Value,
pub(super) route: Value,
@@ -115,6 +118,7 @@ pub struct Instance {
impl Instance {
pub(super) fn new(entry: Option<TerminalViewProjection>, origin: Value) -> Self {
let mut instance = Self {
+ live: entry.as_ref().map(|entry| entry.target.clone()),
entry,
route: origin.clone(),
origin,
@@ -152,6 +156,9 @@ impl Instance {
}
}
pub(super) fn read(&mut self, locale: &str) {
+ if self.live.is_none() {
+ return;
+ }
self.stale = false;
self.pending = self.entry.clone().map(|entry| Work::Call {
entry: Box::new(entry),
@@ -192,7 +199,7 @@ impl Instance {
let Some(view) = &self.view else {
return false;
};
- if self.blocked || self.review.is_some() {
+ if self.live.is_none() || self.blocked || self.review.is_some() {
return false;
}
match intent {
@@ -315,6 +322,7 @@ impl Instance {
}
/// Revokes every operation on the old registration but keeps drafts.
pub(super) fn disconnect(&mut self) {
+ self.live = None;
self.saving = false;
self.unrecorded = false;
self.confirm_discard = false;
diff --git a/crates/tui/src/apps/io.rs b/crates/tui/src/apps/io.rs
index d85466cb53..254afb55e7 100644
--- a/crates/tui/src/apps/io.rs
+++ b/crates/tui/src/apps/io.rs
@@ -203,6 +203,8 @@ pub struct Watch {
pub package: String,
pub method: String,
pub session: Option<String>,
+ /// Replacing a plugin restarts its stream even when its method name stays.
+ pub activation: String,
}
pub enum Change {
@@ -265,7 +267,7 @@ async fn follow(
method: watch.method.clone(),
session_id: watch.session.clone(),
};
- let opened = async {
+ let bound = async {
let RemoteResult::Bound {
target,
handler: RemoteKind::Stream,
@@ -278,59 +280,64 @@ async fn follow(
else {
return None;
};
- let RemoteResult::Document { document } = client
- .plugin_remote(RemoteRequest::OpenDocument)
- .await
- .ok()?
- else {
- return None;
- };
- match client
- .plugin_remote(RemoteRequest::Open {
- binding: binding.clone(),
- target,
- document,
- input: serde_json::Value::Null,
- })
- .await
- {
- Ok(RemoteResult::Opened { stream }) => Some((document, Some(stream))),
- _ => Some((document, None)),
- }
+ (target.activation == watch.activation).then_some(target)
};
- let opened = tokio::select! {
+ let target = tokio::select! {
_ = &mut stopped => return,
- opened = opened => opened,
+ target = bound => target,
};
- let stopped_early = if let Some((document, Some(stream))) = opened {
- let stopped_early = loop {
- let next = tokio::select! {
- _ = &mut stopped => break true,
- next = client.plugin_remote(RemoteRequest::Next { document, stream }) => next,
+ // Once a document is allocated, retain its identity through cancellation
+ // so a pending Open/Next cannot strand Host resources.
+ let document = if target.is_some() {
+ match client.plugin_remote(RemoteRequest::OpenDocument).await {
+ Ok(RemoteResult::Document { document }) => Some(document),
+ _ => None,
+ }
+ } else {
+ None
+ };
+ let stopped_early = if let (Some(target), Some(document)) = (target, document) {
+ let observe = async {
+ let Ok(RemoteResult::Opened { stream }) = client
+ .plugin_remote(RemoteRequest::Open {
+ binding,
+ target,
+ document,
+ input: serde_json::Value::Null,
+ })
+ .await
+ else {
+ return false;
};
- match next {
- Ok(RemoteResult::Item { .. }) => {
- if changes.send(Change::Stale(watch.clone())).is_err() {
- break true;
+ // Subscribe before the authoritative reread: a write between the
+ // first rendered view and this Open must not be missed forever.
+ if changes.send(Change::Stale(watch.clone())).is_err() {
+ return true;
+ }
+ loop {
+ match client
+ .plugin_remote(RemoteRequest::Next { document, stream })
+ .await
+ {
+ Ok(RemoteResult::Item { .. }) => {
+ if changes.send(Change::Stale(watch.clone())).is_err() {
+ break true;
+ }
}
+ Ok(RemoteResult::Pending) => {}
+ _ => break false,
}
- Ok(RemoteResult::Pending) => {}
- _ => break false,
}
};
- let _ = client
- .plugin_remote(RemoteRequest::Close { document, stream })
- .await;
+ let stopped_early = tokio::select! {
+ _ = &mut stopped => true,
+ ended = observe => ended,
+ };
let _ = client
.plugin_remote(RemoteRequest::CloseDocument { document })
.await;
stopped_early
} else {
- if let Some((document, None)) = opened {
- let _ = client
- .plugin_remote(RemoteRequest::CloseDocument { document })
- .await;
- }
false
};
if stopped_early {
diff --git a/crates/tui/src/apps/region.rs b/crates/tui/src/apps/region.rs
index 57b0386cde..5a3f5e8ddc 100644
--- a/crates/tui/src/apps/region.rs
+++ b/crates/tui/src/apps/region.rs
@@ -95,9 +95,11 @@ pub(super) fn input<M: Clone>(
.is_some_and(|field| field.enabled)
};
let editable = |apps: &Apps, well: &Well| {
- apps.instances
- .get(&well.key)
- .is_some_and(|instance| (instance.idle() || instance.refreshing()) && !instance.blocked)
+ apps.instances.get(&well.key).is_some_and(|instance| {
+ instance.live.is_some()
+ && (instance.idle() || instance.refreshing())
+ && !instance.blocked
+ })
};
if let Event::Mouse(mouse) = event {
let well = wells.iter().find(|well| {
diff --git a/crates/tui/src/apps/saved.rs b/crates/tui/src/apps/saved.rs
index 1eed3258f7..50c1d92284 100644
--- a/crates/tui/src/apps/saved.rs
+++ b/crates/tui/src/apps/saved.rs
@@ -214,6 +214,7 @@ impl Instance {
editor.restore_cursor(cursor)?;
}
instance.unresolved = checkpoint.pending;
+ instance.live = None;
instance.blocked = true;
instance.message = Some(Notice::Local(if instance.unresolved.is_some() {
"extensions-unknown"
diff --git a/crates/tui/src/apps/tree.rs b/crates/tui/src/apps/tree.rs
index 442e1c5ef2..492ca7b68d 100644
--- a/crates/tui/src/apps/tree.rs
+++ b/crates/tui/src/apps/tree.rs
@@ -371,7 +371,7 @@ impl<M> Builder<'_, M> {
/// Children keep their natural widths when the row holds them all;
/// otherwise buttons keep theirs and everything else shares the rest
- /// equally. Fields, bars and splits always stretch.
+ /// equally. Fields, bars, splits and columns (lanes) always stretch.
fn row(
&mut self,
key: String,
@@ -634,7 +634,8 @@ impl<M> Builder<'_, M> {
fn stretchy(node: &wire::Node) -> bool {
matches!(
node,
- wire::Node::Input { .. }
+ wire::Node::Column { .. }
+ | wire::Node::Input { .. }
| wire::Node::Progress { .. }
| wire::Node::Split { .. }
| wire::Node::Scroll { .. }
diff --git a/crates/tui/src/view/form.rs b/crates/tui/src/view/form.rs
index cc1945f2e4..333bc6cc35 100644
--- a/crates/tui/src/view/form.rs
+++ b/crates/tui/src/view/form.rs
@@ -31,7 +31,7 @@ pub(crate) fn label_width(labels: impl IntoIterator<Item = usize>, terminal: u16
}
/// One row: its label, then the editor (masked for secrets), or a
-/// placeholder while the field is empty and unfocused.
+/// placeholder while the field is empty, focused or not, until typing.
pub(crate) struct Row<'a> {
pub label: &'a str,
pub focused: bool,
@@ -71,7 +71,6 @@ pub(crate) fn draw(
}
if let Some(placeholder) = row.placeholder
&& editor.text().is_empty()
- && !row.focused
{
frame.render_widget(
Paragraph::new(placeholder).style(Style::default().fg(colors.subtle)),
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index b35387f16d..14e9ed15a0 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -150,6 +150,18 @@ Native endpoints accepting caller-supplied Host paths declare `Endpoint::requiri
`restoreRoot(operationId)` recovers a root created by this package/scope under current workspace and source ceilings, independently of its original model. Creation provenance does not make an ordinary root exclusively managed. `restoreChild` requires the original child creation request. Neither creates anything; absence does not exclude a concurrent creation. `configure` advances the Session revision on every committed choice, including identical values, fencing older configuration CASes [...]
+## Terminal apps
+
+Host plugins use `ctx.tui.app(name, { read, submit, recover? }, descriptor)` to contribute a TUI application without a Desktop bundle or a new Maka binary. The descriptor selects `page`, `panel`, `status`, `settings`, or a named `slot`; its `context` is `application` or `session`. A view can embed `tui.slot(...)` to compose contributions from other plugins.
+
+`read(route, cx)` returns a View v4 body built with `ctx.tui` (columns, rows, splits, tabs, text, Markdown, controls and fields). The SDK adds the version. Stable sibling keys preserve focus and editing state; `cx.t(en, zhCN, zhTW)` selects the reader's language. The shell owns layout, local typing, scrolling, confirmation and draft recovery. Plugins use semantic tones and never emit terminal escapes.
+
+`submit({ route, revision, action, fields, grant }, cx)` applies an explicit user action and returns `applied`, `conflict`, `rejected`, or `consent`. Use the revision for storage CAS and enforce domain authority in the Host. Declare an action's `recovery` route only when `recover(route, cx)` can look up its durable outcome; the shell never blindly replays an uncertain write.
+
+For live updates, `const changed = await ctx.tui.changes('changed')` registers a stream. Set `changes: 'changed'` on the descriptor and call `changed()` after committing data. Invalidation is coalesced; the shell rereads clean views and preserves edited drafts. Subscriptions and controls retire with their registration.
+
+The [Board example](../../crates/cli/tests/fixtures/board-plugin/host.mjs) includes three columns, nested card editing, storage CAS and live refresh. Its [PTY test](../../crates/cli/tests/integration/tui/board.rs) installs it while the TUI is running, interacts with it and checks the persisted domain data.
+
## Usage
`session.inspector.overview` receives the viewed Host's canonical `sessionId` and `locale`. It augments the overview without replacing native trace/context controls. Bind Remote reads to that Session; slot props alone grant no execution permission.
diff --git a/packages/plugin-sdk/README.zh-CN.md b/packages/plugin-sdk/README.zh-CN.md
index 53287bc6d9..aba5377d14 100644
--- a/packages/plugin-sdk/README.zh-CN.md
+++ b/packages/plugin-sdk/README.zh-CN.md
@@ -154,6 +154,18 @@ Remote 回调可以抛出携带 `RemoteFailure.code` 的 `Error`。`outcome_unkn
`restoreRoot(operationId)` 按当前工作区和来源上限恢复本包/作用域创建的根会话,不依赖原模型;创建记录不会使普通根会话变成独占托管会话。`restoreChild` 要求原始子会话创建请求。两者均不创建资源;不存在的观察不能排除并发创建。`configure` 每次成功选择都会推进 Session revision,包括相同值,以阻止较早的配置 CAS 覆盖它,不修改事件历史。
+## 终端应用
+
+Host 插件通过 `ctx.tui.app(name, { read, submit, recover? }, descriptor)` 贡献 TUI 应用,无需 Desktop bundle 或重新编译 Maka。descriptor 选择 `page`、`panel`、`status`、`settings` 或命名 `slot`,上下文为 `application` 或 `session`;视图通过 `tui.slot(...)` 组合其他插件的贡献。
+
+`read(route, cx)` 返回用 `ctx.tui` 构造的 View v4 内容,包括列、行、分栏、标签、文本、Markdown、控件和字段,SDK 自动添加版本。稳定的同级 key 保留焦点与编辑状态;`cx.t(en, zhCN, zhTW)` 选择当前语言。外壳负责布局、本地输入、滚动、确认与草稿恢复;插件使用语义颜色,不输出终端转义序列。
+
+`submit({ route, revision, action, fields, grant }, cx)` 执行明确的用户操作,返回 `applied`、`conflict`、`rejected` 或 `consent`。使用 revision 做存储 CAS,并在 Host 检查领域权限。只有 `recover(route, cx)` 能查询持久结果时才声明 action 的 `recovery` 路由;外壳不会盲目重放结果未知的写入。
+
+实时刷新使用 `const changed = await ctx.tui.changes('changed')` 注册流,在 descriptor 设置 `changes: 'changed'`,数据提交后调用 `changed()`。失效通知会合并,外壳重新读取干净视图并保留已有草稿;订阅与控件随注册退休。
+
+[Board 示例](../../crates/cli/tests/fixtures/board-plugin/host.mjs) 展示三列看板、卡片详情编辑、存储 CAS 与实时刷新。[PTY 测试](../../crates/cli/tests/integration/tui/board.rs) 在 TUI 运行期间安装它、执行交互并读回持久领域数据。
+
## 用量
`session.inspector.overview` 接收当前 Host 的规范 `sessionId` 与 `locale`,补充概览而不替换原生轨迹/上下文控件。Remote 读取应绑定此 Session;插槽参数本身不授予执行权限。
diff --git a/packages/plugin-sdk/src/host.ts b/packages/plugin-sdk/src/host.ts
index 7d6f60263d..714436c75a 100644
--- a/packages/plugin-sdk/src/host.ts
+++ b/packages/plugin-sdk/src/host.ts
@@ -344,6 +344,8 @@ export interface HostContext {
options?: RemoteOptions,
): Promise<Registration>;
};
+ /** Terminal apps: views a plugin presents in the Maka TUI. */
+ readonly tui: import('./terminal-view.js').TerminalApps;
readonly identity: Identity;
readonly signal: Cancellation;
readonly tools: {
diff --git a/packages/plugin-sdk/src/terminal-view.ts b/packages/plugin-sdk/src/terminal-view.ts
index 75a916bed1..25c5b43623 100644
--- a/packages/plugin-sdk/src/terminal-view.ts
+++ b/packages/plugin-sdk/src/terminal-view.ts
@@ -185,3 +185,87 @@ export type TerminalReply =
| { kind: 'unrecorded' }
/** An inert proposal; only the user's explicit approval in the shell grants it. */
| { kind: 'consent'; request: AuthorizationRequest };
+
+/** Who is reading a terminal view, and in which language. */
+export interface TerminalContext {
+ readonly locale: string;
+ readonly caller: import('./host.js').RemoteCaller;
+ /** Picks the reader's text from English, Simplified and Traditional Chinese. */
+ t(en: string, zhCN?: string, zhTW?: string): string;
+}
+export interface TerminalSubmission {
+ readonly route: Json;
+ readonly revision: string;
+ readonly action: string;
+ readonly fields: Readonly<Record<string, boolean | string>>;
+ /** A consent grant, present after the shell asked the user to approve. */
+ readonly grant: string | null;
+}
+/** A view without its version; the SDK adds the one it speaks. */
+export type TerminalViewBody = Omit<TerminalViewTree, 'version'> & { version?: 4 };
+export interface TerminalAppHandlers {
+ read(route: Json, cx: TerminalContext): Awaitable<TerminalViewBody>;
+ submit(submission: TerminalSubmission, cx: TerminalContext): Awaitable<TerminalReply>;
+ /** Only needed when actions declare recovery routes. */
+ recover?(route: Json, cx: TerminalContext): Awaitable<TerminalReply>;
+}
+type Awaitable<T> = T | Promise<T>;
+type Extra<T> = Partial<Omit<T, 'kind' | 'key'>>;
+type ItemExtra = Extra<Extract<TerminalNode, { kind: 'item' }>>;
+
+/** `ctx.tui`: terminal apps and the builders of their views. */
+export interface TerminalApps {
+ /** Serves a terminal app; the descriptor says where the shell shows it. */
+ app(
+ name: string,
+ handlers: TerminalAppHandlers,
+ descriptor: Omit<TerminalView, 'version'>,
+ options?: import('./host.js').RemoteOptions,
+ ): Promise<import('./host.js').Registration>;
+ /** Registers a changes stream; call the result to refresh open views. */
+ changes(name: string): Promise<(() => void) & { close(): Promise<void> }>;
+ view(body: TerminalViewBody): TerminalViewTree;
+ column(key: string, children: TerminalNode[], gap?: number): TerminalNode;
+ stack(key: string, children: TerminalNode[]): TerminalNode;
+ row(key: string, children: TerminalNode[], gap?: number): TerminalNode;
+ text(key: string, text: string, tone?: TerminalTone): TerminalNode;
+ spans(key: string, spans: [string, TerminalTone?][]): TerminalNode;
+ heading(key: string, text: string): TerminalNode;
+ rule(key: string): TerminalNode;
+ scroll(key: string, rows: number, child: TerminalNode): TerminalNode;
+ split(key: string, ratio: number, left: TerminalNode, right: TerminalNode): TerminalNode;
+ tabs(
+ key: string,
+ current: string,
+ tabs: { id: string; label: string; route: Json }[],
+ ): TerminalNode;
+ link(key: string, title: string, route: Json, extra?: ItemExtra): TerminalNode;
+ act(key: string, title: string, action: string, extra?: ItemExtra): TerminalNode;
+ open(key: string, title: string, session: string, extra?: ItemExtra): TerminalNode;
+ button(
+ key: string,
+ action: string,
+ role?: 'normal' | 'primary' | 'destructive',
+ label?: string,
+ ): TerminalNode;
+ input(key: string, field: string, label?: string): TerminalNode;
+ progress(key: string, value: number, max: number, label?: string): TerminalNode;
+ markdown(key: string, text: string): TerminalNode;
+ code(key: string, text: string): TerminalNode;
+ slot(key: string, name: string, context?: Json): TerminalNode;
+ action(id: string, label: string, extra?: Partial<TerminalAction>): TerminalAction;
+ toggle(id: string, value: boolean): TerminalField;
+ line(
+ id: string,
+ value?: string,
+ maxBytes?: number,
+ extra?: { placeholder?: string; secret?: boolean },
+ ): TerminalField;
+ area(
+ id: string,
+ value?: string,
+ maxBytes?: number,
+ extra?: { placeholder?: string },
+ ): TerminalField;
+ choice(id: string, value: string, options: [string, string][]): TerminalField;
+}
diff --git a/packages/plugin-sdk/tsconfig.acceptance.json b/packages/plugin-sdk/tsconfig.acceptance.json
index 5c03b49c54..5ad15f69f6 100644
--- a/packages/plugin-sdk/tsconfig.acceptance.json
+++ b/packages/plugin-sdk/tsconfig.acceptance.json
@@ -23,6 +23,7 @@
"../../crates/runtime-host/tests/fixtures/files-plugin.mjs",
"../../crates/runtime-host/tests/fixtures/clients-plugin.mjs",
"../../crates/runtime-host/tests/fixtures/remote-plugin.mjs",
+ "../../crates/cli/tests/fixtures/board-plugin/host.mjs",
"../workhub/src/client.tsx",
"../workhub/src/styles.d.ts",
"../../crates/assistant/src/todo/client.tsx"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org