| 1 | // workspace.js — carpeta de trabajo, copia legible en disco e inventario. |
| 2 | // |
| 3 | // CORE compartido por Claw y Code. El módulo no sabe qué es una «app generada» |
| 4 | // ni una «conversación»: cada app le pasa un MANIFIESTO de almacenes y él sabe |
| 5 | // leerlos, medirlos, escribirlos a disco, reimportarlos y borrarlos. |
| 6 | // |
| 7 | // Por qué existe: todo vive en IndexedDB/localStorage, que el navegador puede |
| 8 | // desalojar (o el usuario borrar con «limpiar datos del sitio») sin avisar. Con |
| 9 | // una carpeta de trabajo, tu trabajo queda en ficheros normales que puedes ver, |
| 10 | // copiar y respaldar tú. |
| 11 | // |
| 12 | // Lo que NUNCA sale a disco en claro: el vault (secretos cifrados). Se marca |
| 13 | // `sensitive` en el manifiesto y se excluye salvo petición explícita. |
| 14 | |
| 15 | const HANDLE_KEY = 'workspace-handle'; |
| 16 | const ROOT = '.elffuss'; |
| 17 | |
| 18 | let cfg = null; // { app, ns, db, stores } |
| 19 | let dirHandle = null; // FileSystemDirectoryHandle de la carpeta de trabajo |
| 20 | let ready = false; // permiso concedido AHORA |
| 21 | let dirty = new Set(); |
| 22 | let listeners = []; |
| 23 | let lastSaveAt = null, lastError = null; |
| 24 | let autosaveCfg = { enabled: false, debounceMs: 3000 }; |
| 25 | let autosaveTimer = null; |
| 26 | |
| 27 | // `nombreOPFS`: cómo se llama, en el idioma de la interfaz, la carpeta del |
| 28 | // almacenamiento privado del navegador (no tiene nombre propio). Lo da la app. |
| 29 | let nombreOPFS = 'OPFS'; |
| 30 | export function init({ app, ns, db, stores, opfsName }) { |
| 31 | cfg = { app, ns, db, stores: stores || [] }; |
| 32 | if (opfsName) nombreOPFS = opfsName; |
| 33 | } |
| 34 | |
| 35 | export function supported() { |
| 36 | return { |
| 37 | pick: typeof window !== 'undefined' && typeof window.showDirectoryPicker === 'function', |
| 38 | persist: !!(navigator.storage && navigator.storage.persist), |
| 39 | }; |
| 40 | } |
| 41 | |
| 42 | const emit = () => { const s = statusSync(); listeners.forEach(f => { try { f(s); } catch { /* */ } }); }; |
| 43 | export function onChange(fn) { listeners.push(fn); return () => { listeners = listeners.filter(f => f !== fn); }; } |
| 44 | |
| 45 | // La raíz del almacenamiento privado del navegador (OPFS) no tiene nombre: '' |
| 46 | // se leía como «sin carpeta» y la carpeta elegida no se podía usar. |
| 47 | const nombreDe = h => h ? (h.name || nombreOPFS) : null; |
| 48 | |
| 49 | function statusSync() { |
| 50 | return { |
| 51 | supported: supported(), folder: nombreDe(dirHandle), ready, |
| 52 | dirty: [...dirty], lastSaveAt, lastError, autosave: autosaveCfg.enabled, |
| 53 | }; |
| 54 | } |
| 55 | export function status() { return statusSync(); } |
| 56 | |
| 57 | // ── carpeta de trabajo ─────────────────────────────────────────────────────── |
| 58 | async function perm(handle, mode = 'readwrite') { |
| 59 | if (!handle?.queryPermission) return true; // OPFS u otros: dados |
| 60 | if ((await handle.queryPermission({ mode })) === 'granted') return true; |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | // En el arranque: recupera el handle SIN pedir permiso ni abrir diálogos. |
| 65 | export async function restore() { |
| 66 | if (!cfg) throw new Error('workspace.init() primero'); |
| 67 | let h = null; |
| 68 | try { h = await cfg.db.get('kv', HANDLE_KEY); } catch { return null; } |
| 69 | if (!h) return null; |
| 70 | dirHandle = h; |
| 71 | ready = await perm(h); |
| 72 | emit(); |
| 73 | return { name: nombreDe(h), ready, reason: ready ? null : 'prompt' }; |
| 74 | } |
| 75 | |
| 76 | // Elegir carpeta (requiere gesto de usuario). |
| 77 | export async function pick() { |
| 78 | if (!supported().pick) throw new Error('Este navegador no permite elegir una carpeta. Usa «Descargar copia» para guardar tu trabajo.'); |
| 79 | const h = await window.showDirectoryPicker({ mode: 'readwrite', id: 'elffuss-workspace', startIn: 'documents' }); |
| 80 | dirHandle = h; |
| 81 | ready = true; |
| 82 | await cfg.db.set('kv', HANDLE_KEY, h); |
| 83 | emit(); |
| 84 | return { name: nombreDe(h), ready: true }; |
| 85 | } |
| 86 | |
| 87 | // Reutilizar un handle que la app ya tiene (Code: la carpeta del proyecto). |
| 88 | export async function adopt(handle) { |
| 89 | if (!handle) throw new Error('sin handle'); |
| 90 | dirHandle = handle; |
| 91 | ready = await perm(handle); |
| 92 | await cfg.db.set('kv', HANDLE_KEY, handle); |
| 93 | emit(); |
| 94 | return { name: nombreDe(handle), ready }; |
| 95 | } |
| 96 | |
| 97 | // Re-conceder permiso tras recargar (requiere gesto de usuario). |
| 98 | export async function regrant() { |
| 99 | if (!dirHandle) throw new Error('no hay carpeta elegida'); |
| 100 | const ok = dirHandle.requestPermission |
| 101 | ? (await dirHandle.requestPermission({ mode: 'readwrite' })) === 'granted' |
| 102 | : true; |
| 103 | ready = ok; |
| 104 | emit(); |
| 105 | if (!ok) throw new Error('permiso denegado'); |
| 106 | return { name: nombreDe(dirHandle), ready: true }; |
| 107 | } |
| 108 | |
| 109 | export async function forget() { |
| 110 | const name = dirHandle?.name || null; |
| 111 | dirHandle = null; ready = false; |
| 112 | try { await cfg.db.del('kv', HANDLE_KEY); } catch { /* */ } |
| 113 | emit(); |
| 114 | return { forgot: name, deleted: false }; // nunca borra los ficheros del disco |
| 115 | } |
| 116 | |
| 117 | export async function ensurePersistence() { |
| 118 | if (!navigator.storage?.persist) return { persisted: false, asked: false }; |
| 119 | const already = navigator.storage.persisted ? await navigator.storage.persisted() : false; |
| 120 | if (already) return { persisted: true, asked: false }; |
| 121 | const got = await navigator.storage.persist().catch(() => false); |
| 122 | return { persisted: got, asked: true }; |
| 123 | } |
| 124 | |
| 125 | // ── inventario: «ver qué hay» ──────────────────────────────────────────────── |
| 126 | const sizeOf = v => { try { return new Blob([typeof v === 'string' ? v : JSON.stringify(v)]).size; } catch { return 0; } }; |
| 127 | |
| 128 | async function readStore(st) { |
| 129 | if (st.kind === 'ls') { |
| 130 | const items = []; |
| 131 | for (const k of st.keys || []) { |
| 132 | const v = localStorage.getItem(k); |
| 133 | if (v != null) items.push({ key: k, value: v }); |
| 134 | } |
| 135 | return items; |
| 136 | } |
| 137 | if (st.kind === 'idb-store') { // store entero (apps, tasks…) |
| 138 | const [ks, vs] = await Promise.all([cfg.db.keys(st.store), cfg.db.all(st.store)]); |
| 139 | return ks.map((k, i) => ({ key: String(k), value: vs[i] })); |
| 140 | } |
| 141 | // 'idb-key': una clave concreta dentro de kv (history, conversations, skills…) |
| 142 | const v = await cfg.db.get(st.store || 'kv', st.key); |
| 143 | if (v == null) return []; |
| 144 | return Array.isArray(v) ? v.map((x, i) => ({ key: String(x.id ?? x.name ?? i), value: x })) : [{ key: st.key, value: v }]; |
| 145 | } |
| 146 | |
| 147 | export async function inventory() { |
| 148 | const out = []; |
| 149 | for (const st of cfg.stores) { |
| 150 | let items = []; |
| 151 | let err = null; |
| 152 | try { items = await readStore(st); } catch (e) { err = e.message; } |
| 153 | out.push({ |
| 154 | id: st.id, label: st.label, icon: st.icon || '•', sensitive: !!st.sensitive, |
| 155 | count: items.length, bytes: items.reduce((a, b) => a + sizeOf(b.value), 0), |
| 156 | note: st.note || '', error: err, |
| 157 | }); |
| 158 | } |
| 159 | return out; |
| 160 | } |
| 161 | |
| 162 | export async function peek(id, { limit = 50 } = {}) { |
| 163 | const st = cfg.stores.find(s => s.id === id); |
| 164 | if (!st) throw new Error('almacén desconocido: ' + id); |
| 165 | const items = await readStore(st); |
| 166 | return { |
| 167 | id, truncated: items.length > limit, |
| 168 | items: items.slice(0, limit).map(it => ({ |
| 169 | key: it.key, bytes: sizeOf(it.value), |
| 170 | preview: st.sensitive ? '(cifrado — no se muestra)' |
| 171 | : (typeof it.value === 'string' ? it.value : JSON.stringify(it.value)).slice(0, 240), |
| 172 | })), |
| 173 | }; |
| 174 | } |
| 175 | |
| 176 | // Espacio real del origen, incluidas TODAS las caches (los modelos son GB). |
| 177 | export async function storageReport() { |
| 178 | const est = navigator.storage?.estimate ? await navigator.storage.estimate().catch(() => ({})) : {}; |
| 179 | const persisted = navigator.storage?.persisted ? await navigator.storage.persisted().catch(() => false) : false; |
| 180 | const out = { usage: est.usage || 0, quota: est.quota || 0, persisted, caches: [] }; |
| 181 | if (typeof caches !== 'undefined') { |
| 182 | for (const name of await caches.keys().catch(() => [])) { |
| 183 | const c = await caches.open(name); |
| 184 | const reqs = await c.keys(); |
| 185 | let bytes = 0; |
| 186 | for (const r of reqs) { |
| 187 | const res = await c.match(r); |
| 188 | const len = +(res?.headers.get('content-length') || 0); |
| 189 | bytes += len; |
| 190 | } |
| 191 | out.caches.push({ name, entries: reqs.length, bytes }); |
| 192 | } |
| 193 | } |
| 194 | return out; |
| 195 | } |
| 196 | |
| 197 | // ── guardar en disco ───────────────────────────────────────────────────────── |
| 198 | export function touch(id) { |
| 199 | dirty.add(id); |
| 200 | emit(); |
| 201 | if (autosaveCfg.enabled) { |
| 202 | clearTimeout(autosaveTimer); |
| 203 | autosaveTimer = setTimeout(() => { save({ reason: 'auto' }).catch(() => {}); }, autosaveCfg.debounceMs); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | export function autosave({ enabled, debounceMs }) { |
| 208 | autosaveCfg = { enabled: !!enabled, debounceMs: debounceMs || autosaveCfg.debounceMs }; |
| 209 | try { localStorage.setItem(cfg.ns + '.workspace.autosave', enabled ? '1' : '0'); } catch { /* */ } |
| 210 | emit(); |
| 211 | return autosaveCfg; |
| 212 | } |
| 213 | export function autosaveEnabled() { |
| 214 | try { return localStorage.getItem(cfg.ns + '.workspace.autosave') === '1'; } catch { return false; } |
| 215 | } |
| 216 | |
| 217 | async function dirFor(path) { // crea .elffuss/<app>/<sub> y devuelve el handle |
| 218 | let d = dirHandle; |
| 219 | for (const part of path.split('/').filter(Boolean)) d = await d.getDirectoryHandle(part, { create: true }); |
| 220 | return d; |
| 221 | } |
| 222 | async function writeFile(dir, name, text) { |
| 223 | const fh = await dir.getFileHandle(name, { create: true }); |
| 224 | const w = await fh.createWritable(); |
| 225 | await w.write(text); |
| 226 | await w.close(); |
| 227 | } |
| 228 | const safeName = s => String(s).replace(/[^\w.\-]+/g, '_').slice(0, 60) || 'item'; |
| 229 | |
| 230 | export async function save({ only = null, reason = 'manual' } = {}) { |
| 231 | if (!dirHandle) throw new Error('no-folder'); |
| 232 | if (!(await perm(dirHandle))) { ready = false; emit(); throw new Error('needs-regrant'); } |
| 233 | const targets = cfg.stores.filter(st => !st.sensitive && (only ? only.includes(st.id) : true)); |
| 234 | const wrote = [], errors = []; |
| 235 | for (const st of targets) { |
| 236 | try { |
| 237 | const items = await readStore(st); |
| 238 | const base = `${ROOT}/${cfg.app}/${st.id}`; |
| 239 | if (st.files) { // uno por fichero (apps .html, skills .md) |
| 240 | const d = await dirFor(base); |
| 241 | for (const it of items) { |
| 242 | const body = st.files.body ? st.files.body(it.value) : JSON.stringify(it.value, null, 1); |
| 243 | await writeFile(d, safeName(st.files.name ? st.files.name(it.value, it.key) : it.key) + (st.files.ext || '.json'), body); |
| 244 | } |
| 245 | } else { // uno solo (historial, ajustes) |
| 246 | const d = await dirFor(`${ROOT}/${cfg.app}`); |
| 247 | await writeFile(d, st.id + '.json', JSON.stringify(items.map(i => i.value), null, 1)); |
| 248 | } |
| 249 | wrote.push({ id: st.id, files: items.length }); |
| 250 | dirty.delete(st.id); |
| 251 | } catch (e) { errors.push({ id: st.id, error: e.message }); } |
| 252 | } |
| 253 | lastSaveAt = Date.now(); |
| 254 | lastError = errors.length ? errors[0].error : null; |
| 255 | // índice legible con lo que hay |
| 256 | try { |
| 257 | const d = await dirFor(`${ROOT}/${cfg.app}`); |
| 258 | await writeFile(d, 'index.json', JSON.stringify({ app: cfg.app, at: lastSaveAt, reason, wrote }, null, 1)); |
| 259 | } catch { /* */ } |
| 260 | emit(); |
| 261 | return { ok: !errors.length, at: lastSaveAt, wrote, errors }; |
| 262 | } |
| 263 | |
| 264 | // ── copia descargable (Safari/Firefox o backup manual) ─────────────────────── |
| 265 | export async function bundle({ only = null, includeSensitive = false } = {}) { |
| 266 | const data = { app: cfg.app, at: Date.now(), stores: {} }; |
| 267 | for (const st of cfg.stores) { |
| 268 | if (st.sensitive && !includeSensitive) continue; |
| 269 | if (only && !only.includes(st.id)) continue; |
| 270 | try { data.stores[st.id] = (await readStore(st)).map(i => i.value); } catch { /* */ } |
| 271 | } |
| 272 | return new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); |
| 273 | } |
| 274 | |
| 275 | // ── borrar ─────────────────────────────────────────────────────────────────── |
| 276 | export async function wipe({ only = null, confirm } = {}) { |
| 277 | if (confirm !== 'BORRAR') throw new Error('confirmación requerida'); |
| 278 | const removed = []; |
| 279 | for (const st of cfg.stores) { |
| 280 | if (only && !only.includes(st.id)) continue; |
| 281 | try { |
| 282 | if (st.kind === 'ls') { for (const k of st.keys || []) localStorage.removeItem(k); removed.push({ id: st.id }); } |
| 283 | else if (st.kind === 'idb-store') { for (const k of await cfg.db.keys(st.store)) await cfg.db.del(st.store, k); removed.push({ id: st.id }); } |
| 284 | else { await cfg.db.del(st.store || 'kv', st.key); removed.push({ id: st.id }); } |
| 285 | } catch (e) { removed.push({ id: st.id, error: e.message }); } |
| 286 | } |
| 287 | emit(); |
| 288 | return { removed }; |
| 289 | } |
| 290 | |
| 291 | export async function clearCaches({ names } = {}) { |
| 292 | if (typeof caches === 'undefined') return { deleted: [] }; |
| 293 | const target = names || await caches.keys(); |
| 294 | const deleted = []; |
| 295 | for (const n of target) if (await caches.delete(n)) deleted.push(n); |
| 296 | return { deleted }; |
| 297 | } |