Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

fix(desktop): support non-ASCII Windows install paths

Connor772e2d5b8698
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index f0a89e4..647f69d 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -17,6 +17,7 @@ import * as path from 'path'
import { registerMigrationIpc } from './migrate'
import { registerUpdater, markQuitting } from './updater'
import { createStartupLog, redactStartupLog, waitForBackend } from './startup'
+import { resolveRuntimeResources } from './runtime-resources'
// 主进程打 CJS 产物,__dirname 天然可用(import.meta.url 在 CJS 下为 undefined)
declare const __dirname: string
@@ -25,6 +26,8 @@ const DESKTOP_ROOT = path.resolve(__dirname, '..')
// dev 模式下仓库各目录
const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..')
const BACKEND_BUNDLE = path.join(DESKTOP_ROOT, 'build', 'backend.mjs')
+let backendBundle = BACKEND_BUNDLE
+let runtimeResourcesDir = ''
/** workspace 模板版本:内置模板更新时递增,触发向用户目录补缺失文件 */
const TEMPLATE_VERSION = '4'
@@ -195,7 +198,7 @@ function stopBackend(): Promise<void> {
function startBackend(): void {
backendReady = false
backendStartupTail = ''
- const resources = resolveResourceDir()
+ const resources = runtimeResourcesDir || resolveResourceDir()
const env: NodeJS.ProcessEnv = {
...process.env,
PORT: String(backendPort),
@@ -212,14 +215,14 @@ function startBackend(): void {
env.FFPROBE_BIN = path.join(resources, 'bin', `ffprobe${exe}`)
}
- backend = utilityProcess.fork(BACKEND_BUNDLE, [], {
+ backend = utilityProcess.fork(backendBundle, [], {
env,
serviceName: 'huobao-backend',
stdio: 'pipe',
cwd: currentDataDir,
})
const child = backend
- startupLog.write(`backend forked from ${BACKEND_BUNDLE}`)
+ startupLog.write(`backend forked from ${backendBundle}`)
child.on('spawn', () => startupLog.write(`backend spawned pid=${child.pid}`))
child.stdout?.on('data', chunk => {
process.stdout.write(`[backend] ${chunk}`)
@@ -297,8 +300,18 @@ async function bootstrap() {
fs.mkdirSync(currentDataDir, { recursive: true })
const resources = resolveResourceDir()
+ runtimeResourcesDir = app.isPackaged
+ ? await resolveRuntimeResources(resources, {
+ platform: process.platform,
+ version: app.getVersion(),
+ userDataDir: userData,
+ programDataDir: process.env.ProgramData,
+ log: message => startupLog.write(message),
+ })
+ : resources
+ if (app.isPackaged) backendBundle = path.join(runtimeResourcesDir, 'app.asar', 'build', 'backend.mjs')
const templateDir = app.isPackaged
- ? path.join(resources, 'workspace-template')
+ ? path.join(runtimeResourcesDir, 'workspace-template')
: path.join(REPO_ROOT, 'backend', 'workspace')
currentWorkspaceDir = app.isPackaged
? path.join(userData, 'workspace')
@@ -307,10 +320,10 @@ async function bootstrap() {
if (app.isPackaged) syncWorkspaceTemplate(templateDir, currentWorkspaceDir)
currentFrontendDist = app.isPackaged
- ? path.join(resources, 'frontend')
+ ? path.join(runtimeResourcesDir, 'frontend')
: path.join(REPO_ROOT, 'frontend', '.output', 'public')
- if (!fs.existsSync(BACKEND_BUNDLE)) throw new Error('安装资源缺失:build/backend.mjs')
+ if (!fs.existsSync(backendBundle)) throw new Error('安装资源缺失:build/backend.mjs')
if (!fs.existsSync(path.join(currentFrontendDist, 'index.html'))) throw new Error('安装资源缺失:frontend/index.html')
if (quitting) return
startBackend()
diff --git a/desktop/src/runtime-resources.ts b/desktop/src/runtime-resources.ts
new file mode 100644
index 0000000..87d5d19
--- /dev/null
+++ b/desktop/src/runtime-resources.ts
@@ -0,0 +1,146 @@
+/**
+ * Windows 非 ASCII 安装路径兼容。
+ *
+ * 后端 bundle、ASAR 原生模块和 FFmpeg 必须统一使用转换后的 resources 路径,
+ * 否则只转换其中一个,createRequire / asarUnpack 仍可能回到原始中文目录。
+ * 优先使用 NTFS 短路径(零拷贝);系统未启用短文件名时,把只读运行资源
+ * 暂存到 ASCII 目录。业务数据库和用户媒体仍留在原 userData,不参与拷贝。
+ */
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { createHash } from 'node:crypto'
+
+const READY_FILE = 'runtime-ready.json'
+const RESOURCE_ITEMS = ['app.asar', 'app.asar.unpacked', 'frontend', 'workspace-template', 'bin']
+
+export function isAsciiPath(value: string): boolean {
+ return !/[^\x00-\x7f]/.test(value)
+}
+
+interface RuntimeOptions {
+ version: string
+ userDataDir: string
+ programDataDir?: string
+ log?: (message: string) => void
+}
+
+function sourceSignature(resourcesPath: string): string {
+ const stat = fs.statSync(path.join(resourcesPath, 'app.asar'))
+ return `${stat.size}:${Math.round(stat.mtimeMs)}`
+}
+
+function ready(directory: string, signature: string, version: string): boolean {
+ try {
+ const marker = JSON.parse(fs.readFileSync(path.join(directory, READY_FILE), 'utf8'))
+ return marker.signature === signature && marker.version === version
+ && RESOURCE_ITEMS.every(item => fs.existsSync(path.join(directory, item)))
+ } catch {
+ return false
+ }
+}
+
+function copyResources(resourcesPath: string, target: string): void {
+ for (const item of RESOURCE_ITEMS) {
+ const source = path.join(resourcesPath, item)
+ const destination = path.join(target, item)
+ if (!fs.existsSync(source)) throw new Error(`安装资源缺失:${item}`)
+ if (fs.statSync(source).isDirectory()) {
+ fs.cpSync(source, destination, { recursive: true })
+ } else {
+ fs.mkdirSync(path.dirname(destination), { recursive: true })
+ fs.copyFileSync(source, destination)
+ }
+ }
+}
+
+/** 短路径不可用时的零配置回退;导出以便独立验证资源暂存和缓存更新。 */
+export function stageRuntimeResources(resourcesPath: string, options: RuntimeOptions): string {
+ const signature = sourceSignature(resourcesPath)
+ const identity = createHash('sha256')
+ .update(`${resourcesPath}\0${options.userDataDir}`)
+ .digest('hex')
+ .slice(0, 16)
+ const candidates = [
+ path.join(options.userDataDir, 'runtime'),
+ ...(options.programDataDir ? [path.join(options.programDataDir, 'HuobaoDrama')] : []),
+ ].filter(isAsciiPath)
+ let lastError: unknown = null
+
+ for (const base of candidates) {
+ const directory = path.join(base, `resources-${identity}`)
+ const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`
+ try {
+ if (ready(directory, signature, options.version)) return directory
+ fs.mkdirSync(base, { recursive: true })
+ const probe = path.join(base, `.huobao-write-${process.pid}`)
+ fs.writeFileSync(probe, 'probe')
+ fs.rmSync(probe, { force: true })
+
+ fs.rmSync(temporary, { recursive: true, force: true })
+ fs.mkdirSync(temporary, { recursive: true })
+ copyResources(resourcesPath, temporary)
+ fs.writeFileSync(path.join(temporary, READY_FILE), JSON.stringify({
+ version: options.version,
+ signature,
+ }))
+
+ // 同用户单实例锁正常会串行化这里;另一会话恰好先完成时直接复用。
+ if (ready(directory, signature, options.version)) return directory
+ fs.rmSync(directory, { recursive: true, force: true })
+ fs.renameSync(temporary, directory)
+ return directory
+ } catch (error) {
+ lastError = error
+ options.log?.(`ASCII runtime staging failed at ${base}: ${(error as Error).message}`)
+ } finally {
+ fs.rmSync(temporary, { recursive: true, force: true })
+ }
+ }
+
+ throw new Error(`中文安装路径兼容资源准备失败,请检查磁盘空间和目录权限:${(lastError as Error)?.message || '无可用 ASCII 目录'}`)
+}
+
+function windowsShortPath(directory: string): Promise<string | null> {
+ const escaped = directory.replace(/'/g, "''")
+ const script = [
+ "$ErrorActionPreference='Stop'",
+ '$fso=New-Object -ComObject Scripting.FileSystemObject',
+ `$short=$fso.GetFolder('${escaped}').ShortPath`,
+ 'if([string]::IsNullOrWhiteSpace($short)){exit 2}',
+ '[Console]::Write($short)',
+ ].join(';')
+ const encoded = Buffer.from(script, 'utf16le').toString('base64')
+ const powershell = process.env.SystemRoot
+ ? path.join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
+ : 'powershell.exe'
+
+ return new Promise(resolve => {
+ execFile(powershell, [
+ '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
+ '-EncodedCommand', encoded,
+ ], { timeout: 5000, windowsHide: true, encoding: 'utf8', maxBuffer: 64 * 1024 }, (error, stdout) => {
+ if (error) { resolve(null); return }
+ const short = String(stdout).trim()
+ resolve(isAsciiPath(short) && fs.existsSync(path.join(short, 'app.asar')) ? short : null)
+ })
+ })
+}
+
+export async function resolveRuntimeResources(
+ resourcesPath: string,
+ options: RuntimeOptions & { platform: string },
+): Promise<string> {
+ if (options.platform !== 'win32' || isAsciiPath(resourcesPath)) return resourcesPath
+
+ const short = await windowsShortPath(resourcesPath)
+ if (short) {
+ options.log?.(`non-ASCII install path: using Windows short resources path ${short}`)
+ return short
+ }
+
+ options.log?.('non-ASCII install path: short path unavailable, staging runtime resources')
+ const staged = stageRuntimeResources(resourcesPath, options)
+ options.log?.(`non-ASCII install path: using staged resources ${staged}`)
+ return staged
+}
diff --git a/desktop/tests/main-startup.test.mjs b/desktop/tests/main-startup.test.mjs
index be5aefe..b9e552c 100644
--- a/desktop/tests/main-startup.test.mjs
+++ b/desktop/tests/main-startup.test.mjs
@@ -7,9 +7,9 @@ import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const code = fs.readFileSync(new URL('../dist/main.js', import.meta.url), 'utf8')
-async function boot(mode = 'pending') {
+async function boot(mode = 'pending', options = {}) {
const windows = [], errors = [], logs = [], timers = new Map()
- let requests = 0, forks = 0, now = 0, timerId = 0
+ let requests = 0, forks = 0, now = 0, timerId = 0, forkArgs = null
const app = new EventEmitter()
Object.assign(app, { isPackaged: true, getPath: () => '/mock/user', setPath() {}, getVersion: () => 'test', requestSingleInstanceLock: () => true, whenReady: () => Promise.resolve(), quit() { app.emit('before-quit') } })
class Window extends EventEmitter {
@@ -25,10 +25,15 @@ async function boot(mode = 'pending') {
loadURL(url) { this.loadedURL = url; return mode === 'page-failure' ? Promise.reject(new Error('ERR_CONNECTION_RESET')) : Promise.resolve() }
}
const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => {}
- const electron = { app, BrowserWindow: Window, dialog: { showErrorBox: (...args) => errors.push(args) }, ipcMain: { handle() {} }, shell: {}, utilityProcess: { fork() { forks++; return child } } }
+ const electron = { app, BrowserWindow: Window, dialog: { showErrorBox: (...args) => errors.push(args) }, ipcMain: { handle() {} }, shell: {}, utilityProcess: { fork(...args) { forks++; forkArgs = args; return child } } }
+ const childProcess = { execFile(_file, _args, _options, callback) {
+ queueMicrotask(() => options.shortPath
+ ? callback(null, options.shortPath, '')
+ : callback(new Error('short path unavailable'), '', ''))
+ } }
const filesystem = { existsSync: p => !/storage-config|template-version|startup.log/.test(p), mkdirSync() {}, cpSync() {}, writeFileSync() {}, appendFileSync: (_p, s) => logs.push(s) }
const fakeProcess = new EventEmitter()
- Object.assign(fakeProcess, { platform: 'win32', arch: 'x64', env: {}, versions: { electron: '37.10.3' }, pid: 123, resourcesPath: '/mock/resources', stdout: new EventEmitter(), stderr: new EventEmitter() })
+ Object.assign(fakeProcess, { platform: 'win32', arch: 'x64', env: {}, versions: { electron: '37.10.3' }, pid: 123, resourcesPath: options.resourcesPath || '/mock/resources', stdout: new EventEmitter(), stderr: new EventEmitter() })
fakeProcess.stdout.write = fakeProcess.stderr.write = () => true
const net = { createServer() { const s = new EventEmitter(); s.listen = (_p, _h, fn) => fn(); s.address = () => ({port: 43210}); s.close = fn => fn(); return s } }
const http = { get(_opts, callback) {
@@ -37,7 +42,7 @@ async function boot(mode = 'pending') {
if (mode !== 'pending') queueMicrotask(() => callback({ statusCode: 200, resume() {} }))
return request
} }
- const context = vm.createContext({ require: name => name === 'electron' ? electron : /^(node:)?fs$/.test(name) ? filesystem : /^(node:)?net$/.test(name) ? net : name === 'node:http' ? http : require(name),
+ const context = vm.createContext({ require: name => name === 'electron' ? electron : name === 'node:child_process' ? childProcess : /^(node:)?fs$/.test(name) ? filesystem : /^(node:)?net$/.test(name) ? net : name === 'node:http' ? http : require(name),
process: fakeProcess, __dirname: '/mock/resources/app.asar/dist', module: {exports:{}}, exports: {}, console: {log(){},warn(){},error(){}}, Buffer, URL,
Date: class extends Date { static now() { return now } },
setTimeout: (fn, ms) => { const t = { id: ++timerId, at: now + ms, fn, unref() {} }; timers.set(t.id,t); return t },
@@ -46,7 +51,7 @@ async function boot(mode = 'pending') {
vm.runInContext(code, context)
async function flush() { for(let i=0;i<50;i++) await Promise.resolve() }
await flush()
- return { windows, errors, logs, app, child, requests: () => requests, forks: () => forks, flush,
+ return { windows, errors, logs, app, child, requests: () => requests, forks: () => forks, forkArgs: () => forkArgs, flush,
async expireHealth() { now=60_001; for(const t of [...timers.values()]) if(t.at <= now && t.at <= 1000) {timers.delete(t.id);t.fn()} await flush() } }
}
@@ -73,6 +78,18 @@ test('page load failure reports a visible error instead of leaving a hidden wind
const p=await boot('page-failure'); assert.equal(p.errors.length,1)
assert.match(p.errors[0][1],/ERR_CONNECTION_RESET/)
})
+test('non-ASCII Windows install resources use one short path for backend and media tools', async () => {
+ const shortPath = 'C:\\HUOBAO~1\\resources'
+ const p = await boot('healthy', {
+ resourcesPath: 'C:\\用户\\HuobaoDrama\\resources',
+ shortPath,
+ })
+ assert.ok(p.forkArgs()[0].startsWith(shortPath))
+ assert.ok(p.forkArgs()[2].env.FFMPEG_BIN.startsWith(shortPath))
+ assert.ok(p.forkArgs()[2].env.FFPROBE_BIN.startsWith(shortPath))
+ assert.ok(p.forkArgs()[2].env.FRONTEND_DIST.startsWith(shortPath))
+ assert.equal(p.errors.length, 0)
+})
test('closing while backend starts cancels silently', async () => {
const p=await boot(); p.app.quit(); await p.expireHealth(); assert.equal(p.errors.length,0)
})
diff --git a/desktop/tests/runtime-resources.test.ts b/desktop/tests/runtime-resources.test.ts
new file mode 100644
index 0000000..d442198
--- /dev/null
+++ b/desktop/tests/runtime-resources.test.ts
@@ -0,0 +1,72 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { isAsciiPath, stageRuntimeResources } from '../src/runtime-resources.js'
+
+function makeResources(root: string): string {
+ const resources = path.join(root, '中文安装目录', 'resources')
+ fs.mkdirSync(path.join(resources, 'app.asar.unpacked', 'node_modules', 'native'), { recursive: true })
+ fs.mkdirSync(path.join(resources, 'frontend'), { recursive: true })
+ fs.mkdirSync(path.join(resources, 'workspace-template', 'prompts'), { recursive: true })
+ fs.mkdirSync(path.join(resources, 'bin'), { recursive: true })
+ fs.writeFileSync(path.join(resources, 'app.asar'), 'asar-v1')
+ fs.writeFileSync(path.join(resources, 'app.asar.unpacked', 'node_modules', 'native', 'module.node'), 'native')
+ fs.writeFileSync(path.join(resources, 'frontend', 'index.html'), 'frontend-v1')
+ fs.writeFileSync(path.join(resources, 'workspace-template', 'prompts', 'agent.md'), 'prompt')
+ fs.writeFileSync(path.join(resources, 'bin', 'ffmpeg.exe'), 'ffmpeg')
+ fs.writeFileSync(path.join(resources, 'bin', 'ffprobe.exe'), 'ffprobe')
+ return resources
+}
+
+test('ASCII detection only accepts paths safe for native runtime loading', () => {
+ assert.equal(isAsciiPath('C:\\Program Files\\HuobaoDrama'), true)
+ assert.equal(isAsciiPath('C:\\用户\\HuobaoDrama'), false)
+ assert.equal(isAsciiPath('D:\\应用\\HuobaoDrama'), false)
+})
+
+test('runtime staging copies every backend dependency, reuses cache and refreshes on package change', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'huobao-runtime-'))
+ try {
+ const resources = makeResources(root)
+ const options = { version: '1.0.0', userDataDir: path.join(root, 'userData') }
+ const staged = stageRuntimeResources(resources, options)
+ assert.equal(isAsciiPath(staged), true)
+ for (const file of [
+ 'app.asar',
+ 'app.asar.unpacked/node_modules/native/module.node',
+ 'frontend/index.html',
+ 'workspace-template/prompts/agent.md',
+ 'bin/ffmpeg.exe',
+ 'bin/ffprobe.exe',
+ ]) assert.equal(fs.existsSync(path.join(staged, file)), true, file)
+
+ fs.writeFileSync(path.join(resources, 'frontend', 'index.html'), 'frontend-v2')
+ assert.equal(stageRuntimeResources(resources, options), staged)
+ assert.equal(fs.readFileSync(path.join(staged, 'frontend', 'index.html'), 'utf8'), 'frontend-v1')
+
+ fs.appendFileSync(path.join(resources, 'app.asar'), '-updated')
+ assert.equal(stageRuntimeResources(resources, options), staged)
+ assert.equal(fs.readFileSync(path.join(staged, 'frontend', 'index.html'), 'utf8'), 'frontend-v2')
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('a Chinese user profile falls back to an ASCII ProgramData runtime cache', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'huobao-runtime-fallback-'))
+ try {
+ const resources = makeResources(root)
+ const programData = path.join(root, 'ProgramData')
+ const staged = stageRuntimeResources(resources, {
+ version: '1.0.0',
+ userDataDir: path.join(root, '中文用户', 'HuobaoDrama'),
+ programDataDir: programData,
+ })
+ assert.equal(isAsciiPath(staged), true)
+ assert.ok(staged.startsWith(path.join(programData, 'HuobaoDrama')))
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})