Skip to content

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

refactor: desktop-host.ts and dsh-host.ts for improved clarity and functionality

hairyf6f54176ce099
diff --git a/test/e2e/support/desktop-host.ts b/test/e2e/support/desktop-host.ts
index d2f8a301..71da1b86 100644
--- a/test/e2e/support/desktop-host.ts
+++ b/test/e2e/support/desktop-host.ts
@@ -7,15 +7,14 @@
* provider 自己 spawn(它注入 `TAURI_WEBDRIVER_PORT` 并轮询应用内嵌的 WebDriver server),
* 本文件只负责前置校验、环境隔离与收尾。
*
- * 隔离:数据目录由 debug 构建的 `get_dsh_data_path()` 决定,它读 `USERPROFILE`/`HOME`
- * 与 `APPDATA`,并**忽略** `DSH_HOME`(`src-tauri/src/config/runtime.rs:471`)。因此这里
* 隔离:dsh 数据目录由 `get_dsh_data_path()` 决定,它读 `USERPROFILE`/`HOME` 并
- * **忽略** `DSH_HOME`(`src-tauri/src/config/runtime.rs:471`);`app_data_dir()` 同源
+ * 忽略 `DSH_HOME`(`src-tauri/src/config/runtime.rs:471`);`app_data_dir()` 同源
* 派生。因此只重定向 home 根即可隔离,绝不写用户真实的 `~/.dsh.dev` 与 Store。
*/
import { spawn } from 'node:child_process'
-import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
+import { existsSync, mkdirSync, rmSync } from 'node:fs'
+import { readdir, rm, stat } from 'node:fs/promises'
import { createConnection } from 'node:net'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
@@ -24,8 +23,12 @@ import { setTimeout as sleep } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
import { cleanupWdioSession, createTauriCapabilities, startWdioSession } from '@wdio/tauri-service'
+// ============================================================================
+// 常量定义
+// ============================================================================
+
/** 仓库根(本文件位于 `<root>/test/e2e/support/`)。 */
-export const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
+export const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
/** Debug 构建的固定端口(`src-tauri/src/config/constants.rs:53`)。 */
export const APP_PORT = 3081
@@ -42,30 +45,31 @@ export const MAIN_WEBVIEW = 'main'
/**
* 应用内嵌 WebDriver server 的固定端口(`@wdio/tauri-service` 的 embedded provider 默认 4445,
* 应用侧由 `TAURI_WEBDRIVER_PORT` 门控)。
- *
- * 这是**整机唯一**的资源:另一个桌面实例(别的 worktree 的 E2E、或 `cargo build` 出来的
- * devUrl 实例)先占住它时,本进程的应用绑不上,而 wdio 仍会连上对方的 driver——
- * 会话会静默挂到**别人的窗口**上(表现为找不到选择器、甚至跑到桌宠窗口)。
*/
export const WEBDRIVER_PORT = 4445
+/** 下载缓存根:跨运行复用,**不随 scratch home 删除**。 */
+export const DOWNLOAD_CACHE_DIR = join(tmpdir(), 'dsh-e2e-download-cache')
+
/** 残留实例的进程名(按 `productName` 推导)。 */
const APP_PROCESS_NAME = 'deepseek-harness-desktop'
/** E2E 模式下的 Store 文件名(`config::setting::store_dat_file_name` 的测试分支)。 */
const TEST_STORE_FILE = '.store.test.dat'
-/**
- * 下载缓存根:跨运行复用,**不随 scratch home 删除**。
- *
- * 环境(Node/pnpm/Git)与核心都装在这里。首次运行会联网下载,之后复用;
- * 想回到「首次装配」状态用 `resetDownloadCache()`。
- */
-export const DOWNLOAD_CACHE_DIR = join(tmpdir(), 'dsh-e2e-download-cache')
+/** scratch home 的目录前缀。 */
+const SCRATCH_PREFIX = 'dsh-e2e-desktop-'
+
+/** 只清理超过该年龄的残留:足够避开并发会话正在使用的 scratch (30 分钟)。 */
+const STALE_HOME_AGE_MS = 30 * 60 * 1000
/** WDIO 会话建立上限。 */
const SESSION_TIMEOUT_MS = 120_000
+// ============================================================================
+// 类型接口
+// ============================================================================
+
export interface StartDesktopAppOptions {
/** 覆盖二进制路径(用例 007 用它构造「路径不存在」)。 */
appBinaryPath?: string
@@ -95,175 +99,12 @@ export interface DesktopApp {
readonly stop: () => Promise<void>
}
-/** 默认二进制路径。 */
-export function defaultBinaryPath(): string {
- return join(REPO_ROOT, 'src-tauri', 'target', 'debug', `${APP_PROCESS_NAME}${process.platform === 'win32' ? '.exe' : ''}`)
-}
-
-function log(message: string): void {
- process.stderr.write(`[desktop-host] ${message}\n`)
-}
-
-/** 端口是否已被监听。 */
-export function isPortBusy(port: number): Promise<boolean> {
- return new Promise((resolvePromise) => {
- const socket = createConnection({ host: '127.0.0.1', port })
- const done = (busy: boolean): void => {
- socket.destroy()
- resolvePromise(busy)
- }
- socket.setTimeout(1_000)
- socket.once('connect', () => done(true))
- socket.once('timeout', () => done(false))
- socket.once('error', () => done(false))
- })
-}
-
-/**
- * 指定二进制是否仍有存活进程。
- *
- * 按**可执行文件路径**比对,而不是镜像名:用户可能同时装着正式版
- * (如 `G:\Deepseek Harness Desktop\deepseek-harness-desktop.exe`),
- * 按名匹配会把它误判成「测试残留」而拒绝开跑。
- */
-async function hasLiveProcess(binaryPath: string): Promise<boolean> {
- if (process.platform !== 'win32')
- return false
- return new Promise((resolvePromise) => {
- const script = `Get-CimInstance Win32_Process -Filter "Name='${APP_PROCESS_NAME}.exe'" | `
- + 'Select-Object -ExpandProperty ExecutablePath'
- const child = spawn('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
- stdio: ['ignore', 'pipe', 'ignore'],
- windowsHide: true,
- })
- let output = ''
- child.stdout?.on('data', (chunk: string | Uint8Array) => {
- output += chunk.toString()
- })
- child.once('error', () => resolvePromise(false))
- child.once('close', () => {
- const target = binaryPath.toLowerCase()
- resolvePromise(output.split(/\r?\n/).some(line => line.trim().toLowerCase() === target))
- })
- })
-}
-
-/**
- * 前置校验:不满足即 fail,**不自动强杀用户进程**(`desktop.test.md` §6)。
- *
- * 这是测试编排的行为,不是应用行为;用例 008 直接断言本函数的失败语义。
- */
-export async function assertPreconditions(options: { port?: number, binaryPath?: string } = {}): Promise<void> {
- const port = options.port ?? APP_PORT
- const binaryPath = options.binaryPath ?? defaultBinaryPath()
-
- if (!existsSync(binaryPath))
- throw new Error(`二进制不存在:${binaryPath};先在 src-tauri/ 下运行 \`tauri build --debug --no-bundle\`(必须带 custom-protocol,否则应用走 devUrl 而不嵌 dist)。`)
-
- if (await isPortBusy(port))
- throw new Error(`端口 ${port} 已被监听(debug 固定端口);请先停掉 dev/debug 实例。本校验不自动杀进程。`)
-
- if (await isPortBusy(WEBDRIVER_PORT))
- throw new Error(`WebDriver 端口 ${WEBDRIVER_PORT} 已被占用(多半是另一个桌面实例在跑);此时会话会静默挂到对方的窗口上,必须先释放。本校验不自动杀进程。`)
-
- if (await hasLiveProcess(binaryPath))
- throw new Error(`检测到残留桌面实例(${binaryPath});请先关闭后再跑 E2E。本校验不自动杀进程。`)
-}
-
-/**
- * 建隔离根并派生 home 根。
- *
- * `<home>/AppData/Local` 与 `AppData/Roaming` 必须**预先存在**:`tauri-plugin-http`
- * 的 setup 调 `app_cache_dir()`,解析失败即 `UnknownPath`,应用在 `lib.rs` 的
- * `expect` 处 panic(exit 101)。这条约束是实测得到的。
- */
-function makeHome(keep: boolean): string {
- const home = join(tmpdir(), `dsh-e2e-desktop-${Date.now().toString(36)}`)
- const profile = join(home, 'home')
- mkdirSync(join(profile, 'AppData', 'Local'), { recursive: true })
- mkdirSync(join(profile, 'AppData', 'Roaming'), { recursive: true })
- if (keep)
- log(`KEEP_HOME:${home}`)
- return home
-}
-
-/** 应用真实 app-data 目录(`SHGetKnownFolderPath` 解析,环境变量改不动它)。 */
-function appDataDir(): string {
- const roaming = process.env.APPDATA ?? join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming')
- return join(roaming, 'io.github.hairyf.deepseek-harness-desktop')
-}
-
-/**
- * 清空测试 Store:应用在 E2E 模式下(`TAURI_WEBDRIVER_PORT` 存在)读写
- * `.store.test.dat`,与用户真实的 `.store.dev.dat` / `.store.dat` 互不相干。
- *
- * 必须在启动前删除:否则会继承上一次运行留下的窗口几何、端口等状态
- * (`01` 批次 TC-004 因此失败过)。只删测试文件,绝不碰另外两份。
- */
-export function resetTestStore(): void {
- const file = join(appDataDir(), TEST_STORE_FILE)
- rmSync(file, { force: true })
-}
-
-/**
- * 清空下载缓存,回到「首次装配」状态——用于测应用启动的 setup / 装配流程。
- *
- * 只删 E2E 自己的缓存根,绝不碰用户真实 app-data 下的运行时。
- */
-export function resetDownloadCache(dir: string = DOWNLOAD_CACHE_DIR): void {
- rmSync(dir, { recursive: true, force: true })
-}
-
-/** scratch home 的目录前缀。 */
-const SCRATCH_PREFIX = 'dsh-e2e-desktop-'
-
-/** 只清理超过该年龄的残留:足够避开并发会话正在使用的 scratch。 */
-const STALE_HOME_AGE_MS = 30 * 60 * 1000
-
-let purgedStaleHomes = false
-
-/**
- * 清理历史运行残留的 scratch home(每个进程只做一次)。
- *
- * WebView2 子进程经常让上一轮的 `rmSync` 失败,于是残留会一直堆在系统临时目录里;
- * 与其在收尾时反复重试(实测要烧掉 5 秒且仍然删不掉),不如在下次启动前顺手清掉。
- * 按 mtime 过滤,避免误删并发会话(另一个 worktree 的 E2E)正在用的目录。
- */
-export function purgeStaleHomes(): void {
- if (purgedStaleHomes)
- return
- purgedStaleHomes = true
-
- const root = tmpdir()
- const deadline = Date.now() - STALE_HOME_AGE_MS
- let removed = 0
- try {
- for (const entry of readdirSync(root)) {
- if (!entry.startsWith(SCRATCH_PREFIX))
- continue
- const path = join(root, entry)
- try {
- if (statSync(path).mtimeMs > deadline)
- continue
- rmSync(path, { recursive: true, force: true })
- removed++
- }
- catch {
- // 仍被占用(并发会话或系统索引器),留给下一次
- }
- }
- }
- catch {
- // 临时目录不可读时不影响开跑
- }
- if (removed > 0)
- log(`清理历史 scratch:${removed} 个`)
-}
+// ============================================================================
+// 主入口
+// ============================================================================
/**
* 起一个真实桌面应用并建立 WDIO 会话。
- *
- * 调用方负责 `stop()`;用例的 `eachTest` 或 `afterAll` 必须执行它。
*/
export async function startDesktopApp(options: StartDesktopAppOptions = {}): Promise<DesktopApp> {
const {
@@ -275,18 +116,16 @@ export async function startDesktopApp(options: StartDesktopAppOptions = {}): Pro
const binaryPath = options.appBinaryPath ?? defaultBinaryPath()
- if (requireBinary)
+ if (requireBinary) {
await assertPreconditions({ binaryPath })
+ }
- purgeStaleHomes()
+ // 触发异步垃圾回收清理(不阻塞当前应用启动)
+ void purgeStaleHomes()
resetTestStore()
mkdirSync(downloadCacheDir, { recursive: true })
- const home = makeHome(keepHome)
- // 重定向 home 根:`get_dsh_data_path` 读 `USERPROFILE`/`HOME`
- // (`src-tauri/src/config/runtime.rs:455`),`app_data_dir()` 也由 home 派生
- // (`dirs::data_dir()/<identifier>`),因此这一个根同时隔离 dsh 数据与 Store。
- // 下载缓存另由 `DSH_DOWNLOAD_CACHE_DIR` 指向跨运行复用的稳定目录。
+ const home = makeHome(keepHome)
const profile = join(home, 'home')
const env: Record<string, string> = {
USERPROFILE: profile,
@@ -299,6 +138,7 @@ export async function startDesktopApp(options: StartDesktopAppOptions = {}): Pro
driverProvider: 'embedded',
startTimeout: SESSION_TIMEOUT_MS,
})
+
capabilities['wdio:tauriServiceOptions'] = {
...capabilities['wdio:tauriServiceOptions'],
env,
@@ -310,35 +150,33 @@ export async function startDesktopApp(options: StartDesktopAppOptions = {}): Pro
const startedAt = Date.now()
let browser: WebdriverIO.Browser | undefined
let stopped = false
+
const stop = async (): Promise<void> => {
- if (stopped)
- return
+ if (stopped) return
stopped = true
+
if (browser !== undefined) {
try {
await cleanupWdioSession(browser)
- }
- catch (error) {
+ } catch (error) {
log(`会话清理告警:${(error as Error).message}`)
}
}
- if (keepHome)
- return
-
- // 进程退出后 WebView2 子进程仍会短暂持有缓存文件句柄,直接删会 EBUSY/EPERM。
- // 用 WebDriver 端口(随应用进程消亡)做廉价存活探测,再带退避重试删除;
- // 删不掉不纠缠——scratch 落在系统临时目录,交给下一次运行的车道清理
- // (`purgeStaleHomes`),绝不为了清理把已通过的用例拖成红灯。
- for (let i = 0; i < 20 && await isPortBusy(WEBDRIVER_PORT); i++)
+
+ if (keepHome) return
+
+ // 探测 WebDriver 端口以等待 WebView2 子进程释放资源
+ for (let i = 0; i < 20 && (await isPortBusy(WEBDRIVER_PORT)); i++) {
await sleep(150)
+ }
+ // 带退避重试删除临时工作目录
for (let attempt = 1; attempt <= 3; attempt++) {
try {
rmSync(home, { recursive: true, force: true })
log(`收尾完成(${Date.now() - startedAt}ms)`)
return
- }
- catch (error) {
+ } catch (error) {
if (attempt === 3) {
log(`scratch 未删除(残留 ${home}):${(error as Error).message}`)
return
@@ -353,25 +191,182 @@ export async function startDesktopApp(options: StartDesktopAppOptions = {}): Pro
await focusMainWindow(browser)
log(`应用就绪(${Date.now() - startedAt}ms)`)
return { browser, home, binaryPath, stop }
- }
- catch (error) {
+ } catch (error) {
await stop()
throw error
}
}
+// ============================================================================
+// 工具函数
+// ============================================================================
+
+function log(message: string): void {
+ process.stderr.write(`[desktop-host] ${message}\n`)
+}
+
+/** 默认二进制路径。 */
+export function defaultBinaryPath(): string {
+ const exeSuffix = process.platform === 'win32' ? '.exe' : ''
+ return join(REPO_ROOT, 'src-tauri', 'target', 'debug', `${APP_PROCESS_NAME}${exeSuffix}`)
+}
+
+/** 端口是否已被监听。 */
+export function isPortBusy(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const socket = createConnection({ host: '127.0.0.1', port })
+ const cleanup = (busy: boolean): void => {
+ socket.destroy()
+ resolve(busy)
+ }
+ socket.setTimeout(1_000)
+ socket.once('connect', () => cleanup(true))
+ socket.once('timeout', () => cleanup(false))
+ socket.once('error', () => cleanup(false))
+ })
+}
+
+/** 应用真实 app-data 目录(`SHGetKnownFolderPath` 解析,环境变量改不动它)。 */
+function getAppDataDir(): string {
+ const roaming = process.env.APPDATA ?? join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming')
+ return join(roaming, 'io.github.hairyf.deepseek-harness-desktop')
+}
+
+/** 执行 PowerShell 命令的轻量辅助封装。 */
+function execPowerShell(script: string): Promise<string> {
+ return new Promise((resolve) => {
+ const child = spawn('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
+ stdio: ['ignore', 'pipe', 'ignore'],
+ windowsHide: true,
+ })
+ let output = ''
+ child.stdout?.on('data', (chunk: Buffer | string) => {
+ output += chunk.toString()
+ })
+ child.once('error', () => resolve(''))
+ child.once('close', () => resolve(output))
+ })
+}
+
/**
- * 把会话切到主窗口(webview label `main`)。
- *
- * 应用会同时创建主窗口与桌宠窗口(`pet`),会话落在哪个 webview 上取决于两者
- * 的创建先后,实测两种都出现过——落在 `pet` 时页面里没有壳层,所有选择器都找不到。
- * 因此创建会话后必须显式切一次,而不是依赖默认窗口。
+ * 指定二进制是否仍有存活进程。
+ * 按**可执行文件路径**比对,避免误判正式版实例。
*/
+async function hasLiveProcess(binaryPath: string): Promise<boolean> {
+ if (process.platform !== 'win32') return false
+
+ const script = `Get-CimInstance Win32_Process -Filter "Name='${APP_PROCESS_NAME}.exe'" | Select-Object -ExpandProperty ExecutablePath`
+ const output = await execPowerShell(script)
+ const target = binaryPath.toLowerCase()
+
+ return output
+ .split(/\r?\n/)
+ .some((line) => line.trim().toLowerCase() === target)
+}
+
+// ============================================================================
+// 前置校验与状态清理
+// ============================================================================
+
+/**
+ * 前置校验:不满足即 fail,**不自动强杀用户进程**。
+ */
+export async function assertPreconditions(options: { port?: number; binaryPath?: string } = {}): Promise<void> {
+ const port = options.port ?? APP_PORT
+ const binaryPath = options.binaryPath ?? defaultBinaryPath()
+
+ if (!existsSync(binaryPath)) {
+ throw new Error(
+ `二进制不存在:${binaryPath};先在 src-tauri/ 下运行 \`tauri build --debug --no-bundle\`(必须带 custom-protocol,否则应用走 devUrl 而不嵌 dist)。`
+ )
+ }
+
+ if (await isPortBusy(port)) {
+ throw new Error(`端口 ${port} 已被监听(debug 固定端口);请先停掉 dev/debug 实例。本校验不自动杀进程。`)
+ }
+
+ if (await isPortBusy(WEBDRIVER_PORT)) {
+ throw new Error(
+ `WebDriver 端口 ${WEBDRIVER_PORT} 已被占用(多半是另一个桌面实例在跑);此时会话会静默挂到对方的窗口上,必须先释放。本校验不自动杀进程。`
+ )
+ }
+
+ if (await hasLiveProcess(binaryPath)) {
+ throw new Error(`检测到残留桌面实例(${binaryPath});请先关闭后再跑 E2E。本校验不自动杀进程。`)
+ }
+}
+
+/** 清空测试 Store。 */
+export function resetTestStore(): void {
+ const file = join(getAppDataDir(), TEST_STORE_FILE)
+ rmSync(file, { force: true })
+}
+
+/** 清空下载缓存,回到「首次装配」状态。 */
+export function resetDownloadCache(dir: string = DOWNLOAD_CACHE_DIR): void {
+ rmSync(dir, { recursive: true, force: true })
+}
+
+let isStaleHomesPurged = false
+
+/**
+ * 异步清理历史运行残留的 scratch home(每个进程只执行一次,非阻塞)。
+ */
+export async function purgeStaleHomes(): Promise<void> {
+ if (isStaleHomesPurged) return
+ isStaleHomesPurged = true
+
+ const root = tmpdir()
+ const deadline = Date.now() - STALE_HOME_AGE_MS
+ let removedCount = 0
+
+ try {
+ const entries = await readdir(root)
+ for (const entry of entries) {
+ if (!entry.startsWith(SCRATCH_PREFIX)) continue
+ const targetPath = join(root, entry)
+
+ try {
+ const stats = await stat(targetPath)
+ if (stats.mtimeMs <= deadline) {
+ await rm(targetPath, { recursive: true, force: true })
+ removedCount++
+ }
+ } catch {
+ // 忽略单个目录清理失败(仍被占用或无权限)
+ }
+ }
+ } catch {
+ // 忽略读取临时根目录失败
+ }
+
+ if (removedCount > 0) {
+ log(`清理历史 scratch:${removedCount} 个`)
+ }
+}
+
+/** 建隔离根并派生 home 根。 */
+function makeHome(keep: boolean): string {
+ const home = join(tmpdir(), `${SCRATCH_PREFIX}${Date.now().toString(36)}`)
+ const profile = join(home, 'home')
+
+ mkdirSync(join(profile, 'AppData', 'Local'), { recursive: true })
+ mkdirSync(join(profile, 'AppData', 'Roaming'), { recursive: true })
+
+ if (keep) log(`KEEP_HOME:${home}`)
+ return home
+}
+
+/** 把会话切到主窗口(webview label `main`)。 */
async function focusMainWindow(browser: WebdriverIO.Browser): Promise<void> {
- await browser.waitUntil(async () => {
- const handles = await browser.getWindowHandles()
- return handles.includes(MAIN_WEBVIEW)
- }, { timeout: 30_000, timeoutMsg: `未找到主窗口 webview:${MAIN_WEBVIEW}` })
+ await browser.waitUntil(
+ async () => {
+ const handles = await browser.getWindowHandles()
+ return handles.includes(MAIN_WEBVIEW)
+ },
+ { timeout: 30_000, timeoutMsg: `未找到主窗口 webview:${MAIN_WEBVIEW}` }
+ )
await browser.switchToWindow(MAIN_WEBVIEW)
}
+
diff --git a/test/e2e/support/dsh-host.ts b/test/e2e/support/dsh-host.ts
index 4112ec49..86e60720 100644
--- a/test/e2e/support/dsh-host.ts
+++ b/test/e2e/support/dsh-host.ts
@@ -14,7 +14,7 @@
import type { ChildProcess } from 'node:child_process'
import { spawn } from 'node:child_process'
-import { existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { createWriteStream, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
@@ -24,7 +24,7 @@ import { fileURLToPath } from 'node:url'
const require = createRequire(import.meta.url)
/** 仓库根(本文件位于 `<root>/test/e2e/support/`)。 */
-export const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
+export const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
/** scratch profile 名:与桌面端一致(`dsh web` 默认档案)。 */
const PROFILE = 'web'
@@ -67,11 +67,6 @@ export interface DshHost {
readonly baseUrl: string
/**
* 用就绪 URL 的一次性 token 换来的浏览器会话 Cookie(`name=value`)。
- *
- * `/api/**` 要求浏览器会话:`authorizeIndex` **只在 `GET /` 接受** `?token=`,
- * 随即写入签名 Cookie 并 303 到干净的 `/`;HTTP 载体在根路径交换之外既不认
- * query token 也不认 Authorization 头。所以纯 HTTP 断言必须先做这次交换,
- * 再把 Cookie 原样带上。
*/
readonly cookie: string
/** 本次调用独占的 DSH_HOME。 */
@@ -84,51 +79,67 @@ export interface DshHost {
stop: () => Promise<void>
}
-/**
- * 用就绪 URL 的一次性 token 换浏览器会话 Cookie。
- *
- * 机制(见 `@deepseek-ai/dsh-client-connection` 的 README):
- * `GET /?token=…` → 303 + `Set-Cookie` + `Location: /`。
- * 因此这里必须 `redirect: 'manual'`——跟随重定向会丢掉 Set-Cookie。
- *
- * 没有 token 的旧宿主返回空串:那类宿主本就不设信任围栏,无需 Cookie。
- */
-async function exchangeLaunchToken(url: string): Promise<string> {
- const launch = new URL(url)
- if (launch.searchParams.get('token') === null)
- return ''
+/* ==========================================
+ * 通用/基础工具函数 (Utils)
+ * ========================================== */
- const response = await fetch(launch.href, { redirect: 'manual' })
- const headers = response.headers as Headers & { getSetCookie?: () => string[] }
- const setCookies = headers.getSetCookie?.() ?? []
- const first = setCookies[0] ?? response.headers.get('set-cookie')
+function log(message: string): void {
+ process.stderr.write(`[dsh-host] ${message}\n`)
+}
- if (response.status !== 303 || first === null) {
- throw new Error(
- `token 交换未返回 303 + Set-Cookie(实际 ${response.status});`
- + '该宿主可能不支持根路径 token 交换(该通道只在 `GET /?token=` 上生效)',
- )
+function resolveNodeBin(): string {
+ return process.env.DSH_E2E_NODE_BIN ?? process.execPath
+}
+
+/** 通用 JSON 读取,带容错兜底 */
+function readJson<T>(filePath: string): T | null {
+ try {
+ return JSON.parse(readFileSync(filePath, 'utf8')) as T
+ }
+ catch {
+ return null
}
- // 只取 `name=value`,属性交给 fetch 的 cookie 语义处理。
- return first.split(';', 1)[0].trim()
}
-function log(message: string): void {
- process.stderr.write(`[dsh-host] ${message}\n`)
+/** 修改并回写 JSON 文件 */
+function updateJson<T>(filePath: string, updater: (data: T) => T): void {
+ const data = readJson<T>(filePath) ?? ({} as T)
+ const nextData = updater(data)
+ writeFileSync(filePath, `${JSON.stringify(nextData, null, 2)}\n`)
}
+/** 读日志全文;文件不存在或读取异常时返回空字符串 */
+function readLog(path: string): string {
+ try {
+ return readFileSync(path, 'utf8')
+ }
+ catch {
+ return ''
+ }
+}
+
+function tailOf(path: string, lines = 30): string {
+ const text = readLog(path)
+ if (!text)
+ return '(日志为空)'
+ return text.split('\n').slice(-lines).join('\n')
+}
+
+/* ==========================================
+ * 业务逻辑与依赖解析
+ * ========================================== */
+
/** 解析 dsh 入口:显式环境变量 → PATH 上的 `dsh` → 桌面端已装配的 bin.js。 */
function resolveDshCommand(): string[] {
const explicit = process.env.DSH_E2E_DSH_BIN
- if (explicit !== undefined && explicit !== '')
+ if (explicit)
return [explicit]
try {
return [require.resolve('@deepseek-ai/dsh/lib/bin.js')]
}
catch {
- // 仓库不把 dsh CLI 作为依赖安装:它是运行期产物,装进依赖树会与本仓 catalog 的
- // `@deepseek-ai/dsh-*` 形成双树,profile 组合时取到不匹配的实例。
+ // 仓库不把 dsh CLI 作为依赖安装:它是运行期产物
}
if (existsSync(ASSEMBLED_DSH)) {
@@ -136,51 +147,39 @@ function resolveDshCommand(): string[] {
return [ASSEMBLED_DSH]
}
- // 缺核心一律硬失败,不提供「跳过」开关:一旦可跳过,CI 会在什么都没断言的
- // 情况下报绿。
throw new Error(
'DSH_E2E_DSH_BIN 未设置,PATH 与桌面端装配目录都没有 dsh 入口;'
+ '请设置 DSH_E2E_DSH_BIN 指向 @deepseek-ai/dsh 的 lib/bin.js',
)
}
-function resolveNodeBin(): string {
- return process.env.DSH_E2E_NODE_BIN ?? process.execPath
-}
-
/** 读包版本号;读不到返回 `0.0.0`(仅用于日志)。 */
function packageVersion(pkgDir: string): string {
- try {
- const manifest = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')) as { version?: string }
- return manifest.version ?? '0.0.0'
- }
- catch {
- return '0.0.0'
- }
+ interface Manifest { version?: string }
+ return readJson<Manifest>(join(pkgDir, 'package.json'))?.version ?? '0.0.0'
}
-/**
- * 校验插件已构建:`package.json` 的 `main` / `exports` 指向的产物必须存在。
- *
- * E2E 打的是构建产物而不是 TS 源码(官方「真实入口路径」规则),所以这里显式失败,
- * 而不是让 dsh 在 import 阶段抛一个难读的 ERR_MODULE_NOT_FOUND。
- */
+/** 校验插件已构建 */
function assertBuilt(pkgDir: string, pkg: string): void {
- const manifest = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')) as {
+ interface Manifest {
main?: string
exports?: Record<string, unknown>
}
+ const manifest = readJson<Manifest>(join(pkgDir, 'package.json')) ?? {}
const main = manifest.main ?? './dist/index.js'
const hostEntry = join(pkgDir, main.replace(/^\.\//, ''))
+
if (!existsSync(hostEntry)) {
throw new Error(
`${pkg} 尚未构建:缺少 ${hostEntry}。先跑一次 \`pnpm build:plugins\`(或 \`pnpm --filter ${pkg} build\`)。`,
)
}
+
const client = manifest.exports?.['./client']
const clientEntry = typeof client === 'string'
? client
: (client as { default?: string } | undefined)?.default
+
if (clientEntry !== undefined && !existsSync(join(pkgDir, clientEntry.replace(/^\.\//, '')))) {
throw new Error(`${pkg} 的 client 产物缺失:${clientEntry};先跑一次 \`pnpm build:plugins\`。`)
}
@@ -189,15 +188,16 @@ function assertBuilt(pkgDir: string, pkg: string): void {
/** 写 scratch profile 三件套(镜像 dsh 的 profile 模板)。 */
function writeProfile(profileDir: string, bundles: readonly string[]): void {
mkdirSync(profileDir, { recursive: true })
+
writeFileSync(join(profileDir, 'package.json'), `${JSON.stringify({
name: `dsh-profile-${PROFILE}`,
private: true,
dependencies: {},
dsh: { profile: { bundles: [...bundles] } },
}, null, 2)}\n`)
+
writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
- // pnpm 11 的 strict-dep-builds 与 minimumReleaseAge 会拦住 dsh 的传递依赖;
- // 与桌面端 / 社区同一份豁免策略(见 better-sidebar 的 scripts/e2e-common.sh)。
+
writeFileSync(join(profileDir, 'pnpm-workspace.yaml'), [
'packages:',
' - .',
@@ -225,44 +225,57 @@ function linkPackage(profileDir: string, pkg: string): void {
const target = join(profileDir, 'node_modules', pkg)
mkdirSync(dirname(target), { recursive: true })
rmSync(target, { recursive: true, force: true })
+
// junction 对目录链接不需要管理员权限,且在 Windows 上表现稳定。
symlinkSync(source, target, process.platform === 'win32' ? 'junction' : 'dir')
}
-/** 生成读 bundle 列表的辅助:挂载后必须能在 bundles 里看到,缺则立即失败。 */
+interface ProfileManifest {
+ dependencies?: Record<string, string>
+ dsh?: { profile?: { bundles?: string[] } }
+}
+
+/** 读取 bundle 列表 */
function readBundles(profileDir: string): string[] {
- const manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as {
- dsh?: { profile?: { bundles?: string[] } }
- }
- return manifest.dsh?.profile?.bundles ?? []
+ return readJson<ProfileManifest>(join(profileDir, 'package.json'))?.dsh?.profile?.bundles ?? []
}
function addBundle(profileDir: string, pkg: string): void {
const path = join(profileDir, 'package.json')
- const manifest = JSON.parse(readFileSync(path, 'utf8')) as {
- dependencies?: Record<string, string>
- dsh?: { profile?: { bundles?: string[] } }
- }
- manifest.dependencies = manifest.dependencies ?? {}
- manifest.dependencies[pkg] = `link:${join(REPO_ROOT, 'packages', pkg)}`
- const bundles = new Set(manifest.dsh?.profile?.bundles ?? [])
- bundles.add(pkg)
- manifest.dsh = { profile: { ...manifest.dsh?.profile, bundles: [...bundles] } }
- writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`)
+ updateJson<ProfileManifest>(path, (manifest) => {
+ const dependencies = manifest.dependencies ?? {}
+ dependencies[pkg] = `link:${join(REPO_ROOT, 'packages', pkg)}`
+
+ const bundles = new Set(manifest.dsh?.profile?.bundles ?? [])
+ bundles.add(pkg)
+
+ return {
+ ...manifest,
+ dependencies,
+ dsh: {
+ ...manifest.dsh,
+ profile: {
+ ...manifest.dsh?.profile,
+ bundles: [...bundles],
+ },
+ },
+ }
+ })
}
-/** 跑一条子命令,等待结束;非 0 退出即抛错(附输出尾部)。 */
+/* ==========================================
+ * 进程与 CLI 交互
+ * ========================================== */
+
function run(command: string, args: readonly string[], cwd: string, env: NodeJS.ProcessEnv): Promise<void> {
return new Promise((resolvePromise, reject) => {
- const child = spawn(command, [...args], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
+ const child = spawn(command, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
let output = ''
- child.stdout?.on('data', (chunk: Uint8Array) => {
- output += chunk.toString()
- })
- child.stderr?.on('data', (chunk: Uint8Array) => {
- output += chunk.toString()
- })
+
+ child.stdout?.on('data', chunk => output += chunk.toString())
+ child.stderr?.on('data', chunk => output += chunk.toString())
child.on('error', reject)
+
child.on('close', (code) => {
if (code === 0) {
resolvePromise()
@@ -274,38 +287,37 @@ function run(command: string, args: readonly string[], cwd: string, env: NodeJS.
})
}
-/** 走真实 CLI 挂载(需要网络与 pnpm)。 */
async function mountViaCli(profileDir: string, home: string, pkgs: readonly string[]): Promise<void> {
const [dshBin] = resolveDshCommand()
+ const storeDir = process.env.DSH_E2E_PNPM_STORE_DIR
const env: NodeJS.ProcessEnv = {
...process.env,
DSH_HOME: home,
- // 与桌面端 build_plugin_envs 同源:pnpm 10 只认 npm_config_*,pnpm 11 只认 pnpm_config_*。
- ...(process.env.DSH_E2E_PNPM_STORE_DIR
- ? {
- npm_config_store_dir: process.env.DSH_E2E_PNPM_STORE_DIR,
- pnpm_config_store_dir: process.env.DSH_E2E_PNPM_STORE_DIR,
- }
+ ...(storeDir
+ ? { npm_config_store_dir: storeDir, pnpm_config_store_dir: storeDir }
: {}),
}
+
for (const pkg of pkgs) {
- await run(resolveNodeBin(), [dshBin, 'plugin', '--profile', PROFILE, 'add', `link:${join(REPO_ROOT, 'packages', pkg)}`], profileDir, env)
+ const linkArg = `link:${join(REPO_ROOT, 'packages', pkg)}`
+ await run(resolveNodeBin(), [dshBin, 'plugin', '--profile', PROFILE, 'add', linkArg], profileDir, env)
}
}
-/** 杀进程树:Windows 用 taskkill /T /F,其余平台先 SIGTERM 再 SIGKILL。 */
async function killTree(child: ChildProcess): Promise<void> {
if (child.pid === undefined || child.exitCode !== null)
return
+
const pid = child.pid
if (process.platform === 'win32') {
await new Promise<void>((resolvePromise) => {
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
- killer.on('close', () => resolvePromise())
- killer.on('error', () => resolvePromise())
+ killer.on('close', resolvePromise)
+ killer.on('error', resolvePromise)
})
return
}
+
child.kill('SIGTERM')
await new Promise(resolvePromise => setTimeout(resolvePromise, 1_500))
if (child.exitCode === null)
@@ -314,40 +326,56 @@ async function killTree(child: ChildProcess): Promise<void> {
async function waitForReady(child: ChildProcess, logPath: string): Promise<string> {
const deadline = Date.now() + READY_TIMEOUT_MS
+
while (Date.now() < deadline) {
if (child.exitCode !== null)
throw new Error(`dsh web 提前退出(code ${child.exitCode});日志:${logPath}\n${tailOf(logPath)}`)
+
const match = READY_RE.exec(readLog(logPath))
if (match !== null)
return match[0]
+
await new Promise(resolvePromise => setTimeout(resolvePromise, 500))
}
- throw new Error(`等待 dsh web 就绪超时(${READY_TIMEOUT_MS}ms);日志:${logPath}\n${tailOf(logPath)}`)
-}
-function tailOf(path: string, lines = 30): string {
- const text = readLog(path)
- return text === '' ? '(日志为空)' : text.split('\n').slice(-lines).join('\n')
+ throw new Error(`等待 dsh web 就绪超时(${READY_TIMEOUT_MS}ms);日志:${logPath}\n${tailOf(logPath)}`)
}
-/** 读日志全文;子进程还没吐出任何输出时按空处理(首次读发生在文件创建前)。 */
-function readLog(path: string): string {
- try {
- return readFileSync(path, 'utf8')
- }
- catch {
+/** 用就绪 URL 的一次性 token 换浏览器会话 Cookie */
+async function exchangeLaunchToken(url: string): Promise<string> {
+ const launch = new URL(url)
+ if (!launch.searchParams.has('token'))
return ''
+
+ const response = await fetch(launch.href, { redirect: 'manual' })
+
+ // 兼容 Node.js fetch API 的 getSetCookie 提案
+ const getSetCookie = (response.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie
+ const setCookies = getSetCookie?.call(response.headers) ?? []
+ const first = setCookies[0] ?? response.headers.get('set-cookie')
+
+ if (response.status !== 303 || !first) {
+ throw new Error(
+ `token 交换未返回 303 + Set-Cookie(实际 ${response.status});`
+ + '该宿主可能不支持根路径 token 交换(该通道只在 `GET /?token=` 上生效)',
+ )
}
+
+ return first.split(';', 1)[0].trim()
}
+/* ==========================================
+ * 主入口导出 (Main Export)
+ * ========================================== */
+
/**
* 起一个真实 dsh web 宿主并挂载指定插件。
- *
* 调用方负责 `stop()`(Playwright 用 globalSetup/globalTeardown 保证)。
*/
export async function startDshHost(options: StartDshHostOptions): Promise<DshHost> {
const { plugin, also = [], keepHome = false } = options
const packages = [...also, plugin]
+
for (const pkg of packages)
assertBuilt(join(REPO_ROOT, 'packages', pkg), pkg)
@@ -356,7 +384,6 @@ export async function startDshHost(options: StartDshHostOptions): Promise<DshHos
const logPath = join(home, 'dsh-web.log')
const bundles = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', ...packages]
- // 装配期的任何失败都要把 scratch 目录带走,否则 /tmp 里会堆半成品。
try {
writeProfile(profileDir, bundles)
@@ -383,36 +410,31 @@ export async function startDshHost(options: StartDshHostOptions): Promise<DshHos
}
const [dshBin] = resolveDshCommand()
- // `dsh web` 就是 `--profile web` 的别名,两者不能同时给(CLI 会直接报错退出);
- // 因此 scratch profile 的目录名固定为 `web`。
- //
- // 不带 `--skip-auth`:那需要桌面端给核心打的补丁,npm 上的 dsh 没有;本通道改走
- // 上游本就支持的「根路径 token 换 Cookie」(见 `exchangeLaunchToken`),
- // 于是对打过补丁的装配核心与未打补丁的原版核心都成立。
const args = [dshBin, 'web', '--host', '127.0.0.1', '--port', '0', '--no-open']
log(`启动 dsh web(DSH_HOME=${home})`)
- // 先落一个空日志:就绪轮询可能在子进程吐出任何输出之前就读它。
- writeFileSync(logPath, '')
+
+ // **优化点**:改用 WriteStream 追加写日志,避免大规模内存拼接以及全量文件 I/O 阻塞
+ const logStream = createWriteStream(logPath, { flags: 'a' })
+
const child = spawn(resolveNodeBin(), args, {
cwd: profileDir,
env: { ...process.env, DSH_HOME: home },
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
})
- const chunks: string[] = []
- const collect = (chunk: Uint8Array): void => {
- chunks.push(chunk.toString())
- writeFileSync(logPath, chunks.join(''))
- }
- child.stdout?.on('data', collect)
- child.stderr?.on('data', collect)
+
+ child.stdout?.pipe(logStream, { end: false })
+ child.stderr?.pipe(logStream, { end: false })
let stopped = false
const stop = async (): Promise<void> => {
if (stopped)
return
stopped = true
+
+ logStream.end()
await killTree(child)
+
if (!keepHome)
rmSync(home, { recursive: true, force: true })
else
@@ -423,11 +445,14 @@ export async function startDshHost(options: StartDshHostOptions): Promise<DshHos
const url = await waitForReady(child, logPath)
const baseUrl = new URL(url).origin
const cookie = await exchangeLaunchToken(url)
- log(`就绪:${baseUrl}(已挂载 ${packages.join(', ')};${plugin}@${packageVersion(join(REPO_ROOT, 'packages', plugin))};会话 Cookie ${cookie === '' ? '不适用' : '已获取'})`)
+ const version = packageVersion(join(REPO_ROOT, 'packages', plugin))
+
+ log(`就绪:${baseUrl}(已挂载 ${packages.join(', ')};${plugin}@${version};会话 Cookie ${cookie === '' ? '不适用' : '已获取'})`)
+
return { url, baseUrl, cookie, home, logPath, mounted: packages, stop }
}
catch (error) {
await stop()
throw error
}
-}
+}
\ No newline at end of file