diff --git a/src/web-ui.js b/src/web-ui.js index 0deef21..1ed4162 100644 --- a/src/web-ui.js +++ b/src/web-ui.js @@ -618,16 +618,18 @@ module.exports = ` const state = snapshotState(); clearTimeout(saveTimer); saveTimer = setTimeout(() => { - if (writeLocalState(state)) return; + // Write to durable server file first, fall back to localStorage fetch('/state', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(state) - }).catch(() => {}); + }) + .then(() => writeLocalState(state)) + .catch(() => writeLocalState(state)); }, 500); } - async function loadLegacyState() { + async function loadServerState() { try { const resp = await fetch('/state'); const state = await resp.json(); @@ -638,16 +640,18 @@ module.exports = ` } async function load() { - const localState = readLocalState(); - if (localState) { - applyState(localState); + // Prefer durable server-side state (survives browser clears + restarts) + const serverState = await loadServerState(); + if (serverState) { + applyState(serverState); + // keep a local copy for offline resilience + writeLocalState(snapshotState()); return; } - const legacyState = await loadLegacyState(); - if (legacyState) { - applyState(legacyState); - writeLocalState(snapshotState()); + const localState = readLocalState(); + if (localState) { + applyState(localState); } } diff --git a/src/web.js b/src/web.js index 56e3349..2eb9dc8 100644 --- a/src/web.js +++ b/src/web.js @@ -315,4 +315,15 @@ async function startWebServer({ port = 3000 } = {}) { return { port: actualPort, close: () => server.close() } } -module.exports = { startWebServer } +module.exports = { + startWebServer, + STATE_FILE, + readState: () => { + try { return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')) } catch { return {} } + }, + writeState: (obj) => { + const dir = path.dirname(STATE_FILE) + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }) + fs.writeFileSync(STATE_FILE, JSON.stringify(obj, null, 2), { mode: 0o600 }) + } +}