Skip to content

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

fix(service): surface unexpected Harness exits (#213)

Justin Skowyraaee12b892322
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 46643701..2aa2125a 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -437,6 +437,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// PID 与句柄作为整体一次登记,与退出清理(take 一并取出)配对
let handle_value = handle as usize;
set_owned_process_with_handle(pid, handle_value);
+ let exit_app_handle = app_handle.clone();
std::thread::spawn(move || unsafe {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{
@@ -444,21 +445,18 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
};
let process_handle = handle_value as windows_sys::Win32::Foundation::HANDLE;
WaitForSingleObject(process_handle, INFINITE);
- // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败,
- // 退出码也便于诊断问题
- let mut exit_code: u32 = 0;
- if GetExitCodeProcess(process_handle, &mut exit_code) != 0 {
- log::warn!("Owned Harness process {pid} exited with code {exit_code}");
- } else {
- log::warn!("Owned Harness process {pid} exited (exit code unavailable)");
- }
// 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为
// Stopped(原有实现只清 PID、状态永远停留在 Running)。
// 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。
// take 返回值里的句柄由本线程负责关闭(不会与
// terminate_owned_process 重复 close——进程已 exit,
// 通常是本线程取走)。
- let owned = on_owned_process_exit(pid);
+ let owned = on_owned_process_exit(&exit_app_handle, pid, |owned| {
+ let handle = owned.handle as windows_sys::Win32::Foundation::HANDLE;
+ let mut exit_code: u32 = 0;
+ (GetExitCodeProcess(handle, &mut exit_code) != 0)
+ .then_some(i64::from(exit_code))
+ });
if let Some(owned) = owned {
let h = owned.handle as windows_sys::Win32::Foundation::HANDLE;
CloseHandle(h);
@@ -495,18 +493,13 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
let stdout = child.stdout.take();
let stderr = child.stderr.take();
set_owned_process(pid);
+ let exit_app_handle = app_handle.clone();
std::thread::spawn(move || {
let code = child.wait().ok().and_then(|status| status.code());
- // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败
- if let Some(code) = code {
- log::warn!("Owned Harness process {pid} exited with code {code}");
- } else {
- log::warn!("Owned Harness process {pid} exited (no exit code)");
- }
// 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为 Stopped
// (Unix 无进程句柄可关闭,忽略返回的进程记录)。
// 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。
- let _ = on_owned_process_exit(pid);
+ let _ = on_owned_process_exit(&exit_app_handle, pid, |_| code.map(i64::from));
});
(stdout, stderr, pid)
})
diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rs
index b0295e37..391f4f65 100644
--- a/src-tauri/src/service/workflow/process.rs
+++ b/src-tauri/src/service/workflow/process.rs
@@ -9,10 +9,22 @@ use std::process::Command;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
+use tauri::{AppHandle, Emitter};
use super::status;
use super::sweep::harness_pid_path;
+/// 当前持有的 Harness 根进程意外退出时通知前端的专用事件。
+pub(super) const HARNESS_PROCESS_EXITED_EVENT: &str = "harness-process-exited";
+
+/// Harness 根进程退出事件载荷。退出码在 Unix 被信号终止或系统查询失败时为空。
+#[derive(Clone, Debug, serde::Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub(super) struct HarnessProcessExitedPayload {
+ pub(super) pid: u32,
+ pub(super) exit_code: Option<i64>,
+}
+
/// 启动守卫:并发调用 `launch` 时只允许一个真正拉起 dsh 进程
pub(crate) static LAUNCH_GUARD: AtomicBool = AtomicBool::new(false);
@@ -109,22 +121,42 @@ pub fn has_owned_process() -> bool {
/// - 仅当退出的 PID 仍是当前登记的那个进程时才清空持有(`take_owned_process_if`
/// 按 pid 匹配),PID/句柄作为整体成对取出——杜绝「读 PID」与「清句柄」
/// 之间的跨原子竞态(WARN-6),也杜绝旧监视线程误清新启动进程的登记;
-/// - 若当前状态仍是 Running,回落到 Stopped——否则进程已经没了、状态却永远
-/// 显示「运行中」,前端按钮/横幅会长期处于错误语义(WARN-5)。
+/// - 匹配成功后无条件回落到 Stopped——进程可能在 Starting 或 Running 阶段
+/// 退出,任何情况下都不能继续广播一个已经失效的运行状态(WARN-5)。
///
/// 返回被取出的进程记录(含 Windows 句柄),取到者负责 `CloseHandle`——保证
/// 「取走进程」与「关闭句柄」同属一个调用者,杜绝重复 close。幂等:多次调用
/// (tick 与监视线程并发)只会生效一次,后续调用返回 None。
-pub(super) fn on_owned_process_exit(pid: u32) -> Option<OwnedProcess> {
+pub(super) fn on_owned_process_exit(
+ app_handle: &AppHandle,
+ pid: u32,
+ exit_code: impl FnOnce(&OwnedProcess) -> Option<i64>,
+) -> Option<OwnedProcess> {
let owned = take_owned_process_if(pid)?;
+ // 必须在成功取走当前 PID 后才读取 Windows 句柄:正常停止会先取走并关闭
+ // 句柄,旧监视线程不得再查询该句柄,更不得发送“意外退出”事件。
+ let exit_code = exit_code(&owned);
- log::warn!(
- "Owned Harness process {} exited; resetting status to Stopped",
- owned.pid
- );
+ if let Some(code) = exit_code {
+ log::warn!(
+ "Owned Harness process {} exited with code {code}; resetting status to Stopped",
+ owned.pid
+ );
+ } else {
+ log::warn!(
+ "Owned Harness process {} exited (exit code unavailable); resetting status to Stopped",
+ owned.pid
+ );
+ }
- if status::get_status() == status::Status::Running {
- status::set_status(status::Status::Stopped);
+ status::set_status(status::Status::Stopped);
+ status::emit_status(app_handle);
+ let payload = HarnessProcessExitedPayload {
+ pid: owned.pid,
+ exit_code,
+ };
+ if let Err(error) = app_handle.emit(HARNESS_PROCESS_EXITED_EVENT, payload) {
+ log::warn!("Failed to emit Harness process exit event: {error}");
}
Some(owned)
}
@@ -438,6 +470,27 @@ mod tests {
assert!(take_owned_process_if_matching(&mut slot, 42).is_none());
}
+ /// 退出载荷保留退出码(含 0),无法取得时显式序列化为 null。
+ #[test]
+ fn harness_process_exit_payload_serializes_exit_code() {
+ let with_code = serde_json::to_value(HarnessProcessExitedPayload {
+ pid: 42,
+ exit_code: Some(0),
+ })
+ .expect("serialize process exit payload");
+ assert_eq!(with_code, serde_json::json!({ "pid": 42, "exitCode": 0 }));
+
+ let without_code = serde_json::to_value(HarnessProcessExitedPayload {
+ pid: 43,
+ exit_code: None,
+ })
+ .expect("serialize process exit payload");
+ assert_eq!(
+ without_code,
+ serde_json::json!({ "pid": 43, "exitCode": null })
+ );
+ }
+
/// `ps -axo pid=,command=` 行解析:首列 PID,其余为命令行。
#[test]
fn parse_ps_line_extracts_pid_and_cmdline() {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 89c1c88d..2b7b4663 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -80,6 +80,8 @@
"errors.startup_inactivity": "Harness made no progress during {{phase}} before its activity deadline. Last readiness status: {{reason}}",
"errors.startup_absolute": "Harness exceeded the maximum allowed time for {{phase}}. Last readiness status: {{reason}}",
"errors.startup_exited": "Harness exited during {{phase}}. Last readiness status: {{reason}}",
+ "errors.process_exited_with_code": "Harness stopped unexpectedly (exit code {{code}}). Restart to continue.",
+ "errors.process_exited_without_code": "Harness stopped unexpectedly. Restart to continue.",
"errors.no_readiness_reason": "No readiness reason was reported.",
"errors.client_boot_stalled": "The client remained on Loading plugins after all bounded reload attempts.",
"errors.plugin_route_conflict": "Detected a plugin route conflict: two plugins registered the same route twice. Uninstall the recently added plugin (e.g. dsh-web-ui-all / dsh-better-sidebar) from the Plugins panel, or run dsh plugin --profile <profile> remove <package> for the active profile and retry.",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 6585af73..9a0209e6 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -80,6 +80,8 @@
"errors.startup_inactivity": "Harness 在{{phase}}阶段超过无活动期限。最后的就绪状态:{{reason}}",
"errors.startup_absolute": "Harness 在{{phase}}阶段超过最长允许时间。最后的就绪状态:{{reason}}",
"errors.startup_exited": "Harness 在{{phase}}阶段退出。最后的就绪状态:{{reason}}",
+ "errors.process_exited_with_code": "Harness 意外停止(退出码 {{code}})。请重新启动以继续。",
+ "errors.process_exited_without_code": "Harness 意外停止。请重新启动以继续。",
"errors.no_readiness_reason": "后端未报告就绪原因。",
"errors.client_boot_stalled": "客户端在全部有界刷新尝试后仍停留在 Loading plugins。",
"errors.plugin_route_conflict": "检测到插件路由冲突:两个插件重复注册了同一路由。请在「插件」面板卸载最近安装的插件(如 dsh-web-ui-all / dsh-better-sidebar),或在终端对当前档案执行 dsh plugin --profile <档案名> remove <包名> 后重试。",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index b9b8b54f..19cc0bef 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -1,6 +1,7 @@
/* eslint-disable no-control-regex */
import type { UnlistenFn } from '@tauri-apps/api/event'
import type {
+ HarnessProcessExitedPayload,
InstallerState,
InstallProgress,
InternalPluginsPhasePayload,
@@ -21,6 +22,7 @@ import { queryClient } from '@/config/client'
import { internalPluginReason } from '@/utils/internal-plugin-phase'
import { containsInotifyLimitError, pickErrorLines } from '@/utils/log'
import { BoundedReloadGate, pollReadiness, SingleFlight, waitForActivityTask } from '@/utils/readiness'
+import { runtimeExitMessageKey, shouldAcceptRuntimeExit } from '@/utils/runtime-exit'
import { harnessUpdater } from '../harness-updater'
const IFRAME_LOAD_TIMEOUT = 20000
@@ -63,6 +65,8 @@ const initialRecovery: RecoveryState = {
/** 启动流程令牌:boot 并发/重复调用时只采纳最后一次的结果 */
let bootToken = 0
+/** 最终健康复核到 ready 提交之间的启动代;退出事件可使该提交失效。 */
+let readinessCommitToken: number | null = null
/** 首次自动启动去重(React StrictMode 会重复挂载 effect) */
let bootStarted = false
let pluginActivitySequence = 0
@@ -269,10 +273,89 @@ export const harness = defineStore({
await Promise.all([
this.listenPluginRecovery(),
this.listenInternalPhase(),
+ this.listenProcessExit(),
])
await this.boot()
},
+ /** 订阅当前持有的 Harness 根进程退出事件,及时撤下失效 iframe。 */
+ async listenProcessExit() {
+ try {
+ await listen<HarnessProcessExitedPayload>('harness-process-exited', (event) => {
+ void this.handleProcessExit(event.payload)
+ })
+ }
+ catch (err) {
+ console.error('[Harness] failed to listen harness-process-exited:', err)
+ }
+ },
+
+ /**
+ * 处理运行期退出:先通过 ownership-aware 健康代理确认事件仍属于当前代,
+ * 避免延迟事件覆盖已重启的新进程;确认后使旧启动链失效并展示可重试错误页。
+ */
+ async handleProcessExit(payload: HarnessProcessExitedPayload) {
+ const observedToken = bootToken
+ if (!shouldAcceptRuntimeExit({
+ serviceHealthy: this.serviceHealthy,
+ serviceRunning: this.serviceRunning,
+ readinessCommitPending: readinessCommitToken === observedToken,
+ busyAction: this.busyAction,
+ observedToken,
+ currentToken: bootToken,
+ notOwned: true,
+ })) {
+ return
+ }
+
+ const probe = await checkHealthViaProxy()
+ if (!shouldAcceptRuntimeExit({
+ serviceHealthy: this.serviceHealthy,
+ serviceRunning: this.serviceRunning,
+ readinessCommitPending: readinessCommitToken === observedToken,
+ busyAction: this.busyAction,
+ observedToken,
+ currentToken: bootToken,
+ notOwned: probe.notOwned,
+ })) {
+ return
+ }
+
+ const exitToken = ++bootToken
+ const message = i18next.t(runtimeExitMessageKey(payload.exitCode), {
+ code: payload.exitCode,
+ })
+ let exitDetail = '(exit code unavailable)'
+ if (payload.exitCode != null)
+ exitDetail = `(exit code ${payload.exitCode})`
+ console.warn(
+ `[Harness] owned process ${payload.pid} exited unexpectedly`,
+ exitDetail,
+ )
+ iframeReloadGate.reset()
+ if (iframeRefreshTimer !== undefined) {
+ clearTimeout(iframeRefreshTimer)
+ iframeRefreshTimer = undefined
+ }
+ this.serviceHealthy = false
+ this.iframeLoaded = false
+ this.iframeError = false
+ this.fail(message)
+
+ const error = await attachStartupDiagnostics(new Error(message))
+ if (exitToken !== bootToken)
+ return
+ await this.reviewStartupRecovery(error.logLines ?? error.logs ?? [], exitToken)
+ if (exitToken !== bootToken)
+ return
+ this.fail(
+ error.message,
+ error.logs,
+ error.pluginConflictHint,
+ error.inotifyLimitHint,
+ )
+ },
+
/**
* 订阅后端「插件异常」推送:`report_plugin_error`(运行期异常)会推送
* `plugin-recovery-required`,据此弹出「卸除此插件并继续检测」修复界面。
@@ -396,9 +479,25 @@ export const harness = defineStore({
},
/** 服务探测通过后的统一收尾;token 用于阻止旧启动流程覆盖新状态 */
- async completeReadiness(token?: number): Promise<boolean> {
+ async completeReadiness(token: number): Promise<boolean> {
+ if (token !== bootToken)
+ return false
+
+ // poll 通过与 ready 提交之间仍可能退出。进入提交窗口后再复核一次 ownership,
+ // 既能捕获窗口开启前已丢失的退出事件,也让窗口内事件用 token 中止本次提交。
+ const finalProbe = await checkHealthViaProxy()
+ if (token !== bootToken)
+ return false
+ // 上一轮 poll 已确认就绪;这里只让 ownership 丢失推翻结果,短暂探测失败不降级。
+ if (finalProbe.notOwned) {
+ this.serviceRunning = false
+ const phase = finalProbe.phase ?? this.startupPhase
+ const reason = finalProbe.reason ?? (this.startupReason || i18next.t('errors.no_readiness_reason'))
+ throw startupError(phase, reason, 'exited')
+ }
+
const readyInfo = await invoke<{ service_url: string }>('get_runtime_info')
- if (token !== undefined && token !== bootToken)
+ if (token !== bootToken)
return false
this.serviceUrl = readyInfo.service_url
@@ -486,7 +585,15 @@ export const harness = defineStore({
// (auto_start)而提前返回,此刻端口若尚未落库,上面读到的 service_url 会是
// 旧端口;健康检查通过意味着服务已在最终端口就绪,此时读取必然准确。
// 避免 iframe 挂载到一个无人监听的地址(表现为首次加载失败、刷新后恢复)。
- await this.completeReadiness(token)
+ const readinessToken = token ?? bootToken
+ readinessCommitToken = readinessToken
+ try {
+ await this.completeReadiness(readinessToken)
+ }
+ finally {
+ if (readinessCommitToken === readinessToken)
+ readinessCommitToken = null
+ }
}
catch (err) {
// 失败时附上服务日志里的真实错误行,供错误界面展示而不是只显示超时文案
@@ -646,11 +753,13 @@ export const harness = defineStore({
* 启动失败时尝试定位问题插件并弹出修复界面。
* 能定位到具体插件 → 设置 `recovery`;定位不到则保持普通错误态(无插件可卸载)。
*/
- async reviewStartupRecovery(logs: string[]) {
+ async reviewStartupRecovery(logs: string[], token?: number) {
if (this.recovery.required || logs.length === 0)
return
try {
const info = await invoke<PluginRecoveryInfo>('detect_plugin_recovery', { logs })
+ if (token !== undefined && token !== bootToken)
+ return
if (info.plugins.length > 0) {
this.recovery = {
required: true,
@@ -716,6 +825,11 @@ export const harness = defineStore({
if (this.busyAction)
return
this.busyAction = 'restart'
+ // 重启旧进程前先撤下旧 iframe;这样延迟到达的旧进程退出事件不会被
+ // 误当成新一代启动失败。新进程通过 completeReadiness 后再恢复 healthy。
+ this.serviceHealthy = false
+ this.iframeLoaded = false
+ this.iframeError = false
// 手动重启(含修复界面上的「重启 Harness」):先退出恢复态,
// 若重启仍失败,boot 的 catch 会重新定位问题插件并再次弹出。
this.recovery = { ...this.recovery, required: false, busy: false }
@@ -727,7 +841,6 @@ export const harness = defineStore({
console.error('[Harness] shutdown during restart failed:', err)
}
this.serviceRunning = false
- this.iframeLoaded = false
try {
await this.boot()
}
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index 73d69c88..765391a9 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -4,6 +4,12 @@ export type SetupStatus = 'checking' | 'installing' | 'starting' | 'preinstall'
/** 侧边栏忙碌标记:标识当前正在执行的服务操作 */
export type SidebarBusyAction = 'restart' | 'shutdown' | 'start' | 'openBrowser' | null
+/** Rust 侧 harness-process-exited 事件载荷(camelCase)。 */
+export interface HarnessProcessExitedPayload {
+ pid: number
+ exitCode: number | null
+}
+
/** 预装插件列表项(与 Rust service::plugin::PreinstallPlugin 对齐) */
export interface PreinstallPlugin {
id: string
diff --git a/src/utils/runtime-exit.ts b/src/utils/runtime-exit.ts
new file mode 100644
index 00000000..fa3cd809
--- /dev/null
+++ b/src/utils/runtime-exit.ts
@@ -0,0 +1,39 @@
+import type { SidebarBusyAction } from '@/store/modules/harness'
+
+export interface RuntimeExitAcceptance {
+ serviceHealthy: boolean
+ serviceRunning: boolean
+ readinessCommitPending: boolean
+ busyAction: SidebarBusyAction
+ observedToken: number
+ currentToken: number
+ notOwned: boolean
+}
+
+/** 只有当前运行实例确已失去后端进程时,才采纳异步退出事件。 */
+export function shouldAcceptRuntimeExit({
+ serviceHealthy,
+ serviceRunning,
+ readinessCommitPending,
+ busyAction,
+ observedToken,
+ currentToken,
+ notOwned,
+}: RuntimeExitAcceptance): boolean {
+ if (!serviceHealthy && !readinessCommitPending)
+ return false
+ if (!serviceRunning)
+ return false
+ if (busyAction === 'shutdown')
+ return false
+ if (observedToken !== currentToken)
+ return false
+ return notOwned
+}
+
+/** 退出码 0 仍是已知退出码;只有 null/undefined 才使用“未知退出码”文案。 */
+export function runtimeExitMessageKey(exitCode: number | null | undefined): string {
+ if (exitCode == null)
+ return 'errors.process_exited_without_code'
+ return 'errors.process_exited_with_code'
+}
diff --git a/test/runtime-exit-store.test.ts b/test/runtime-exit-store.test.ts
new file mode 100644
index 00000000..514ec8e9
--- /dev/null
+++ b/test/runtime-exit-store.test.ts
@@ -0,0 +1,174 @@
+import type { Event } from '@tauri-apps/api/event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const eventListeners = new Map<string, (event: Event<unknown>) => void>()
+const invoke = vi.fn()
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke }))
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn(async (event: string, callback: (payload: Event<unknown>) => void) => {
+ eventListeners.set(event, callback)
+ return vi.fn()
+ }),
+}))
+vi.mock('@hairy/react-lib', () => ({ emitter: { emit: vi.fn() } }))
+vi.mock('@/config/client', () => ({ queryClient: { invalidateQueries: vi.fn() } }))
+vi.mock('../src/store/modules/harness-updater', () => ({
+ harnessUpdater: { checkForUpdate: vi.fn() },
+}))
+
+const { harness } = await import('../src/store/modules/harness/store')
+
+beforeEach(() => {
+ eventListeners.clear()
+ invoke.mockReset()
+ Object.assign(harness, {
+ status: 'ready',
+ errorMsg: '',
+ errorLogs: [],
+ pluginConflictHint: '',
+ inotifyLimitHint: '',
+ serviceHealthy: true,
+ serviceRunning: true,
+ iframeLoaded: true,
+ iframeError: true,
+ busyAction: null,
+ recovery: { required: false, info: null, attempts: 0, busy: false },
+ })
+})
+
+describe('runtime exit store', () => {
+ it('registers the dedicated backend event listener', async () => {
+ await harness.listenProcessExit()
+ expect(eventListeners.has('harness-process-exited')).toBe(true)
+ })
+
+ it('withdraws stale runtime state and exposes diagnostics after ownership is lost', async () => {
+ invoke.mockImplementation(async (command: string) => {
+ if (command === 'proxy_health_check')
+ throw new Error('HARNESS_NOT_OWNED: no Harness process is owned by this app')
+ if (command === 'read_service_logs')
+ return 'Error: runtime process exited\nlast useful line'
+ if (command === 'detect_plugin_recovery')
+ return { plugins: [], reason: 'unknown', detail: '', raw_error: '' }
+ throw new Error(`unexpected invoke: ${command}`)
+ })
+
+ await harness.handleProcessExit({ pid: 42, exitCode: 0 })
+
+ expect(harness.status).toBe('error')
+ expect(harness.serviceHealthy).toBe(false)
+ expect(harness.serviceRunning).toBe(false)
+ expect(harness.iframeLoaded).toBe(false)
+ expect(harness.iframeError).toBe(false)
+ expect(harness.errorLogs).toContain('Error: runtime process exited')
+ })
+
+ it('does not clobber a replacement process that owns the runtime slot', async () => {
+ invoke.mockResolvedValue('HARNESS_NOT_READY: replacement process is starting')
+ const original = {
+ status: harness.status,
+ serviceHealthy: harness.serviceHealthy,
+ serviceRunning: harness.serviceRunning,
+ iframeLoaded: harness.iframeLoaded,
+ iframeError: harness.iframeError,
+ }
+
+ await harness.handleProcessExit({ pid: 41, exitCode: null })
+
+ expect({
+ status: harness.status,
+ serviceHealthy: harness.serviceHealthy,
+ serviceRunning: harness.serviceRunning,
+ iframeLoaded: harness.iframeLoaded,
+ iframeError: harness.iframeError,
+ }).toEqual(original)
+ })
+
+ it('does not commit ready when the owned process exits during the final runtime-info read', async () => {
+ let healthChecks = 0
+ let runtimeInfoReads = 0
+ let resolveFinalRuntimeInfo!: (value: { service_url: string }) => void
+ const finalRuntimeInfo = new Promise<{ service_url: string }>((resolve) => {
+ resolveFinalRuntimeInfo = resolve
+ })
+
+ invoke.mockImplementation(async (command: string) => {
+ if (command === 'launch_harness')
+ return undefined
+ if (command === 'get_runtime_info') {
+ runtimeInfoReads++
+ if (runtimeInfoReads === 1)
+ return { service_url: 'http://127.0.0.1:31415' }
+ return finalRuntimeInfo
+ }
+ if (command === 'proxy_health_check') {
+ healthChecks++
+ if (healthChecks <= 2)
+ return 'Healthy'
+ throw new Error('HARNESS_NOT_OWNED: process exited during readiness commit')
+ }
+ if (command === 'read_service_logs')
+ return 'Error: process exited during readiness commit'
+ if (command === 'detect_plugin_recovery')
+ return { plugins: [], reason: 'unknown', detail: '', raw_error: '' }
+ throw new Error(`unexpected invoke: ${command}`)
+ })
+
+ const launch = harness.launchAndWait()
+ await vi.waitFor(() => expect(runtimeInfoReads).toBe(2))
+ await harness.handleProcessExit({ pid: 43, exitCode: 1 })
+ resolveFinalRuntimeInfo({ service_url: 'http://127.0.0.1:31415' })
+ await launch
+
+ expect(harness.status).toBe('error')
+ expect(harness.serviceHealthy).toBe(false)
+ expect(harness.serviceRunning).toBe(false)
+ expect(harness.errorLogs).toContain('Error: process exited during readiness commit')
+ })
+
+ it('preserves a successful readiness poll across a transient owned recheck', async () => {
+ let healthChecks = 0
+ invoke.mockImplementation(async (command: string) => {
+ if (command === 'launch_harness')
+ return undefined
+ if (command === 'get_runtime_info')
+ return { service_url: 'http://127.0.0.1:31415' }
+ if (command === 'proxy_health_check') {
+ healthChecks++
+ return healthChecks === 1 ? 'Healthy' : 'HARNESS_NOT_READY: transient response'
+ }
+ throw new Error(`unexpected invoke: ${command}`)
+ })
+
+ await harness.launchAndWait()
+
+ expect(harness.status).toBe('ready')
+ expect(harness.serviceHealthy).toBe(true)
+ expect(harness.serviceRunning).toBe(true)
+ })
+
+ it('clears running when the final ownership recheck detects an exit without an event', async () => {
+ let healthChecks = 0
+ invoke.mockImplementation(async (command: string) => {
+ if (command === 'launch_harness')
+ return undefined
+ if (command === 'get_runtime_info')
+ return { service_url: 'http://127.0.0.1:31415' }
+ if (command === 'proxy_health_check') {
+ healthChecks++
+ if (healthChecks === 1)
+ return 'Healthy'
+ throw new Error('HARNESS_NOT_OWNED: process exited before readiness commit')
+ }
+ if (command === 'read_service_logs')
+ return 'Error: process exited before readiness commit'
+ throw new Error(`unexpected invoke: ${command}`)
+ })
+
+ await expect(harness.launchAndWait()).rejects.toThrow()
+
+ expect(harness.serviceHealthy).toBe(false)
+ expect(harness.serviceRunning).toBe(false)
+ })
+})
diff --git a/test/runtime-exit.test.ts b/test/runtime-exit.test.ts
new file mode 100644
index 00000000..9a51c246
--- /dev/null
+++ b/test/runtime-exit.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest'
+import { runtimeExitMessageKey, shouldAcceptRuntimeExit } from '../src/utils/runtime-exit'
+
+describe('runtime exit acceptance', () => {
+ const current = {
+ serviceHealthy: true,
+ serviceRunning: true,
+ readinessCommitPending: false,
+ busyAction: null,
+ observedToken: 4,
+ currentToken: 4,
+ notOwned: true,
+ } as const
+
+ it('accepts an exit only after the current runtime loses ownership', () => {
+ expect(shouldAcceptRuntimeExit(current)).toBe(true)
+ expect(shouldAcceptRuntimeExit({ ...current, notOwned: false })).toBe(false)
+ expect(shouldAcceptRuntimeExit({ ...current, serviceHealthy: false })).toBe(false)
+ expect(shouldAcceptRuntimeExit({ ...current, serviceRunning: false })).toBe(false)
+ })
+
+ it('accepts an exit while the final readiness commit is pending', () => {
+ expect(shouldAcceptRuntimeExit({
+ ...current,
+ serviceHealthy: false,
+ readinessCommitPending: true,
+ })).toBe(true)
+ })
+
+ it('rejects delayed events and explicit service transitions', () => {
+ expect(shouldAcceptRuntimeExit({ ...current, currentToken: 5 })).toBe(false)
+ expect(shouldAcceptRuntimeExit({ ...current, busyAction: 'shutdown' })).toBe(false)
+ })
+
+ it('accepts a new process exit after readiness even before start or restart clears busy state', () => {
+ expect(shouldAcceptRuntimeExit({ ...current, busyAction: 'start' })).toBe(true)
+ expect(shouldAcceptRuntimeExit({ ...current, busyAction: 'restart' })).toBe(true)
+ })
+
+ it('does not suppress a real exit during an unrelated browser action', () => {
+ expect(shouldAcceptRuntimeExit({ ...current, busyAction: 'openBrowser' })).toBe(true)
+ })
+
+ it('preserves exit code zero as a known code', () => {
+ expect(runtimeExitMessageKey(0)).toBe('errors.process_exited_with_code')
+ expect(runtimeExitMessageKey(null)).toBe('errors.process_exited_without_code')
+ expect(runtimeExitMessageKey(undefined)).toBe('errors.process_exited_without_code')
+ })
+})