fix: 恢复成功后整体替换待写队列,修首屏自愈抢跑写空

This commit is contained in:
2026-11-02 23:30:30 +08:00
parent 62f5168dfe
commit ff1abee438
9 changed files with 101 additions and 43 deletions
+9 -5
View File
@@ -35,11 +35,14 @@ const RETRY_DELAYS = [0, 300, 700, 1200, 2000, 3000]
* - reachable: true, state: null → 宿主可达但还没有镜像(首次使用),可以写
* - reachable: false → 读不到,本次会话禁止写
*/
export async function loadHostState(): Promise<HostReadResult> {
export async function loadHostState(localAt = 0): Promise<HostReadResult> {
for (const delay of RETRY_DELAYS) {
if (delay) await new Promise((r) => setTimeout(r, delay))
try {
const r = await fetch(ENDPOINT, { cache: 'no-store', headers: { accept: 'application/json' } })
const r = await fetch(ENDPOINT + '?localAt=' + encodeURIComponent(String(localAt)), {
cache: 'no-store',
headers: { accept: 'application/json' },
})
if (!r.ok) continue
const j: any = await r.json()
if (j && typeof j === 'object' && j.state && typeof j.state === 'object') {
@@ -103,10 +106,11 @@ export function queueHostSave(patch: HostStateParts): void {
/**
* 宿主镜像已成功读到,放行写入。
* 传入读到的内容,让之后的半截写入也能带上另一半。
* 传入权威内容时**整体替换**待写队列 —— 首屏自愈等早于恢复发生的写入必须作废,
* 否则那半截空值会把刚恢复好的项目盖掉(真实事故)。
*/
export function markHydrated(seed?: HostStateParts): void {
if (seed) parts = { ...seed, ...parts }
export function markHydrated(authoritative?: HostStateParts | null): void {
parts = authoritative ? { projects: authoritative.projects, view: authoritative.view } : {}
hydrated = true
}
+8 -5
View File
@@ -1433,7 +1433,9 @@ function WorktableSection(props: any) {
useEffect(() => {
let cancelled = false
void (async () => {
const res = await loadHostState()
let localAt = 0
try { localAt = Number(localStorage.getItem(SAVED_AT_KEY) ?? '0') || 0 } catch {}
const res = await loadHostState(localAt)
if (cancelled) return
if (!res.reachable) {
// 读不到就不写:宁可本次只在本地,也不拿空状态覆盖宿主镜像
@@ -1442,15 +1444,16 @@ function WorktableSection(props: any) {
return
}
const host = res.state
let localAt = 0
try { localAt = Number(localStorage.getItem(SAVED_AT_KEY) ?? '0') || 0 } catch {}
const hostAt = typeof host?.updatedAt === 'number' ? host.updatedAt : 0
if (host && hostAt > localAt) {
if (host.projects) persistProjects(normalizeProjects(host.projects))
if (host.view) persistView(normalizeView(host.view))
// 以宿主为准:作废首屏自愈等早于恢复的待写内容,避免半截空值回写
markHydrated({ projects: host.projects, view: host.view })
} else {
// 本地更新或宿主还没有镜像:什么都不发,等用户真的改动再写
markHydrated(null)
}
markHydrated(host ? { projects: host.projects, view: host.view } : {})
if (hostAt <= localAt) flushHostSave()
})()
const flush = () => flushHostSave()
window.addEventListener('pagehide', flush)
+26 -4
View File
@@ -282,13 +282,27 @@ export function apply(ctx: Context) {
const previews = createPreviewFiles()
ctx.effect(() => () => previews.clear(), 'dsh-worktable: preview capabilities')
/** 诊断日志:状态路由到底有没有被调用、被什么挡住(排查重启丢数据用,稳定后可删) */
const stateLog = (line: string) => {
void (async () => {
try {
const fsx = await import('node:fs/promises')
const dir = pathResolve(resolveDshHomeSafe(), 'logs')
await fsx.mkdir(dir, { recursive: true })
await fsx.appendFile(pathResolve(dir, 'worktable-state.log'), new Date().toISOString() + ' ' + line + '\n', 'utf8')
} catch {}
})()
}
// Direct WebServer routes do NOT inherit the host's /api authentication route.
const register = (route: any, publicAsset = false) => ctx.effect(() => webServer.register({
...route,
handler: async (req: any, res: any) => {
if (!publicAsset && route.path !== HEALTH_PATH) {
const rejected = await requestRejection(ctx, req)
if (rejected !== undefined) { json(res, rejected, { error: rejectionText(rejected) }); return }
if (rejected !== undefined) {
if (route.path === '/api/worktable/state') stateLog('REJECT ' + req.method + ' -> ' + rejected)
json(res, rejected, { error: rejectionText(rejected) }); return
}
}
return route.handler(req, res)
},
@@ -561,9 +575,11 @@ export function apply(ctx: Context) {
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) })
const parsed: any = JSON.parse(text)
json(res, 200, { ok: true, path: file, state: parsed })
} catch (err: any) {
if (err?.code === 'ENOENT') { json(res, 200, { ok: true, path: file, state: null }); return }
if (err?.code === 'ENOENT') { stateLog('GET empty (no file)'); json(res, 200, { ok: true, path: file, state: null }); return }
stateLog('GET error ' + String(err))
json(res, 500, { error: String(err) })
}
return
@@ -572,7 +588,7 @@ export function apply(ctx: Context) {
try {
const body = await readJsonBody(req)
const incoming = body && typeof body.state === 'object' && body.state !== null ? body.state : null
if (!incoming) { json(res, 400, { error: 'missing state' }); return }
if (!incoming) { stateLog('POST 400 missing state'); json(res, 400, { error: 'missing state' }); return }
// 按 key 合并:客户端只带 view 的半截写入不能把 projects 抹掉
let previous: any = null
try {
@@ -583,6 +599,12 @@ export function apply(ctx: Context) {
? { ...previous, ...incoming }
: incoming
const text = JSON.stringify(state)
// 只在「项目变少」时记一行:正常保存不写日志,避免文件无限增长
const inN = incoming?.projects?.layouts?.length ?? 0
const prevN = previous?.projects?.layouts?.length ?? 0
if (inN < prevN) {
stateLog('WARN projects shrink ' + prevN + ' -> ' + inN + ' (keys=' + Object.keys(incoming).join('+') + ')')
}
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 })