Files
magpie/internal/gui/assets/sessions.js
T
yetone 585f7f7dfa sessions, gui: Codex sessions made with another provider are moved to Codex's own from the Sessions page, and back (#887, cjyrainbow) — Codex's history lists only the sessions of the provider it uses now, so sessions made through CC Switch (model_provider "custom") vanished from it once Codex used magpie, though their files were still there and the Sessions page listed them. The Codex tab now reads each session's provider from its session_meta (cached with the rest) and the one Codex in that session's home uses (config.toml's model_provider, or its profile's; "openai" when none), says how many were made with another and which, and tags each. "Move to <provider>…" opens magpie's own dialog listing them, each ticked; Move rewrites only the model_provider string in each session's files (.jsonl and .jsonl.zst, in its own Codex home, so WSL's too, mtime kept) and in Codex's state_*.sqlite threads row: messages, id, title and archive are left as they are. A copy of the files goes to magpie's trash folder (trash/codex-provider, with a move.json) first, a failed rewrite is put back from it, and a session written to in the last minute is left alone and said so. Undo moves each back to the provider it had, byte for byte. Nothing is moved by itself. POST /api/sessions/codex-provider; en/zh/ja/de. TestMoveCodexProvider (listing, bytes, mtime, the DB row and nothing else, backup, byte-identical undo, an active session, a bad id), TestMoveCodexProviderPacked and TestCodexProviderIn fail without the change, as does sessions-codex-provider.test.cjs (WebKit, en and zh: magpie's dialog, Cancel posts nothing, an unticked one stays, Undo, no click moves the page, no left border, translations); sessions-manage, -toolbar, -purge, -folder-delete, -wsl-delete and click-scroll pass. Not tried against a real CC Switch history. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-05 17:26:19 +08:00

