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 e892c17b0b..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(), @@ -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,10 +1438,11 @@ 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"); register::(catalog, None); + catalog.register_shared("uiExtensions"); register::(catalog, Some(SESSION_GROUP)); register::(catalog, None); register::(catalog, None); @@ -1490,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"), @@ -1512,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"), @@ -1522,8 +1520,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..aa5cd6bbd5 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}; @@ -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 @@ -836,7 +847,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 +868,10 @@ 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(), + manifest: manifest.ui.clone(), + }) .await { outcome.refused.push(refused(Kind::Ui, error)); @@ -963,7 +977,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 +1031,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/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/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/crates/dim-app-server/src/ui_extensions/manifest.rs b/crates/dim-app-server/src/ui_extensions/manifest.rs index c1187899dc..beb34baea5 100644 --- a/crates/dim-app-server/src/ui_extensions/manifest.rs +++ b/crates/dim-app-server/src/ui_extensions/manifest.rs @@ -40,11 +40,11 @@ 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 }, - 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 6d06e8cf0c..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), }) @@ -95,23 +97,22 @@ 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 manifest: 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,53 +121,56 @@ 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> { - let Some(package) = package else { - self.withdraw(plugin).await; + pub async fn register(&self, request: UiExtensionRegistration) -> Result<(), ResourceError> { + 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().map_err(|error| error.message)?; + 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.into(), (name.into(), 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()), + .insert(plugin.clone(), manifest.clone()); + let prepared = match Package::read(&directory, 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(); - 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(), - message: message.clone(), + plugin_name: name, + message: message.message.clone(), }, ); } @@ -179,13 +183,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 +200,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, @@ -494,8 +520,14 @@ 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 { - if let Err(error) = service.register(&plugin, &name, Some(&package)).await { + for (plugin, manifest) in sources { + if let Err(error) = service + .register(UiExtensionRegistration { + plugin: plugin.clone(), + manifest: Some(manifest), + }) + .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..162fa7bfb3 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"))?; + 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..bd15c45ca3 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,75 @@ 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 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( + &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"); + } + 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/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..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 | @@ -63,8 +61,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/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 69de4c7b52..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 声明交给内容 owner,不保存客户端面板状态,不复制 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 的镜像。它只消费已启用的内容目录,管理面板实例;这里的客户端能力是一个固定接口集合,不是浏览器中的通用依赖注入容器。 @@ -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/contracts/process-owner-operations.md b/docs/design/contracts/process-owner-operations.md index 3b9d8f234c..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`. Bind the existing catalog methods. | +| 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 ce2a57ab21..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 validated -content declaration and stable plugin name to UiExtensions; 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/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 | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index adadc3b24a..91a26b1847 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1264,6 +1264,28 @@ export interface ListenAddresses { read(): Promise } +export type UiExtensionPlugin = { + plugin: string +} + +export type UiExtensionRegistration = { + plugin: string + manifest?: import('./plugin.js').BridgeJsonValue | null +} + +export type ResourceError = { + code: string + message: string +} + +export interface UiExtensions { + plugins(request: Empty): Promise + refusal(request: UiExtensionPlugin): Promise + /** @throws {ResourceErrorThrown} */ + register(request: UiExtensionRegistration): Promise + withdraw(request: UiExtensionPlugin): Promise +} + export type PublishFile = { /** Absolute host path inside an already authorized FileStorage root. */ path: string @@ -1275,11 +1297,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 @@ -1373,5 +1390,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..2177eaf8e9 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}): void; + release(request: {connectionId: string}): void; + finished(request: {connectionId: string}): void; +} + 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..163c44123d --- /dev/null +++ b/runtime/fixtures/ui-owner.ts @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict' +import { definePlugin } from '@arcships/rutis' +import type { ManagementMethods, Services, UiExtensions, UiHost } from '../../npm/plugin.js' + +export default definePlugin({ + name: 'UiOwnerFixture', + provides: {}, + 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' + 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: '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 { + assert.equal(host.release({connectionId}), undefined) + await extensions.withdraw({plugin}) + assert.equal(await extensions.refusal({plugin}), null) + assert.ok(!(await extensions.plugins({})).includes(plugin)) + } + return {kind: 'value', value: true} + }) + }, +})