| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552 |
- /*
- The AGI playground page. The engine (the real Otto interpreter and the AGI
- libraries, compiled to WebAssembly from scripts/agidocgen/playground) runs
- in playground/worker.js; this file keeps the workspace (files, request,
- user, mock answers, stored state) in IndexedDB, edits it and shows what a
- run returns.
- */
- (function () {
- "use strict";
- const pg = document.getElementById("pg");
- if (!pg) return;
- const ROOT = document.body.getAttribute("data-root") || "";
- const VER = document.body.getAttribute("data-ver") || "";
- const BASE = ROOT + "playground/";
- const $ = (sel, el) => (el || pg).querySelector(sel);
- const $$ = (sel, el) => Array.prototype.slice.call((el || pg).querySelectorAll(sel));
- const enc = new TextEncoder();
- const dec = new TextDecoder("utf-8");
- const ROOTS = [
- { id: "web", path: "web:/", label: "web", note: "WebApp folder" },
- { id: "user", path: "user:/", label: "user:/", note: "" },
- { id: "tmp", path: "tmp:/", label: "tmp:/", note: "" }
- ];
- const TEXT_EXT = /\.(agi|js|json|txt|md|csv|tsv|html?|css|xml|svg|log|ini|ya?ml|conf|sql)$/i;
- // Otto reports "Line 4:5" for syntax errors and "<anonymous>:4:5" in stacks.
- const ERR_LINE = /(?:Line |<anonymous>:)(\d+):(\d+)/;
- const IMG_EXT = /\.(png|jpe?g|gif|webp|svg|bmp|ico)$/i;
- // ---------- small helpers ----------
- function icon(name) {
- const src = document.querySelector('#pg-icons [data-i="' + name + '"]');
- return src ? src.innerHTML : "";
- }
- function el(tag, attrs, children) {
- const e = document.createElement(tag);
- if (attrs) for (const k in attrs) {
- if (k === "class") e.className = attrs[k];
- else if (k === "html") e.innerHTML = attrs[k];
- else if (k === "text") e.textContent = attrs[k];
- else if (k.startsWith("on")) e.addEventListener(k.slice(2), attrs[k]);
- else if (attrs[k] !== undefined && attrs[k] !== null && attrs[k] !== false) e.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
- }
- (children || []).forEach((c) => { if (c != null) e.append(c); });
- return e;
- }
- function toast(msg) {
- if (window.AGIDocs && AGIDocs.toast) AGIDocs.toast(msg);
- }
- function esc(s) { return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }
- function clone(o) { return JSON.parse(JSON.stringify(o)); }
- function parentOf(p) {
- const i = p.indexOf(":/");
- const rel = p.slice(i + 2);
- if (!rel) return null;
- const j = rel.lastIndexOf("/");
- return j < 0 ? p.slice(0, i + 2) : p.slice(0, i + 2) + rel.slice(0, j);
- }
- function baseName(p) {
- if (p.endsWith(":/")) return p;
- return p.slice(p.lastIndexOf("/") + 1);
- }
- function join(dir, name) { return dir.endsWith("/") ? dir + name : dir + "/" + name; }
- function fmtSize(n) {
- if (n < 1024) return n + " B";
- if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0) + " KB";
- return (n / 1048576).toFixed(1) + " MB";
- }
- function getPath(obj, path) {
- return path.split(".").reduce((o, k) => (o == null ? undefined : o[k]), obj);
- }
- function setPath(obj, path, v) {
- const ks = path.split(".");
- let o = obj;
- for (let i = 0; i < ks.length - 1; i++) { if (o[ks[i]] == null) o[ks[i]] = {}; o = o[ks[i]]; }
- o[ks[ks.length - 1]] = v;
- }
- function b64urlDecode(s) {
- s = s.replace(/-/g, "+").replace(/_/g, "/");
- while (s.length % 4) s += "=";
- const bin = atob(s);
- const bytes = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
- return dec.decode(bytes);
- }
- function toB64(bytes) {
- let s = "";
- for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
- return btoa(s);
- }
- function fromB64(s) {
- const bin = atob(s);
- const out = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
- return out;
- }
- function isText(path, data) {
- if (TEXT_EXT.test(path)) return true;
- if (IMG_EXT.test(path)) return false;
- if (!data) return true;
- const n = Math.min(data.length, 2048);
- for (let i = 0; i < n; i++) if (data[i] === 0) return false;
- return true;
- }
- function langOf(path) {
- if (/\.(agi|js)$/i.test(path)) return "js";
- if (/\.json$/i.test(path)) return "json";
- if (/\.(html?|xml|svg)$/i.test(path)) return "html";
- return "text";
- }
- function debounce(fn, ms) {
- let t;
- return function () { clearTimeout(t); t = setTimeout(fn, ms); };
- }
- // ---------- in-page dialogs ----------
- const dlg = $("#pg-dialog");
- function dialog(message, opts) {
- opts = opts || {};
- return new Promise((resolve) => {
- $(".pg-dialog-msg", dlg).textContent = message;
- const input = $(".pg-dialog-input", dlg);
- input.hidden = opts.input === undefined;
- input.value = opts.input || "";
- const ok = $("[data-ok]", dlg);
- ok.textContent = opts.ok || "OK";
- $("[data-cancel]", dlg).hidden = !!opts.alert;
- dlg.hidden = false;
- (input.hidden ? ok : input).focus();
- if (!input.hidden) input.select();
- function done(v) {
- dlg.hidden = true;
- dlg.removeEventListener("keydown", onKey);
- $("form", dlg).onsubmit = null;
- $("[data-cancel]", dlg).onclick = null;
- resolve(v);
- }
- function onKey(e) { if (e.key === "Escape") done(null); }
- dlg.addEventListener("keydown", onKey);
- $("form", dlg).onsubmit = (e) => { e.preventDefault(); done(input.hidden ? true : input.value.trim()); };
- $("[data-cancel]", dlg).onclick = () => done(null);
- });
- }
- // ---------- storage ----------
- let idbP = null;
- function idb() {
- if (!idbP) idbP = new Promise((resolve, reject) => {
- const r = indexedDB.open("aroz-agi-playground", 1);
- r.onupgradeneeded = () => r.result.createObjectStore("kv");
- r.onsuccess = () => resolve(r.result);
- r.onerror = () => reject(r.error);
- });
- return idbP;
- }
- function kv(mode, key, value) {
- return idb().then((db) => new Promise((resolve, reject) => {
- const tx = db.transaction("kv", mode === "get" ? "readonly" : "readwrite");
- const st = tx.objectStore("kv");
- const r = mode === "get" ? st.get(key) : mode === "del" ? st.delete(key) : st.put(value, key);
- r.onsuccess = () => resolve(r.result);
- r.onerror = () => reject(r.error);
- }));
- }
- // ---------- workspace ----------
- function defaultMocks() {
- return {
- http: {
- fallback: "error",
- rules: [
- { on: true, method: "GET", url: "https://api.example.com/users/*", status: 200, headersText: "Content-Type: application/json", body: '{"id": 7, "name": "Amy", "role": "editor"}', base64: false, error: "", delayMs: 0 },
- { on: true, method: "POST", url: "https://api.example.com/echo", status: 201, headersText: "", body: '{"received": {{body}}}', base64: false, error: "", delayMs: 0 }
- ]
- },
- llm: { mode: "fixed", reply: "", reasoning: "", rules: [{ match: "capital of France", reply: "The capital of France is Paris." }], error: "", model: "gpt-4o-mini", modelsText: "gpt-4o-mini, gpt-4o", chunkSize: 12, chunkDelayMs: 30 },
- cnn: { responses: {}, error: "" },
- sqlite: [{ fn: "query", match: "FROM notes", result: '[{"id": 1, "title": "First note"}, {"id": 2, "title": "Second note"}]' }],
- sysinfo: { cpu: "", ram: "", network: "", disks: "" },
- generic: {},
- ws: { refuse: false, script: [{ afterMs: 300, text: "hello" }, { afterMs: 500, text: "ping" }], closeAfterMs: 1500 },
- schedulerDenied: false
- };
- }
- function defaultSettings() {
- return {
- open: ["web:/Playground/main.agi"],
- active: "web:/Playground/main.agi",
- selected: "web:/Playground",
- expanded: { "web:/": true, "web:/Playground": true, "user:/": true, "user:/Documents": true, "tmp:/": true },
- request: { method: "POST", bodyType: "form", form: [["name", "World"]], query: [], body: '{"name": "World"}', timeoutSec: 30 },
- user: { username: "developer", admin: true, quotaMB: "" },
- mocks: defaultMocks(),
- state: {},
- layout: { outW: null, wins: {} },
- outTab: "response"
- };
- }
- const MAIN_AGI = [
- "/*",
- " Welcome to the AGI playground.",
- " This file is web/Playground/main.agi: a WebApp backend script.",
- " Press Run (Ctrl+Enter). Load more from Samples.",
- "*/",
- 'requirelib("filelib");',
- "",
- "// POST fields are global variables (set them in the Request window).",
- 'var who = (typeof name !== "undefined") ? name : "stranger";',
- "",
- 'var files = filelib.glob("user:/Documents/*");',
- 'console.log("Found " + files.length + " files for " + USERNAME);',
- "",
- "sendJSONResp({",
- ' greeting: "Hello, " + who + "!",',
- " user: USERNAME,",
- " documents: files",
- "});",
- ""
- ].join("\n");
- function picture(type, w, h, label) {
- return new Promise((resolve) => {
- const c = document.createElement("canvas");
- c.width = w; c.height = h;
- const x = c.getContext("2d");
- const g = x.createLinearGradient(0, 0, w, h);
- g.addColorStop(0, "#0071e3"); g.addColorStop(0.55, "#8e5cff"); g.addColorStop(1, "#e8508f");
- x.fillStyle = g; x.fillRect(0, 0, w, h);
- x.fillStyle = "rgba(255,255,255,0.9)";
- x.font = "600 " + Math.round(h / 5) + "px -apple-system, Segoe UI, sans-serif";
- x.textAlign = "center"; x.textBaseline = "middle";
- x.fillText(label || "AGI", w / 2, h / 2);
- c.toBlob((b) => b.arrayBuffer().then((ab) => resolve(new Uint8Array(ab))), type, 0.9);
- });
- }
- async function defaultFiles() {
- const now = Date.now();
- const t = (s) => ({ data: enc.encode(s), mtime: now });
- const files = {
- "web:/Playground": { dir: true, mtime: now },
- "web:/Playground/main.agi": t(MAIN_AGI),
- "web:/Playground/lib": { dir: true, mtime: now },
- "web:/Playground/lib/format.js": t('// Shared helpers, loaded with includes("lib/format.js").\nfunction formatBytes(n){\n var units = ["B", "KB", "MB", "GB"];\n var i = 0;\n while (n >= 1024 && i < units.length - 1){ n = n / 1024; i++; }\n return (Math.round(n * 10) / 10) + " " + units[i];\n}\n'),
- "user:/Desktop": { dir: true, mtime: now },
- "user:/Desktop/hello.txt": t("Hello from the playground drive.\n"),
- "user:/Documents": { dir: true, mtime: now },
- "user:/Documents/notes.md": t("# Notes\n\n- Files on user:/ are what filelib sees.\n- Scripts change them only when you press Run.\n"),
- "user:/Documents/data.json": t('{\n "project": "ArozOS",\n "tags": ["nas", "desktop", "agi"],\n "stars": 1200\n}\n'),
- "user:/Documents/scores.csv": t("name,score\nAmy,92\nBen,85\nChloe,78\n"),
- "user:/Photo": { dir: true, mtime: now }
- };
- files["user:/Photo/gradient.png"] = { data: await picture("image/png", 320, 200, "AGI"), mtime: now };
- files["user:/Photo/sunset.jpg"] = { data: await picture("image/jpeg", 640, 400, "Sunset"), mtime: now };
- return files;
- }
- const S = {}; // settings (persisted)
- let FILES = {}; // path -> {dir, data, mtime}
- let SAMPLES = [];
- let CATALOG = [];
- let DEFAULTS = { cnn: {} };
- let last = null; // last run result
- let changedPaths = {};
- const persist = debounce(() => {
- kv("put", "workspace", { v: 1, files: FILES, settings: S }).catch(() => {});
- }, 300);
- async function loadWorkspace() {
- let saved = null;
- try { saved = await kv("get", "workspace"); } catch (e) { /* private mode */ }
- Object.assign(S, defaultSettings());
- if (saved && saved.files && saved.settings) {
- FILES = saved.files;
- const d = defaultSettings();
- Object.assign(S, saved.settings);
- S.request = Object.assign(d.request, S.request);
- S.user = Object.assign(d.user, S.user);
- S.mocks = Object.assign(d.mocks, S.mocks);
- S.layout = Object.assign(d.layout, S.layout);
- } else {
- FILES = await defaultFiles();
- }
- }
- // ---------- engine ----------
- let worker = null;
- let ready = false;
- let running = false;
- function setStatus(state, text) {
- pg.setAttribute("data-state", state);
- $("#pg-status-text").textContent = text;
- }
- function startWorker() {
- ready = false;
- $("#pg-run").disabled = true;
- try {
- worker = new Worker(BASE + "worker.js?v=" + VER);
- } catch (e) {
- setStatus("failed", "This browser cannot start the engine: " + e.message);
- return;
- }
- worker.onmessage = (e) => onWorker(e.data);
- worker.onerror = (e) => {
- setStatus("failed", "The engine did not start: " + (e.message || "worker error") + ". Was the site built with -nowasm?");
- };
- }
- function onWorker(m) {
- if (m.type === "ready") {
- ready = true;
- DEFAULTS = m.defaults || DEFAULTS;
- $("#pg-run").disabled = false;
- setStatus("ready", "Ready");
- renderCNN();
- } else if (m.type === "fail") {
- setStatus("failed", "The engine did not load (" + m.message + "). Build the docs without -nowasm to include playground/agi.wasm.");
- } else if (m.type === "event") {
- const p = JSON.parse(m.payload);
- if (m.kind === "log") addConsole(p, true);
- if (m.kind === "ws") addWS(p, true);
- } else if (m.type === "done") {
- finishRun(JSON.parse(m.json), m.files);
- }
- }
- function genericCatalog() {
- const out = {};
- CATALOG.forEach((lib) => {
- if (lib.play === "Services" && lib.load && lib.id !== "sqlite" && lib.id !== "sysinfo") {
- const names = [];
- lib.fns.forEach((f) => f.names.forEach((n) => { if (n.indexOf(lib.id + ".") === 0) names.push(n); }));
- out[lib.id] = names;
- }
- });
- return out;
- }
- function parseHeaders(text) {
- const h = {};
- (text || "").split("\n").forEach((line) => {
- const i = line.indexOf(":");
- if (i > 0) h[line.slice(0, i).trim()] = line.slice(i + 1).trim();
- });
- return h;
- }
- function buildMocks() {
- const m = S.mocks;
- const num = (v) => (v === "" || v == null || isNaN(+v) ? 0 : +v);
- return {
- http: {
- fallback: m.http.fallback,
- rules: m.http.rules.filter((r) => r.on !== false).map((r, i) => ({
- name: "rule " + (i + 1) + " (" + (r.method || "ANY") + " " + r.url + ")",
- method: r.method, url: r.url, status: num(r.status), headers: parseHeaders(r.headersText),
- body: r.body, base64: !!r.base64, error: r.error, delayMs: num(r.delayMs)
- }))
- },
- llm: {
- mode: m.llm.mode, reply: m.llm.reply, reasoning: m.llm.reasoning, rules: m.llm.rules, error: m.llm.error,
- model: m.llm.model, models: (m.llm.modelsText || "").split(",").map((s) => s.trim()).filter(Boolean),
- chunkSize: num(m.llm.chunkSize), chunkDelayMs: num(m.llm.chunkDelayMs)
- },
- cnn: { responses: m.cnn.responses, error: m.cnn.error },
- sqlite: m.sqlite, sysinfo: m.sysinfo, generic: m.generic,
- ws: { refuse: !!m.ws.refuse, script: m.ws.script.map((f) => ({ afterMs: num(f.afterMs), text: f.text })), closeAfterMs: num(m.ws.closeAfterMs) },
- schedulerDenied: !!m.schedulerDenied
- };
- }
- function pairs(list) {
- const o = {};
- (list || []).forEach((p) => { if (p[0]) o[p[0]] = p[1] || ""; });
- return o;
- }
- function runnable(path) { return /\.(agi|js)$/i.test(path || "") && FILES[path] && !FILES[path].dir; }
- function run() {
- if (!ready || running) return;
- flushEditor();
- const script = S.active;
- if (!runnable(script)) {
- toast("Open a .agi or .js file to run it");
- return;
- }
- const r = S.request;
- const json = r.bodyType === "json";
- const req = {
- script: script,
- code: dec.decode(FILES[script].data),
- method: r.method,
- query: pairs(r.query),
- form: json ? {} : pairs(r.form),
- body: json ? r.body : "",
- contentType: json ? "application/json" : "application/x-www-form-urlencoded",
- user: { username: S.user.username || "developer", admin: !!S.user.admin, quotaTotal: S.user.quotaMB === "" || S.user.quotaMB == null ? -1 : Math.round(+S.user.quotaMB * 1048576) },
- state: S.state || {},
- mocks: buildMocks(),
- timeoutSec: +r.timeoutSec || 30,
- catalog: genericCatalog()
- };
- const files = [];
- Object.keys(FILES).forEach((p) => {
- const f = FILES[p];
- files.push({ path: p, dir: !!f.dir, data: f.dir ? null : f.data, mtime: f.mtime || 0 });
- });
- running = true;
- runStarted = performance.now();
- beforeRun = {};
- Object.keys(FILES).forEach((p) => { beforeRun[p] = true; });
- clearOutput();
- $("#pg-run").disabled = true;
- $("#pg-stop").hidden = false;
- setStatus("running", "Running " + baseName(script));
- worker.postMessage({ type: "run", req: req, files: files });
- }
- let runStarted = 0;
- let beforeRun = {};
- function stop() {
- if (!running) return;
- worker.terminate();
- running = false;
- $("#pg-stop").hidden = true;
- wsInputs(false);
- addConsole({ t: Math.round(performance.now() - runStarted), source: "playground", level: "warn", text: "Stopped. The drive and database keep their state from before the run." }, true);
- $("#pg-resp").innerHTML = '<p class="pg-hint">Stopped before the script finished. Nothing it wrote was kept.</p>';
- setStatus("loading", "Restarting the engine");
- startWorker();
- }
- function finishRun(res, files) {
- running = false;
- last = res;
- $("#pg-stop").hidden = true;
- $("#pg-run").disabled = !ready;
- wsInputs(false);
- changedPaths = {};
- (files || []).forEach((f) => {
- changedPaths[f.path] = beforeRun[f.path] ? "modified" : "created";
- FILES[f.path] = f.dir ? { dir: true, mtime: f.mtime } : { data: f.data, mtime: f.mtime };
- });
- (res.removed || []).forEach((p) => {
- changedPaths[p] = "deleted";
- delete FILES[p];
- });
- if (res.state) S.state = res.state;
- S.open = S.open.filter((p) => FILES[p]);
- if (S.active && !FILES[S.active]) S.active = S.open[0] || null;
- persist();
- renderTree();
- renderTabs();
- loadEditor();
- renderOutput(res);
- const label = res.error ? (res.error.kind === "timeout" ? "Timed out" : "Failed") : "Finished";
- setStatus(res.error ? "failed" : "ready", label + " in " + res.durationMs + " ms · " + res.status + (res.mode === "webapp" ? " · WebApp script" : " · serverless script"));
- if (res.error) setTimeout(() => pg.setAttribute("data-state", "ready"), 4000);
- }
- // ---------- file tree ----------
- const tree = $("#pg-tree");
- function children(dir) {
- const prefix = dir.endsWith("/") ? dir : dir + "/";
- return Object.keys(FILES).filter((p) => p.startsWith(prefix) && p !== dir && p.slice(prefix.length).indexOf("/") < 0)
- .sort((a, b) => {
- const da = FILES[a].dir ? 0 : 1, db = FILES[b].dir ? 0 : 1;
- return da - db || a.localeCompare(b, undefined, { numeric: true });
- });
- }
- function renderTree() {
- tree.innerHTML = "";
- ROOTS.forEach((r) => {
- tree.append(treeNode(r.path, 0, r));
- if (S.expanded[r.path]) renderChildren(r.path, 1);
- });
- }
- function renderChildren(dir, depth) {
- children(dir).forEach((p) => {
- tree.append(treeNode(p, depth));
- if (FILES[p].dir && S.expanded[p]) renderChildren(p, depth + 1);
- });
- }
- function treeNode(p, depth, root) {
- const f = root ? { dir: true } : FILES[p];
- const isDir = !!f.dir;
- const cls = ["pg-node", isDir ? "dir" : "file"];
- if (isDir && S.expanded[p]) cls.push("expanded");
- if (S.selected === p) cls.push("sel");
- if (S.active === p) cls.push("open-file");
- if (changedPaths[p] && changedPaths[p] !== "deleted") cls.push("changed");
- const name = root ? root.label : baseName(p);
- const ic = root ? icon(root.id === "web" ? "box" : "drive") : isDir ? icon("folder") : IMG_EXT.test(p) ? icon("image") : /\.(agi|js)$/i.test(p) ? icon("code") : icon("file");
- const acts = el("span", { class: "acts" });
- if (!root) {
- if (!isDir) acts.append(el("button", { type: "button", title: "Download", html: icon("download"), onclick: (e) => { e.stopPropagation(); download(p); } }));
- acts.append(el("button", { type: "button", title: "Rename", html: icon("rename"), onclick: (e) => { e.stopPropagation(); rename(p); } }));
- acts.append(el("button", { type: "button", title: "Delete", html: icon("trash"), onclick: (e) => { e.stopPropagation(); remove(p); } }));
- }
- const node = el("div", {
- class: cls.join(" "), role: "treeitem", "data-path": p, title: p,
- "aria-expanded": isDir ? String(!!S.expanded[p]) : null,
- style: "padding-left:" + (6 + depth * 14) + "px"
- }, [
- el("span", { class: "tw", html: isDir ? icon("chevron") : "" }),
- el("span", { class: "ic", html: ic }),
- el("span", { class: "pg-name", text: name }),
- root && root.note ? el("span", { class: "pg-root-label", text: root.note }) : null,
- !isDir && f.data ? el("span", { class: "pg-size", text: fmtSize(f.data.length) }) : null,
- acts
- ]);
- node.addEventListener("click", () => {
- S.selected = p;
- if (isDir) S.expanded[p] = !S.expanded[p];
- else openFile(p);
- persist();
- renderTree();
- });
- return node;
- }
- function targetDir() {
- const s = S.selected;
- if (!s) return "user:/";
- if (s.endsWith(":/") || (FILES[s] && FILES[s].dir)) return s;
- return parentOf(s) || "user:/";
- }
- async function newEntry(dir) {
- const base = targetDir();
- const name = await dialog(dir ? "New folder in " + base : "New file in " + base, { input: dir ? "New folder" : "untitled.agi", ok: "Create" });
- if (!name) return;
- if (/[\\:]/.test(name) || name.split("/").some((s) => s === ".." || s === ".")) { toast("That name is not allowed"); return; }
- const p = join(base, name.replace(/^\/+|\/+$/g, ""));
- if (FILES[p]) { toast(baseName(p) + " already exists"); return; }
- ensureParents(p);
- FILES[p] = dir ? { dir: true, mtime: Date.now() } : { data: new Uint8Array(0), mtime: Date.now() };
- S.expanded[base] = true;
- S.selected = p;
- if (!dir) openFile(p);
- persist();
- renderTree();
- }
- function ensureParents(p) {
- let d = parentOf(p);
- while (d && !d.endsWith(":/")) {
- if (!FILES[d]) FILES[d] = { dir: true, mtime: Date.now() };
- d = parentOf(d);
- }
- }
- async function rename(p) {
- const name = await dialog("Rename " + baseName(p), { input: baseName(p), ok: "Rename" });
- if (!name || name === baseName(p)) return;
- if (/[\\/:]/.test(name)) { toast("A name cannot contain / \\ or :"); return; }
- const np = join(parentOf(p), name);
- if (FILES[np]) { toast(name + " already exists"); return; }
- Object.keys(FILES).forEach((k) => {
- if (k === p || k.startsWith(p + "/")) {
- const nk = np + k.slice(p.length);
- FILES[nk] = FILES[k];
- delete FILES[k];
- S.open = S.open.map((o) => (o === k ? nk : o));
- if (S.active === k) S.active = nk;
- if (S.expanded[k]) { S.expanded[nk] = true; delete S.expanded[k]; }
- }
- });
- S.selected = np;
- persist();
- renderTree();
- renderTabs();
- updateMode();
- }
- async function remove(p) {
- const isDir = FILES[p] && FILES[p].dir;
- const ok = await dialog("Delete " + p + (isDir ? " and everything in it" : "") + "?", { ok: "Delete" });
- if (!ok) return;
- Object.keys(FILES).forEach((k) => { if (k === p || k.startsWith(p + "/")) delete FILES[k]; });
- S.open = S.open.filter((o) => FILES[o]);
- if (!FILES[S.active]) S.active = S.open[0] || null;
- if (S.selected === p) S.selected = parentOf(p);
- persist();
- renderTree();
- renderTabs();
- loadEditor();
- }
- function download(p) {
- const f = FILES[p];
- const url = URL.createObjectURL(new Blob([f.data]));
- const a = el("a", { href: url, download: baseName(p) });
- document.body.append(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 2000);
- }
- async function upload(fileList, dir) {
- dir = dir || targetDir();
- let n = 0;
- for (const file of Array.from(fileList)) {
- if (file.size > 20 * 1048576) { toast(file.name + " is over 20 MB; skipped"); continue; }
- const p = join(dir, file.name);
- ensureParents(p);
- FILES[p] = { data: new Uint8Array(await file.arrayBuffer()), mtime: file.lastModified || Date.now() };
- n++;
- }
- if (!n) return;
- S.expanded[dir] = true;
- persist();
- renderTree();
- toast("Uploaded " + n + " file" + (n === 1 ? "" : "s") + " to " + dir);
- }
- // ---------- editor ----------
- const text = $("#pg-text");
- const hl = $("#pg-hl");
- const gutter = $("#pg-gutter");
- let errorLine = 0;
- function openFile(p) {
- flushEditor();
- if (S.open.indexOf(p) < 0) S.open.push(p);
- S.active = p;
- errorLine = 0;
- renderTabs();
- loadEditor();
- updateMode();
- persist();
- }
- function closeTab(p) {
- flushEditor();
- const i = S.open.indexOf(p);
- if (i < 0) return;
- S.open.splice(i, 1);
- if (S.active === p) S.active = S.open[Math.min(i, S.open.length - 1)] || null;
- renderTabs();
- loadEditor();
- updateMode();
- renderTree();
- persist();
- }
- function renderTabs() {
- const tabs = $("#pg-tabs");
- tabs.innerHTML = "";
- S.open.forEach((p) => {
- if (!FILES[p]) return;
- const t = el("button", { type: "button", class: "pg-tab", role: "tab", "aria-selected": String(p === S.active), title: p }, [
- el("span", { text: baseName(p) }),
- el("span", { class: "x", html: icon("close"), title: "Close", onclick: (e) => { e.stopPropagation(); closeTab(p); } })
- ]);
- t.addEventListener("click", () => openFile(p));
- t.addEventListener("auxclick", (e) => { if (e.button === 1) closeTab(p); });
- tabs.append(t);
- if (p === S.active) requestAnimationFrame(() => t.scrollIntoView({ block: "nearest", inline: "nearest" }));
- });
- }
- let loaded = null; // path shown in the textarea
- function loadEditor() {
- const p = S.active;
- const f = p && FILES[p];
- const code = $("#pg-code"), prev = $("#pg-preview"), empty = $("#pg-empty");
- code.hidden = prev.hidden = empty.hidden = true;
- loaded = null;
- if (!f) { empty.hidden = false; return; }
- if (isText(p, f.data)) {
- code.hidden = false;
- const s = dec.decode(f.data || new Uint8Array(0));
- if (text.value !== s) text.value = s;
- loaded = p;
- paint();
- return;
- }
- prev.hidden = false;
- prev.innerHTML = "";
- if (IMG_EXT.test(p)) {
- const url = URL.createObjectURL(new Blob([f.data], { type: /\.svg$/i.test(p) ? "image/svg+xml" : "" }));
- const img = el("img", { src: url, alt: baseName(p) });
- img.onload = () => {
- prev.append(el("p", { class: "pg-size", text: img.naturalWidth + " x " + img.naturalHeight + " · " + fmtSize(f.data.length) }));
- };
- prev.append(img);
- } else {
- let hex = "";
- for (let i = 0; i < Math.min(f.data.length, 256); i++) hex += (f.data[i] < 16 ? "0" : "") + f.data[i].toString(16) + (i % 16 === 15 ? "\n" : " ");
- prev.append(el("div", { class: "pg-bin" }, [el("p", { text: "Binary file · " + fmtSize(f.data.length) }), el("pre", { text: hex })]));
- }
- }
- function paint() {
- const p = loaded;
- const v = text.value;
- hl.innerHTML = window.AGIHL ? AGIHL.highlight(v, langOf(p || "")) + "\n " : esc(v) + "\n ";
- const lines = v.split("\n").length;
- let g = "";
- for (let i = 1; i <= lines; i++) g += i === errorLine ? '<div class="err">' + i + "</div>" : "<div>" + i + "</div>";
- gutter.innerHTML = g;
- syncScroll();
- }
- function syncScroll() {
- hl.scrollTop = text.scrollTop;
- hl.scrollLeft = text.scrollLeft;
- gutter.scrollTop = text.scrollTop;
- }
- function flushEditor() {
- if (!loaded || !FILES[loaded]) return;
- const data = enc.encode(text.value);
- const old = FILES[loaded].data;
- if (old && old.length === data.length && old.every((b, i) => b === data[i])) return;
- FILES[loaded] = { data: data, mtime: Date.now() };
- persist();
- }
- const saveSoon = debounce(() => { flushEditor(); renderTreeSizes(); }, 400);
- function renderTreeSizes() {
- const n = tree.querySelector('[data-path="' + CSS.escape(loaded || "") + '"] .pg-size');
- if (n && FILES[loaded]) n.textContent = fmtSize(FILES[loaded].data.length);
- }
- text.addEventListener("input", () => { errorLine = 0; paint(); saveSoon(); });
- text.addEventListener("scroll", syncScroll);
- text.addEventListener("keydown", (e) => {
- const v = text.value, s = text.selectionStart, en = text.selectionEnd;
- if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); run(); return; }
- if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") { e.preventDefault(); flushEditor(); toast("Saved to the playground drive"); return; }
- if ((e.ctrlKey || e.metaKey) && e.key === "/") {
- e.preventDefault();
- const ls = v.lastIndexOf("\n", s - 1) + 1;
- let le = v.indexOf("\n", en - (en > s && v[en - 1] === "\n" ? 1 : 0));
- if (le < 0) le = v.length;
- const block = v.slice(ls, le).split("\n");
- const all = block.every((l) => /^\s*\/\//.test(l) || !l.trim());
- const out = block.map((l) => (all ? l.replace(/^(\s*)\/\/ ?/, "$1") : l.trim() ? l.replace(/^(\s*)/, "$1// ") : l)).join("\n");
- replaceRange(ls, le, out, ls, ls + out.length);
- return;
- }
- if (e.key === "Tab") {
- e.preventDefault();
- if (s === en && !e.shiftKey) { replaceRange(s, en, " ", s + 4, s + 4); return; }
- const ls = v.lastIndexOf("\n", s - 1) + 1;
- const block = v.slice(ls, en).split("\n");
- const out = block.map((l) => (e.shiftKey ? l.replace(/^ {1,4}|^\t/, "") : " " + l)).join("\n");
- replaceRange(ls, en, out, ls, ls + out.length);
- return;
- }
- if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
- e.preventDefault();
- const ls = v.lastIndexOf("\n", s - 1) + 1;
- const indent = /^[ \t]*/.exec(v.slice(ls, s))[0];
- const before = v.slice(0, s).trimEnd();
- const extra = /[{[(]$/.test(before) ? " " : "";
- const closing = extra && /^[}\])]/.test(v.slice(en).trimStart()) && v.slice(en).trimStart() === v.slice(en).replace(/^[ \t]*/, "");
- const ins = "\n" + indent + extra + (closing ? "\n" + indent : "");
- replaceRange(s, en, ins, s + 1 + indent.length + extra.length, s + 1 + indent.length + extra.length);
- }
- });
- function replaceRange(a, b, str, selA, selB) {
- text.focus();
- text.setSelectionRange(a, b);
- // execCommand keeps the browser's undo history working.
- if (!document.execCommand || !document.execCommand("insertText", false, str)) {
- text.setRangeText(str, a, b, "end");
- text.dispatchEvent(new Event("input"));
- }
- text.setSelectionRange(selA, selB);
- }
- function gotoLine(n) {
- const lines = text.value.split("\n");
- let pos = 0;
- for (let i = 0; i < n - 1 && i < lines.length; i++) pos += lines[i].length + 1;
- text.focus();
- text.setSelectionRange(pos, pos + (lines[n - 1] || "").length);
- const lh = parseFloat(getComputedStyle(text).lineHeight) || 20;
- text.scrollTop = Math.max(0, (n - 4) * lh);
- syncScroll();
- }
- function updateMode() {
- const p = S.active;
- const m = $("#pg-mode");
- if (!runnable(p)) { m.innerHTML = "Open a <b>.agi</b> file to run it"; return; }
- m.innerHTML = p.startsWith("web:/")
- ? "<b>WebApp script</b> · POST fields are globals"
- : "<b>Serverless script</b> · getPara / postPara / readBody";
- }
- // ---------- output ----------
- const outPanels = {
- console: $("#pg-console"), calls: $("#pg-calls"), changes: $("#pg-changes"), ws: $("#pg-ws-log")
- };
- outPanels.console.setAttribute("data-empty", "console.log() output and the messages ArozOS would write to its log appear here.");
- outPanels.calls.setAttribute("data-empty", "Calls to mocked services (http, llm, cnn, sqlite, ...) and the answers they got appear here.");
- outPanels.changes.setAttribute("data-empty", "Files the script creates, changes or deletes appear here.");
- outPanels.ws.setAttribute("data-empty", "After websocket.upgrade() the frames both sides send appear here.");
- function showTab(name) {
- S.outTab = name;
- $$(".pg-out-tabs [data-out]").forEach((b) => b.setAttribute("aria-selected", String(b.getAttribute("data-out") === name)));
- $$(".pg-out-body [data-panel]").forEach((p) => { p.hidden = p.getAttribute("data-panel") !== name; });
- if (name === "state") renderState();
- persist();
- }
- $$(".pg-out-tabs [data-out]").forEach((b) => b.addEventListener("click", () => showTab(b.getAttribute("data-out"))));
- function count(name, n, bad) {
- const b = $('[data-count="' + name + '"]');
- b.textContent = n ? n : "";
- b.className = bad ? "err" : "";
- }
- let consoleN = 0, wsN = 0, consoleBad = false;
- function clearOutput() {
- Object.keys(outPanels).forEach((k) => { outPanels[k].innerHTML = ""; });
- consoleN = wsN = 0;
- consoleBad = false;
- ["console", "calls", "changes", "ws"].forEach((k) => count(k, 0));
- $("#pg-resp-head").innerHTML = "";
- $("#pg-resp-view").hidden = true;
- $("#pg-resp").innerHTML = '<p class="pg-hint">Running...</p>';
- errorLine = 0;
- paint();
- }
- function line(t, cls, src, txt) {
- return el("div", { class: "pg-line " + cls }, [
- el("span", { class: "t", text: t + " ms" }),
- el("span", { class: "txt" }, [src ? el("span", { class: "src", text: src }) : null, document.createTextNode(txt)])
- ]);
- }
- function addConsole(l, live) {
- const bad = /Runtime Error|Script error|Failed/.test(l.text);
- const node = line(l.t, l.level + (bad ? " error" : ""), l.source === "script" ? "" : "[" + l.source + "]", l.text);
- outPanels.console.append(node);
- consoleN++;
- if (bad || l.level === "error") consoleBad = true;
- count("console", consoleN, consoleBad);
- if (live) outPanels.console.parentNode.scrollTop = outPanels.console.parentNode.scrollHeight;
- }
- function addWS(f, live) {
- const label = { out: "script ->", in: "-> script", open: "", close: "" }[f.dir];
- const cls = f.dir === "out" ? "ws-out" : f.dir === "in" ? "ws-in" : "ws-meta";
- outPanels.ws.append(line(f.t, cls, label, f.text));
- wsN++;
- count("ws", wsN);
- if (f.dir === "open" && live) wsInputs(true);
- if (f.dir === "close") wsInputs(false);
- }
- function wsInputs(on) {
- $$("#pg-ws-send input, #pg-ws-send button").forEach((x) => { x.disabled = !on; });
- }
- $("#pg-ws-send").addEventListener("submit", (e) => {
- e.preventDefault();
- const inp = $("#pg-ws-send input");
- if (!running || !inp.value) return;
- worker.postMessage({ type: "ws", text: inp.value });
- inp.value = "";
- });
- $('#pg-ws-send [data-act="ws-close"]').addEventListener("click", () => { if (running) worker.postMessage({ type: "wsclose" }); });
- function chip(text, cls) { return el("span", { class: "pg-chip " + (cls || ""), text: text }); }
- function renderOutput(res) {
- // Console and WebSocket were streamed; redraw them from the result so
- // the order is exact even if events raced the end of the run.
- outPanels.console.innerHTML = "";
- consoleN = 0; consoleBad = false;
- (res.console || []).forEach((l) => addConsole(l));
- count("console", consoleN, consoleBad);
- outPanels.ws.innerHTML = "";
- wsN = 0;
- (res.ws || []).forEach((f) => addWS(f));
- count("ws", wsN);
- const head = $("#pg-resp-head");
- head.innerHTML = "";
- head.append(chip(String(res.status), res.status < 400 ? "ok" : "bad"));
- head.append(chip(res.exited ? "exit() · type left to the browser" : res.contentType || "text/plain"));
- head.append(chip(res.durationMs + " ms"));
- if (res.headers && res.headers.Location) head.append(chip("Location: " + res.headers.Location, "warn"));
- if (res.upgraded) head.append(chip("WebSocket", "warn"));
- if (res.modules && res.modules.length) head.append(chip(res.modules.length + " module registered", "ok"));
- if (res.error) {
- const m = ERR_LINE.exec(res.error.stack || res.error.message || "");
- if (m && res.error.kind !== "timeout") { errorLine = +m[1]; paint(); }
- }
- renderResponse(res);
- // Calls to mocked services
- outPanels.calls.innerHTML = "";
- (res.calls || []).forEach((c) => {
- outPanels.calls.append(el("div", { class: "pg-call" }, [
- el("div", { class: "pg-call-head" }, [el("span", { class: "t", text: c.t + " ms" }), el("code", { text: c.lib + "." + c.fn }), el("span", { class: "rule", text: c.rule || "" })]),
- c.args ? el("pre", { text: c.args }) : null,
- el("pre", { class: "res", text: "-> " + c.result })
- ]));
- });
- count("calls", (res.calls || []).length);
- // Changes
- outPanels.changes.innerHTML = "";
- const keys = Object.keys(changedPaths).sort();
- keys.forEach((p) => {
- const k = changedPaths[p];
- const a = el("a", { text: p, onclick: () => { if (FILES[p] && !FILES[p].dir) { revealPath(p); openFile(p); } } });
- outPanels.changes.append(el("div", { class: "pg-change" }, [el("span", { class: "k " + k, text: k }), a,
- FILES[p] && FILES[p].data ? el("span", { class: "pg-size", text: fmtSize(FILES[p].data.length) }) : null]));
- });
- count("changes", keys.length);
- if (S.outTab === "state") renderState();
- }
- let respView = "pretty";
- $$("#pg-resp-view button").forEach((b) => b.addEventListener("click", () => {
- respView = b.getAttribute("data-view");
- $$("#pg-resp-view button").forEach((x) => x.setAttribute("aria-selected", String(x === b)));
- if (last) renderResponse(last);
- }));
- // renderResponse draws the error (if any) and the body of a result.
- function renderResponse(res) {
- const box = $("#pg-resp");
- box.innerHTML = "";
- if (res.error) {
- const m = ERR_LINE.exec(res.error.stack || res.error.message || "");
- const errBox = el("div", { class: "pg-error" }, [
- el("strong", { text: res.error.kind === "timeout" ? "Time limit reached" : "Script error" }),
- el("pre", { text: res.error.stack || res.error.message })
- ]);
- if (m && res.error.kind !== "timeout") {
- errBox.append(el("button", { type: "button", class: "pg-btn", text: "Go to line " + m[1], onclick: () => gotoLine(+m[1]) }));
- }
- box.append(errBox);
- }
- renderBody(res);
- }
- function renderBody(res) {
- const box = $("#pg-resp");
- const body = res.response || "";
- const ct = (res.contentType || "").toLowerCase();
- const sniffHTML = !ct && /^\s*</.test(body);
- const isHTML = ct.indexOf("text/html") >= 0 || sniffHTML;
- let pretty = null;
- $("#pg-resp-view").hidden = !isHTML && !/^data:image\//.test(body);
- if (res.upgraded && !body) {
- box.append(el("p", { class: "pg-hint", text: "The connection was upgraded to a WebSocket; see the WebSocket tab." }));
- return;
- }
- if (!body) {
- if (!res.error) box.append(el("p", { class: "pg-hint", text: "The script sent an empty response." }));
- return;
- }
- if (respView === "pretty") {
- if (/^data:image\/[a-z+]+;base64,/.test(body)) {
- box.append(el("img", { src: body, alt: "Response image" }));
- return;
- }
- if (isHTML) {
- box.append(el("iframe", { sandbox: "", srcdoc: body, title: "HTML response" }));
- return;
- }
- if (ct.indexOf("json") >= 0 || /^\s*[{[]/.test(body)) {
- try { pretty = JSON.stringify(JSON.parse(body), null, 2); } catch (e) { pretty = null; }
- }
- }
- const pre = el("pre");
- if (pretty != null && window.AGIHL) pre.innerHTML = AGIHL.highlight(pretty, "json");
- else pre.textContent = body;
- box.append(pre);
- }
- function revealPath(p) {
- let d = parentOf(p);
- while (d) { S.expanded[d] = true; d = parentOf(d); }
- S.selected = p;
- renderTree();
- }
- function renderState() {
- const box = $("#pg-state");
- const st = S.state || {};
- box.innerHTML = "";
- const note = el("p", { text: "What outlives a run, as on a server: the system database, shares, scheduled tasks, accounts and llm usage. Clear it from the menu at the top right." });
- box.append(note);
- const db = st.db || {};
- const tables = Object.keys(db).sort();
- box.append(el("h5", { text: "Database tables (" + tables.length + ")" }));
- if (!tables.length) box.append(el("p", { text: "No tables yet. newDBTableIfNotExists(\"name\") creates one." }));
- tables.forEach((t) => {
- const keys = Object.keys(db[t]).sort();
- box.append(el("h5", { text: t + " · " + keys.length + " key" + (keys.length === 1 ? "" : "s") }));
- if (!keys.length) return;
- const tb = el("table", null, [el("tr", null, [el("th", { text: "Key" }), el("th", { text: "Value" })])]);
- keys.forEach((k) => tb.append(el("tr", null, [el("td", { text: k }), el("td", { text: db[t][k] })])));
- box.append(tb);
- });
- const list = (title, items, cols) => {
- if (!items || !items.length) return;
- box.append(el("h5", { text: title + " (" + items.length + ")" }));
- const tb = el("table", null, [el("tr", null, cols.map((c) => el("th", { text: c[0] })))]);
- items.forEach((it) => tb.append(el("tr", null, cols.map((c) => el("td", { text: String(it[c[1]] == null ? "" : it[c[1]]) })))));
- box.append(tb);
- };
- list("Shares", st.shares, [["UUID", "uuid"], ["File", "vpath"], ["Owner", "owner"]]);
- list("Scheduled tasks", st.tasks, [["Name", "name"], ["Every (s)", "interval"], ["Script", "script"]]);
- list("Accounts", (st.users || []).map((u) => ({ u: u })), [["Username", "u"]]);
- if (st.llmUsage && st.llmUsage.totalRequests) {
- box.append(el("h5", { text: "llm usage" }));
- box.append(el("p", { text: st.llmUsage.totalRequests + " requests, " + st.llmUsage.totalTokens + " tokens (estimated)" }));
- }
- if (last && last.notifications && last.notifications.length) list("Notifications sent by the last run", last.notifications, [["To", "to"], ["Title", "title"], ["Message", "message"], ["Priority", "priority"]]);
- if (last && last.modules && last.modules.length) {
- box.append(el("h5", { text: "registerModule() in the last run" }));
- last.modules.forEach((m) => box.append(el("pre", { class: "pg-mono", text: JSON.stringify(m, null, 2) })));
- }
- }
- // ---------- splitter ----------
- const split = $("#pg-split");
- function applyLayout() {
- if (S.layout.outW) pg.style.setProperty("--pg-out-w", S.layout.outW + "px");
- }
- split.addEventListener("pointerdown", (e) => {
- split.setPointerCapture(e.pointerId);
- split.classList.add("drag");
- const body = $(".pg-body").getBoundingClientRect();
- const move = (ev) => {
- const w = Math.max(280, Math.min(body.right - ev.clientX, body.width - 520));
- S.layout.outW = Math.round(w);
- applyLayout();
- };
- const up = () => {
- split.classList.remove("drag");
- split.removeEventListener("pointermove", move);
- split.removeEventListener("pointerup", up);
- persist();
- };
- split.addEventListener("pointermove", move);
- split.addEventListener("pointerup", up);
- });
- // ---------- tool windows ----------
- // Tool windows stack between 61 and 66, under the toolbar menus (80) and
- // the dialog (90).
- let zOrder = [];
- function front(w) {
- zOrder = zOrder.filter((x) => x !== w);
- zOrder.push(w);
- zOrder.forEach((x, i) => { x.style.zIndex = 61 + i; });
- }
- function openWin(name, show) {
- const w = $('.pg-win[data-win="' + name + '"]');
- const btn = $('.pg-wins [data-win="' + name + '"]');
- const open = show === undefined ? w.hidden : show;
- w.hidden = !open;
- btn.setAttribute("aria-pressed", String(open));
- const st = S.layout.wins[name] || (S.layout.wins[name] = {});
- st.open = open;
- if (open) {
- if (st.x != null) {
- w.style.left = Math.max(0, Math.min(st.x, innerWidth - 120)) + "px";
- w.style.top = Math.max(60, Math.min(st.y, innerHeight - 60)) + "px";
- }
- if (st.w) { w.style.width = st.w + "px"; w.style.height = st.h + "px"; }
- front(w);
- renderWin(name);
- }
- persist();
- }
- $$(".pg-wins [data-win]").forEach((b) => b.addEventListener("click", () => openWin(b.getAttribute("data-win"))));
- $$(".pg-win").forEach((w) => {
- const name = w.getAttribute("data-win");
- $("[data-close]", w).addEventListener("click", () => openWin(name, false));
- w.addEventListener("pointerdown", () => front(w));
- const head = $(".pg-win-head", w);
- head.addEventListener("pointerdown", (e) => {
- if (e.target.closest("button")) return;
- const r = w.getBoundingClientRect();
- const dx = e.clientX - r.left, dy = e.clientY - r.top;
- head.setPointerCapture(e.pointerId);
- const move = (ev) => {
- w.style.left = Math.max(0, Math.min(ev.clientX - dx, innerWidth - 80)) + "px";
- w.style.top = Math.max(50, Math.min(ev.clientY - dy, innerHeight - 40)) + "px";
- };
- const up = () => {
- head.removeEventListener("pointermove", move);
- head.removeEventListener("pointerup", up);
- const st = S.layout.wins[name] || (S.layout.wins[name] = {});
- const b = w.getBoundingClientRect();
- st.x = Math.round(b.left); st.y = Math.round(b.top);
- persist();
- };
- head.addEventListener("pointermove", move);
- head.addEventListener("pointerup", up);
- });
- // Remember a resize (the CSS resize handle).
- if (window.ResizeObserver) new ResizeObserver(() => {
- if (w.hidden) return;
- const st = S.layout.wins[name] || (S.layout.wins[name] = {});
- const b = w.getBoundingClientRect();
- if (b.width && (Math.abs((st.w || 0) - b.width) > 2 || Math.abs((st.h || 0) - b.height) > 2) && w.dataset.sized) {
- st.w = Math.round(b.width); st.h = Math.round(b.height);
- persist();
- }
- w.dataset.sized = "1";
- }).observe(w);
- });
- function renderWin(name) {
- const w = $('.pg-win[data-win="' + name + '"]');
- bindAll(w);
- $$("[data-kv]", w).forEach(renderKV);
- $$("[data-rules]", w).forEach(renderRules);
- if (name === "cnn") renderCNN();
- if (name === "services") renderGeneric();
- }
- // data-bind: two-way binding of inputs to the settings.
- function readInput(inp) {
- if (inp.type === "checkbox") return inp.checked;
- if (inp.type === "number") return inp.value === "" ? "" : +inp.value;
- return inp.value;
- }
- function bindAll(scope) {
- $$("[data-bind]", scope).forEach((inp) => {
- const path = inp.getAttribute("data-bind");
- const v = getPath(S, path);
- if (inp.type === "checkbox") inp.checked = !!v;
- else inp.value = v == null ? "" : v;
- if (!inp.dataset.bound) {
- inp.dataset.bound = "1";
- inp.addEventListener(inp.tagName === "SELECT" || inp.type === "checkbox" ? "change" : "input", () => {
- setPath(S, path, readInput(inp));
- applyWhen(scope);
- persist();
- });
- }
- });
- applyWhen(scope);
- }
- function applyWhen(scope) {
- $$("[data-when]", scope).forEach((n) => {
- const m = /^([\w.]+)(!?=)(.*)$/.exec(n.getAttribute("data-when"));
- if (!m) return;
- const v = String(getPath(S, m[1]));
- n.hidden = m[2] === "=" ? v !== m[3] : v === m[3];
- });
- }
- function renderKV(box) {
- const path = box.getAttribute("data-kv");
- let list = getPath(S, path);
- if (!Array.isArray(list)) { list = []; setPath(S, path, list); }
- const draw = () => {
- box.innerHTML = "";
- const rows = list.concat([["", ""]]);
- rows.forEach((pair, i) => {
- const k = el("input", { type: "text", placeholder: "name", value: pair[0] });
- const v = el("input", { type: "text", placeholder: "value", value: pair[1] });
- const x = el("button", { type: "button", class: "pg-icon-btn", title: "Remove", html: icon("close") });
- // Typing in the blank last row adds it and draws a new blank row.
- const upd = () => {
- if (i >= list.length) { list.push([k.value, v.value]); draw(); }
- else list[i] = [k.value, v.value];
- persist();
- };
- k.addEventListener("input", () => { const wasNew = i >= list.length; upd(); if (wasNew) focusKV(box, i, 0, k.value.length); });
- v.addEventListener("input", () => { const wasNew = i >= list.length; upd(); if (wasNew) focusKV(box, i, 1, v.value.length); });
- x.addEventListener("click", () => { if (i < list.length) { list.splice(i, 1); draw(); persist(); } });
- if (i >= list.length) x.style.visibility = "hidden";
- box.append(el("div", { class: "pg-kv-row" }, [k, v, x]));
- });
- };
- draw();
- }
- function focusKV(box, row, col, pos) {
- const inp = box.querySelectorAll(".pg-kv-row")[row].querySelectorAll("input")[col];
- inp.focus();
- inp.setSelectionRange(pos, pos);
- }
- // Rule lists of the HTTP, LLM, WebSocket and sqlite windows.
- const RULES = {
- http: {
- list: () => S.mocks.http.rules,
- blank: () => ({ on: true, method: "GET", url: "https://api.example.com/", status: 200, headersText: "", body: "", base64: false, error: "", delayMs: 0 }),
- empty: "No rules: every request fails.",
- draw: (r) => [
- el("div", { class: "pg-rule-top" }, [
- field(r, "on", "checkbox", { title: "Use this rule" }),
- select(r, "method", ["ANY", "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"]),
- field(r, "url", "text", { placeholder: "https://api.example.com/*", "aria-label": "URL" }),
- field(r, "status", "number", { title: "Status code", "aria-label": "Status" })
- ]),
- labelled("Body", field(r, "body", "textarea", { rows: 3, class: "pg-mono", placeholder: '{"ok": true}' })),
- el("div", { class: "pg-rule-more" }, [
- labelled("Headers (Name: value per line)", field(r, "headersText", "textarea", { rows: 2, class: "pg-mono" })),
- el("div", { class: "pg-field" }, [
- labelled("Fail with error", field(r, "error", "text", { placeholder: "e.g. connection refused" })),
- labelled("Delay (ms)", field(r, "delayMs", "number", {})),
- el("label", { class: "pg-check" }, [field(r, "base64", "checkbox", {}), document.createTextNode("Body is base64 (binary)")])
- ])
- ])
- ]
- },
- llm: {
- list: () => S.mocks.llm.rules,
- blank: () => ({ match: "", reply: "" }),
- empty: "No rules: every prompt gets the reply above.",
- draw: (r) => [
- el("div", { class: "pg-rule-top" }, [field(r, "match", "text", { placeholder: "prompt contains... or /regex/i", "aria-label": "Match" })]),
- field(r, "reply", "textarea", { rows: 2, placeholder: "Reply", "aria-label": "Reply" })
- ]
- },
- ws: {
- list: () => S.mocks.ws.script,
- blank: () => ({ afterMs: 500, text: "" }),
- empty: "The browser sends nothing on its own.",
- draw: (r) => [el("div", { class: "pg-rule-top" }, [
- field(r, "afterMs", "number", { title: "Wait (ms) after the previous frame", "aria-label": "Wait in ms" }),
- field(r, "text", "text", { placeholder: "frame text", "aria-label": "Frame" })
- ])]
- },
- sqlite: {
- list: () => S.mocks.sqlite,
- blank: () => ({ fn: "query", match: "", result: "[]" }),
- empty: "No rules: the defaults answer.",
- draw: (r) => [
- el("div", { class: "pg-rule-top" }, [select(r, "fn", ["exec", "query", "queryRow", "tables", "schema"]), field(r, "match", "text", { placeholder: "SQL contains... or /regex/i", "aria-label": "Match" })]),
- field(r, "result", "textarea", { rows: 2, class: "pg-mono", "aria-label": "JSON result" })
- ]
- }
- };
- function field(obj, key, type, attrs) {
- const inp = type === "textarea" ? el("textarea", attrs) : el("input", Object.assign({ type: type }, attrs));
- if (type === "checkbox") inp.checked = key === "on" ? obj[key] !== false : !!obj[key];
- else inp.value = obj[key] == null ? "" : obj[key];
- inp.addEventListener(type === "checkbox" ? "change" : "input", () => {
- obj[key] = readInput(inp);
- if (key === "on") inp.closest(".pg-rule").classList.toggle("off", !inp.checked);
- persist();
- });
- return inp;
- }
- function select(obj, key, options) {
- const s = el("select", { "aria-label": key }, options.map((o) => el("option", { value: o === "ANY" ? "" : o, text: o })));
- s.value = obj[key] || "";
- s.addEventListener("change", () => { obj[key] = s.value; persist(); });
- return s;
- }
- function labelled(text, inp) { return el("label", null, [document.createTextNode(text), inp]); }
- function renderRules(box) {
- const kind = box.getAttribute("data-rules");
- const def = RULES[kind];
- const list = def.list();
- box.setAttribute("data-empty", def.empty);
- box.innerHTML = "";
- list.forEach((r, i) => {
- const del = el("button", { type: "button", class: "pg-icon-btn", title: "Remove", html: icon("trash"), onclick: () => { list.splice(i, 1); renderRules(box); persist(); } });
- const parts = def.draw(r);
- parts[0].append(del);
- box.append(el("div", { class: "pg-rule" + (r.on === false ? " off" : "") }, parts));
- });
- }
- $$("[data-add]").forEach((b) => b.addEventListener("click", () => {
- const kind = b.getAttribute("data-add");
- RULES[kind].list().push(RULES[kind].blank());
- $$('[data-rules="' + kind + '"]').forEach(renderRules);
- persist();
- }));
- // CNN window
- const CNN_FNS = ["classify", "detect", "segment", "pose", "oriented", "faceDetect", "faceLandmarks", "faceEmbedding", "faceAttributes", "faceCompare", "models", "health"];
- const cnnSel = $("#pg-cnn-fn"), cnnText = $("#pg-cnn-json");
- CNN_FNS.forEach((f) => cnnSel.append(el("option", { value: f, text: "cnn." + f + "()" })));
- function renderCNN() {
- const f = cnnSel.value || "classify";
- const own = S.mocks.cnn.responses[f];
- let v = own != null ? own : DEFAULTS.cnn[f] || "";
- if (own == null && v) { try { v = JSON.stringify(JSON.parse(v), null, 2); } catch (e) { /* keep */ } }
- cnnText.value = v;
- jsonState(cnnText, $("#pg-cnn-state"), own == null ? "Default answer" : "");
- }
- function jsonState(ta, out, label) {
- const v = ta.value.trim();
- if (!v) { out.textContent = label || "Empty"; out.className = "pg-json-state"; return true; }
- try { JSON.parse(v); out.textContent = label || "Valid JSON"; out.className = "pg-json-state"; return true; } catch (e) { out.textContent = "Not valid JSON: " + e.message; out.className = "pg-json-state bad"; return false; }
- }
- cnnSel.addEventListener("change", renderCNN);
- cnnText.addEventListener("input", () => {
- S.mocks.cnn.responses[cnnSel.value] = cnnText.value;
- jsonState(cnnText, $("#pg-cnn-state"));
- persist();
- });
- $('[data-act="cnn-default"]').addEventListener("click", () => { delete S.mocks.cnn.responses[cnnSel.value]; renderCNN(); persist(); });
- // Services window: answers of generic mocks
- const genSel = $("#pg-gen-fn"), genText = $("#pg-gen-json");
- function renderGeneric() {
- const cur = genSel.value;
- genSel.innerHTML = "";
- const cat = genericCatalog();
- Object.keys(cat).sort().forEach((lib) => {
- const og = el("optgroup", { label: lib });
- cat[lib].forEach((n) => og.append(el("option", { value: n, text: (S.mocks.generic[n] ? "* " : "") + n + "()" })));
- genSel.append(og);
- });
- if (cur) genSel.value = cur;
- genText.value = S.mocks.generic[genSel.value] || "";
- jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null");
- }
- genSel.addEventListener("change", () => { genText.value = S.mocks.generic[genSel.value] || ""; jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null"); });
- genText.addEventListener("input", () => {
- if (genText.value.trim()) S.mocks.generic[genSel.value] = genText.value;
- else delete S.mocks.generic[genSel.value];
- jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null");
- const o = genSel.selectedOptions[0];
- if (o) o.textContent = (S.mocks.generic[genSel.value] ? "* " : "") + genSel.value + "()";
- persist();
- });
- // ---------- samples ----------
- function renderSamples() {
- const menu = $(".pg-samples-menu");
- menu.innerHTML = "";
- // Groups in the order they first appear in the numbered files.
- const groups = [];
- SAMPLES.forEach((s) => { if (groups.indexOf(s.group || "") < 0) groups.push(s.group || ""); });
- groups.forEach((g) => {
- menu.append(el("h5", { text: g || "Samples" }));
- SAMPLES.filter((s) => (s.group || "") === g).forEach((s) => {
- menu.append(el("button", { type: "button", role: "menuitem", onclick: () => loadSample(s) }, [document.createTextNode(s.title), el("small", { text: s.summary || "" })]));
- });
- });
- }
- async function loadSample(s) {
- $("#pg-samples").classList.remove("open");
- const existing = FILES[s.path];
- if (existing && !existing.dir && dec.decode(existing.data) !== s.code) {
- const ok = await dialog(s.path + " was changed. Replace it with the sample?", { ok: "Replace" });
- if (!ok) { openFile(s.path); return; }
- }
- ensureParents(s.path);
- FILES[s.path] = { data: enc.encode(s.code), mtime: Date.now() };
- const setup = s.setup || {};
- if (setup.request) {
- const r = setup.request;
- if (r.method) S.request.method = r.method;
- if (r.form) { S.request.bodyType = "form"; S.request.form = Object.keys(r.form).map((k) => [k, String(r.form[k])]); }
- if (r.json) { S.request.bodyType = "json"; S.request.body = JSON.stringify(r.json, null, 2); }
- if (r.query) S.request.query = Object.keys(r.query).map((k) => [k, String(r.query[k])]);
- }
- if (setup.user) Object.assign(S.user, setup.user);
- const m = setup.mocks || {};
- if (m.http && m.http.rules) {
- m.http.rules.slice().reverse().forEach((nr) => {
- const rule = Object.assign(RULES.http.blank(), nr);
- if (nr.headers) rule.headersText = Object.keys(nr.headers).map((k) => k + ": " + nr.headers[k]).join("\n");
- S.mocks.http.rules = S.mocks.http.rules.filter((r) => !(r.url === rule.url && (r.method || "") === (rule.method || "")));
- S.mocks.http.rules.unshift(rule);
- });
- }
- if (m.llm) Object.assign(S.mocks.llm, m.llm);
- if (m.cnn && m.cnn.responses) Object.assign(S.mocks.cnn.responses, m.cnn.responses);
- if (m.ws) Object.assign(S.mocks.ws, m.ws);
- if (m.sqlite) S.mocks.sqlite = m.sqlite.concat(S.mocks.sqlite.filter((r) => !m.sqlite.some((x) => x.fn === r.fn && x.match === r.match)));
- if (m.generic) Object.assign(S.mocks.generic, m.generic);
- for (const f of setup.files || []) {
- if (FILES[f.path]) continue;
- ensureParents(f.path);
- if (f.dir) FILES[f.path] = { dir: true, mtime: Date.now() };
- else if (f.image) FILES[f.path] = { data: await picture(f.image === "png" ? "image/png" : "image/jpeg", f.width || 640, f.height || 400, f.label || "AGI"), mtime: Date.now() };
- else FILES[f.path] = { data: enc.encode(f.text || ""), mtime: Date.now() };
- }
- revealPath(s.path);
- openFile(s.path);
- $$(".pg-win").forEach((w) => { if (!w.hidden) renderWin(w.getAttribute("data-win")); });
- persist();
- toast("Loaded the " + s.title + " sample");
- }
- // ---------- menus and actions ----------
- async function exportWorkspace() {
- flushEditor();
- const files = {};
- Object.keys(FILES).forEach((p) => {
- files[p] = FILES[p].dir ? { dir: true } : { b64: toB64(FILES[p].data), mtime: FILES[p].mtime };
- });
- const blob = new Blob([JSON.stringify({ kind: "agi-playground", v: 1, files: files, settings: S }, null, 1)], { type: "application/json" });
- const url = URL.createObjectURL(blob);
- const a = el("a", { href: url, download: "agi-playground.json" });
- document.body.append(a); a.click(); a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 2000);
- }
- async function importWorkspace(file) {
- let data;
- try { data = JSON.parse(await file.text()); } catch (e) { toast("That file is not a playground export"); return; }
- if (!data || data.kind !== "agi-playground" || !data.files) { toast("That file is not a playground export"); return; }
- const ok = await dialog("Replace the current workspace with " + file.name + "?", { ok: "Replace" });
- if (!ok) return;
- FILES = {};
- Object.keys(data.files).forEach((p) => {
- const f = data.files[p];
- FILES[p] = f.dir ? { dir: true, mtime: Date.now() } : { data: fromB64(f.b64 || ""), mtime: f.mtime || Date.now() };
- });
- Object.keys(S).forEach((k) => delete S[k]);
- Object.assign(S, defaultSettings(), data.settings || {});
- refreshAll();
- persist();
- }
- async function resetAll() {
- const ok = await dialog("Reset the playground? Files, settings and the stored database go back to the start.", { ok: "Reset" });
- if (!ok) return;
- try { await kv("del", "workspace"); } catch (e) { /* ignore */ }
- Object.keys(S).forEach((k) => delete S[k]);
- Object.assign(S, defaultSettings());
- FILES = await defaultFiles();
- last = null;
- changedPaths = {};
- refreshAll();
- persist();
- }
- $$("#pg-more [data-act]").forEach((b) => b.addEventListener("click", async () => {
- $("#pg-more").classList.remove("open");
- const act = b.getAttribute("data-act");
- if (act === "export") exportWorkspace();
- if (act === "import") $("#pg-import").click();
- if (act === "reset") resetAll();
- if (act === "clear-state") {
- const ok = await dialog("Clear the stored database tables, shares, scheduled tasks, accounts and llm usage?", { ok: "Clear" });
- if (!ok) return;
- S.state = {};
- persist();
- renderState();
- toast("Stored state cleared");
- }
- }));
- $("#pg-import").addEventListener("change", (e) => { if (e.target.files[0]) importWorkspace(e.target.files[0]); e.target.value = ""; });
- $('[data-act="new-file"]').addEventListener("click", () => newEntry(false));
- $('[data-act="new-folder"]').addEventListener("click", () => newEntry(true));
- $('[data-act="upload"]').addEventListener("click", () => $("#pg-upload").click());
- $("#pg-upload").addEventListener("change", (e) => { upload(e.target.files); e.target.value = ""; });
- $("#pg-run").addEventListener("click", run);
- $("#pg-stop").addEventListener("click", stop);
- const filesPane = $(".pg-files");
- filesPane.addEventListener("dragover", (e) => {
- if (!e.dataTransfer || Array.prototype.indexOf.call(e.dataTransfer.types, "Files") < 0) return;
- e.preventDefault();
- filesPane.classList.add("drop");
- });
- filesPane.addEventListener("dragleave", (e) => { if (!filesPane.contains(e.relatedTarget)) filesPane.classList.remove("drop"); });
- filesPane.addEventListener("drop", (e) => {
- e.preventDefault();
- filesPane.classList.remove("drop");
- const node = e.target.closest && e.target.closest(".pg-node");
- let dir = null;
- if (node) {
- const p = node.getAttribute("data-path");
- dir = p.endsWith(":/") || (FILES[p] && FILES[p].dir) ? p : parentOf(p);
- }
- if (dir && dir.startsWith("web:/") && dir === "web:/") dir = "web:/Playground";
- upload(e.dataTransfer.files, dir);
- });
- document.addEventListener("keydown", (e) => {
- if (e.target === text || dlg.contains(e.target)) return;
- if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); run(); }
- });
- // ---------- start ----------
- function refreshAll() {
- applyLayout();
- renderTree();
- renderTabs();
- loadEditor();
- updateMode();
- showTab(S.outTab || "response");
- $$(".pg-win").forEach((w) => {
- const name = w.getAttribute("data-win");
- const st = S.layout.wins[name];
- openWin(name, !!(st && st.open));
- });
- }
- async function start() {
- startWorker();
- const [samples, catalog] = await Promise.all([
- fetch(BASE + "samples.json?v=" + VER).then((r) => r.json()).catch(() => []),
- fetch(BASE + "catalog.json?v=" + VER).then((r) => r.json()).catch(() => []),
- loadWorkspace()
- ]);
- SAMPLES = samples || [];
- CATALOG = catalog || [];
- renderSamples();
- takeSnippet();
- refreshAll();
- persist();
- window.addEventListener("hashchange", () => { if (takeSnippet()) refreshAll(); });
- }
- // A "Run" link from a code example: #code=<base64url of the script>.
- function takeSnippet() {
- const m = /[#&]code=([^&]+)/.exec(location.hash);
- if (!m) return false;
- history.replaceState(null, "", location.pathname + location.search);
- try {
- const code = b64urlDecode(m[1]);
- const p = "web:/Playground/snippet.agi";
- flushEditor();
- ensureParents(p);
- FILES[p] = { data: enc.encode(code), mtime: Date.now() };
- if (S.open.indexOf(p) < 0) S.open.push(p);
- S.active = p;
- S.selected = p;
- S.expanded["web:/"] = S.expanded["web:/Playground"] = true;
- persist();
- setTimeout(() => toast("The example is in web/Playground/snippet.agi. Press Run."), 300);
- return true;
- } catch (e) {
- toast("Could not read the example from the link");
- return false;
- }
- }
- start();
- })();
|