Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix: recover delayed plugin startup (#118)

Cloga Chen4a4a97967ac1
diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rs
index c7f6d275..cd9feea0 100644
--- a/src-tauri/src/service/plugin/install.rs
+++ b/src-tauri/src/service/plugin/install.rs
@@ -187,7 +187,7 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
// 真正修复:核验本次安装是否真实落盘。pnpm 可能在 allowBuilds 阻断时仍以
// exit 0 退出(假成功),若产物缺失则记录错误并返回 Err,让前端如实展示失败、
// 允许重试,而不是误报「已安装」。已落盘的插件在上一步被核验并清除历史错误。
- verify_installed_products(app_handle, ids, &preset_map)?;
+ verify_installed_products(app_handle, ids, &preset_map, &last_output)?;
// Windows 极简模式专项修复
if ids.iter().any(|id| id == "dsh-win-terminal-inspector") {
@@ -244,34 +244,36 @@ fn preset_spec_for_install(
/// 存在:缺失者记录错误并整体返回 Err,避免前端误报「已安装 N 个插件」。
///
/// 已落盘的插件同步清除其历史错误;`ids` 里未匹配到预设的条目忽略(调用处已先
-/// 校验过 ID,正常不可达)。
+/// 校验过 ID,正常不可达)。同时接收全部命令输出,以便静默失败时保留早期重试的
+/// 诊断,而不是因最后一次重试无输出而误报「子进程完全无输出」。
fn verify_installed_products(
app_handle: &AppHandle,
ids: &[String],
preset_map: &HashMap<&str, &PreinstallPluginInfo>,
+ command_output: &str,
) -> Result<(), String> {
let node_modules = profile_dir(app_handle).join("node_modules");
- let mut missing: Vec<String> = Vec::new();
+ let mut missing = Vec::new();
for id in ids {
let Some(preset) = preset_map.get(id.as_str()) else {
continue;
};
let name = installed_name(preset);
- if node_modules.join(name).join("package.json").is_file() {
+ let manifest = node_modules.join(name).join("package.json");
+ if manifest.is_file() {
if let Err(e) = errors::clear(app_handle, id) {
log::warn!("failed to clear plugin error for {id}: {e}");
}
} else {
- missing.push(id.clone());
+ missing.push((id.clone(), manifest));
}
}
if missing.is_empty() {
return Ok(());
}
- let detail = format!(
- "PREINSTALL_SILENT_FAIL: 以下插件退出码为 0 但未真正安装(node_modules 缺少产物):{missing:?}"
- );
- for id in &missing {
+ let detail = silent_install_failure_detail(&missing, command_output);
+ log::error!("{detail}");
+ for (id, _) in &missing {
if let Err(e) = errors::record(app_handle, id, "install", &detail) {
log::warn!("failed to record plugin error for {id}: {e}");
}
@@ -279,6 +281,29 @@ fn verify_installed_products(
Err(detail)
}
+/// 为 exit 0 但无落盘产物的假成功生成可操作诊断:明确缺失插件、预期清单路径,
+/// 并区分「子进程完全无输出」与「有输出但仍未落盘」,方便日志反馈直接定位。
+fn silent_install_failure_detail(missing: &[(String, PathBuf)], command_output: &str) -> String {
+ let ids = missing
+ .iter()
+ .map(|(id, _)| id.as_str())
+ .collect::<Vec<_>>()
+ .join(", ");
+ let manifests = missing
+ .iter()
+ .map(|(_, path)| path.display().to_string())
+ .collect::<Vec<_>>()
+ .join(", ");
+ let output_hint = if command_output.trim().is_empty() {
+ "The dsh plugin command produced no output."
+ } else {
+ "Review the preinstall log above for the command output."
+ };
+ format!(
+ "PREINSTALL_SILENT_FAIL: dsh plugin exited with code 0, but no install artifact was created for [{ids}]. Expected package manifests: [{manifests}]. {output_hint} Retry the installation; if it repeats, include the preinstall log and these paths in the bug report."
+ )
+}
+
/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色,
/// PATH 前置 shim 目录与 node 目录;用户 pnpm 过旧时强制捆绑版(见 ensure_pnpm)。
///
@@ -328,12 +353,15 @@ pub(crate) fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: boo
/// `lib/index.js` 缺失」的坏态,下一次启动便因 `${DSH_HOME}/profiles/<档案>/node_modules/<pkg>/lib/index.js`
/// 无法解析而 `ERR_MODULE_NOT_FOUND` 失败。
///
-/// 返回 `(退出码, 最后一次捕获的输出)`。输出仍逐行经 `preinstall-log` 实时推送。
+/// 返回 `(退出码, 所有尝试累积的输出)`,避免最后一次重试无输出时丢失此前诊断。
+/// 输出仍逐行经 `preinstall-log` 实时推送。
///
/// 注意:pnpm v11 在 `allowBuilds` 将 git 托管插件(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)
/// 或传递依赖(`ERR_PNPM_IGNORED_BUILDS`)拦截时仍可能以 **exit 0** 退出(假成功),
/// 因此不能仅凭退出码判断成败——必须先解析输出里的 `allowBuilds` 键,有键就写入
/// profile 的 `pnpm-workspace.yaml` 并重试。无键可加(或到达重试上限)才以本次退出码为准。
+///
+/// 每次重试的输出都必须累积,避免最终尝试无输出时覆盖此前真正有用的 pnpm 诊断。
async fn run_plugin_with_allow_build_retry(
app_handle: &AppHandle,
node: &Path,
@@ -344,8 +372,10 @@ async fn run_plugin_with_allow_build_retry(
action: &str,
) -> Result<(i32, String), String> {
let mut retries = 0usize;
- let (exit_code, last_output) = loop {
+ let mut all_output = String::new();
+ let exit_code = loop {
let (code, captured) = run_plugin_process(node, args, cwd, envs, window).await?;
+ append_command_output(&mut all_output, &captured);
let new_keys = parse_allowlist_keys(&captured);
// 有可补充的 allowBuilds 键且未达上限 → 写入并重试(无论本次退出码是否为 0,
// 见上方注释:pnpm 可能在阻断时仍以 0 退出)。
@@ -369,16 +399,27 @@ async fn run_plugin_with_allow_build_retry(
log::error!(
"dsh plugin {action}: allowBuilds retry limit reached ({retries}), keys {new_keys:?} unresolved"
);
- break (if code == 0 { 1 } else { code }, captured);
+ break if code == 0 { 1 } else { code };
}
if code != 0 {
log::error!(
"dsh plugin {action} failed with exit code {code}; no allowBuilds entries to add"
);
}
- break (code, captured);
+ break code;
};
- Ok((exit_code, last_output))
+ Ok((exit_code, all_output))
+}
+
+/// 合并单次命令输出,并在相邻尝试之间补换行,保证后续错误解析不会粘连两段日志。
+fn append_command_output(all_output: &mut String, captured: &str) {
+ if captured.is_empty() {
+ return;
+ }
+ if !all_output.is_empty() && !all_output.ends_with('\n') {
+ all_output.push('\n');
+ }
+ all_output.push_str(captured);
}
/// 升级单个插件:`dsh plugin --profile <当前档案> update <id>`
@@ -1068,7 +1109,7 @@ pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
- use super::{apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, shell_quote_spec, PreinstallPluginInfo};
+ use super::{append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, shell_quote_spec, silent_install_failure_detail, PreinstallPluginInfo};
/// 构造预设条目的测试助手(internal 由各用例显式指定)
fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {
@@ -1122,6 +1163,49 @@ mod tests {
assert!(err.contains("dsh-tauri"));
}
+ /// 验证命令无输出且产物缺失时,会同时报告预期清单路径和可操作提示。
+ #[test]
+ fn silent_install_failure_reports_empty_output_and_expected_artifact() {
+ let missing = vec![(
+ "dsh-win-terminal-inspector".to_string(),
+ PathBuf::from(
+ "C:\\Users\\test\\.dsh\\profiles\\web\\node_modules\\dsh-win-terminal-inspector\\package.json",
+ ),
+ )];
+
+ let detail = silent_install_failure_detail(&missing, " \r\n");
+
+ assert!(detail.starts_with("PREINSTALL_SILENT_FAIL:"));
+ assert!(detail.contains("dsh-win-terminal-inspector"));
+ assert!(detail.contains("package.json"));
+ assert!(detail.contains("produced no output"));
+ assert!(detail.contains("Retry the installation"));
+ }
+
+ /// 验证已有命令日志时,引导用户查看日志而不会误报为完全无输出。
+ #[test]
+ fn silent_install_failure_points_to_existing_command_log() {
+ let missing = vec![(
+ "dshmarket".to_string(),
+ PathBuf::from("/tmp/profile/node_modules/dshmarket/package.json"),
+ )];
+
+ let detail = silent_install_failure_detail(&missing, "pnpm completed\n");
+
+ assert!(detail.contains("Review the preinstall log above"));
+ assert!(!detail.contains("produced no output"));
+ }
+
+ /// 验证最终重试无输出时,早期尝试产生的诊断不会被覆盖丢失。
+ #[test]
+ fn command_output_retains_earlier_retry_diagnostics() {
+ let mut output = String::new();
+ append_command_output(&mut output, "ERR_PNPM_IGNORED_BUILDS");
+ append_command_output(&mut output, "");
+
+ assert_eq!(output, "ERR_PNPM_IGNORED_BUILDS");
+ }
+
#[test]
fn store_major_parsed_from_modules_yaml() {
// 真实 pnpm v10 写入的 .modules.yaml:storeDir 指向 store\v10
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index 104b442b..a16de6e8 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -11,6 +11,7 @@ import type {
SetupStatus,
SidebarBusyAction,
} from './types'
+import type { ReadinessProbeResult } from '@/utils/readiness'
import { emitter } from '@hairy/react-lib'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
@@ -18,6 +19,7 @@ import i18next from 'i18next'
import { defineStore } from 'valtio-define'
import { queryClient } from '@/config/client'
import { containsInotifyLimitError, pickErrorLines } from '@/utils/log'
+import { pollReadiness } from '@/utils/readiness'
import { harnessUpdater } from '../harness-updater'
const MAX_RETRIES = 8
@@ -33,6 +35,8 @@ interface StartupError extends Error {
pluginConflictHint?: string
/** Linux inotify 文件监视上限(ENOSPC)导致服务启动即崩溃时的针对性提示 */
inotifyLimitHint?: string
+ /** 初始就绪窗口已耗尽,但后端进程仍由桌面端持有,可继续后台探测 */
+ readinessTimedOut?: boolean
}
const initialInstaller: InstallerState = {
@@ -61,14 +65,8 @@ function generateTimestampedUrl(baseUrl: string): string {
return `${baseUrl}${separator}t=${timestamp}`
}
-/** 健康检查结果:healthy 表示服务就绪;notOwned 表示 dsh 进程已退出(启动即崩溃,快速失败信号) */
-interface HealthCheckResult {
- healthy: boolean
- notOwned: boolean
-}
-
/** 通过 Rust 代理探测服务健康状态(超时 8s,网络抖动时重试) */
-async function checkHealthViaProxy(): Promise<HealthCheckResult> {
+async function checkHealthViaProxy(): Promise<ReadinessProbeResult> {
try {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error('health check timeout')), 8000)
@@ -275,8 +273,67 @@ export const harness = defineStore({
})
},
+ /** 服务探测通过后的统一收尾;token 用于阻止旧启动流程覆盖新状态 */
+ async completeReadiness(token?: number): Promise<boolean> {
+ const readyInfo = await invoke<{ service_url: string }>('get_runtime_info')
+ if (token !== undefined && token !== bootToken)
+ return false
+
+ this.serviceUrl = readyInfo.service_url
+ this.iframeSrc = generateTimestampedUrl(readyInfo.service_url)
+ this.serviceHealthy = true
+ this.serviceRunning = true
+ this.status = 'ready'
+ this.errorMsg = ''
+ this.errorLogs = []
+ this.pluginConflictHint = ''
+ this.inotifyLimitHint = ''
+ this.preinstall.error = ''
+ // 服务(重)启动成功:清空插件异常修复态(若曾进入),并重置已「暂不处理」的插件
+ this.recovery = { required: false, info: null, attempts: 0, busy: false }
+ this.dismissedRecoveryIds = []
+ // 服务(重)启动成功后,dsh 版本/端口/CLI 链接状态等运行时信息可能已变化
+ // (典型:Harness 更新后旧版本缓存仍在,调试侧边栏需刷新页面才显示新版本)。
+ // 使侧边栏相关查询缓存失效,重新打开/已挂载时自动拉取最新值。
+ void queryClient.invalidateQueries({ queryKey: ['info'] })
+ void queryClient.invalidateQueries({ queryKey: ['config'] })
+ void queryClient.invalidateQueries({ queryKey: ['cli_status'] })
+ // 档案/核心切换后重启:当前档案的插件列表、核心来源状态一并刷新
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
+ void queryClient.invalidateQueries({ queryKey: ['profiles'] })
+ void queryClient.invalidateQueries({ queryKey: ['cores'] })
+ return true
+ },
+
+ /**
+ * 初始就绪窗口超时后继续探测同一已持有进程。错误界面仍会及时出现,但只要后端
+ * 稍后完成插件加载,就自动恢复并挂载 iframe;新一轮 boot 会用 token 终止旧探测。
+ */
+ async recoverReadiness(token: number) {
+ const result = await pollReadiness({
+ probe: checkHealthViaProxy,
+ intervalMs: 2000,
+ shouldContinue: () => token === bootToken && this.serviceRunning && !this.serviceHealthy,
+ })
+ if (token !== bootToken)
+ return
+ if (result.notOwned) {
+ this.serviceRunning = false
+ return
+ }
+ if (!result.healthy)
+ return
+
+ try {
+ await this.completeReadiness(token)
+ }
+ catch (err) {
+ console.error('[Harness] failed to complete delayed readiness recovery:', err)
+ }
+ },
+
/** 拉起服务并等待健康检查通过,通过后才允许挂载 iframe */
- async launchAndWait() {
+ async launchAndWait(token?: number) {
this.status = 'ready'
this.installer = initialInstaller
this.errorMsg = ''
@@ -296,42 +353,24 @@ export const harness = defineStore({
this.serviceUrl = runtimeInfo.service_url
this.iframeSrc = generateTimestampedUrl(runtimeInfo.service_url)
- let healthy = false
- let notOwned = false
- for (let attempt = 0; attempt < MAX_RETRIES && !healthy && !notOwned; attempt++) {
- const result = await checkHealthViaProxy()
- healthy = result.healthy
- notOwned = result.notOwned
- if (!healthy && !notOwned) {
- await new Promise(resolve => setTimeout(resolve, 2000))
- }
- }
- if (!healthy) {
- throw new Error(
+ const result = await pollReadiness({
+ probe: checkHealthViaProxy,
+ intervalMs: 2000,
+ maxAttempts: MAX_RETRIES,
+ shouldContinue: () => token === undefined || token === bootToken,
+ })
+ if (!result.healthy) {
+ const error: StartupError = new Error(
i18next.t('errors.service_start_timeout', { port: new URL(this.serviceUrl).port || '3080' }),
)
+ error.readinessTimedOut = !result.notOwned
+ throw error
}
// 服务已就绪后再取一次真实地址:`launch_harness` 可能因后端已在并发拉起
// (auto_start)而提前返回,此刻端口若尚未落库,上面读到的 service_url 会是
// 旧端口;健康检查通过意味着服务已在最终端口就绪,此时读取必然准确。
// 避免 iframe 挂载到一个无人监听的地址(表现为首次加载失败、刷新后恢复)。
- const readyInfo = await invoke<{ service_url: string }>('get_runtime_info')
- this.serviceUrl = readyInfo.service_url
- this.iframeSrc = generateTimestampedUrl(readyInfo.service_url)
- this.serviceHealthy = true
- // 服务(重)启动成功:清空插件异常修复态(若曾进入),并重置已「暂不处理」的插件
- this.recovery = { required: false, info: null, attempts: 0, busy: false }
- this.dismissedRecoveryIds = []
- // 服务(重)启动成功后,dsh 版本/端口/CLI 链接状态等运行时信息可能已变化
- // (典型:Harness 更新后旧版本缓存仍在,调试侧边栏需刷新页面才显示新版本)。
- // 使侧边栏相关查询缓存失效,重新打开/已挂载时自动拉取最新值。
- void queryClient.invalidateQueries({ queryKey: ['info'] })
- void queryClient.invalidateQueries({ queryKey: ['config'] })
- void queryClient.invalidateQueries({ queryKey: ['cli_status'] })
- // 档案/核心切换后重启:当前档案的插件列表、核心来源状态一并刷新
- void queryClient.invalidateQueries({ queryKey: ['plugins'] })
- void queryClient.invalidateQueries({ queryKey: ['profiles'] })
- void queryClient.invalidateQueries({ queryKey: ['cores'] })
+ await this.completeReadiness(token)
}
catch (err) {
// 失败时附上服务日志里的真实错误行,供错误界面展示而不是只显示超时文案
@@ -411,7 +450,7 @@ export const harness = defineStore({
return
}
- await this.launchAndWait()
+ await this.launchAndWait(token)
if (token !== bootToken)
return
@@ -427,12 +466,17 @@ export const harness = defineStore({
const startupError = await attachStartupDiagnostics(err)
// 尝试从日志定位问题插件:能定位则弹出修复界面(全屏恢复页)
await this.reviewStartupRecovery(startupError.logLines ?? startupError.logs ?? [])
+ const keepServiceRunning = startupError.readinessTimedOut === true
this.fail(
String(startupError),
startupError.logs,
startupError.pluginConflictHint,
startupError.inotifyLimitHint,
+ keepServiceRunning,
)
+ if (keepServiceRunning) {
+ void this.recoverReadiness(token)
+ }
}
finally {
unlistenInstall?.()
@@ -446,13 +490,13 @@ export const harness = defineStore({
},
/** 进入错误态(供本模块与 updater 模块共用) */
- fail(message: string, logs?: string[], pluginConflictHint?: string, inotifyLimitHint?: string) {
+ fail(message: string, logs?: string[], pluginConflictHint?: string, inotifyLimitHint?: string, keepServiceRunning = false) {
this.errorMsg = message
this.errorLogs = logs ?? []
this.pluginConflictHint = pluginConflictHint ?? ''
this.inotifyLimitHint = inotifyLimitHint ?? ''
this.status = 'error'
- this.serviceRunning = false
+ this.serviceRunning = keepServiceRunning
},
/**
@@ -650,6 +694,9 @@ export const harness = defineStore({
catch (err) {
console.error('[Harness] preinstall failed:', err)
this.preinstall.error = String(err)
+ if (err instanceof Error && (err as StartupError).readinessTimedOut) {
+ void this.recoverReadiness(bootToken)
+ }
}
finally {
unlisten?.()
diff --git a/src/utils/readiness.ts b/src/utils/readiness.ts
new file mode 100644
index 00000000..129bdef6
--- /dev/null
+++ b/src/utils/readiness.ts
@@ -0,0 +1,45 @@
+export interface ReadinessProbeResult {
+ healthy: boolean
+ notOwned: boolean
+}
+
+interface PollReadinessOptions {
+ probe: () => Promise<ReadinessProbeResult>
+ intervalMs: number
+ maxAttempts?: number
+ shouldContinue?: () => boolean
+ wait?: (milliseconds: number) => Promise<void>
+}
+
+function delay(milliseconds: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, milliseconds))
+}
+
+export async function pollReadiness({
+ probe,
+ intervalMs,
+ maxAttempts,
+ shouldContinue = () => true,
+ wait = delay,
+}: PollReadinessOptions): Promise<ReadinessProbeResult> {
+ let remainingAttempts = maxAttempts
+
+ while (shouldContinue() && remainingAttempts !== 0) {
+ const result = await probe()
+ if (!shouldContinue()) {
+ return { healthy: false, notOwned: false }
+ }
+ if (remainingAttempts !== undefined) {
+ remainingAttempts--
+ }
+
+ if (result.healthy || result.notOwned) {
+ return result
+ }
+ if (shouldContinue() && remainingAttempts !== 0) {
+ await wait(intervalMs)
+ }
+ }
+
+ return { healthy: false, notOwned: false }
+}
diff --git a/test/readiness.test.ts b/test/readiness.test.ts
new file mode 100644
index 00000000..5cb0b841
--- /dev/null
+++ b/test/readiness.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest'
+import { pollReadiness } from '../src/utils/readiness'
+
+function noWait(): Promise<void> {
+ return Promise.resolve()
+}
+
+describe('pollReadiness', () => {
+ it('stops after the initial bounded attempts', async () => {
+ let attempts = 0
+ const result = await pollReadiness({
+ probe: async () => {
+ attempts++
+ return { healthy: false, notOwned: false }
+ },
+ intervalMs: 0,
+ maxAttempts: 3,
+ wait: noWait,
+ })
+
+ expect(result).toEqual({ healthy: false, notOwned: false })
+ expect(attempts).toBe(3)
+ })
+
+ it('keeps recovery polling until a slow service becomes healthy', async () => {
+ let attempts = 0
+ const result = await pollReadiness({
+ probe: async () => {
+ attempts++
+ return { healthy: attempts === 5, notOwned: false }
+ },
+ intervalMs: 0,
+ wait: noWait,
+ })
+
+ expect(result.healthy).toBe(true)
+ expect(attempts).toBe(5)
+ })
+
+ it('stops recovery when the owning startup is superseded', async () => {
+ let attempts = 0
+ let active = true
+ const result = await pollReadiness({
+ probe: async () => {
+ attempts++
+ active = false
+ return { healthy: false, notOwned: false }
+ },
+ intervalMs: 0,
+ shouldContinue: () => active,
+ wait: noWait,
+ })
+
+ expect(result).toEqual({ healthy: false, notOwned: false })
+ expect(attempts).toBe(1)
+ })
+
+ it('discards a healthy probe result when recovery is cancelled while probing', async () => {
+ let active = true
+ const pendingProbe = Promise.withResolvers<{ healthy: boolean, notOwned: boolean }>()
+ const resultPromise = pollReadiness({
+ probe: () => pendingProbe.promise,
+ intervalMs: 0,
+ shouldContinue: () => active,
+ wait: noWait,
+ })
+
+ active = false
+ pendingProbe.resolve({ healthy: true, notOwned: false })
+
+ await expect(resultPromise).resolves.toEqual({ healthy: false, notOwned: false })
+ })
+})