Skip to content

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

refactor(ui): split app into kebab-case components and hooks

hairyf79d8ce843e3b
diff --git a/src/app.tsx b/src/app.tsx
new file mode 100644
index 00000000..2c06983d
--- /dev/null
+++ b/src/app.tsx
@@ -0,0 +1,133 @@
+import { useState } from 'react'
+import DownloadToast from './components/download-toast'
+import HarnessView from './components/harness-view'
+import SidebarPanel from './components/sidebar-panel'
+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'
+/**
+ * 应用根组件:组合 useHarness 业务 hook 与各视图组件,
+ * 自身只保留侧边栏展开状态这类纯 UI 状态。
+ */
+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,
+ }
+
+ 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>
+ )
+ }
+
+ if (status !== 'ready') {
+ return (
+ <div className="flex h-screen w-screen">
+ <HarnessView {...harnessViewProps} status={status} errorMsg="" />
+ </div>
+ )
+ }
+
+ 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}
+ />
+ </div>
+ )
+}
diff --git a/src/components/SetupScreen.tsx b/src/components/SetupScreen.tsx
deleted file mode 100644
index bed866f0..00000000
--- a/src/components/SetupScreen.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { useI18n } from '../i18n/context'
-
-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
-}
-
-const LOG_LIMIT = 5
-
-/**
- * Installer/download page, modeled on the early n8n-based
- * `hairyf/damn-reports` `Installer` + `StepStatus` components: an icon, a
- * headline, a description, a value-labelled progress bar, and a
- * terminal-style panel showing the most recent progress lines.
- */
-export default function SetupScreen({
- status,
- title,
- detail,
- percentage,
- logs,
- errorMsg,
- onRetry,
-}: SetupScreenProps) {
- const { t } = useI18n()
- 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 visibleLogs = logs.length ? logs : [t('ui.waiting_logs')]
-
- return (
- <div className="flex h-full items-center justify-center">
- <div className="w-[min(460px,88vw)] rounded-[14px] border border-line bg-panel px-[46px] py-[42px] text-center">
- <div className="text-accent2">
- <div className="inline-flex h-16 w-16 items-center justify-center rounded-full border border-[rgba(77,107,254,0.35)] bg-gradient-to-br from-[rgba(77,107,254,0.2)] to-[rgba(110,139,255,0.06)] text-accent2">
- <svg viewBox="0 0 24 24" width="34" height="34" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
- <polyline points="7 10 12 15 17 10" />
- <line x1="12" y1="15" x2="12" y2="3" />
- </svg>
- </div>
- </div>
-
- <h2 className="mt-[18px] mb-1.5 text-xl font-semibold text-ink truncate">{heading}</h2>
- <p className="mb-6 min-h-[18px] text-[13px] break-all text-muted">{errorMsg || description}</p>
-
- {installing && (
- <>
- <div className="mb-5 flex items-center gap-3">
- <div className="h-2 flex-1 overflow-hidden rounded-full bg-panel2" role="progressbar" aria-valuenow={Math.round(percentage)}>
- <div className="h-full bg-gradient-to-r from-accent to-accent2 transition-[width] duration-150" style={{ width: `${Math.min(percentage, 100)}%` }} />
- </div>
- <span className="min-w-[44px] text-right text-[13px] font-semibold tabular-nums text-accent2">
- {Math.round(percentage)}
- %
- </span>
- </div>
-
- <div className="mb-5 min-h-[112px] max-h-[184px] overflow-y-auto rounded-lg border border-line bg-log-bg px-3.5 py-2.5 text-left font-mono text-xs leading-[1.7]" aria-label={t('ui.install_log')}>
- {visibleLogs.slice(-LOG_LIMIT).map((line, index) => (
- // 日志行内容可能重复,需以 index 区分 key
- // eslint-disable-next-line react/no-array-index-key
- <p key={`${line}-${index}`} className="m-0 flex gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-log-ink">
- <span className="shrink-0 text-accent select-none">›</span>
- <span className="min-w-0 overflow-hidden text-ellipsis">{line}</span>
- </p>
- ))}
- </div>
- </>
- )}
-
- {!error && (
- <div className="inline-flex items-center gap-2.5">
- <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-line border-t-accent" />
- <span className="text-[11px] font-semibold tracking-[0.18em] text-muted">PROCESSING...</span>
- </div>
- )}
-
- {error && (
- <button
- className="inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55"
- onClick={onRetry}
- >
- {t('app.retry')}
- </button>
- )}
- </div>
- </div>
- )
-}
diff --git a/src/components/download-toast.tsx b/src/components/download-toast.tsx
new file mode 100644
index 00000000..098331f8
--- /dev/null
+++ b/src/components/download-toast.tsx
@@ -0,0 +1,55 @@
+import type { DownloadFinishedPayload } from '../hooks/use-harness'
+import { invoke } from '@tauri-apps/api/core'
+import { useI18n } from '../i18n/i18n-context'
+
+const btnPrimary
+ = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55'
+const btnGhost
+ = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-line bg-panel2 px-3 py-1.5 text-[13px] text-ink transition-colors hover:bg-panel-hover'
+
+interface DownloadToastProps {
+ notice: DownloadFinishedPayload | null
+ onClose: () => void
+}
+
+/** 右下角"下载已保存/失败"提示条 */
+export default function DownloadToast({ notice, onClose }: DownloadToastProps) {
+ const { t } = useI18n()
+
+ if (!notice) {
+ return null
+ }
+
+ const { success, path } = notice
+
+ function revealInFolder(targetPath: string) {
+ void invoke('reveal_in_folder', { path: targetPath }).catch((err) => {
+ console.error('[App] 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="min-w-0 flex-1">
+ <p className="text-[13px] font-semibold text-ink">
+ {success ? t('download.saved') : t('download.failed')}
+ </p>
+ {success && path && (
+ <p className="mt-0.5 text-xs text-muted break-all truncate">
+ {t('download.saved_to')}
+ :
+ {path}
+ </p>
+ )}
+ </div>
+ {success && path && (
+ <button className={btnPrimary} onClick={() => revealInFolder(path)}>
+ {t('download.show_in_folder')}
+ </button>
+ )}
+ <button className={btnGhost} onClick={onClose}>
+ {t('download.close')}
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/harness-view.tsx b/src/components/harness-view.tsx
new file mode 100644
index 00000000..32d6ebc7
--- /dev/null
+++ b/src/components/harness-view.tsx
@@ -0,0 +1,108 @@
+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'
+
+const btnPrimary
+ = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55'
+
+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
+ ? (
+ // 底色用 load-bg 与官方 boot 页一致,交接瞬间无闪白
+ <iframe
+ key={iframeKey}
+ className="block h-full w-full border-none bg-load-bg"
+ src={iframeSrc}
+ onLoad={onIframeLoad}
+ onError={onIframeError}
+ title={t('app.open_editor')}
+ />
+ )
+ : (
+ // 服务未就绪前的加载遮罩,与官方 boot 页同款视觉
+ <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/loadable.tsx b/src/components/loadable.tsx
new file mode 100644
index 00000000..9a0e4713
--- /dev/null
+++ b/src/components/loadable.tsx
@@ -0,0 +1,113 @@
+import type { LucideIcon } from 'lucide-react'
+import type { ReactNode } from 'react'
+import { useI18n } from '../i18n/i18n-context'
+
+const LOG_LIMIT = 5
+
+/**
+ * 通用加载/安装界面。
+ *
+ * 不传任何 props 时,渲染结果与官方 web shell 的 boot 加载页
+ * (packages/client/web 的 AppRoot + AppRoot.module.css)逐项一致:
+ * wordmark(16px/600/0.08em)+ 20px 2px 单色 spinner(0.8s 旋转,
+ * 顶弧取 brand-primary,明暗主题下即黑/白)+ 12px/18px hint,16px gap。
+ * 颜色通过 load-* 系列主题变量精确对应官方 dsw alias token。
+ * 传入 icon/title/subtitle/percentage/logs/errorMsg/onRetry 后按需扩展。
+ */
+export interface LoadableProps {
+ /** 状态图标(lucide 组件),不传则不显示(官方 boot 页无图标) */
+ icon?: LucideIcon
+ /** wordmark 位文案,默认官网的 "HARNESS" */
+ title?: string
+ /** hint 位文案,默认官网的 "Loading plugins…" */
+ subtitle?: string
+ /** 进度百分比(0-100),传入则显示进度条 */
+ percentage?: number
+ /** 安装日志行,传入则显示日志面板(空数组显示"等待日志"占位) */
+ logs?: string[]
+ /** 错误信息,传入则切换为失败态(隐藏 spinner) */
+ errorMsg?: string
+ /** 失败态时的重试按钮回调 */
+ onRetry?: () => void
+ /** 附加内容,渲染在提示文字之后 */
+ children?: ReactNode
+}
+
+export default function Loadable({
+ icon: Icon,
+ title,
+ subtitle,
+ percentage,
+ logs,
+ errorMsg,
+ onRetry,
+ children,
+}: LoadableProps) {
+ const { t } = useI18n()
+ const error = errorMsg != null
+ const wordmark = title ?? t('app.wordmark')
+ const hint = error ? errorMsg : subtitle ?? t('status.loading_plugins')
+ const hasLogs = logs != null
+ const showPanel = hasLogs || percentage != null
+
+ return (
+ <div className="flex h-full items-center justify-center bg-load-bg -mt-[1px]">
+ <div className="flex w-[min(460px,88vw)] flex-col items-center gap-4 text-center">
+ {Icon && <Icon className="size-7 text-load-ink" strokeWidth={1.75} />}
+
+ <span className="text-base leading-6 font-semibold tracking-[0.08em] text-load-ink truncate">{wordmark}</span>
+
+ {error
+ ? (
+ // 失败态:官方 failed 展示样式(代码字体错误信息)
+ <p className="min-h-[18px] max-w-full font-mono text-xs leading-[18px] break-all text-load-muted">{hint}</p>
+ )
+ : (
+ <>
+ <span className="h-5 w-5 animate-spin rounded-full border-2 border-load-ring border-t-load-ink [animation-duration:0.8s]" />
+ <p className="min-h-[18px] text-xs leading-[18px] break-all text-load-muted">{hint}</p>
+ </>
+ )}
+
+ {onRetry && (
+ <button
+ className="inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55"
+ onClick={onRetry}
+ >
+ {t('app.retry')}
+ </button>
+ )}
+
+ {showPanel && (
+ <div className="flex w-full flex-col gap-4">
+ {percentage != null && (
+ <div className="flex items-center gap-3">
+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-panel2" role="progressbar" aria-valuenow={Math.round(percentage)}>
+ <div className="h-full bg-gradient-to-r from-accent to-accent2 transition-[width] duration-150" style={{ width: `${Math.min(percentage, 100)}%` }} />
+ </div>
+ <span className="min-w-[44px] text-right text-[13px] font-semibold tabular-nums text-accent2">
+ {Math.round(percentage)}
+ %
+ </span>
+ </div>
+ )}
+ {hasLogs && (
+ <div className="min-h-[112px] max-h-[184px] overflow-y-auto rounded-lg border border-line bg-log-bg px-3.5 py-2.5 text-left font-mono text-xs leading-[1.7]" aria-label={t('ui.install_log')}>
+ {(logs!.length ? logs! : [t('ui.waiting_logs')]).slice(-LOG_LIMIT).map((line, index) => (
+ // 日志行内容可能重复,需以 index 区分 key
+ // eslint-disable-next-line react/no-array-index-key
+ <p key={`${line}-${index}`} className="m-0 flex gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-log-ink">
+ <span className="shrink-0 text-accent select-none">›</span>
+ <span className="min-w-0 overflow-hidden text-ellipsis">{line}</span>
+ </p>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {children}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/setup-screen.tsx b/src/components/setup-screen.tsx
new file mode 100644
index 00000000..642f9cfd
--- /dev/null
+++ b/src/components/setup-screen.tsx
@@ -0,0 +1,67 @@
+import type { LucideIcon } from 'lucide-react'
+import { CircleAlert, CircleCheck, Download, Rocket, ScanSearch } from 'lucide-react'
+import { useI18n } from '../i18n/i18n-context'
+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,
+ installing: Download,
+ starting: Rocket,
+ ready: CircleCheck,
+ error: CircleAlert,
+}
+
+/**
+ * 安装/更新页:基于通用 Loadable 组件渲染,
+ * 视觉与官方 web shell 的 boot 加载页(AppRoot)一致。
+ */
+export default function SetupScreen({
+ status,
+ title,
+ detail,
+ percentage,
+ logs,
+ errorMsg,
+ onRetry,
+}: SetupScreenProps) {
+ const { t } = useI18n()
+ 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 StatusIcon = STATUS_ICONS[status]
+
+ return (
+ <Loadable
+ icon={StatusIcon}
+ title={heading}
+ subtitle={error ? undefined : description}
+ percentage={installing ? percentage : undefined}
+ logs={installing ? logs : undefined}
+ errorMsg={error ? errorMsg : undefined}
+ onRetry={error ? onRetry : undefined}
+ />
+ )
+}
diff --git a/src/components/SidebarPanel.tsx b/src/components/sidebar-panel.tsx
similarity index 97%
rename from src/components/SidebarPanel.tsx
rename to src/components/sidebar-panel.tsx
index 358967e1..f14713a7 100644
--- a/src/components/SidebarPanel.tsx
+++ b/src/components/sidebar-panel.tsx
@@ -1,6 +1,6 @@
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useState } from 'react'
-import { useI18n } from '../i18n/context'
+import { useI18n } from '../i18n/i18n-context'
export interface RuntimeInfo {
app_version: string
@@ -74,7 +74,7 @@ export default function SidebarPanel({
const [saving, setSaving] = useState(false)
const [busy, setBusy] = useState<string | null>(null)
- const refreshInfo = async () => {
+ async function refreshInfo() {
if (busy)
return
setBusy('refreshInfo')
@@ -90,7 +90,7 @@ export default function SidebarPanel({
}
}
- const refreshConfig = async () => {
+ async function refreshConfig() {
try {
const nextConfig = await invoke<AppConfig>('get_app_config')
setPort(String(nextConfig.port))
@@ -102,7 +102,7 @@ export default function SidebarPanel({
}
}
- const refreshCliStatus = async () => {
+ async function refreshCliStatus() {
try {
setCliStatus(await invoke<CliLinkStatus>('get_cli_link_status'))
}
@@ -111,7 +111,7 @@ export default function SidebarPanel({
}
}
- const refreshLogs = async () => {
+ async function refreshLogs() {
if (busy)
return
setBusy('refreshLogs')
@@ -127,10 +127,10 @@ export default function SidebarPanel({
}
useEffect(() => {
- refreshInfo()
- refreshConfig()
- refreshCliStatus()
- refreshLogs()
+ void refreshInfo()
+ void refreshConfig()
+ void refreshCliStatus()
+ void refreshLogs()
// eslint-disable-next-line react/exhaustive-deps
}, [])
@@ -141,7 +141,7 @@ export default function SidebarPanel({
return () => clearTimeout(timer)
}, [notice])
- const saveConfig = async () => {
+ async function saveConfig() {
setSaving(true)
try {
const nextPort = Number(port)
@@ -170,7 +170,7 @@ export default function SidebarPanel({
}
}
- const copyUrl = async () => {
+ async function copyUrl() {
if (busy)
return
setBusy('copy')
@@ -186,7 +186,7 @@ export default function SidebarPanel({
}
}
- const clearLogs = async () => {
+ async function clearLogs() {
if (busy)
return
setBusy('clearLogs')
@@ -203,7 +203,7 @@ export default function SidebarPanel({
}
}
- const revealDataDir = async () => {
+ async function revealDataDir() {
if (busy)
return
setBusy('revealDataDir')
diff --git a/src/components/sidebar-toggle.tsx b/src/components/sidebar-toggle.tsx
new file mode 100644
index 00000000..3a5506a5
--- /dev/null
+++ b/src/components/sidebar-toggle.tsx
@@ -0,0 +1,25 @@
+import { Wrench } from 'lucide-react'
+import { useI18n } from '../i18n/i18n-context'
+
+interface SidebarToggleProps {
+ /** 上方有提示条时上移,避免重叠 */
+ lifted: boolean
+ onClick: () => void
+}
+
+/** 右下角侧边栏展开按钮 */
+export default function SidebarToggle({ lifted, onClick }: SidebarToggleProps) {
+ const { t } = useI18n()
+
+ return (
+ <button
+ onClick={onClick}
+ 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'
+ }`}
+ >
+ <Wrench className="size-4" />
+ </button>
+ )
+}
diff --git a/src/components/update-toast.tsx b/src/components/update-toast.tsx
new file mode 100644
index 00000000..d74af549
--- /dev/null
+++ b/src/components/update-toast.tsx
@@ -0,0 +1,38 @@
+import type { DshUpdateInfo } from '../hooks/use-harness'
+import { useI18n } from '../i18n/i18n-context'
+
+const btnPrimary
+ = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55'
+const btnGhost
+ = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-line bg-panel2 px-3 py-1.5 text-[13px] text-ink transition-colors hover:bg-panel-hover'
+
+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-accent/40 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/useAutoSync.ts b/src/hooks/use-auto-sync.ts
similarity index 94%
rename from src/hooks/useAutoSync.ts
rename to src/hooks/use-auto-sync.ts
index 9d12e5b9..ac2fb5ff 100644
--- a/src/hooks/useAutoSync.ts
+++ b/src/hooks/use-auto-sync.ts
@@ -11,7 +11,7 @@ export function useAutoSync(onSync: () => void) {
useEffect(() => {
let unlisten: UnlistenFn | null = null
- const setupListener = async () => {
+ async function setupListener() {
try {
unlisten = await listen<string>('app://sync-state', () => onSync())
}
@@ -20,7 +20,7 @@ export function useAutoSync(onSync: () => void) {
}
}
- setupListener()
+ void setupListener()
return () => {
unlisten?.()
}
diff --git a/src/hooks/useDshTheme.ts b/src/hooks/use-dsh-theme.ts
similarity index 95%
rename from src/hooks/useDshTheme.ts
rename to src/hooks/use-dsh-theme.ts
index ee475980..15d90054 100644
--- a/src/hooks/useDshTheme.ts
+++ b/src/hooks/use-dsh-theme.ts
@@ -30,7 +30,7 @@ export function useDshTheme(): ResolvedTheme {
let unlisten: UnlistenFn | null = null
let disposed = false
- const apply = (preference: DshThemePreference) => {
+ function apply(preference: DshThemePreference) {
preferenceRef.current = preference
if (!disposed) {
setTheme(resolveTheme(preference))
@@ -53,7 +53,7 @@ export function useDshTheme(): ResolvedTheme {
})
const mediaQuery = window.matchMedia(DARK_QUERY)
- const onSystemThemeChange = () => {
+ function onSystemThemeChange() {
if (preferenceRef.current === 'system') {
setTheme(resolveTheme('system'))
}
diff --git a/src/App.tsx b/src/hooks/use-harness.ts
similarity index 53%
rename from src/App.tsx
rename to src/hooks/use-harness.ts
index 574230bc..b58fbbb3 100644
--- a/src/App.tsx
+++ b/src/hooks/use-harness.ts
@@ -1,30 +1,33 @@
import type { UnlistenFn } from '@tauri-apps/api/event'
-import type { InstallProgress, SetupStatus } from './components/SetupScreen'
-import type { SidebarBusyAction } from './components/SidebarPanel'
+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 { Wrench } from 'lucide-react'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import SetupScreen from './components/SetupScreen'
-import SidebarPanel from './components/SidebarPanel'
-import { generateTimestampedUrl } from './hooks/useAutoSync'
-import { useDshTheme } from './hooks/useDshTheme'
-import { useI18n } from './i18n/context'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useI18n } from '../i18n/i18n-context'
+import { generateTimestampedUrl } from './use-auto-sync'
const MAX_RETRIES = 8
-interface InstallerState {
+export interface InstallerState {
title: string
detail: string
percentage: number
logs: string[]
}
-interface DshUpdateInfo {
+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: '',
@@ -32,12 +35,15 @@ const initialInstaller: InstallerState = {
logs: [],
}
-const btnPrimary
- = 'inline-flex cursor-pointer items-center justify-center rounded-md border border-accent bg-accent px-3 py-1.5 text-[13px] text-white transition-colors hover:bg-accent2 disabled:cursor-not-allowed disabled:opacity-55'
-
-export default function App() {
+/**
+ * 桌面外壳核心业务 hook:安装/更新流程、服务生命周期(启动/健康检查/重启/停止)、
+ * iframe 加载状态与挂起兜底、版本更新检查、下载完成提示。
+ *
+ * 内部方法一律使用 function 声明(不用箭头),内嵌回调(事件监听、setTimeout 等)
+ * 除外;boot 的启动 effect 靠 bootStartedRef 保证只执行一次。
+ */
+export function useHarness() {
const { t } = useI18n()
- useDshTheme()
const [status, setStatus] = useState<SetupStatus>('ready')
const [installer, setInstaller] = useState<InstallerState>(initialInstaller)
const [errorMsg, setErrorMsg] = useState('')
@@ -48,40 +54,34 @@ export default function App() {
const [serviceHealthy, setServiceHealthy] = useState(false)
const [updateInfo, setUpdateInfo] = useState<DshUpdateInfo | null>(null)
const [updating, setUpdating] = useState(false)
- const [sidebarOpen, setSidebarOpen] = useState(() => {
- const saved = localStorage.getItem('sidebarOpen')
- return saved === null ? false : saved === 'true'
- })
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])
- // 右下角触发点:展开/收起侧边栏
- const handleToggleSidebar = () => {
- setSidebarOpen((prev) => {
- const next = !prev
- localStorage.setItem('sidebarOpen', String(next))
- return next
- })
+ // 刷新 iframe:清除加载态并延迟重新挂载
+ function refreshIframe() {
+ setIframeLoaded(false)
+ setIframeError(false)
+ setTimeout(() => setIframeKey(prev => prev + 1), 800)
}
- // 点击侧边栏外内容(遮罩)时收起侧边栏
- const handleCloseSidebar = () => {
- setSidebarOpen(false)
- localStorage.setItem('sidebarOpen', 'false')
+ // iframe 加载成功/失败时由视图回调更新状态
+ function markIframeLoaded() {
+ setIframeLoaded(true)
+ setIframeError(false)
}
- const refreshIframe = useCallback(() => {
+ function markIframeError() {
+ setIframeError(true)
setIframeLoaded(false)
- setIframeError(false)
- setTimeout(() => setIframeKey(prev => prev + 1), 800)
- }, [])
+ }
- const checkHealthViaProxy = async (): Promise<boolean> => {
+ async function checkHealthViaProxy(): Promise<boolean> {
try {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error('health check timeout')), 8000)
@@ -116,7 +116,7 @@ export default function App() {
}
// 安装进度流:只前进不后退,供首次安装/手动更新共用
- const listenInstallProgress = useCallback(async (): Promise<UnlistenFn> => {
+ async function listenInstallProgress(): Promise<UnlistenFn> {
return listen<InstallProgress>('install-progress', (e) => {
const payload = e.payload
setInstaller((prev) => {
@@ -134,10 +134,10 @@ export default function App() {
}
})
})
- }, [])
+ }
// 后台静默检查是否有新版 Harness(网络失败/API 限流时静默跳过)
- const checkForUpdate = useCallback(async () => {
+ async function checkForUpdate() {
try {
const info = await invoke<DshUpdateInfo | null>('check_dsh_update')
if (info) {
@@ -147,10 +147,10 @@ export default function App() {
catch (err) {
console.warn('[App] update check skipped:', err)
}
- }, [])
+ }
// 拉起服务并等待健康检查通过,通过后才挂载 iframe
- const launchAndWait = useCallback(async () => {
+ async function launchAndWait() {
setStatus('ready')
setInstaller(initialInstaller)
setServiceHealthy(false)
@@ -172,9 +172,9 @@ export default function App() {
)
}
setServiceHealthy(true)
- }, [serviceUrl, t])
+ }
- const boot = useCallback(async () => {
+ async function boot() {
const token = ++bootTokenRef.current
// 回到加载态:已安装时不再显示检测/启动界面,直接进入页面加载状态
setServiceHealthy(false)
@@ -224,10 +224,10 @@ export default function App() {
finally {
unlistenInstall?.()
}
- }, [listenInstallProgress, launchAndWait, checkForUpdate, t])
+ }
// 手动更新:重新下载安装新版并重启服务
- const handleUpdate = async () => {
+ async function handleUpdate() {
if (updating)
return
setUpdating(true)
@@ -253,27 +253,7 @@ export default function App() {
}
}
- // React StrictMode 在 dev 下会执行两次 effect,这里确保 boot 只挂载一次
- useEffect(() => {
- if (bootStartedRef.current)
- return
- bootStartedRef.current = true
- void boot()
- }, [boot])
-
- // 进入 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])
-
- const restart = async () => {
+ async function restart() {
if (busyAction)
return
setBusyAction('restart')
@@ -293,7 +273,7 @@ export default function App() {
}
}
- const shutdown = async () => {
+ async function shutdown() {
if (busyAction)
return
setBusyAction('shutdown')
@@ -311,8 +291,8 @@ export default function App() {
setErrorMsg(t('ui.stopped'))
}
- // 服务未运行时点击"重试":重新拉起服务并等待健康检查
- const start = async () => {
+ // 服务未运行时点击“重试”:重新拉起服务并等待健康检查
+ async function start() {
if (busyAction)
return
setBusyAction('start')
@@ -324,7 +304,7 @@ export default function App() {
}
}
- const openBrowser = async () => {
+ async function openBrowser() {
if (busyAction)
return
setBusyAction('openBrowser')
@@ -339,134 +319,78 @@ export default function App() {
}
}
- if (status === 'error') {
- return (
- <div className="flex h-screen w-screen">
- <main className="relative flex-1 bg-canvas">
- <SetupScreen
- status="error"
- title=""
- detail=""
- percentage={installer.percentage}
- logs={installer.logs}
- errorMsg={serviceUrl ? `${errorMsg} (${serviceUrl})` : errorMsg}
- onRetry={boot}
- />
- </main>
- {!sidebarOpen && (
- <button
- onClick={handleToggleSidebar}
- title={t('app.expand_sidebar')}
- className="fixed right-4 bottom-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"
- >
- <Wrench className="size-4" />
- </button>
- )}
- <SidebarPanel
- open={sidebarOpen}
- serviceRunning={serviceRunning}
- busyAction={busyAction}
- onClose={handleCloseSidebar}
- onRestart={restart}
- onShutdown={shutdown}
- onStart={start}
- onOpenBrowser={openBrowser}
- />
- </div>
- )
+ function dismissUpdate() {
+ setUpdateInfo(null)
}
- if (status !== 'ready') {
- return (
- <div className="flex h-screen w-screen">
- <main className="relative w-full bg-canvas">
- <SetupScreen
- status={status}
- title={installer.title}
- detail={installer.detail}
- percentage={installer.percentage}
- logs={installer.logs}
- errorMsg=""
- onRetry={boot}
- />
- </main>
- </div>
- )
+ function dismissDownload() {
+ setDownloadNotice(null)
}
- return (
- <div className="flex h-screen w-screen">
- <main className="relative flex-1 bg-canvas">
- {!iframeLoaded && (
- <div className="absolute inset-0 z-[1] flex flex-col items-center justify-center gap-3 bg-canvas text-ink">
- <span className="h-[34px] w-[34px] animate-spin rounded-full border-[3px] border-line border-t-accent" />
- <p>{t('status.loading')}</p>
- </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={refreshIframe}>
- {t('app.retry')}
- </button>
- </div>
- )}
- {serviceHealthy && (
- <iframe
- key={iframeKey}
- className="block h-full w-full border-none bg-white"
- src={iframeSrc}
- onLoad={() => {
- setIframeLoaded(true)
- setIframeError(false)
- }}
- onError={() => {
- setIframeError(true)
- setIframeLoaded(false)
- }}
- title={t('app.open_editor')}
- />
- )}
- </main>
- {updateInfo && !updating && (
- <div className="fixed bottom-4 right-4 z-50 flex max-w-[420px] items-center gap-3 rounded-lg border border-accent/40 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: updateInfo.tag })}</p>
- <p className="mt-0.5 text-xs text-muted">{updateInfo.commit.slice(0, 7)}</p>
- </div>
- <button className={btnPrimary} onClick={handleUpdate}>
- {t('update.now')}
- </button>
- <button
- className="inline-flex cursor-pointer items-center justify-center rounded-md border border-line bg-panel2 px-3 py-1.5 text-[13px] text-ink transition-colors hover:bg-panel-hover"
- onClick={() => setUpdateInfo(null)}
- >
- {t('update.later')}
- </button>
- </div>
- )}
- {!sidebarOpen && (
- <button
- onClick={handleToggleSidebar}
- 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 ${
- updateInfo && !updating ? 'bottom-[84px]' : 'bottom-4'
- }`}
- >
- <Wrench className="size-4" />
- </button>
- )}
- <SidebarPanel
- open={sidebarOpen}
- serviceRunning={serviceRunning}
- busyAction={busyAction}
- onClose={handleCloseSidebar}
- onRestart={restart}
- onShutdown={shutdown}
- onStart={start}
- onOpenBrowser={openBrowser}
- />
- </div>
- )
+ // 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/context.tsx b/src/i18n/i18n-context.tsx
similarity index 91%
rename from src/i18n/context.tsx
rename to src/i18n/i18n-context.tsx
index d28d0bac..281de347 100644
--- a/src/i18n/context.tsx
+++ b/src/i18n/i18n-context.tsx
@@ -43,7 +43,7 @@ export const I18nProvider: React.FC<{ children: ReactNode, defaultLanguage?: Lan
children,
defaultLanguage = 'en',
}) => {
- const getInitialLanguage = (): Language => {
+ function getInitialLanguage(): Language {
const saved = localStorage.getItem(STORAGE_KEY) as Language | null
if (saved === 'en' || saved === 'zh') {
return saved
@@ -54,7 +54,7 @@ export const I18nProvider: React.FC<{ children: ReactNode, defaultLanguage?: Lan
const [languageState, setLanguageState] = useState<Language>(getInitialLanguage)
- const setLanguage = (lang: Language) => {
+ function setLanguage(lang: Language) {
setLanguageState(lang)
localStorage.setItem(STORAGE_KEY, lang)
invoke('set_language', { lang }).catch(() => {
@@ -62,8 +62,9 @@ export const I18nProvider: React.FC<{ children: ReactNode, defaultLanguage?: Lan
})
}
- const t = (key: string, params?: Record<string, string | number>): string =>
- getTranslation(translations[languageState], key, params)
+ function t(key: string, params?: Record<string, string | number>): string {
+ return getTranslation(translations[languageState], key, params)
+ }
useEffect(() => {
document.documentElement.lang = languageState
diff --git a/src/main.tsx b/src/main.tsx
index 4fe67019..86918233 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,7 +1,7 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
-import App from './App'
-import { I18nProvider } from './i18n/context'
+import App from './app'
+import { I18nProvider } from './i18n/i18n-context'
import './style/main.css'
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(