v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var ai = A.ai;
- var t = ai.t;
- var esc = util.esc;
-
- var MAX_STORED = 400;
- var MAX_IMAGES = 4;
- var IMAGE_BYTES = 4 * 1024 * 1024;
- var AUTOFIX_GAP = 60000;
- var HEADING = /^## (user|assistant) · ([^·\n]+?)(?: · ([^·\n]+?))?(?: · ([^·\n]+?))?\s*$/;
-
- var state = {
- key: null,
- messages: [],
- busy: false,
- controller: null,
- current: null,
- images: [],
- override: "auto",
- lastAuto: 0,
- lastAutoSig: ""
- };
- var root = null;
- var list = null;
- var input = null;
- var sendBtn = null;
- var overrideSel = null;
- var chips = null;
- var totalEl = null;
- var offBox = null;
- var renderQueued = new Set();
-
- function el(tag, attrs, children) {
- return util.el(tag, attrs, children);
- }
-
- function uid() {
- return "m" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
- }
-
- function money(cost, known) {
- return known === false ? t("ai.chat.cost_unknown", { cost: ai.budget.format(cost) }) : ai.budget.format(cost);
- }
-
- function stamp(ms) {
- var d = new Date(ms);
- var p = function (n) { return n < 10 ? "0" + n : String(n); };
- return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate()) + " " + p(d.getHours()) + ":" + p(d.getMinutes());
- }
-
- function shortText(s, n) {
- s = String(s == null ? "" : s).replace(/\s+/g, " ").trim();
- return s.length > n ? s.slice(0, n) + "…" : s;
- }
-
- function reveal(text) {
- return ai.redact ? ai.redact.restore(text).text : text;
- }
-
- function secretChips(html) {
- return html.replace(/«([A-Z]{3,10}_\d{1,5})(?::\s?([^»\n<]{0,80}))?»/g, function (m) {
- return "<span class=\"ath-ai-secret\" title=\"" + esc(t("ai.chat.secret_title")) + "\">" + m + "</span>";
- });
- }
-
- function inline(src) {
- return String(src).split(/(`[^`\n]+`)/g).map(function (part) {
- if (/^`[^`\n]+`$/.test(part)) {
- var code = part.slice(1, -1);
- var m = /^([\w./-]+\.(?:html?|php|phtml|css|scss|js|mjs|json|md|sql|svg|xml|txt|htaccess))(?::(\d+))?$/i.exec(code);
- if (m && !/^(https?:|\/\/)/.test(code)) {
- return "<a href=\"#\" class=\"ath-ai-fileref\" data-path=\"" + esc(m[1]) + "\" data-line=\"" + (m[2] || "") + "\"><code>" + esc(code) + "</code></a>";
- }
- return "<code>" + esc(code) + "</code>";
- }
- return secretChips(esc(part))
- .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, "<a href=\"$2\" target=\"_blank\" rel=\"noopener noreferrer\">$1</a>")
- .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
- .replace(/(^|[^*\w])\*([^*\n]+)\*(?![\w*])/g, "$1<em>$2</em>");
- }).join("");
- }
-
- function cells(line) {
- return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map(function (c) { return c.trim(); });
- }
-
- function markdown(src) {
- var lines = String(src || "").replace(/\r/g, "").split("\n");
- var html = [];
- var para = [];
- var i = 0;
- function flush() {
- if (!para.length) return;
- html.push("<p>" + inline(para.join("\n")).replace(/\n/g, "<br>") + "</p>");
- para = [];
- }
- while (i < lines.length) {
- var line = lines[i];
- var fence = /^\s*```\s*([\w+#.-]*)\s*$/.exec(line);
- if (fence) {
- flush();
- var code = [];
- i++;
- while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) { code.push(lines[i]); i++; }
- i++;
- 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>");
- continue;
- }
- var h = /^(#{1,4})\s+(.+)$/.exec(line);
- if (h) {
- flush();
- var lvl = Math.min(6, h[1].length + 2);
- html.push("<h" + lvl + ">" + inline(h[2]) + "</h" + lvl + ">");
- i++;
- continue;
- }
- if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
- flush();
- var ordered = /^\s*\d/.test(line);
- var items = [];
- while (i < lines.length && /^\s*([-*+]|\d+[.)])\s+/.test(lines[i])) {
- items.push(lines[i].replace(/^\s*([-*+]|\d+[.)])\s+/, "").replace(/^\[([ xX])\]\s*/, function (m, c) { return c === " " ? "☐ " : "☑ "; }));
- i++;
- }
- html.push((ordered ? "<ol>" : "<ul>") + items.map(function (it) { return "<li>" + inline(it) + "</li>"; }).join("") + (ordered ? "</ol>" : "</ul>"));
- continue;
- }
- if (/^>\s?/.test(line)) {
- flush();
- var quote = [];
- while (i < lines.length && /^>\s?/.test(lines[i])) { quote.push(lines[i].replace(/^>\s?/, "")); i++; }
- html.push("<blockquote>" + inline(quote.join("\n")).replace(/\n/g, "<br>") + "</blockquote>");
- continue;
- }
- if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
- flush();
- var head = cells(line);
- i += 2;
- var rows = [];
- while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { rows.push(cells(lines[i])); i++; }
- html.push("<div class=\"ath-ai-table\"><table><thead><tr>" + head.map(function (c) { return "<th>" + inline(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
- rows.map(function (r) { return "<tr>" + r.map(function (c) { return "<td>" + inline(c) + "</td>"; }).join("") + "</tr>"; }).join("") + "</tbody></table></div>");
- continue;
- }
- if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) {
- flush();
- html.push("<hr>");
- i++;
- continue;
- }
- if (!line.trim()) {
- flush();
- i++;
- continue;
- }
- para.push(line);
- i++;
- }
- flush();
- return html.join("");
- }
-
- function storeKey() {
- return "ai.chat." + (A.fs.provider ? A.fs.provider.name : "_");
- }
-
- function storable(m) {
- return {
- id: m.id,
- role: m.role,
- at: m.at,
- text: m.text || "",
- auto: !!m.auto,
- attachments: m.attachments || [],
- blocks: (m.blocks || []).map(function (b) {
- 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 };
- }),
- meta: m.meta || {},
- failed: !!m.failed,
- local: !!m.local
- };
- }
-
- var saveSoon = util.debounce(function () { save().catch(function (e) { console.warn(e); }); }, 500);
-
- async function save() {
- if (!state.key) return;
- await A.idb.set(state.key, state.messages.filter(function (m) { return !m.pending; }).slice(-MAX_STORED).map(storable));
- }
-
- function toMarkdown(messages) {
- var name = ai.name();
- var out = ["# " + t("ai.chat.md_title", { project: A.fs.provider ? A.fs.provider.name : "" }), ""];
- messages.forEach(function (m) {
- var head = "## " + m.role + " · " + stamp(m.at);
- if (m.role === "assistant") head += " · " + (m.meta && m.meta.model || name) + " · " + (m.meta && m.meta.cost != null ? ai.budget.format(m.meta.cost) : "-");
- out.push(head, "");
- var text = m.role === "assistant" ? assistantText(m) : m.text;
- out.push(String(text || "").replace(/^## (user|assistant) · /gm, "\\## $1 · ").trim(), "");
- });
- return out.join("\n");
- }
-
- function parseMarkdown(text) {
- var msgs = [];
- var cur = null;
- String(text || "").replace(/\r/g, "").split("\n").forEach(function (line) {
- var m = HEADING.exec(line);
- if (m) {
- if (cur) msgs.push(cur);
- var at = Date.parse(m[2].trim().replace(" ", "T"));
- cur = { id: uid(), role: m[1], at: isNaN(at) ? Date.now() : at, text: "", blocks: [], meta: {}, lines: [] };
- if (m[1] === "assistant" && m[3]) cur.meta.model = m[3].trim();
- return;
- }
- if (cur) cur.lines.push(line.replace(/^\\## (user|assistant) · /, "## $1 · "));
- });
- if (cur) msgs.push(cur);
- return msgs.map(function (m) {
- var body = m.lines.join("\n").trim();
- delete m.lines;
- if (m.role === "assistant") m.blocks = [{ k: "text", text: body }];
- m.text = body;
- return m;
- }).filter(function (m) { return m.text; });
- }
-
- function assistantText(m) {
- var parts = (m.blocks || []).filter(function (b) { return b.k === "text" && b.text.trim(); }).map(function (b) { return b.text.trim(); });
- return parts.length ? parts.join("\n\n") : m.text || "";
- }
-
- async function syncFile() {
- if (!ai.get("conversation.sync") || !A.fs.provider) return;
- var keep = ai.get("conversation.keep");
- var msgs = state.messages.filter(function (m) { return !m.pending && !m.failed && !m.local && (m.role === "user" || assistantText(m)); }).slice(-keep);
- if (!msgs.length) return;
- if (!(await ai.private.exists("Conversation.md")) && !(await ai.private.ensure())) {
- ai.set("conversation.sync", false);
- A.ui.toast(ai.t("ai.chat.sync_off"), "info");
- return;
- }
- await ai.private.write("Conversation.md", toMarkdown(msgs));
- }
-
- async function load() {
- var key = storeKey();
- state.key = key;
- var stored = await A.idb.get(key);
- if (state.key !== key) return;
- var msgs = Array.isArray(stored) ? stored : [];
- if (!msgs.length && A.fs.provider) {
- try {
- var md = await ai.private.read("Conversation.md");
- if (md) msgs = parseMarkdown(md);
- } catch (e) { msgs = []; }
- }
- if (state.key !== key) return;
- state.messages = msgs;
- renderAll();
- }
-
- function historyFor() {
- var keep = ai.get("conversation.keep");
- var src = state.messages.filter(function (m) { return !m.pending && !m.failed && !m.local; }).slice(-keep);
- var out = [];
- src.forEach(function (m) {
- var text = m.role === "assistant" ? assistantText(m) : m.text;
- if (!text || !text.trim()) return;
- var last = out[out.length - 1];
- if (last && last.role === m.role) last.content[0].text += "\n\n" + text;
- else out.push({ role: m.role, content: [{ type: "text", text: text }] });
- });
- while (out.length && out[0].role !== "user") out.shift();
- return out;
- }
-
- function overrideValue() {
- var v = overrideSel ? overrideSel.value : "auto";
- if (v === "auto") return null;
- if (v.indexOf("m:") === 0) {
- var p = v.slice(2).split("|");
- return { provider: p[0], model: p.slice(1).join("|") };
- }
- return { role: v };
- }
-
- function fillOverride() {
- if (!overrideSel) return;
- var current = overrideSel.value || state.override;
- overrideSel.innerHTML = "";
- overrideSel.appendChild(el("option", { value: "auto" }, t("ai.chat.model_auto")));
- var roles = el("optgroup", { label: t("ai.chat.model_roles") });
- ai.ROLES.forEach(function (r) { roles.appendChild(el("option", { value: r }, t("ai.role." + r))); });
- overrideSel.appendChild(roles);
- var models = el("optgroup", { label: t("ai.chat.model_models") });
- var seen = {};
- ai.models().forEach(function (m) {
- var v = "m:" + m.provider + "|" + m.model;
- if (!m.model || seen[v]) return;
- seen[v] = true;
- models.appendChild(el("option", { value: v }, m.model + " · " + ai.providerLabel(m.provider)));
- });
- if (models.children.length) overrideSel.appendChild(models);
- overrideSel.value = Array.prototype.some.call(overrideSel.options, function (o) { return o.value === current; }) ? current : "auto";
- }
-
- function toolIcon(name) {
- if (/^preview_screenshot/.test(name)) return "eye";
- if (/^preview_/.test(name)) return "device";
- if (/search/.test(name)) return "search";
- if (/^(create|edit|overwrite|copy)_file/.test(name)) return "pencil";
- if (/^(delete)_file/.test(name)) return "trash";
- if (/^move_file/.test(name)) return "arrowRight";
- if (/crawl|fetch/.test(name)) return "globe";
- return "file";
- }
-
- function argOf(input) {
- input = input || {};
- var v = input.path || input.from || input.selector || input.query || input.url || input.preset || input.dir || "";
- if (input.to) v += " → " + input.to;
- return shortText(v, 80);
- }
-
- function addRow(msg, icon, text, tone, extra) {
- var row = Object.assign({ k: "row", icon: icon, text: text, tone: tone || "muted" }, extra || {});
- msg.blocks.push(row);
- msg.textBlock = null;
- return row;
- }
-
- function onEvent(msg, e) {
- switch (e.type) {
- case "route":
- msg.meta.model = e.decision.model;
- msg.meta.provider = e.decision.provider;
- msg.meta.role = e.decision.role;
- addRow(msg, "sparkles", e.text, e.decision.notices.length ? "warn" : "muted");
- break;
- case "estimate":
- addRow(msg, "coins", t("ai.chat.estimate", { cost: money(e.cost, e.known), up: money(e.upTo, e.known) }), "muted");
- break;
- case "compacting":
- addRow(msg, "collapse", t("ai.chat.compacting"), "muted");
- break;
- case "call":
- msg.textBlock = null;
- break;
- case "text":
- if (!msg.textBlock) {
- msg.textBlock = { k: "text", text: "" };
- msg.blocks.push(msg.textBlock);
- }
- msg.textBlock.text += e.delta;
- msg.thinking = false;
- break;
- case "thinking":
- msg.thinking = true;
- break;
- case "tool_run":
- addRow(msg, toolIcon(e.name), t("ai.chat.tool", { name: e.name, arg: argOf(e.input) }), "tool", { toolId: e.id });
- break;
- case "tool_result":
- var row = msg.blocks.filter(function (b) { return b.toolId === e.id; }).pop();
- if (row) {
- row.tone = e.isError ? "danger" : "ok";
- if (e.isError) row.detail = shortText(e.content, 240);
- }
- break;
- case "status":
- var s = e.status || {};
- if (s.type === "search") addRow(msg, "search", t("ai.chat.searching", { query: shortText(s.query, 100) }), "muted");
- else if (s.type === "fetch") addRow(msg, "globe", t("ai.chat.fetching", { url: shortText(s.url, 100) }), "muted");
- else if (s.type === "fallback") addRow(msg, "refresh", t("ai.chat.fallback", { from: s.from || "", to: s.to || "" }), "warn");
- break;
- case "usage":
- if (e.result && e.result.model) msg.meta.model = e.result.model;
- break;
- case "notice":
- 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");
- break;
- case "check_start":
- addRow(msg, "eye", t("ai.chat.checking"), "muted");
- break;
- case "check":
- 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") });
- break;
- case "quality":
- 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);
- break;
- case "autofix":
- addRow(msg, "wand", t("ai.chat.autofix_step", { n: e.iteration, max: e.max }), "warn");
- break;
- case "done":
- msg.meta.cost = e.cost;
- msg.meta.known = e.known;
- msg.meta.usage = e.usage;
- msg.meta.calls = e.calls;
- break;
- case "error":
- addRow(msg, "warning", e.message, "danger");
- if (e.code === "locked") msg.meta.locked = true;
- break;
- case "aborted":
- addRow(msg, "x", t("ai.chat.aborted", { cost: ai.budget.format(e.cost || 0) }), "warn");
- break;
- }
- queueRender(msg);
- }
-
- A.on("ai-run", function (e) {
- if (e.state === "start" && state.busy && state.current && !state.current.runId) state.current.runId = e.runId;
- });
-
- var reported = new Set();
-
- A.on("ai-redacted", function (e) {
- var msg = state.current;
- if (!state.busy || !msg || !e || !e.items || e.kind === "ghost") return;
- var fresh = e.items.filter(function (it) { return !reported.has(it.id); });
- if (!fresh.length) return;
- fresh.forEach(function (it) { reported.add(it.id); });
- addRow(msg, "shield", t("ai.chat.redacted", { list: ai.redact.summary(fresh) }), "muted", {
- detail: fresh.map(function (it) { return "«" + it.id + (it.label ? ": " + it.label : "") + "» " + it.sample + (it.path ? " · " + it.path + ":" + it.line : ""); }).join("\n")
- });
- queueRender(msg);
- });
-
- A.on("ai-change", function (ev) {
- var msg = state.current;
- var rec = ev && ev.record;
- if (!msg || !rec || (msg.runId && rec.runId !== msg.runId)) return;
- var stats = "";
- if (rec.before != null || rec.after != null) {
- var lines = ai.tools.diffLines(rec.before, rec.after);
- var add = 0, del = 0;
- lines.forEach(function (l) { if (l.t === "+") add++; else if (l.t === "-") del++; });
- if (rec.op !== "move") stats = " (+" + add + " −" + del + ")";
- }
- addRow(msg, "check", t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" }) + stats, "change", { change: rec.id });
- queueRender(msg);
- });
-
- function queueRender(msg) {
- renderQueued.add(msg);
- if (renderQueued.size > 1) return;
- requestAnimationFrame(function () {
- var stick = nearBottom();
- renderQueued.forEach(function (m) { updateNode(m); });
- renderQueued.clear();
- if (stick) scrollBottom();
- });
- }
-
- function nearBottom() {
- return !list || list.scrollHeight - list.scrollTop - list.clientHeight < 80;
- }
-
- function scrollBottom() {
- if (list) list.scrollTop = list.scrollHeight;
- }
-
- function blockNode(msg, b) {
- if (b.k === "text") return el("div", { class: "ath-ai-md", html: markdown(b.text) });
- var node = el("div", { class: "ath-ai-ev is-" + (b.tone || "muted") + (b.undone ? " is-undone" : "") }, [
- el("span", { class: "ath-ai-ev-icon", html: A.icon(b.tone === "ok" && b.icon !== "check" ? b.icon : b.icon) }),
- el("span", { class: "ath-ai-ev-text" }, b.text)
- ]);
- if (b.tone === "tool" && msg.pending) node.appendChild(el("span", { class: "ath-ai-ev-spin" }));
- if (b.change) {
- var actions = el("span", { class: "ath-ai-ev-actions" }, [
- 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); } }),
- 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 () {
- ai.tools.undo(b.change).then(function (done) {
- if (!done) return;
- b.undone = true;
- updateNode(msg);
- saveSoon();
- }).catch(fail);
- } })
- ]);
- node.appendChild(actions);
- }
- if (b.detail) {
- var wrap = el("details", { class: "ath-ai-ev-detail" }, [el("summary", {}, t("ai.chat.details")), el("pre", {}, b.detail)]);
- return el("div", {}, [node, wrap]);
- }
- return node;
- }
-
- async function showDiff(id) {
- var rec = (await ai.tools.snapshots()).find(function (s) { return s.id === id; });
- if (!rec) return A.ui.toast(t("ai.chat.diff_gone"), "info");
- A.ui.dialog({
- title: t("ai.change.op_" + rec.op, { path: rec.path, to: rec.to || "" }),
- size: "lg",
- body: ai.tools.diffView(rec.before, rec.after),
- actions: [{ label: A.t("common.close"), value: null, kind: "secondary" }]
- });
- }
-
- function fail(e) {
- if (e && e.name === "AbortError") return;
- console.error(e);
- A.ui.toast(e && e.message ? e.message : String(e), "danger");
- }
-
- function metaLine(msg) {
- var m = msg.meta || {};
- var parts = [];
- if (m.model) parts.push(m.model + (m.role ? " · " + t("ai.role." + m.role) : ""));
- if (m.cost != null) parts.push(money(m.cost, m.known));
- if (m.usage) {
- var u = m.usage;
- var prompt = u.input + u.cacheRead + u.cacheWrite;
- parts.push(t("ai.chat.tokens", { input: prompt.toLocaleString(), output: u.output.toLocaleString(), cache: prompt ? Math.round((u.cacheRead / prompt) * 100) : 0 }));
- }
- return parts.join(" · ");
- }
-
- function updateNode(msg) {
- if (!msg.node) return;
- var node = msg.node;
- node.className = "ath-ai-msg is-" + msg.role + (msg.pending ? " is-pending" : "") + (msg.auto ? " is-auto" : "");
- node.innerHTML = "";
- var who = msg.role === "user" ? t(msg.auto ? "ai.chat.auto_label" : "ai.chat.you") : ai.name();
- var head = el("div", { class: "ath-ai-msg-head" }, [
- el("span", { class: "ath-ai-msg-who" }, who),
- el("span", { class: "ath-ai-msg-meta" }, msg.role === "assistant" ? metaLine(msg) : stamp(msg.at)),
- msg.role === "assistant" && !msg.pending && assistantText(msg) ? el("button", {
- type: "button",
- class: "ath-icon-btn",
- title: t("ai.chat.copy_message"),
- "aria-label": t("ai.chat.copy_message"),
- html: A.icon("copy"),
- onclick: function () { A.ui.copyText(reveal(assistantText(msg))).then(function () { A.ui.toast(t("ai.chat.copied"), "success"); }); }
- }) : null
- ]);
- node.appendChild(head);
- var body = el("div", { class: "ath-ai-msg-body" });
- if (msg.role === "user") {
- body.appendChild(el("div", { class: "ath-ai-md", html: markdown(msg.text) }));
- if (msg.attachments && msg.attachments.length) {
- body.appendChild(el("div", { class: "ath-ai-attach" }, msg.attachments.map(function (a) { return el("span", { class: "ath-ai-chip-static" }, a); })));
- }
- } else {
- (msg.blocks || []).forEach(function (b) { body.appendChild(blockNode(msg, b)); });
- 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") : "")]));
- }
- node.appendChild(body);
- }
-
- function messageNode(msg) {
- msg.node = el("div", { class: "ath-ai-msg" });
- updateNode(msg);
- return msg.node;
- }
-
- function emptyState() {
- var examples = ["ai.chat.example_1", "ai.chat.example_2", "ai.chat.example_3"];
- return el("div", { class: "ath-ai-empty" }, [
- el("span", { class: "ath-ai-empty-logo", html: A.icon("sparkles") }),
- el("p", { class: "ath-ai-empty-title" }, t("ai.chat.empty_title")),
- el("p", { class: "ath-ai-empty-text" }, t("ai.chat.empty_text")),
- el("div", { class: "ath-ai-examples" }, examples.map(function (k) {
- return el("button", { type: "button", class: "ath-ai-example", onclick: function () { input.value = t(k); input.focus(); autosize(); } }, t(k));
- }))
- ]);
- }
-
- function renderAll() {
- if (!list) return;
- list.innerHTML = "";
- if (!state.messages.length) list.appendChild(emptyState());
- state.messages.forEach(function (m) { list.appendChild(messageNode(m)); });
- scrollBottom();
- syncControls();
- }
-
- function autosize() {
- if (!input) return;
- input.style.height = "auto";
- input.style.height = Math.min(220, input.scrollHeight + 2) + "px";
- }
-
- function renderChips() {
- if (!chips) return;
- chips.innerHTML = "";
- var picked = ai.viewer && ai.viewer.picked();
- if (picked) {
- chips.appendChild(el("span", { class: "ath-ai-chip" }, [
- el("span", { html: A.icon("target") }),
- el("span", {}, t("ai.chat.picked", { selector: shortText(picked.info.selector, 40) })),
- el("button", { type: "button", "aria-label": A.t("common.delete"), title: A.t("common.delete"), html: A.icon("x"), onclick: function () { ai.viewer.clearPicked(); } })
- ]));
- }
- state.images.forEach(function (img, i) {
- chips.appendChild(el("span", { class: "ath-ai-chip" }, [
- el("img", { src: "data:" + img.mime + ";base64," + img.data, alt: "" }),
- el("span", {}, shortText(img.name, 24)),
- 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(); } })
- ]));
- });
- chips.hidden = !chips.children.length;
- }
-
- function syncControls() {
- if (!root) return;
- var on = ai.enabled();
- offBox.hidden = on;
- sendBtn.innerHTML = A.icon(state.busy ? "x" : "arrowRight") + "<span>" + esc(t(state.busy ? "ai.chat.stop" : "ai.chat.send")) + "</span>";
- sendBtn.classList.toggle("orb-btn-danger", state.busy);
- sendBtn.classList.toggle("orb-btn-primary", !state.busy);
- input.placeholder = t("ai.chat.placeholder");
- updateTotal();
- }
-
- function updateTotal() {
- if (!totalEl) return;
- var s = ai.budget.session();
- totalEl.textContent = t("ai.chat.session_total", { cost: ai.budget.format(s.cost) });
- }
-
- function readImage(file) {
- return new Promise(function (resolve) {
- if (!/^image\/(png|jpeg|webp|gif)$/.test(file.type) || file.size > IMAGE_BYTES) return resolve(null);
- var r = new FileReader();
- r.onload = function () {
- var url = String(r.result);
- resolve({ mime: file.type, data: url.slice(url.indexOf(",") + 1), name: file.name || "image" });
- };
- r.onerror = function () { resolve(null); };
- r.readAsDataURL(file);
- });
- }
-
- async function addImages(files) {
- for (var f of files) {
- if (state.images.length >= MAX_IMAGES) break;
- var img = await readImage(f);
- if (img) state.images.push(img);
- else A.ui.toast(t("ai.chat.image_rejected", { name: f.name || "image" }), "warning");
- }
- renderChips();
- }
-
- function build() {
- list = el("div", { class: "ath-ai-chat-list", role: "log", "aria-live": "polite" });
- input = el("textarea", { class: "ath-ai-chat-input", rows: 2, spellcheck: "true", "aria-label": t("ai.chat.placeholder") });
- sendBtn = el("button", { type: "button", class: "orb-btn orb-btn-sm orb-btn-primary ath-ai-send" });
- overrideSel = el("select", { class: "orb-select ath-ai-override", title: t("ai.chat.model_title"), "aria-label": t("ai.chat.model_title") });
- chips = el("div", { class: "ath-ai-chips", hidden: true });
- totalEl = el("span", { class: "ath-ai-total" });
- offBox = el("div", { class: "ath-ai-chat-off" }, [
- el("span", {}, t("ai.chat.off")),
- el("button", { type: "button", class: "orb-btn orb-btn-sm orb-btn-primary", onclick: function () { ai.enable().catch(fail); } }, t("ai.ov.enable"))
- ]);
- 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 () {
- if (!ai.allowed("preview")) return A.ui.toast(ai.t("ai.viewer.err_perm"), "info");
- ai.viewer.pick().catch(fail);
- } });
- 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 });
- suggest.box = el("div", { class: "ath-ai-suggest", role: "listbox", hidden: true });
- root = el("div", { class: "ath-ai-chat" }, [
- offBox,
- list,
- el("div", { class: "ath-ai-composer" }, [
- suggest.box,
- chips,
- input,
- el("div", { class: "ath-ai-composer-bar" }, [overrideSel, totalEl, el("span", { class: "ath-ai-spacer" }), newBtn, pickBtn, sendBtn])
- ])
- ]);
- sendBtn.addEventListener("click", function () {
- if (state.busy) stop();
- else submit();
- });
- input.addEventListener("keydown", function (e) {
- if (!suggest.box || suggest.box.hidden || !suggest.items.length) return;
- if (e.key === "ArrowDown" || e.key === "ArrowUp") {
- e.preventDefault();
- e.stopImmediatePropagation();
- suggest.index = (suggest.index + (e.key === "ArrowDown" ? 1 : -1) + suggest.items.length) % suggest.items.length;
- renderSuggest();
- } else if (e.key === "Enter" || e.key === "Tab") {
- e.preventDefault();
- e.stopImmediatePropagation();
- applySuggest(suggest.index);
- } else if (e.key === "Escape") {
- e.preventDefault();
- e.stopImmediatePropagation();
- closeSuggest();
- }
- });
- input.addEventListener("input", function () { updateSuggest().catch(function () { }); });
- input.addEventListener("blur", function () { setTimeout(closeSuggest, 150); });
- input.addEventListener("keydown", function (e) {
- if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
- e.preventDefault();
- if (!state.busy) submit();
- } else if (e.key === "Escape" && state.busy) {
- e.preventDefault();
- e.stopPropagation();
- stop();
- }
- });
- input.addEventListener("input", autosize);
- input.addEventListener("paste", function (e) {
- var files = Array.prototype.filter.call((e.clipboardData && e.clipboardData.files) || [], function (f) { return /^image\//.test(f.type); });
- if (!files.length) return;
- e.preventDefault();
- addImages(files);
- });
- root.addEventListener("dragover", function (e) {
- if (e.dataTransfer && Array.prototype.some.call(e.dataTransfer.types, function (x) { return x === "Files"; })) e.preventDefault();
- });
- root.addEventListener("drop", function (e) {
- var files = Array.prototype.filter.call((e.dataTransfer && e.dataTransfer.files) || [], function (f) { return /^image\//.test(f.type); });
- if (!files.length) return;
- e.preventDefault();
- e.stopPropagation();
- e.athHandled = true;
- addImages(files);
- });
- list.addEventListener("click", function (e) {
- var copy = e.target.closest("[data-copy]");
- if (copy) {
- var code = copy.closest(".ath-ai-code").querySelector("code").textContent;
- A.ui.copyText(reveal(code)).then(function () { A.ui.toast(t("ai.chat.copied"), "success"); });
- return;
- }
- var ref = e.target.closest(".ath-ai-fileref");
- if (ref) {
- e.preventDefault();
- openRef(ref.getAttribute("data-path"), Number(ref.getAttribute("data-line")) || 0);
- }
- });
- fillOverride();
- renderChips();
- renderAll();
- }
-
- async function openRef(path, line) {
- if (!A.fs.provider) return;
- try { path = ai.tools.cleanPath(path); } catch (e) { return; }
- if (!(await ai.tools.io.exists(path))) return A.ui.toast(A.t("preview.page_not_found", { path: path }), "info");
- var tab = await A.tabs.openPath(path);
- if (tab && tab.kind === "text" && line) requestAnimationFrame(function () { A.editor.goTo(line, 1); });
- }
-
- function newChat() {
- if (state.busy) return;
- if (!state.messages.length) return;
- A.ui.confirm(t("ai.chat.new"), t("ai.chat.new_confirm"), t("ai.chat.new"), false).then(function (ok) {
- if (!ok) return;
- state.messages = [];
- renderAll();
- saveSoon();
- });
- }
-
- function localReply(text, markdownText) {
- var user = { id: uid(), role: "user", at: Date.now(), text: text, blocks: [], meta: {}, local: true };
- var reply = { id: uid(), role: "assistant", at: Date.now(), text: markdownText, blocks: [{ k: "text", text: markdownText }], meta: { model: t("ai.chat.local") }, local: true };
- var empty = list && list.querySelector(".ath-ai-empty");
- if (empty) empty.remove();
- state.messages.push(user, reply);
- if (list) {
- list.appendChild(messageNode(user));
- list.appendChild(messageNode(reply));
- scrollBottom();
- }
- if (input) {
- input.value = "";
- autosize();
- }
- saveSoon();
- }
-
- var suggest = { box: null, items: [], index: 0 };
-
- function closeSuggest() {
- if (!suggest.box) return;
- suggest.box.hidden = true;
- suggest.items = [];
- }
-
- function applySuggest(i) {
- var item = suggest.items[i];
- if (!item) return;
- input.value = "/" + item.name + " ";
- closeSuggest();
- input.focus();
- autosize();
- }
-
- function renderSuggest() {
- suggest.box.innerHTML = "";
- suggest.items.forEach(function (item, i) {
- suggest.box.appendChild(el("button", {
- type: "button",
- class: "ath-ai-suggest-item" + (i === suggest.index ? " is-active" : ""),
- onmousedown: function (e) { e.preventDefault(); applySuggest(i); }
- }, [el("code", {}, "/" + item.name), el("span", {}, item.description)]));
- });
- suggest.box.hidden = !suggest.items.length;
- }
-
- async function updateSuggest() {
- if (!ai.commands || !suggest.box) return;
- var v = input.value;
- if (!/^\/[a-z0-9-]*$/i.test(v)) return closeSuggest();
- var items = await ai.commands.suggestions(v);
- if (input.value !== v) return;
- suggest.items = items.slice(0, 9);
- suggest.index = 0;
- renderSuggest();
- }
-
- function stop() {
- if (state.controller) state.controller.abort();
- }
-
- function submit() {
- var text = input.value;
- if (!text.trim() && !state.images.length) return;
- send(text).catch(fail);
- }
-
- async function send(text, opts) {
- opts = opts || {};
- if (state.busy) return false;
- text = String(text || "").trim();
- if (!ai.enabled()) {
- if (!(await ai.enable())) return false;
- }
- if (!state.key) await load();
- var command = null;
- if (/^\/[a-z0-9-]/i.test(text) && ai.commands) {
- command = await ai.commands.resolve(text);
- if (command && command.error) {
- A.ui.toast(command.error, "warning");
- return false;
- }
- if (command && command.local) {
- localReply(text, command.text);
- return true;
- }
- }
- var parsed = command ? { text: command.text, override: command.override || null } : ai.router.parseOverride(text);
- var override = parsed.override || overrideValue();
- var attachments = [];
- var picked = ai.viewer && ai.viewer.picked();
- if (picked) attachments.push(t("ai.chat.picked", { selector: shortText(picked.info.selector, 40) }));
- state.images.forEach(function (img) { attachments.push(t("ai.chat.image_label", { name: shortText(img.name, 30) })); });
- var history = historyFor();
- var user = { id: uid(), role: "user", at: Date.now(), text: text, auto: !!opts.auto, attachments: attachments, blocks: [], meta: {} };
- var msg = { id: uid(), role: "assistant", at: Date.now(), text: "", blocks: [], meta: {}, pending: true };
- var empty = list && list.querySelector(".ath-ai-empty");
- if (empty) empty.remove();
- state.messages.push(user, msg);
- if (list) {
- list.appendChild(messageNode(user));
- list.appendChild(messageNode(msg));
- scrollBottom();
- }
- if (!opts.auto && input) {
- input.value = "";
- autosize();
- }
- var images = state.images.slice();
- state.images = [];
- renderChips();
- state.busy = true;
- state.current = msg;
- state.controller = new AbortController();
- syncControls();
- A.emit("ai-chat-busy", true);
- try {
- var res = await ai.agent.run({
- text: parsed.text,
- history: history,
- override: override,
- images: images,
- extra: (opts.extra || []).concat(command ? command.extra : []),
- purpose: opts.purpose || (command && command.purpose) || null,
- readOnly: !!(command && command.readOnly),
- signal: state.controller.signal,
- onEvent: function (e) { onEvent(msg, e); }
- });
- msg.text = res.text;
- msg.runId = res.runId;
- } catch (e) {
- if (e.name !== "AbortError") {
- msg.failed = !assistantText(msg);
- if (!msg.blocks.some(function (b) { return b.tone === "danger"; })) addRow(msg, "warning", e.message || String(e), "danger");
- } else {
- msg.failed = !assistantText(msg);
- }
- } finally {
- msg.pending = false;
- msg.thinking = false;
- state.busy = false;
- state.current = null;
- state.controller = null;
- updateNode(msg);
- syncControls();
- A.emit("ai-chat-busy", false);
- saveSoon();
- syncFile().catch(function (err) { console.warn(err); });
- }
- return true;
- }
-
- A.on("ai-autofix", function (e) {
- if (!ai.get("preview.autoFix") || state.busy || !ai.enabled() || !ai.allowed("preview")) return;
- if (ai.agent.busy()) return;
- var sig = (e.errors || []).join("|");
- if (Date.now() - state.lastAuto < AUTOFIX_GAP || sig === state.lastAutoSig) return;
- state.lastAuto = Date.now();
- state.lastAutoSig = sig;
- if (A.aiUi && !A.aiUi.isOpen()) A.aiUi.open("chat");
- send(t("ai.chat.autofix_msg"), { auto: true, purpose: "fix" }).catch(fail);
- });
-
- A.on("ai-picked", renderChips);
- A.on("ai-usage", updateTotal);
- A.on("ai-config", function (path) {
- if (path === "models" || path === "mode") fillOverride();
- if (path === "enabled" || path === "consent") syncControls();
- });
- A.on("ai-name", function () { if (list) renderAll(); });
- A.on("lang", function () {
- if (!root) return;
- var parent = root.parentNode;
- root = null;
- build();
- if (parent) parent.appendChild(root);
- });
- A.on("workspace", function () {
- if (state.busy) stop();
- reported.clear();
- state.key = null;
- state.messages = [];
- load().catch(function (e) { console.warn(e); });
- });
-
- A.aiUi.section({
- id: "chat",
- order: 5,
- icon: "chat",
- label: "ai.sec.chat",
- full: true,
- render: function (box) {
- if (!root) build();
- if (!state.key) load().catch(function (e) { console.warn(e); });
- box.appendChild(root);
- syncControls();
- setTimeout(function () {
- scrollBottom();
- if (input && !state.busy && A.aiUi.wantsFocus()) input.focus({ preventScroll: true });
- }, 0);
- }
- });
-
- ai.chat = {
- send: send,
- stop: stop,
- busy: function () { return state.busy; },
- messages: function () { return state.messages.map(storable); },
- markdown: markdown,
- toMarkdown: toMarkdown,
- parseMarkdown: parseMarkdown,
- reload: load
- };
- })();
-