playground.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. /*
  2. The AGI playground page. The engine (the real Otto interpreter and the AGI
  3. libraries, compiled to WebAssembly from scripts/agidocgen/playground) runs
  4. in playground/worker.js; this file keeps the workspace (files, request,
  5. user, mock answers, stored state) in IndexedDB, edits it and shows what a
  6. run returns.
  7. */
  8. (function () {
  9. "use strict";
  10. const pg = document.getElementById("pg");
  11. if (!pg) return;
  12. const ROOT = document.body.getAttribute("data-root") || "";
  13. const VER = document.body.getAttribute("data-ver") || "";
  14. const BASE = ROOT + "playground/";
  15. const $ = (sel, el) => (el || pg).querySelector(sel);
  16. const $$ = (sel, el) => Array.prototype.slice.call((el || pg).querySelectorAll(sel));
  17. const enc = new TextEncoder();
  18. const dec = new TextDecoder("utf-8");
  19. const ROOTS = [
  20. { id: "web", path: "web:/", label: "web", note: "WebApp folder" },
  21. { id: "user", path: "user:/", label: "user:/", note: "" },
  22. { id: "tmp", path: "tmp:/", label: "tmp:/", note: "" }
  23. ];
  24. const TEXT_EXT = /\.(agi|js|json|txt|md|csv|tsv|html?|css|xml|svg|log|ini|ya?ml|conf|sql)$/i;
  25. // Otto reports "Line 4:5" for syntax errors and "<anonymous>:4:5" in stacks.
  26. const ERR_LINE = /(?:Line |<anonymous>:)(\d+):(\d+)/;
  27. const IMG_EXT = /\.(png|jpe?g|gif|webp|svg|bmp|ico)$/i;
  28. // ---------- small helpers ----------
  29. function icon(name) {
  30. const src = document.querySelector('#pg-icons [data-i="' + name + '"]');
  31. return src ? src.innerHTML : "";
  32. }
  33. function el(tag, attrs, children) {
  34. const e = document.createElement(tag);
  35. if (attrs) for (const k in attrs) {
  36. if (k === "class") e.className = attrs[k];
  37. else if (k === "html") e.innerHTML = attrs[k];
  38. else if (k === "text") e.textContent = attrs[k];
  39. else if (k.startsWith("on")) e.addEventListener(k.slice(2), attrs[k]);
  40. else if (attrs[k] !== undefined && attrs[k] !== null && attrs[k] !== false) e.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
  41. }
  42. (children || []).forEach((c) => { if (c != null) e.append(c); });
  43. return e;
  44. }
  45. function toast(msg) {
  46. if (window.AGIDocs && AGIDocs.toast) AGIDocs.toast(msg);
  47. }
  48. function esc(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
  49. function clone(o) { return JSON.parse(JSON.stringify(o)); }
  50. function parentOf(p) {
  51. const i = p.indexOf(":/");
  52. const rel = p.slice(i + 2);
  53. if (!rel) return null;
  54. const j = rel.lastIndexOf("/");
  55. return j < 0 ? p.slice(0, i + 2) : p.slice(0, i + 2) + rel.slice(0, j);
  56. }
  57. function baseName(p) {
  58. if (p.endsWith(":/")) return p;
  59. return p.slice(p.lastIndexOf("/") + 1);
  60. }
  61. function join(dir, name) { return dir.endsWith("/") ? dir + name : dir + "/" + name; }
  62. function fmtSize(n) {
  63. if (n < 1024) return n + " B";
  64. if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0) + " KB";
  65. return (n / 1048576).toFixed(1) + " MB";
  66. }
  67. function getPath(obj, path) {
  68. return path.split(".").reduce((o, k) => (o == null ? undefined : o[k]), obj);
  69. }
  70. function setPath(obj, path, v) {
  71. const ks = path.split(".");
  72. let o = obj;
  73. for (let i = 0; i < ks.length - 1; i++) { if (o[ks[i]] == null) o[ks[i]] = {}; o = o[ks[i]]; }
  74. o[ks[ks.length - 1]] = v;
  75. }
  76. function b64urlDecode(s) {
  77. s = s.replace(/-/g, "+").replace(/_/g, "/");
  78. while (s.length % 4) s += "=";
  79. const bin = atob(s);
  80. const bytes = new Uint8Array(bin.length);
  81. for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
  82. return dec.decode(bytes);
  83. }
  84. function toB64(bytes) {
  85. let s = "";
  86. for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
  87. return btoa(s);
  88. }
  89. function fromB64(s) {
  90. const bin = atob(s);
  91. const out = new Uint8Array(bin.length);
  92. for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  93. return out;
  94. }
  95. function isText(path, data) {
  96. if (TEXT_EXT.test(path)) return true;
  97. if (IMG_EXT.test(path)) return false;
  98. if (!data) return true;
  99. const n = Math.min(data.length, 2048);
  100. for (let i = 0; i < n; i++) if (data[i] === 0) return false;
  101. return true;
  102. }
  103. function langOf(path) {
  104. if (/\.(agi|js)$/i.test(path)) return "js";
  105. if (/\.json$/i.test(path)) return "json";
  106. if (/\.(html?|xml|svg)$/i.test(path)) return "html";
  107. return "text";
  108. }
  109. function debounce(fn, ms) {
  110. let t;
  111. return function () { clearTimeout(t); t = setTimeout(fn, ms); };
  112. }
  113. // ---------- in-page dialogs ----------
  114. const dlg = $("#pg-dialog");
  115. function dialog(message, opts) {
  116. opts = opts || {};
  117. return new Promise((resolve) => {
  118. $(".pg-dialog-msg", dlg).textContent = message;
  119. const input = $(".pg-dialog-input", dlg);
  120. input.hidden = opts.input === undefined;
  121. input.value = opts.input || "";
  122. const ok = $("[data-ok]", dlg);
  123. ok.textContent = opts.ok || "OK";
  124. $("[data-cancel]", dlg).hidden = !!opts.alert;
  125. dlg.hidden = false;
  126. (input.hidden ? ok : input).focus();
  127. if (!input.hidden) input.select();
  128. function done(v) {
  129. dlg.hidden = true;
  130. dlg.removeEventListener("keydown", onKey);
  131. $("form", dlg).onsubmit = null;
  132. $("[data-cancel]", dlg).onclick = null;
  133. resolve(v);
  134. }
  135. function onKey(e) { if (e.key === "Escape") done(null); }
  136. dlg.addEventListener("keydown", onKey);
  137. $("form", dlg).onsubmit = (e) => { e.preventDefault(); done(input.hidden ? true : input.value.trim()); };
  138. $("[data-cancel]", dlg).onclick = () => done(null);
  139. });
  140. }
  141. // ---------- storage ----------
  142. let idbP = null;
  143. function idb() {
  144. if (!idbP) idbP = new Promise((resolve, reject) => {
  145. const r = indexedDB.open("aroz-agi-playground", 1);
  146. r.onupgradeneeded = () => r.result.createObjectStore("kv");
  147. r.onsuccess = () => resolve(r.result);
  148. r.onerror = () => reject(r.error);
  149. });
  150. return idbP;
  151. }
  152. function kv(mode, key, value) {
  153. return idb().then((db) => new Promise((resolve, reject) => {
  154. const tx = db.transaction("kv", mode === "get" ? "readonly" : "readwrite");
  155. const st = tx.objectStore("kv");
  156. const r = mode === "get" ? st.get(key) : mode === "del" ? st.delete(key) : st.put(value, key);
  157. r.onsuccess = () => resolve(r.result);
  158. r.onerror = () => reject(r.error);
  159. }));
  160. }
  161. // ---------- workspace ----------
  162. function defaultMocks() {
  163. return {
  164. http: {
  165. fallback: "error",
  166. rules: [
  167. { 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 },
  168. { on: true, method: "POST", url: "https://api.example.com/echo", status: 201, headersText: "", body: '{"received": {{body}}}', base64: false, error: "", delayMs: 0 }
  169. ]
  170. },
  171. 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 },
  172. cnn: { responses: {}, error: "" },
  173. sqlite: [{ fn: "query", match: "FROM notes", result: '[{"id": 1, "title": "First note"}, {"id": 2, "title": "Second note"}]' }],
  174. sysinfo: { cpu: "", ram: "", network: "", disks: "" },
  175. generic: {},
  176. ws: { refuse: false, script: [{ afterMs: 300, text: "hello" }, { afterMs: 500, text: "ping" }], closeAfterMs: 1500 },
  177. schedulerDenied: false
  178. };
  179. }
  180. function defaultSettings() {
  181. return {
  182. open: ["web:/Playground/main.agi"],
  183. active: "web:/Playground/main.agi",
  184. selected: "web:/Playground",
  185. expanded: { "web:/": true, "web:/Playground": true, "user:/": true, "user:/Documents": true, "tmp:/": true },
  186. request: { method: "POST", bodyType: "form", form: [["name", "World"]], query: [], body: '{"name": "World"}', timeoutSec: 30 },
  187. user: { username: "developer", admin: true, quotaMB: "" },
  188. mocks: defaultMocks(),
  189. state: {},
  190. layout: { outW: null, wins: {} },
  191. outTab: "response"
  192. };
  193. }
  194. const MAIN_AGI = [
  195. "/*",
  196. " Welcome to the AGI playground.",
  197. " This file is web/Playground/main.agi: a WebApp backend script.",
  198. " Press Run (Ctrl+Enter). Load more from Samples.",
  199. "*/",
  200. 'requirelib("filelib");',
  201. "",
  202. "// POST fields are global variables (set them in the Request window).",
  203. 'var who = (typeof name !== "undefined") ? name : "stranger";',
  204. "",
  205. 'var files = filelib.glob("user:/Documents/*");',
  206. 'console.log("Found " + files.length + " files for " + USERNAME);',
  207. "",
  208. "sendJSONResp({",
  209. ' greeting: "Hello, " + who + "!",',
  210. " user: USERNAME,",
  211. " documents: files",
  212. "});",
  213. ""
  214. ].join("\n");
  215. function picture(type, w, h, label) {
  216. return new Promise((resolve) => {
  217. const c = document.createElement("canvas");
  218. c.width = w; c.height = h;
  219. const x = c.getContext("2d");
  220. const g = x.createLinearGradient(0, 0, w, h);
  221. g.addColorStop(0, "#0071e3"); g.addColorStop(0.55, "#8e5cff"); g.addColorStop(1, "#e8508f");
  222. x.fillStyle = g; x.fillRect(0, 0, w, h);
  223. x.fillStyle = "rgba(255,255,255,0.9)";
  224. x.font = "600 " + Math.round(h / 5) + "px -apple-system, Segoe UI, sans-serif";
  225. x.textAlign = "center"; x.textBaseline = "middle";
  226. x.fillText(label || "AGI", w / 2, h / 2);
  227. c.toBlob((b) => b.arrayBuffer().then((ab) => resolve(new Uint8Array(ab))), type, 0.9);
  228. });
  229. }
  230. async function defaultFiles() {
  231. const now = Date.now();
  232. const t = (s) => ({ data: enc.encode(s), mtime: now });
  233. const files = {
  234. "web:/Playground": { dir: true, mtime: now },
  235. "web:/Playground/main.agi": t(MAIN_AGI),
  236. "web:/Playground/lib": { dir: true, mtime: now },
  237. "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'),
  238. "user:/Desktop": { dir: true, mtime: now },
  239. "user:/Desktop/hello.txt": t("Hello from the playground drive.\n"),
  240. "user:/Documents": { dir: true, mtime: now },
  241. "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"),
  242. "user:/Documents/data.json": t('{\n "project": "ArozOS",\n "tags": ["nas", "desktop", "agi"],\n "stars": 1200\n}\n'),
  243. "user:/Documents/scores.csv": t("name,score\nAmy,92\nBen,85\nChloe,78\n"),
  244. "user:/Photo": { dir: true, mtime: now }
  245. };
  246. files["user:/Photo/gradient.png"] = { data: await picture("image/png", 320, 200, "AGI"), mtime: now };
  247. files["user:/Photo/sunset.jpg"] = { data: await picture("image/jpeg", 640, 400, "Sunset"), mtime: now };
  248. return files;
  249. }
  250. const S = {}; // settings (persisted)
  251. let FILES = {}; // path -> {dir, data, mtime}
  252. let SAMPLES = [];
  253. let CATALOG = [];
  254. let DEFAULTS = { cnn: {} };
  255. let last = null; // last run result
  256. let changedPaths = {};
  257. const persist = debounce(() => {
  258. kv("put", "workspace", { v: 1, files: FILES, settings: S }).catch(() => {});
  259. }, 300);
  260. async function loadWorkspace() {
  261. let saved = null;
  262. try { saved = await kv("get", "workspace"); } catch (e) { /* private mode */ }
  263. Object.assign(S, defaultSettings());
  264. if (saved && saved.files && saved.settings) {
  265. FILES = saved.files;
  266. const d = defaultSettings();
  267. Object.assign(S, saved.settings);
  268. S.request = Object.assign(d.request, S.request);
  269. S.user = Object.assign(d.user, S.user);
  270. S.mocks = Object.assign(d.mocks, S.mocks);
  271. S.layout = Object.assign(d.layout, S.layout);
  272. } else {
  273. FILES = await defaultFiles();
  274. }
  275. }
  276. // ---------- engine ----------
  277. let worker = null;
  278. let ready = false;
  279. let running = false;
  280. function setStatus(state, text) {
  281. pg.setAttribute("data-state", state);
  282. $("#pg-status-text").textContent = text;
  283. }
  284. function startWorker() {
  285. ready = false;
  286. $("#pg-run").disabled = true;
  287. try {
  288. worker = new Worker(BASE + "worker.js?v=" + VER);
  289. } catch (e) {
  290. setStatus("failed", "This browser cannot start the engine: " + e.message);
  291. return;
  292. }
  293. worker.onmessage = (e) => onWorker(e.data);
  294. worker.onerror = (e) => {
  295. setStatus("failed", "The engine did not start: " + (e.message || "worker error") + ". Was the site built with -nowasm?");
  296. };
  297. }
  298. function onWorker(m) {
  299. if (m.type === "ready") {
  300. ready = true;
  301. DEFAULTS = m.defaults || DEFAULTS;
  302. $("#pg-run").disabled = false;
  303. setStatus("ready", "Ready");
  304. renderCNN();
  305. } else if (m.type === "fail") {
  306. setStatus("failed", "The engine did not load (" + m.message + "). Build the docs without -nowasm to include playground/agi.wasm.");
  307. } else if (m.type === "event") {
  308. const p = JSON.parse(m.payload);
  309. if (m.kind === "log") addConsole(p, true);
  310. if (m.kind === "ws") addWS(p, true);
  311. } else if (m.type === "done") {
  312. finishRun(JSON.parse(m.json), m.files);
  313. }
  314. }
  315. function genericCatalog() {
  316. const out = {};
  317. CATALOG.forEach((lib) => {
  318. if (lib.play === "Services" && lib.load && lib.id !== "sqlite" && lib.id !== "sysinfo") {
  319. const names = [];
  320. lib.fns.forEach((f) => f.names.forEach((n) => { if (n.indexOf(lib.id + ".") === 0) names.push(n); }));
  321. out[lib.id] = names;
  322. }
  323. });
  324. return out;
  325. }
  326. function parseHeaders(text) {
  327. const h = {};
  328. (text || "").split("\n").forEach((line) => {
  329. const i = line.indexOf(":");
  330. if (i > 0) h[line.slice(0, i).trim()] = line.slice(i + 1).trim();
  331. });
  332. return h;
  333. }
  334. function buildMocks() {
  335. const m = S.mocks;
  336. const num = (v) => (v === "" || v == null || isNaN(+v) ? 0 : +v);
  337. return {
  338. http: {
  339. fallback: m.http.fallback,
  340. rules: m.http.rules.filter((r) => r.on !== false).map((r, i) => ({
  341. name: "rule " + (i + 1) + " (" + (r.method || "ANY") + " " + r.url + ")",
  342. method: r.method, url: r.url, status: num(r.status), headers: parseHeaders(r.headersText),
  343. body: r.body, base64: !!r.base64, error: r.error, delayMs: num(r.delayMs)
  344. }))
  345. },
  346. llm: {
  347. mode: m.llm.mode, reply: m.llm.reply, reasoning: m.llm.reasoning, rules: m.llm.rules, error: m.llm.error,
  348. model: m.llm.model, models: (m.llm.modelsText || "").split(",").map((s) => s.trim()).filter(Boolean),
  349. chunkSize: num(m.llm.chunkSize), chunkDelayMs: num(m.llm.chunkDelayMs)
  350. },
  351. cnn: { responses: m.cnn.responses, error: m.cnn.error },
  352. sqlite: m.sqlite, sysinfo: m.sysinfo, generic: m.generic,
  353. ws: { refuse: !!m.ws.refuse, script: m.ws.script.map((f) => ({ afterMs: num(f.afterMs), text: f.text })), closeAfterMs: num(m.ws.closeAfterMs) },
  354. schedulerDenied: !!m.schedulerDenied
  355. };
  356. }
  357. function pairs(list) {
  358. const o = {};
  359. (list || []).forEach((p) => { if (p[0]) o[p[0]] = p[1] || ""; });
  360. return o;
  361. }
  362. function runnable(path) { return /\.(agi|js)$/i.test(path || "") && FILES[path] && !FILES[path].dir; }
  363. function run() {
  364. if (!ready || running) return;
  365. flushEditor();
  366. const script = S.active;
  367. if (!runnable(script)) {
  368. toast("Open a .agi or .js file to run it");
  369. return;
  370. }
  371. const r = S.request;
  372. const json = r.bodyType === "json";
  373. const req = {
  374. script: script,
  375. code: dec.decode(FILES[script].data),
  376. method: r.method,
  377. query: pairs(r.query),
  378. form: json ? {} : pairs(r.form),
  379. body: json ? r.body : "",
  380. contentType: json ? "application/json" : "application/x-www-form-urlencoded",
  381. 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) },
  382. state: S.state || {},
  383. mocks: buildMocks(),
  384. timeoutSec: +r.timeoutSec || 30,
  385. catalog: genericCatalog()
  386. };
  387. const files = [];
  388. Object.keys(FILES).forEach((p) => {
  389. const f = FILES[p];
  390. files.push({ path: p, dir: !!f.dir, data: f.dir ? null : f.data, mtime: f.mtime || 0 });
  391. });
  392. running = true;
  393. runStarted = performance.now();
  394. beforeRun = {};
  395. Object.keys(FILES).forEach((p) => { beforeRun[p] = true; });
  396. clearOutput();
  397. $("#pg-run").disabled = true;
  398. $("#pg-stop").hidden = false;
  399. setStatus("running", "Running " + baseName(script));
  400. worker.postMessage({ type: "run", req: req, files: files });
  401. }
  402. let runStarted = 0;
  403. let beforeRun = {};
  404. function stop() {
  405. if (!running) return;
  406. worker.terminate();
  407. running = false;
  408. $("#pg-stop").hidden = true;
  409. wsInputs(false);
  410. 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);
  411. $("#pg-resp").innerHTML = '<p class="pg-hint">Stopped before the script finished. Nothing it wrote was kept.</p>';
  412. setStatus("loading", "Restarting the engine");
  413. startWorker();
  414. }
  415. function finishRun(res, files) {
  416. running = false;
  417. last = res;
  418. $("#pg-stop").hidden = true;
  419. $("#pg-run").disabled = !ready;
  420. wsInputs(false);
  421. changedPaths = {};
  422. (files || []).forEach((f) => {
  423. changedPaths[f.path] = beforeRun[f.path] ? "modified" : "created";
  424. FILES[f.path] = f.dir ? { dir: true, mtime: f.mtime } : { data: f.data, mtime: f.mtime };
  425. });
  426. (res.removed || []).forEach((p) => {
  427. changedPaths[p] = "deleted";
  428. delete FILES[p];
  429. });
  430. if (res.state) S.state = res.state;
  431. S.open = S.open.filter((p) => FILES[p]);
  432. if (S.active && !FILES[S.active]) S.active = S.open[0] || null;
  433. persist();
  434. renderTree();
  435. renderTabs();
  436. loadEditor();
  437. renderOutput(res);
  438. const label = res.error ? (res.error.kind === "timeout" ? "Timed out" : "Failed") : "Finished";
  439. setStatus(res.error ? "failed" : "ready", label + " in " + res.durationMs + " ms · " + res.status + (res.mode === "webapp" ? " · WebApp script" : " · serverless script"));
  440. if (res.error) setTimeout(() => pg.setAttribute("data-state", "ready"), 4000);
  441. }
  442. // ---------- file tree ----------
  443. const tree = $("#pg-tree");
  444. function children(dir) {
  445. const prefix = dir.endsWith("/") ? dir : dir + "/";
  446. return Object.keys(FILES).filter((p) => p.startsWith(prefix) && p !== dir && p.slice(prefix.length).indexOf("/") < 0)
  447. .sort((a, b) => {
  448. const da = FILES[a].dir ? 0 : 1, db = FILES[b].dir ? 0 : 1;
  449. return da - db || a.localeCompare(b, undefined, { numeric: true });
  450. });
  451. }
  452. function renderTree() {
  453. tree.innerHTML = "";
  454. ROOTS.forEach((r) => {
  455. tree.append(treeNode(r.path, 0, r));
  456. if (S.expanded[r.path]) renderChildren(r.path, 1);
  457. });
  458. }
  459. function renderChildren(dir, depth) {
  460. children(dir).forEach((p) => {
  461. tree.append(treeNode(p, depth));
  462. if (FILES[p].dir && S.expanded[p]) renderChildren(p, depth + 1);
  463. });
  464. }
  465. function treeNode(p, depth, root) {
  466. const f = root ? { dir: true } : FILES[p];
  467. const isDir = !!f.dir;
  468. const cls = ["pg-node", isDir ? "dir" : "file"];
  469. if (isDir && S.expanded[p]) cls.push("expanded");
  470. if (S.selected === p) cls.push("sel");
  471. if (S.active === p) cls.push("open-file");
  472. if (changedPaths[p] && changedPaths[p] !== "deleted") cls.push("changed");
  473. const name = root ? root.label : baseName(p);
  474. 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");
  475. const acts = el("span", { class: "acts" });
  476. if (!root) {
  477. if (!isDir) acts.append(el("button", { type: "button", title: "Download", html: icon("download"), onclick: (e) => { e.stopPropagation(); download(p); } }));
  478. acts.append(el("button", { type: "button", title: "Rename", html: icon("rename"), onclick: (e) => { e.stopPropagation(); rename(p); } }));
  479. acts.append(el("button", { type: "button", title: "Delete", html: icon("trash"), onclick: (e) => { e.stopPropagation(); remove(p); } }));
  480. }
  481. const node = el("div", {
  482. class: cls.join(" "), role: "treeitem", "data-path": p, title: p,
  483. "aria-expanded": isDir ? String(!!S.expanded[p]) : null,
  484. style: "padding-left:" + (6 + depth * 14) + "px"
  485. }, [
  486. el("span", { class: "tw", html: isDir ? icon("chevron") : "" }),
  487. el("span", { class: "ic", html: ic }),
  488. el("span", { class: "pg-name", text: name }),
  489. root && root.note ? el("span", { class: "pg-root-label", text: root.note }) : null,
  490. !isDir && f.data ? el("span", { class: "pg-size", text: fmtSize(f.data.length) }) : null,
  491. acts
  492. ]);
  493. node.addEventListener("click", () => {
  494. S.selected = p;
  495. if (isDir) S.expanded[p] = !S.expanded[p];
  496. else openFile(p);
  497. persist();
  498. renderTree();
  499. });
  500. return node;
  501. }
  502. function targetDir() {
  503. const s = S.selected;
  504. if (!s) return "user:/";
  505. if (s.endsWith(":/") || (FILES[s] && FILES[s].dir)) return s;
  506. return parentOf(s) || "user:/";
  507. }
  508. async function newEntry(dir) {
  509. const base = targetDir();
  510. const name = await dialog(dir ? "New folder in " + base : "New file in " + base, { input: dir ? "New folder" : "untitled.agi", ok: "Create" });
  511. if (!name) return;
  512. if (/[\\:]/.test(name) || name.split("/").some((s) => s === ".." || s === ".")) { toast("That name is not allowed"); return; }
  513. const p = join(base, name.replace(/^\/+|\/+$/g, ""));
  514. if (FILES[p]) { toast(baseName(p) + " already exists"); return; }
  515. ensureParents(p);
  516. FILES[p] = dir ? { dir: true, mtime: Date.now() } : { data: new Uint8Array(0), mtime: Date.now() };
  517. S.expanded[base] = true;
  518. S.selected = p;
  519. if (!dir) openFile(p);
  520. persist();
  521. renderTree();
  522. }
  523. function ensureParents(p) {
  524. let d = parentOf(p);
  525. while (d && !d.endsWith(":/")) {
  526. if (!FILES[d]) FILES[d] = { dir: true, mtime: Date.now() };
  527. d = parentOf(d);
  528. }
  529. }
  530. async function rename(p) {
  531. const name = await dialog("Rename " + baseName(p), { input: baseName(p), ok: "Rename" });
  532. if (!name || name === baseName(p)) return;
  533. if (/[\\/:]/.test(name)) { toast("A name cannot contain / \\ or :"); return; }
  534. const np = join(parentOf(p), name);
  535. if (FILES[np]) { toast(name + " already exists"); return; }
  536. Object.keys(FILES).forEach((k) => {
  537. if (k === p || k.startsWith(p + "/")) {
  538. const nk = np + k.slice(p.length);
  539. FILES[nk] = FILES[k];
  540. delete FILES[k];
  541. S.open = S.open.map((o) => (o === k ? nk : o));
  542. if (S.active === k) S.active = nk;
  543. if (S.expanded[k]) { S.expanded[nk] = true; delete S.expanded[k]; }
  544. }
  545. });
  546. S.selected = np;
  547. persist();
  548. renderTree();
  549. renderTabs();
  550. updateMode();
  551. }
  552. async function remove(p) {
  553. const isDir = FILES[p] && FILES[p].dir;
  554. const ok = await dialog("Delete " + p + (isDir ? " and everything in it" : "") + "?", { ok: "Delete" });
  555. if (!ok) return;
  556. Object.keys(FILES).forEach((k) => { if (k === p || k.startsWith(p + "/")) delete FILES[k]; });
  557. S.open = S.open.filter((o) => FILES[o]);
  558. if (!FILES[S.active]) S.active = S.open[0] || null;
  559. if (S.selected === p) S.selected = parentOf(p);
  560. persist();
  561. renderTree();
  562. renderTabs();
  563. loadEditor();
  564. }
  565. function download(p) {
  566. const f = FILES[p];
  567. const url = URL.createObjectURL(new Blob([f.data]));
  568. const a = el("a", { href: url, download: baseName(p) });
  569. document.body.append(a);
  570. a.click();
  571. a.remove();
  572. setTimeout(() => URL.revokeObjectURL(url), 2000);
  573. }
  574. async function upload(fileList, dir) {
  575. dir = dir || targetDir();
  576. let n = 0;
  577. for (const file of Array.from(fileList)) {
  578. if (file.size > 20 * 1048576) { toast(file.name + " is over 20 MB; skipped"); continue; }
  579. const p = join(dir, file.name);
  580. ensureParents(p);
  581. FILES[p] = { data: new Uint8Array(await file.arrayBuffer()), mtime: file.lastModified || Date.now() };
  582. n++;
  583. }
  584. if (!n) return;
  585. S.expanded[dir] = true;
  586. persist();
  587. renderTree();
  588. toast("Uploaded " + n + " file" + (n === 1 ? "" : "s") + " to " + dir);
  589. }
  590. // ---------- editor ----------
  591. const text = $("#pg-text");
  592. const hl = $("#pg-hl");
  593. const gutter = $("#pg-gutter");
  594. let errorLine = 0;
  595. function openFile(p) {
  596. flushEditor();
  597. if (S.open.indexOf(p) < 0) S.open.push(p);
  598. S.active = p;
  599. errorLine = 0;
  600. renderTabs();
  601. loadEditor();
  602. updateMode();
  603. persist();
  604. }
  605. function closeTab(p) {
  606. flushEditor();
  607. const i = S.open.indexOf(p);
  608. if (i < 0) return;
  609. S.open.splice(i, 1);
  610. if (S.active === p) S.active = S.open[Math.min(i, S.open.length - 1)] || null;
  611. renderTabs();
  612. loadEditor();
  613. updateMode();
  614. renderTree();
  615. persist();
  616. }
  617. function renderTabs() {
  618. const tabs = $("#pg-tabs");
  619. tabs.innerHTML = "";
  620. S.open.forEach((p) => {
  621. if (!FILES[p]) return;
  622. const t = el("button", { type: "button", class: "pg-tab", role: "tab", "aria-selected": String(p === S.active), title: p }, [
  623. el("span", { text: baseName(p) }),
  624. el("span", { class: "x", html: icon("close"), title: "Close", onclick: (e) => { e.stopPropagation(); closeTab(p); } })
  625. ]);
  626. t.addEventListener("click", () => openFile(p));
  627. t.addEventListener("auxclick", (e) => { if (e.button === 1) closeTab(p); });
  628. tabs.append(t);
  629. if (p === S.active) requestAnimationFrame(() => t.scrollIntoView({ block: "nearest", inline: "nearest" }));
  630. });
  631. }
  632. let loaded = null; // path shown in the textarea
  633. function loadEditor() {
  634. const p = S.active;
  635. const f = p && FILES[p];
  636. const code = $("#pg-code"), prev = $("#pg-preview"), empty = $("#pg-empty");
  637. code.hidden = prev.hidden = empty.hidden = true;
  638. loaded = null;
  639. if (!f) { empty.hidden = false; return; }
  640. if (isText(p, f.data)) {
  641. code.hidden = false;
  642. const s = dec.decode(f.data || new Uint8Array(0));
  643. if (text.value !== s) text.value = s;
  644. loaded = p;
  645. paint();
  646. return;
  647. }
  648. prev.hidden = false;
  649. prev.innerHTML = "";
  650. if (IMG_EXT.test(p)) {
  651. const url = URL.createObjectURL(new Blob([f.data], { type: /\.svg$/i.test(p) ? "image/svg+xml" : "" }));
  652. const img = el("img", { src: url, alt: baseName(p) });
  653. img.onload = () => {
  654. prev.append(el("p", { class: "pg-size", text: img.naturalWidth + " x " + img.naturalHeight + " · " + fmtSize(f.data.length) }));
  655. };
  656. prev.append(img);
  657. } else {
  658. let hex = "";
  659. 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" : " ");
  660. prev.append(el("div", { class: "pg-bin" }, [el("p", { text: "Binary file · " + fmtSize(f.data.length) }), el("pre", { text: hex })]));
  661. }
  662. }
  663. function paint() {
  664. const p = loaded;
  665. const v = text.value;
  666. hl.innerHTML = window.AGIHL ? AGIHL.highlight(v, langOf(p || "")) + "\n " : esc(v) + "\n ";
  667. const lines = v.split("\n").length;
  668. let g = "";
  669. for (let i = 1; i <= lines; i++) g += i === errorLine ? '<div class="err">' + i + "</div>" : "<div>" + i + "</div>";
  670. gutter.innerHTML = g;
  671. syncScroll();
  672. }
  673. function syncScroll() {
  674. hl.scrollTop = text.scrollTop;
  675. hl.scrollLeft = text.scrollLeft;
  676. gutter.scrollTop = text.scrollTop;
  677. }
  678. function flushEditor() {
  679. if (!loaded || !FILES[loaded]) return;
  680. const data = enc.encode(text.value);
  681. const old = FILES[loaded].data;
  682. if (old && old.length === data.length && old.every((b, i) => b === data[i])) return;
  683. FILES[loaded] = { data: data, mtime: Date.now() };
  684. persist();
  685. }
  686. const saveSoon = debounce(() => { flushEditor(); renderTreeSizes(); }, 400);
  687. function renderTreeSizes() {
  688. const n = tree.querySelector('[data-path="' + CSS.escape(loaded || "") + '"] .pg-size');
  689. if (n && FILES[loaded]) n.textContent = fmtSize(FILES[loaded].data.length);
  690. }
  691. text.addEventListener("input", () => { errorLine = 0; paint(); saveSoon(); });
  692. text.addEventListener("scroll", syncScroll);
  693. text.addEventListener("keydown", (e) => {
  694. const v = text.value, s = text.selectionStart, en = text.selectionEnd;
  695. if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); run(); return; }
  696. if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") { e.preventDefault(); flushEditor(); toast("Saved to the playground drive"); return; }
  697. if ((e.ctrlKey || e.metaKey) && e.key === "/") {
  698. e.preventDefault();
  699. const ls = v.lastIndexOf("\n", s - 1) + 1;
  700. let le = v.indexOf("\n", en - (en > s && v[en - 1] === "\n" ? 1 : 0));
  701. if (le < 0) le = v.length;
  702. const block = v.slice(ls, le).split("\n");
  703. const all = block.every((l) => /^\s*\/\//.test(l) || !l.trim());
  704. const out = block.map((l) => (all ? l.replace(/^(\s*)\/\/ ?/, "$1") : l.trim() ? l.replace(/^(\s*)/, "$1// ") : l)).join("\n");
  705. replaceRange(ls, le, out, ls, ls + out.length);
  706. return;
  707. }
  708. if (e.key === "Tab") {
  709. e.preventDefault();
  710. if (s === en && !e.shiftKey) { replaceRange(s, en, " ", s + 4, s + 4); return; }
  711. const ls = v.lastIndexOf("\n", s - 1) + 1;
  712. const block = v.slice(ls, en).split("\n");
  713. const out = block.map((l) => (e.shiftKey ? l.replace(/^ {1,4}|^\t/, "") : " " + l)).join("\n");
  714. replaceRange(ls, en, out, ls, ls + out.length);
  715. return;
  716. }
  717. if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
  718. e.preventDefault();
  719. const ls = v.lastIndexOf("\n", s - 1) + 1;
  720. const indent = /^[ \t]*/.exec(v.slice(ls, s))[0];
  721. const before = v.slice(0, s).trimEnd();
  722. const extra = /[{[(]$/.test(before) ? " " : "";
  723. const closing = extra && /^[}\])]/.test(v.slice(en).trimStart()) && v.slice(en).trimStart() === v.slice(en).replace(/^[ \t]*/, "");
  724. const ins = "\n" + indent + extra + (closing ? "\n" + indent : "");
  725. replaceRange(s, en, ins, s + 1 + indent.length + extra.length, s + 1 + indent.length + extra.length);
  726. }
  727. });
  728. function replaceRange(a, b, str, selA, selB) {
  729. text.focus();
  730. text.setSelectionRange(a, b);
  731. // execCommand keeps the browser's undo history working.
  732. if (!document.execCommand || !document.execCommand("insertText", false, str)) {
  733. text.setRangeText(str, a, b, "end");
  734. text.dispatchEvent(new Event("input"));
  735. }
  736. text.setSelectionRange(selA, selB);
  737. }
  738. function gotoLine(n) {
  739. const lines = text.value.split("\n");
  740. let pos = 0;
  741. for (let i = 0; i < n - 1 && i < lines.length; i++) pos += lines[i].length + 1;
  742. text.focus();
  743. text.setSelectionRange(pos, pos + (lines[n - 1] || "").length);
  744. const lh = parseFloat(getComputedStyle(text).lineHeight) || 20;
  745. text.scrollTop = Math.max(0, (n - 4) * lh);
  746. syncScroll();
  747. }
  748. function updateMode() {
  749. const p = S.active;
  750. const m = $("#pg-mode");
  751. if (!runnable(p)) { m.innerHTML = "Open a <b>.agi</b> file to run it"; return; }
  752. m.innerHTML = p.startsWith("web:/")
  753. ? "<b>WebApp script</b> · POST fields are globals"
  754. : "<b>Serverless script</b> · getPara / postPara / readBody";
  755. }
  756. // ---------- output ----------
  757. const outPanels = {
  758. console: $("#pg-console"), calls: $("#pg-calls"), changes: $("#pg-changes"), ws: $("#pg-ws-log")
  759. };
  760. outPanels.console.setAttribute("data-empty", "console.log() output and the messages ArozOS would write to its log appear here.");
  761. outPanels.calls.setAttribute("data-empty", "Calls to mocked services (http, llm, cnn, sqlite, ...) and the answers they got appear here.");
  762. outPanels.changes.setAttribute("data-empty", "Files the script creates, changes or deletes appear here.");
  763. outPanels.ws.setAttribute("data-empty", "After websocket.upgrade() the frames both sides send appear here.");
  764. function showTab(name) {
  765. S.outTab = name;
  766. $$(".pg-out-tabs [data-out]").forEach((b) => b.setAttribute("aria-selected", String(b.getAttribute("data-out") === name)));
  767. $$(".pg-out-body [data-panel]").forEach((p) => { p.hidden = p.getAttribute("data-panel") !== name; });
  768. if (name === "state") renderState();
  769. persist();
  770. }
  771. $$(".pg-out-tabs [data-out]").forEach((b) => b.addEventListener("click", () => showTab(b.getAttribute("data-out"))));
  772. function count(name, n, bad) {
  773. const b = $('[data-count="' + name + '"]');
  774. b.textContent = n ? n : "";
  775. b.className = bad ? "err" : "";
  776. }
  777. let consoleN = 0, wsN = 0, consoleBad = false;
  778. function clearOutput() {
  779. Object.keys(outPanels).forEach((k) => { outPanels[k].innerHTML = ""; });
  780. consoleN = wsN = 0;
  781. consoleBad = false;
  782. ["console", "calls", "changes", "ws"].forEach((k) => count(k, 0));
  783. $("#pg-resp-head").innerHTML = "";
  784. $("#pg-resp-view").hidden = true;
  785. $("#pg-resp").innerHTML = '<p class="pg-hint">Running...</p>';
  786. errorLine = 0;
  787. paint();
  788. }
  789. function line(t, cls, src, txt) {
  790. return el("div", { class: "pg-line " + cls }, [
  791. el("span", { class: "t", text: t + " ms" }),
  792. el("span", { class: "txt" }, [src ? el("span", { class: "src", text: src }) : null, document.createTextNode(txt)])
  793. ]);
  794. }
  795. function addConsole(l, live) {
  796. const bad = /Runtime Error|Script error|Failed/.test(l.text);
  797. const node = line(l.t, l.level + (bad ? " error" : ""), l.source === "script" ? "" : "[" + l.source + "]", l.text);
  798. outPanels.console.append(node);
  799. consoleN++;
  800. if (bad || l.level === "error") consoleBad = true;
  801. count("console", consoleN, consoleBad);
  802. if (live) outPanels.console.parentNode.scrollTop = outPanels.console.parentNode.scrollHeight;
  803. }
  804. function addWS(f, live) {
  805. const label = { out: "script ->", in: "-> script", open: "", close: "" }[f.dir];
  806. const cls = f.dir === "out" ? "ws-out" : f.dir === "in" ? "ws-in" : "ws-meta";
  807. outPanels.ws.append(line(f.t, cls, label, f.text));
  808. wsN++;
  809. count("ws", wsN);
  810. if (f.dir === "open" && live) wsInputs(true);
  811. if (f.dir === "close") wsInputs(false);
  812. }
  813. function wsInputs(on) {
  814. $$("#pg-ws-send input, #pg-ws-send button").forEach((x) => { x.disabled = !on; });
  815. }
  816. $("#pg-ws-send").addEventListener("submit", (e) => {
  817. e.preventDefault();
  818. const inp = $("#pg-ws-send input");
  819. if (!running || !inp.value) return;
  820. worker.postMessage({ type: "ws", text: inp.value });
  821. inp.value = "";
  822. });
  823. $('#pg-ws-send [data-act="ws-close"]').addEventListener("click", () => { if (running) worker.postMessage({ type: "wsclose" }); });
  824. function chip(text, cls) { return el("span", { class: "pg-chip " + (cls || ""), text: text }); }
  825. function renderOutput(res) {
  826. // Console and WebSocket were streamed; redraw them from the result so
  827. // the order is exact even if events raced the end of the run.
  828. outPanels.console.innerHTML = "";
  829. consoleN = 0; consoleBad = false;
  830. (res.console || []).forEach((l) => addConsole(l));
  831. count("console", consoleN, consoleBad);
  832. outPanels.ws.innerHTML = "";
  833. wsN = 0;
  834. (res.ws || []).forEach((f) => addWS(f));
  835. count("ws", wsN);
  836. const head = $("#pg-resp-head");
  837. head.innerHTML = "";
  838. head.append(chip(String(res.status), res.status < 400 ? "ok" : "bad"));
  839. head.append(chip(res.exited ? "exit() · type left to the browser" : res.contentType || "text/plain"));
  840. head.append(chip(res.durationMs + " ms"));
  841. if (res.headers && res.headers.Location) head.append(chip("Location: " + res.headers.Location, "warn"));
  842. if (res.upgraded) head.append(chip("WebSocket", "warn"));
  843. if (res.modules && res.modules.length) head.append(chip(res.modules.length + " module registered", "ok"));
  844. if (res.error) {
  845. const m = ERR_LINE.exec(res.error.stack || res.error.message || "");
  846. if (m && res.error.kind !== "timeout") { errorLine = +m[1]; paint(); }
  847. }
  848. renderResponse(res);
  849. // Calls to mocked services
  850. outPanels.calls.innerHTML = "";
  851. (res.calls || []).forEach((c) => {
  852. outPanels.calls.append(el("div", { class: "pg-call" }, [
  853. 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 || "" })]),
  854. c.args ? el("pre", { text: c.args }) : null,
  855. el("pre", { class: "res", text: "-> " + c.result })
  856. ]));
  857. });
  858. count("calls", (res.calls || []).length);
  859. // Changes
  860. outPanels.changes.innerHTML = "";
  861. const keys = Object.keys(changedPaths).sort();
  862. keys.forEach((p) => {
  863. const k = changedPaths[p];
  864. const a = el("a", { text: p, onclick: () => { if (FILES[p] && !FILES[p].dir) { revealPath(p); openFile(p); } } });
  865. outPanels.changes.append(el("div", { class: "pg-change" }, [el("span", { class: "k " + k, text: k }), a,
  866. FILES[p] && FILES[p].data ? el("span", { class: "pg-size", text: fmtSize(FILES[p].data.length) }) : null]));
  867. });
  868. count("changes", keys.length);
  869. if (S.outTab === "state") renderState();
  870. }
  871. let respView = "pretty";
  872. $$("#pg-resp-view button").forEach((b) => b.addEventListener("click", () => {
  873. respView = b.getAttribute("data-view");
  874. $$("#pg-resp-view button").forEach((x) => x.setAttribute("aria-selected", String(x === b)));
  875. if (last) renderResponse(last);
  876. }));
  877. // renderResponse draws the error (if any) and the body of a result.
  878. function renderResponse(res) {
  879. const box = $("#pg-resp");
  880. box.innerHTML = "";
  881. if (res.error) {
  882. const m = ERR_LINE.exec(res.error.stack || res.error.message || "");
  883. const errBox = el("div", { class: "pg-error" }, [
  884. el("strong", { text: res.error.kind === "timeout" ? "Time limit reached" : "Script error" }),
  885. el("pre", { text: res.error.stack || res.error.message })
  886. ]);
  887. if (m && res.error.kind !== "timeout") {
  888. errBox.append(el("button", { type: "button", class: "pg-btn", text: "Go to line " + m[1], onclick: () => gotoLine(+m[1]) }));
  889. }
  890. box.append(errBox);
  891. }
  892. renderBody(res);
  893. }
  894. function renderBody(res) {
  895. const box = $("#pg-resp");
  896. const body = res.response || "";
  897. const ct = (res.contentType || "").toLowerCase();
  898. const sniffHTML = !ct && /^\s*</.test(body);
  899. const isHTML = ct.indexOf("text/html") >= 0 || sniffHTML;
  900. let pretty = null;
  901. $("#pg-resp-view").hidden = !isHTML && !/^data:image\//.test(body);
  902. if (res.upgraded && !body) {
  903. box.append(el("p", { class: "pg-hint", text: "The connection was upgraded to a WebSocket; see the WebSocket tab." }));
  904. return;
  905. }
  906. if (!body) {
  907. if (!res.error) box.append(el("p", { class: "pg-hint", text: "The script sent an empty response." }));
  908. return;
  909. }
  910. if (respView === "pretty") {
  911. if (/^data:image\/[a-z+]+;base64,/.test(body)) {
  912. box.append(el("img", { src: body, alt: "Response image" }));
  913. return;
  914. }
  915. if (isHTML) {
  916. box.append(el("iframe", { sandbox: "", srcdoc: body, title: "HTML response" }));
  917. return;
  918. }
  919. if (ct.indexOf("json") >= 0 || /^\s*[{[]/.test(body)) {
  920. try { pretty = JSON.stringify(JSON.parse(body), null, 2); } catch (e) { pretty = null; }
  921. }
  922. }
  923. const pre = el("pre");
  924. if (pretty != null && window.AGIHL) pre.innerHTML = AGIHL.highlight(pretty, "json");
  925. else pre.textContent = body;
  926. box.append(pre);
  927. }
  928. function revealPath(p) {
  929. let d = parentOf(p);
  930. while (d) { S.expanded[d] = true; d = parentOf(d); }
  931. S.selected = p;
  932. renderTree();
  933. }
  934. function renderState() {
  935. const box = $("#pg-state");
  936. const st = S.state || {};
  937. box.innerHTML = "";
  938. 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." });
  939. box.append(note);
  940. const db = st.db || {};
  941. const tables = Object.keys(db).sort();
  942. box.append(el("h5", { text: "Database tables (" + tables.length + ")" }));
  943. if (!tables.length) box.append(el("p", { text: "No tables yet. newDBTableIfNotExists(\"name\") creates one." }));
  944. tables.forEach((t) => {
  945. const keys = Object.keys(db[t]).sort();
  946. box.append(el("h5", { text: t + " · " + keys.length + " key" + (keys.length === 1 ? "" : "s") }));
  947. if (!keys.length) return;
  948. const tb = el("table", null, [el("tr", null, [el("th", { text: "Key" }), el("th", { text: "Value" })])]);
  949. keys.forEach((k) => tb.append(el("tr", null, [el("td", { text: k }), el("td", { text: db[t][k] })])));
  950. box.append(tb);
  951. });
  952. const list = (title, items, cols) => {
  953. if (!items || !items.length) return;
  954. box.append(el("h5", { text: title + " (" + items.length + ")" }));
  955. const tb = el("table", null, [el("tr", null, cols.map((c) => el("th", { text: c[0] })))]);
  956. items.forEach((it) => tb.append(el("tr", null, cols.map((c) => el("td", { text: String(it[c[1]] == null ? "" : it[c[1]]) })))));
  957. box.append(tb);
  958. };
  959. list("Shares", st.shares, [["UUID", "uuid"], ["File", "vpath"], ["Owner", "owner"]]);
  960. list("Scheduled tasks", st.tasks, [["Name", "name"], ["Every (s)", "interval"], ["Script", "script"]]);
  961. list("Accounts", (st.users || []).map((u) => ({ u: u })), [["Username", "u"]]);
  962. if (st.llmUsage && st.llmUsage.totalRequests) {
  963. box.append(el("h5", { text: "llm usage" }));
  964. box.append(el("p", { text: st.llmUsage.totalRequests + " requests, " + st.llmUsage.totalTokens + " tokens (estimated)" }));
  965. }
  966. if (last && last.notifications && last.notifications.length) list("Notifications sent by the last run", last.notifications, [["To", "to"], ["Title", "title"], ["Message", "message"], ["Priority", "priority"]]);
  967. if (last && last.modules && last.modules.length) {
  968. box.append(el("h5", { text: "registerModule() in the last run" }));
  969. last.modules.forEach((m) => box.append(el("pre", { class: "pg-mono", text: JSON.stringify(m, null, 2) })));
  970. }
  971. }
  972. // ---------- splitter ----------
  973. const split = $("#pg-split");
  974. function applyLayout() {
  975. if (S.layout.outW) pg.style.setProperty("--pg-out-w", S.layout.outW + "px");
  976. }
  977. split.addEventListener("pointerdown", (e) => {
  978. split.setPointerCapture(e.pointerId);
  979. split.classList.add("drag");
  980. const body = $(".pg-body").getBoundingClientRect();
  981. const move = (ev) => {
  982. const w = Math.max(280, Math.min(body.right - ev.clientX, body.width - 520));
  983. S.layout.outW = Math.round(w);
  984. applyLayout();
  985. };
  986. const up = () => {
  987. split.classList.remove("drag");
  988. split.removeEventListener("pointermove", move);
  989. split.removeEventListener("pointerup", up);
  990. persist();
  991. };
  992. split.addEventListener("pointermove", move);
  993. split.addEventListener("pointerup", up);
  994. });
  995. // ---------- tool windows ----------
  996. // Tool windows stack between 61 and 66, under the toolbar menus (80) and
  997. // the dialog (90).
  998. let zOrder = [];
  999. function front(w) {
  1000. zOrder = zOrder.filter((x) => x !== w);
  1001. zOrder.push(w);
  1002. zOrder.forEach((x, i) => { x.style.zIndex = 61 + i; });
  1003. }
  1004. function openWin(name, show) {
  1005. const w = $('.pg-win[data-win="' + name + '"]');
  1006. const btn = $('.pg-wins [data-win="' + name + '"]');
  1007. const open = show === undefined ? w.hidden : show;
  1008. w.hidden = !open;
  1009. btn.setAttribute("aria-pressed", String(open));
  1010. const st = S.layout.wins[name] || (S.layout.wins[name] = {});
  1011. st.open = open;
  1012. if (open) {
  1013. if (st.x != null) {
  1014. w.style.left = Math.max(0, Math.min(st.x, innerWidth - 120)) + "px";
  1015. w.style.top = Math.max(60, Math.min(st.y, innerHeight - 60)) + "px";
  1016. }
  1017. if (st.w) { w.style.width = st.w + "px"; w.style.height = st.h + "px"; }
  1018. front(w);
  1019. renderWin(name);
  1020. }
  1021. persist();
  1022. }
  1023. $$(".pg-wins [data-win]").forEach((b) => b.addEventListener("click", () => openWin(b.getAttribute("data-win"))));
  1024. $$(".pg-win").forEach((w) => {
  1025. const name = w.getAttribute("data-win");
  1026. $("[data-close]", w).addEventListener("click", () => openWin(name, false));
  1027. w.addEventListener("pointerdown", () => front(w));
  1028. const head = $(".pg-win-head", w);
  1029. head.addEventListener("pointerdown", (e) => {
  1030. if (e.target.closest("button")) return;
  1031. const r = w.getBoundingClientRect();
  1032. const dx = e.clientX - r.left, dy = e.clientY - r.top;
  1033. head.setPointerCapture(e.pointerId);
  1034. const move = (ev) => {
  1035. w.style.left = Math.max(0, Math.min(ev.clientX - dx, innerWidth - 80)) + "px";
  1036. w.style.top = Math.max(50, Math.min(ev.clientY - dy, innerHeight - 40)) + "px";
  1037. };
  1038. const up = () => {
  1039. head.removeEventListener("pointermove", move);
  1040. head.removeEventListener("pointerup", up);
  1041. const st = S.layout.wins[name] || (S.layout.wins[name] = {});
  1042. const b = w.getBoundingClientRect();
  1043. st.x = Math.round(b.left); st.y = Math.round(b.top);
  1044. persist();
  1045. };
  1046. head.addEventListener("pointermove", move);
  1047. head.addEventListener("pointerup", up);
  1048. });
  1049. // Remember a resize (the CSS resize handle).
  1050. if (window.ResizeObserver) new ResizeObserver(() => {
  1051. if (w.hidden) return;
  1052. const st = S.layout.wins[name] || (S.layout.wins[name] = {});
  1053. const b = w.getBoundingClientRect();
  1054. if (b.width && (Math.abs((st.w || 0) - b.width) > 2 || Math.abs((st.h || 0) - b.height) > 2) && w.dataset.sized) {
  1055. st.w = Math.round(b.width); st.h = Math.round(b.height);
  1056. persist();
  1057. }
  1058. w.dataset.sized = "1";
  1059. }).observe(w);
  1060. });
  1061. function renderWin(name) {
  1062. const w = $('.pg-win[data-win="' + name + '"]');
  1063. bindAll(w);
  1064. $$("[data-kv]", w).forEach(renderKV);
  1065. $$("[data-rules]", w).forEach(renderRules);
  1066. if (name === "cnn") renderCNN();
  1067. if (name === "services") renderGeneric();
  1068. }
  1069. // data-bind: two-way binding of inputs to the settings.
  1070. function readInput(inp) {
  1071. if (inp.type === "checkbox") return inp.checked;
  1072. if (inp.type === "number") return inp.value === "" ? "" : +inp.value;
  1073. return inp.value;
  1074. }
  1075. function bindAll(scope) {
  1076. $$("[data-bind]", scope).forEach((inp) => {
  1077. const path = inp.getAttribute("data-bind");
  1078. const v = getPath(S, path);
  1079. if (inp.type === "checkbox") inp.checked = !!v;
  1080. else inp.value = v == null ? "" : v;
  1081. if (!inp.dataset.bound) {
  1082. inp.dataset.bound = "1";
  1083. inp.addEventListener(inp.tagName === "SELECT" || inp.type === "checkbox" ? "change" : "input", () => {
  1084. setPath(S, path, readInput(inp));
  1085. applyWhen(scope);
  1086. persist();
  1087. });
  1088. }
  1089. });
  1090. applyWhen(scope);
  1091. }
  1092. function applyWhen(scope) {
  1093. $$("[data-when]", scope).forEach((n) => {
  1094. const m = /^([\w.]+)(!?=)(.*)$/.exec(n.getAttribute("data-when"));
  1095. if (!m) return;
  1096. const v = String(getPath(S, m[1]));
  1097. n.hidden = m[2] === "=" ? v !== m[3] : v === m[3];
  1098. });
  1099. }
  1100. function renderKV(box) {
  1101. const path = box.getAttribute("data-kv");
  1102. let list = getPath(S, path);
  1103. if (!Array.isArray(list)) { list = []; setPath(S, path, list); }
  1104. const draw = () => {
  1105. box.innerHTML = "";
  1106. const rows = list.concat([["", ""]]);
  1107. rows.forEach((pair, i) => {
  1108. const k = el("input", { type: "text", placeholder: "name", value: pair[0] });
  1109. const v = el("input", { type: "text", placeholder: "value", value: pair[1] });
  1110. const x = el("button", { type: "button", class: "pg-icon-btn", title: "Remove", html: icon("close") });
  1111. // Typing in the blank last row adds it and draws a new blank row.
  1112. const upd = () => {
  1113. if (i >= list.length) { list.push([k.value, v.value]); draw(); }
  1114. else list[i] = [k.value, v.value];
  1115. persist();
  1116. };
  1117. k.addEventListener("input", () => { const wasNew = i >= list.length; upd(); if (wasNew) focusKV(box, i, 0, k.value.length); });
  1118. v.addEventListener("input", () => { const wasNew = i >= list.length; upd(); if (wasNew) focusKV(box, i, 1, v.value.length); });
  1119. x.addEventListener("click", () => { if (i < list.length) { list.splice(i, 1); draw(); persist(); } });
  1120. if (i >= list.length) x.style.visibility = "hidden";
  1121. box.append(el("div", { class: "pg-kv-row" }, [k, v, x]));
  1122. });
  1123. };
  1124. draw();
  1125. }
  1126. function focusKV(box, row, col, pos) {
  1127. const inp = box.querySelectorAll(".pg-kv-row")[row].querySelectorAll("input")[col];
  1128. inp.focus();
  1129. inp.setSelectionRange(pos, pos);
  1130. }
  1131. // Rule lists of the HTTP, LLM, WebSocket and sqlite windows.
  1132. const RULES = {
  1133. http: {
  1134. list: () => S.mocks.http.rules,
  1135. blank: () => ({ on: true, method: "GET", url: "https://api.example.com/", status: 200, headersText: "", body: "", base64: false, error: "", delayMs: 0 }),
  1136. empty: "No rules: every request fails.",
  1137. draw: (r) => [
  1138. el("div", { class: "pg-rule-top" }, [
  1139. field(r, "on", "checkbox", { title: "Use this rule" }),
  1140. select(r, "method", ["ANY", "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"]),
  1141. field(r, "url", "text", { placeholder: "https://api.example.com/*", "aria-label": "URL" }),
  1142. field(r, "status", "number", { title: "Status code", "aria-label": "Status" })
  1143. ]),
  1144. labelled("Body", field(r, "body", "textarea", { rows: 3, class: "pg-mono", placeholder: '{"ok": true}' })),
  1145. el("div", { class: "pg-rule-more" }, [
  1146. labelled("Headers (Name: value per line)", field(r, "headersText", "textarea", { rows: 2, class: "pg-mono" })),
  1147. el("div", { class: "pg-field" }, [
  1148. labelled("Fail with error", field(r, "error", "text", { placeholder: "e.g. connection refused" })),
  1149. labelled("Delay (ms)", field(r, "delayMs", "number", {})),
  1150. el("label", { class: "pg-check" }, [field(r, "base64", "checkbox", {}), document.createTextNode("Body is base64 (binary)")])
  1151. ])
  1152. ])
  1153. ]
  1154. },
  1155. llm: {
  1156. list: () => S.mocks.llm.rules,
  1157. blank: () => ({ match: "", reply: "" }),
  1158. empty: "No rules: every prompt gets the reply above.",
  1159. draw: (r) => [
  1160. el("div", { class: "pg-rule-top" }, [field(r, "match", "text", { placeholder: "prompt contains... or /regex/i", "aria-label": "Match" })]),
  1161. field(r, "reply", "textarea", { rows: 2, placeholder: "Reply", "aria-label": "Reply" })
  1162. ]
  1163. },
  1164. ws: {
  1165. list: () => S.mocks.ws.script,
  1166. blank: () => ({ afterMs: 500, text: "" }),
  1167. empty: "The browser sends nothing on its own.",
  1168. draw: (r) => [el("div", { class: "pg-rule-top" }, [
  1169. field(r, "afterMs", "number", { title: "Wait (ms) after the previous frame", "aria-label": "Wait in ms" }),
  1170. field(r, "text", "text", { placeholder: "frame text", "aria-label": "Frame" })
  1171. ])]
  1172. },
  1173. sqlite: {
  1174. list: () => S.mocks.sqlite,
  1175. blank: () => ({ fn: "query", match: "", result: "[]" }),
  1176. empty: "No rules: the defaults answer.",
  1177. draw: (r) => [
  1178. 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" })]),
  1179. field(r, "result", "textarea", { rows: 2, class: "pg-mono", "aria-label": "JSON result" })
  1180. ]
  1181. }
  1182. };
  1183. function field(obj, key, type, attrs) {
  1184. const inp = type === "textarea" ? el("textarea", attrs) : el("input", Object.assign({ type: type }, attrs));
  1185. if (type === "checkbox") inp.checked = key === "on" ? obj[key] !== false : !!obj[key];
  1186. else inp.value = obj[key] == null ? "" : obj[key];
  1187. inp.addEventListener(type === "checkbox" ? "change" : "input", () => {
  1188. obj[key] = readInput(inp);
  1189. if (key === "on") inp.closest(".pg-rule").classList.toggle("off", !inp.checked);
  1190. persist();
  1191. });
  1192. return inp;
  1193. }
  1194. function select(obj, key, options) {
  1195. const s = el("select", { "aria-label": key }, options.map((o) => el("option", { value: o === "ANY" ? "" : o, text: o })));
  1196. s.value = obj[key] || "";
  1197. s.addEventListener("change", () => { obj[key] = s.value; persist(); });
  1198. return s;
  1199. }
  1200. function labelled(text, inp) { return el("label", null, [document.createTextNode(text), inp]); }
  1201. function renderRules(box) {
  1202. const kind = box.getAttribute("data-rules");
  1203. const def = RULES[kind];
  1204. const list = def.list();
  1205. box.setAttribute("data-empty", def.empty);
  1206. box.innerHTML = "";
  1207. list.forEach((r, i) => {
  1208. const del = el("button", { type: "button", class: "pg-icon-btn", title: "Remove", html: icon("trash"), onclick: () => { list.splice(i, 1); renderRules(box); persist(); } });
  1209. const parts = def.draw(r);
  1210. parts[0].append(del);
  1211. box.append(el("div", { class: "pg-rule" + (r.on === false ? " off" : "") }, parts));
  1212. });
  1213. }
  1214. $$("[data-add]").forEach((b) => b.addEventListener("click", () => {
  1215. const kind = b.getAttribute("data-add");
  1216. RULES[kind].list().push(RULES[kind].blank());
  1217. $$('[data-rules="' + kind + '"]').forEach(renderRules);
  1218. persist();
  1219. }));
  1220. // CNN window
  1221. const CNN_FNS = ["classify", "detect", "segment", "pose", "oriented", "faceDetect", "faceLandmarks", "faceEmbedding", "faceAttributes", "faceCompare", "models", "health"];
  1222. const cnnSel = $("#pg-cnn-fn"), cnnText = $("#pg-cnn-json");
  1223. CNN_FNS.forEach((f) => cnnSel.append(el("option", { value: f, text: "cnn." + f + "()" })));
  1224. function renderCNN() {
  1225. const f = cnnSel.value || "classify";
  1226. const own = S.mocks.cnn.responses[f];
  1227. let v = own != null ? own : DEFAULTS.cnn[f] || "";
  1228. if (own == null && v) { try { v = JSON.stringify(JSON.parse(v), null, 2); } catch (e) { /* keep */ } }
  1229. cnnText.value = v;
  1230. jsonState(cnnText, $("#pg-cnn-state"), own == null ? "Default answer" : "");
  1231. }
  1232. function jsonState(ta, out, label) {
  1233. const v = ta.value.trim();
  1234. if (!v) { out.textContent = label || "Empty"; out.className = "pg-json-state"; return true; }
  1235. 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; }
  1236. }
  1237. cnnSel.addEventListener("change", renderCNN);
  1238. cnnText.addEventListener("input", () => {
  1239. S.mocks.cnn.responses[cnnSel.value] = cnnText.value;
  1240. jsonState(cnnText, $("#pg-cnn-state"));
  1241. persist();
  1242. });
  1243. $('[data-act="cnn-default"]').addEventListener("click", () => { delete S.mocks.cnn.responses[cnnSel.value]; renderCNN(); persist(); });
  1244. // Services window: answers of generic mocks
  1245. const genSel = $("#pg-gen-fn"), genText = $("#pg-gen-json");
  1246. function renderGeneric() {
  1247. const cur = genSel.value;
  1248. genSel.innerHTML = "";
  1249. const cat = genericCatalog();
  1250. Object.keys(cat).sort().forEach((lib) => {
  1251. const og = el("optgroup", { label: lib });
  1252. cat[lib].forEach((n) => og.append(el("option", { value: n, text: (S.mocks.generic[n] ? "* " : "") + n + "()" })));
  1253. genSel.append(og);
  1254. });
  1255. if (cur) genSel.value = cur;
  1256. genText.value = S.mocks.generic[genSel.value] || "";
  1257. jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null");
  1258. }
  1259. genSel.addEventListener("change", () => { genText.value = S.mocks.generic[genSel.value] || ""; jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null"); });
  1260. genText.addEventListener("input", () => {
  1261. if (genText.value.trim()) S.mocks.generic[genSel.value] = genText.value;
  1262. else delete S.mocks.generic[genSel.value];
  1263. jsonState(genText, $("#pg-gen-state"), genText.value ? "" : "Returns null");
  1264. const o = genSel.selectedOptions[0];
  1265. if (o) o.textContent = (S.mocks.generic[genSel.value] ? "* " : "") + genSel.value + "()";
  1266. persist();
  1267. });
  1268. // ---------- samples ----------
  1269. function renderSamples() {
  1270. const menu = $(".pg-samples-menu");
  1271. menu.innerHTML = "";
  1272. // Groups in the order they first appear in the numbered files.
  1273. const groups = [];
  1274. SAMPLES.forEach((s) => { if (groups.indexOf(s.group || "") < 0) groups.push(s.group || ""); });
  1275. groups.forEach((g) => {
  1276. menu.append(el("h5", { text: g || "Samples" }));
  1277. SAMPLES.filter((s) => (s.group || "") === g).forEach((s) => {
  1278. menu.append(el("button", { type: "button", role: "menuitem", onclick: () => loadSample(s) }, [document.createTextNode(s.title), el("small", { text: s.summary || "" })]));
  1279. });
  1280. });
  1281. }
  1282. async function loadSample(s) {
  1283. $("#pg-samples").classList.remove("open");
  1284. const existing = FILES[s.path];
  1285. if (existing && !existing.dir && dec.decode(existing.data) !== s.code) {
  1286. const ok = await dialog(s.path + " was changed. Replace it with the sample?", { ok: "Replace" });
  1287. if (!ok) { openFile(s.path); return; }
  1288. }
  1289. ensureParents(s.path);
  1290. FILES[s.path] = { data: enc.encode(s.code), mtime: Date.now() };
  1291. const setup = s.setup || {};
  1292. if (setup.request) {
  1293. const r = setup.request;
  1294. if (r.method) S.request.method = r.method;
  1295. if (r.form) { S.request.bodyType = "form"; S.request.form = Object.keys(r.form).map((k) => [k, String(r.form[k])]); }
  1296. if (r.json) { S.request.bodyType = "json"; S.request.body = JSON.stringify(r.json, null, 2); }
  1297. if (r.query) S.request.query = Object.keys(r.query).map((k) => [k, String(r.query[k])]);
  1298. }
  1299. if (setup.user) Object.assign(S.user, setup.user);
  1300. const m = setup.mocks || {};
  1301. if (m.http && m.http.rules) {
  1302. m.http.rules.slice().reverse().forEach((nr) => {
  1303. const rule = Object.assign(RULES.http.blank(), nr);
  1304. if (nr.headers) rule.headersText = Object.keys(nr.headers).map((k) => k + ": " + nr.headers[k]).join("\n");
  1305. S.mocks.http.rules = S.mocks.http.rules.filter((r) => !(r.url === rule.url && (r.method || "") === (rule.method || "")));
  1306. S.mocks.http.rules.unshift(rule);
  1307. });
  1308. }
  1309. if (m.llm) Object.assign(S.mocks.llm, m.llm);
  1310. if (m.cnn && m.cnn.responses) Object.assign(S.mocks.cnn.responses, m.cnn.responses);
  1311. if (m.ws) Object.assign(S.mocks.ws, m.ws);
  1312. 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)));
  1313. if (m.generic) Object.assign(S.mocks.generic, m.generic);
  1314. for (const f of setup.files || []) {
  1315. if (FILES[f.path]) continue;
  1316. ensureParents(f.path);
  1317. if (f.dir) FILES[f.path] = { dir: true, mtime: Date.now() };
  1318. 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() };
  1319. else FILES[f.path] = { data: enc.encode(f.text || ""), mtime: Date.now() };
  1320. }
  1321. revealPath(s.path);
  1322. openFile(s.path);
  1323. $$(".pg-win").forEach((w) => { if (!w.hidden) renderWin(w.getAttribute("data-win")); });
  1324. persist();
  1325. toast("Loaded the " + s.title + " sample");
  1326. }
  1327. // ---------- menus and actions ----------
  1328. async function exportWorkspace() {
  1329. flushEditor();
  1330. const files = {};
  1331. Object.keys(FILES).forEach((p) => {
  1332. files[p] = FILES[p].dir ? { dir: true } : { b64: toB64(FILES[p].data), mtime: FILES[p].mtime };
  1333. });
  1334. const blob = new Blob([JSON.stringify({ kind: "agi-playground", v: 1, files: files, settings: S }, null, 1)], { type: "application/json" });
  1335. const url = URL.createObjectURL(blob);
  1336. const a = el("a", { href: url, download: "agi-playground.json" });
  1337. document.body.append(a); a.click(); a.remove();
  1338. setTimeout(() => URL.revokeObjectURL(url), 2000);
  1339. }
  1340. async function importWorkspace(file) {
  1341. let data;
  1342. try { data = JSON.parse(await file.text()); } catch (e) { toast("That file is not a playground export"); return; }
  1343. if (!data || data.kind !== "agi-playground" || !data.files) { toast("That file is not a playground export"); return; }
  1344. const ok = await dialog("Replace the current workspace with " + file.name + "?", { ok: "Replace" });
  1345. if (!ok) return;
  1346. FILES = {};
  1347. Object.keys(data.files).forEach((p) => {
  1348. const f = data.files[p];
  1349. FILES[p] = f.dir ? { dir: true, mtime: Date.now() } : { data: fromB64(f.b64 || ""), mtime: f.mtime || Date.now() };
  1350. });
  1351. Object.keys(S).forEach((k) => delete S[k]);
  1352. Object.assign(S, defaultSettings(), data.settings || {});
  1353. refreshAll();
  1354. persist();
  1355. }
  1356. async function resetAll() {
  1357. const ok = await dialog("Reset the playground? Files, settings and the stored database go back to the start.", { ok: "Reset" });
  1358. if (!ok) return;
  1359. try { await kv("del", "workspace"); } catch (e) { /* ignore */ }
  1360. Object.keys(S).forEach((k) => delete S[k]);
  1361. Object.assign(S, defaultSettings());
  1362. FILES = await defaultFiles();
  1363. last = null;
  1364. changedPaths = {};
  1365. refreshAll();
  1366. persist();
  1367. }
  1368. $$("#pg-more [data-act]").forEach((b) => b.addEventListener("click", async () => {
  1369. $("#pg-more").classList.remove("open");
  1370. const act = b.getAttribute("data-act");
  1371. if (act === "export") exportWorkspace();
  1372. if (act === "import") $("#pg-import").click();
  1373. if (act === "reset") resetAll();
  1374. if (act === "clear-state") {
  1375. const ok = await dialog("Clear the stored database tables, shares, scheduled tasks, accounts and llm usage?", { ok: "Clear" });
  1376. if (!ok) return;
  1377. S.state = {};
  1378. persist();
  1379. renderState();
  1380. toast("Stored state cleared");
  1381. }
  1382. }));
  1383. $("#pg-import").addEventListener("change", (e) => { if (e.target.files[0]) importWorkspace(e.target.files[0]); e.target.value = ""; });
  1384. $('[data-act="new-file"]').addEventListener("click", () => newEntry(false));
  1385. $('[data-act="new-folder"]').addEventListener("click", () => newEntry(true));
  1386. $('[data-act="upload"]').addEventListener("click", () => $("#pg-upload").click());
  1387. $("#pg-upload").addEventListener("change", (e) => { upload(e.target.files); e.target.value = ""; });
  1388. $("#pg-run").addEventListener("click", run);
  1389. $("#pg-stop").addEventListener("click", stop);
  1390. const filesPane = $(".pg-files");
  1391. filesPane.addEventListener("dragover", (e) => {
  1392. if (!e.dataTransfer || Array.prototype.indexOf.call(e.dataTransfer.types, "Files") < 0) return;
  1393. e.preventDefault();
  1394. filesPane.classList.add("drop");
  1395. });
  1396. filesPane.addEventListener("dragleave", (e) => { if (!filesPane.contains(e.relatedTarget)) filesPane.classList.remove("drop"); });
  1397. filesPane.addEventListener("drop", (e) => {
  1398. e.preventDefault();
  1399. filesPane.classList.remove("drop");
  1400. const node = e.target.closest && e.target.closest(".pg-node");
  1401. let dir = null;
  1402. if (node) {
  1403. const p = node.getAttribute("data-path");
  1404. dir = p.endsWith(":/") || (FILES[p] && FILES[p].dir) ? p : parentOf(p);
  1405. }
  1406. if (dir && dir.startsWith("web:/") && dir === "web:/") dir = "web:/Playground";
  1407. upload(e.dataTransfer.files, dir);
  1408. });
  1409. document.addEventListener("keydown", (e) => {
  1410. if (e.target === text || dlg.contains(e.target)) return;
  1411. if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); run(); }
  1412. });
  1413. // ---------- start ----------
  1414. function refreshAll() {
  1415. applyLayout();
  1416. renderTree();
  1417. renderTabs();
  1418. loadEditor();
  1419. updateMode();
  1420. showTab(S.outTab || "response");
  1421. $$(".pg-win").forEach((w) => {
  1422. const name = w.getAttribute("data-win");
  1423. const st = S.layout.wins[name];
  1424. openWin(name, !!(st && st.open));
  1425. });
  1426. }
  1427. async function start() {
  1428. startWorker();
  1429. const [samples, catalog] = await Promise.all([
  1430. fetch(BASE + "samples.json?v=" + VER).then((r) => r.json()).catch(() => []),
  1431. fetch(BASE + "catalog.json?v=" + VER).then((r) => r.json()).catch(() => []),
  1432. loadWorkspace()
  1433. ]);
  1434. SAMPLES = samples || [];
  1435. CATALOG = catalog || [];
  1436. renderSamples();
  1437. takeSnippet();
  1438. refreshAll();
  1439. persist();
  1440. window.addEventListener("hashchange", () => { if (takeSnippet()) refreshAll(); });
  1441. }
  1442. // A "Run" link from a code example: #code=<base64url of the script>.
  1443. function takeSnippet() {
  1444. const m = /[#&]code=([^&]+)/.exec(location.hash);
  1445. if (!m) return false;
  1446. history.replaceState(null, "", location.pathname + location.search);
  1447. try {
  1448. const code = b64urlDecode(m[1]);
  1449. const p = "web:/Playground/snippet.agi";
  1450. flushEditor();
  1451. ensureParents(p);
  1452. FILES[p] = { data: enc.encode(code), mtime: Date.now() };
  1453. if (S.open.indexOf(p) < 0) S.open.push(p);
  1454. S.active = p;
  1455. S.selected = p;
  1456. S.expanded["web:/"] = S.expanded["web:/Playground"] = true;
  1457. persist();
  1458. setTimeout(() => toast("The example is in web/Playground/snippet.agi. Press Run."), 300);
  1459. return true;
  1460. } catch (e) {
  1461. toast("Could not read the example from the link");
  1462. return false;
  1463. }
  1464. }
  1465. start();
  1466. })();