DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(ui): drive views from global store and shared primitives
hairyfbb41859b1ddb
diff --git a/src/app.tsx b/src/app.tsxindex 2c06983d..9bc0c978 100644--- a/src/app.tsx+++ b/src/app.tsx@@ -1,133 +1,37 @@-import { useState } from 'react'+import { useEffect } from 'react'+import { useStore } from 'valtio-define'+import DebugSidebar from './components/debug-sidebar'import DownloadToast from './components/download-toast'-import HarnessView from './components/harness-view'-import SidebarPanel from './components/sidebar-panel'+import HarnessUpdater from './components/harness-updater'+import HarnessWebview from './components/harness-webview'import SidebarToggle from './components/sidebar-toggle'-import UpdateToast from './components/update-toast'import { useDshTheme } from './hooks/use-dsh-theme'-import { useHarness } from './hooks/use-harness'+import { store } from './store'+/**- * 应用根组件:组合 useHarness 业务 hook 与各视图组件,- * 自身只保留侧边栏展开状态这类纯 UI 状态。+ * 应用根组件:只负责首次启动与整体布局。+ * 业务状态与操作方法全部收敛到 valtio-define store,+ * 各子组件自行订阅 store,不再通过 props 透传回调与状态。*/export default function App() {useDshTheme()- const {- status,- installer,- errorMsg,- serviceUrl,- iframeError,- iframeKey,- serviceHealthy,- updateInfo,- updating,- serviceRunning,- busyAction,- downloadNotice,- iframeSrc,- boot,- restart,- shutdown,- start,- openBrowser,- handleUpdate,- refreshIframe,- markIframeLoaded,- markIframeError,- dismissUpdate,- dismissDownload,- } = useHarness()-- const [sidebarOpen, setSidebarOpen] = useState(() => {- const saved = localStorage.getItem('sidebarOpen')- return saved === null ? false : saved === 'true'- })-- // 右下角触发点:展开/收起侧边栏- function handleToggleSidebar() {- setSidebarOpen((prev) => {- const next = !prev- localStorage.setItem('sidebarOpen', String(next))- return next- })- }-- // 点击侧边栏外内容(遮罩)时收起侧边栏- function handleCloseSidebar() {- setSidebarOpen(false)- localStorage.setItem('sidebarOpen', 'false')- }-- const harnessViewProps = {- installer,- serviceHealthy,- iframeError,- iframeKey,- iframeSrc,- serviceUrl,- onRetry: boot,- onIframeLoad: markIframeLoaded,- onIframeError: markIframeError,- onRefresh: refreshIframe,- }+ const { status } = useStore(store.harness)- if (status === 'error') {- return (- <div className="flex h-screen w-screen">- <HarnessView- {...harnessViewProps}- status="error"- errorMsg={serviceUrl ? `${errorMsg} (${serviceUrl})` : errorMsg}- />- {!sidebarOpen && (- <SidebarToggle lifted={false} onClick={handleToggleSidebar} />- )}- <SidebarPanel- open={sidebarOpen}- serviceRunning={serviceRunning}- busyAction={busyAction}- onClose={handleCloseSidebar}- onRestart={restart}- onShutdown={shutdown}- onStart={start}- onOpenBrowser={openBrowser}- />- </div>- )- }+ // 首次挂载自动启动 harness(store 内部对 StrictMode 重复挂载去重)+ useEffect(() => {+ store.harness.startup()+ }, [])- if (status !== 'ready') {- return (- <div className="flex h-screen w-screen">- <HarnessView {...harnessViewProps} status={status} errorMsg="" />- </div>- )- }+ // 安装/启动过程中不展示侧边栏;就绪与错误态才展示+ const showSidebar = status === 'ready' || status === 'error'return (<div className="flex h-screen w-screen">- <HarnessView {...harnessViewProps} status="ready" errorMsg="" />- <UpdateToast- info={updateInfo}- updating={updating}- onUpdate={handleUpdate}- onDismiss={dismissUpdate}- />- <DownloadToast notice={downloadNotice} onClose={dismissDownload} />- {!sidebarOpen && (- <SidebarToggle lifted={updateInfo !== null && !updating} onClick={handleToggleSidebar} />- )}- <SidebarPanel- open={sidebarOpen}- serviceRunning={serviceRunning}- busyAction={busyAction}- onClose={handleCloseSidebar}- onRestart={restart}- onShutdown={shutdown}- onStart={start}- onOpenBrowser={openBrowser}- />+ <HarnessWebview />+ {status === 'ready' && <HarnessUpdater />}+ {status === 'ready' && <DownloadToast />}+ {showSidebar && <SidebarToggle />}+ {showSidebar && <DebugSidebar />}</div>)}diff --git a/src/components/sidebar-panel.tsx b/src/components/debug-sidebar.tsxsimilarity index 53%rename from src/components/sidebar-panel.tsxrename to src/components/debug-sidebar.tsxindex 58b242c5..ca7eb88f 100644--- a/src/components/sidebar-panel.tsx+++ b/src/components/debug-sidebar.tsx@@ -1,6 +1,23 @@import { invoke } from '@tauri-apps/api/core'import { useEffect, useState } from 'react'-import { useI18n } from '../i18n/i18n-context'+import { useStore } from 'valtio-define'+import { harness } from '../store/modules/harness'+import { setting, useI18n } from '../store/modules/setting'+import {+ button,+ codeBlock,+ dataDesc,+ dataTerm,+ drawer,+ input,+ logPanel,+ notice,+ overlay,+ sectionTitle,+ select,+ spinner,+ statusPill,+} from './primitives'export interface RuntimeInfo {app_version: string@@ -27,48 +44,20 @@ export interface CliLinkStatus {shim_path: string}-export type SidebarBusyAction = 'restart' | 'shutdown' | 'start' | 'openBrowser' | null--interface SidebarPanelProps {- open: boolean- serviceRunning: boolean- busyAction: SidebarBusyAction- onClose: () => void- onRestart: () => void- onShutdown: () => void- onStart: () => void- onOpenBrowser: () => void-}--// 按钮内的小型加载指示器:边框旋转动画,颜色跟随当前文字。-// 用 animate-load-spin(直接 animation + keyframes)而非 animate-spin,-// 避免 Tailwind var() 间接层在 WebView2 下不旋转。+/** 按钮内的小型加载指示器:边框旋转动画,颜色跟随当前文字 */function Spinner() {- return (- <span className="inline-block h-3 w-3 shrink-0 animate-load-spin rounded-full border-2 border-current border-t-transparent" />- )+ return <span className={spinner()} />}-export default function SidebarPanel({- open,- serviceRunning,- busyAction,- onClose,- onRestart,- onShutdown,- onStart,- onOpenBrowser,-}: SidebarPanelProps) {+/**+ * 右侧调试侧边栏:运行时信息、服务操作、设置与日志。+ * 展开状态来自 setting store;服务状态与操作(重启/停止/启动/打开浏览器)+ * 直接引用 harness store 的方法,不再接收 onClose/onRestart 等回调 props。+ */+export default function DebugSidebar() {const { t, language, setLanguage } = useI18n()- // 官方 sm 按钮几何:h28 / 圆角 14px 胶囊 / padding 0 10px / 12px 字号(对应 ui-primitives Button)- const btnBase- = 'inline-flex h-7 cursor-pointer items-center justify-center gap-1 rounded-[14px] px-2.5 text-xs text-ink transition-colors disabled:cursor-not-allowed disabled:opacity-40'- // ghost 风格:透明底 + 官方 interactive-bg-hover/active 微透明底- const btnGhost = `${btnBase} hover:bg-btn-hover active:bg-btn-active`- // 主按钮:官方中性品牌色填充,无边框- const btnPrimary = `${btnBase} bg-btn-fill text-btn-ink hover:bg-btn-fill-hover`- const btnDanger = `${btnGhost} text-danger hover:bg-btn-danger-hover`- const btnBlock = ' mt-1.5 w-full'+ const { sidebarOpen } = useStore(setting)+ const { serviceRunning, busyAction } = useStore(harness)const [info, setInfo] = useState<RuntimeInfo | null>(null)const [port, setPort] = useState('3080')const [autoStart, setAutoStart] = useState(true)@@ -76,7 +65,7 @@ export default function SidebarPanel({const [cliToggled, setCliToggled] = useState(false)const [cliStatus, setCliStatus] = useState<CliLinkStatus | null>(null)const [logs, setLogs] = useState('')- const [notice, setNotice] = useState('')+ const [noticeMsg, setNoticeMsg] = useState('')const [saving, setSaving] = useState(false)const [busy, setBusy] = useState<string | null>(null)@@ -89,7 +78,7 @@ export default function SidebarPanel({setInfo(nextInfo)}catch (err) {- console.error('[SidebarPanel] failed to load runtime info:', err)+ console.error('[DebugSidebar] failed to load runtime info:', err)}finally {setBusy(null)@@ -104,7 +93,7 @@ export default function SidebarPanel({setCliLinkEnabled(nextConfig.cli_link_enabled)}catch (err) {- console.error('[SidebarPanel] failed to load config:', err)+ console.error('[DebugSidebar] failed to load config:', err)}}@@ -113,7 +102,7 @@ export default function SidebarPanel({setCliStatus(await invoke<CliLinkStatus>('get_cli_link_status'))}catch (err) {- console.error('[SidebarPanel] failed to load cli link status:', err)+ console.error('[DebugSidebar] failed to load cli link status:', err)}}@@ -125,7 +114,7 @@ export default function SidebarPanel({setLogs(await invoke<string>('read_service_logs', { maxBytes: 64 * 1024 }))}catch (err) {- console.error('[SidebarPanel] failed to read logs:', err)+ console.error('[DebugSidebar] failed to read logs:', err)}finally {setBusy(null)@@ -141,11 +130,11 @@ export default function SidebarPanel({}, [])useEffect(() => {- if (!notice)+ if (!noticeMsg)return- const timer = setTimeout(setNotice, 2500, '')+ const timer = setTimeout(setNoticeMsg, 2500, '')return () => clearTimeout(timer)- }, [notice])+ }, [noticeMsg])async function saveConfig() {setSaving(true)@@ -157,7 +146,7 @@ export default function SidebarPanel({cliLinkEnabled,})setPort(String(nextConfig.port))- setNotice(+ setNoticeMsg(cliToggled? cliLinkEnabled? t('messages.cli_link_enabled')@@ -168,8 +157,8 @@ export default function SidebarPanel({await refreshCliStatus()}catch (err) {- console.error('[SidebarPanel] failed to save config:', err)- setNotice(t('messages.save_failed'))+ console.error('[DebugSidebar] failed to save config:', err)+ setNoticeMsg(t('messages.save_failed'))}finally {setSaving(false)@@ -182,10 +171,10 @@ export default function SidebarPanel({setBusy('copy')try {await invoke('copy_service_url')- setNotice(t('messages.copy_success'))+ setNoticeMsg(t('messages.copy_success'))}catch {- setNotice(t('messages.copy_failed'))+ setNoticeMsg(t('messages.copy_failed'))}finally {setBusy(null)@@ -199,10 +188,10 @@ export default function SidebarPanel({try {await invoke('clear_service_logs')setLogs('')- setNotice(t('messages.logs_cleared'))+ setNoticeMsg(t('messages.logs_cleared'))}catch (err) {- console.error('[SidebarPanel] failed to clear logs:', err)+ console.error('[DebugSidebar] failed to clear logs:', err)}finally {setBusy(null)@@ -217,7 +206,7 @@ export default function SidebarPanel({await invoke('reveal_data_dir')}catch (err) {- console.error('[SidebarPanel] failed to reveal data dir:', err)+ console.error('[DebugSidebar] failed to reveal data dir:', err)}finally {setBusy(null)@@ -227,34 +216,33 @@ export default function SidebarPanel({return (<>{/* 点击侧边栏外内容时关闭侧边栏;透明遮罩位于内容之上、侧边栏之下 */}- {open && <div aria-hidden onClick={onClose} className="fixed inset-0 z-[25]" />}- <aside- className={`fixed inset-y-0 right-0 z-30 flex w-[300px] flex-col overflow-y-auto border-l border-line bg-panel shadow-2xl transition-transform duration-200 ease-out ${open ? 'translate-x-0' : 'translate-x-full'- }`}- >+ {sidebarOpen && <div aria-hidden onClick={setting.closeSidebar} className={overlay()} />}+ <aside className={drawer({ open: sidebarOpen })}><div className="px-3 pt-4 pb-5"><div className="mb-[18px]">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">{t('ui.connection_status')}</h3>- <span- className={`inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold ${serviceRunning ? 'bg-[rgba(34,197,94,0.15)] text-ok' : 'bg-[rgba(242,90,90,0.15)] text-danger'- }`}- >+ <h3 className={sectionTitle()}>{t('ui.connection_status')}</h3>+ <span className={statusPill({ tone: serviceRunning ? 'running' : 'stopped' })}>{serviceRunning ? t('ui.running') : t('ui.stopped')}</span></div><div className="mb-[18px]">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">{t('ui.service_url')}</h3>+ <h3 className={sectionTitle()}>{t('ui.service_url')}</h3><div className="flex items-center gap-1.5">- <code className="flex-1 truncate rounded-md border border-line bg-panel2 px-2 py-1.5 text-xs">{info?.service_url ?? '-'}</code>- <button className={btnGhost} onClick={copyUrl} disabled={busy === 'copy'} title={t('app.copy_url')}>+ <code className={codeBlock()}>{info?.service_url ?? '-'}</code>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={copyUrl}+ disabled={busy === 'copy'}+ title={t('app.copy_url')}+ >{busy === 'copy' && <Spinner />}{t('buttons.copy')}</button></div><button- className={`${btnGhost}${btnBlock}`}- onClick={onOpenBrowser}+ className={button({ size: 'sm', tone: 'ghost', block: true })}+ onClick={harness.openBrowser}disabled={busyAction !== null}>{busyAction === 'openBrowser' && <Spinner />}@@ -263,28 +251,44 @@ export default function SidebarPanel({</div><div className="mb-[18px]">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">{t('ui.actions')}</h3>+ <h3 className={sectionTitle()}>{t('ui.actions')}</h3><div className="flex flex-wrap gap-1.5">{serviceRunning? (<>- <button className={btnGhost} onClick={onRestart} disabled={busyAction !== null}>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={harness.restart}+ disabled={busyAction !== null}+ >{busyAction === 'restart' && <Spinner />}{t('app.restart')}</button>- <button className={btnDanger} onClick={onShutdown} disabled={busyAction !== null}>+ <button+ className={button({ size: 'sm', tone: 'danger' })}+ onClick={harness.shutdown}+ disabled={busyAction !== null}+ >{busyAction === 'shutdown' && <Spinner />}{t('app.shutdown')}</button></>): (- <button className={btnPrimary} onClick={onStart} disabled={busyAction !== null}>+ <button+ className={button({ size: 'sm', tone: 'primary' })}+ onClick={harness.start}+ disabled={busyAction !== null}+ >{busyAction === 'start' && <Spinner />}{t('app.retry')}</button>)}- <button className={btnGhost} onClick={refreshInfo} disabled={busy === 'refreshInfo'}>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={refreshInfo}+ disabled={busy === 'refreshInfo'}+ >{busy === 'refreshInfo' && <Spinner />}{t('app.refresh')}</button>@@ -292,28 +296,32 @@ export default function SidebarPanel({</div><div className="mb-[18px]">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">{t('ui.app_info')}</h3>+ <h3 className={sectionTitle()}>{t('ui.app_info')}</h3><dl className="m-0 text-xs">- <dt className="mt-1.5 text-muted">{t('ui.current_version')}</dt>- <dd className="mt-0.5 break-all">{info?.app_version ?? '-'}</dd>- <dt className="mt-1.5 text-muted">{t('ui.dsh_version')}</dt>- <dd className="mt-0.5 break-all">{info?.dsh_version ?? '-'}</dd>- <dt className="mt-1.5 text-muted">{t('ui.node_version')}</dt>- <dd className="mt-0.5 break-all">+ <dt className={dataTerm()}>{t('ui.current_version')}</dt>+ <dd className={dataDesc()}>{info?.app_version ?? '-'}</dd>+ <dt className={dataTerm()}>{t('ui.dsh_version')}</dt>+ <dd className={dataDesc()}>{info?.dsh_version ?? '-'}</dd>+ <dt className={dataTerm()}>{t('ui.node_version')}</dt>+ <dd className={dataDesc()}>v{info?.node_version ?? '-'}</dd>- <dt className="mt-1.5 text-muted">Platform</dt>- <dd className="mt-0.5 break-all">+ <dt className={dataTerm()}>Platform</dt>+ <dd className={dataDesc()}>{info?.platform ?? '-'}{' '}/{info?.arch ?? '-'}</dd>- <dt className="mt-1.5 text-muted">{t('ui.data_dir')}</dt>+ <dt className={dataTerm()}>{t('ui.data_dir')}</dt><dd className="mt-0.5 flex items-center justify-center gap-2" title={info?.data_dir}><div className="break-all truncate">{info?.data_dir ?? '-'}</div>- <button className={`${btnGhost} flex-shrink-0 text-[10px]`} onClick={revealDataDir} disabled={busy === 'revealDataDir'}>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={revealDataDir}+ disabled={busy === 'revealDataDir'}+ >{busy === 'revealDataDir' && <Spinner />}{t('app.reveal_dir')}</button>@@ -322,23 +330,19 @@ export default function SidebarPanel({</div><div className="mb-[18px]">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">{t('ui.settings')}</h3>+ <h3 className={sectionTitle()}>{t('ui.settings')}</h3><label className="mb-2 flex items-center gap-2"><span>{t('ui.port')}</span><input- className="flex-1 rounded-md border border-line bg-panel2 px-2 py-1.5 text-[13px] text-ink outline-none focus:border-accent/60"+ className={input()}value={port}onChange={e => setPort(e.target.value)}inputMode="numeric"/></label>- {/* <label className="mb-2 flex cursor-pointer items-center gap-2">- <input type="checkbox" checked={autoStart} onChange={(e) => setAutoStart(e.target.checked)} />- <span>{t("ui.auto_start")}</span>- </label> */}<p className="mb-1 mt-2 text-[11px] font-semibold text-muted">{t('ui.cli_link')}</p>- <label className="flex cursor-pointer items-center gap-2 mb-1">+ <label className="mb-1 flex cursor-pointer items-center gap-2"><inputtype="checkbox"checked={cliLinkEnabled}@@ -350,15 +354,13 @@ export default function SidebarPanel({<span>{t('ui.cli_link_enabled')}</span></label><div className="mb-2 rounded-md border border-line bg-panel2 px-2 py-1.5">- <p className="mt-1 text-[11px] leading-[1.5] text-muted">- {cliStatus && (- <code className="mt-1 block break-all text-[10px] text-muted truncate">{cliStatus.bin_dir}</code>- )}- </p>+ {cliStatus && (+ <code className="mt-1 block truncate break-all text-[10px] text-muted">{cliStatus.bin_dir}</code>+ )}<p className="mt-1 text-[11px] text-muted">{t('ui.cli_link_hint')}</p></div>- <button className={`${btnPrimary}${btnBlock}`} onClick={saveConfig} disabled={saving}>+ <button className={button({ size: 'sm', tone: 'primary', block: true })} onClick={saveConfig} disabled={saving}>{saving? (<>@@ -376,7 +378,7 @@ export default function SidebarPanel({:</span><select- className="flex-1 rounded-md border border-line bg-panel2 px-2 py-1 text-[13px] text-ink outline-none"+ className={select()}value={language}onChange={e => setLanguage(e.target.value as 'en' | 'zh')}>@@ -387,22 +389,31 @@ export default function SidebarPanel({</div><div className="flex flex-col gap-1.5">- <h3 className="mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted">+ <h3 className={sectionTitle()}>{t('ui.logs')}- <button className={btnGhost} onClick={refreshLogs} disabled={busy === 'refreshLogs'} title={t('buttons.refresh_logs')}>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={refreshLogs}+ disabled={busy === 'refreshLogs'}+ title={t('buttons.refresh_logs')}+ >{busy === 'refreshLogs' ? <Spinner /> : '↻'}</button></h3>- <pre className="m-0 max-h-[200px] overflow-auto whitespace-pre-wrap break-all rounded-md border border-line bg-log-bg px-2 py-2 text-[11px] leading-[1.45] text-log-ink">{logs || t('ui.no_logs')}</pre>- <button className={btnGhost} onClick={clearLogs} disabled={busy === 'clearLogs'}>+ <pre className={logPanel()}>{logs || t('ui.no_logs')}</pre>+ <button+ className={button({ size: 'sm', tone: 'ghost' })}+ onClick={clearLogs}+ disabled={busy === 'clearLogs'}+ >{busy === 'clearLogs' && <Spinner />}{t('buttons.clear_logs')}</button></div>- {notice && (- <div className="fixed bottom-[18px] left-1/2 z-10 -translate-x-1/2 rounded-lg border border-line bg-panel2 px-3.5 py-2 text-[13px] shadow-[0_8px_24px_rgba(0,0,0,0.45)]">- {notice}+ {noticeMsg && (+ <div className={notice()}>+ {noticeMsg}</div>)}</div>diff --git a/src/components/download-toast.tsx b/src/components/download-toast.tsxindex 6c1e5e53..45331646 100644--- a/src/components/download-toast.tsx+++ b/src/components/download-toast.tsx@@ -1,21 +1,13 @@-import type { DownloadFinishedPayload } from '../hooks/use-harness'import { invoke } from '@tauri-apps/api/core'-import { useI18n } from '../i18n/i18n-context'+import { useStore } from 'valtio-define'+import { download } from '../store/modules/download'+import { useI18n } from '../store/modules/setting'+import { button, toast } from './primitives'-// 官方按钮:胶囊形 + 中性品牌色(对应 ui-primitives Button)-const btnPrimary- = 'inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] bg-btn-fill px-3.5 text-sm leading-[22px] text-btn-ink transition-colors hover:bg-btn-fill-hover disabled:cursor-not-allowed disabled:opacity-40'-const btnGhost- = 'inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] px-3.5 text-sm leading-[22px] text-ink transition-colors hover:bg-btn-hover active:bg-btn-active'--interface DownloadToastProps {- notice: DownloadFinishedPayload | null- onClose: () => void-}--/** 右下角"下载已保存/失败"提示条 */-export default function DownloadToast({ notice, onClose }: DownloadToastProps) {+/** 右下角"下载已保存/失败"提示条:状态与关闭操作直接来自 download store */+export default function DownloadToast() {const { t } = useI18n()+ const { notice } = useStore(download)if (!notice) {return null@@ -25,12 +17,12 @@ export default function DownloadToast({ notice, onClose }: DownloadToastProps) {function revealInFolder(targetPath: string) {void invoke('reveal_in_folder', { path: targetPath }).catch((err) => {- console.error('[App] reveal_in_folder failed:', err)+ console.error('[Harness] reveal_in_folder failed:', err)})}return (- <div className="fixed right-4 bottom-4 z-50 flex max-w-[440px] items-start gap-3 rounded-lg border border-line bg-panel px-4 py-3 shadow-lg">+ <div className={toast({ size: 'md', align: 'start' })}><div className="min-w-0 flex-1"><p className="text-[13px] font-semibold text-ink">{success ? t('download.saved') : t('download.failed')}@@ -44,11 +36,11 @@ export default function DownloadToast({ notice, onClose }: DownloadToastProps) {)}</div>{success && path && (- <button className={btnPrimary} onClick={() => revealInFolder(path)}>+ <button className={button({ tone: 'primary' })} onClick={() => revealInFolder(path)}>{t('download.show_in_folder')}</button>)}- <button className={btnGhost} onClick={onClose}>+ <button className={button({ tone: 'ghost' })} onClick={download.dismiss}>{t('download.close')}</button></div>diff --git a/src/components/harness-updater.tsx b/src/components/harness-updater.tsxnew file mode 100644index 00000000..8532fe10--- /dev/null+++ b/src/components/harness-updater.tsx@@ -0,0 +1,29 @@+import { useStore } from 'valtio-define'+import { useI18n } from '../store/modules/setting'+import { updater } from '../store/modules/updater'+import { button, toast } from './primitives'++/** 右下角"发现新版本"提示条:状态与操作直接来自 updater store */+export default function HarnessUpdater() {+ const { t } = useI18n()+ const { updateInfo, updating } = useStore(updater)++ if (!updateInfo || updating) {+ return null+ }++ return (+ <div className={toast()}>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-semibold text-ink">{t('update.available', { tag: updateInfo.tag })}</p>+ <p className="mt-0.5 text-xs text-muted">{updateInfo.commit.slice(0, 7)}</p>+ </div>+ <button className={button({ tone: 'primary' })} onClick={updater.handleUpdate}>+ {t('update.now')}+ </button>+ <button className={button({ tone: 'ghost' })} onClick={updater.dismissUpdate}>+ {t('update.later')}+ </button>+ </div>+ )+}diff --git a/src/components/harness-view.tsx b/src/components/harness-view.tsxdeleted file mode 100644index 733d1463..00000000--- a/src/components/harness-view.tsx+++ /dev/null@@ -1,110 +0,0 @@-/* eslint-disable react/dom-no-unsafe-iframe-sandbox */-import type { InstallerState } from '../hooks/use-harness'-import type { SetupStatus } from './setup-screen'-import { useI18n } from '../i18n/i18n-context'-import Loadable from './loadable'-import SetupScreen from './setup-screen'--// 官方 md 主按钮:h36 / 圆角 18px 胶囊 / 中性品牌色填充无边框(对应 ui-primitives Button)-const btnPrimary- = 'inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] bg-btn-fill px-3.5 text-sm leading-[22px] text-btn-ink transition-colors hover:bg-btn-fill-hover disabled:cursor-not-allowed disabled:opacity-40'--interface HarnessViewProps {- status: SetupStatus- installer: InstallerState- errorMsg: string- serviceHealthy: boolean- iframeError: boolean- iframeKey: number- iframeSrc: string- serviceUrl: string- onRetry: () => void- onIframeLoad: () => void- onIframeError: () => void- onRefresh: () => void-}--/**- * 主区域视图:安装/错误态渲染 SetupScreen,- * 就绪态渲染 iframe(挂载后加载职责交给 dsh 应用内官方 boot 页,避免两套 loading 叠加)。- */-export default function HarnessView({- status,- installer,- errorMsg,- serviceHealthy,- iframeError,- iframeKey,- iframeSrc,- serviceUrl,- onRetry,- onIframeLoad,- onIframeError,- onRefresh,-}: HarnessViewProps) {- const { t } = useI18n()-- if (status === 'error') {- return (- <main className="relative flex-1 bg-canvas">- <SetupScreen- status="error"- title=""- detail=""- percentage={installer.percentage}- logs={installer.logs}- errorMsg={errorMsg}- onRetry={onRetry}- />- </main>- )- }-- if (status !== 'ready') {- return (- <main className="relative w-full bg-canvas">- <SetupScreen- status={status}- title={installer.title}- detail={installer.detail}- percentage={installer.percentage}- logs={installer.logs}- errorMsg=""- onRetry={onRetry}- />- </main>- )- }-- return (- <main className="relative flex-1 bg-canvas">- {serviceHealthy- ? (- <iframe- key={iframeKey}- className="block h-full w-full border-none bg-load-bg"- src={iframeSrc}- allow="clipboard-read; clipboard-write; camera; microphone; geolocation; display-capture; autoplay; encrypted-media; fullscreen"- sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-modals allow-downloads allow-storage-access-by-user-activation"- onLoad={onIframeLoad}- onError={onIframeError}- title={t('app.open_editor')}- />- )- : (- <div className="absolute inset-0 z-[1]">- <Loadable subtitle={t('status.loading')} />- </div>- )}- {serviceHealthy && iframeError && (- <div className="absolute inset-0 z-[1] flex flex-col items-center justify-center gap-3 bg-canvas text-ink">- <p>{t('ui.iframe_error')}</p>- <p className="text-muted">{t('ui.ensure_running', { url: serviceUrl })}</p>- <button className={btnPrimary} onClick={onRefresh}>- {t('app.retry')}- </button>- </div>- )}- </main>- )-}diff --git a/src/components/harness-webview.tsx b/src/components/harness-webview.tsxnew file mode 100644index 00000000..1237a3bd--- /dev/null+++ b/src/components/harness-webview.tsx@@ -0,0 +1,71 @@+/* eslint-disable react/dom-no-unsafe-iframe-sandbox */+import { CircleAlert } from 'lucide-react'+import { useStore } from 'valtio-define'+import { harness } from '../store/modules/harness'+import { useI18n } from '../store/modules/setting'+import Loadable from './loadable'+import Setup from './setup'++/**+ * 主区域视图:安装/错误态渲染 Setup,+ * 就绪态渲染 iframe(挂载后加载职责交给 dsh 应用内官方 boot 页,避免两套 loading 叠加)。+ * 状态与方法全部来自 harness store,不再接收 props。+ */+export default function HarnessWebview() {+ const { t } = useI18n()+ const {+ status,+ serviceHealthy,+ iframeError,+ iframeKey,+ iframeSrc,+ serviceUrl,+ } = useStore(harness)++ if (status === 'error') {+ return (+ <main className="relative flex-1 bg-canvas">+ <Setup />+ </main>+ )+ }++ if (status !== 'ready') {+ return (+ <main className="relative w-full bg-canvas">+ <Setup />+ </main>+ )+ }++ return (+ <main className="relative flex-1 bg-canvas">+ {serviceHealthy+ ? (+ <iframe+ key={iframeKey}+ className="block h-full w-full border-none bg-load-bg"+ src={iframeSrc}+ allow="clipboard-read; clipboard-write; camera; microphone; geolocation; display-capture; autoplay; encrypted-media; fullscreen"+ sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-modals allow-downloads allow-storage-access-by-user-activation"+ onLoad={harness.markIframeLoaded}+ onError={harness.markIframeError}+ title={t('app.open_editor')}+ />+ )+ : (+ <div className="absolute inset-0 z-[1]">+ <Loadable subtitle={t('status.loading')} />+ </div>+ )}+ {serviceHealthy && iframeError && (+ <Loadable+ icon={CircleAlert}+ title={t('ui.iframe_error')}+ errorMsg={t('ui.ensure_running', { url: serviceUrl })}+ onRetry={harness.refreshIframe}+ />+ )}+ </main>+ )+}diff --git a/src/components/loadable.tsx b/src/components/loadable.tsxindex e2d7250a..19043454 100644--- a/src/components/loadable.tsx+++ b/src/components/loadable.tsx@@ -1,6 +1,7 @@import type { LucideIcon } from 'lucide-react'import type { ReactNode } from 'react'-import { useI18n } from '../i18n/i18n-context'+import { useI18n } from '../store/modules/setting'+import { button } from './primitives'const LOG_LIMIT = 5@@ -26,7 +27,7 @@ export interface LoadableProps {/** 进度百分比(0-100),传入则显示进度条 */percentage?: number/** 安装日志行,传入则显示日志面板(空数组显示"等待日志"占位) */- logs?: string[]+ logs?: readonly string[]/** 错误信息,传入则切换为失败态(隐藏 spinner) */errorMsg?: string/** 失败态时的重试按钮回调 */@@ -74,7 +75,7 @@ export default function Loadable({{onRetry && (<button- className="inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] bg-btn-fill px-3.5 text-sm leading-[22px] text-btn-ink transition-colors hover:bg-btn-fill-hover disabled:cursor-not-allowed disabled:opacity-40"+ className={button({ tone: 'primary' })}onClick={onRetry}>{t('app.retry')}diff --git a/src/components/primitives.ts b/src/components/primitives.tsnew file mode 100644index 00000000..c0d0ac85--- /dev/null+++ b/src/components/primitives.ts@@ -0,0 +1,130 @@+import { tv } from 'tailwind-variants'++// ==================== 按钮 ====================+// 对应官方 ui-primitives Button 的两档几何:+// md(h36 / 圆角 18px 胶囊 / 14px 字号)与 sm(h28 / 圆角 14px 胶囊 / 12px 字号)。+// 颜色沿用官方 dsw alias token(bg-btn-fill / interactive-bg-* 等)。+export const button = tv({+ base: 'inline-flex cursor-pointer items-center justify-center gap-1 transition-colors disabled:cursor-not-allowed disabled:opacity-40',+ variants: {+ size: {+ sm: 'h-7 rounded-[14px] px-2.5 text-xs',+ md: 'h-9 rounded-[18px] px-3.5 text-sm leading-[22px]',+ },+ tone: {+ primary: 'bg-btn-fill text-btn-ink hover:bg-btn-fill-hover',+ ghost: 'text-ink hover:bg-btn-hover active:bg-btn-active',+ danger: 'text-danger hover:bg-btn-danger-hover',+ },+ block: {+ true: 'mt-1.5 w-full',+ },+ },+ defaultVariants: {+ size: 'md',+ tone: 'ghost',+ },+})++// 按钮内小型加载指示器:边框旋转动画,颜色跟随当前文字。+// 用 animate-load-spin(直接 animation + keyframes)而非 animate-spin,+// 避免 Tailwind var() 间接层在 WebView2 下不旋转。+export const spinner = tv({+ base: 'inline-block h-3 w-3 shrink-0 animate-load-spin rounded-full border-2 border-current border-t-transparent',+})++// ==================== 侧边栏 ====================+// 点击侧边栏外内容时关闭侧边栏的透明遮罩(位于内容之上、侧边栏之下)+export const overlay = tv({+ base: 'fixed inset-0 z-[25]',+})++// 右侧调试侧边栏抽屉+export const drawer = tv({+ base: 'fixed inset-y-0 right-0 z-30 flex w-[300px] flex-col overflow-y-auto border-l border-line bg-panel shadow-2xl transition-transform duration-200 ease-out',+ variants: {+ open: {+ true: 'translate-x-0',+ false: 'translate-x-full',+ },+ },+})++// 分组标题(h3)+export const sectionTitle = tv({+ base: 'mb-2 flex items-center justify-between gap-1.5 text-xs uppercase tracking-[0.06em] text-muted',+})++// 连接状态胶囊+export const statusPill = tv({+ base: 'inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold',+ variants: {+ tone: {+ running: 'bg-[rgba(34,197,94,0.15)] text-ok',+ stopped: 'bg-[rgba(242,90,90,0.15)] text-danger',+ },+ },+})++// 信息列表(dl)的 dt/dd+export const dataTerm = tv({+ base: 'mt-1.5 text-muted',+})+export const dataDesc = tv({+ base: 'mt-0.5 break-all',+})++// 代码/URL 展示块+export const codeBlock = tv({+ base: 'flex-1 truncate rounded-md border border-line bg-panel2 px-2 py-1.5 text-xs',+})++// 表单输入 / 下拉选择+export const input = tv({+ base: 'flex-1 rounded-md border border-line bg-panel2 px-2 py-1.5 text-[13px] text-ink outline-none focus:border-accent/60',+})+export const select = tv({+ base: 'flex-1 rounded-md border border-line bg-panel2 px-2 py-1 text-[13px] text-ink outline-none',+})++// 日志面板(pre)+export const logPanel = tv({+ base: 'm-0 max-h-[200px] overflow-auto whitespace-pre-wrap break-all rounded-md border border-line bg-log-bg px-2 py-2 text-[11px] leading-[1.45] text-log-ink',+})++// 侧边栏内底部居中的轻提示+export const notice = tv({+ base: 'fixed bottom-[18px] left-1/2 z-10 -translate-x-1/2 rounded-lg border border-line bg-panel2 px-3.5 py-2 text-[13px] shadow-[0_8px_24px_rgba(0,0,0,0.45)]',+})++// ==================== 浮动提示条 ====================+// 右下角浮动提示条(更新提示 / 下载完成提示)+export const toast = tv({+ base: 'fixed right-4 bottom-4 z-50 flex gap-3 rounded-lg border border-line bg-panel px-4 py-3 shadow-lg',+ variants: {+ size: {+ sm: 'max-w-[420px] items-center',+ md: 'max-w-[440px]',+ },+ align: {+ start: 'items-start',+ },+ },+ defaultVariants: {+ size: 'sm',+ },+})++// 右下角侧边栏展开按钮(lifted:上方有提示条时上移,避免重叠)+export const toggle = tv({+ base: 'fixed right-4 z-20 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-line bg-panel/80 text-ink shadow-lg backdrop-blur-md transition-colors hover:bg-panel-hover',+ variants: {+ lifted: {+ true: 'bottom-[84px]',+ false: 'bottom-4',+ },+ },+ defaultVariants: {+ lifted: false,+ },+})diff --git a/src/components/setup-screen.tsx b/src/components/setup.tsxsimilarity index 51%rename from src/components/setup-screen.tsxrename to src/components/setup.tsxindex 642f9cfd..5469256c 100644--- a/src/components/setup-screen.tsx+++ b/src/components/setup.tsx@@ -1,29 +1,11 @@import type { LucideIcon } from 'lucide-react'+import type { SetupStatus } from '../store/modules/harness'import { CircleAlert, CircleCheck, Download, Rocket, ScanSearch } from 'lucide-react'-import { useI18n } from '../i18n/i18n-context'+import { useStore } from 'valtio-define'+import { harness } from '../store/modules/harness'+import { useI18n } from '../store/modules/setting'import Loadable from './loadable'-export type SetupStatus = 'checking' | 'installing' | 'starting' | 'ready' | 'error'--export interface InstallProgress {- title: string- detail: string- log: string- type: string- percentage: number- progress: number-}--interface SetupScreenProps {- status: SetupStatus- title: string- detail: string- percentage: number- logs: string[]- errorMsg: string- onRetry: () => void-}-// 各阶段对应不同图标,保持与 logo 一致的黑白中性色调const STATUS_ICONS: Record<SetupStatus, LucideIcon> = {checking: ScanSearch,@@ -36,21 +18,15 @@ const STATUS_ICONS: Record<SetupStatus, LucideIcon> = {/*** 安装/更新页:基于通用 Loadable 组件渲染,* 视觉与官方 web shell 的 boot 加载页(AppRoot)一致。+ * 状态与重试动作直接从 harness store 读取,不再接收 props。*/-export default function SetupScreen({- status,- title,- detail,- percentage,- logs,- errorMsg,- onRetry,-}: SetupScreenProps) {+export default function Setup() {const { t } = useI18n()+ const { status, installer, errorMsg } = useStore(harness)const error = status === 'error'const installing = status === 'installing'- const heading = error ? t('status.error') : title || t('status.installing')- const description = error ? '' : detail || t('status.installing')+ const heading = error ? t('status.error') : installer.title || t('status.installing')+ const description = error ? '' : installer.detail || t('status.installing')const StatusIcon = STATUS_ICONS[status]return (@@ -58,10 +34,10 @@ export default function SetupScreen({icon={StatusIcon}title={heading}subtitle={error ? undefined : description}- percentage={installing ? percentage : undefined}- logs={installing ? logs : undefined}+ percentage={installing ? installer.percentage : undefined}+ logs={installing ? installer.logs : undefined}errorMsg={error ? errorMsg : undefined}- onRetry={error ? onRetry : undefined}+ onRetry={error ? harness.boot : undefined}/>)}diff --git a/src/components/sidebar-toggle.tsx b/src/components/sidebar-toggle.tsxindex 3a5506a5..a184f24e 100644--- a/src/components/sidebar-toggle.tsx+++ b/src/components/sidebar-toggle.tsx@@ -1,23 +1,28 @@import { Wrench } from 'lucide-react'-import { useI18n } from '../i18n/i18n-context'+import { useStore } from 'valtio-define'+import { setting, useI18n } from '../store/modules/setting'+import { updater } from '../store/modules/updater'+import { toggle } from './primitives'-interface SidebarToggleProps {- /** 上方有提示条时上移,避免重叠 */- lifted: boolean- onClick: () => void-}--/** 右下角侧边栏展开按钮 */-export default function SidebarToggle({ lifted, onClick }: SidebarToggleProps) {+/**+ * 右下角侧边栏展开按钮:显隐与位置都从 store 读取,+ * 不再接收 lifted/onClick 等 props。+ */+export default function SidebarToggle() {const { t } = useI18n()+ const { sidebarOpen } = useStore(setting)+ const { updateInfo, updating } = useStore(updater)++ // 侧边栏已展开时隐藏,避免与抽屉重叠+ if (sidebarOpen) {+ return null+ }return (<button- onClick={onClick}+ onClick={setting.toggleSidebar}title={t('app.expand_sidebar')}- className={`fixed right-4 z-20 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-line bg-panel/80 text-ink shadow-lg backdrop-blur-md transition-colors hover:bg-panel-hover ${- lifted ? 'bottom-[84px]' : 'bottom-4'- }`}+ className={toggle({ lifted: updateInfo !== null && !updating })}><Wrench className="size-4" /></button>diff --git a/src/components/update-toast.tsx b/src/components/update-toast.tsxdeleted file mode 100644index 3474c17e..00000000--- a/src/components/update-toast.tsx+++ /dev/null@@ -1,39 +0,0 @@-import type { DshUpdateInfo } from '../hooks/use-harness'-import { useI18n } from '../i18n/i18n-context'--// 官方按钮:胶囊形 + 中性品牌色(对应 ui-primitives Button)-const btnPrimary- = 'inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] bg-btn-fill px-3.5 text-sm leading-[22px] text-btn-ink transition-colors hover:bg-btn-fill-hover disabled:cursor-not-allowed disabled:opacity-40'-const btnGhost- = 'inline-flex h-9 cursor-pointer items-center justify-center gap-1 rounded-[18px] px-3.5 text-sm leading-[22px] text-ink transition-colors hover:bg-btn-hover active:bg-btn-active'--interface UpdateToastProps {- info: DshUpdateInfo | null- updating: boolean- onUpdate: () => void- onDismiss: () => void-}--/** 右下角"发现新版本"提示条 */-export default function UpdateToast({ info, updating, onUpdate, onDismiss }: UpdateToastProps) {- const { t } = useI18n()-- if (!info || updating) {- return null- }-- return (- <div className="fixed right-4 bottom-4 z-50 flex max-w-[420px] items-center gap-3 rounded-lg border border-line bg-panel px-4 py-3 shadow-lg">- <div className="min-w-0 flex-1">- <p className="text-[13px] font-semibold text-ink">{t('update.available', { tag: info.tag })}</p>- <p className="mt-0.5 text-xs text-muted">{info.commit.slice(0, 7)}</p>- </div>- <button className={btnPrimary} onClick={onUpdate}>- {t('update.now')}- </button>- <button className={btnGhost} onClick={onDismiss}>- {t('update.later')}- </button>- </div>- )-}diff --git a/src/hooks/use-auto-sync.ts b/src/hooks/use-auto-sync.tsdeleted file mode 100644index ac2fb5ff..00000000--- a/src/hooks/use-auto-sync.ts+++ /dev/null@@ -1,35 +0,0 @@-import type { UnlistenFn } from '@tauri-apps/api/event'-import { listen } from '@tauri-apps/api/event'-import { useEffect } from 'react'--/**- * Listen for the `app://sync-state` event and run a callback when it fires.- * Kept for parity with the reference desktop implementation; the backend may- * emit it after lifecycle transitions.- */-export function useAutoSync(onSync: () => void) {- useEffect(() => {- let unlisten: UnlistenFn | null = null-- async function setupListener() {- try {- unlisten = await listen<string>('app://sync-state', () => onSync())- }- catch (error) {- console.error('[useAutoSync] failed to register listener:', error)- }- }-- void setupListener()- return () => {- unlisten?.()- }- }, [onSync])-}--/** Build a cache-busting URL for the harness iframe. */-export function generateTimestampedUrl(baseUrl: string): string {- const timestamp = Date.now()- const separator = baseUrl.includes('?') ? '&' : '?'- return `${baseUrl}${separator}t=${timestamp}`-}diff --git a/src/hooks/use-harness.ts b/src/hooks/use-harness.tsdeleted file mode 100644index b58fbbb3..00000000--- a/src/hooks/use-harness.ts+++ /dev/null@@ -1,396 +0,0 @@-import type { UnlistenFn } from '@tauri-apps/api/event'-import type { InstallProgress, SetupStatus } from '../components/setup-screen'-import type { SidebarBusyAction } from '../components/sidebar-panel'-import { invoke } from '@tauri-apps/api/core'-import { listen } from '@tauri-apps/api/event'-import { useEffect, useMemo, useRef, useState } from 'react'-import { useI18n } from '../i18n/i18n-context'-import { generateTimestampedUrl } from './use-auto-sync'--const MAX_RETRIES = 8--export interface InstallerState {- title: string- detail: string- percentage: number- logs: string[]-}--export interface DshUpdateInfo {- tag: string- commit: string-}--/** Rust 侧 on_download 接管下载后 emit 的完成事件载荷 */-export interface DownloadFinishedPayload {- url: string- path: string | null- success: boolean-}--const initialInstaller: InstallerState = {- title: '',- detail: '',- percentage: 0,- logs: [],-}--/**- * 桌面外壳核心业务 hook:安装/更新流程、服务生命周期(启动/健康检查/重启/停止)、- * iframe 加载状态与挂起兜底、版本更新检查、下载完成提示。- *- * 内部方法一律使用 function 声明(不用箭头),内嵌回调(事件监听、setTimeout 等)- * 除外;boot 的启动 effect 靠 bootStartedRef 保证只执行一次。- */-export function useHarness() {- const { t } = useI18n()- const [status, setStatus] = useState<SetupStatus>('ready')- const [installer, setInstaller] = useState<InstallerState>(initialInstaller)- const [errorMsg, setErrorMsg] = useState('')- const [serviceUrl, setServiceUrl] = useState('http://127.0.0.1:3080')- const [iframeLoaded, setIframeLoaded] = useState(false)- const [iframeError, setIframeError] = useState(false)- const [iframeKey, setIframeKey] = useState(0)- const [serviceHealthy, setServiceHealthy] = useState(false)- const [updateInfo, setUpdateInfo] = useState<DshUpdateInfo | null>(null)- const [updating, setUpdating] = useState(false)- const [serviceRunning, setServiceRunning] = useState(false)- const [busyAction, setBusyAction] = useState<SidebarBusyAction>(null)- const [downloadNotice, setDownloadNotice] = useState<DownloadFinishedPayload | null>(null)-- const bootTokenRef = useRef(0)- const bootStartedRef = useRef(false)-- const iframeSrc = useMemo(() => generateTimestampedUrl(serviceUrl), [serviceUrl])-- // 刷新 iframe:清除加载态并延迟重新挂载- function refreshIframe() {- setIframeLoaded(false)- setIframeError(false)- setTimeout(() => setIframeKey(prev => prev + 1), 800)- }-- // iframe 加载成功/失败时由视图回调更新状态- function markIframeLoaded() {- setIframeLoaded(true)- setIframeError(false)- }-- function markIframeError() {- setIframeError(true)- setIframeLoaded(false)- }-- async function checkHealthViaProxy(): Promise<boolean> {- try {- const timeoutPromise = new Promise<never>((_, reject) => {- setTimeout(() => reject(new Error('health check timeout')), 8000)- })- const resultPromise = invoke<string>('proxy_health_check')- const result = await Promise.race([resultPromise, timeoutPromise])-- const lower = result.toLowerCase()- if (- lower.includes('healthy')- || lower.includes('ready')- || result.includes('200')- || result.includes('201')- || lower.includes('ok')- ) {- console.warn('[App] health check passed:', result)- return true- }- console.warn('[App] health check returned:', result)- return false- }- catch (err) {- const message = String(err)- if (message.includes('502') || message.includes('Bad Gateway')) {- console.warn('[App] transient 502 during health check, retrying')- }- else {- console.error('[App] health check failed:', err)- }- return false- }- }-- // 安装进度流:只前进不后退,供首次安装/手动更新共用- async function listenInstallProgress(): Promise<UnlistenFn> {- return listen<InstallProgress>('install-progress', (e) => {- const payload = e.payload- setInstaller((prev) => {- if (payload.percentage < prev.percentage) {- return prev- }- const logs = payload.log- ? [...prev.logs, payload.log].slice(-5)- : prev.logs- return {- title: payload.title || prev.title,- detail: payload.detail || prev.detail,- percentage: payload.percentage,- logs,- }- })- })- }-- // 后台静默检查是否有新版 Harness(网络失败/API 限流时静默跳过)- async function checkForUpdate() {- try {- const info = await invoke<DshUpdateInfo | null>('check_dsh_update')- if (info) {- setUpdateInfo(info)- }- }- catch (err) {- console.warn('[App] update check skipped:', err)- }- }-- // 拉起服务并等待健康检查通过,通过后才挂载 iframe- async function launchAndWait() {- setStatus('ready')- setInstaller(initialInstaller)- setServiceHealthy(false)- setIframeLoaded(false)- setIframeError(false)- await invoke('launch_harness')- setServiceRunning(true)-- let healthy = false- for (let attempt = 0; attempt < MAX_RETRIES && !healthy; attempt++) {- healthy = await checkHealthViaProxy()- if (!healthy) {- await new Promise(resolve => setTimeout(resolve, 2000))- }- }- if (!healthy) {- throw new Error(- t('errors.service_start_timeout', { port: new URL(serviceUrl).port || '3080' }),- )- }- setServiceHealthy(true)- }-- async function boot() {- const token = ++bootTokenRef.current- // 回到加载态:已安装时不再显示检测/启动界面,直接进入页面加载状态- setServiceHealthy(false)- setIframeLoaded(false)- setIframeError(false)- let unlistenInstall: UnlistenFn | null = null-- try {- // 事件监听失败(例如 IPC 自定义协议被 CSP 拦截、回退 postMessage 也异常)- // 不应阻断启动流程,因此容错跳过。- try {- unlistenInstall = await listenInstallProgress()- }- catch (err) {- console.error('[App] failed to listen install-progress:', err)- }- const runtimeInfo = await invoke<{ service_url: string }>('get_runtime_info')- setServiceUrl(runtimeInfo.service_url)-- // 已安装过则跳过安装界面,避免每次启动都闪现“正在安装依赖...”- const config = await invoke<{ installed: boolean }>('get_app_config')-- // 仅首次使用需要检测环境/安装依赖;之后直接进入页面- if (!config.installed) {- setStatus('installing')- setInstaller({ ...initialInstaller, title: t('status.installing') })- await invoke('install_dependencies')- }-- await launchAndWait()-- if (token !== bootTokenRef.current)- return- // 已安装时后台静默检查新版,发现后提示用户- if (config.installed) {- void checkForUpdate()- }- }- catch (err) {- if (token !== bootTokenRef.current)- return- console.error('[App] startup failed:', err)- setErrorMsg(String(err))- setStatus('error')- setServiceRunning(false)- }- finally {- unlistenInstall?.()- }- }-- // 手动更新:重新下载安装新版并重启服务- async function handleUpdate() {- if (updating)- return- setUpdating(true)- setUpdateInfo(null)- let unlistenInstall: UnlistenFn | null = null- try {- unlistenInstall = await listenInstallProgress()- setStatus('installing')- setInstaller({ ...initialInstaller, title: t('status.updating') })- await invoke('install_dependencies')- await launchAndWait()- setUpdateInfo(null)- }- catch (err) {- console.error('[App] update failed:', err)- setErrorMsg(String(err))- setStatus('error')- setServiceRunning(false)- }- finally {- unlistenInstall?.()- setUpdating(false)- }- }-- async function restart() {- if (busyAction)- return- setBusyAction('restart')- try {- await invoke('shutdown_harness')- }- catch (err) {- console.error('[App] shutdown during restart failed:', err)- }- setServiceRunning(false)- setIframeLoaded(false)- try {- await boot()- }- finally {- setBusyAction(null)- }- }-- async function shutdown() {- if (busyAction)- return- setBusyAction('shutdown')- try {- await invoke('shutdown_harness')- }- catch (err) {- console.error('[App] shutdown failed:', err)- }- finally {- setBusyAction(null)- }- setServiceRunning(false)- setStatus('error')- setErrorMsg(t('ui.stopped'))- }-- // 服务未运行时点击“重试”:重新拉起服务并等待健康检查- async function start() {- if (busyAction)- return- setBusyAction('start')- try {- await boot()- }- finally {- setBusyAction(null)- }- }-- async function openBrowser() {- if (busyAction)- return- setBusyAction('openBrowser')- try {- await invoke('open_in_browser')- }- catch (err) {- console.error('[App] open in browser failed:', err)- }- finally {- setBusyAction(null)- }- }-- function dismissUpdate() {- setUpdateInfo(null)- }-- function dismissDownload() {- setDownloadNotice(null)- }-- // React StrictMode 在 dev 下会执行两次 effect;boot 内部每次执行都会- // 递增 bootToken,此处再用 ref 兜底保证启动流程只挂载一次。- // 不传依赖数组:boot 每次渲染都是新函数,effect 重跑时靠 ref 直接跳过。- useEffect(() => {- if (bootStartedRef.current)- return- bootStartedRef.current = true- void boot()- })-- // 监听 Rust 侧接管下载的完成事件:dsh iframe 内的下载在 WebView2 中是- // 静默保存的(用户零感知),由外壳弹出“已保存 + 打开文件夹”提示- useEffect(() => {- let unlisten: UnlistenFn | null = null- listen<DownloadFinishedPayload>('harness-download-finished', (e) => {- setDownloadNotice(e.payload)- })- .then((fn) => {- unlisten = fn- })- .catch((err) => {- console.error('[App] failed to listen harness-download-finished:', err)- })- return () => {- unlisten?.()- }- }, [])-- // 进入 ready 后如果 iframe 长时间未加载(dsh 未就绪/挂起),- // 转为错误界面,避免一直停在黑色加载遮罩- useEffect(() => {- if (status !== 'ready' || !serviceHealthy || iframeLoaded)- return- const timer = setTimeout(() => {- setIframeLoaded(false)- setIframeError(true)- }, 20000)- return () => clearTimeout(timer)- }, [status, serviceHealthy, iframeLoaded, iframeKey])-- return {- status,- installer,- errorMsg,- serviceUrl,- iframeError,- iframeKey,- serviceHealthy,- updateInfo,- updating,- serviceRunning,- busyAction,- downloadNotice,- iframeSrc,- boot,- restart,- shutdown,- start,- openBrowser,- handleUpdate,- refreshIframe,- markIframeLoaded,- markIframeError,- dismissUpdate,- dismissDownload,- }-}diff --git a/src/i18n/i18n-context.tsx b/src/i18n/i18n-context.tsxdeleted file mode 100644index 281de347..00000000--- a/src/i18n/i18n-context.tsx+++ /dev/null@@ -1,90 +0,0 @@-import type { ReactNode } from 'react'-import type { Language, Translations } from './index'-import { invoke } from '@tauri-apps/api/core'-import React, { createContext, useContext, useEffect, useState } from 'react'-import { translations } from './index'--interface I18nContextType {- language: Language- setLanguage: (lang: Language) => void- t: (key: string, params?: Record<string, string | number>) => string-}--const I18nContext = createContext<I18nContextType | undefined>(undefined)--const STORAGE_KEY = 'deepseek-harness-desktop-language'--function getTranslation(obj: Translations, keyPath: string, params?: Record<string, string | number>): string {- const keys = keyPath.split('.')- let value: unknown = obj-- for (const key of keys) {- if (value && typeof value === 'object' && key in value) {- value = (value as Record<string, unknown>)[key]- }- else {- return keyPath- }- }-- if (typeof value !== 'string') {- return keyPath- }-- if (params) {- return value.replace(/\{\{(\w+)\}\}/g, (match, paramName: string) => {- return params[paramName]?.toString() ?? match- })- }- return value-}--export const I18nProvider: React.FC<{ children: ReactNode, defaultLanguage?: Language }> = ({- children,- defaultLanguage = 'en',-}) => {- function getInitialLanguage(): Language {- const saved = localStorage.getItem(STORAGE_KEY) as Language | null- if (saved === 'en' || saved === 'zh') {- return saved- }- const browserLang = navigator.language.toLowerCase()- return browserLang.startsWith('zh') ? 'zh' : defaultLanguage- }-- const [languageState, setLanguageState] = useState<Language>(getInitialLanguage)-- function setLanguage(lang: Language) {- setLanguageState(lang)- localStorage.setItem(STORAGE_KEY, lang)- invoke('set_language', { lang }).catch(() => {- // Backend language is best-effort only.- })- }-- function t(key: string, params?: Record<string, string | number>): string {- return getTranslation(translations[languageState], key, params)- }-- useEffect(() => {- document.documentElement.lang = languageState- document.documentElement.dir = 'ltr'- }, [languageState])-- return (- <I18nContext.Provider value={{ language: languageState, setLanguage, t }}>- {children}- </I18nContext.Provider>- )-}--// useI18n 为消费 Context 的 hook,与 Provider 同文件导出,-// 会触发 react-refresh 的"仅导出组件"检查,属合理例外,故行内豁免-// eslint-disable-next-line react-refresh/only-export-components-export function useI18n(): I18nContextType {- const context = useContext(I18nContext)- if (!context) {- throw new Error('useI18n must be used within an I18nProvider')- }- return context-}diff --git a/src/main.tsx b/src/main.tsxindex 86918233..9dcc952b 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -1,13 +1,10 @@import React from 'react'import ReactDOM from 'react-dom/client'import App from './app'-import { I18nProvider } from './i18n/i18n-context'import './style/main.css'ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<React.StrictMode>- <I18nProvider>- <App />- </I18nProvider>+ <App /></React.StrictMode>,)