From f31d3933ae67f3e5d9556eac6a76b47175b00585 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 7 Oct 2026 14:26:22 +0800 Subject: [PATCH] feat(sync): add durable sync center and controlled updates --- CHANGELOG.md | 7 ++ README.md | 6 +- package.json | 2 +- public/addons.js | 150 +++++++++++++++++++++++++++++++----- public/backup.js | 4 +- public/index.html | 2 +- public/service-worker.js | 8 +- public/system-navigation.js | 2 +- public/terminal-app.js | 4 +- scripts/build.mjs | 2 +- scripts/validate.mjs | 6 +- 11 files changed, 161 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35c1eff..110e930 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ 本项目按 `v主版本.次版本.修订版本` 标记应用版本;按需创建 Git tag。下列内容以对应提交和已发布功能为准。 +## v1.21.0 — 2026-10-07 + +- 新增同步中心与任务栏同步状态入口,显示联网状态、待同步数量、冲突数量和上次成功同步时间,并支持手动重试。 +- 云端修改先写入设备本地持久队列;网络中断或请求失败后保留待同步操作,恢复联网时自动重试。 +- 同步冲突不再依赖一次性的系统确认框;同步中心并排展示本设备与云端版本,可逐项决定保留内容。 +- PWA 新版本安装完成后显示可控更新入口,由用户选择重启更新,避免使用过程中突然刷新。 + ## v1.20.0 — 2026-10-03 - JSON 备份升级为 Schema v3,覆盖全部可迁移的设备本地记录,并使用 SHA-256 校验文件完整性;继续兼容导入 v1/v2 备份。 diff --git a/README.md b/README.md index 118566f..42a1471 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 以桌面操作系统为交互方式的个人记录网站。用 App 记录日常、管理目标与待办,并沿时间线回看已经留下的内容。 -在线站点:[Life OS](https://life-os-personal-desktop.biss0.chatgpt.site) · 当前应用版本:**v1.20.0** · [更新日志](CHANGELOG.md) +在线站点:[Life OS](https://life-os-personal-desktop.biss0.chatgpt.site) · 当前应用版本:**v1.21.0** · [更新日志](CHANGELOG.md) ## 功能 @@ -34,13 +34,13 @@ 首次使用可选择“仅本地使用”或“登录并云同步”。仅本地模式无需登录,也不会请求云同步接口;数据写入当前设备、当前浏览器、本站专属的 OPFS 私有存储区,逻辑数据库位置为 `OPFS:/lifeos.sqlite`。SQLite 是本地持久层,`localStorage` 作为同步界面缓存和兼容旧版本的数据迁移来源。系统设置会显示当前模式、数据库状态、近似大小和持久存储状态。 -云端模式继续使用 ChatGPT 登录标识隔离不同用户的数据,资料通过同源 API 保存到 Sites 的 D1 数据库,本地 SQLite 作为离线副本。首次云端恢复前,本地资料会保留一份迁移前副本。浏览器缓存与 JSON 备份仍使用 `lifeos_system.tasksBoard`;云端将其中的目标和待办拆分为独立记录。用户可随时切回仅本地模式;切换不会自动删除已有云端数据。 +云端模式继续使用 ChatGPT 登录标识隔离不同用户的数据,资料通过同源 API 保存到 Sites 的 D1 数据库,本地 SQLite 作为离线副本。首次云端恢复前,本地资料会保留一份迁移前副本。浏览器缓存与 JSON 备份仍使用 `lifeos_system.tasksBoard`;云端将其中的目标和待办拆分为独立记录。用户可随时切回仅本地模式;切换不会自动删除已有云端数据。任务栏同步入口与系统设置中的同步中心会显示联网状态、待同步更改、冲突和上次成功同步时间;写入失败时操作保留在设备队列,恢复联网后自动重试。 OPFS 不对应用户可见的系统文件夹,并与网站来源和浏览器配置绑定。更换设备或浏览器不会自动带走本地数据,清除本站数据也会删除 SQLite 数据库,因此迁移前必须导出 JSON 备份。应用会在用户选择本地模式时请求持久存储,浏览器仍可能拒绝;无 OPFS 支持时保留 `localStorage` 兼容模式,并在设置中显示数据库不可用。数据页也可下载原始 `.sqlite` 副本,便于高级归档或检查;跨设备恢复仍以 JSON 备份为准。 **系统设置 → 导出数据** 会生成 JSON 备份;导入支持合并或覆盖。备份格式使用 `schemaVersion: 3`,会保存全部可迁移的设备本地记录并附带 SHA-256 完整性校验,仍可导入 v1/v2 备份。覆盖恢复前,应用会先自动下载当前状态的保险备份。云同步基线、冲突副本、存储模式和数据库缓存修订号不会跨设备迁移,避免把设备身份或同步内部状态带到新环境。 -主要本地数据键:`lifeos_memories`、`lifeos_museum`、`lifeos_profile`、`lifeos_settings`、`lifeos_system`。云端表结构见 `drizzle/0001_lifeos_records.sql`:记忆、标签、目标、待办、收藏各自按记录保存,资料与设置保留按用户存储的 JSON。旧版 `lifeos_states` 作为只读迁移来源保留;用户首次访问新版本时自动回填新表,旧表不会被清空。单条记录的修改使用版本号校验;冲突时会保存本地副本并要求选择。旧版浏览器标签页需刷新,整份状态写入接口已停用,避免覆盖新数据。应用的备份 `schemaVersion: 3` 与数据库迁移编号是两回事。建议定期导出备份。 +主要本地数据键:`lifeos_memories`、`lifeos_museum`、`lifeos_profile`、`lifeos_settings`、`lifeos_system`。云端表结构见 `drizzle/0001_lifeos_records.sql`:记忆、标签、目标、待办、收藏各自按记录保存,资料与设置保留按用户存储的 JSON。旧版 `lifeos_states` 作为只读迁移来源保留;用户首次访问新版本时自动回填新表,旧表不会被清空。单条记录的修改使用版本号校验;冲突时会保存本地副本,并在同步中心并排展示本设备与云端版本供用户逐项选择。同步队列、冲突和内部同步状态不会进入可迁移 JSON 备份。旧版浏览器标签页需刷新,整份状态写入接口已停用,避免覆盖新数据。应用的备份 `schemaVersion: 3` 与数据库迁移编号是两回事。建议定期导出备份。 数据库管理器的服务器固定为本站 D1,用户名固定为 `lifeos-admin`。每个 ChatGPT 账号首次打开管理器时设置自己的密码(至少 12 个字符),旧版共用口令不再有效。密码以独立盐值与 PBKDF2 摘要存入 `lifeos_admin_credentials`,不保存明文,也不写进仓库或浏览器;管理页可验证当前密码后更换。它在原有账号登录之上再次验证密码;会话仅在当前页面内存中保留 20 分钟,退出或修改密码后旧会话立即失效,连续五次输错锁定 15 分钟。管理 API 只允许当前账号在预设表内按记录操作,没有任意 SQL 执行入口。更改云端记录后应刷新桌面,使其他 App 重新加载数据。派生的标签索引和旧版状态备份不能在管理器中单独修改。 diff --git a/package.json b/package.json index 76a926d..b012b73 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "life-os", - "version": "1.20.0", + "version": "1.21.0", "private": true, "type": "module", "scripts": { diff --git a/public/addons.js b/public/addons.js index 2ba43db..b786c3a 100644 --- a/public/addons.js +++ b/public/addons.js @@ -2,8 +2,8 @@ (() => { const DRAFT_KEY = 'lifeos_today_draft_v1'; const localDay = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }; - const escapeHtml = value => String(value || '').replace(/[&<>]/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char])); - const APP_VERSION = '1.20.0'; + const escapeHtml = value => String(value || '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char])); + const APP_VERSION = '1.21.0'; window.LifeOSVersion = APP_VERSION; const appIds = ['today', 'timeline', 'museum', 'insights', 'profile', 'tasks', 'calendar', 'system', 'browser', 'terminal', 'database']; const t = (key, values) => LifeI18n.t(key, values); @@ -80,8 +80,29 @@ // The System panel uses inline onclick handlers, so expose this complete exporter. window.exportData = exportData; const CLOUD_KEYS = { profile: 'lifeos_profile', memories: 'lifeos_memories', museum: 'lifeos_museum', settings: 'lifeos_settings', system: 'lifeos_system' }; + const OUTBOX_KEY = 'lifeos_sync_outbox_v1'; + const CONFLICTS_KEY = 'lifeos_sync_conflicts_v1'; + const META_KEY = 'lifeos_sync_meta_v1'; let cloudReady = false, applyingCloud = false, syncTimer = null, syncErrorShown = false, syncing = false, syncAgain = false; let baseline = null, versions = null; + const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key) || 'null') ?? fallback; } catch { return fallback; } }; + const opKey = op => `${op.kind}:${op.id}`; + const outbox = () => readJson(OUTBOX_KEY, []); + const conflicts = () => readJson(CONFLICTS_KEY, []); + const meta = () => readJson(META_KEY, {}); + function persistQueue(key, value) { localStorage.setItem(key, JSON.stringify(value)); emitSyncState(); } + function queueOperations(operations) { + const existing = new Map(outbox().map(op => [opKey(op), op])), queued = new Map(); + operations.forEach(op => queued.set(opKey(op), { ...op, queuedAt: existing.get(opKey(op))?.queuedAt || new Date().toISOString() })); + persistQueue(OUTBOX_KEY, [...queued.values()]); + } + function dequeue(operation) { persistQueue(OUTBOX_KEY, outbox().filter(item => opKey(item) !== opKey(operation))); } + function setMeta(patch) { localStorage.setItem(META_KEY, JSON.stringify({ ...meta(), ...patch })); emitSyncState(); } + function syncState() { + const mode = window.LifeOSLocalDB?.mode?.() || 'unset', details = meta(); + return { mode, online: navigator.onLine, phase: syncing ? 'syncing' : !navigator.onLine ? 'offline' : details.errorAt ? 'paused' : 'ready', pending: outbox().length, conflicts: conflicts().length, lastSyncAt: details.lastSyncAt || null, errorAt: details.errorAt || null, updateAvailable: Boolean(window.LifeOSPWA?.updateAvailable?.()) }; + } + function emitSyncState() { if (typeof window.dispatchEvent === 'function' && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('lifeos-sync-state', { detail: syncState() })); } const cloudMode = () => window.LifeOSLocalDB?.mode?.() === 'cloud'; const cloudFallback = { profile: {}, memories: [], museum: [], settings: {}, system: { schemaVersion: 2 } }; function cloudSnapshot() { @@ -146,17 +167,12 @@ const latest = await response.json(); const remote = record(latest.state, op.kind, op.id); localStorage.setItem('lifeos_sync_conflict_backup_v1', JSON.stringify({ exportedAt: new Date().toISOString(), state: cloudSnapshot() })); - const overwrite = remote !== null && confirm(t('addon.syncConflictConfirm')); + const item = { key: opKey(op), kind: op.kind, recordId: op.id, local: op.value, remote, remoteVersion: latest.versions[op.kind][op.id] || 0, detectedAt: new Date().toISOString() }; + const pending = conflicts().filter(conflict => conflict.key !== item.key); + persistQueue(CONFLICTS_KEY, [...pending, item]); baseline = replaceRecord(baseline, op.kind, op.id, remote); versions[op.kind][op.id] = latest.versions[op.kind][op.id] || 0; - if (!overwrite) { - const restored = replaceRecord(cloudSnapshot(), op.kind, op.id, remote); - applyingCloud = true; - const field = ['goals', 'tasks'].includes(op.kind) ? 'system' : op.kind; - localStorage.setItem(CLOUD_KEYS[field], JSON.stringify(restored[field])); - applyingCloud = false; - window.renderAll?.(); - } + dequeue(op); saveBaseline(); } async function uploadCloudState() { @@ -165,18 +181,26 @@ try { do { syncAgain = false; - for (const op of changes(baseline, cloudSnapshot())) { + const blocked = new Set(conflicts().map(item => item.key)); + const operations = changes(baseline, cloudSnapshot()).filter(op => !blocked.has(opKey(op))); + queueOperations(operations); + for (const op of operations) { const response = await post('/api/lifeos-sync', op); - if (response.status === 409) { await resolveConflict(op); syncAgain = true; break; } + if (response.status === 409) { await resolveConflict(op); break; } if (!response.ok) throw new Error('sync failed'); const result = await response.json(); baseline = replaceRecord(baseline, op.kind, op.id, op.value); versions[op.kind][op.id] = result.version; + dequeue(op); saveBaseline(); } - } while (syncAgain || changes(baseline, cloudSnapshot()).length); + } while (syncAgain || changes(baseline, cloudSnapshot()).some(op => !conflicts().some(conflict => conflict.key === opKey(op)))); syncErrorShown = false; - } finally { syncing = false; } + setMeta({ lastSyncAt: new Date().toISOString(), errorAt: null }); + } catch (error) { + setMeta({ errorAt: new Date().toISOString() }); + throw error; + } finally { syncing = false; emitSyncState(); } } function scheduleCloudSync() { if (!cloudMode() || !cloudReady || applyingCloud) return; @@ -185,6 +209,23 @@ if (!syncErrorShown) { syncErrorShown = true; toast('addon.syncPaused'); } }), 450); } + function resolveSavedConflict(key, choice) { + const item = conflicts().find(conflict => conflict.key === key); + if (!item || !baseline || !versions) return; + baseline = replaceRecord(baseline, item.kind, item.recordId, item.remote); + versions[item.kind][item.recordId] = item.remoteVersion || 0; + if (choice === 'cloud') { + const restored = replaceRecord(cloudSnapshot(), item.kind, item.recordId, item.remote); + applyingCloud = true; + const field = ['goals', 'tasks'].includes(item.kind) ? 'system' : item.kind; + localStorage.setItem(CLOUD_KEYS[field], JSON.stringify(restored[field])); + applyingCloud = false; + window.renderAll?.(); + } + persistQueue(CONFLICTS_KEY, conflicts().filter(conflict => conflict.key !== key)); + saveBaseline(); + if (choice === 'local') scheduleCloudSync(); + } function migrationPrompt(state) { const dialog = document.createElement('div'); dialog.id = 'lifeos-cloud-migration'; @@ -223,7 +264,8 @@ if (!same(record(previous.state, op.kind, op.id), record(state, op.kind, op.id))) { localStorage.setItem('lifeos_sync_conflict_backup_v1', JSON.stringify({ exportedAt: new Date().toISOString(), state: local })); hadConflict = true; - if (record(state, op.kind, op.id) === null || !confirm(t('addon.syncConflictConfirm'))) continue; + const item = { key: opKey(op), kind: op.kind, recordId: op.id, local: op.value, remote: record(state, op.kind, op.id), remoteVersion: cloudVersions[op.kind][op.id] || 0, detectedAt: new Date().toISOString() }; + persistQueue(CONFLICTS_KEY, [...conflicts().filter(conflict => conflict.key !== item.key), item]); } const restored = replaceRecord(cloudSnapshot(), op.kind, op.id, op.value); applyingCloud = true; @@ -263,9 +305,81 @@ syncAgain = false; clearTimeout(syncTimer); } - window.LifeOSCloud = { start: startCloudSync, stop: stopCloudSync }; + window.LifeOSCloud = { start: startCloudSync, stop: stopCloudSync, retry: () => { setMeta({ errorAt: null }); return uploadCloudState(); }, status: syncState, conflicts, resolveConflict: resolveSavedConflict }; if (cloudMode()) startCloudSync(); - new MutationObserver(() => { wireToday(); wireLanguageControl(); }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['title'] }); + window.addEventListener('online', () => { emitSyncState(); if (cloudMode()) window.LifeOSCloud.retry().catch(() => {}); }); + window.addEventListener('offline', emitSyncState); + const syncText = { + en: { title:'SYNC CENTER', local:'Local only', ready:'Up to date', syncing:'Syncing', offline:'Offline', paused:'Sync paused', pending:'Pending changes', conflicts:'Conflicts', last:'Last synced', never:'Not yet', retry:'RETRY NOW', close:'CLOSE', update:'UPDATE READY', install:'RESTART & UPDATE', noConflicts:'No conflicts need your attention.', conflictHelp:'Choose which version to keep. Nothing is discarded until you decide.', localVersion:'THIS DEVICE', cloudVersion:'CLOUD', keepLocal:'KEEP THIS DEVICE', keepCloud:'KEEP CLOUD', mode:'Storage mode', status:'Sync status' }, + 'zh-CN': { title:'同步中心', local:'仅本地使用', ready:'已是最新', syncing:'正在同步', offline:'当前离线', paused:'同步已暂停', pending:'待同步更改', conflicts:'同步冲突', last:'上次同步', never:'尚未同步', retry:'立即重试', close:'关闭', update:'发现新版本', install:'重启并更新', noConflicts:'没有需要处理的冲突。', conflictHelp:'请选择保留哪个版本;在你决定之前,系统不会丢弃任何一方的数据。', localVersion:'本设备版本', cloudVersion:'云端版本', keepLocal:'保留本设备', keepCloud:'保留云端', mode:'存储模式', status:'同步状态' }, + 'zh-HK': { title:'同步中心', local:'只在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' }, + 'zh-MO': { title:'同步中心', local:'只在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' }, + 'zh-TW': { title:'同步中心', local:'僅在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' } + }; + const syncCopy = () => syncText[window.LifeI18n?.language?.()] || syncText.en; + const stateLabel = state => state.mode === 'local' ? syncCopy().local : syncCopy()[state.phase] || syncCopy().ready; + const when = value => value ? new Intl.DateTimeFormat(window.LifeI18n?.locale?.() || 'en-US', { dateStyle:'medium', timeStyle:'short' }).format(new Date(value)) : syncCopy().never; + const pretty = value => value === null ? '∅' : JSON.stringify(value, null, 2); + function syncIndicator() { + let button = document.querySelector('#lifeos-sync-indicator'); + if (button) return button; + button = document.createElement('button'); button.id = 'lifeos-sync-indicator'; button.type = 'button'; button.addEventListener('click', openSyncCenter); + const taskbar = document.querySelector('.taskbar'), clockNode = taskbar?.querySelector('.clock'); + if (taskbar) taskbar.insertBefore(button, clockNode || null); + return button; + } + function renderSyncSurfaces() { + const state = syncState(), copy = syncCopy(), button = syncIndicator(); + if (button) { + button.className = `sync-indicator ${state.phase} ${state.conflicts || state.updateAvailable ? 'attention' : ''}`; + button.innerHTML = `${state.conflicts || state.pending || (state.updateAvailable ? '↑' : '')}`; + button.title = state.updateAvailable ? copy.update : `${copy.status}: ${stateLabel(state)}`; button.setAttribute('aria-label', button.title); + } + const dataPanel = document.querySelector('#content-system [data-settings-group="data"]'); + if (dataPanel && !dataPanel.querySelector('[data-sync-summary]')) { + dataPanel.insertAdjacentHTML('beforeend', `
${copy.title}
`); + } + const summary = dataPanel?.querySelector('[data-sync-summary] button'); + const summaryText = `${stateLabel(state)} · ${copy.pending} ${state.pending} · ${copy.conflicts} ${state.conflicts}`; + if (summary && summary.textContent !== summaryText) summary.textContent = summaryText; + } + function fillSyncCenter(root) { + const state = syncState(), copy = syncCopy(), items = conflicts(); + root.querySelector('.sync-center-card').innerHTML = `
${copy.title}

