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