From 72ac5cda54734f5a92ef89acc63f677f9fe5f25f Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 12:16:00 +0800 Subject: [PATCH 1/9] Plan finish Connection, control and UI owner operations From 786cf00b304d17bb14b2b61cf381fbb7a4a30fa8 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 18:50:39 +0800 Subject: [PATCH 2/9] Serve UI connection cleanup and extension registration on their owners --- crates/dim-app-server/src/lib.rs | 4 +- crates/dim-app-server/src/plugin_manager.rs | 19 ++- .../src/ui_extensions/manifest.rs | 3 +- .../dim-app-server/src/ui_extensions/mod.rs | 108 +++++++++++------- crates/dim-app-server/src/ui_host.rs | 49 ++++++++ crates/dim-app-server/src/ui_leaf.rs | 4 + .../tests/transport_flow/ui_host.rs | 46 ++++++++ .../generated/app-server/services.json | 12 ++ .../rust-agent/generated/catalog.md | 4 +- npm/branch-services.d.ts | 49 ++++++++ npm/plugin.d.ts | 8 +- runtime/fixtures/ui-owner.ts | 38 ++++++ 12 files changed, 292 insertions(+), 52 deletions(-) create mode 100644 runtime/fixtures/ui-owner.ts diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index e892c17b0b..055d865e76 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1442,7 +1442,9 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata register::(catalog, None); catalog.register_shared(dim_agent_runtime::names::name_of::()); register::(catalog, None); + catalog.register_shared("uiHost"); register::(catalog, None); + catalog.register_shared("uiExtensions"); register::(catalog, Some(SESSION_GROUP)); register::(catalog, None); register::(catalog, None); @@ -1522,8 +1524,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("timelineTreeControl", "owner-api"), ("toolBinding", "hot-path"), ("toolExecutor", "hot-path"), - ("uiExtensions", "control"), - ("uiHost", "control"), ] { builder.internal_name(name, reason); } diff --git a/crates/dim-app-server/src/plugin_manager.rs b/crates/dim-app-server/src/plugin_manager.rs index e9c7788b45..b6d22548b1 100644 --- a/crates/dim-app-server/src/plugin_manager.rs +++ b/crates/dim-app-server/src/plugin_manager.rs @@ -12,7 +12,7 @@ use crate::hooks_settings::HooksService; use crate::mcp::{McpError, McpServiceBinding}; use crate::methods::ManagementMethods; use crate::settings::{Settings, SettingsError, SourceDeclaration}; -use crate::ui_extensions::UiExtensions; +use crate::ui_extensions::{UiExtensionPlugin, UiExtensionRegistration, UiExtensions}; use acquire::PluginsDir; use dim_agent_capabilities::methods::{Interruption, MethodCall, MethodDecl, Progress, RpcError}; use dim_agent_capabilities::skills::{SkillIssue, SkillsCatalogBinding}; @@ -836,7 +836,7 @@ impl Owners { if kinds.contains(&Kind::Ui) && let Some(ui) = self.ctx.get_at(&self.ui) { - held.extend(ui.plugins()); + held.extend(ui.plugins(crate::protocol::Empty {})); } held } @@ -857,7 +857,11 @@ impl Owners { match self.ctx.get_at(&self.ui) { Some(ui) => { if let Err(error) = ui - .register(plugin, &manifest.name, manifest.ui.as_ref()) + .register(UiExtensionRegistration { + plugin: plugin.into(), + name: manifest.name.clone(), + package: manifest.ui.clone(), + }) .await { outcome.refused.push(refused(Kind::Ui, error)); @@ -963,7 +967,10 @@ impl Owners { if kinds.contains(&Kind::Ui) && let Some(ui) = self.ctx.get_at(&self.ui) { - ui.withdraw(plugin).await; + ui.withdraw(UiExtensionPlugin { + plugin: plugin.into(), + }) + .await; } for kind in kinds { self.clear_refusal(plugin, *kind); @@ -1014,7 +1021,9 @@ impl Owners { async fn refused(&self, plugin: &str, manifest: &Manifest) -> Vec { let mut found = Vec::new(); if let Some(ui) = self.ctx.get_at(&self.ui) - && let Some(error) = ui.plugin_refusal(plugin) + && let Some(error) = ui.refusal(UiExtensionPlugin { + plugin: plugin.into(), + }) { found.push(refused(Kind::Ui, error)); } diff --git a/crates/dim-app-server/src/ui_extensions/manifest.rs b/crates/dim-app-server/src/ui_extensions/manifest.rs index c1187899dc..b545071a44 100644 --- a/crates/dim-app-server/src/ui_extensions/manifest.rs +++ b/crates/dim-app-server/src/ui_extensions/manifest.rs @@ -40,7 +40,8 @@ pub struct Panel { pub methods: Vec, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] pub enum Package { Supported { root: PathBuf, panels: Vec }, Unsupported { version: u64 }, diff --git a/crates/dim-app-server/src/ui_extensions/mod.rs b/crates/dim-app-server/src/ui_extensions/mod.rs index 6d06e8cf0c..4727c945b8 100644 --- a/crates/dim-app-server/src/ui_extensions/mod.rs +++ b/crates/dim-app-server/src/ui_extensions/mod.rs @@ -95,23 +95,23 @@ pub struct UiExtensions { updating: tokio::sync::Mutex<()>, reads: Reads, } +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct UiExtensionPlugin { + pub plugin: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct UiExtensionRegistration { + pub plugin: String, + pub name: String, + pub package: Option, +} + +#[rutis::service(name = "uiExtensions")] impl UiExtensions { - pub fn directory(&self) -> Directory { - let catalog = self.catalog.lock().unwrap(); - Directory { - revision: *self.changes.borrow(), - extensions: catalog - .entries - .values() - .map(|entry| entry.extension.clone()) - .collect(), - errors: catalog.errors.values().cloned().collect(), - } - } - pub fn subscribe(&self) -> watch::Receiver { - self.changes.subscribe() - } - pub fn plugins(&self) -> Vec { + pub fn plugins(&self, _request: crate::protocol::Empty) -> Vec { let catalog = self.catalog.lock().unwrap(); catalog .entries @@ -120,25 +120,22 @@ impl UiExtensions { .cloned() .collect() } - pub fn plugin_refusal(&self, plugin: &str) -> Option { + pub fn refusal(&self, request: UiExtensionPlugin) -> Option { self.catalog .lock() .unwrap() .errors - .get(plugin) + .get(&request.plugin) .map(|error| error.message.clone()) } - fn changed(&self) { - self.changes.send_replace(self.configuration.revision()); - } - pub async fn register( - &self, - plugin: &str, - name: &str, - package: Option<&Package>, - ) -> Result<(), String> { + pub async fn register(&self, request: UiExtensionRegistration) -> Result<(), String> { + let UiExtensionRegistration { + plugin, + name, + package, + } = request; let Some(package) = package else { - self.withdraw(plugin).await; + self.withdraw(UiExtensionPlugin { plugin }).await; return Ok(()); }; let _update = self.updating.lock().await; @@ -147,25 +144,25 @@ impl UiExtensions { .sources .lock() .unwrap() - .insert(plugin.into(), (name.into(), package.clone())); - let prepared = match package { - Package::Supported { root, panels } => self.prepare(name, root, panels).await, + .insert(plugin.clone(), (name.clone(), package.clone())); + let prepared = match &package { + Package::Supported { root, panels } => self.prepare(&name, root, panels).await, Package::Unsupported { version } => Err(format!("Unsupported UI version {version}")), Package::Rejected { message } => Err(message.clone()), }; let old = { let mut catalog = self.catalog.lock().unwrap(); - let old = catalog.entries.remove(plugin); - catalog.errors.remove(plugin); + let old = catalog.entries.remove(&plugin); + catalog.errors.remove(&plugin); match &prepared { Ok(snapshot) => { - catalog.entries.insert(plugin.into(), snapshot.clone()); + catalog.entries.insert(plugin, snapshot.clone()); } Err(message) => { catalog.errors.insert( - plugin.into(), + plugin, Unavailable { - plugin_name: name.into(), + plugin_name: name, message: message.clone(), }, ); @@ -179,13 +176,14 @@ impl UiExtensions { } prepared.map(|_| ()) } - pub async fn withdraw(&self, plugin: &str) { + pub async fn withdraw(&self, request: UiExtensionPlugin) { + let plugin = request.plugin; let _update = self.updating.lock().await; - self.configuration.sources.lock().unwrap().remove(plugin); + self.configuration.sources.lock().unwrap().remove(&plugin); let old = { let mut catalog = self.catalog.lock().unwrap(); - let old = catalog.entries.remove(plugin); - let error = catalog.errors.remove(plugin); + let old = catalog.entries.remove(&plugin); + let error = catalog.errors.remove(&plugin); if old.is_some() || error.is_some() { self.changed(); } @@ -195,6 +193,27 @@ impl UiExtensions { self.remove(old).await; } } +} + +impl UiExtensions { + pub fn directory(&self) -> Directory { + let catalog = self.catalog.lock().unwrap(); + Directory { + revision: *self.changes.borrow(), + extensions: catalog + .entries + .values() + .map(|entry| entry.extension.clone()) + .collect(), + errors: catalog.errors.values().cloned().collect(), + } + } + pub fn subscribe(&self) -> watch::Receiver { + self.changes.subscribe() + } + fn changed(&self) { + self.changes.send_replace(self.configuration.revision()); + } async fn prepare( &self, name: &str, @@ -495,7 +514,14 @@ impl DynPlugin for UiExtensionsPlugin { .map_err(|error| ErrorKind::PluginFailed(error.into()))?; let sources = self.configuration.sources.lock().unwrap().clone(); for (plugin, (name, package)) in sources { - if let Err(error) = service.register(&plugin, &name, Some(&package)).await { + if let Err(error) = service + .register(UiExtensionRegistration { + plugin: plugin.clone(), + name, + package: Some(package), + }) + .await + { tracing::warn!(%plugin, %error, "UI content restore refused"); } } diff --git a/crates/dim-app-server/src/ui_host.rs b/crates/dim-app-server/src/ui_host.rs index 9a08ae7ea2..dcce4e7d29 100644 --- a/crates/dim-app-server/src/ui_host.rs +++ b/crates/dim-app-server/src/ui_host.rs @@ -585,6 +585,55 @@ impl UiHost { } } +#[derive(serde::Deserialize)] +#[serde( + tag = "method", + content = "request", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +enum ConnectionOperation { + Detach { + connection_id: String, + session_id: String, + }, + Release { + connection_id: String, + }, + Finished { + connection_id: String, + }, +} + +impl rutis_bridge::session::HostDispatch for UiHost { + fn methods(&self) -> Option { + Some(serde_json::json!({"detach":"sync", "release":"sync", "finished":"sync"})) + } + + fn invoke( + &self, + method: &str, + args: rutis_bridge::session::Value, + ) -> rutis_bridge::session::Reply { + use rutis_bridge::session::{Error, Value}; + let [request] = <[_; 1]>::try_from(args.list()?) + .map_err(|_| Error::Value("expected one UI connection request".into()))?; + let op = + serde_json::from_value(serde_json::json!({"method":method, "request":request.json()?})) + .map_err(|error| Error::Value(error.to_string()))?; + match op { + ConnectionOperation::Detach { + connection_id, + session_id, + } => self.detach(&connection_id, &session_id), + ConnectionOperation::Release { connection_id } => self.release(&connection_id), + ConnectionOperation::Finished { connection_id } => self.finished(&connection_id), + } + Ok(Value::Undefined) + } +} + /// Claims `old` for the replacement `by`, checking its Session and the /// generation the caller observed. fn claim( diff --git a/crates/dim-app-server/src/ui_leaf.rs b/crates/dim-app-server/src/ui_leaf.rs index 84cdd0c68e..c6d37ce55a 100644 --- a/crates/dim-app-server/src/ui_leaf.rs +++ b/crates/dim-app-server/src/ui_leaf.rs @@ -166,6 +166,10 @@ impl Plugin for UiHostPlugin { async fn apply(&self, ctx: &Ctx, (): ()) -> rutis::Result { let host = crate::ui_host::UiHost::new(UiLeaves { ctx: ctx.clone() }); ctx.provide_as::(host.clone())?; + ctx.provide_at::( + rutis_bridge::session::host_key("uiHost"), + host.clone(), + )?; ctx.effect(move || async move { host.close_all().await; Ok(()) diff --git a/crates/dim-app-server/tests/transport_flow/ui_host.rs b/crates/dim-app-server/tests/transport_flow/ui_host.rs index c36f4057e8..3a1a2715ab 100644 --- a/crates/dim-app-server/tests/transport_flow/ui_host.rs +++ b/crates/dim-app-server/tests/transport_flow/ui_host.rs @@ -546,3 +546,49 @@ async fn a_leaf_that_never_attaches_is_closed_after_its_start_bound() { leaf.exit().await; } } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_ui_operations_use_the_connected_client_and_extension_catalog() { + let mut parts = super::session_typescript::fixture(); + parts.rows = vec![json!({ + "id":"ui-owner", "name":parts.anchor.parent().unwrap().join("fixtures/ui-owner.ts"), + "provides":{} + })]; + let home = std::env::temp_dir().join(format!("dm-ui-{}", uuid::Uuid::new_v4())); + let (server, _, _) = super::session_typescript::start(ServerConfig { + target_home: Some(home.join("rust")), + session_typescript: Some(parts), + ..Default::default() + }) + .await; + let mut client = Client::new_version(&server, false, 3).await; + let session = attached_session(&mut client).await; + for action in ["detach", "release"] { + assert_ok( + &client + .rpc("ui.attach", json!({"sessionId":session,"kind":"tui"})) + .await, + ); + let result = super::process_typescript::files_available( + &mut client, + &format!("uifixture.{action}"), + json!({"sessionId":session}), + ) + .await; + assert_eq!(result, true); + let status = client.rpc("ui.status", json!({})).await; + assert_eq!(status["result"]["instances"], json!([])); + let catalog = client.rpc("ui.extensions.list", json!({})).await; + assert_ok(&catalog); + let refused = catalog["result"]["errors"] + .as_array() + .unwrap() + .iter() + .any(|error| error["pluginName"] == "ui-fixture"); + assert_eq!(refused, action == "detach"); + } + server.shutdown(); + server.join().await.unwrap(); + std::fs::remove_dir_all(home).unwrap(); +} diff --git a/docs/architecture/rust-agent/generated/app-server/services.json b/docs/architecture/rust-agent/generated/app-server/services.json index e5709a60db..2fa62a4135 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.json +++ b/docs/architecture/rust-agent/generated/app-server/services.json @@ -3948,6 +3948,18 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#uiExtensions", + "provider": 36, + "generation": 1, + "removing": false + }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#uiHost", + "provider": 42, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#wakeups", "provider": 72, diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d2481d5fb9..7baa897035 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -63,8 +63,8 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `store` | process | SessionStore | data | `addGrant` async, `catalog` async, `createOwnedSession` async, `creationRecord` async, `delete` async, `fork` async, `grants` async, `hasRecords` async, `owner` async, `query` async, `removeGrant` async, `removeWorktree` async, `removeWorktreeDirectory` async, `sessionConfig` async, `sessionConfigText` async, `sessionsUnderWorkspace` async, `setSessionLanguage` async, `worktreeDirectories` async, `worktreeUsages` async | | `summaryPromptSettingsHost` | process | PromptSettings | data | `systemPrompt` async | | `toolchainSourceHost` | process | ToolchainSource | data | `list` sync | -| `uiExtensions` | process | UiExtensions | internal(control) | — | -| `uiHost` | process | UiHost | internal(control) | — | +| `uiExtensions` | process | UiExtensions | data | `plugins` async, `refusal` async, `register` async, `withdraw` async | +| `uiHost` | process | UiHost | data | `detach` sync, `finished` sync, `release` sync | | `wakeups` | process | Scheduler | data | `cancel` async, `create` async, `list` async | | `workflowFiles` | process | Settings | data | `createDirectory` async, `list` async, `read` async, `replace` async | | `worktreeAssociations` | process | SessionStore | data | `associate` async | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b89bf93026..d568ad5dbb 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1264,6 +1264,51 @@ export interface ListenAddresses { read(): Promise } +export interface UiExtensionPlugin { + plugin: string +} + +export interface Title { + default: string + translations?: Record +} + +export type MethodScope = "session" | "branch" + +export interface Method { + name: string + scope: MethodScope +} + +export interface Panel { + id: string + title: Title + icon?: string | null + entry: string + placement: string + requires: string[] + methods: Method[] +} + +export type Package = + | { kind: "supported"; root: string; panels: Panel[] } + | { kind: "unsupported"; version: number | bigint } + | { kind: "rejected"; message: string } + +export interface UiExtensionRegistration { + plugin: string + name: string + package?: Package | null +} + +export interface UiExtensions { + plugins(request: Empty): Promise + refusal(request: UiExtensionPlugin): Promise + /** @throws {StringThrown} */ + register(request: UiExtensionRegistration): Promise + withdraw(request: UiExtensionPlugin): Promise +} + export interface PublishFile { /** Absolute host path inside an already authorized FileStorage root. */ path: string @@ -1325,6 +1370,9 @@ export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceErr /** What a method returning `Err(SessionsError)` throws. */ export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> +/** What a method returning `Err(String)` throws. */ +export type StringThrown = RustError<"Error", "Error", undefined> + /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> @@ -1373,5 +1421,6 @@ export interface Services { mcpSession: McpSession workflowFiles: WorkflowFiles listenAddresses: ListenAddresses + uiExtensions: UiExtensions uiResources: UiResources } diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index c7ea5d1837..5aa1721f80 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -262,7 +262,7 @@ export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, - UiResources, PublishFile, ResourceRef, ResourceErrorThrown, + UiExtensions, UiExtensionRegistration, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; export interface HistoryPage { through: number; events: AgentEvent[] } export interface WithdrawRequest extends SessionRef { inputId: string; reason?: string | null } @@ -628,6 +628,12 @@ export type StoredAgentProfile = { name: string; description: string; systemPrompt: string; tools?: string[]; model?: ModelId; }; export type StoredProviderSelection = { provider_id: string; model_id: string; version: number }; +export interface UiHost { + detach(request: {connectionId: string, sessionId: string}): Promise; + release(request: {connectionId: string}): Promise; + finished(request: {connectionId: string}): Promise; +} + export interface SqliteStorage extends Pick { commitTimelineRound(request: { batches: TimelineAppend[] }): Promise<{ sessions: { sessionId: string; result: { Ok: null } | { Err: { code: string; message: string } } }[] }>; readSelection(request: { scope: string }): Promise; diff --git a/runtime/fixtures/ui-owner.ts b/runtime/fixtures/ui-owner.ts new file mode 100644 index 0000000000..91f68abbee --- /dev/null +++ b/runtime/fixtures/ui-owner.ts @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict' +import { definePlugin } from '@arcships/rutis' +import type { ManagementMethods, UiExtensions, UiHost } from '../../npm/plugin.js' + +export default definePlugin({ + name: 'UiOwnerFixture', + provides: {}, + inject: ['uiHost', 'uiExtensions', 'managementMethods'], + async apply(ctx) { + const host = ctx.use('uiHost') + const extensions = ctx.use('uiExtensions') + await ctx.use('managementMethods').register('uifixture', [ + { name: 'uifixture.detach', mutating: true, interruption: 'drain', progress: false }, + { name: 'uifixture.release', mutating: true, interruption: 'drain', progress: false }, + ], async call => { + const connectionId = call.origin?.connectionId + assert.ok(connectionId) + const plugin = 'ui-fixture' + if (call.method === 'uifixture.detach') { + const params = call.params + assert.ok(params && typeof params === 'object' && !Array.isArray(params) && 'sessionId' in params) + const {sessionId} = params + assert.ok(typeof sessionId === 'string') + await host.detach({connectionId, sessionId}) + await assert.rejects(extensions.register({plugin, name: plugin, package: {kind: 'unsupported', version: 2}}), /Unsupported UI version 2/) + assert.ok((await extensions.plugins({})).includes(plugin)) + assert.equal(await extensions.refusal({plugin}), 'Unsupported UI version 2') + } else { + await host.release({connectionId}) + await host.finished({connectionId}) + await extensions.withdraw({plugin}) + assert.equal(await extensions.refusal({plugin}), null) + assert.ok(!(await extensions.plugins({})).includes(plugin)) + } + return {kind: 'value', value: true} + }) + }, +}) From 2bab82ae1521b9e7f55d94d74717d79f7f723ca1 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 21:34:00 +0800 Subject: [PATCH 3/9] Keep native daemon and connection handles private to the server --- crates/dim-app-server/src/agents/tests.rs | 8 ++++---- crates/dim-app-server/src/connection.rs | 6 +++--- crates/dim-app-server/src/lib.rs | 4 ---- crates/dim-app-server/src/transport.rs | 4 ++-- docs/architecture/rust-agent/generated/catalog.md | 2 -- docs/design/service-faces.md | 4 ---- 6 files changed, 9 insertions(+), 19 deletions(-) diff --git a/crates/dim-app-server/src/agents/tests.rs b/crates/dim-app-server/src/agents/tests.rs index 0baf308917..3eb7fbdcb9 100644 --- a/crates/dim-app-server/src/agents/tests.rs +++ b/crates/dim-app-server/src/agents/tests.rs @@ -129,10 +129,10 @@ async fn process_startup_and_restart_follow_rows_becoming_active() { let (completed, _) = tokio::sync::watch::channel(0); for step in 0..4 { let completed = completed.clone(); - builder.plugin(move |names| { + builder.plugin(move |_| { Ok(Box::new(ProgressingProcess { name: format!("test.process-progress-{step}"), - hub: names.key()?, + hub: rutis::host::Key::of(), step, completed: completed.clone(), })) @@ -272,10 +272,10 @@ async fn a_stored_agent_creation_timeout_settles_during_progressing_startup() { let mut held = HeldCreation::new(&stored.default_agent); let mut progressing = builder(); let (completed, _) = tokio::sync::watch::channel(0); - progressing.plugin(move |names| { + progressing.plugin(move |_| { Ok(Box::new(ProgressingProcess { name: "test.stored-owner-progress".into(), - hub: names.key()?, + hub: rutis::host::Key::of(), step: 0, completed: completed.clone(), })) diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index 8d379ec7a5..94d057eab4 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -2226,7 +2226,7 @@ impl ConnectionPlugin { pub fn new(names: &Names<'_>, config: Arc) -> rutis::Result { Ok(Self { config, - control: names.key()?, + control: Key::of(), ui: names.key()?, clients: names.key()?, parts: names.key()?, @@ -2469,8 +2469,8 @@ impl RpcPlugin { root, index: names.key()?, collaboration: names.key()?, - hub: names.key()?, - control: names.key()?, + hub: Key::of(), + control: Key::of(), loader: names.key()?, management: names.key()?, callers: Key::of(), diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 055d865e76..e42c1bb5c8 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1426,7 +1426,6 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { use dim_agent_capabilities::host::SelectableModelsHost; use dim_agent_runtime::{SESSION_GROUP, names::register}; - register::(catalog, None); register::(catalog, None); register::(catalog, None); catalog.register_shared("sqliteStorage"); @@ -1439,7 +1438,6 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata catalog.register_shared(dim_agent_runtime::names::name_of::< collaboration::CollaborationDirectory, >()); - register::(catalog, None); catalog.register_shared(dim_agent_runtime::names::name_of::()); register::(catalog, None); catalog.register_shared("uiHost"); @@ -1492,7 +1490,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("compactionStrategyHost", "hot-path"), ("configurationPublisher", "hot-path"), ("configureControl", "hot-path"), - ("connectionHub", "control"), ("contextModelHost", "hot-path"), ("contextPreparation", "hot-path"), ("contextUsage", "hot-path"), @@ -1514,7 +1511,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("prompt", "hot-path"), ("providerConnectionResolver", "host-resource"), ("providerService", "secret"), - ("serverControl", "control"), ("sessionLoader", "control"), ("sessionStore", "owner-api"), ("settingsService", "owner-api"), diff --git a/crates/dim-app-server/src/transport.rs b/crates/dim-app-server/src/transport.rs index e5c0d0e478..ca0cad0eda 100644 --- a/crates/dim-app-server/src/transport.rs +++ b/crates/dim-app-server/src/transport.rs @@ -330,8 +330,8 @@ impl TransportPlugin { /// The database lock is a dependency only with native storage. pub fn new(names: &Names<'_>, config: Arc) -> rutis::Result { Ok(Self { - hub: names.key()?, - control: names.key()?, + hub: Key::of(), + control: Key::of(), storage: config .database_path .is_some() diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index 7baa897035..7cc13bdf71 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -15,7 +15,6 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `basePromptSettingsHost` | process | PromptSettings | data | `base` async | | `callChannel` | process | CallChannel | data | `closed` async, `notify` async | | `collaborationDirectory` | process | CollaborationDirectory | data | `relations` async | -| `connectionHub` | process | Connection | internal(control) | — | | `credentialVariablesHost` | process | root | data | `variables` async | | `eventHub` | process | eventhub | data | `declare` async, `publish` async | | `eventSubscriptions` | process | eventhub | data | `list` sync, `sources` sync, `subscribe` async, `unsubscribe` async | @@ -48,7 +47,6 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `rutis/loader` | process | rutis-loader | data | `create` async, `reload` async, `remove` async, `status` async | | `scheduleJobs` | process | Scheduler | data | `call` async | | `selectableModelsHost` | process | Provider | data | `selectableForModality` async, `selectableModels` async | -| `serverControl` | process | ServerControl | internal(control) | — | | `sessionClientsHost` | process | Connection | data | `presences` async | | `sessionFiles` | process | SessionStore | data | `import` async, `owned_paths` async, `owns` async, `put` async, `read` async, `register` async | | `sessionMetadata` | process | SessionStore | data | `read` async, `setTitle` async | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index de466837b4..357127022b 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -195,12 +195,8 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | 名字 | scope | provider | reason | | --- | --- | --- | --- | -| `serverControl` | process | ServerControl | control | -| `connectionHub` | process | Connection | control | | `grokOAuthService` | process | GrokOAuth | secret | | `openAICodexOAuthService` | process | OpenAICodexOAuth | secret | -| `uiHost` | process | UiHost | control | -| `uiExtensions` | process | UiExtensions | control | | `mentionIndex` | process | WorkspaceToolsOwner | host-resource | | `mcpService` | process | Mcp | host-resource | | `hooksService` | process | HooksSettings | host-resource | From 25e66103c1003731ce65ad95ff2a1dbb86beebca Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 22:09:32 +0800 Subject: [PATCH 4/9] Match UiHost TypeScript results to the synchronous dispatcher --- npm/plugin.d.ts | 6 +++--- runtime/fixtures/ui-owner.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 5aa1721f80..2177eaf8e9 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -629,9 +629,9 @@ export type StoredAgentProfile = { }; export type StoredProviderSelection = { provider_id: string; model_id: string; version: number }; export interface UiHost { - detach(request: {connectionId: string, sessionId: string}): Promise; - release(request: {connectionId: string}): Promise; - finished(request: {connectionId: string}): Promise; + detach(request: {connectionId: string, sessionId: string}): void; + release(request: {connectionId: string}): void; + finished(request: {connectionId: string}): void; } export interface SqliteStorage extends Pick { diff --git a/runtime/fixtures/ui-owner.ts b/runtime/fixtures/ui-owner.ts index 91f68abbee..bde1fde256 100644 --- a/runtime/fixtures/ui-owner.ts +++ b/runtime/fixtures/ui-owner.ts @@ -21,13 +21,13 @@ export default definePlugin({ assert.ok(params && typeof params === 'object' && !Array.isArray(params) && 'sessionId' in params) const {sessionId} = params assert.ok(typeof sessionId === 'string') - await host.detach({connectionId, sessionId}) + assert.equal(host.detach({connectionId, sessionId}), undefined) await assert.rejects(extensions.register({plugin, name: plugin, package: {kind: 'unsupported', version: 2}}), /Unsupported UI version 2/) assert.ok((await extensions.plugins({})).includes(plugin)) assert.equal(await extensions.refusal({plugin}), 'Unsupported UI version 2') } else { - await host.release({connectionId}) - await host.finished({connectionId}) + assert.equal(host.release({connectionId}), undefined) + assert.equal(host.finished({connectionId}), undefined) await extensions.withdraw({plugin}) assert.equal(await extensions.refusal({plugin}), null) assert.ok(!(await extensions.plugins({})).includes(plugin)) From d3ac98c239447f833b62327d347e3048073fc365 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 23:43:17 +0800 Subject: [PATCH 5/9] Verify connection presence when a disposed UI leaf finishes --- .../tests/transport_flow/ui_host.rs | 17 +++++++++++++ runtime/fixtures/ui-owner.ts | 24 ++++++++++++------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/crates/dim-app-server/tests/transport_flow/ui_host.rs b/crates/dim-app-server/tests/transport_flow/ui_host.rs index 3a1a2715ab..c107e996db 100644 --- a/crates/dim-app-server/tests/transport_flow/ui_host.rs +++ b/crates/dim-app-server/tests/transport_flow/ui_host.rs @@ -588,6 +588,23 @@ async fn node_ui_operations_use_the_connected_client_and_extension_catalog() { .any(|error| error["pluginName"] == "ui-fixture"); assert_eq!(refused, action == "detach"); } + let mut leaf = FakeLeaf::start().await; + let opened = client + .rpc("ui.open", opening(&session, &leaf, json!({}))) + .await; + assert_ok(&opened); + leaf.attach(&server, &session, &opened).await; + assert_ok(&client.rpc("ui.close", json!({"uiId": leaf.peer})).await); + leaf.closed(Duration::from_secs(10)).await; + let finished = leaf + .tui + .as_mut() + .unwrap() + .rpc("uifixture.finished", json!({"sessionId": session})) + .await; + assert_ok(&finished); + assert_eq!(finished["result"], true); + leaf.exit().await; server.shutdown(); server.join().await.unwrap(); std::fs::remove_dir_all(home).unwrap(); diff --git a/runtime/fixtures/ui-owner.ts b/runtime/fixtures/ui-owner.ts index bde1fde256..3abb7b5a7b 100644 --- a/runtime/fixtures/ui-owner.ts +++ b/runtime/fixtures/ui-owner.ts @@ -1,33 +1,41 @@ import assert from 'node:assert/strict' import { definePlugin } from '@arcships/rutis' -import type { ManagementMethods, UiExtensions, UiHost } from '../../npm/plugin.js' +import type { ManagementMethods, Services, UiExtensions, UiHost } from '../../npm/plugin.js' export default definePlugin({ name: 'UiOwnerFixture', provides: {}, - inject: ['uiHost', 'uiExtensions', 'managementMethods'], + inject: ['uiHost', 'uiExtensions', 'managementMethods', 'sessionClientsHost'], async apply(ctx) { const host = ctx.use('uiHost') + const clients = ctx.use('sessionClientsHost') const extensions = ctx.use('uiExtensions') await ctx.use('managementMethods').register('uifixture', [ { name: 'uifixture.detach', mutating: true, interruption: 'drain', progress: false }, + { name: 'uifixture.finished', mutating: true, interruption: 'drain', progress: false }, { name: 'uifixture.release', mutating: true, interruption: 'drain', progress: false }, ], async call => { const connectionId = call.origin?.connectionId assert.ok(connectionId) const plugin = 'ui-fixture' - if (call.method === 'uifixture.detach') { - const params = call.params - assert.ok(params && typeof params === 'object' && !Array.isArray(params) && 'sessionId' in params) - const {sessionId} = params - assert.ok(typeof sessionId === 'string') + const params = call.params + assert.ok(params && typeof params === 'object' && !Array.isArray(params) && 'sessionId' in params) + const {sessionId} = params + assert.ok(typeof sessionId === 'string') + if (call.method === 'uifixture.finished') { + const before = await clients.presences({ sessionId }) + assert.equal(before.presences.length, 1) + assert.equal(host.finished({connectionId}), undefined) + const after = await clients.presences({ sessionId }) + assert.equal(after.presences.length, 2) + assert.ok(after.presences.every(presence => presence.channel !== 'tui')) + } else if (call.method === 'uifixture.detach') { assert.equal(host.detach({connectionId, sessionId}), undefined) await assert.rejects(extensions.register({plugin, name: plugin, package: {kind: 'unsupported', version: 2}}), /Unsupported UI version 2/) assert.ok((await extensions.plugins({})).includes(plugin)) assert.equal(await extensions.refusal({plugin}), 'Unsupported UI version 2') } else { assert.equal(host.release({connectionId}), undefined) - assert.equal(host.finished({connectionId}), undefined) await extensions.withdraw({plugin}) assert.equal(await extensions.refusal({plugin}), null) assert.ok(!(await extensions.plugins({})).includes(plugin)) From d53aefc39daeb3463a1d738a79d21587cbf10caf Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 02:25:08 +0800 Subject: [PATCH 6/9] Admit UI manifests at the shared registration entry before preparing snapshots --- crates/dim-app-server/src/plugin_manager.rs | 7 +++- .../src/plugin_manager/record.rs | 8 ++--- .../src/ui_extensions/manifest.rs | 1 - .../dim-app-server/src/ui_extensions/mod.rs | 30 +++++++++++------ .../contracts/process-owner-operations.md | 2 +- npm/branch-services.d.ts | 32 +++---------------- 6 files changed, 35 insertions(+), 45 deletions(-) diff --git a/crates/dim-app-server/src/plugin_manager.rs b/crates/dim-app-server/src/plugin_manager.rs index b6d22548b1..a23b0901ee 100644 --- a/crates/dim-app-server/src/plugin_manager.rs +++ b/crates/dim-app-server/src/plugin_manager.rs @@ -860,7 +860,12 @@ impl Owners { .register(UiExtensionRegistration { plugin: plugin.into(), name: manifest.name.clone(), - package: manifest.ui.clone(), + package: manifest.ui.clone().map(|manifest| { + crate::ui_extensions::UiPackage { + directory: dir.to_path_buf(), + manifest, + } + }), }) .await { diff --git a/crates/dim-app-server/src/plugin_manager/record.rs b/crates/dim-app-server/src/plugin_manager/record.rs index 490e39fd4b..a2fd3da442 100644 --- a/crates/dim-app-server/src/plugin_manager/record.rs +++ b/crates/dim-app-server/src/plugin_manager/record.rs @@ -300,7 +300,7 @@ pub struct Manifest { pub skills: Option, pub mcp: Option, pub hooks: Option, - pub ui: Option, + pub ui: Option, } /// The rutis row fields of a plugin's code, with `entry` resolved. @@ -417,11 +417,7 @@ impl Manifest { skills: path(file.skills, "skills")?, mcp: path(file.mcp, "mcp")?, hooks: path(file.hooks, "hooks")?, - ui: file.ui.map(|value| { - crate::ui_extensions::manifest::Package::read(dir, value).unwrap_or_else( - |message| crate::ui_extensions::manifest::Package::Rejected { message }, - ) - }), + ui: file.ui, }) } diff --git a/crates/dim-app-server/src/ui_extensions/manifest.rs b/crates/dim-app-server/src/ui_extensions/manifest.rs index b545071a44..beb34baea5 100644 --- a/crates/dim-app-server/src/ui_extensions/manifest.rs +++ b/crates/dim-app-server/src/ui_extensions/manifest.rs @@ -45,7 +45,6 @@ pub struct Panel { pub enum Package { Supported { root: PathBuf, panels: Vec }, Unsupported { version: u64 }, - Rejected { message: String }, } #[derive(Deserialize)] diff --git a/crates/dim-app-server/src/ui_extensions/mod.rs b/crates/dim-app-server/src/ui_extensions/mod.rs index 4727c945b8..4df7be6960 100644 --- a/crates/dim-app-server/src/ui_extensions/mod.rs +++ b/crates/dim-app-server/src/ui_extensions/mod.rs @@ -70,7 +70,7 @@ struct Catalog { pub(crate) struct Configuration { cache: PathBuf, - sources: Mutex>, + sources: Mutex>, revision: AtomicU64, } impl Configuration { @@ -106,7 +106,14 @@ pub struct UiExtensionPlugin { pub struct UiExtensionRegistration { pub plugin: String, pub name: String, - pub package: Option, + pub package: Option, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UiPackage { + pub directory: PathBuf, + pub manifest: serde_json::Value, } #[rutis::service(name = "uiExtensions")] @@ -128,7 +135,7 @@ impl UiExtensions { .get(&request.plugin) .map(|error| error.message.clone()) } - pub async fn register(&self, request: UiExtensionRegistration) -> Result<(), String> { + pub async fn register(&self, request: UiExtensionRegistration) -> Result<(), ResourceError> { let UiExtensionRegistration { plugin, name, @@ -139,16 +146,21 @@ impl UiExtensions { return Ok(()); }; let _update = self.updating.lock().await; - let _operation = self.reads.enter().map_err(|error| error.message)?; + let _operation = self.reads.enter()?; self.configuration .sources .lock() .unwrap() .insert(plugin.clone(), (name.clone(), package.clone())); - let prepared = match &package { - Package::Supported { root, panels } => self.prepare(&name, root, panels).await, - Package::Unsupported { version } => Err(format!("Unsupported UI version {version}")), - Package::Rejected { message } => Err(message.clone()), + let prepared = match Package::read(&package.directory, package.manifest) { + Ok(Package::Supported { root, panels }) => self + .prepare(&name, &root, &panels) + .await + .map_err(file_error), + Ok(Package::Unsupported { version }) => Err(ResourceError::invalid(&format!( + "Unsupported UI version {version}" + ))), + Err(message) => Err(ResourceError::invalid(&message)), }; let old = { let mut catalog = self.catalog.lock().unwrap(); @@ -163,7 +175,7 @@ impl UiExtensions { plugin, Unavailable { plugin_name: name, - message: message.clone(), + message: message.message.clone(), }, ); } diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 3b9d8f234c..af2ade655f 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -27,7 +27,7 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Session configuration → `providerService` (managed profile) | `configuration(explicit?, cwd?, preferences) → ModelSelection`; `applyPreferences(current, update) → ModelSelection`. Bind the existing Provider operations. | | Session creation/adoption and Collaboration → `providerService` (managed profile) | `prepareStartup(request) → {model, admissionId?}`, `checkStartup(source) → void`, `retainStartup({sessionId, generation, model, admissionId?}) → void`, `releaseStartup({admissionId}) → void`. Reuse the pending startup binding ID. Retain on success for that Session generation; release on failure or caller unload. | | Session creation / worktree management → ManagedWorktrees | `create({source, base?, branch?}) → CreatedWorktreeReply`, `discard(created) → void`, `list({}) → WorktreeView[]`, `pruneSelection({olderThanMs?, keep?, force}) → PruneSelection`, `remove({taskId, force}) → boolean`. Bind the existing operations. Failed Session creation discards the created worktree on its node. | -| PluginManager → UiExtensions | `plugins({}) → string[]`, `refusal({plugin}) → string or null`, `register({plugin, name, package?}) → void`, `withdraw({plugin}) → void`. Bind the existing catalog methods. | +| PluginManager → UiExtensions | `plugins({}) → string[]`, `refusal({plugin}) → string or null`, `register({plugin, name, package?}) → void`, `withdraw({plugin}) → void`. For registration, `package` contains the plugin directory and its UI manifest. UiExtensions admits the root and panels before publishing the snapshot. | ### Session use and generation observation diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index ed2340dc34..863be0d9d6 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1268,43 +1268,21 @@ export type UiExtensionPlugin = { plugin: string } -export type Title = { - default: string - translations?: Record +export type UiPackage = { + directory: string + manifest: JsonValue } -export type MethodScope = "session" | "branch" - -export type Method = { - name: string - scope: MethodScope -} - -export type Panel = { - id: string - title: Title - icon?: string | null - entry: string - placement: string - requires: string[] - methods: Method[] -} - -export type Package = - | { kind: "supported"; root: string; panels: Panel[] } - | { kind: "unsupported"; version: number | bigint } - | { kind: "rejected"; message: string } - export type UiExtensionRegistration = { plugin: string name: string - package?: Package | null + package?: UiPackage | null } export interface UiExtensions { plugins(request: Empty): Promise refusal(request: UiExtensionPlugin): Promise - /** @throws {StringThrown} */ + /** @throws {ResourceErrorThrown} */ register(request: UiExtensionRegistration): Promise withdraw(request: UiExtensionPlugin): Promise } From f7a68b09fff687071f7cb302ceab3b6e1e59810e Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 02:25:48 +0800 Subject: [PATCH 7/9] Use the SDK bridge value type for UI manifests --- npm/branch-services.d.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 863be0d9d6..734b585acb 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1270,7 +1270,7 @@ export type UiExtensionPlugin = { export type UiPackage = { directory: string - manifest: JsonValue + manifest: import('./plugin.js').BridgeJsonValue } export type UiExtensionRegistration = { @@ -1279,6 +1279,11 @@ export type UiExtensionRegistration = { package?: UiPackage | null } +export type ResourceError = { + code: string + message: string +} + export interface UiExtensions { plugins(request: Empty): Promise refusal(request: UiExtensionPlugin): Promise @@ -1298,11 +1303,6 @@ export type ResourceRef = { id: string } -export type ResourceError = { - code: string - message: string -} - export interface UiResources { /** * Publishes a finalized regular file at a canonical absolute host path @@ -1349,7 +1349,6 @@ export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceErr export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(String)` throws. */ -export type StringThrown = RustError<"Error", "Error", undefined> /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> From de3b7a7f602810f781b488219178bcdc7c10c326 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 23:04:52 +0800 Subject: [PATCH 8/9] Align the UI fixture, generated bindings and manifest ownership docs --- docs/design/client-ui-extensions.md | 6 +++--- docs/design/plugins/PluginManager.md | 4 ++-- npm/branch-services.d.ts | 2 -- runtime/fixtures/ui-owner.ts | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 69de4c7b52..7a0f8b73a7 100644 --- a/docs/design/client-ui-extensions.md +++ b/docs/design/client-ui-extensions.md @@ -43,7 +43,7 @@ Status: Ready. UiExtensions 是拥有内容状态的 App Server 插件,不是把错误作用域接回 Session 的接线模块。UiResources 的资源属于 Session,不能只在进程表里存一个 Session ID,再另建 Session 关闭观察系统。两者都不读写分支 Timeline,不是 Capability。两者由独立的 UiExtensions 插件装配并可停用;位于 App Server crate 不代表属于协议内核。App Server 负责装配与受保护传输,Web/Desktop 负责界面。将内容与文件 owner 放入 CLI 会让直连 daemon 的客户端依赖另一个常驻客户端,因此不这样放置。 -复用 [PluginManager](plugins/PluginManager.md) 的安装、选择、启停、重载与内容分发。PluginManager 将已经验证的 UI 声明交给内容 owner,不保存客户端面板状态,不复制 UI 目录和资源读取任务。使用 [贡献注册规则](rutis-usage.md#r6-contributions-register-with-their-owner) 管理注册与撤下,不增加插件运行时、依赖图或第二套服务总线。 +复用 [PluginManager](plugins/PluginManager.md) 的安装、选择、启停、重载与内容分发。PluginManager 将选中包的目录与 UI 声明交给 UiExtensions 验证,不保存客户端面板状态,不复制 UI 目录和资源读取任务。使用 [贡献注册规则](rutis-usage.md#r6-contributions-register-with-their-owner) 管理注册与撤下,不增加插件运行时、依赖图或第二套服务总线。 客户端没有 rutis loader 的镜像。它只消费已启用的内容目录,管理面板实例;这里的客户端能力是一个固定接口集合,不是浏览器中的通用依赖注入容器。 @@ -75,7 +75,7 @@ UiExtensions 公开目录只包含当前被选择并启用的内容,不包含 目录的 generation 属于 UI 内容 owner,不等于 rutis 后端代码 generation: - 禁用、移除、选择其他安装副本及显式刷新内容会撤下旧 UI generation。 -- UI 声明解析失败时,由 PluginManager 报告内容诊断并撤下旧注册;已验证声明的快照构建失败,由 UiExtensions 在目录中报告内容错误。不能静默继续展示已被替换的版本,各 owner 只保留自己产生的错误。 +- UiExtensions 在声明解析或快照构建失败时撤下旧注册,并在目录中报告内容错误。不能静默继续展示已被替换的版本,各 owner 只保留自己产生的错误。 - 后端代码重启不自动证明内容变化。面板所需方法不可用时,面板按 §5 进入不可用状态;UI-only 内容不依赖后端 row 是否 Active。 - 后端方法的准入和已接受调用仍使用 [Session 方法契约](contracts/session-boundary.md#a1-method-contributions)。UI generation 不包装成另一层业务请求 generation,不改变原来的调用结算。 @@ -430,7 +430,7 @@ type PreviewMethods = { | 名称 | 范围 | 输入与结果 | | --- | --- | --- | -| `uiExtensions` | process,后端命名服务 | 接受 PluginManager 的已验证内容注册/撤下;提供目录快照及变化观察,不供页面发布内容 | +| `uiExtensions` | process,后端命名服务 | 接收 PluginManager 选中包的注册/撤下,验证 UI 声明和资源路径;提供目录快照及变化观察,不供页面发布内容 | | `uiResources` | Session,后端命名服务 | `publishFile({path, mediaType}) -> ResourceRef`;`withdraw(ref)` 等到读取结束;注册自动归调用者生命周期,调用者不能撤下其他注册 | | `ui.extensions.list` | 已授权客户端的精确只读方法 | `{}` → `{revision, extensions, errors}`;extension 包含插件名、generation 和面板声明,不含 URL;errors 仅含 UiExtensions 自己产生的内容错误且不含绝对路径 | | `ui.extensions.read` | 已授权客户端的精确只读方法(local) | `{generation, path, offset?, limit?}` → `{offset, bytes, total, mediaType, data}`;`data` 为标准 base64;默认 1 MiB、上限 4 MiB;不在 `WEB_MANAGEMENT_METHODS` | diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index ce2a57ab21..af2224c0f6 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -96,8 +96,8 @@ The repository's own TypeScript plugins (`runtime/plugins/*`) get a `dim-plugin. `ui` is an optional manifest member owned by [UiExtensions](../client-ui-extensions.md#附录-a-manifest-绑定). A UI-only package -has kind `ui` and needs no code row. PluginManager forwards the validated -content declaration and stable plugin name to UiExtensions; unsupported versions +has kind `ui` and needs no code row. PluginManager forwards the selected package directory, its UI declaration and +its stable name. UiExtensions validates the declaration and its resource paths; unsupported versions and invalid UI declarations appear as content refusals without stopping the package's backend code or other content. When UiExtensions is absent, `ui` is reported as skipped. Withdrawals use the installed id, as for other content. diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 734b585acb..28715cfbfc 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1348,8 +1348,6 @@ export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceErr /** What a method returning `Err(SessionsError)` throws. */ export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> -/** What a method returning `Err(String)` throws. */ - /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> diff --git a/runtime/fixtures/ui-owner.ts b/runtime/fixtures/ui-owner.ts index 3abb7b5a7b..6ede90cf4f 100644 --- a/runtime/fixtures/ui-owner.ts +++ b/runtime/fixtures/ui-owner.ts @@ -31,7 +31,7 @@ export default definePlugin({ assert.ok(after.presences.every(presence => presence.channel !== 'tui')) } else if (call.method === 'uifixture.detach') { assert.equal(host.detach({connectionId, sessionId}), undefined) - await assert.rejects(extensions.register({plugin, name: plugin, package: {kind: 'unsupported', version: 2}}), /Unsupported UI version 2/) + await assert.rejects(extensions.register({plugin, name: plugin, package: {directory: '.', manifest: {version: 2}}}), /Unsupported UI version 2/) assert.ok((await extensions.plugins({})).includes(plugin)) assert.equal(await extensions.refusal({plugin}), 'Unsupported UI version 2') } else { From 52d7ec38ee8375de0d4d831b9da21308df9f0b0a Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 23:12:23 +0800 Subject: [PATCH 9/9] Resolve UI registration paths from the installed plugin ID --- crates/dim-app-server/src/lib.rs | 4 +- crates/dim-app-server/src/plugin_manager.rs | 19 ++++++---- .../dim-app-server/src/ui_extensions/mod.rs | 38 ++++++++----------- .../tests/transport_flow/ui_host.rs | 9 +++++ docs/design/client-ui-extensions.md | 2 +- .../contracts/process-owner-operations.md | 2 +- docs/design/plugins/PluginManager.md | 4 +- npm/branch-services.d.ts | 8 +--- runtime/fixtures/ui-owner.ts | 7 +++- 9 files changed, 50 insertions(+), 43 deletions(-) diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index e42c1bb5c8..8ec0057f82 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1036,8 +1036,8 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul } None => None, }; - if let Some(home) = plugin_home { - let configuration = ui_extensions::Configuration::new(home.join("ui-cache")); + if let (Some(home), Some(state)) = (plugin_home, &plugins) { + let configuration = ui_extensions::Configuration::new(home.join("ui-cache"), state.clone()); rows.push(register_part( &mut builtins, builder.catalog(), diff --git a/crates/dim-app-server/src/plugin_manager.rs b/crates/dim-app-server/src/plugin_manager.rs index a23b0901ee..aa5cd6bbd5 100644 --- a/crates/dim-app-server/src/plugin_manager.rs +++ b/crates/dim-app-server/src/plugin_manager.rs @@ -188,6 +188,17 @@ pub(crate) struct StartupLayer { } impl State { + pub(crate) fn package_by_id(&self, id: &str) -> Option<(String, PathBuf)> { + let record = self.record.lock().unwrap(); + if let Some(entry) = record.installed(id) { + return Some((entry.name.clone(), entry.dir.clone())); + } + self.defaults + .plugins + .get(id) + .map(|dir| (id.to_owned(), dir.clone())) + } + /// Startup (§3.1), first part: reads `plugins.json` and the default /// configuration file, deletes the copies no entry names (§7), and /// registers the `instanceNames` and process names of the plugins that @@ -859,13 +870,7 @@ impl Owners { if let Err(error) = ui .register(UiExtensionRegistration { plugin: plugin.into(), - name: manifest.name.clone(), - package: manifest.ui.clone().map(|manifest| { - crate::ui_extensions::UiPackage { - directory: dir.to_path_buf(), - manifest, - } - }), + manifest: manifest.ui.clone(), }) .await { diff --git a/crates/dim-app-server/src/ui_extensions/mod.rs b/crates/dim-app-server/src/ui_extensions/mod.rs index 4df7be6960..f30286f9b9 100644 --- a/crates/dim-app-server/src/ui_extensions/mod.rs +++ b/crates/dim-app-server/src/ui_extensions/mod.rs @@ -70,13 +70,15 @@ struct Catalog { pub(crate) struct Configuration { cache: PathBuf, - sources: Mutex>, + plugins: Arc, + sources: Mutex>, revision: AtomicU64, } impl Configuration { - pub fn new(cache: PathBuf) -> Arc { + pub fn new(cache: PathBuf, plugins: Arc) -> Arc { Arc::new(Self { cache, + plugins, sources: Mutex::default(), revision: AtomicU64::new(0), }) @@ -105,15 +107,7 @@ pub struct UiExtensionPlugin { #[serde(deny_unknown_fields)] pub struct UiExtensionRegistration { pub plugin: String, - pub name: String, - pub package: Option, -} - -#[derive(Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct UiPackage { - pub directory: PathBuf, - pub manifest: serde_json::Value, + pub manifest: Option, } #[rutis::service(name = "uiExtensions")] @@ -136,23 +130,24 @@ impl UiExtensions { .map(|error| error.message.clone()) } pub async fn register(&self, request: UiExtensionRegistration) -> Result<(), ResourceError> { - let UiExtensionRegistration { - plugin, - name, - package, - } = request; - let Some(package) = package else { + let UiExtensionRegistration { plugin, manifest } = request; + let Some(manifest) = manifest else { self.withdraw(UiExtensionPlugin { plugin }).await; return Ok(()); }; let _update = self.updating.lock().await; let _operation = self.reads.enter()?; + let (name, directory) = self + .configuration + .plugins + .package_by_id(&plugin) + .ok_or_else(|| ResourceError::invalid("Unknown plugin ID"))?; self.configuration .sources .lock() .unwrap() - .insert(plugin.clone(), (name.clone(), package.clone())); - let prepared = match Package::read(&package.directory, package.manifest) { + .insert(plugin.clone(), manifest.clone()); + let prepared = match Package::read(&directory, manifest) { Ok(Package::Supported { root, panels }) => self .prepare(&name, &root, &panels) .await @@ -525,12 +520,11 @@ impl DynPlugin for UiExtensionsPlugin { .await .map_err(|error| ErrorKind::PluginFailed(error.into()))?; let sources = self.configuration.sources.lock().unwrap().clone(); - for (plugin, (name, package)) in sources { + for (plugin, manifest) in sources { if let Err(error) = service .register(UiExtensionRegistration { plugin: plugin.clone(), - name, - package: Some(package), + manifest: Some(manifest), }) .await { diff --git a/crates/dim-app-server/tests/transport_flow/ui_host.rs b/crates/dim-app-server/tests/transport_flow/ui_host.rs index c107e996db..bd15c45ca3 100644 --- a/crates/dim-app-server/tests/transport_flow/ui_host.rs +++ b/crates/dim-app-server/tests/transport_flow/ui_host.rs @@ -563,6 +563,15 @@ async fn node_ui_operations_use_the_connected_client_and_extension_catalog() { }) .await; let mut client = Client::new_version(&server, false, 3).await; + let source = home.join("ui-fixture"); + std::fs::create_dir_all(source.join("ui")).unwrap(); + std::fs::write(source.join("dim-plugin.json"), r#"{"name":"ui-fixture"}"#).unwrap(); + std::fs::write(source.join("ui/panel.js"), "export default 1").unwrap(); + let installed = client + .rpc("plugin.install", json!({"source":{"path":source}})) + .await; + assert_ok(&installed); + assert_eq!(installed["result"]["id"], "ui-fixture"); let session = attached_session(&mut client).await; for action in ["detach", "release"] { assert_ok( diff --git a/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 7a0f8b73a7..8d7c8782d4 100644 --- a/docs/design/client-ui-extensions.md +++ b/docs/design/client-ui-extensions.md @@ -43,7 +43,7 @@ Status: Ready. UiExtensions 是拥有内容状态的 App Server 插件,不是把错误作用域接回 Session 的接线模块。UiResources 的资源属于 Session,不能只在进程表里存一个 Session ID,再另建 Session 关闭观察系统。两者都不读写分支 Timeline,不是 Capability。两者由独立的 UiExtensions 插件装配并可停用;位于 App Server crate 不代表属于协议内核。App Server 负责装配与受保护传输,Web/Desktop 负责界面。将内容与文件 owner 放入 CLI 会让直连 daemon 的客户端依赖另一个常驻客户端,因此不这样放置。 -复用 [PluginManager](plugins/PluginManager.md) 的安装、选择、启停、重载与内容分发。PluginManager 将选中包的目录与 UI 声明交给 UiExtensions 验证,不保存客户端面板状态,不复制 UI 目录和资源读取任务。使用 [贡献注册规则](rutis-usage.md#r6-contributions-register-with-their-owner) 管理注册与撤下,不增加插件运行时、依赖图或第二套服务总线。 +复用 [PluginManager](plugins/PluginManager.md) 的安装、选择、启停、重载与内容分发。调用方以插件 ID 和 UI 声明注册。UiExtensions 按 ID 从 PluginManager 获取实际安装目录,再验证声明和资源路径,不保存客户端面板状态,不复制 UI 目录和资源读取任务。使用 [贡献注册规则](rutis-usage.md#r6-contributions-register-with-their-owner) 管理注册与撤下,不增加插件运行时、依赖图或第二套服务总线。 客户端没有 rutis loader 的镜像。它只消费已启用的内容目录,管理面板实例;这里的客户端能力是一个固定接口集合,不是浏览器中的通用依赖注入容器。 diff --git a/docs/design/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index af2ade655f..438b92fee1 100644 --- a/docs/design/contracts/process-owner-operations.md +++ b/docs/design/contracts/process-owner-operations.md @@ -27,7 +27,7 @@ The target removes `sessionPermissions`, `selectableModelsHost`, `modelSelection | Session configuration → `providerService` (managed profile) | `configuration(explicit?, cwd?, preferences) → ModelSelection`; `applyPreferences(current, update) → ModelSelection`. Bind the existing Provider operations. | | Session creation/adoption and Collaboration → `providerService` (managed profile) | `prepareStartup(request) → {model, admissionId?}`, `checkStartup(source) → void`, `retainStartup({sessionId, generation, model, admissionId?}) → void`, `releaseStartup({admissionId}) → void`. Reuse the pending startup binding ID. Retain on success for that Session generation; release on failure or caller unload. | | Session creation / worktree management → ManagedWorktrees | `create({source, base?, branch?}) → CreatedWorktreeReply`, `discard(created) → void`, `list({}) → WorktreeView[]`, `pruneSelection({olderThanMs?, keep?, force}) → PruneSelection`, `remove({taskId, force}) → boolean`. Bind the existing operations. Failed Session creation discards the created worktree on its node. | -| PluginManager → UiExtensions | `plugins({}) → string[]`, `refusal({plugin}) → string or null`, `register({plugin, name, package?}) → void`, `withdraw({plugin}) → void`. For registration, `package` contains the plugin directory and its UI manifest. UiExtensions admits the root and panels before publishing the snapshot. | +| PluginManager → UiExtensions | `plugins({}) → string[]`, `refusal({plugin}) → string or null`, `register({plugin, manifest?}) → void`, `withdraw({plugin}) → void`. UiExtensions resolves the package name and installation directory by plugin ID through PluginManager. Any trusted caller can register or withdraw by ID. UiExtensions admits the root and panels before publishing the snapshot. | ### Session use and generation observation diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index af2224c0f6..275a999026 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -96,8 +96,8 @@ The repository's own TypeScript plugins (`runtime/plugins/*`) get a `dim-plugin. `ui` is an optional manifest member owned by [UiExtensions](../client-ui-extensions.md#附录-a-manifest-绑定). A UI-only package -has kind `ui` and needs no code row. PluginManager forwards the selected package directory, its UI declaration and -its stable name. UiExtensions validates the declaration and its resource paths; unsupported versions +has kind `ui` and needs no code row. PluginManager forwards the plugin ID and UI declaration. UiExtensions looks up +the name and installation directory by ID and validates the resource paths; unsupported versions and invalid UI declarations appear as content refusals without stopping the package's backend code or other content. When UiExtensions is absent, `ui` is reported as skipped. Withdrawals use the installed id, as for other content. diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 28715cfbfc..91a26b1847 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1268,15 +1268,9 @@ export type UiExtensionPlugin = { plugin: string } -export type UiPackage = { - directory: string - manifest: import('./plugin.js').BridgeJsonValue -} - export type UiExtensionRegistration = { plugin: string - name: string - package?: UiPackage | null + manifest?: import('./plugin.js').BridgeJsonValue | null } export type ResourceError = { diff --git a/runtime/fixtures/ui-owner.ts b/runtime/fixtures/ui-owner.ts index 6ede90cf4f..163c44123d 100644 --- a/runtime/fixtures/ui-owner.ts +++ b/runtime/fixtures/ui-owner.ts @@ -31,7 +31,12 @@ export default definePlugin({ assert.ok(after.presences.every(presence => presence.channel !== 'tui')) } else if (call.method === 'uifixture.detach') { assert.equal(host.detach({connectionId, sessionId}), undefined) - await assert.rejects(extensions.register({plugin, name: plugin, package: {directory: '.', manifest: {version: 2}}}), /Unsupported UI version 2/) + await assert.rejects(extensions.register({plugin: 'missing-ui-fixture', manifest: {version: 1}}), /Unknown plugin ID/) + await extensions.register({plugin, manifest: { + version: 1, root: 'ui', panels: [{id: 'viewer', title: {default: 'Viewer'}, entry: 'panel.js', placement: 'session-panel', requires: [], methods: []}], + }}) + assert.equal(await extensions.refusal({plugin}), null) + await assert.rejects(extensions.register({plugin, manifest: {version: 2}}), /Unsupported UI version 2/) assert.ok((await extensions.plugins({})).includes(plugin)) assert.equal(await extensions.refusal({plugin}), 'Unsupported UI version 2') } else {