You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/12 13:26:58 UTC

(maka) branch feat/runtime-host-rust updated: fix: integrate TUI startup trust and preserve activation errors

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/feat/runtime-host-rust by this push:
     new 6786d3917c fix: integrate TUI startup trust and preserve activation errors
6786d3917c is described below

commit 6786d3917c197028f6cb5ef06e98a459ffdd6fc8
Author: Wang <m4...@gmail.com>
AuthorDate: Mon Oct 12 21:26:45 2026 +0800

    fix: integrate TUI startup trust and preserve activation errors
    
    Keep first-install confirmation in the terminal UI and carry original Host failures through startup and terminal restoration. Enable soft wrapping for the TUI plugin URL editor so hidden editor mounts cannot prevent activation.
---
 platform/host-runtime/src/application/owner.rs     |  10 +-
 .../src/application/transport/catalogue.rs         |  16 +-
 .../src/application/transport/endpoints.rs         |  32 ++-
 platform/render-terminal/src/application.rs        |   9 +-
 platform/render-terminal/src/application/run.rs    |  27 +-
 platform/render-terminal/src/lib.rs                |   1 +
 platform/render-terminal/src/startup.rs            | 318 +++++++++++++++++++++
 platform/transport/src/connections.rs              |  13 +-
 platform/transport/src/transport/process.rs        |  77 ++++-
 platform/transport/tests/owners.rs                 |   3 +
 plugins/shared/deployment-import.ts                |   2 +-
 products/maka/cli/README.md                        |   2 +
 products/maka/cli/README.zh-CN.md                  |   2 +
 products/maka/cli/notices.json                     |   2 +-
 products/maka/cli/src/application.rs               |  21 +-
 .../maka/cli/src/application/product/launch.rs     |  60 ++--
 .../tests/integration/terminal/bundled_product.rs  | 112 ++++++++
 17 files changed, 643 insertions(+), 64 deletions(-)

