fix(desktop): 状态镜像到宿主侧,修复随机端口导致重启丢数据

This commit is contained in:
2026-11-02 18:20:16 +08:00
parent f98246ef0c
commit a870f74875
9 changed files with 523 additions and 113 deletions
+43
View File
@@ -544,5 +544,48 @@ export function apply(ctx: Context) {
},
})
/**
* 工作台状态宿主侧镜像(本地补丁)。
*
* 桌面端宿主以 `--port 0` 启动,端口每次随机,页面来源跟着变;而 localStorage 按来源隔离,
* 于是「新建的项目重启就没了」。这里把项目/视图这份 JSON 落到 DSH_HOME 下的固定文件:
* 跨重启、跨端口稳定。客户端启动时比对时间戳决定是否回填(见 client/hostState.ts)。
*/
const statePath = () => pathResolve(resolveDshHomeSafe(), 'worktable-state.json')
register({
kind: 'exact',
path: '/api/worktable/state',
handler: async (req: any, res: any) => {
const file = statePath()
if (req.method === 'GET' || req.method === 'HEAD') {
try {
const raw = await readFile(file, 'utf8')
const text = raw.charCodeAt(0) === 0xFEFF ? raw.slice(1) : raw
json(res, 200, { ok: true, path: file, state: JSON.parse(text) })
} catch (err: any) {
if (err?.code === 'ENOENT') { json(res, 200, { ok: true, path: file, state: null }); return }
json(res, 500, { error: String(err) })
}
return
}
if (req.method !== 'POST') { json(res, 405, { error: 'method not allowed' }); return }
try {
const body = await readJsonBody(req)
const state = body && typeof body.state === 'object' && body.state !== null ? body.state : null
if (!state) { json(res, 400, { error: 'missing state' }); return }
const text = JSON.stringify(state)
if (text.length > 20 * 1024 * 1024) { json(res, 413, { error: 'state too large' }); return }
const fsx = await import('node:fs/promises')
await fsx.mkdir(dirname(file), { recursive: true })
const tmp = file + '.tmp-' + process.pid + '-' + Date.now()
await fsx.writeFile(tmp, text, 'utf8')
await fsx.rename(tmp, file)
json(res, 200, { ok: true, path: file })
} catch (err: any) {
json(res, err?.status ?? 500, { error: String(err) })
}
},
})
setupTerminal(webServer, ctx)
}