Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions src/web-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -618,16 +618,18 @@ module.exports = `<!DOCTYPE html>
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();
Expand All @@ -638,16 +640,18 @@ module.exports = `<!DOCTYPE html>
}

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);
}
}

Expand Down
13 changes: 12 additions & 1 deletion src/web.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}
}