`;
}).join("");
el.onclick = e => { const a = e.target.closest("[data-ws]"); if (a) ws(a.dataset.ws); };
}
/* ------------------------------------------------------------ thread state */
let EV = []; // all events, in file order
let slots = new Map(); // card event id -> {el, sig}: every card has its own place in the thread
let lastDay = "", lastId = null, firstLoad = true;
const edit = new Set(); // card ids the user is re-answering
const draft = new Map(); // card id -> draft state of an unanswered card (survives re-renders)
// A card sent again under a key that was used before (the next round's questions under the same key): the new one is the live card, at its
// own place (the bottom); the older one stays where it was, read-only, with its own answers and "updated, see below" (c.newer = the newer
// card's id). Answers belong to the card id they were given to, never to the newer card. Thread.cards() (conversation.py) agrees: it keeps
// only the newest card of a key, so an answer to an older one is refused. A progress card is the exception: only the newest is shown.
const cardState = () => {
const cards = new Map(), byKey = new Map();
for (const e of EV) {
if (e.type !== "card") continue;
const k = e.card.key, prev = k && byKey.get(k);
if (prev && cards.has(prev)) { if (e.card.kind === "progress") cards.delete(prev); else cards.get(prev).newer = e.id; }
if (k) byKey.set(k, e.id);
cards.set(e.id, { slot: e.id, ev: e, answers: [] });
}
for (const e of EV) if (e.type === "answer" && cards.has(e.card_id)) cards.get(e.card_id).answers.push(e);
return cards;
};
const ANSWERABLE = new Set(["permission", "questions", "understanding", "options", "candidates", "go", "task"]);
const pending = () => [...cardState().values()].filter(c => ANSWERABLE.has(c.ev.card.kind) && !c.newer && !c.answers.length).length;
/* tiny markdown for the agent's words: **bold**, `code`, [text](url), "- " lists */
function md(s) {
// links: [text](url) and bare http(s) URLs or /conv/ /media/ /build/ paths; a /conv/ file downloads
const link = (a, u) => `${esc(a)}`;
const inl = t => {
const L = [], keep = h => (L.push(h), `\u0000${L.length - 1}\u0000`);
t = String(t).replace(/\[([^\]]+)\]\(((?:https?:\/\/|#|\/)[^)\s]*)\)/g, (_, a, u) => keep(link(a, u)))
.replace(/https?:\/\/[^\s<>"')),。]+|(?"')),。]+/g, u => keep(link(u, u)));
return esc(t).replace(/`([^`]+)`/g, "$1").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\u0000(\d+)\u0000/g, (_, i) => L[+i]);
};
const out = []; let list = false;
for (const ln of String(s || "").split("\n")) {
const m = /^\s*[-*]\s+(.*)$/.exec(ln);
if (m) { if (!list) { out.push("
` : "";
// agentd's live build card (live.py): what the builder does right now, a banner when it is stuck / paused, the newest pictures
const EN_ = M2W.lang === "en", al = k.alert;
const alert = al ? `
`;
}
/* gathering what the user typed into a card */
const val = (el, sel) => { const x = $(sel, el); return x ? x.value : ""; };
function wireCard(el, slot) {
el.oninput = ev => { // an understanding card: a typed note turns "都对" into "提交修改"
if (!ev.target.matches("textarea.note")) return;
const b = $(".foot [data-act=ok]", el), c = cardState().get(slot); if (!b || !c) return;
const d = draft.get(c.ev.id) || {}, n = Object.keys(d).filter(x => x !== "picked" && x !== "skip").length;
b.textContent = t(n || ev.target.value.trim() ? "提交修改" : "都对");
};
el.onclick = async ev => {
const c = cardState().get(slot); if (!c) return;
const nw = ev.target.closest("[data-newer]");
if (nw) { const x = $(`#thread .msg[data-id="${CSS.escape(nw.dataset.newer)}"]`); if (x) x.scrollIntoView({ behavior: "smooth", block: "start" }); return; }
const tg = ev.target.closest("[data-act],[data-open],.opt,[data-ws]"); if (!tg) return;
if (c.newer && !tg.dataset.open && !tg.dataset.ws) return; // an older version: nothing to answer any more
const id = c.ev.id, kind = c.ev.card.kind, k = c.ev.card;
if (tg.dataset.ws) { ev.preventDefault(); return ws(tg.dataset.ws); }
if (tg.dataset.open) return ws(tg.dataset.open);
const d = draft.get(id) || {}; draft.set(id, d);
const note = () => val(el, "textarea.note").trim();
const send = async a => { const r = await post("/api/thread/answer", { card_id: id, answer: a }); if (!r.ok) return toast(r.error || t("没能发出去")); edit.delete(id); draft.delete(id); await poll(); };
if (tg.classList.contains("opt") && !tg.dataset.act) {
if (!$(".foot [data-act=submit]", el)) return;
const key = tg.dataset.k, s = new Set((d.picked ?? lastPicked(c)).map(String));
if (k.multi === false) { s.clear(); s.add(key); } else s.has(key) ? s.delete(key) : s.add(key);
d.picked = [...s]; return refresh(c);
}
switch (tg.dataset.act) {
case "redo": edit.add(id); return refresh(c);
case "cancel": edit.delete(id); draft.delete(id); return refresh(c);
case "yes": return send({ decision: "yes", note: note() });
case "no": return send({ decision: "no", note: note() });
case "start": { // no runner: builds run on the project's build model only (builds.py)
const ri = $("input.rnd", el), pr = ri ? parseInt(ri.value, 10) : null;
if (ri && !(pr >= 1 && pr <= 10)) return toast(t("试玩轮数要在 1 到 10 之间"));
return send({ decision: "start", note: note(), ...(pr ? { playtest_rounds: pr } : {}) }); }
case "wait": return send({ decision: "wait", note: note() });
case "taskdone": return send({ done: true, note: note() });
case "tasklater": return send({ later: true, note: note() });
case "pick": { const key = tg.dataset.k, s = new Set((d.picked ?? lastPicked(c)).map(String));
if (!k.multi) { const was = s.has(key); s.clear(); if (!was) s.add(key); } else s.has(key) ? s.delete(key) : s.add(key);
d.picked = [...s]; return refresh(c); }
case "submit":
if (kind === "questions") {
const answers = {}, skipped = [], prev = {}; c.answers.forEach(a => Object.assign(prev, a.answer.answers || {}));
$$(".q", el).forEach(q => { const n = q.dataset.n, ta = $("textarea", q); const v = ta ? ta.value.trim() : "";
if (v && v !== String(prev[n] ?? "").trim()) answers[n] = v; else if (!v && q.classList.contains("skip")) skipped.push(n); });
if (!Object.keys(answers).length && !skipped.length) return toast(t("还没写任何回答"));
return send({ answers, skipped });
}
if (kind === "options") { const p = d.picked ?? lastPicked(c); if (!p.length && !note()) return toast(t("先选一个,或者写一句话")); return send({ picked: p, note: note() }); }
if (kind === "candidates") { const p = d.picked ?? lastPicked(c); if (!p.length && !note()) return toast(t("都不要的话,请写一句原因")); return send({ picked: p, note: note() }); }
return;
case "skip": { const q = tg.closest(".q"), dq = d.skip || (d.skip = {}); dq[q.dataset.n] = !q.classList.contains("skip"); return refresh(c); }
case "reanswer": edit.add(id + ":" + tg.dataset.n); return refresh(c);
case "editpt": { const li = tg.closest("li"), pid = li.dataset.id;
const inp = document.createElement("input"); inp.className = "inp"; inp.value = tg.textContent; tg.replaceWith(inp); inp.focus();
const done = () => { const v = inp.value.trim(), orig = k.points.find(p => String(p.id) === pid).text; d[pid] = v; if (!v || v === orig) delete d[pid]; refresh(c); };
inp.onblur = done; inp.onkeydown = e2 => { if (e2.key === "Enter") { e2.preventDefault(); inp.blur(); } if (e2.key === "Escape") { inp.value = tg.textContent; inp.blur(); } }; return; }
case "ok": {
const edits = { ...d }; delete edits.picked; delete edits.skip;
return Object.keys(edits).length ? send({ edits, note: note() }) : note() ? send({ note: note() }) : send({ ok: true });
}
}
};
}
const lastPicked = c => { const a = c.answers[c.answers.length - 1]; return a ? (a.answer.picked || []) : []; };
function refresh(c) {
const slot = slots.get(c.slot); if (!slot) return;
const cur = cardState().get(c.slot); if (!cur) return;
// keep what the user is typing: textareas are read by key before the repaint and written back after
const key = t => { const q = t.closest(".q"); return q ? "q" + q.dataset.n : "note"; };
const vals = new Map($$("textarea", slot.el).filter(t => t.value).map(t => [key(t), t.value]));
paintCard(slot.el, cur);
$$("textarea", slot.el).forEach(t => { if (vals.has(key(t))) t.value = vals.get(key(t)); });
}
/* ------------------------------------------------------------ read receipt + "working" line */
let stateSig = "";
function renderState() {
const th = $("#thread"), ids = EV.map(e => e.id), ci = AGENT && AGENT.cursor ? ids.indexOf(AGENT.cursor) : -1;
const mine = EV.map((e, i) => [e, i]).filter(([e]) => e.from === "user" && (e.type === "text" || e.type === "answer") && e.source === "ui");
const lastUser = mine.length ? mine[mine.length - 1] : null, lastRead = mine.filter(([, i]) => i <= ci).pop();
const agentAfter = lastUser && EV.slice(lastUser[1] + 1).some(e => e.from === "agent");
// the server's `phase` (conversation.phase): sent -> calling -> working -> the reply; or queued / failed / down. Shown whether or not
// an agent is online, so a message never sits there without a word about what happens to it.
let line = AGENT && AGENT.phase || "";
if (!line && lastUser && !agentAfter && AGENT && AGENT.online) { // an older server without `phase`
const ni = AGENT.noticed ? ids.indexOf(AGENT.noticed) : -1; line = lastUser[1] <= Math.max(ci, ni) ? "working" : "sent";
}
if (!line && AGENT && AGENT.busy) line = "working";
const sig = JSON.stringify([lastRead && lastRead[0].id, AGENT && AGENT.read_at, line, line === "queued" && AGENT.queued, M2W.lang]);
const foot = $("#thstate");
if (sig === stateSig && foot && foot === th.lastElementChild) return;
stateSig = sig;
const stick = th.scrollHeight - th.scrollTop - th.clientHeight < 80;
$$(".seen", th).forEach(x => x.remove()); if (foot) foot.remove();
if (lastRead) {
const col = $(`.msg.me[data-id="${lastRead[0].id}"] .col`, th);
if (col) { const x = document.createElement("div"); x.className = "seen"; x.textContent = t("已读") + (AGENT.read_at ? " " + hhmm(AGENT.read_at) : ""); col.append(x); }
}
const dots = ``, ring = ``;
const LINE = { working: [ring, "agent 正在处理…"], sent: [dots, "已送达,等 agent 读取"], calling: [ring, "已送达 · 正在叫 agent,大约半分钟"],
queued: [dots, "已送达 · 排队中"], failed: [dots, "agent 这次没能回复。再说一句会重新叫 agent"], down: [dots, "已送达,但后台调度没有运行,暂时没有 agent 来读"] };
if (line === "failed" && AGENT.failed && AGENT.failed.reason === "auth") LINE.failed = [dots, "Claude 登录过期:命令行要单独登录一次,让桌面 App 里的 Claude 替你运行 claude auth login"];
if (LINE[line]) {
const x = document.createElement("div"); x.id = "thstate"; x.className = "thstate" + (line === "failed" || line === "down" ? " bad" : "");
x.innerHTML = LINE[line][0] + esc(t(LINE[line][1])) + (line === "queued" && AGENT.queued ? `${esc(t("(最多同时 {c} 个项目)", { c: AGENT.queued.cap }))}` : "");
th.append(x);
}
if (stick) th.scrollTop = th.scrollHeight;
}
/* ------------------------------------------------------------ render the thread */
function toBottom(th, jump) { // jump: no smooth animation (opening a long thread scrolled from the very top for seconds)
if (!jump) { th.scrollTop = th.scrollHeight; return; }
th.style.scrollBehavior = "auto"; th.scrollTop = th.scrollHeight; th.style.scrollBehavior = "";
}
function render(newEvents) {
const th = $("#thread"), stick = firstLoad || th.scrollHeight - th.scrollTop - th.clientHeight < 80;
const cards = cardState();
for (const e of newEvents) {
if (e.type === "text") {
addDay(e); th.append(e.from === "user" ? userMsg(e) : agentMsg(e, `
${md(e.text)}
${files(e)}`));
} else if (e.type === "status") {
const x = document.createElement("div"); x.className = "sys" + (e.live ? " lv " + String(e.live).replace(/[^a-z_]/g, "") : ""); x.textContent = e.text || ""; th.append(x);
} else if (e.type === "card") {
const k = e.card.key, prog = k && e.card.kind === "progress";
const slotId = e.id; // a new card under an old key: here, at the bottom (cardState)
if (prog) for (const [id, s] of [...slots]) if (id !== slotId && s.el.dataset.pkey === k) { s.el.remove(); slots.delete(id); } // the older version moves down
if (!slots.has(slotId)) { const cc = cards.get(slotId); if (!cc) continue; addDay(e); const el = cardEl(cc); if (prog) el.dataset.pkey = k; th.append(el); slots.set(slotId, { el, sig: sig(cc) }); }
}
}
for (const [id, s] of slots) { // updated cards (answers; an older version that became read-only)
const cc = cards.get(id); if (!cc) continue; const g = sig(cc);
if (g !== s.sig) { s.sig = g; refresh(cc); }
}
if (!EV.length && firstLoad) th.innerHTML = `
${emptyText()}
`;
else { const em = $(".empty", th); if (em && EV.length) em.remove(); }
if (stick) {
toBottom(th, firstLoad);
// images and audio load after the first render and push the bottom down: keep following until they settle
if (firstLoad && !th._follow) { // media load after the first render and push the bottom down: follow it for a few seconds
const stop = () => { clearInterval(th._follow); th.removeEventListener("wheel", stop); th.removeEventListener("touchstart", stop); };
th._follow = setInterval(() => toBottom(th, true), 150); setTimeout(stop, 5000);
th.addEventListener("wheel", stop, { passive: true }); th.addEventListener("touchstart", stop, { passive: true });
}
}
const n = pending(); const cnt = $("#gochat .cnt");
if (SH && (cnt ? +cnt.textContent : 0) !== n) renderSide();
}
const sig = c => JSON.stringify([c.ev.id, c.ev.card, c.answers.map(a => a.id), c.newer || null]);
// an empty thread: a brand-new project is greeted by the supervisor by itself (agentd), so say what is happening
const emptyText = () => AGENT.run || AGENT.busy ? `${t("agent 正在过来和你打招呼…")}`
: daemonUp() ? t("agent 马上会来和你打个招呼。你也可以先在下面说说你的想法。")
: t("还没有对话。在下面说说你的想法;后台调度没有运行,agent 暂时不会来,话会排队。");
let busy = false;
async function poll() {
if (busy) return; busy = true;
try {
const r = await get("/api/thread" + (lastId ? "?after=" + encodeURIComponent(lastId) : ""));
if (JSON.stringify(r.agent) !== JSON.stringify(AGENT)) { AGENT = r.agent; renderPills(); const em = $("#thread .empty"); if (em) em.innerHTML = emptyText(); }
if (JSON.stringify(r.build || []) !== JSON.stringify(BUILD)) { BUILD = r.build || []; renderBuild(); }
if (r.events.length && !firstLoad) notifyFor(r.events);
if (r.events.length || firstLoad) { EV = EV.concat(r.events); if (r.events.length) lastId = r.events[r.events.length - 1].id; render(r.events); firstLoad = false; }
renderState();
} catch (e) { /* server restarting: try again on the next tick */ }
busy = false;
}
/* ------------------------------------------------------------ composer */
let ctx = []; // context chips {kind, id|m|t|frame_data, label}
const sending = { files: [] }; // uploaded attachment paths (inbox-relative)
let uploads = 0;
function renderChips() {
$("#chips").innerHTML = ctx.map((c, i) => `${c.frame_data ? `` : icon("at", "width:12px;height:12px")}${esc(chipLabel(c))}`).join("")
+ sending.files.map((f, i) => `${icon("clip", "width:12px;height:12px")}${esc(f.split("/").pop())}`).join("");
$$("#chips button").forEach(b => b.onclick = () => { if (b.dataset.i != null) ctx.splice(+b.dataset.i, 1); else sending.files.splice(+b.dataset.f, 1); renderChips(); });
}
const chipLabel = c => c.kind === "video" ? t("试玩 · 第 {n} 版 · {t}", { n: String(c.m).replace(/\D/g, "") || c.m, t: fmtT(+c.t || 0) }) : (c.kind === "person" ? t("人物 · ") : t("时刻 · ")) + (c.label || c.id);
window.addEventListener("message", ev => {
if (ev.origin !== location.origin || !ev.data || ev.data.type !== "m2w-context") return;
const add = (ev.data.context || []).filter(c => c && c.kind);
ctx = ctx.filter(o => !add.some(n => n.kind === o.kind && (n.kind === "video" || n.id === o.id)));
ctx.push(...add); renderChips();
const ta = $("#msg"); if (ev.data.text && !ta.value) ta.value = ev.data.text;
ta.focus();
});
async function sendMsg() {
const ta = $("#msg"), text = ta.value.trim();
if (uploads) return toast(t("文件还在上传,等一下"));
if (!text && !sending.files.length) return;
$("#send").disabled = true;
const r = await post("/api/thread", { text, context: ctx, attachments: sending.files });
$("#send").disabled = false;
if (!r.ok) return toast(r.error || t("没能发出去"));
ta.value = ""; ctx = []; sending.files = []; renderChips(); firstLoad = true; await poll(); toBottom($("#thread"), true);
}
$("#send").onclick = sendMsg;
$("#coachbtn").onclick = () => startCoach();
$("#msg").addEventListener("keydown", e => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); sendMsg(); } });
$("#pick").onchange = e => { attach([...e.target.files]); e.target.value = ""; };
const cb = $("#cbox");
["dragenter", "dragover"].forEach(e => cb.addEventListener(e, ev => { ev.preventDefault(); cb.classList.add("over"); }));
["dragleave", "drop"].forEach(e => cb.addEventListener(e, ev => { ev.preventDefault(); cb.classList.remove("over"); }));
cb.addEventListener("drop", ev => attach([...ev.dataTransfer.files]));
$("#thread").addEventListener("click", e => { const a = e.target.closest("[data-ws]"); if (a) { e.preventDefault(); ws(a.dataset.ws); } });
/* attachments go through the chunked upload into 0_inbox, then are referenced in the message as files */
const CHUNK = 8 * 1024 * 1024, rnd = () => "u" + [...crypto.getRandomValues(new Uint8Array(12))].map(x => x.toString(16).padStart(2, "0")).join("");
function attach(files) {
for (const f of files) {
const row = document.createElement("div"); row.className = "u"; row.innerHTML = `${esc(f.name)} · 0%`; $("#ups").append(row);
uploads++;
upload(f, p => { $("i", row).style.width = p + "%"; $("span", row).textContent = `${f.name} · ${Math.round(p)}%`; })
.then(path => { sending.files.push(path); row.remove(); renderChips(); })
.catch(err => { row.classList.add("err"); $("span", row).textContent = `${f.name} · ${err.message}`; setTimeout(() => row.remove(), 6000); })
.finally(() => uploads--);
}
}
async function upload(file, onp, target) {
if (!file.size) throw new Error(t("空文件"));
const uid = rnd(); let at = 0, res = {};
while (at < file.size) {
const b = Math.min(at + CHUNK, file.size);
res = await new Promise((ok, bad) => {
const x = new XMLHttpRequest(); x.open("POST", "/api/upload");
x.setRequestHeader("X-Upload-Id", uid); x.setRequestHeader("X-Lang", M2W.lang); x.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
if (target) x.setRequestHeader("X-Upload-Target", target);
x.setRequestHeader("Content-Range", `bytes ${at}-${b - 1}/${file.size}`); x.setRequestHeader("Content-Type", "application/octet-stream");
x.upload.onprogress = e => onp((at + e.loaded) / file.size * 100);
x.onload = () => { let j = {}; try { j = JSON.parse(x.responseText); } catch (e) {} x.status === 200 ? ok(j) : bad(new Error(j.error || t("上传失败({s})", { s: x.status }))); };
x.onerror = () => bad(new Error(t("连接断了"))); x.send(file.slice(at, b));
});
at = b;
}
onp(100); return res.path;
}
/* ------------------------------------------------------------ models: the 「对话 / 构建」 chips next to the input (/api/models, models.py)
Which agent CLI and model answers this chat and which one builds. Only the owner changes them (a viewer sees them read only); the menu
lists only the agents the owner can run, each with a short model list and a one-line hint. Another agent for the chat = a new session. */
let MODELS = null;
const modelText = (role, x) => t(role === "chat" ? "对话:{a} · {m}" : "构建:{a} · {m}", { a: x.agent_name, m: x.model_shown || t("默认") });
function modelChipsHtml(M) {
if (!M || !M.chat) return "";
return ["chat", "build"].map(r => ``).join("");
}
function modelMenuHtml(role, M, sel) {
const cur = { ...M[role], model: M[role].model_shown || "" }, s = sel || { agent: cur.agent, model: cur.model }; // '' = the CLI default (Claude Code: sonnet)
const isOn = (a, m) => s.agent === a && (s.model || "") === (m || "");
const picked = ((M.agents || []).find(g => g.id === s.agent) || { models: [] }).models.find(m => (m.id || "") === (s.model || ""));
const dear = picked && picked.warn && !isOn(cur.agent, cur.model) ? picked.warn : ""; // Fable: very expensive, she confirms it
const grp = g => {
const known = g.models.some(m => isOn(g.id, m.id)), typed = s.agent === g.id && !known ? s.model : "";
return `
`;
}
// the go card's read-only line: builds run ONLY on the project's build model. Unanswered (live): the model the build will use now (the
// 「构建」 chip), with a pointer to the chip and a note when the estimate was made for another one; answered: the one the card named.
function goModelHtml(k, live, M) {
const B = M && M.build, now = B ? B.agent_name + (B.model_shown ? " · " + B.model_shown : "") : "", was = (k.build_model || {}).label || "";
const L = live ? now || was : was;
if (!L) return "";
const stale = live && now && was && now !== was;
return `