${stateLabel(state)}

${copy.mode}
${state.mode === 'local' ? copy.local : 'Cloud'}
${copy.pending}
${state.pending}
${copy.conflicts}
${state.conflicts}
${copy.last}
${when(state.lastSyncAt)}
${state.mode === 'cloud' ? `` : ''}${state.updateAvailable ? `` : ''}
${items.length ? `

${copy.conflictHelp}

${items.map(item => `
${escapeHtml(item.kind)}${when(item.detectedAt)}
${copy.localVersion}
${escapeHtml(pretty(item.local))}
${copy.cloudVersion}
${escapeHtml(pretty(item.remote))}
`).join('')}` : `

${copy.noConflicts}

`}
`; + } + function openSyncCenter() { + let root = document.querySelector('#lifeos-sync-center'); + if (!root) { root = document.createElement('div'); root.id = 'lifeos-sync-center'; root.className = 'modal'; root.innerHTML = ''; document.body.append(root); } + fillSyncCenter(root); + } + document.addEventListener('click', event => { + if (event.target.closest('[data-open-sync]')) openSyncCenter(); + if (event.target.closest('[data-close-sync]') || (event.target.id === 'lifeos-sync-center')) document.querySelector('#lifeos-sync-center')?.remove(); + if (event.target.closest('[data-retry-sync]')) window.LifeOSCloud.retry().catch(() => {}); + if (event.target.closest('[data-apply-update]')) window.LifeOSPWA?.applyUpdate?.(); + const choice = event.target.closest('[data-conflict-choice]'); + if (choice) { const key = choice.closest('[data-conflict-key]')?.dataset.conflictKey; if (key) { resolveSavedConflict(key, choice.dataset.conflictChoice); const center = document.querySelector('#lifeos-sync-center'); if (center) fillSyncCenter(center); } } + }); + let waitingWorker = null, reloadingForUpdate = false; + window.LifeOSPWA = { + updateAvailable: () => Boolean(waitingWorker), + applyUpdate: () => waitingWorker?.postMessage({ type:'SKIP_WAITING' }), + register: async () => { + if (!('serviceWorker' in navigator)) return; + const registration = await navigator.serviceWorker.register('/service-worker.js'); + const inspect = worker => { if (worker?.state === 'installed' && navigator.serviceWorker.controller) { waitingWorker = worker; emitSyncState(); renderSyncSurfaces(); } }; + if (registration.waiting) inspect(registration.waiting); + registration.addEventListener('updatefound', () => { const worker = registration.installing; worker?.addEventListener('statechange', () => inspect(worker)); }); + navigator.serviceWorker.addEventListener('controllerchange', () => { if (reloadingForUpdate) return; reloadingForUpdate = true; location.reload(); }); + } + }; + window.openSyncCenter = openSyncCenter; + window.addEventListener('lifeos-sync-state', renderSyncSurfaces); + window.addEventListener('load', () => { renderSyncSurfaces(); window.LifeOSPWA.register().catch(() => {}); }); + const syncStyle = document.createElement('style'); + syncStyle.textContent = `.sync-indicator{position:relative;width:40px;height:40px;border:0;border-radius:11px;background:transparent;color:var(--muted)}.sync-indicator>span{display:block;width:10px;height:10px;margin:auto;border:2px solid currentColor;border-radius:50%}.sync-indicator.syncing>span{border-top-color:transparent;animation:sync-spin .8s linear infinite}.sync-indicator.offline,.sync-indicator.paused,.sync-indicator.attention{color:#f3a36f}.sync-indicator b{position:absolute;right:3px;top:2px;min-width:15px;height:15px;padding:0 3px;border-radius:8px;background:var(--accent);color:var(--bg);font:500 10px/15px 'DM Mono'}@keyframes sync-spin{to{transform:rotate(360deg)}}.sync-summary .secondary{font-size:12px;line-height:1.4}.sync-center-card{width:min(760px,calc(100vw - 28px));max-height:min(760px,calc(100vh - 28px));overflow:auto}.sync-center-card h2{font-size:24px;letter-spacing:-.04em}.sync-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:18px 0}.sync-facts div{padding:13px;border:1px solid var(--line);border-radius:10px;background:var(--panel2)}.sync-facts dt{color:var(--muted);font-size:12px}.sync-facts dd{margin:5px 0 0;font-size:14px;overflow-wrap:anywhere}.sync-help,.sync-empty{margin:22px 0 0;color:var(--muted);font-size:14px;line-height:1.6}.sync-conflict{margin-top:13px;padding-top:13px;border-top:1px solid var(--line)}.sync-conflict header{display:flex;justify-content:space-between;gap:12px}.sync-conflict header span{color:var(--muted);font-size:12px}.sync-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px}.sync-compare section{min-width:0;padding:12px;border:1px solid var(--line);border-radius:10px}.sync-compare pre{max-height:190px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--muted);font:12px/1.5 'DM Mono'}.sync-compare button{width:100%}@media(max-width:650px){.sync-indicator{width:32px;padding:0}.sync-facts,.sync-compare{grid-template-columns:1fr}.sync-center-card{max-height:calc(100vh - 18px)}.sync-conflict header{display:grid}}`; + document.head.append(syncStyle); + new MutationObserver(() => { wireToday(); wireLanguageControl(); renderSyncSurfaces(); }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['title'] }); wireToday(); wireLanguageControl(); document.addEventListener('click', e => { if (e.target.closest('#content-today .primary')) clearDraftAfterSave(); }); diff --git a/public/backup.js b/public/backup.js index bc17dad..4413775 100644 --- a/public/backup.js +++ b/public/backup.js @@ -2,7 +2,7 @@ (() => { const BACKUP_SCHEMA = 3; const SAFETY_KEY = 'lifeos_restore_safety_v1'; - const excluded = /^(lifeos_(?:cloud_|precloud_|sync_conflict_|storage_mode_|local_cache_revision_|restore_safety_))/; + const excluded = /^(lifeos_(?:cloud_|precloud_|sync_|storage_mode_|local_cache_revision_|restore_safety_))/; const portableKey = key => typeof key === 'string' && key.startsWith('lifeos_') && !excluded.test(key); const records = () => Object.fromEntries( Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) @@ -22,7 +22,7 @@ const stored = records(); return { app: 'Life OS', - version: window.LifeOSVersion || '1.20.0', + version: window.LifeOSVersion || '1.21.0', schemaVersion: BACKUP_SCHEMA, exportedAt: new Date().toISOString(), profile: json('lifeos_profile', {}), diff --git a/public/index.html b/public/index.html index 0119caf..2101ffd 100644 --- a/public/index.html +++ b/public/index.html @@ -25,4 +25,4 @@ function profileApp(c){let p=profile(),a=mems(),common=Object.entries(a.reduce(( function today(c){let m=mems().find(x=>x.date===day());if(todayDraft===null){selectedMood=m?.mood||'cloudy';selectedEnergy=m?.energy||3}let f=m||filmFor(selectedMood,selectedEnergy),text=todayDraft===null?(m?.text||''):todayDraft,cWeek=new Date().toLocaleDateString(LifeI18n.locale(),{weekday:'long'}).toUpperCase();c.innerHTML=`
${cWeek}

${fmtDate(day()).replace(/^[^,]+, /,'')}

${i18n('How was your day?')}

`}function rerenderToday(){let old=document.querySelector('#entry');todayDraft=old?old.value:todayDraft||'';window.today(document.querySelector('#content-today'));let entry=document.querySelector('#entry');entry?.focus();entry?.setSelectionRange(entry.value.length,entry.value.length)} function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS

System, local and yours.

APPEARANCE
${['dark','light','auto'].map(x=>``).join('')}
LANGUAGE
DATA
STORAGE

Local Storage
${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB

DATA STORAGE

Your data is stored locally in this browser.
Create regular backups to prevent data loss.

${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'
BACKUP RECOMMENDED':''}

VERSION

Life OS
Version ${window.LifeOSVersion||'1.18.1'} · Schema v2

`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2,3].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=``}function replaceConfirm(){modal.innerHTML=``}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=``}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)} window.renderIcons=renderIcons;window.renderAll=renderAll;window.toast=toast; - + diff --git a/public/service-worker.js b/public/service-worker.js index c04f8ba..5782bf2 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -1,11 +1,15 @@ -const CACHE = 'life-os-shell-v1.20.0'; +const CACHE = 'life-os-shell-v1.21.0'; const SHELL = [ '/', '/index.html', '/manifest.webmanifest', '/life-os-icon.svg', '/local-db-worker.js', '/sqlite3.mjs', '/sqlite3.wasm' ]; self.addEventListener('install', event => { - event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting())); + event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL))); +}); + +self.addEventListener('message', event => { + if (event.data?.type === 'SKIP_WAITING') self.skipWaiting(); }); self.addEventListener('activate', event => { diff --git a/public/system-navigation.js b/public/system-navigation.js index 39989b1..d613791 100644 --- a/public/system-navigation.js +++ b/public/system-navigation.js @@ -27,7 +27,7 @@ shell.innerHTML = `
${t('settings')}

${t(active)}

${active === 'home' ? `

${t('homeHint')}

` : ''}
`; const view = shell.querySelector('.system-settings-view'); if (active === 'home') { - view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.20.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; + view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.21.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; } else { const group = document.createElement('div'); group.className = 'settings system-settings-group'; diff --git a/public/terminal-app.js b/public/terminal-app.js index b3cc913..61f1269 100644 --- a/public/terminal-app.js +++ b/public/terminal-app.js @@ -150,7 +150,7 @@ return { message: new Intl.DateTimeFormat(LifeI18n.locale(), options).format(new Date()) }; } if (kind === 'uptime') { if (verb) throw new Error('usage'); const seconds = Math.floor((Date.now() - startedAt) / 1000); return { message: t('uptime', { minutes: Math.floor(seconds / 60), seconds: seconds % 60 }) }; } - if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.20.0'}` }; } + if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.21.0'}` }; } if (kind === 'status') { if (verb) throw new Error('usage'); const data = board(); return { message: t('status', { memories: mems().length, goals: data.goals.length, tasks: data.tasks.length }) }; } if (kind === 'apps') { if (verb) throw new Error('usage'); return { message: Object.keys(APPS).map(id => `${id} — ${LifeI18n.t(`app.${id}`)}`).join('\n') }; } if (kind === 'history') { if (verb) throw new Error('usage'); return { message: history.slice(-20).map((entry,index) => `${index + 1}. ${entry}`).join('\n') || t('empty') }; } @@ -235,7 +235,7 @@ }; window.terminalApp = node => { if (node.querySelector('.terminal-shell') && node.dataset.terminalLocale === lang()) { output(node); return; } - if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.20.0' }), kind: 'system' }); welcomed = true; } + if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.21.0' }), kind: 'system' }); welcomed = true; } node.dataset.terminalLocale = lang(); node.innerHTML = `
Life OS / ${t('title')}${t('hint')}
`; output(node); composer(node, Boolean(compose)); diff --git a/scripts/build.mjs b/scripts/build.mjs index 32a34a2..6893cb0 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -13,7 +13,7 @@ const [rawIndexHtml, addonsJs, backupJs, bootGuardJs, localDbJs, localDbWorkerJs readFile(new URL("../node_modules/@sqlite.org/sqlite-wasm/dist/sqlite3.wasm", import.meta.url)), text("i18n.js"), text("tasks.js"), text("calendar.js"), text("notifications.js"), text("i18n-renderers.js"), text("desktop-personalization.js"), text("desktop-widgets.js"), text("system-navigation.js"), text("browser-app.js"), text("data-actions.js"), text("terminal-app.js"), text("db-admin.js"), text("manifest.webmanifest"), text("service-worker.js"), text("life-os-icon.svg"), readFile(new URL("../public/locales/en.json", import.meta.url), "utf8"), readFile(new URL("../public/locales/zh-CN.json", import.meta.url), "utf8") ]); -const release = "1.20.0"; +const release = "1.21.0"; const localeEnJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales.en=${localeEn};`; const localeZhJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales['zh-CN']=${localeZh};`; const extraLocaleCodes = ['zh-HK', 'zh-MO', 'zh-TW', 'ar', 'fr', 'ru', 'es', 'ja']; diff --git a/scripts/validate.mjs b/scripts/validate.mjs index 08af939..cc545e1 100644 --- a/scripts/validate.mjs +++ b/scripts/validate.mjs @@ -18,6 +18,10 @@ assert.match(assets.addonsJs, /widgetLayout/); assert.match(assets.i18nRenderersJs, /lifeos_widget_layout_v1/); assert.match(assets.addonsJs, /lifeos_cloud_baseline_v3/); assert.match(assets.addonsJs, /api\/lifeos-sync/); +assert.match(assets.addonsJs, /lifeos_sync_outbox_v1/); +assert.match(assets.addonsJs, /function openSyncCenter/); +assert.match(assets.addonsJs, /resolveSavedConflict/); +assert.match(assets.serviceWorker, /SKIP_WAITING/); assert.match(assets.i18nRenderersJs, /dialog\.goals/); assert.match(assets.i18nRenderersJs, /shell\.wallpaperTitle/); assert.match(assets.i18nRenderersJs, /window\.museumApp/); @@ -275,7 +279,7 @@ assert.ok(command('date').message.length > 8); assert.ok(command('time').message.includes(':')); assert.ok(command('datetime').message.length > 12); assert.equal(command('uptime').message, 'terminal.uptime'); -assert.equal(command('version').message, 'Life OS v1.20.0'); +assert.equal(command('version').message, 'Life OS v1.21.0'); assert.equal(command('status').message, 'terminal.status'); assert.match(command('apps').message, /calendar/); assert.equal(command('echo "hello Life OS"').message, 'hello Life OS');