WebOrbiton
v1.5.0

AtheraStudio Code

982 lines · 37.2 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var ai = A.ai;
  7. var t = ai.t;
  8. var esc = util.esc;
  9. ​
  10. var MAX_STORED = 400;
  11. var MAX_IMAGES = 4;
  12. var IMAGE_BYTES = 4 * 1024 * 1024;
  13. var AUTOFIX_GAP = 60000;
  14. var HEADING = /^## (user|assistant) · ([^·\n]+?)(?: · ([^·\n]+?))?(?: · ([^·\n]+?))?\s*$/;
  15. ​
  16. var state = {
  17. key: null,
  18. messages: [],
  19. busy: false,
  20. controller: null,
  21. current: null,
  22. images: [],
  23. override: "auto",
  24. lastAuto: 0,
  25. lastAutoSig: ""
  26. };
  27. var root = null;
  28. var list = null;
  29. var input = null;
  30. var sendBtn = null;
  31. var overrideSel = null;
  32. var chips = null;
  33. var totalEl = null;
  34. var offBox = null;
  35. var renderQueued = new Set();
  36. ​
  37. function el(tag, attrs, children) {
  38. return util.el(tag, attrs, children);
  39. }
  40. ​
  41. function uid() {
  42. return "m" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
  43. }
  44. ​
  45. function money(cost, known) {
  46. return known === false ? t("ai.chat.cost_unknown", { cost: ai.budget.format(cost) }) : ai.budget.format(cost);
  47. }
  48. ​
  49. function stamp(ms) {
  50. var d = new Date(ms);
  51. var p = function (n) { return n < 10 ? "0" + n : String(n); };
  52. return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate()) + " " + p(d.getHours()) + ":" + p(d.getMinutes());
  53. }
  54. ​
  55. function shortText(s, n) {
  56. s = String(s == null ? "" : s).replace(/\s+/g, " ").trim();
  57. return s.length > n ? s.slice(0, n) + "…" : s;
  58. }
  59. ​
  60. function reveal(text) {
  61. return ai.redact ? ai.redact.restore(text).text : text;
  62. }
  63. ​
  64. function secretChips(html) {
  65. return html.replace(/«([A-Z]{3,10}_\d{1,5})(?::\s?([^»\n<]{0,80}))?»/g, function (m) {
  66. return "<span class=\"ath-ai-secret\" title=\"" + esc(t("ai.chat.secret_title")) + "\">" + m + "</span>";
  67. });
  68. }
  69. ​
  70. function inline(src) {
  71. return String(src).split(/(`[^`\n]+`)/g).map(function (part) {
  72. if (/^`[^`\n]+`$/.test(part)) {
  73. var code = part.slice(1, -1);
  74. var m = /^([\w./-]+\.(?:html?|php|phtml|css|scss|js|mjs|json|md|sql|svg|xml|txt|htaccess))(?::(\d+))?$/i.exec(code);
  75. if (m && !/^(https?:|\/\/)/.test(code)) {
  76. return "<a href=\"#\" class=\"ath-ai-fileref\" data-path=\"" + esc(m[1]) + "\" data-line=\"" + (m[2] || "") + "\"><code>" + esc(code) + "</code></a>";
  77. }
  78. return "<code>" + esc(code) + "</code>";
  79. }
  80. return secretChips(esc(part))
  81. .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, "<a href=\"$2\" target=\"_blank\" rel=\"noopener noreferrer\">$1</a>")
  82. .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
  83. .replace(/(^|[^*\w])\*([^*\n]+)\*(?![\w*])/g, "$1<em>$2</em>");
  84. }).join("");
  85. }
  86. ​
  87. function cells(line) {
  88. return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map(function (c) { return c.trim(); });
  89. }
  90. ​
  91. function markdown(src) {
  92. var lines = String(src || "").replace(/\r/g, "").split("\n");
  93. var html = [];
  94. var para = [];
  95. var i = 0;
  96. function flush() {
  97. if (!para.length) return;
  98. html.push("<p>" + inline(para.join("\n")).replace(/\n/g, "<br>") + "</p>");
  99. para = [];
  100. }
  101. while (i < lines.length) {
  102. var line = lines[i];
  103. var fence = /^\s*```\s*([\w+#.-]*)\s*$/.exec(line);
  104. if (fence) {
  105. flush();
  106. var code = [];
  107. i++;
  108. while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) { code.push(lines[i]); i++; }
  109. i++;
  110. html.push("<div class=\"ath-ai-code\"><div class=\"ath-ai-code-head\"><span>" + esc(fence[1] || "") + "</span><button type=\"button\" class=\"ath-ai-copy\" data-copy>" + esc(t("ai.chat.copy")) + "</button></div><pre><code>" + esc(code.join("\n")) + "</code></pre></div>");
  111. continue;
  112. }
  113. var h = /^(#{1,4})\s+(.+)$/.exec(line);
  114. if (h) {
  115. flush();
  116. var lvl = Math.min(6, h[1].length + 2);
  117. html.push("<h" + lvl + ">" + inline(h[2]) + "</h" + lvl + ">");
  118. i++;
  119. continue;
  120. }
  121. if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
  122. flush();
  123. var ordered = /^\s*\d/.test(line);
  124. var items = [];
  125. while (i < lines.length && /^\s*([-*+]|\d+[.)])\s+/.test(lines[i])) {
  126. items.push(lines[i].replace(/^\s*([-*+]|\d+[.)])\s+/, "").replace(/^\[([ xX])\]\s*/, function (m, c) { return c === " " ? "☐ " : "☑ "; }));
  127. i++;
  128. }
  129. html.push((ordered ? "<ol>" : "<ul>") + items.map(function (it) { return "<li>" + inline(it) + "</li>"; }).join("") + (ordered ? "</ol>" : "</ul>"));
  130. continue;
  131. }
  132. if (/^>\s?/.test(line)) {
  133. flush();
  134. var quote = [];
  135. while (i < lines.length && /^>\s?/.test(lines[i])) { quote.push(lines[i].replace(/^>\s?/, "")); i++; }
  136. html.push("<blockquote>" + inline(quote.join("\n")).replace(/\n/g, "<br>") + "</blockquote>");
  137. continue;
  138. }
  139. if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
  140. flush();
  141. var head = cells(line);
  142. i += 2;
  143. var rows = [];
  144. while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { rows.push(cells(lines[i])); i++; }
  145. html.push("<div class=\"ath-ai-table\"><table><thead><tr>" + head.map(function (c) { return "<th>" + inline(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
  146. rows.map(function (r) { return "<tr>" + r.map(function (c) { return "<td>" + inline(c) + "</td>"; }).join("") + "</tr>"; }).join("") + "</tbody></table></div>");
  147. continue;
  148. }
  149. if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) {
  150. flush();
  151. html.push("<hr>");
  152. i++;
  153. continue;
  154. }
  155. if (!line.trim()) {
  156. flush();
  157. i++;
  158. continue;
  159. }
  160. para.push(line);
  161. i++;
  162. }
  163. flush();
  164. return html.join("");
  165. }
  166. ​
  167. function storeKey() {
  168. return "ai.chat." + (A.fs.provider ? A.fs.provider.name : "_");
  169. }
  170. ​
  171. function storable(m) {
  172. return {
  173. id: m.id,
  174. role: m.role,
  175. at: m.at,
  176. text: m.text || "",
  177. auto: !!m.auto,
  178. attachments: m.attachments || [],
  179. blocks: (m.blocks || []).map(function (b) {
  180. return b.k === "text" ? { k: "text", text: b.text } : { k: "row", icon: b.icon, text: b.text, tone: b.tone, detail: b.detail || "", change: b.change || null, undone: !!b.undone };
  181. }),
  182. meta: m.meta || {},
  183. failed: !!m.failed,
  184. local: !!m.local
  185. };
  186. }
  187. ​
  188. var saveSoon = util.debounce(function () { save().catch(function (e) { console.warn(e); }); }, 500);
  189. ​
  190. async function save() {
  191. if (!state.key) return;
  192. await A.idb.set(state.key, state.messages.filter(function (m) { return !m.pending; }).slice(-MAX_STORED).map(storable));
  193. }
  194. ​
  195. function toMarkdown(messages) {
  196. var name = ai.name();
  197. var out = ["# " + t("ai.chat.md_title", { project: A.fs.provider ? A.fs.provider.name : "" }), ""];
  198. messages.forEach(function (m) {
  199. var head = "## " + m.role + " · " + stamp(m.at);
  200. if (m.role === "assistant") head += " · " + (m.meta && m.meta.model || name) + " · " + (m.meta && m.meta.cost != null ? ai.budget.format(m.meta.cost) : "-");
  201. out.push(head, "");
  202. var text = m.role === "assistant" ? assistantText(m) : m.text;
  203. out.push(String(text || "").replace(/^## (user|assistant) · /gm, "\\## $1 · ").trim(), "");
  204. });
  205. return out.join("\n");
  206. }
  207. ​
  208. function parseMarkdown(text) {
  209. var msgs = [];
  210. var cur = null;
  211. String(text || "").replace(/\r/g, "").split("\n").forEach(function (line) {
  212. var m = HEADING.exec(line);
  213. if (m) {
  214. if (cur) msgs.push(cur);
  215. var at = Date.parse(m[2].trim().replace(" ", "T"));
  216. cur = { id: uid(), role: m[1], at: isNaN(at) ? Date.now() : at, text: "", blocks: [], meta: {}, lines: [] };
  217. if (m[1] === "assistant" && m[3]) cur.meta.model = m[3].trim();
  218. return;
  219. }
  220. if (cur) cur.lines.push(line.replace(/^\\## (user|assistant) · /, "## $1 · "));
  221. });
  222. if (cur) msgs.push(cur);
  223. return msgs.map(function (m) {
  224. var body = m.lines.join("\n").trim();
  225. delete m.lines;
  226. if (m.role === "assistant") m.blocks = [{ k: "text", text: body }];
  227. m.text = body;
  228. return m;
  229. }).filter(function (m) { return m.text; });
  230. }
  231. ​
  232. function assistantText(m) {
  233. var parts = (m.blocks || []).filter(function (b) { return b.k === "text" && b.text.trim(); }).map(function (b) { return b.text.trim(); });
  234. return parts.length ? parts.join("\n\n") : m.text || "";
  235. }
  236. ​
  237. async function syncFile() {
  238. if (!ai.get("conversation.sync") || !A.fs.provider) return;
  239. var keep = ai.get("conversation.keep");
  240. var msgs = state.messages.filter(function (m) { return !m.pending && !m.failed && !m.local && (m.role === "user" || assistantText(m)); }).slice(-keep);
  241. if (!msgs.length) return;
  242. if (!(await ai.private.exists("Conversation.md")) && !(await ai.private.ensure())) {
  243. ai.set("conversation.sync", false);
  244. A.ui.toast(ai.t("ai.chat.sync_off"), "info");
  245. return;
  246. }
  247. await ai.private.write("Conversation.md", toMarkdown(msgs));
  248. }
  249. ​
  250. async function load() {
  251. var key = storeKey();
  252. state.key = key;
  253. var stored = await A.idb.get(key);
  254. if (state.key !== key) return;
  255. var msgs = Array.isArray(stored) ? stored : [];
  256. if (!msgs.length && A.fs.provider) {
  257. try {
  258. var md = await ai.private.read("Conversation.md");
  259. if (md) msgs = parseMarkdown(md);
  260. } catch (e) { msgs = []; }
  261. }
  262. if (state.key !== key) return;
  263. state.messages = msgs;
  264. renderAll();
  265. }
  266. ​
  267. function historyFor() {
  268. var keep = ai.get("conversation.keep");
  269. var src = state.messages.filter(function (m) { return !m.pending && !m.failed && !m.local; }).slice(-keep);
  270. var out = [];
  271. src.forEach(function (m) {
  272. var text = m.role === "assistant" ? assistantText(m) : m.text;
  273. if (!text || !text.trim()) return;
  274. var last = out[out.length - 1];
  275. if (last && last.role === m.role) last.content[0].text += "\n\n" + text;
  276. else out.push({ role: m.role, content: [{ type: "text", text: text }] });
  277. });
  278. while (out.length && out[0].role !== "user") out.shift();
  279. return out;
  280. }
  281. ​
  282. function overrideValue() {
  283. var v = overrideSel ? overrideSel.value : "auto";
  284. if (v === "auto") return null;
  285. if (v.indexOf("m:") === 0) {
  286. var p = v.slice(2).split("|");
  287. return { provider: p[0], model: p.slice(1).join("|") };
  288. }
  289. return { role: v };
  290. }
  291. ​
  292. function fillOverride() {
  293. if (!overrideSel) return;
  294. var current = overrideSel.value || state.override;
  295. overrideSel.innerHTML = "";
  296. overrideSel.appendChild(el("option", { value: "auto" }, t("ai.chat.model_auto")));
  297. var roles = el("optgroup", { label: t("ai.chat.model_roles") });
  298. ai.ROLES.forEach(function (r) { roles.appendChild(el("option", { value: r }, t("ai.role." + r))); });
  299. overrideSel.appendChild(roles);
  300. var models = el("optgroup", { label: t("ai.chat.model_models") });
  301. var seen = {};
  302. ai.models().forEach(function (m) {
  303. var v = "m:" + m.provider + "|" + m.model;
  304. if (!m.model || seen[v]) return;
  305. seen[v] = true;
  306. models.appendChild(el("option", { value: v }, m.model + " · " + ai.providerLabel(m.provider)));
  307. });
  308. if (models.children.length) overrideSel.appendChild(models);
  309. overrideSel.value = Array.prototype.some.call(overrideSel.options, function (o) { return o.value === current; }) ? current : "auto";
  310. }
  311. ​
  312. function toolIcon(name) {
  313. if (/^preview_screenshot/.test(name)) return "eye";
  314. if (/^preview_/.test(name)) return "device";
  315. if (/search/.test(name)) return "search";
  316. if (/^(create|edit|overwrite|copy)_file/.test(name)) return "pencil";
  317. if (/^(delete)_file/.test(name)) return "trash";
  318. if (/^move_file/.test(name)) return "arrowRight";
  319. if (/crawl|fetch/.test(name)) return "globe";
  320. return "file";
  321. }
  322. ​
  323. function argOf(input) {
  324. input = input || {};
  325. var v = input.path || input.from || input.selector || input.query || input.url || input.preset || input.dir || "";
  326. if (input.to) v += " → " + input.to;
  327. return shortText(v, 80);
  328. }
  329. ​
  330. function addRow(msg, icon, text, tone, extra) {
  331. var row = Object.assign({ k: "row", icon: icon, text: text, tone: tone || "muted" }, extra || {});
  332. msg.blocks.push(row);
  333. msg.textBlock = null;
  334. return row;
  335. }
  336. ​
  337. function onEvent(msg, e) {
  338. switch (e.type) {
  339. case "route":
  340. msg.meta.model = e.decision.model;
  341. msg.meta.provider = e.decision.provider;
  342. msg.meta.role = e.decision.role;
  343. addRow(msg, "sparkles", e.text, e.decision.notices.length ? "warn" : "muted");
  344. break;
  345. case "estimate":
  346. addRow(msg, "coins", t("ai.chat.estimate", { cost: money(e.cost, e.known), up: money(e.upTo, e.known) }), "muted");
  347. break;
  348. case "compacting":
  349. addRow(msg, "collapse", t("ai.chat.compacting"), "muted");
  350. break;
  351. case "call":
  352. msg.textBlock = null;
  353. break;
  354. case "text":
  355. if (!msg.textBlock) {
  356. msg.textBlock = { k: "text", text: "" };
  357. msg.blocks.push(msg.textBlock);
  358. }
  359. msg.textBlock.text += e.delta;
  360. msg.thinking = false;
  361. break;
  362. case "thinking":
  363. msg.thinking = true;
  364. break;
  365. case "tool_run":
  366. addRow(msg, toolIcon(e.name), t("ai.chat.tool", { name: e.name, arg: argOf(e.input) }), "tool", { toolId: e.id });
  367. break;
  368. case "tool_result":
  369. var row = msg.blocks.filter(function (b) { return b.toolId === e.id; }).pop();
  370. if (row) {
  371. row.tone = e.isError ? "danger" : "ok";
  372. if (e.isError) row.detail = shortText(e.content, 240);
  373. }
  374. break;
  375. case "status":
  376. var s = e.status || {};
  377. if (s.type === "search") addRow(msg, "search", t("ai.chat.searching", { query: shortText(s.query, 100) }), "muted");
  378. else if (s.type === "fetch") addRow(msg, "globe", t("ai.chat.fetching", { url: shortText(s.url, 100) }), "muted");
  379. else if (s.type === "fallback") addRow(msg, "refresh", t("ai.chat.fallback", { from: s.from || "", to: s.to || "" }), "warn");
  380. break;
  381. case "usage":
  382. if (e.result && e.result.model) msg.meta.model = e.result.model;
  383. break;
  384. case "notice":
  385. addRow(msg, "info", t(e.key, e.params || {}), /refusal|truncated|limit|fix_stop|fix_off/.test(e.key) ? "warn" : e.key === "ai.viewer.check_ok" ? "ok" : "muted");
  386. break;
  387. case "check_start":
  388. addRow(msg, "eye", t("ai.chat.checking"), "muted");
  389. break;
  390. case "check":
  391. if (e.problems.length) addRow(msg, "warning", t("ai.chat.check_found", { n: e.problems.length }), "warn", { detail: e.problems.slice(0, 6).join("\n") });
  392. break;
  393. case "quality":
  394. addRow(msg, "shield", e.problems.length ? t("ai.chat.quality_found", { n: e.problems.length }) : t("ai.chat.quality_ok"), e.problems.length ? "warn" : "ok", e.problems.length ? { detail: e.problems.slice(0, 12).map(function (p) { return p.path + ":" + p.line + " " + p.message; }).join("\n") } : null);
  395. break;
  396. case "autofix":
  397. addRow(msg, "wand", t("ai.chat.autofix_step", { n: e.iteration, max: e.max }), "warn");
  398. break;
  399. case "done":
  400. msg.meta.cost = e.cost;
  401. msg.meta.known = e.known;
  402. msg.meta.usage = e.usage;
  403. msg.meta.calls = e.calls;
  404. break;
  405. case "error":
  406. addRow(msg, "warning", e.message, "danger");
  407. if (e.code === "locked") msg.meta.locked = true;
  408. break;
  409. case "aborted":
  410. addRow(msg, "x", t("ai.chat.aborted", { cost: ai.budget.format(e.cost || 0) }), "warn");
  411. break;
  412. }
  413. queueRender(msg);
  414. }
  415. ​
  416. A.on("ai-run", function (e) {
  417. if (e.state === "start" && state.busy && state.current && !state.current.runId) state.current.runId = e.runId;
  418. });
  419. ​
  420. var reported = new Set();
  421. ​
  422. A.on("ai-redacted", function (e) {
  423. var msg = state.current;
  424. if (!state.busy || !msg || !e || !e.items || e.kind === "ghost") return;
  425. var fresh = e.items.filter(function (it) { return !reported.has(it.id); });
  426. if (!fresh.length) return;
  427. fresh.forEach(function (it) { reported.add(it.id); });
  428. addRow(msg, "shield", t("ai.chat.redacted", { list: ai.redact.summary(fresh) }), "muted", {
  429. detail: fresh.map(function (it) { return "«" + it.id + (it.label ? ": " + it.label : "") + "» " + it.sample + (it.path ? " · " + it.path + ":" + it.line : ""); }).join("\n")
  430. });
  431. queueRender(msg);
  432. });
  433. ​
  434. A.on("ai-change", function (ev) {
  435. var msg = state.current;
  436. var rec = ev && ev.record;
  437. if (!msg || !rec || (msg.runId && rec.runId !== msg.runId)) return;
  438. var stats = "";
  439. if (rec.before != null || rec.after != null) {
  440. var lines = ai.tools.diffLines(rec.before, rec.after);
  441. var add = 0, del = 0;
  442. lines.forEach(function (l) { if (l.t === "+") add++; else if (l.t === "-") del++; });
  443. if (rec.op !== "move") stats = " (+" + add + " −" + del + ")";
  444. }
  445. addRow(msg, "check", t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" }) + stats, "change", { change: rec.id });
  446. queueRender(msg);
  447. });
  448. ​
  449. function queueRender(msg) {
  450. renderQueued.add(msg);
  451. if (renderQueued.size > 1) return;
  452. requestAnimationFrame(function () {
  453. var stick = nearBottom();
  454. renderQueued.forEach(function (m) { updateNode(m); });
  455. renderQueued.clear();
  456. if (stick) scrollBottom();
  457. });
  458. }
  459. ​
  460. function nearBottom() {
  461. return !list || list.scrollHeight - list.scrollTop - list.clientHeight < 80;
  462. }
  463. ​
  464. function scrollBottom() {
  465. if (list) list.scrollTop = list.scrollHeight;
  466. }
  467. ​
  468. function blockNode(msg, b) {
  469. if (b.k === "text") return el("div", { class: "ath-ai-md", html: markdown(b.text) });
  470. var node = el("div", { class: "ath-ai-ev is-" + (b.tone || "muted") + (b.undone ? " is-undone" : "") }, [
  471. el("span", { class: "ath-ai-ev-icon", html: A.icon(b.tone === "ok" && b.icon !== "check" ? b.icon : b.icon) }),
  472. el("span", { class: "ath-ai-ev-text" }, b.text)
  473. ]);
  474. if (b.tone === "tool" && msg.pending) node.appendChild(el("span", { class: "ath-ai-ev-spin" }));
  475. if (b.change) {
  476. var actions = el("span", { class: "ath-ai-ev-actions" }, [
  477. el("button", { type: "button", class: "ath-icon-btn", title: t("ai.changes.show_diff"), "aria-label": t("ai.changes.show_diff"), html: A.icon("eye"), onclick: function () { showDiff(b.change); } }),
  478. b.undone ? null : el("button", { type: "button", class: "ath-icon-btn", title: t("ai.change.undo"), "aria-label": t("ai.change.undo"), html: A.icon("undo"), onclick: function () {
  479. ai.tools.undo(b.change).then(function (done) {
  480. if (!done) return;
  481. b.undone = true;
  482. updateNode(msg);
  483. saveSoon();
  484. }).catch(fail);
  485. } })
  486. ]);
  487. node.appendChild(actions);
  488. }
  489. if (b.detail) {
  490. var wrap = el("details", { class: "ath-ai-ev-detail" }, [el("summary", {}, t("ai.chat.details")), el("pre", {}, b.detail)]);
  491. return el("div", {}, [node, wrap]);
  492. }
  493. return node;
  494. }
  495. ​
  496. async function showDiff(id) {
  497. var rec = (await ai.tools.snapshots()).find(function (s) { return s.id === id; });
  498. if (!rec) return A.ui.toast(t("ai.chat.diff_gone"), "info");
  499. A.ui.dialog({
  500. title: t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" }),
  501. size: "lg",
  502. body: ai.tools.diffView(rec.before, rec.after),
  503. actions: [{ label: A.t("common.close"), value: null, kind: "secondary" }]
  504. });
  505. }
  506. ​
  507. function fail(e) {
  508. if (e && e.name === "AbortError") return;
  509. console.error(e);
  510. A.ui.toast(e && e.message ? e.message : String(e), "danger");
  511. }
  512. ​
  513. function metaLine(msg) {
  514. var m = msg.meta || {};
  515. var parts = [];
  516. if (m.model) parts.push(m.model + (m.role ? " · " + t("ai.role." + m.role) : ""));
  517. if (m.cost != null) parts.push(money(m.cost, m.known));
  518. if (m.usage) {
  519. var u = m.usage;
  520. var prompt = u.input + u.cacheRead + u.cacheWrite;
  521. parts.push(t("ai.chat.tokens", { input: prompt.toLocaleString(), output: u.output.toLocaleString(), cache: prompt ? Math.round((u.cacheRead / prompt) * 100) : 0 }));
  522. }
  523. return parts.join(" · ");
  524. }
  525. ​
  526. function updateNode(msg) {
  527. if (!msg.node) return;
  528. var node = msg.node;
  529. node.className = "ath-ai-msg is-" + msg.role + (msg.pending ? " is-pending" : "") + (msg.auto ? " is-auto" : "");
  530. node.innerHTML = "";
  531. var who = msg.role === "user" ? t(msg.auto ? "ai.chat.auto_label" : "ai.chat.you") : ai.name();
  532. var head = el("div", { class: "ath-ai-msg-head" }, [
  533. el("span", { class: "ath-ai-msg-who" }, who),
  534. el("span", { class: "ath-ai-msg-meta" }, msg.role === "assistant" ? metaLine(msg) : stamp(msg.at)),
  535. msg.role === "assistant" && !msg.pending && assistantText(msg) ? el("button", {
  536. type: "button",
  537. class: "ath-icon-btn",
  538. title: t("ai.chat.copy_message"),
  539. "aria-label": t("ai.chat.copy_message"),
  540. html: A.icon("copy"),
  541. onclick: function () { A.ui.copyText(reveal(assistantText(msg))).then(function () { A.ui.toast(t("ai.chat.copied"), "success"); }); }
  542. }) : null
  543. ]);
  544. node.appendChild(head);
  545. var body = el("div", { class: "ath-ai-msg-body" });
  546. if (msg.role === "user") {
  547. body.appendChild(el("div", { class: "ath-ai-md", html: markdown(msg.text) }));
  548. if (msg.attachments && msg.attachments.length) {
  549. body.appendChild(el("div", { class: "ath-ai-attach" }, msg.attachments.map(function (a) { return el("span", { class: "ath-ai-chip-static" }, a); })));
  550. }
  551. } else {
  552. (msg.blocks || []).forEach(function (b) { body.appendChild(blockNode(msg, b)); });
  553. if (msg.pending) body.appendChild(el("div", { class: "ath-ai-typing" }, [el("span"), el("span"), el("span"), el("small", {}, msg.thinking ? t("ai.chat.thinking") : "")]));
  554. }
  555. node.appendChild(body);
  556. }
  557. ​
  558. function messageNode(msg) {
  559. msg.node = el("div", { class: "ath-ai-msg" });
  560. updateNode(msg);
  561. return msg.node;
  562. }
  563. ​
  564. function emptyState() {
  565. var examples = ["ai.chat.example_1", "ai.chat.example_2", "ai.chat.example_3"];
  566. return el("div", { class: "ath-ai-empty" }, [
  567. el("span", { class: "ath-ai-empty-logo", html: A.icon("sparkles") }),
  568. el("p", { class: "ath-ai-empty-title" }, t("ai.chat.empty_title")),
  569. el("p", { class: "ath-ai-empty-text" }, t("ai.chat.empty_text")),
  570. el("div", { class: "ath-ai-examples" }, examples.map(function (k) {
  571. return el("button", { type: "button", class: "ath-ai-example", onclick: function () { input.value = t(k); input.focus(); autosize(); } }, t(k));
  572. }))
  573. ]);
  574. }
  575. ​
  576. function renderAll() {
  577. if (!list) return;
  578. list.innerHTML = "";
  579. if (!state.messages.length) list.appendChild(emptyState());
  580. state.messages.forEach(function (m) { list.appendChild(messageNode(m)); });
  581. scrollBottom();
  582. syncControls();
  583. }
  584. ​
  585. function autosize() {
  586. if (!input) return;
  587. input.style.height = "auto";
  588. input.style.height = Math.min(220, input.scrollHeight + 2) + "px";
  589. }
  590. ​
  591. function renderChips() {
  592. if (!chips) return;
  593. chips.innerHTML = "";
  594. var picked = ai.viewer && ai.viewer.picked();
  595. if (picked) {
  596. chips.appendChild(el("span", { class: "ath-ai-chip" }, [
  597. el("span", { html: A.icon("target") }),
  598. el("span", {}, t("ai.chat.picked", { selector: shortText(picked.info.selector, 40) })),
  599. el("button", { type: "button", "aria-label": A.t("common.delete"), title: A.t("common.delete"), html: A.icon("x"), onclick: function () { ai.viewer.clearPicked(); } })
  600. ]));
  601. }
  602. state.images.forEach(function (img, i) {
  603. chips.appendChild(el("span", { class: "ath-ai-chip" }, [
  604. el("img", { src: "data:" + img.mime + ";base64," + img.data, alt: "" }),
  605. el("span", {}, shortText(img.name, 24)),
  606. el("button", { type: "button", "aria-label": A.t("common.delete"), title: A.t("common.delete"), html: A.icon("x"), onclick: function () { state.images.splice(i, 1); renderChips(); } })
  607. ]));
  608. });
  609. chips.hidden = !chips.children.length;
  610. }
  611. ​
  612. function syncControls() {
  613. if (!root) return;
  614. var on = ai.enabled();
  615. offBox.hidden = on;
  616. sendBtn.innerHTML = A.icon(state.busy ? "x" : "arrowRight") + "<span>" + esc(t(state.busy ? "ai.chat.stop" : "ai.chat.send")) + "</span>";
  617. sendBtn.classList.toggle("orb-btn-danger", state.busy);
  618. sendBtn.classList.toggle("orb-btn-primary", !state.busy);
  619. input.placeholder = t("ai.chat.placeholder");
  620. updateTotal();
  621. }
  622. ​
  623. function updateTotal() {
  624. if (!totalEl) return;
  625. var s = ai.budget.session();
  626. totalEl.textContent = t("ai.chat.session_total", { cost: ai.budget.format(s.cost) });
  627. }
  628. ​
  629. function readImage(file) {
  630. return new Promise(function (resolve) {
  631. if (!/^image\/(png|jpeg|webp|gif)$/.test(file.type) || file.size > IMAGE_BYTES) return resolve(null);
  632. var r = new FileReader();
  633. r.onload = function () {
  634. var url = String(r.result);
  635. resolve({ mime: file.type, data: url.slice(url.indexOf(",") + 1), name: file.name || "image" });
  636. };
  637. r.onerror = function () { resolve(null); };
  638. r.readAsDataURL(file);
  639. });
  640. }
  641. ​
  642. async function addImages(files) {
  643. for (var f of files) {
  644. if (state.images.length >= MAX_IMAGES) break;
  645. var img = await readImage(f);
  646. if (img) state.images.push(img);
  647. else A.ui.toast(t("ai.chat.image_rejected", { name: f.name || "image" }), "warning");
  648. }
  649. renderChips();
  650. }
  651. ​
  652. function build() {
  653. list = el("div", { class: "ath-ai-chat-list", role: "log", "aria-live": "polite" });
  654. input = el("textarea", { class: "ath-ai-chat-input", rows: 2, spellcheck: "true", "aria-label": t("ai.chat.placeholder") });
  655. sendBtn = el("button", { type: "button", class: "orb-btn orb-btn-sm orb-btn-primary ath-ai-send" });
  656. overrideSel = el("select", { class: "orb-select ath-ai-override", title: t("ai.chat.model_title"), "aria-label": t("ai.chat.model_title") });
  657. chips = el("div", { class: "ath-ai-chips", hidden: true });
  658. totalEl = el("span", { class: "ath-ai-total" });
  659. offBox = el("div", { class: "ath-ai-chat-off" }, [
  660. el("span", {}, t("ai.chat.off")),
  661. el("button", { type: "button", class: "orb-btn orb-btn-sm orb-btn-primary", onclick: function () { ai.enable().catch(fail); } }, t("ai.ov.enable"))
  662. ]);
  663. var pickBtn = el("button", { type: "button", class: "ath-icon-btn", title: t("ai.viewer.pick"), "aria-label": t("ai.viewer.pick"), html: A.icon("target"), onclick: function () {
  664. if (!ai.allowed("preview")) return A.ui.toast(ai.t("ai.viewer.err_perm"), "info");
  665. ai.viewer.pick().catch(fail);
  666. } });
  667. var newBtn = el("button", { type: "button", class: "ath-icon-btn", title: t("ai.chat.new"), "aria-label": t("ai.chat.new"), html: A.icon("filePlus"), onclick: newChat });
  668. suggest.box = el("div", { class: "ath-ai-suggest", role: "listbox", hidden: true });
  669. root = el("div", { class: "ath-ai-chat" }, [
  670. offBox,
  671. list,
  672. el("div", { class: "ath-ai-composer" }, [
  673. suggest.box,
  674. chips,
  675. input,
  676. el("div", { class: "ath-ai-composer-bar" }, [overrideSel, totalEl, el("span", { class: "ath-ai-spacer" }), newBtn, pickBtn, sendBtn])
  677. ])
  678. ]);
  679. sendBtn.addEventListener("click", function () {
  680. if (state.busy) stop();
  681. else submit();
  682. });
  683. input.addEventListener("keydown", function (e) {
  684. if (!suggest.box || suggest.box.hidden || !suggest.items.length) return;
  685. if (e.key === "ArrowDown" || e.key === "ArrowUp") {
  686. e.preventDefault();
  687. e.stopImmediatePropagation();
  688. suggest.index = (suggest.index + (e.key === "ArrowDown" ? 1 : -1) + suggest.items.length) % suggest.items.length;
  689. renderSuggest();
  690. } else if (e.key === "Enter" || e.key === "Tab") {
  691. e.preventDefault();
  692. e.stopImmediatePropagation();
  693. applySuggest(suggest.index);
  694. } else if (e.key === "Escape") {
  695. e.preventDefault();
  696. e.stopImmediatePropagation();
  697. closeSuggest();
  698. }
  699. });
  700. input.addEventListener("input", function () { updateSuggest().catch(function () { }); });
  701. input.addEventListener("blur", function () { setTimeout(closeSuggest, 150); });
  702. input.addEventListener("keydown", function (e) {
  703. if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
  704. e.preventDefault();
  705. if (!state.busy) submit();
  706. } else if (e.key === "Escape" && state.busy) {
  707. e.preventDefault();
  708. e.stopPropagation();
  709. stop();
  710. }
  711. });
  712. input.addEventListener("input", autosize);
  713. input.addEventListener("paste", function (e) {
  714. var files = Array.prototype.filter.call((e.clipboardData && e.clipboardData.files) || [], function (f) { return /^image\//.test(f.type); });
  715. if (!files.length) return;
  716. e.preventDefault();
  717. addImages(files);
  718. });
  719. root.addEventListener("dragover", function (e) {
  720. if (e.dataTransfer && Array.prototype.some.call(e.dataTransfer.types, function (x) { return x === "Files"; })) e.preventDefault();
  721. });
  722. root.addEventListener("drop", function (e) {
  723. var files = Array.prototype.filter.call((e.dataTransfer && e.dataTransfer.files) || [], function (f) { return /^image\//.test(f.type); });
  724. if (!files.length) return;
  725. e.preventDefault();
  726. e.stopPropagation();
  727. e.athHandled = true;
  728. addImages(files);
  729. });
  730. list.addEventListener("click", function (e) {
  731. var copy = e.target.closest("[data-copy]");
  732. if (copy) {
  733. var code = copy.closest(".ath-ai-code").querySelector("code").textContent;
  734. A.ui.copyText(reveal(code)).then(function () { A.ui.toast(t("ai.chat.copied"), "success"); });
  735. return;
  736. }
  737. var ref = e.target.closest(".ath-ai-fileref");
  738. if (ref) {
  739. e.preventDefault();
  740. openRef(ref.getAttribute("data-path"), Number(ref.getAttribute("data-line")) || 0);
  741. }
  742. });
  743. fillOverride();
  744. renderChips();
  745. renderAll();
  746. }
  747. ​
  748. async function openRef(path, line) {
  749. if (!A.fs.provider) return;
  750. try { path = ai.tools.cleanPath(path); } catch (e) { return; }
  751. if (!(await ai.tools.io.exists(path))) return A.ui.toast(A.t("preview.page_not_found", { path: path }), "info");
  752. var tab = await A.tabs.openPath(path);
  753. if (tab && tab.kind === "text" && line) requestAnimationFrame(function () { A.editor.goTo(line, 1); });
  754. }
  755. ​
  756. function newChat() {
  757. if (state.busy) return;
  758. if (!state.messages.length) return;
  759. A.ui.confirm(t("ai.chat.new"), t("ai.chat.new_confirm"), t("ai.chat.new"), false).then(function (ok) {
  760. if (!ok) return;
  761. state.messages = [];
  762. renderAll();
  763. saveSoon();
  764. });
  765. }
  766. ​
  767. function localReply(text, markdownText) {
  768. var user = { id: uid(), role: "user", at: Date.now(), text: text, blocks: [], meta: {}, local: true };
  769. var reply = { id: uid(), role: "assistant", at: Date.now(), text: markdownText, blocks: [{ k: "text", text: markdownText }], meta: { model: t("ai.chat.local") }, local: true };
  770. var empty = list && list.querySelector(".ath-ai-empty");
  771. if (empty) empty.remove();
  772. state.messages.push(user, reply);
  773. if (list) {
  774. list.appendChild(messageNode(user));
  775. list.appendChild(messageNode(reply));
  776. scrollBottom();
  777. }
  778. if (input) {
  779. input.value = "";
  780. autosize();
  781. }
  782. saveSoon();
  783. }
  784. ​
  785. var suggest = { box: null, items: [], index: 0 };
  786. ​
  787. function closeSuggest() {
  788. if (!suggest.box) return;
  789. suggest.box.hidden = true;
  790. suggest.items = [];
  791. }
  792. ​
  793. function applySuggest(i) {
  794. var item = suggest.items[i];
  795. if (!item) return;
  796. input.value = "/" + item.name + " ";
  797. closeSuggest();
  798. input.focus();
  799. autosize();
  800. }
  801. ​
  802. function renderSuggest() {
  803. suggest.box.innerHTML = "";
  804. suggest.items.forEach(function (item, i) {
  805. suggest.box.appendChild(el("button", {
  806. type: "button",
  807. class: "ath-ai-suggest-item" + (i === suggest.index ? " is-active" : ""),
  808. onmousedown: function (e) { e.preventDefault(); applySuggest(i); }
  809. }, [el("code", {}, "/" + item.name), el("span", {}, item.description)]));
  810. });
  811. suggest.box.hidden = !suggest.items.length;
  812. }
  813. ​
  814. async function updateSuggest() {
  815. if (!ai.commands || !suggest.box) return;
  816. var v = input.value;
  817. if (!/^\/[a-z0-9-]*$/i.test(v)) return closeSuggest();
  818. var items = await ai.commands.suggestions(v);
  819. if (input.value !== v) return;
  820. suggest.items = items.slice(0, 9);
  821. suggest.index = 0;
  822. renderSuggest();
  823. }
  824. ​
  825. function stop() {
  826. if (state.controller) state.controller.abort();
  827. }
  828. ​
  829. function submit() {
  830. var text = input.value;
  831. if (!text.trim() && !state.images.length) return;
  832. send(text).catch(fail);
  833. }
  834. ​
  835. async function send(text, opts) {
  836. opts = opts || {};
  837. if (state.busy) return false;
  838. text = String(text || "").trim();
  839. if (!ai.enabled()) {
  840. if (!(await ai.enable())) return false;
  841. }
  842. if (!state.key) await load();
  843. var command = null;
  844. if (/^\/[a-z0-9-]/i.test(text) && ai.commands) {
  845. command = await ai.commands.resolve(text);
  846. if (command && command.error) {
  847. A.ui.toast(command.error, "warning");
  848. return false;
  849. }
  850. if (command && command.local) {
  851. localReply(text, command.text);
  852. return true;
  853. }
  854. }
  855. var parsed = command ? { text: command.text, override: command.override || null } : ai.router.parseOverride(text);
  856. var override = parsed.override || overrideValue();
  857. var attachments = [];
  858. var picked = ai.viewer && ai.viewer.picked();
  859. if (picked) attachments.push(t("ai.chat.picked", { selector: shortText(picked.info.selector, 40) }));
  860. state.images.forEach(function (img) { attachments.push(t("ai.chat.image_label", { name: shortText(img.name, 30) })); });
  861. var history = historyFor();
  862. var user = { id: uid(), role: "user", at: Date.now(), text: text, auto: !!opts.auto, attachments: attachments, blocks: [], meta: {} };
  863. var msg = { id: uid(), role: "assistant", at: Date.now(), text: "", blocks: [], meta: {}, pending: true };
  864. var empty = list && list.querySelector(".ath-ai-empty");
  865. if (empty) empty.remove();
  866. state.messages.push(user, msg);
  867. if (list) {
  868. list.appendChild(messageNode(user));
  869. list.appendChild(messageNode(msg));
  870. scrollBottom();
  871. }
  872. if (!opts.auto && input) {
  873. input.value = "";
  874. autosize();
  875. }
  876. var images = state.images.slice();
  877. state.images = [];
  878. renderChips();
  879. state.busy = true;
  880. state.current = msg;
  881. state.controller = new AbortController();
  882. syncControls();
  883. A.emit("ai-chat-busy", true);
  884. try {
  885. var res = await ai.agent.run({
  886. text: parsed.text,
  887. history: history,
  888. override: override,
  889. images: images,
  890. extra: (opts.extra || []).concat(command ? command.extra : []),
  891. purpose: opts.purpose || (command && command.purpose) || null,
  892. readOnly: !!(command && command.readOnly),
  893. signal: state.controller.signal,
  894. onEvent: function (e) { onEvent(msg, e); }
  895. });
  896. msg.text = res.text;
  897. msg.runId = res.runId;
  898. } catch (e) {
  899. if (e.name !== "AbortError") {
  900. msg.failed = !assistantText(msg);
  901. if (!msg.blocks.some(function (b) { return b.tone === "danger"; })) addRow(msg, "warning", e.message || String(e), "danger");
  902. } else {
  903. msg.failed = !assistantText(msg);
  904. }
  905. } finally {
  906. msg.pending = false;
  907. msg.thinking = false;
  908. state.busy = false;
  909. state.current = null;
  910. state.controller = null;
  911. updateNode(msg);
  912. syncControls();
  913. A.emit("ai-chat-busy", false);
  914. saveSoon();
  915. syncFile().catch(function (err) { console.warn(err); });
  916. }
  917. return true;
  918. }
  919. ​
  920. A.on("ai-autofix", function (e) {
  921. if (!ai.get("preview.autoFix") || state.busy || !ai.enabled() || !ai.allowed("preview")) return;
  922. if (ai.agent.busy()) return;
  923. var sig = (e.errors || []).join("|");
  924. if (Date.now() - state.lastAuto < AUTOFIX_GAP || sig === state.lastAutoSig) return;
  925. state.lastAuto = Date.now();
  926. state.lastAutoSig = sig;
  927. if (A.aiUi && !A.aiUi.isOpen()) A.aiUi.open("chat");
  928. send(t("ai.chat.autofix_msg"), { auto: true, purpose: "fix" }).catch(fail);
  929. });
  930. ​
  931. A.on("ai-picked", renderChips);
  932. A.on("ai-usage", updateTotal);
  933. A.on("ai-config", function (path) {
  934. if (path === "models" || path === "mode") fillOverride();
  935. if (path === "enabled" || path === "consent") syncControls();
  936. });
  937. A.on("ai-name", function () { if (list) renderAll(); });
  938. A.on("lang", function () {
  939. if (!root) return;
  940. var parent = root.parentNode;
  941. root = null;
  942. build();
  943. if (parent) parent.appendChild(root);
  944. });
  945. A.on("workspace", function () {
  946. if (state.busy) stop();
  947. reported.clear();
  948. state.key = null;
  949. state.messages = [];
  950. load().catch(function (e) { console.warn(e); });
  951. });
  952. ​
  953. A.aiUi.section({
  954. id: "chat",
  955. order: 5,
  956. icon: "chat",
  957. label: "ai.sec.chat",
  958. full: true,
  959. render: function (box) {
  960. if (!root) build();
  961. if (!state.key) load().catch(function (e) { console.warn(e); });
  962. box.appendChild(root);
  963. syncControls();
  964. setTimeout(function () {
  965. scrollBottom();
  966. if (input && !state.busy && A.aiUi.wantsFocus()) input.focus({ preventScroll: true });
  967. }, 0);
  968. }
  969. });
  970. ​
  971. ai.chat = {
  972. send: send,
  973. stop: stop,
  974. busy: function () { return state.busy; },
  975. messages: function () { return state.messages.map(storable); },
  976. markdown: markdown,
  977. toMarkdown: toMarkdown,
  978. parseMarkdown: parseMarkdown,
  979. reload: load
  980. };
  981. })();
  982. ​