DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(ux): user-facing polish — listener leaks, port validation, error states, blocking IPC
[email protected]79307e8f2d62
diff --git a/src-tauri/src/service/cli/shim.rs b/src-tauri/src/service/cli/shim.rsindex 05182312..5189c321 100644--- a/src-tauri/src/service/cli/shim.rs+++ b/src-tauri/src/service/cli/shim.rs@@ -596,6 +596,7 @@ mod tests {}#[test]+ #[cfg(windows)]fn cmd_shim_contains_baked_paths() {let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());assert!(content.contains(r"C:\Users\test\AppData\Roaming"));@@ -653,6 +654,7 @@ mod tests {}#[test]+ #[cfg(windows)]fn ps1_shim_escapes_quotes() {let dir = PathBuf::from(r"C:\Users\o'brien\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop");let content = build_ps1_shim(&dir, &sample_dsh_home());diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex 33a2451e..8aaea0ef 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -667,8 +667,12 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {log::info!("Stopping Harness service...");// 重置启动守卫,确保后续 launch 可以重新拉起;仅结束持有的根进程树。+ // 进程终止涉及 WaitForSingleObject(至多 5s)与 taskkill/kill 等同步阻塞+ // 调用,移出 Tokio 执行线程避免卡住其他并发任务(WARN-7/P2-#20)。LAUNCH_GUARD.store(false, Ordering::SeqCst);- terminate_owned_process();+ tauri::async_runtime::spawn_blocking(terminate_owned_process)+ .await+ .map_err(|e| format!("STOP_FAILED: {e}"))?;// 清理孤儿清扫标记:正常停止的实例不应被下次启动当作残留let _ = fs::remove_file(harness_pid_path(&app_handle));@@ -713,7 +717,15 @@ pub async fn install(// (不在 .harness.pid 标记中)同样从 dependencies/dsh 启动、占用目录文件// 句柄,会导致更新切换目录失败(INSTALL_BACKUP_FAILED, os error 32)。// 按命令行路径精确清扫所有本应用 dsh 安装目录启动的进程。- terminate_stale_harness_processes(app_handle);+ // 枚举/结束涉及 powershell 枚举与 taskkill(同步阻塞),移出 Tokio 线程。+ {+ let handle = app_handle.clone();+ tauri::async_runtime::spawn_blocking(move || {+ terminate_stale_harness_processes(&handle);+ })+ .await+ .map_err(|e| format!("STOP_FAILED: {e}"))?;+ }let window = app_handle.get_webview_window("main")diff --git a/src/components/config-debug.tsx b/src/components/config-debug.tsxindex a33df275..e4915e2e 100644--- a/src/components/config-debug.tsx+++ b/src/components/config-debug.tsx@@ -40,21 +40,21 @@ export function ConfigDebug() {const { serviceRunning, busyAction, preinstall } = useStore(store.harness)const { updateInfo } = useStore(store.harnessUpdater)- const [port, setPort] = useState<number>(3080)+ // 端口编辑态:用户尚未输入时为 undefined,由 `data?.port ?? 3080` 提供初值。+ // 初值不写入 state(避免 queryFn 副作用 / effect 同步),渲染与保存时统一+ // 读取 config 数据;用户一旦输入即以输入值为准。+ const [portInput, setPortInput] = useState<number>()const { data: info } = useQuery({queryKey: ['info'],queryFn: () => invoke<RuntimeInfo>('get_runtime_info'),})- const { refetch: refreshConfig } = useQuery({+ const { data: config, refetch: refreshConfig } = useQuery({queryKey: ['config'],- queryFn: async () => {- const config = await invoke<AppConfig>('get_app_config')- setPort(config.port)- return config- },+ queryFn: () => invoke<AppConfig>('get_app_config'),})+ const port = portInput ?? config?.port ?? 3080const { data: cliStatus, refetch: refreshCliStatus } = useQuery({queryKey: ['cli_status'],@@ -73,6 +73,10 @@ export function ConfigDebug() {await refreshLogs()toast(t('messages.logs_cleared'))},+ onError: (err: unknown) => {+ console.error('[ConfigDebug] clear logs failed:', err)+ toast(t('messages.logs_clear_failed'), { variant: 'danger' })+ },})const { mutate: onToggleCliLink } = useMutation({@@ -80,6 +84,10 @@ export function ConfigDebug() {await invoke<AppConfig>('update_app_config', { cliLinkEnabled: enabled })await refreshCliStatus()},+ onError: (err: unknown) => {+ console.error('[ConfigDebug] toggle cli link failed:', err)+ toast(t('messages.cli_link_failed'), { variant: 'danger' })+ },})const { mutate: onCopyServiceUrl } = useMutation({@@ -87,10 +95,18 @@ export function ConfigDebug() {await invoke('copy_service_url')toast(t('messages.copy_success'))},+ onError: (err: unknown) => {+ console.error('[ConfigDebug] copy url failed:', err)+ toast(t('messages.copy_failed'), { variant: 'danger' })+ },})const { mutate: onSavePort } = useMutation({mutationFn: async (port: number) => {+ // 保存前校验:必须是 1–65535 的整数(输入框可能被清空成 0 / 浮点 / NaN)+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new Error('PORT_INVALID')+ }await invoke<AppConfig>('update_app_config', { port })await refreshConfig()const key = toast(t('messages.port_changed'), {@@ -106,10 +122,23 @@ export function ConfigDebug() {},})},+ onError: (err: unknown) => {+ console.error('[ConfigDebug] save port failed:', err)+ if (String(err).includes('PORT_INVALID')) {+ toast(t('messages.port_invalid'), { variant: 'danger' })+ }+ else {+ toast(t('messages.port_save_failed'), { variant: 'danger' })+ }+ },})const { mutate: onRevealDataDir } = useMutation({mutationFn: () => invoke('reveal_data_dir'),+ onError: (err: unknown) => {+ console.error('[ConfigDebug] reveal data dir failed:', err)+ toast(t('messages.reveal_dir_failed'), { variant: 'danger' })+ },})return (@@ -267,7 +296,7 @@ export function ConfigDebug() {type="number"variant="secondary"value={String(port)}- onChange={e => setPort(Number(e.target.value))}+ onChange={e => setPortInput(Number(e.target.value))}className="w-24 h-8 rounded-md [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"aria-label={t('ui.port')}/>diff --git a/src/components/download-core-dialog.tsx b/src/components/download-core-dialog.tsxindex 7f0750a8..aea4f213 100644--- a/src/components/download-core-dialog.tsx+++ b/src/components/download-core-dialog.tsx@@ -59,7 +59,9 @@ export function DownloadCoreDialog(props: DownloadCoreDialogProps) {}}).then((fn) => {- unlisten = fn+ // 竞态防护:组件已卸载而 listen 才 resolve → 立即注销防泄漏+ if (cancelled) fn()+ else unlisten = fn}).catch(() => {})diff --git a/src/config/client.ts b/src/config/client.tsindex 9f692601..20ad582e 100644--- a/src/config/client.ts+++ b/src/config/client.ts@@ -1,3 +1,21 @@-import { QueryClient } from '@tanstack/react-query'+import { MutationCache, QueryClient } from '@tanstack/react-query'-export const queryClient = new QueryClient()+/**+ * 全局 QueryClient。+ *+ * - `retry: false`:本地 Tauri IPC 连续调用没有"瞬时网络抖动"概念,失败重试+ * 只会在 IPC 层重复排队、无收益,失败应当直接呈现给调用方;+ * - `MutationCache.onError`:兜底打印(各 mutation 已按场景提供 onError 展示,+ * 这里保证任何遗漏的失败都至少留痕,不吞错)。+ */+export const queryClient = new QueryClient({+ defaultOptions: {+ mutations: { retry: false },+ queries: { retry: false },+ },+ mutationCache: new MutationCache({+ onError: (error) => {+ console.error('[QueryClient] unhandled mutation error:', error)+ },+ }),+})\ No newline at end of filediff --git a/src/hooks/use-dsh-cores.ts b/src/hooks/use-dsh-cores.tsindex cfd86717..e26bb877 100644--- a/src/hooks/use-dsh-cores.ts+++ b/src/hooks/use-dsh-cores.ts@@ -58,15 +58,19 @@ export function useDshCores(): UseDshCoresResult {})useEffect(() => {+ let disposed = falselet unlisten: (() => void) | undefinedlisten('setting_updated', () => {void queryClient.invalidateQueries({ queryKey: ['cores'] })}).then((fn) => {- unlisten = fn+ // 竞态防护:若组件已卸载而 listen 才 resolve,立即注销防泄漏+ if (disposed) fn()+ else unlisten = fn}).catch(() => {})return () => {+ disposed = trueunlisten?.()}}, [queryClient])diff --git a/src/hooks/use-dsh-profiles.ts b/src/hooks/use-dsh-profiles.tsindex b7726028..066f83d2 100644--- a/src/hooks/use-dsh-profiles.ts+++ b/src/hooks/use-dsh-profiles.ts@@ -45,15 +45,19 @@ export function useDshProfiles(): UseDshProfilesResult {// 后端设置变更(切换档案等)后刷新档案列表useEffect(() => {+ let disposed = falselet unlisten: (() => void) | undefinedlisten('setting_updated', () => {void queryClient.invalidateQueries({ queryKey: ['profiles'] })}).then((fn) => {- unlisten = fn+ // 竞态防护:若组件已卸载而 listen 才 resolve,立即注销防泄漏+ if (disposed) fn()+ else unlisten = fn}).catch(() => {})return () => {+ disposed = trueunlisten?.()}}, [queryClient])diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex db3c6f85..4c88d690 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -34,6 +34,7 @@"preinstall.cancelling": "Cancelling...","preinstall.open_repo": "Open repository of {{name}}","preinstall.failed": "Installation failed",+ "preinstall.load_failed": "Failed to load preinstall plugin list","preinstall.empty": "No preinstalled plugins available.","preinstall.settings_title": "Recommended Plugins","preinstall.settings_hint": "Reopen the preset wizard to re-select or install recommended plugins.",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex 9e75c66b..0417757f 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -34,6 +34,7 @@"preinstall.cancelling": "正在取消...","preinstall.open_repo": "打开 {{name}} 的仓库","preinstall.failed": "安装失败",+ "preinstall.load_failed": "预装插件列表加载失败","preinstall.empty": "暂无可预装的插件。","preinstall.settings_title": "预装插件","preinstall.settings_hint": "重新打开预设引导,可重新选择或安装推荐的插件。",diff --git a/src/layout/components/preinstall-setup.tsx b/src/layout/components/preinstall-setup.tsxindex 5de72839..45363e7c 100644--- a/src/layout/components/preinstall-setup.tsx+++ b/src/layout/components/preinstall-setup.tsx@@ -199,21 +199,43 @@ export function PreinstallSetup() {{/* 插件列表 */}<div className="space-y-3 flex-wrap gap-2"><If- cond={preinstall.plugins.length > 0}+ cond={preinstall.loadError === ''}else={(- <Empty>{t('preinstall.empty')}</Empty>+ // 列表加载失败(区别于空列表):错误说明 + 重试+ <div className="flex flex-col items-center gap-2 rounded-md border border-danger/30 bg-danger/5 p-4 text-center">+ <p className="text-xs font-medium text-danger">{t('preinstall.load_failed')}</p>+ <p className="max-h-[80px] max-w-full overflow-y-auto break-all font-mono text-[11px] text-muted">+ {preinstall.loadError}+ </p>+ <Button+ className="h-8 rounded-md"+ size="sm"+ variant="primary"+ onPress={() => void store.harness.loadPreinstallPlugins()}+ isDisabled={preinstall.loading}+ >+ {t('app.retry')}+ </Button>+ </div>)}>- {preinstall.plugins.map(plugin => (- <PluginRow- key={plugin.id}- plugin={plugin}- checked={effectiveSelected.has(plugin.id)}- disabled={installing}- onToggle={toggle}- onOpenRepo={openRepo}- />- ))}+ <If+ cond={preinstall.plugins.length > 0}+ else={(+ <Empty>{t('preinstall.empty')}</Empty>+ )}+ >+ {preinstall.plugins.map(plugin => (+ <PluginRow+ key={plugin.id}+ plugin={plugin}+ checked={effectiveSelected.has(plugin.id)}+ disabled={installing}+ onToggle={toggle}+ onOpenRepo={openRepo}+ />+ ))}+ </If></If></div>diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex b51e638d..7a2370d5 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -171,7 +171,10 @@ export const harness = defineStore({/** 用户触发了“取消”但仍需等后端结束进程树 */cancelling: false,logs: [] as string[],+ /** 安装失败错误(区别于下面列表加载失败) */error: '',+ /** 拉取预装插件列表失败(区别于空列表;UI 据此展示错误态 + 重试) */+ loadError: '',},serviceUrl: 'http://127.0.0.1:3080',/** 带时间戳的 iframe 地址(boot 时生成一次,避免缓存) */@@ -553,9 +556,13 @@ export const harness = defineStore({this.preinstall.loading = truetry {this.preinstall.plugins = await invoke<PreinstallPlugin[]>('get_preinstall_plugins')+ // 成功加载后清除历史加载错误,避免残留错误态遮蔽新列表+ this.preinstall.loadError = ''}catch (err) {console.error('[Harness] failed to load preinstall plugins:', err)+ // 记录错误而非伪装空列表:UI 据此展示错误态与重试按钮+ this.preinstall.loadError = String(err)}finally {this.preinstall.loading = false@@ -607,17 +614,23 @@ export const harness = defineStore({// 后端结束进程树导致 `install_preinstall_plugins` 提前返回并进入 catch,// 通过 installing=false 让其回到列表态而不是报错态。this.preinstall.cancelling = true+ // 一次性监听:先挂事件(拿到注销函数再 invoke),finally 里注销,+ // 避免每次取消都永久注册一个 `preinstall-cancelled` 监听(泄漏)。+ let unlisten: (() => void) | undefinedtry {- await invoke('cancel_preinstall_plugins')- await listen<unknown>('preinstall-cancelled', () => {+ unlisten = await listen<unknown>('preinstall-cancelled', () => {this.preinstall.installing = falsethis.preinstall.cancelling = false})+ await invoke('cancel_preinstall_plugins')}catch (err) {console.error('[Harness] cancel preinstall failed:', err)this.preinstall.cancelling = false}+ finally {+ unlisten?.()+ }},/** 跳过预装插件引导:记录状态后继续启动服务 */