import { cleanText } from "../core.ts"; import { gen } from "./brain.ts"; import { DEBUG } from "./config.ts"; import { changed, petEngine } from "./engine.ts"; import { brain, emit, store, ui } from "./store.ts"; import { canRunLocally } from "./hosting.ts"; // Pages are written by the pet, never on request: today's at bedtime, and // missed days one at a time, oldest first, when the brain is free and the // owner has left it alone for 30 s. The engine chooses when (see pump()); a // page with unsafe text is dropped and its day stays pending. export async function writeDiary(date?: string, rewrite = false) { if (!canRunLocally() || brain.state !== "ready" || brain.busy || !store.state.pet) return false; const execution = store.executionRevision; const e = petEngine(); const turn = e.diaryTurn(date || store.state.today.date, Date.now(), DEBUG && rewrite); if (!turn) return false; brain.busy = true; ui.diaryWriting = true; ui.diaryDraft = "dear diary,"; emit(); try { const r = await gen(turn.request(), (t) => { ui.diaryDraft = cleanText("dear diary," + t); emit(); }); if (execution !== store.executionRevision || !canRunLocally() || !store.tabOwned) return false; if (!e.commitDiary(turn, r.text)) console.warn("diary page filtered; the day stays pending"); changed(); } catch (err) { console.warn(err); } finally { turn.free(); if (execution === store.executionRevision) brain.busy = false; ui.diaryWriting = false; emit(); } return true; }