diff --git a/platform/host-runtime/src/application/owner.rs b/platform/host-runtime/src/application/owner.rs
index 4cab373b54..ed8667fb86 100644
--- a/platform/host-runtime/src/application/owner.rs
+++ b/platform/host-runtime/src/application/owner.rs
@@ -438,7 +438,15 @@ impl Owner {
         Ok(true)
     }
     fn fail_initialization(&mut self, id: InstanceId, error: String) {
-        self.startup_error.get_or_insert(error);
+        let path = self
+            .runtime
+            .desired()
+            .instances()
+            .get(&id)
+            .map(|instance| instance.path.join("/"))
+            .unwrap_or_else(|| format!("{id:?}"));
+        self.startup_error
+            .get_or_insert_with(|| diagnostic(&format!("plugin {path}: {error}")));
         self.initialization_failures.insert(id.clone());
         if let Some(activation) = self.activations.get(&id) {
             for retired in self.runtime.retire(activation).expect("owned activation") {
diff --git a/platform/host-runtime/src/application/transport/catalogue.rs b/platform/host-runtime/src/application/transport/catalogue.rs
index b9fe31c1d3..8a810f9b00 100644
--- a/platform/host-runtime/src/application/transport/catalogue.rs
+++ b/platform/host-runtime/src/application/transport/catalogue.rs
@@ -44,6 +44,8 @@ pub struct Description {
 #[serde(deny_unknown_fields)]
 pub struct Catalogue {
     endpoints: BTreeMap<String, Description>,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    startup_error: Option<String>,
 }
 #[derive(Clone, Debug)]
 pub struct Selection {
@@ -59,8 +61,14 @@ impl Catalogue {
     pub fn captured(endpoints: &Endpoints) -> Self {
         Self {
             endpoints: endpoints.descriptions(),
+            startup_error: endpoints.startup_error.clone(),
         }
     }
+    /// Diagnostic only; endpoint registration and admission stay independent.
+    pub fn startup_error(&self) -> Option<&str> {
+        self.startup_error.as_deref()
+    }
+
     pub fn epochs(&self) -> BTreeMap<String, Option<Uuid>> {
         self.endpoints
             .iter()
@@ -97,7 +105,13 @@ impl Catalogue {
         Ok((catalogue, reader.inner))
     }
     pub fn validate(&self) -> Result<()> {
-        if self.endpoints.is_empty() || self.endpoints.len() > 128 {
+        if self.endpoints.is_empty()
+            || self.endpoints.len() > 128
+            || self
+                .startup_error
+                .as_ref()
+                .is_some_and(|error| error.len() > 64 * 1024)
+        {
             return Err("invalid Host endpoint catalogue".into());
         }
         for (name, description) in &self.endpoints {
diff --git a/platform/host-runtime/src/application/transport/endpoints.rs b/platform/host-runtime/src/application/transport/endpoints.rs
index 18983303b9..9c64f0005e 100644
--- a/platform/host-runtime/src/application/transport/endpoints.rs
+++ b/platform/host-runtime/src/application/transport/endpoints.rs
@@ -56,7 +56,10 @@ impl HostEndpoint {
     }
 }
 #[derive(Clone)]
-pub struct Endpoints(BTreeMap<String, Entry>);
+pub struct Endpoints {
+    entries: BTreeMap<String, Entry>,
+    pub(super) startup_error: Option<String>,
+}
 #[derive(Clone)]
 enum Entry {
     Ready(Endpoint),
@@ -64,12 +67,13 @@ enum Entry {
 }
 impl From<BTreeMap<String, Endpoint>> for Endpoints {
     fn from(endpoints: BTreeMap<String, Endpoint>) -> Self {
-        Self(
-            endpoints
+        Self {
+            entries: endpoints
                 .into_iter()
                 .map(|(name, endpoint)| (name, Entry::Ready(endpoint)))
                 .collect(),
-        )
+            startup_error: None,
+        }
     }
 }
 impl Endpoints {
@@ -103,12 +107,16 @@ impl Endpoints {
                 .await?;
             endpoints.insert(name.clone(), captured, selection.grant.clone())?;
         }
+        endpoints.startup_error = client.snapshot().startup_error;
         endpoints.validate()?;
         Ok(endpoints)
     }
 
     fn empty() -> Self {
-        Self(BTreeMap::new())
+        Self {
+            entries: BTreeMap::new(),
+            startup_error: None,
+        }
     }
     fn insert(&mut self, name: String, import: CapturedImport, grant: Grant) -> Result<()> {
         let entry = match import {
@@ -127,16 +135,16 @@ impl Endpoints {
                 })
             }
         };
-        if self.0.insert(name, entry).is_some() {
+        if self.entries.insert(name, entry).is_some() {
             return Err("duplicate Application endpoint".into());
         }
         Ok(())
     }
     pub(super) fn validate(&self) -> Result<()> {
-        if self.0.is_empty()
-            || self.0.len() > 128
+        if self.entries.is_empty()
+            || self.entries.len() > 128
             || self
-                .0
+                .entries
                 .keys()
                 .any(|name| name.is_empty() || name.len() > 256)
         {
@@ -145,13 +153,13 @@ impl Endpoints {
         Ok(())
     }
     pub(super) fn get(&self, name: &str) -> Option<&Endpoint> {
-        match self.0.get(name)? {
+        match self.entries.get(name)? {
             Entry::Ready(endpoint) => Some(endpoint),
             Entry::Unavailable(_) => None,
         }
     }
     pub fn epochs(&self) -> BTreeMap<String, Option<uuid::Uuid>> {
-        self.0
+        self.entries
             .iter()
             .map(|(name, entry)| {
                 (
@@ -165,7 +173,7 @@ impl Endpoints {
             .collect()
     }
     pub(super) fn descriptions(&self) -> BTreeMap<String, Description> {
-        self.0
+        self.entries
             .iter()
             .map(|(name, entry)| {
                 (
diff --git a/platform/render-terminal/src/application.rs b/platform/render-terminal/src/application.rs
index d4bb8f5721..ac13f0396c 100644
--- a/platform/render-terminal/src/application.rs
+++ b/platform/render-terminal/src/application.rs
@@ -399,9 +399,12 @@ impl Presenter {
         let root = match application.mount_bootstrap(props) {
             Ok(root) => root,
             Err(error) => {
-                if let Some(initial) = application.deployment_status().error {
-                    eprintln!("application activation failed: {}", sanitize(&initial));
-                }
+                let error = match application.deployment_status().error {
+                    Some(initial) => {
+                        Error::Invalid(format!("application activation failed: {initial}; {error}"))
+                    }
+                    None => error,
+                };
                 // This presenter has not created a terminal or renderer resources.
                 // Retain the foreground application until its actual modules close.
                 let mut reported = std::collections::BTreeSet::new();
diff --git a/platform/render-terminal/src/application/run.rs b/platform/render-terminal/src/application/run.rs
index 45c30559c7..1495845fdd 100644
--- a/platform/render-terminal/src/application/run.rs
+++ b/platform/render-terminal/src/application/run.rs
@@ -29,6 +29,7 @@ use std::{
 /// Run on the foreground thread inside a multithreaded Tokio runtime.
 /// Accepted service workers remain owned after the terminal surface closes.
 /// 在前台线程运行;关闭界面后仍等待真实服务执行与资源回执。
+#[allow(clippy::too_many_arguments)]
 pub fn run(
     store: std::sync::Arc<maka_event_log::EventLog>,
     source: maka_plugin_core::deployment::DeploymentRef,
@@ -36,6 +37,8 @@ pub fn run(
     scheduler: tokio::runtime::Handle,
     mut updates: maka_transport::Updates,
     execution: maka_ui_runtime::ExecutionOptions,
+    startup: Option<crate::startup::Startup>,
+    mut startup_errors: Vec<String>,
 ) -> Result<(), String> {
     let mut presenter = scheduler
         .block_on(Presenter::start_from_store(
@@ -48,15 +51,35 @@ pub fn run(
             execution,
         ))
         .map_err(|e| sanitize(&e.to_string()))?;
-    let mut guard = terminal::Guard::new();
+    let (mut guard, previous_screen) = match startup {
+        Some(startup) => (startup.guard, Some(startup.screen)),
+        None => (terminal::Guard::new(), None),
+    };
     let mut failure = None;
-    let mut screen = match guard.setup("an interactive terminal is required") {
+    let mut screen = match previous_screen
+        .map_or_else(|| guard.setup("an interactive terminal is required"), Ok)
+    {
         Ok(screen) => Some(screen),
         Err(error) => {
             failure = Some(sanitize(&error.to_string()));
             None
         }
     };
+    if startup_errors.is_empty()
+        && let Some(error) = presenter.deployment_status().error
+    {
+        startup_errors.push(error);
+    }
+    if !startup_errors.is_empty()
+        && let Some(screen) = screen.as_mut()
+    {
+        let diagnostic = startup_errors.join("\n\n");
+        match crate::startup::issues(screen, &diagnostic) {
+            Ok(true) => {}
+            Ok(false) => failure = Some(diagnostic),
+            Err(error) => failure = Some(format!("{diagnostic}\n{error}")),
+        }
+    }
     let mut reported = BTreeSet::new();
     let mut exit_key = ExitKey::default();
     loop {
diff --git a/platform/render-terminal/src/lib.rs b/platform/render-terminal/src/lib.rs
index 910b518145..ac2c6b5358 100644
--- a/platform/render-terminal/src/lib.rs
+++ b/platform/render-terminal/src/lib.rs
@@ -22,4 +22,5 @@
 pub mod application;
 mod editor;
 pub mod markdown;
+pub mod startup;
 mod terminal;
diff --git a/platform/render-terminal/src/startup.rs b/platform/render-terminal/src/startup.rs
new file mode 100644
index 0000000000..ce014253be
--- /dev/null
+++ b/platform/render-terminal/src/startup.rs
@@ -0,0 +1,318 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! Trusted first-install UI, before any product modules or workspace tools run.
+use crate::terminal::{self, Guard, Screen};
+use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
+use ratatui::{
+    layout::{Constraint, Layout},
+    style::{Color, Modifier, Style},
+    text::{Line, Span},
+    widgets::{Block, Padding, Paragraph, Wrap},
+};
+use std::{io, path::Path};
+
+/// The same alternate screen and terminal guard pass into the product presenter.
+pub struct Startup {
+    pub(crate) screen: Screen,
+    pub(crate) guard: Guard,
+}
+impl Startup {
+    pub fn confirm(workspace: &Path, locale: &str, light: bool) -> io::Result<Option<Self>> {
+        let mut guard = Guard::new();
+        let screen = guard.setup("an interactive terminal is required")?;
+        let mut startup = Self { screen, guard };
+        let copy = Copy::for_locale(locale);
+        let path = crate::application::sanitize(&workspace.display().to_string());
+        let mut accept = false;
+        loop {
+            terminal::draw(&mut startup.screen, |frame| {
+                paint(frame, &copy, &path, light, accept, false);
+            })?;
+            match choice(event::read()?, &mut accept) {
+                Some(true) => {
+                    terminal::draw(&mut startup.screen, |frame| {
+                        paint(frame, &copy, &path, light, accept, true);
+                    })?;
+                    return Ok(Some(startup));
+                }
+                Some(false) => {
+                    startup.guard.finish()?;
+                    return Ok(None);
+                }
+                None => {}
+            }
+        }
+    }
+}
+/// Keep startup failures visible even when a recovery component can mount.
+/// This owns no plugin work; the caller retains and drains the original presenter.
+pub(crate) fn issues(screen: &mut Screen, message: &str) -> io::Result<bool> {
+    let message = crate::application::sanitize(message);
+    let mut scroll = 0u16;
+    loop {
+        terminal::draw(screen, |frame| {
+            let area = frame.area();
+            frame.render_widget(
+                Block::default().style(
+                    Style::default()
+                        .bg(Color::Rgb(23, 23, 26))
+                        .fg(Color::Rgb(235, 235, 240)),
+                ),
+                area,
+            );
+            let body = Block::default().padding(Padding::uniform(2)).inner(area);
+            let chunks = Layout::vertical([
+                Constraint::Length(2),
+                Constraint::Min(1),
+                Constraint::Length(2),
+            ])
+            .split(body);
+            frame.render_widget(
+                Paragraph::new("Maka · Startup failed").style(
+                    Style::default()
+                        .fg(Color::Rgb(255, 160, 140))
+                        .add_modifier(Modifier::BOLD),
+                ),
+                chunks[0],
+            );
+            frame.render_widget(
+                Paragraph::new(message.as_str())
+                    .wrap(Wrap { trim: false })
+                    .scroll((scroll, 0)),
+                chunks[1],
+            );
+            frame.render_widget(
+                Paragraph::new("Enter: open recovery interface · Ctrl-Q / Esc: exit · ↑ ↓: scroll")
+                    .wrap(Wrap { trim: false }),
+                chunks[2],
+            );
+        })?;
+        let Event::Key(key) = event::read()? else {
+            continue;
+        };
+        if key.kind != KeyEventKind::Press {
+            continue;
+        }
+        match key.code {
+            KeyCode::Enter => return Ok(true),
+            KeyCode::Esc => return Ok(false),
+            KeyCode::Char('c' | 'q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
+                return Ok(false);
+            }
+            KeyCode::Down => {
+                scroll = scroll
+                    .saturating_add(1)
+                    .min(message.chars().count().min(u16::MAX as usize) as u16)
+            }
+            KeyCode::Up => scroll = scroll.saturating_sub(1),
+            _ => {}
+        }
+    }
+}
+
+fn choice(event: Event, accept: &mut bool) -> Option<bool> {
+    let Event::Key(key) = event else { return None };
+    if key.kind != KeyEventKind::Press {
+        return None;
+    }
+    if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('c' | 'q'))
+    {
+        return Some(false);
+    }
+    if key
+        .modifiers
+        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
+    {
+        return None;
+    }
+    match key.code {
+        KeyCode::Tab
+        | KeyCode::BackTab
+        | KeyCode::Left
+        | KeyCode::Right
+        | KeyCode::Up
+        | KeyCode::Down => {
+            *accept = !*accept;
+            None
+        }
+        KeyCode::Char('y' | 'Y') => Some(true),
+        KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(false),
+        KeyCode::Enter => Some(*accept),
+        _ => None,
+    }
+}
+struct Copy {
+    title: &'static str,
+    body: &'static str,
+    accept: &'static str,
+    cancel: &'static str,
+    keys: &'static str,
+    opening: &'static str,
+}
+impl Copy {
+    fn for_locale(locale: &str) -> Self {
+        let language = locale.to_ascii_lowercase();
+        if language.starts_with("zh") {
+            if ["hant", "tw", "hk", "mo"]
+                .iter()
+                .any(|part| language.contains(part))
+            {
+                Self {
+                    title: "信任此工作目錄?",
+                    body: "允許修改此目錄中的檔案並執行沙箱命令。命令可以讀取目錄外的檔案,但網路存取已停用。專案和使用者技能目錄將啟用。",
+                    accept: "信任並繼續",
+                    cancel: "退出",
+                    keys: "← → / Tab 選擇 · Enter 確認 · Esc 退出",
+                    opening: "正在初始化產品…",
+                }
+            } else {
+                Self {
+                    title: "信任此工作目录?",
+                    body: "允许修改此目录中的文件并执行沙箱命令。命令可以读取目录外的文件,但网络访问已禁用。项目和用户技能目录将启用。",
+                    accept: "信任并继续",
+                    cancel: "退出",
+                    keys: "← → / Tab 选择 · Enter 确认 · Esc 退出",
+                    opening: "正在初始化产品…",
+                }
+            }
+        } else {
+            Self {
+                title: "Trust this workspace?",
+                body: "Allow file changes in this directory and sandboxed commands. Commands may read files outside it; their network access is disabled. Project and user skill directories will be enabled.",
+                accept: "Trust and continue",
+                cancel: "Exit",
+                keys: "← → / Tab select · Enter confirm · Esc exit",
+                opening: "Initializing product…",
+            }
+        }
+    }
+}
+fn paint(
+    frame: &mut ratatui::Frame<'_>,
+    copy: &Copy,
+    path: &str,
+    light: bool,
+    accept: bool,
+    opening: bool,
+) {
+    let (background, foreground, muted, accent) = if light {
+        (
+            Color::Rgb(250, 250, 250),
+            Color::Rgb(25, 25, 28),
+            Color::Rgb(90, 90, 100),
+            Color::Rgb(30, 95, 170),
+        )
+    } else {
+        (
+            Color::Rgb(23, 23, 26),
+            Color::Rgb(235, 235, 240),
+            Color::Rgb(160, 160, 170),
+            Color::Rgb(110, 180, 250),
+        )
+    };
+    let area = frame.area();
+    frame.render_widget(
+        Block::default().style(Style::default().bg(background).fg(foreground)),
+        area,
+    );
+    let width = area.width.min(84);
+    let body = ratatui::layout::Rect {
+        x: area.x + (area.width - width) / 2,
+        y: area.y,
+        width,
+        height: area.height,
+    };
+    let body = Block::default().padding(Padding::uniform(2)).inner(body);
+    let chunks = Layout::vertical([
+        Constraint::Length(2),
+        Constraint::Min(1),
+        Constraint::Length(3),
+    ])
+    .split(body);
+    frame.render_widget(
+        Paragraph::new("Maka").style(Style::default().fg(accent).add_modifier(Modifier::BOLD)),
+        chunks[0],
+    );
+    let text = vec![
+        Line::from(Span::styled(
+            copy.title,
+            Style::default().add_modifier(Modifier::BOLD),
+        )),
+        Line::from(""),
+        Line::from(path),
+        Line::from(""),
+        Line::from(Span::styled(copy.body, Style::default().fg(muted))),
+    ];
+    frame.render_widget(Paragraph::new(text).wrap(Wrap { trim: false }), chunks[1]);
+    let selected = Style::default()
+        .bg(accent)
+        .fg(background)
+        .add_modifier(Modifier::BOLD);
+    let actions = if opening {
+        vec![Line::from(Span::styled(
+            copy.opening,
+            Style::default().fg(accent),
+        ))]
+    } else {
+        vec![
+            Line::from(vec![
+                Span::styled(
+                    format!(" {} ", copy.accept),
+                    if accept { selected } else { Style::default() },
+                ),
+                Span::raw("   "),
+                Span::styled(
+                    format!(" {} ", copy.cancel),
+                    if !accept { selected } else { Style::default() },
+                ),
+            ]),
+            Line::from(""),
+            Line::from(Span::styled(copy.keys, Style::default().fg(muted))),
+        ]
+    };
+    frame.render_widget(Paragraph::new(actions), chunks[2]);
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crossterm::event::KeyEvent;
+    #[test]
+    fn trust_requires_explicit_selection_and_ignores_paste_and_releases() {
+        let mut accept = false;
+        let key = |code| Event::Key(KeyEvent::new(code, KeyModifiers::NONE));
+        assert_eq!(choice(Event::Paste("y\n".into()), &mut accept), None);
+        assert_eq!(choice(key(KeyCode::Enter), &mut accept), Some(false));
+        assert_eq!(choice(key(KeyCode::Tab), &mut accept), None);
+        assert_eq!(choice(key(KeyCode::Enter), &mut accept), Some(true));
+        assert_eq!(
+            choice(
+                Event::Key(KeyEvent::new_with_kind(
+                    KeyCode::Char('y'),
+                    KeyModifiers::NONE,
+                    KeyEventKind::Release
+                )),
+                &mut accept
+            ),
+            None
+        );
+        assert_eq!(choice(key(KeyCode::Esc), &mut accept), Some(false));
+    }
+}
diff --git a/platform/transport/src/connections.rs b/platform/transport/src/connections.rs
index 95f3b42719..4cae3d94c2 100644
--- a/platform/transport/src/connections.rs
+++ b/platform/transport/src/connections.rs
@@ -197,6 +197,7 @@ pub struct Connections {
     prepared: Vec<PreparedHost>,
     hosts: Vec<OwnedHost>,
     registrations: Vec<RemoteService>,
+    startup_errors: Vec<String>,
     phase: Phase,
 }
 impl Connections {
@@ -303,6 +304,7 @@ impl Connections {
             prepared,
             hosts: Vec::new(),
             registrations: Vec::new(),
+            startup_errors: Vec::new(),
             phase: Phase::Prepared,
         })
     }
@@ -323,7 +325,12 @@ impl Connections {
             let host = prepared.configuration;
             let catalogue = self
                 .start_selected(host.clone(), prepared.consumers, self.source.clone())
-                .await?;
+                .await
+                .map_err(|error| format!("Host {}: {error}", host.name))?;
+            if let Some(error) = catalogue.startup_error() {
+                self.startup_errors
+                    .push(format!("Host {}: {error}", host.name));
+            }
             let owned = self.hosts.last_mut().unwrap();
             catalogue.check_names(host.endpoints.keys())?;
             owned.epochs = catalogue.epochs();
@@ -505,6 +512,10 @@ impl Connections {
     pub fn source(&self) -> &DeploymentRef {
         &self.source
     }
+    pub fn startup_errors(&self) -> &[String] {
+        &self.startup_errors
+    }
+
     pub fn registrations(&self) -> Vec<RemoteService> {
         self.registrations.clone()
     }
diff --git a/platform/transport/src/transport/process.rs b/platform/transport/src/transport/process.rs
index 0bfd4ab5e9..5296cfaf4a 100644
--- a/platform/transport/src/transport/process.rs
+++ b/platform/transport/src/transport/process.rs
@@ -105,6 +105,8 @@ enum Event {
     },
     Closed {
         nonce: Uuid,
+        #[serde(default, skip_serializing_if = "Option::is_none")]
+        error: Option<String>,
     },
     Captured {
         nonce: Uuid,
@@ -178,9 +180,11 @@ impl<R: AsyncRead + Unpin, W: AsyncWrite + Unpin> Control<R, W> {
                 self.phase = Phase::Started;
                 Ok(catalogue)
             }
-            Event::Closed { nonce } if nonce == self.nonce => {
+            Event::Closed { nonce, error } if nonce == self.nonce => {
                 self.phase = Phase::Closed;
-                Err("Host closed before publishing its original registrations".into())
+                Err(error.unwrap_or_else(|| {
+                    "Host closed before publishing its original registrations".into()
+                }))
             }
             _ => Err("Host control did not publish its original registrations".into()),
         }
@@ -325,7 +329,7 @@ impl<R: AsyncRead + Unpin, W: AsyncWrite + Unpin> Control<R, W> {
                 }
             };
             match event {
-                Event::Closed { nonce } if nonce == self.nonce => {
+                Event::Closed { nonce, .. } if nonce == self.nonce => {
                     self.phase = Phase::Closed;
                     return Ok(());
                 }
@@ -402,6 +406,7 @@ pub async fn serve(
                 &mut output,
                 &Event::Closed {
                     nonce: bootstrap.nonce,
+                    error: Some(startup_diagnostic(&error)),
                 },
             )
             .await?;
@@ -533,6 +538,7 @@ pub async fn serve(
         &mut output,
         &Event::Closed {
             nonce: bootstrap.nonce,
+            error: result.as_ref().err().map(|error| startup_diagnostic(error)),
         },
     )
     .await?;
@@ -544,6 +550,10 @@ pub async fn serve(
         .map_err(|e| e.to_string())?;
     result
 }
+fn startup_diagnostic(error: &str) -> String {
+    // At most 64 KiB before JSON escaping, including non-ASCII diagnostics.
+    error.chars().take(16 * 1024).collect()
+}
 fn capture_reply(nonce: Uuid, result: Result<Catalogue>) -> Event {
     let event = Event::Captured { nonce, result };
     match wire::encode_bounded(&event, wire::FRAME_LIMIT) {
@@ -616,7 +626,7 @@ mod tests {
             )
             .await
             .unwrap();
-            wire::write(&mut child_writer, &Event::Closed { nonce })
+            wire::write(&mut child_writer, &Event::Closed { nonce, error: None })
                 .await
                 .unwrap();
         });
@@ -635,6 +645,65 @@ mod tests {
         peer.await.unwrap();
     }
 
+    #[tokio::test]
+    async fn failed_bootstrap_returns_original_error_and_confirms_cleanup() {
+        let nonce = Uuid::new_v4();
+        let consumer = InstanceId(vec![Uuid::new_v4()]);
+        let bootstrap = Bootstrap {
+            root: "/unused/host".into(),
+            state_domain: None,
+            deployment: Uuid::new_v4(),
+            namespaces: RootNamespaces {
+                ownership: "/unused/owners".into(),
+                control: "/unused/control".into(),
+            },
+            source: DeploymentRef {
+                state_domain: "a".repeat(64),
+                deployment: Uuid::new_v4(),
+                revision: 1,
+            },
+            consumers: [consumer.clone()].into(),
+            endpoints: [(
+                "agent".into(),
+                HostEndpoint {
+                    consumer,
+                    import: "agent".into(),
+                    grant: maka_host_runtime::application::transport::Grant {
+                        methods: ["read".into()].into(),
+                        recovery: false,
+                    },
+                },
+            )]
+            .into(),
+            native: vec![],
+            address: "/unused/address".into(),
+            nonce,
+        };
+        let (writer, child_reader) = tokio::io::duplex(4096);
+        let (mut child_writer, reader) = tokio::io::duplex(4096);
+        let mut control = Control::new(reader, writer, nonce).unwrap();
+        let peer = tokio::spawn(async move {
+            let mut reader = wire::Reader::new(child_reader);
+            assert_eq!(reader.read::<Bootstrap>().await.unwrap().nonce, nonce);
+            wire::write(
+                &mut child_writer,
+                &Event::Closed {
+                    nonce,
+                    error: Some("original Host State Root identity changed".into()),
+                },
+            )
+            .await
+            .unwrap();
+        });
+        assert_eq!(
+            control.start(&bootstrap).await.unwrap_err(),
+            "original Host State Root identity changed"
+        );
+        assert!(control.phase == Phase::Closed);
+        control.close().await.unwrap();
+        peer.await.unwrap();
+    }
+
     #[test]
     fn oversized_capture_is_a_bounded_error_acknowledgement() {
         let contract = serde_json::json!({
diff --git a/platform/transport/tests/owners.rs b/platform/transport/tests/owners.rs
index 6aa1fe3082..c716645510 100644
--- a/platform/transport/tests/owners.rs
+++ b/platform/transport/tests/owners.rs
@@ -371,6 +371,9 @@ Some(maka_host_js::factory(Default::default())),).await.unwrap();
         connections.start().await.unwrap();
         assert_eq!(connections.registrations().len(), 1);
         assert_eq!(connections.registrations()[0].target.export, "Receipts");
+        assert_eq!(connections.startup_errors().len(), 1);
+        assert!(connections.startup_errors()[0].contains("plugin business:"));
+        assert!(connections.startup_errors()[0].contains("business initializer rejected"));
         assert_eq!(RootOwner::open(&root, &namespaces).err().unwrap().kind(), std::io::ErrorKind::WouldBlock);
         connections.close().await.unwrap();
         store.shutdown().await.unwrap();
diff --git a/plugins/shared/deployment-import.ts b/plugins/shared/deployment-import.ts
index 9ea0a4e2c3..41a27c81f7 100644
--- a/plugins/shared/deployment-import.ts
+++ b/plugins/shared/deployment-import.ts
@@ -159,7 +159,7 @@ export function importView<N extends Node>(
                   readOnly: busy || !!confirmation,
                   disabled: false,
                   autoFocus: false,
-                  softWrap: false,
+                  softWrap: presentation.target === 'tui',
                   terminalRows: { min: 1, max: 2 },
                   submit: 'primary_enter',
                   command: null,
diff --git a/products/maka/cli/README.md b/products/maka/cli/README.md
index 7b3f3fc7a5..3965e4f149 100644
--- a/products/maka/cli/README.md
+++ b/products/maka/cli/README.md
@@ -27,6 +27,8 @@ From the repository root, run `just run` or `just run --help`. Development build
 
 [Source](src/main.rs) · [Cargo manifest](Cargo.toml)
 
+The first installation asks for workspace trust inside the TUI, before starting the Host or enabling project skills and tools. Tab or the arrow keys select an action; Enter confirms and Esc exits. The initial selection is Exit. Confirmation keeps the same terminal screen while the product initializes. Reopening uses the saved installation without asking again.
+
 ## Product recovery and URL installation
 
 Close the product UI and its local Host before changing an owned Root from the CLI. Both commands default to `~/.maka/application`; select another installation with `--root DIRECTORY`.
diff --git a/products/maka/cli/README.zh-CN.md b/products/maka/cli/README.zh-CN.md
index 0cd3fa4028..1b7c2f78ab 100644
--- a/products/maka/cli/README.zh-CN.md
+++ b/products/maka/cli/README.zh-CN.md
@@ -27,6 +27,8 @@
 
 [源码](src/main.rs) · [Cargo 配置](Cargo.toml)
 
+首次安装会在 TUI 内确认工作目录信任,然后才启动 Host、启用项目技能与工具。Tab 或方向键选择,Enter 确认,Esc 退出;默认选中退出。确认后在同一终端画面中初始化并进入产品。再次打开使用已保存的安装,不重复询问。
+
 ## 产品恢复与 URL 安装
 
 通过 CLI 修改已有 Root 前,先关闭该产品的 UI 和本地 Host。两个命令默认使用 `~/.maka/application`;可用 `--root DIRECTORY` 选择其他安装。
diff --git a/products/maka/cli/notices.json b/products/maka/cli/notices.json
index c119fac655..efbcffa422 100644
--- a/products/maka/cli/notices.json
+++ b/products/maka/cli/notices.json
@@ -272,7 +272,7 @@
     "plugins/shared/contracts.ts": "ad8c7048b6c5eb5354c318f4ad9cfe26a7c6534e34d1f4fefb7c3e7b1c0aef08",
     "plugins/shared/conversation-search.ts": "57c796ec95df84904a00d9d95a2b8378c410df5ce530f012273ffb0106ed2ab8",
     "plugins/shared/deployment-document.ts": "0fd08cd83442f4300d8f4f6cadf18fada02f40bf46c523e93f99541a5319e0da",
-    "plugins/shared/deployment-import.ts": "7c3398dc16017ccae7d0aec82bd06b4782f5650e7b806428826b52cf0a7ba7ab",
+    "plugins/shared/deployment-import.ts": "ad1cd8550e36bb203f54de4540154a9c1a3dd7e3c8740c4b81d18e24a3d90659",
     "plugins/shared/drafts.ts": "0f0defa0085af58539a7deaabe09450e3f3effdb9894e0e745f2aab79cb8bf5d",
     "plugins/shared/instance-settings.ts": "5b5bad8f3aabf6daa7aa696f72dba20337dbcdf70266ee0d761cea1e836280be",
     "plugins/shared/locale.ts": "17d38d161cfc6b7f3020a02471d1dc1da5ef9536377dabd996bfc415903c4df4",
diff --git a/products/maka/cli/src/application.rs b/products/maka/cli/src/application.rs
index 57dbd73912..c248a948b9 100644
--- a/products/maka/cli/src/application.rs
+++ b/products/maka/cli/src/application.rs
@@ -207,7 +207,7 @@ impl Command {
                     .transpose()?
                     .unwrap_or_default();
                 let store = Arc::new(open_store(args.root).await?);
-                run_tui(store, args.deployment, configuration).await?;
+                run_tui(store, args.deployment, configuration, None).await?;
             }
         }
         Ok(())
@@ -287,6 +287,7 @@ async fn run_tui(
     store: Arc<maka_event_log::EventLog>,
     deployment: uuid::Uuid,
     configuration: maka_transport::Configuration,
+    startup: Option<maka_render_terminal::startup::Startup>,
 ) -> Result<(), HostError> {
     // Keep the foreground VM on one dedicated blocking owner, with
     // no deeply nested CLI async stack under V8 initialization.
@@ -330,6 +331,7 @@ async fn run_tui(
         store.drain().await;
         return Err(error.into());
     }
+    let startup_errors = connections.startup_errors().to_vec();
     let source = connections.source().clone();
     let registrations = connections.registrations();
     let foreground_store = store.clone();
@@ -347,6 +349,7 @@ async fn run_tui(
             return Err(error.into());
         }
     };
+    let terminal_errors = startup_errors.clone();
     let result = tokio::task::spawn_blocking(move || -> Result<(), HostError> {
         maka_render_terminal::application::run(
             foreground_store,
@@ -355,6 +358,8 @@ async fn run_tui(
             scheduler,
             updates,
             maka_ui_js::execution(Default::default()),
+            startup,
+            terminal_errors,
         )
         .map_err(Into::into)
     })
@@ -367,6 +372,16 @@ async fn run_tui(
     }
     connections.lock().await.drain().await;
     store.drain().await;
-    result??;
-    Ok(())
+    match result? {
+        Ok(()) => Ok(()),
+        Err(error)
+            if startup_errors.is_empty()
+                || startup_errors
+                    .iter()
+                    .all(|cause| error.to_string().contains(cause)) =>
+        {
+            Err(error)
+        }
+        Err(error) => Err(format!("{}\nUI activation: {error}", startup_errors.join("\n")).into()),
+    }
 }
diff --git a/products/maka/cli/src/application/product/launch.rs b/products/maka/cli/src/application/product/launch.rs
index a1b0abfa36..a2aaac72d6 100644
--- a/products/maka/cli/src/application/product/launch.rs
+++ b/products/maka/cli/src/application/product/launch.rs
@@ -35,12 +35,7 @@ use maka_plugin_core::{
 use maka_transport::{Configuration, HostLocation};
 use serde::{Deserialize, Serialize};
 use serde_json::Value;
-use std::{
-    collections::BTreeMap,
-    io::{IsTerminal, Write},
-    path::PathBuf,
-    sync::Arc,
-};
+use std::{collections::BTreeMap, io::IsTerminal, path::PathBuf, sync::Arc};
 use uuid::Uuid;
 
 #[derive(Args, Default)]
@@ -88,6 +83,7 @@ impl Launch {
         }
         let root = super::root_path(self.root.clone())?;
         let store = Arc::new(open(root.clone(), true, None).await?);
+        let mut startup = None;
         let result = async {
             let existing = store.application_launch().await?.is_some();
             if existing && (self.workspace.is_some() || self.locale.is_some() || self.light
@@ -97,19 +93,28 @@ impl Launch {
             let configuration = match self.configuration {
                 Some(path) => Some(read_json(&path)?),
                 None if existing => None,
-                None => Some(standard_configuration(root, self.workspace, self.locale, self.light, self.trust_workspace).await?),
+                None => match standard_configuration(root, self.workspace, self.locale, self.light, self.trust_workspace, &mut startup).await? {
+                    Some(configuration) => Some(configuration),
+                    None => return Ok(None),
+                },
             };
-            prepare(&store, configuration, self.product.unwrap_or(Product::Agent)).await
+            prepare(&store, configuration, self.product.unwrap_or(Product::Agent)).await.map(Some)
         }.await;
         let (deployment, configuration) = match result {
-            Ok(value) => value,
+            Ok(Some(value)) => value,
+            Ok(None) => {
+                store.drain().await;
+                return Ok(());
+            }
             Err(error) => {
                 store.drain().await;
                 return Err(error);
             }
         };
-        eprintln!("Opening product…");
-        run_tui(store, deployment, configuration).await
+        if startup.is_none() {
+            eprintln!("Opening product…");
+        }
+        run_tui(store, deployment, configuration, startup).await
     }
 }
 async fn standard_configuration(
@@ -118,7 +123,8 @@ async fn standard_configuration(
     locale: Option<String>,
     light: bool,
     trusted: bool,
-) -> Result<Value, HostError> {
+    startup: &mut Option<maka_render_terminal::startup::Startup>,
+) -> Result<Option<Value>, HostError> {
     let workspace = std::fs::canonicalize(workspace.unwrap_or(std::env::current_dir()?))?;
     if !workspace.is_dir() {
         return Err("workspace must be a directory".into());
@@ -131,28 +137,12 @@ async fn standard_configuration(
             .filter(|value| *value != "auto")
             .map(str::to_owned)
             .unwrap_or_else(maka_ui_runtime::locale::system);
-        let accepted = tokio::task::spawn_blocking(move || -> Result<bool, std::io::Error> {
-            eprintln!("Maka workspace: {}", shown.display().to_string().escape_debug());
-            let language = language.to_ascii_lowercase();
-            if language.starts_with("zh") {
-                if language.contains("hant") || language.contains("tw") || language.contains("hk") || language.contains("mo") {
-                    eprintln!("信任此目錄以修改檔案和執行沙箱命令?命令可以讀取目錄外的檔案,但網路存取已停用。專案和使用者技能目錄將啟用。");
-                    eprint!("繼續 [y/N]:");
-                } else {
-                    eprintln!("信任此目录以修改文件和执行沙箱命令?命令可以读取目录外的文件,但网络访问已禁用。项目和用户技能目录将启用。");
-                    eprint!("继续 [y/N]:");
-                }
-            } else {
-                eprintln!("Trust this directory for file changes and sandboxed commands? Commands may read files outside it; their network access is disabled. Project and user skill directories are enabled.");
-                eprint!("Continue [y/N]: ");
-            }
-            std::io::stderr().flush()?;
-            let mut answer = String::new();
-            std::io::stdin().read_line(&mut answer)?;
-            Ok(matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
-        }).await??;
-        if !accepted {
-            return Err("workspace was not trusted; no product was installed".into());
+        *startup = tokio::task::spawn_blocking(move || {
+            maka_render_terminal::startup::Startup::confirm(&shown, &language, light)
+        })
+        .await??;
+        if startup.is_none() {
+            return Ok(None);
         }
     }
     let options = serde_json::json!({
@@ -162,7 +152,7 @@ async fn standard_configuration(
         "locale": locale.unwrap_or_else(|| "auto".into()),
         "scheme": if light { "light" } else { "dark" },
     });
-    super::installation(options).await
+    super::installation(options).await.map(Some)
 }
 
 pub(super) async fn open(
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product.rs b/products/maka/cli/tests/integration/terminal/bundled_product.rs
index a3f76ebc21..4214dc3417 100644
--- a/products/maka/cli/tests/integration/terminal/bundled_product.rs
+++ b/products/maka/cli/tests/integration/terminal/bundled_product.rs
@@ -468,3 +468,115 @@ fn bundled_ui_authoring_installs_and_reloads_original_source_without_replaying()
         store.shutdown().await.unwrap();
     });
 }
+
+#[test]
+#[ignore = "starts the standard product and its real Host in a native PTY"]
+fn first_install_trust_uses_one_terminal_and_cancel_has_no_product_effects() {
+    let directory = tempfile::tempdir().unwrap();
+    let root = directory.path().join("ui");
+    let workspace = directory.path().join("workspace");
+    std::fs::create_dir(&workspace).unwrap();
+    let args = [
+        "application",
+        "launch",
+        "--root",
+        root.to_str().unwrap(),
+        "--workspace",
+        workspace.to_str().unwrap(),
+        "--locale",
+        "en",
+    ];
+    let mut cancelled = Pty::spawn(&args);
+    cancelled.wait_for("Trust this workspace?");
+    assert!(cancelled.screen.snapshot().unwrap().alternate_screen);
+    assert!(!root.join("host").exists());
+    cancelled.send(b"\r");
+    cancelled.finish();
+    assert!(!cancelled.screen.snapshot().unwrap().alternate_screen);
+    assert!(!root.join("host").exists());
+    let mut tui = Pty::spawn(&args);
+    tui.wait_for("Trust this workspace?");
+    tui.send(b"\t\r");
+    tui.wait_until_with_timeout(
+        |screen| screen.contains("Settings"),
+        Duration::from_secs(60),
+    );
+    assert!(tui.screen.snapshot().unwrap().alternate_screen);
+    // No alternate-screen teardown between confirmation and the actual product.
+    assert!(!tui.output.windows(8).any(|bytes| bytes == b"\x1b[?1049l"));
+    tui.send(b"\x11");
+    tui.finish();
+    assert!(!tui.screen.snapshot().unwrap().alternate_screen);
+    let mut reopened = Pty::spawn(&["application", "launch", "--root", root.to_str().unwrap()]);
+    reopened.wait_until_with_timeout(
+        |screen| screen.contains("Settings"),
+        Duration::from_secs(30),
+    );
+    assert!(!String::from_utf8_lossy(&reopened.output).contains("Trust this workspace?"));
+    reopened.send(b"\x11");
+    reopened.finish();
+}
+
+#[test]
+#[ignore = "checks a failed standard product startup in a native PTY"]
+fn first_install_failure_keeps_original_host_error_after_terminal_restoration() {
+    let directory = tempfile::tempdir().unwrap();
+    let root = directory.path().join("ui");
+    let workspace = directory.path().join("workspace");
+    std::fs::create_dir(&workspace).unwrap();
+    let mut tui = Pty::spawn(&[
+        "application",
+        "launch",
+        "--root",
+        root.to_str().unwrap(),
+        "--workspace",
+        workspace.to_str().unwrap(),
+        "--locale",
+        "en",
+    ]);
+    tui.wait_for("Trust this workspace?");
+    // The selected path disappears while the user reads the prompt. Its Host
+    // initializer must fail, and that concrete failure must survive the UI error.
+    std::fs::remove_dir(&workspace).unwrap();
+    tui.send(b"\t\r");
+    tui.wait_until_with_timeout(
+        |screen| screen.contains("Host local: plugin"),
+        Duration::from_secs(60),
+    );
+    let startup = tui.screen.snapshot().unwrap();
+    assert!(startup.alternate_screen);
+    assert!(
+        startup.screen.contains("skills_configuration_invalid")
+            || startup
+                .screen
+                .contains("agent_workspace_configuration_invalid")
+    );
+    tui.send(b"\x11");
+    let deadline = Instant::now() + Duration::from_secs(10);
+    loop {
+        tui.read();
+        if let Some(status) = tui.child.try_wait().unwrap() {
+            tui.read();
+            assert!(!status.success());
+            break;
+        }
+        assert!(Instant::now() < deadline, "failed startup did not settle");
+    }
+    let snapshot = tui.screen.snapshot().unwrap();
+    assert!(!snapshot.alternate_screen);
+    assert!(
+        snapshot.screen.contains("Host local: plugin"),
+        "{}",
+        snapshot.screen
+    );
+    assert!(
+        snapshot.screen.contains("skills_configuration_invalid")
+            || snapshot
+                .screen
+                .contains("agent_workspace_configuration_invalid"),
+        "{}",
+        snapshot.screen
+    );
+    let output = String::from_utf8_lossy(&tui.output);
+    assert!(output.rfind("Host local: plugin").unwrap() > output.rfind("\x1b[?1049l").unwrap());
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org