utopia-ia/elffuss-claw public
Changesets · Branches · Tags · Compare
| Changeset | c7179c489e0d974ff61beb277b32e73bbffdaffb77a4b7aaa6f9efc5f273bac2 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 18:04 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 18:04 +02:00 |
| Parents | 4a5cecddc855 |
2 files changed
modified tests/mind_claw.mjs +3 −1
| @@ -203,7 +203,9 @@ | ||
| 203 | 203 | ok('el ciclo pausado no forja ninguna propuesta', trasPausa.built === 0 && trasPausa.paused === 1 |
| 204 | 204 | && await p.evaluate(() => document.querySelectorAll('.mind-node-label').length) === nodosAntes, |
| 205 | 205 | `built=${trasPausa.built} paused=${trasPausa.paused}`); |
| 206 | -ok('la Mente cuenta que dejó el ciclo', /dejo lo mío|cortado el ciclo/.test(trasPausa.log), trasPausa.log.slice(-160)); | |
| 206 | +// Una pausa a propósito tiene su propio texto («En pausa: corto el ciclo…»); | |
| 207 | +// «Vuelves tú — dejo lo mío…» es para cuando el usuario vuelve a usar la app. | |
| 208 | +ok('la Mente cuenta que cortó el ciclo porque se pausó', /En pausa: corto el ciclo/.test(trasPausa.log), trasPausa.log.slice(-160)); | |
| 207 | 209 | |
| 208 | 210 | await p.screenshot({ path: OUT + '/mind_claw.png' }); |
| 209 | 211 | console.log('captura → mind_claw.png'); |
modified web/js/ceo.js +58 −16
| @@ -68,11 +68,24 @@ | ||
| 68 | 68 | // Una parada por ciclo: pausar o volver a usar la app la aborta, y la señal |
| 69 | 69 | // llega hasta el proveedor (corta la generación) y hasta las herramientas. |
| 70 | 70 | let cycleAborter = null; |
| 71 | +// Cada pausa o actividad del usuario cambia la «época». tick() y forceCycle() | |
| 72 | +// esperan a isReady() antes de arrancar, y en Claw esa espera es asíncrona | |
| 73 | +// (consulta IndexedDB): si la época cambió mientras esperaban, el usuario pausó | |
| 74 | +// o volvió y el ciclo NO arranca. Antes solo se miraba `running`, que en ese | |
| 75 | +// hueco aún es false, así que interrupt() no hacía nada y el ciclo arrancaba | |
| 76 | +// igual y escribía su propuesta justo después de pausar. | |
| 77 | +let epoca = 0; | |
| 78 | +// Quién cortó: 'actividad' (el usuario volvió) o 'pausa' (lo pausó a propósito | |
| 79 | +// desde la Mente). Cuenta el primero que corta el ciclo; con eso se elige qué | |
| 80 | +// se le dice (antes las dos decían «Vuelves tú…»). | |
| 81 | +let motivoCorte = 'actividad'; | |
| 71 | 82 | // Interrumpir el ciclo en curso. `running` NO se pone a false aquí: lo hace el |
| 72 | 83 | // propio ciclo al terminar de verdad. Mientras tanto vale 'interrupt' y |
| 73 | 84 | // forceCycle()/tick() no arrancan un segundo ciclo encima del que aún se está |
| 74 | 85 | // desmontando — dos ciclos a la vez son dos generate() contra el mismo modelo. |
| 75 | -function interrupt() { | |
| 86 | +function interrupt(motivo = 'actividad') { | |
| 87 | + epoca++; | |
| 88 | + if (running !== 'interrupt') motivoCorte = motivo; | |
| 76 | 89 | if (!running) return; |
| 77 | 90 | running = 'interrupt'; |
| 78 | 91 | try { cycleAborter?.abort(); } catch { /* */ } |
| @@ -140,7 +153,7 @@ | ||
| 140 | 153 | initCrossTab(); |
| 141 | 154 | } |
| 142 | 155 | export function isThisTabLeader() { return isLeader; } |
| 143 | -export function noteActivity() { lastActivity = Date.now(); interrupt(); } | |
| 156 | +export function noteActivity() { lastActivity = Date.now(); interrupt('actividad'); } | |
| 144 | 157 | export function isEnabled() { return enabled; } |
| 145 | 158 | export function isRunning() { return !!running; } |
| 146 | 159 | // Play/stop: persistido AQUÍ (fuente única) — cualquier botón que lo toque |
| @@ -173,37 +186,52 @@ | ||
| 173 | 186 | export function disable() { |
| 174 | 187 | // Antes ponía running = false sin más: el ciclo seguía generando por detrás, |
| 175 | 188 | // escribía su propuesta igual, y «Pensar ahora» podía lanzar otro a la vez. |
| 176 | - enabled = false; interrupt(); if (timer) clearTimeout(timer); | |
| 189 | + enabled = false; interrupt('pausa'); if (timer) clearTimeout(timer); | |
| 177 | 190 | try { localStorage.setItem(CLAVE_DECISION(), 'off'); } catch { /* */ } |
| 178 | 191 | emit('sys', { type: 'status', text: 'CEO en pausa' }); |
| 179 | 192 | } |
| 180 | 193 | |
| 181 | 194 | function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(tick, TICK_MS); } |
| 182 | 195 | |
| 196 | +// ¿Puede pensar AHORA? Para que la UI lo diga antes de prometer un ciclo: | |
| 197 | +// devuelve '' si sí, o el motivo ('leader' | 'running' | 'workspace' | | |
| 198 | +// 'provider'). Sin modelo de verdad (el anfitrión devuelve null en modo | |
| 199 | +// básico) no hay ciclo: con el motor de reglas solo salían propuestas basura | |
| 200 | +// escritas dentro del proyecto. | |
| 201 | +export async function whyNotThink() { | |
| 202 | + if (!isLeader) return 'leader'; | |
| 203 | + if (running) return 'running'; | |
| 204 | + if (!(await ws?.isReady())) return 'workspace'; | |
| 205 | + if (!getProvider()) return 'provider'; | |
| 206 | + return ''; | |
| 207 | +} | |
| 208 | + | |
| 183 | 209 | // «Pensar ahora» — salta la espera de ociosidad. Sigue respetando el |
| 184 | 210 | // semáforo: si otra pestaña es la líder, no compite por la GPU. |
| 185 | 211 | export async function forceCycle() { |
| 186 | 212 | if (!isLeader) { emit('ceo', { type: 'paused', text: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.' }); return false; } |
| 187 | 213 | if (running) return false; |
| 214 | + const e = epoca; | |
| 188 | 215 | // isReady() puede ser síncrona (Code: handle en memoria) o async (Claw: consulta IndexedDB) — se espera siempre. |
| 189 | 216 | if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: 'Necesito un espacio de trabajo abierto y un modelo cargado.' }); return false; } |
| 190 | 217 | if (running) return false; // otro ciclo arrancó mientras se esperaba a isReady() |
| 218 | + if (e !== epoca) { emit('ceo', { type: 'paused', text: textoCorte() }); return false; } | |
| 191 | 219 | try { await runCycle(); } finally { lastCycleEnd = Date.now(); } |
| 192 | 220 | return true; |
| 193 | 221 | } |
| 194 | 222 | |
| 195 | 223 | async function tick() { |
| 196 | 224 | if (!enabled) return; |
| 197 | - // ¿Toca ciclo? Se mira ANTES y DESPUÉS de esperar a isReady(). Esa espera | |
| 198 | - // puede ser asíncrona (Claw consulta IndexedDB) y mientras dura puede llegar | |
| 199 | - // una pausa o actividad del usuario; como aún no hay ciclo en marcha, | |
| 200 | - // interrupt() no tiene nada que parar. Mirando después solo `running`, un | |
| 201 | - // ciclo entero arrancaba —y escribía su propuesta— justo después de pausar. | |
| 202 | - const toca = () => enabled && isLeader && !running && !isBusy() | |
| 203 | - && Date.now() - lastActivity >= IDLE_MS && Date.now() - lastCycleEnd > COOLDOWN_MS && !!getProvider(); | |
| 204 | - if (toca() && await ws?.isReady() && toca()) { | |
| 205 | - try { await runCycle(); } catch { /* siguiente ciclo */ } | |
| 206 | - lastCycleEnd = Date.now(); | |
| 225 | + const idle = Date.now() - lastActivity; | |
| 226 | + const rested = Date.now() - lastCycleEnd > COOLDOWN_MS; | |
| 227 | + const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider(); | |
| 228 | + if (mightRun) { | |
| 229 | + const e = epoca; | |
| 230 | + // Tras la espera se vuelve a mirar todo lo que pudo cambiar en ella. | |
| 231 | + if (await ws?.isReady() && e === epoca && enabled && !running && !isBusy()) { | |
| 232 | + try { await runCycle(); } catch { /* siguiente ciclo */ } | |
| 233 | + lastCycleEnd = Date.now(); | |
| 234 | + } | |
| 207 | 235 | } |
| 208 | 236 | schedule(); |
| 209 | 237 | } |
| @@ -219,6 +247,12 @@ | ||
| 219 | 247 | if (!prov) return ''; |
| 220 | 248 | if (signal?.aborted) throw new Error('interrumpido'); |
| 221 | 249 | const a = new Agent({ chat: (h, s, cb, sig) => prov.chat(h, s, cb, sig) }); |
| 250 | + // Un agente sin stop() no se entera de la señal (el de Claw antes de su | |
| 251 | + // stop-fix: handle(texto, onEvent)). Con él la única forma de cortarlo es | |
| 252 | + // lanzar desde su callback, como hacía antes el core; si no, cada perfil | |
| 253 | + // seguía llamando al modelo y ejecutando herramientas hasta el final aunque | |
| 254 | + // el usuario hubiera vuelto. Con stop() se ignora sin lanzar (ver abajo). | |
| 255 | + const sinParada = typeof a.stop !== 'function'; | |
| 222 | 256 | const stop = () => { try { a.stop?.(); } catch { /* */ } }; |
| 223 | 257 | signal?.addEventListener('abort', stop, { once: true }); |
| 224 | 258 | let out = ''; |
| @@ -227,7 +261,10 @@ | ||
| 227 | 261 | // Parado: se ignora lo que llegue, sin lanzar. Lanzar desde aquí metía una |
| 228 | 262 | // excepción en mitad del agente (y de su proveedor), y un agente que no |
| 229 | 263 | // distingue la parada la reportaba a telemetría como fallo del modelo. |
| 230 | - if (running === 'interrupt' || signal?.aborted) return; | |
| 264 | + if (running === 'interrupt' || signal?.aborted) { | |
| 265 | + if (sinParada) throw new Error('interrumpido'); | |
| 266 | + return; | |
| 267 | + } | |
| 231 | 268 | if (ev.type === 'token') { out += ev.text; emit(channel, { type: 'token', text: ev.text }); } |
| 232 | 269 | else if (ev.type === 'tool') emit(channel, { type: 'tool', text: humanizeTool(ev.call.tool, ev.call.args), tool: ev.call.tool, path: ev.call.args?.path || null }); |
| 233 | 270 | else if (ev.type === 'tool_result') emit(channel, { type: 'tool_result', tool: ev.tool, text: String(ev.result || '').replace(/\s+/g, ' ').trim().slice(0, 100) }); |
| @@ -238,6 +275,11 @@ | ||
| 238 | 275 | return out; |
| 239 | 276 | } |
| 240 | 277 | |
| 278 | +// Lo que se dice al cortar un ciclo, según quién lo cortó (ver motivoCorte). | |
| 279 | +const textoCorte = () => motivoCorte === 'pausa' | |
| 280 | + ? 'En pausa: corto el ciclo y no guardo nada.' | |
| 281 | + : 'Vuelves tú — dejo lo mío y te cedo el mando.'; | |
| 282 | + | |
| 241 | 283 | async function runCycle() { |
| 242 | 284 | running = true; |
| 243 | 285 | const aborter = (cycleAborter = new AbortController()); |
| @@ -267,7 +309,7 @@ | ||
| 267 | 309 | catch { emit(d.id, { type: 'done', text: '(interrumpido)' }); return null; } |
| 268 | 310 | })); |
| 269 | 311 | // Interrumpido: NO se escribe nada. Ni propuesta a medias ni fichero vacío. |
| 270 | - if (running === 'interrupt' || signal.aborted) { emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; } | |
| 312 | + if (running === 'interrupt' || signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; } | |
| 271 | 313 | |
| 272 | 314 | const valid = proposals.filter(Boolean).filter(p => p.text && p.text.length > 8); |
| 273 | 315 | const md = `# Propuestas de mejora — ciclo ${cycleN}\n\n**Misión:** ${getMission()}\n\n` + |
| @@ -279,7 +321,7 @@ | ||
| 279 | 321 | const path = `${getSoulDir()}/${stamp}-${topic}.md`; |
| 280 | 322 | try { |
| 281 | 323 | await rotateSoul(); |
| 282 | - if (signal.aborted) { emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; } | |
| 324 | + if (signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; } | |
| 283 | 325 | await ws.write({ path, content: md }); |
| 284 | 326 | emit('ceo', { type: 'built', text: `Propuesta guardada en ${path}`, path, md, proposals: valid }); |
| 285 | 327 | } catch (e) { |