781 lines
35 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Sessions: every session of an agent on this computer, by the folder it
// ran in, to pick up again or to delete. A delete asks first, in magpie's
// own dialog, and moves the session's files into magpie's trash; the Trash
// lists them, each with a Restore and a Delete forever, and can be emptied;
// erasing for good asks in the same dialog, and is only ever done when the
// reader asks for it. A session written to in the last minute
// may still be running, and is left as it is. Each row shows what the
// session spent, as the Usage page's list does, and that list's rows open
// here (#752). Everything comes from /api/sessions/manage.
(() => {
const page = $("#view-sessions");
if (!page) return;
let data = null; // /api/sessions/manage
let failed = "";
let agent = "";
try { agent = localStorage.getItem("magpie.sessionsAgent") || ""; } catch {}
let query = "";
let trashOn = false;
const picked = new Set(); // ids picked to delete, of the agent shown
const opened = new Set(); // folders unfolded, by cwd
const folderBoxes = new Map(); // each folder's box as drawn, by cwd
let openedFor = ""; // the agent the folders were first unfolded for
let detail = ""; // the session opened to its details
const talkOpen = new Set(); // sessions whose conversation is shown, by agent/id
const talks = new Map(); // what was said in them, as read, by agent/id
let loading = 0;
let fitObserver = null;
let focus = null; // { agent, id, until }: a session to bring into sight once drawn
const TRASH = "M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5M7 7v4M9 7v4";
const TERM = "M3 4.5 6 7.5 3 10.5M7.5 11.5h5.5";
const UNDO = "M5.5 3.5 2.5 6.5l3 3M2.5 6.5H10a3.5 3.5 0 0 1 0 7H7";
async function load(name) {
const n = ++loading;
if (!data) draw();
try {
const d = await api("sessions/manage?agent=" + encodeURIComponent(name ?? agent));
if (n !== loading) return;
// models may be null for a session that spent nothing
data = { ...d, agents: d?.agents || [], sessions: (d?.sessions || []).map((s) => ({ ...s, models: s.models || [] })), trash: d?.trash || [], agent: d?.agent || "" };
failed = "";
talks.clear(); // read again when shown: a session may have gone on
if (agent !== d.agent) { agent = d.agent; picked.clear(); }
} catch (e) {
if (n !== loading) return;
failed = e.message;
}
if (view === "sessions") draw();
}
window.loadSessionsPage = load;
// openSessionOnPage: the Sessions page, from the Usage page's list (#752):
// on the session's agent, its folder unfolded and the session opened to
// its details, brought into sight once it is drawn; with no id, the page
// on that agent (or as it was). The reader's click is what moves the view.
window.openSessionOnPage = (s, e) => {
if (s.agent && s.agent !== agent) {
agent = s.agent;
try { localStorage.setItem("magpie.sessionsAgent", agent); } catch {}
picked.clear();
if (data) data = { ...data, agent, sessions: null };
}
trashOn = false;
if (s.id) {
query = "";
detail = s.id;
openedFor = agent;
opened.clear();
opened.add(s.cwd || "");
focus = scrollOnPurpose(e) ? { agent, id: s.id, until: performance.now() + 5000 } : null;
}
show("sessions");
};
// bring the session asked for into sight, once its row is drawn
function toFocus() {
if (!focus || focus.agent !== data?.agent || !data.sessions) return;
if (performance.now() > focus.until) { focus = null; return; }
const r = page.querySelector(`.row.sm-sess[data-id="${CSS.escape(focus.id)}"]`);
focus = null;
if (!r) return;
readerScrolls(1000);
r.closest(".sm-item").scrollIntoView({ block: "nearest", behavior: "instant" });
readerLeaves(page);
}
const current = () => data?.agents.find((a) => a.agent === data.agent);
const shown = () => {
const q = query.trim().toLowerCase();
const list = data?.sessions || [];
return q ? list.filter((s) => [s.title, s.cwd, s.id, ...(s.models || []).map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))) : list;
};
function draw() {
const keepFocus = page.querySelector(".sm-agent-pick:focus, .sm-agents .opt:focus");
fitObserver?.disconnect();
if (page.querySelector(".sm-agent-pick.open")) closeProtoMenu();
page.classList.toggle("loading", !data?.sessions && !failed);
page.replaceChildren(head(), body());
const wrap = page.querySelector(".sm-switch");
const tabs = wrap.querySelector(".sm-agents");
const pick = wrap.querySelector(".sm-agent-pick");
const fit = () => {
const room = parseFloat(getComputedStyle(wrap).width);
if (!room) return;
const focused = document.activeElement;
// Measure the actual labels, including language, font and text zoom,
// rather than guessing a breakpoint or a number of agents.
tabs.hidden = false;
const compact = tabs.scrollWidth > Math.floor(room);
tabs.hidden = compact || !data?.agents.length;
pick.hidden = !compact || !current();
if (!compact && pick.classList.contains("open")) closeProtoMenu();
if (compact && tabs.contains(focused)) pick.focus({ preventScroll: true });
else if (!compact && focused === pick) tabs.querySelector(".on")?.focus({ preventScroll: true });
};
fitObserver = new ResizeObserver(fit);
fitObserver.observe(wrap);
fit();
if (keepFocus) (pick.hidden ? tabs.querySelector(".on") : pick)?.focus({ preventScroll: true });
}
function chooseAgent(name) {
if (name === data.agent && !trashOn) return;
trashOn = false;
agent = name;
try { localStorage.setItem("magpie.sessionsAgent", name); } catch {}
picked.clear();
detail = "";
data = { ...data, agent: name, sessions: null };
draw();
load(name);
}
function head() {
const h = el("div", "usage-head sm-head");
const wrap = el("div", "sm-switch");
const tabs = el("div", "segs regions sm-agents");
for (const x of data?.agents || []) {
const on = x.agent === data.agent && !trashOn;
const b = el("button", "opt" + (on ? " on" : ""));
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.append(icon(x.icon), el("span", "", x.name), el("em", "", String(x.count)));
b.onclick = () => chooseAgent(x.agent);
tabs.append(b);
}
const a = current();
const pick = el("button", "sess-pick sm-agent-pick");
pick.type = "button";
pick.hidden = !a;
pick.disabled = (data?.agents.length || 0) < 2;
pick.setAttribute("aria-haspopup", "menu");
pick.setAttribute("aria-expanded", "false");
if (a) {
pick.title = a.name;
pick.append(icon(a.icon), el("span", "", a.name), el("em", "", String(a.count)), svg(CHEV, 11, 1.6));
pick.onclick = (e) => {
e.stopPropagation();
if (pick.classList.contains("open")) return closeProtoMenu();
const opts = data.agents.map((x) => ({ v: x.agent, name: x.name, note: String(x.count), literalName: true }));
openProtoMenu(pick, opts, data.agent, (name) => {
pick.focus({ preventScroll: true });
chooseAgent(name);
}, "Agent", "sm-agent-menu");
};
}
wrap.append(tabs, pick);
h.append(wrap);
const q = el("input", "sess-filter sm-filter");
q.type = "search";
q.spellcheck = false;
q.autocomplete = "off";
q.placeholder = t("Filter sessions");
q.value = query;
q.hidden = trashOn;
q.oninput = () => { query = q.value; redrawList(); };
q.onkeydown = (e) => { if (e.key === "Escape" && q.value) { e.stopPropagation(); q.value = ""; query = ""; redrawList(); } };
const tr = el("button", "text sm-trash-btn" + (trashOn ? " on" : ""));
tr.type = "button";
tr.setAttribute("aria-pressed", String(trashOn));
tr.append(svg(TRASH, 13, 1.4), el("span", "", t("Trash")));
if (data?.trash.length) tr.append(el("em", "", String(data.trash.length)));
tr.onclick = () => { trashOn = !trashOn; draw(); };
h.append(q, tr);
return h;
}
function body() {
const box = el("div", "sm-body");
if (failed) { box.append(el("div", "empty-state", failed)); return box; }
if (!data || (!trashOn && !data.sessions)) {
const l = el("div", "list sm-group");
for (let i = 0; i < 4; i++) { const r = el("div", "row"); r.append(el("span", "skeleton sk-line")); l.append(r); }
box.append(l);
return box;
}
if (trashOn) { box.append(...trash()); return box; }
if (!data.agents.length) {
const e = el("div", "empty-state");
e.append(el("b", "", t("No sessions yet")), el("span", "", t("Claude Code's, Codex's, Hermes's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.")));
box.append(e);
return box;
}
const a = current();
if (a && (data.sessions.some((s) => s.read_only) || !a.deletable)) {
const canResume = data.sessions.some((s) => s.resume);
const key = data.sessions.some((s) => s.read_only)
? canResume
? "Some {agent} sessions are read only and cannot be deleted."
: "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them."
: canResume
? "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own."
: "magpie can list {agent}'s sessions, but cannot resume or delete them.";
box.append(el("p", "usage-note sm-note", t(key, { agent: a.name })));
}
const prov = providerBar();
if (prov) box.append(prov);
box.append(selectBar(), el("div", "sm-tree"));
queueMicrotask(redrawList);
return box;
}
// Codex lists in its history only the sessions made with the provider it
// uses now; ones made with another (CC Switch's "custom") are there as
// files but hidden from it (#887). They can be moved to Codex's provider
// here, picked in a dialog first, and the last move undone.
const otherProvider = (s) => !s.read_only && s.provider && s.uses_provider && s.provider !== s.uses_provider;
let lastMove = null; // { agent, moved: [{ id, from, to }] }
function providerBar() {
if (data.agent !== "codex") return null;
const hidden = data.sessions.filter(otherProvider);
const undo = lastMove?.agent === data.agent && lastMove.moved.length ? lastMove : null;
if (!hidden.length && !undo) return null;
const bar = el("div", "row sm-provider");
if (hidden.length) {
const from = [...new Set(hidden.map((s) => s.provider))].join(", ");
const to = hidden[0].uses_provider;
bar.append(el("span", "sm-provider-text", t(hidden.length === 1
? "1 Codex session was made with another provider ({from}): Codex lists only {to}'s sessions in its history now, so it doesn't show there."
: "{n} Codex sessions were made with another provider ({from}): Codex lists only {to}'s sessions in its history now, so they don't show there.", { n: hidden.length, from, to })));
const go = el("button", "text sm-provider-move", t("Move to {to}…", { to }));
go.type = "button";
go.onclick = (e) => { e.stopPropagation(); askProvider(hidden); };
bar.append(el("span", "grow"), go);
} else {
bar.append(el("span", "sm-provider-text", t(undo.moved.length === 1 ? "Moved 1 session to {to}" : "Moved {n} sessions to {to}", { n: undo.moved.length, to: undo.moved[0].to })), el("span", "grow"));
}
if (undo) {
const back = el("button", "text sm-provider-undo");
back.type = "button";
back.append(svg(UNDO, 13, 1.4), el("span", "", t("Undo")));
back.onclick = async (e) => {
e.stopPropagation();
back.disabled = true;
const out = await moveProviders(undo.moved.map((m) => ({ id: m.id, to: m.from })));
if (!out) { back.disabled = false; return; }
lastMove = null;
if (!out.refused.length) status(t(out.moved.length === 1 ? "Moved 1 session back" : "Moved {n} sessions back", { n: out.moved.length }), "ok");
await load();
};
bar.append(back);
}
return bar;
}
// moveProviders posts the moves, says what was refused, and gives the
// reply (null when the post failed)
async function moveProviders(moves) {
let out;
try {
out = await api("sessions/codex-provider", { moves });
} catch (err) {
status(err.message, "err");
return null;
}
if (out.refused.length) {
const first = out.refused[0], s = data.sessions.find((x) => x.id === first.id);
const active = out.refused.filter((r) => r.active);
status(active.length ? t(active.length === 1 ? "{title} is still being written to; close it in {agent} and try again in a minute" : "{n} sessions are still being written to; close them in {agent} and try again in a minute", { title: s?.title || first.id, n: active.length, agent: "Codex" })
: (s?.title || first.id) + ": " + first.error, "err");
}
return out;
}
// askProvider: the sessions to move, each ticked, to untick before Move
function askProvider(list) {
const to = list[0].uses_provider;
const chosen = new Set(list.map((s) => s.id));
const ed = el("div", "editor sm-ask sm-provider-ask");
const h = el("div", "ehead");
h.append(icon(current()?.icon || "generic"), el("b", "", t("Move sessions to {to}?", { to })));
ed.append(h);
const names = el("ul", "sm-ask-list sm-provider-list");
const go = el("button", "text primary", t("Move"));
for (const s of list) {
const li = el("li");
const lab = el("label");
const c = el("input", "sm-check");
c.type = "checkbox";
c.checked = true;
c.onchange = () => { c.checked ? chosen.add(s.id) : chosen.delete(s.id); go.disabled = !chosen.size; };
lab.append(c, el("span", "name", s.title || s.id), el("span", "sm-prov", s.provider), el("span", "note", ago(s.last)));
li.append(lab);
names.append(li);
}
ed.append(names);
ed.append(el("p", "lib-confirm", t("Only the provider each one names is changed, in its files and in Codex's database: its messages, id, title and archive stay as they are. A copy of its files is kept in magpie's trash folder first, and Undo moves them back. A session written to in the last minute is left alone.")));
const bar = el("div", "bar");
go.type = "button";
go.onclick = async (e) => {
e.stopPropagation();
go.disabled = true;
go.classList.add("busy");
const out = await moveProviders([...chosen].map((id) => ({ id, to })));
if (!out) { go.disabled = false; go.classList.remove("busy"); return; }
closeConfirmAsk();
lastMove = { agent: data.agent, moved: out.moved };
if (!out.refused.length) status(t(out.moved.length === 1 ? "Moved 1 session to {to}" : "Moved {n} sessions to {to}", { n: out.moved.length, to }), "ok");
await load();
};
const cancel = el("button", "text", t("Cancel"));
cancel.type = "button";
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
cancel.focus({ preventScroll: true });
}
// the bar over the tree: pick every session shown, and delete those picked
function selectBar() {
const bar = el("div", "row-head sm-bar");
const a = current();
if (!a?.deletable) { bar.hidden = true; return bar; }
const list = shown().filter((s) => !s.read_only);
const all = el("input", "sm-check");
all.type = "checkbox";
all.checked = list.length > 0 && list.every((s) => picked.has(s.id));
all.indeterminate = !all.checked && list.some((s) => picked.has(s.id));
all.setAttribute("aria-label", t("Select every session shown"));
all.onchange = () => {
for (const s of list) all.checked ? picked.add(s.id) : picked.delete(s.id);
redrawList();
};
const n = el("span", "note sm-count", picked.size ? t("{n} selected", { n: picked.size }) : t(list.length === 1 ? "{n} session" : "{n} sessions", { n: list.length }));
const del = el("button", "text danger sm-delete");
del.type = "button";
del.disabled = !picked.size;
del.append(svg(TRASH, 13, 1.4), el("span", "", t("Delete")));
del.onclick = () => askDelete([...picked], wholeFolder([...picked]));
bar.append(all, n, el("span", "grow"), del);
return bar;
}
// wholeFolder: the folder (a cwd, "" for none) when ids are every
// session of that one folder, so the dialog names it
function wholeFolder(ids) {
const all = data?.sessions || [];
const set = new Set(ids);
const cwds = new Set(all.filter((s) => set.has(s.id)).map((s) => s.cwd || ""));
if (cwds.size !== 1) return undefined;
const [cwd] = cwds;
return all.filter((s) => (s.cwd || "") === cwd).every((s) => set.has(s.id)) ? cwd : undefined;
}
function redrawList() {
const tree = page.querySelector(".sm-tree");
if (!tree || !data) return;
const bar = page.querySelector(".sm-bar");
if (bar) bar.replaceWith(selectBar());
const list = shown();
// the folder of the latest session is open the first time an agent is shown
if (openedFor !== data.agent) {
openedFor = data.agent;
opened.clear();
if (list[0]) opened.add(list[0].cwd || "");
}
const groups = new Map();
for (const s of list) {
const k = s.cwd || "";
if (!groups.has(k)) groups.set(k, []);
groups.get(k).push(s);
}
tree.replaceChildren();
folderBoxes.clear();
if (!list.length) {
tree.append(el("div", "empty-state", query ? t("No session matches.") : t("No sessions yet")));
return;
}
const q = query.trim();
for (const [cwd, items] of groups) {
const open = !!q || opened.has(cwd);
const g = el("div", "list sm-group");
const r = el("div", "row sm-folder");
const writable = items.filter((s) => !s.read_only);
// the folder's box picks every session of it shown, folded or not,
// for the bar's Delete; the bar still counts sessions (#527)
if (current()?.deletable && writable.length) {
const c = el("input", "sm-check sm-folder-check");
c.type = "checkbox";
// a session's own box ticked or not shows here at once
c.sync = () => {
c.checked = writable.every((s) => picked.has(s.id));
c.indeterminate = !c.checked && writable.some((s) => picked.has(s.id));
};
c.sync();
folderBoxes.set(cwd, c);
c.setAttribute("aria-label", t("Select every session in {folder}", { folder: cwd ? baseName(cwd) : t("No folder") }));
c.onclick = (e) => e.stopPropagation();
c.onchange = () => {
for (const s of writable) c.checked ? picked.add(s.id) : picked.delete(s.id);
redrawList();
};
r.append(c);
}
const fold = el("button", "fold");
fold.type = "button";
fold.setAttribute("aria-expanded", String(open));
fold.append(svg(CHEV_R, 10, 1.6), el("span", "name", cwd ? baseName(cwd) : t("No folder")));
fold.onclick = () => {
if (opened.has(cwd)) opened.delete(cwd); else opened.add(cwd);
redrawList();
};
r.append(fold, el("span", "sub sm-path", cwd), el("span", "grow"), el("span", "note", t(items.length === 1 ? "{n} session" : "{n} sessions", { n: items.length })));
r.title = cwd;
g.append(r);
if (open) for (const s of items) g.append(item(s));
tree.append(g);
}
toFocus();
}
function item(s) {
const a = current();
const wrap = el("div", "sess-item sm-item" + (detail === s.id ? " open" : ""));
const r = el("div", "row sess sm-sess");
r.dataset.id = s.id;
if (a?.deletable && !s.read_only) {
const c = el("input", "sm-check");
c.type = "checkbox";
c.checked = picked.has(s.id);
c.setAttribute("aria-label", t("Select"));
c.onclick = (e) => e.stopPropagation();
c.onchange = () => { c.checked ? picked.add(s.id) : picked.delete(s.id); const bar = page.querySelector(".sm-bar"); if (bar) bar.replaceWith(selectBar()); folderBoxes.get(s.cwd || "")?.sync(); };
r.append(c);
}
const who = el("div", "who");
who.append(el("div", "name", s.title || t("(no prompt)")));
const sub = el("div", "sub", [ago(s.last), sessModelsText(s), s.messages ? t(s.messages === 1 ? "{n} message" : "{n} messages", { n: s.messages }) : "", fmtBytes(s.size), s.id.slice(0, 8)].filter(Boolean).join(" · "));
if (s.via?.length) sub.title = s.via.map(viaText).join("\n");
if (s.wsl) sub.prepend(wslBadge(s), " ");
if (otherProvider(s)) {
const p = el("span", "sm-prov", s.provider);
p.title = t("Made with {from}: Codex's history lists only {to}'s sessions now", { from: s.provider, to: s.uses_provider });
sub.prepend(p, " ");
}
who.append(sub);
// what it spent, as the Usage page's list shows it
r.append(who, ...sessSpent(s));
if (s.resume) {
const res = el("button", "sess-resume", t("Resume"));
res.type = "button";
res.title = t("Copy the command that resumes it: {cmd}", { cmd: s.resume });
res.onclick = async (e) => {
e.stopPropagation();
await copy(s.resume, t("Resume command"));
res.textContent = t("Copied");
res.classList.add("done");
clearTimeout(res.copiedT);
res.copiedT = setTimeout(() => { res.textContent = t("Resume"); res.classList.remove("done"); }, 1400);
};
r.append(res);
if (data.terminal) {
const term = el("button", "copy sess-term");
term.type = "button";
term.title = t("Open in session terminal");
term.append(svg(TERM, 13, 1.6));
term.onclick = (e) => {
e.stopPropagation();
api("sessions/terminal", { agent: s.agent, id: s.id }).then(() => status(t("Opening in session terminal"), "ok"), (err) => status(err.message, "err"));
};
r.append(term);
}
}
if (s.carry?.length) r.append(carryPick(s));
if (a?.deletable && !s.read_only) {
const del = el("button", "copy sm-del");
del.type = "button";
del.title = t("Delete");
del.setAttribute("aria-label", t("Delete"));
del.append(svg(TRASH, 13, 1.4));
del.onclick = (e) => { e.stopPropagation(); askDelete([s.id]); };
r.append(del);
}
r.onclick = () => {
if (window.getSelection()?.toString()) return;
detail = detail === s.id ? "" : s.id;
redrawList();
};
wrap.append(r);
if (detail === s.id) wrap.append(details(s));
return wrap;
}
function details(s) {
const d = el("div", "sess-detail");
const line = (k, v, extra) => {
const l = el("div", "sess-line");
l.append(el("span", "k", k), v instanceof Node ? v : el("span", "v", v));
if (extra) l.append(extra);
d.append(l);
};
line(t("Time"), stamp(s.start || s.last) + " – " + stamp(s.last));
if (s.wsl) line("WSL", s.wsl);
if (s.cwd) line(t("Folder"), s.cwd);
line(t("Session ID"), s.id, copyBtn(s.id, t("Session id")));
if (s.resume) line(t("Resume"), el("code", "", s.resume), copyBtn(s.resume, t("Resume command")));
for (const c of s.carry || []) line(t("Continue in {agent}", { agent: agentOf(c.agent).name }), el("code", "", c.command), copyBtn(c.command, t("Command")));
sessUsageDetail(d, s, line);
if (s.path) line(t("File"), s.path + (s.files > 1 ? " " + t("+{n} more", { n: s.files - 1 }) : ""));
if (s.transcript) {
const box = el("div", "sess-talk");
const b = el("button", "text sess-talk-btn");
b.type = "button";
const show = () => {
const on = talkOpen.has(s.agent + "/" + s.id);
b.textContent = t(on ? "Hide conversation" : "Show conversation");
b.setAttribute("aria-expanded", String(on));
box.hidden = !on;
if (on) drawTalk(box, s);
};
b.onclick = (e) => {
e.stopPropagation();
const k = s.agent + "/" + s.id;
if (talkOpen.has(k)) talkOpen.delete(k); else talkOpen.add(k);
show();
};
line(t("Conversation"), b);
d.append(box);
show();
}
return d;
}
// agentOf is an agent as the page names it: of those with sessions, else
// by its id
const agentOf = (id) => data?.agents.find((x) => x.agent === id) || { agent: id, name: id, icon: id };
// carryPick is the other agents that can carry a session on from its
// file as it is (#845; oh-my-pi forks a Pi session), in the app's menu:
// copy the command, or open it in the session terminal.
function carryPick(s) {
const b = el("button", "sess-pick sess-carry");
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.title = t("Continue this session in another agent");
b.append(el("span", "", t("Continue in")), svg(CHEV, 11, 1.6));
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
const opts = [];
for (const c of s.carry) {
const name = agentOf(c.agent).name;
opts.push({ v: "copy\x01" + c.agent, name, literalName: true, note: "Copy the command", title: c.command });
if (data.terminal) opts.push({ v: "term\x01" + c.agent, name, literalName: true, note: "Open in session terminal", title: c.command });
}
openProtoMenu(b, opts, "", (v) => {
b.focus({ preventScroll: true });
const [how, to] = v.split("\x01");
const c = s.carry.find((x) => x.agent === to);
if (!c) return;
if (how === "copy") copy(c.command, t("Command"));
else api("sessions/terminal", { agent: s.agent, id: s.id, in: to }).then(() => status(t("Opening in session terminal"), "ok"), (err) => status(err.message, "err"));
}, "Continue in another agent", "sess-carry-menu", "right");
};
return b;
}
// drawTalk fills box with what was said in a session, read from the
// agent's own file when it is first shown (only read, never written)
function drawTalk(box, s) {
const k = s.agent + "/" + s.id;
const got = talks.get(k);
if (!got) {
box.replaceChildren(el("p", "cx-none", t("Reading…")));
talks.set(k, { busy: true });
api("sessions/transcript?agent=" + encodeURIComponent(s.agent) + "&id=" + encodeURIComponent(s.id))
.then((tr) => talks.set(k, { tr }), (err) => talks.set(k, { err: err.message }))
.then(() => { if (box.isConnected && talkOpen.has(k)) drawTalk(box, s); });
return;
}
if (got.busy) return;
if (got.err) { box.replaceChildren(el("p", "cx-none", got.err)); talks.delete(k); return; }
const parts = got.tr?.parts || [];
const out = [];
if (!parts.length) out.push(el("p", "cx-none", t("Nothing was said here")));
for (const p of parts) out.push(ledSaid(p));
if (got.tr?.cut) out.push(el("p", "cx-none", t("There was more than is shown here")));
out.push(el("p", "cx-src", t("Read from the agent's session file; magpie keeps no copy")));
box.replaceChildren(...out);
}
// askDelete asks in magpie's dialog before the sessions go to its trash;
// folder (a cwd, "" for none) when they are every session of one folder
function askDelete(ids, folder) {
const byID = new Map((data?.sessions || []).map((s) => [s.id, s]));
const list = ids.map((id) => byID.get(id)).filter(Boolean);
if (!list.length) return;
const a = current();
const ed = el("div", "editor sm-ask");
const h = el("div", "ehead");
const whole = folder !== undefined && list.length > 1;
// picked folders each whole: how many folders, as well as sessions
const cwds = new Set(list.map((s) => s.cwd || ""));
const folders = !whole && cwds.size > 1 && (data?.sessions || []).every((s) => !cwds.has(s.cwd || "") || ids.includes(s.id)) ? cwds.size : 0;
h.append(icon(a.icon), el("b", "", list.length === 1 ? t("Delete this session?")
: whole ? t("Delete all {n} sessions in {folder}?", { n: list.length, folder: folder ? baseName(folder) : t("No folder") })
: folders ? t("Delete all {n} sessions in {k} folders?", { n: list.length, k: folders })
: t("Delete {n} sessions?", { n: list.length })));
ed.append(h);
if (folder) ed.append(el("p", "sub sm-ask-path", folder));
const names = el("ul", "sm-ask-list");
for (const s of list.slice(0, 5)) names.append(el("li", "", s.title || s.id));
if (list.length > 5) names.append(el("li", "more", t("+{n} more", { n: list.length - 5 })));
ed.append(names);
ed.append(el("p", "lib-confirm", t("Their files are moved to magpie's trash ({dir}), not erased: Trash puts them back. A session written to in the last minute is left alone, as {agent} may still be running it.", { dir: data.trashDir, agent: a.name })));
const bar = el("div", "bar");
const go = el("button", "text primary danger-fill", t("Delete"));
go.type = "button";
go.onclick = async (e) => {
e.stopPropagation();
go.disabled = true;
go.classList.add("busy");
let out;
try {
out = await api("sessions/delete", { agent: data.agent, ids: list.map((s) => s.id) });
} catch (err) {
go.disabled = false;
go.classList.remove("busy");
status(err.message, "err");
return;
}
closeConfirmAsk();
for (const id of out.deleted) { picked.delete(id); if (detail === id) detail = ""; }
const active = out.refused.filter((r) => r.active);
if (out.refused.length) {
const first = out.refused[0], s = byID.get(first.id);
status(active.length ? t(active.length === 1 ? "{title} is still being written to; close it in {agent} and try again in a minute" : "{n} sessions are still being written to; close them in {agent} and try again in a minute", { title: s?.title || first.id, n: active.length, agent: a.name })
: (s?.title || first.id) + ": " + first.error, "err");
} else {
status(t(out.deleted.length === 1 ? "Moved to magpie's trash" : "{n} sessions moved to magpie's trash", { n: out.deleted.length }), "ok");
}
await load();
};
const cancel = el("button", "text", t("Cancel"));
cancel.type = "button";
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
cancel.focus({ preventScroll: true });
}
// askPurge asks in magpie's dialog before trashed sessions are erased for
// good: the ones listed, or the whole trash (all)
function askPurge(list, all) {
if (!list.length) return;
const ed = el("div", "editor sm-ask sm-ask-purge");
const h = el("div", "ehead");
h.append(svg(TRASH, 15, 1.4), el("b", "", all ? t("Empty magpie's trash?") : t("Delete this session forever?")));
ed.append(h);
const names = el("ul", "sm-ask-list");
for (const x of list.slice(0, 5)) names.append(el("li", "", x.title || x.id));
if (list.length > 5) names.append(el("li", "more", t("+{n} more", { n: list.length - 5 })));
ed.append(names);
ed.append(el("p", "lib-confirm", all ? t("Every session in magpie's trash is erased for good: it can't be restored.") : t("Its files are erased for good: it can't be restored.")));
const bar = el("div", "bar");
const go = el("button", "text primary danger-fill", all ? t("Empty trash") : t("Delete forever"));
go.type = "button";
go.onclick = async (e) => {
e.stopPropagation();
go.disabled = true;
go.classList.add("busy");
let out;
try {
out = await api("sessions/purge", all ? { all: true } : { keys: list.map((x) => x.key) });
} catch (err) {
go.disabled = false;
go.classList.remove("busy");
status(err.message, "err");
return;
}
closeConfirmAsk();
if (out.refused.length) {
const first = out.refused[0], x = list.find((y) => y.key === first.key);
status((x?.title || x?.id || first.key) + ": " + first.error, "err");
} else {
status(t(out.purged.length === 1 ? "Erased for good" : "{n} sessions erased for good", { n: out.purged.length }), "ok");
}
await load();
};
const cancel = el("button", "text", t("Cancel"));
cancel.type = "button";
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
cancel.focus({ preventScroll: true });
}
function trash() {
const out = [];
const items = data.trash;
if (items.length) {
const bar = el("div", "row-head sm-bar sm-trash-bar");
const empty = el("button", "text danger sm-empty");
empty.type = "button";
empty.append(svg(TRASH, 13, 1.4), el("span", "", t("Empty trash")));
empty.onclick = () => askPurge(items, true);
bar.append(el("span", "note sm-count", t(items.length === 1 ? "{n} session" : "{n} sessions", { n: items.length })), el("span", "grow"), empty);
out.push(bar);
}
if (!items.length) {
const e = el("div", "empty-state");
e.append(el("b", "", t("Trash is empty")), el("span", "", t("Sessions deleted here wait in magpie's trash, to be restored.")));
out.push(e);
} else {
const l = el("div", "list sm-group sm-trash");
for (const x of items) {
const r = el("div", "row sess");
r.append(icon(x.icon));
const who = el("div", "who");
who.append(el("div", "name", x.title || x.id));
who.append(el("div", "sub", [x.name, x.cwd ? baseName(x.cwd) : "", t("deleted {when}", { when: ago(x.deleted) }), fmtBytes(x.size)].filter(Boolean).join(" · ")));
who.title = x.items.map((i) => i.from).join("\n");
r.append(who);
const b = el("button", "sess-resume sm-restore");
b.type = "button";
b.append(svg(UNDO, 12, 1.5), el("span", "", t("Restore")));
b.onclick = async (e) => {
e.stopPropagation();
b.disabled = true;
try {
await api("sessions/restore", { key: x.key });
status(t("{title} restored", { title: x.title || x.id }), "ok");
} catch (err) {
b.disabled = false;
status(err.message, "err");
return;
}
await load();
};
r.append(b);
const del = el("button", "copy sm-del sm-purge");
del.type = "button";
del.title = t("Delete forever");
del.setAttribute("aria-label", t("Delete forever"));
del.append(svg(TRASH, 13, 1.4));
del.onclick = (e) => { e.stopPropagation(); askPurge([x], false); };
r.append(del);
l.append(r);
}
out.push(l);
}
out.push(el("p", "usage-note", t("Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.", { dir: data.trashDir })));
return out;
}
})();