Files

729 lines
35 KiB
HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Background shells</title>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: transparent; overflow: hidden; }
body {
font: 12px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
color: hsl(var(--foreground, 222 47% 11%));
-webkit-font-smoothing: antialiased;
}
#root:empty { display: none; }
.card {
border: 1px solid hsl(var(--border, 214 32% 91%));
background: hsl(var(--card, 0 0% 100%));
border-radius: 12px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 6px;
}
.head {
display: flex; align-items: center; gap: 5px;
font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em;
color: hsl(var(--muted-foreground, 215 16% 47%));
white-space: nowrap;
}
.head > span:first-of-type { overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.head .cnt { flex-shrink: 0; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-variant-numeric: tabular-nums; }
.head .run { margin-left: auto; flex-shrink: 0; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-transform: none; letter-spacing: 0; color: #d97706; }
html.dark .head .run { color: #fbbf24; }
.head svg { width: 14px; height: 14px; flex-shrink: 0; }
.head .ico-pri { color: hsl(var(--primary, 24 95% 53%)); }
.head .ico-amb { color: #f59e0b; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 50% { opacity: .4; } }
.list { display: flex; flex-direction: column; gap: 4px; }
.row {
border: 1px solid hsl(var(--border, 214 32% 91%) / .7);
background: hsl(var(--muted, 210 40% 96%) / .25);
border-radius: 7px;
font-size: 12px;
transition: border-color .15s, background .15s;
}
.row.live { border-color: rgb(245 158 11 / .42); background: rgb(245 158 11 / .07); }
.row-pad { padding: 6px 6px; }
.row-btn {
display: flex; align-items: center; gap: 5px; width: 100%; min-width: 0;
border: 0; background: transparent; padding: 0; margin: 0; text-align: left;
color: inherit; font: inherit; cursor: pointer;
}
.row-btn .chev { width: 12px; height: 12px; flex-shrink: 0; color: hsl(var(--muted-foreground)); transition: transform .15s; }
.row.open .row-btn .chev { transform: rotate(90deg); }
.row-btn .tico { width: 13px; height: 13px; flex-shrink: 0; color: hsl(var(--muted-foreground)); }
.row.live .row-btn .tico { color: #f59e0b; }
.row-btn .lbl { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; }
.meta-line { display: flex; align-items: center; gap: 3px; margin-top: 3px; padding-left: 17px; min-width: 0; }
.meta-left { display: flex; align-items: center; gap: 4px; flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; }
.meta-time { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 9.5px; font-variant-numeric: tabular-nums;
color: hsl(var(--muted-foreground)); overflow: hidden; text-overflow: ellipsis; }
.acts { display: flex; align-items: center; flex-shrink: 0; margin: -2px 0; }
.ibtn {
display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px;
border: 0; border-radius: 5px; background: transparent; color: hsl(var(--muted-foreground));
cursor: pointer; padding: 0;
}
.ibtn:hover:not(:disabled) { background: hsl(var(--accent, 210 40% 96%)); color: hsl(var(--foreground)); }
.ibtn:disabled { opacity: .4; cursor: default; }
.ibtn.stop { color: #f43f5e; }
.ibtn.stop:hover:not(:disabled) { color: #e11d48; }
.ibtn.ok { color: #22c55e; }
.ibtn svg { width: 11px; height: 11px; }
.ibtn .spin { animation: spin 1s linear infinite; }
.pill {
display: inline-flex; align-items: center; gap: 3.5px; flex-shrink: 0; white-space: nowrap;
border-radius: 999px; border: 1px solid hsl(var(--border)); background: hsl(var(--muted) / .5);
color: hsl(var(--muted-foreground)); padding: 0 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 9.5px; line-height: 15px;
}
.pill.amber { border-color: rgb(245 158 11 / .4); background: rgb(245 158 11 / .1); color: #d97706; }
html.dark .pill.amber { color: #fbbf24; }
.pill.green { border-color: rgb(16 185 129 / .4); background: rgb(16 185 129 / .1); color: #059669; }
html.dark .pill.green { color: #34d399; }
.pill.red { border-color: rgb(239 68 68 / .4); background: rgb(239 68 68 / .1); color: #dc2626; }
html.dark .pill.red { color: #f87171; }
.pill .dot { width: 5px; height: 5px; border-radius: 999px; background: currentColor; animation: pulse 1.5s ease-in-out infinite; }
.read-line { margin-top: 2px; padding-left: 17px; display: flex; }
.preview {
display: block; width: 100%; margin-top: 2px; padding: 0 0 0 17px; border: 0; background: transparent;
text-align: left; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 10.5px;
color: hsl(var(--muted-foreground)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer;
}
.preview:hover { color: hsl(var(--foreground)); }
.confirm {
display: flex; align-items: center; gap: 6px; border-top: 1px solid rgb(245 158 11 / .3);
padding: 6px 8px; font-size: 11px;
}
.confirm span { flex: 1; min-width: 0; color: hsl(var(--muted-foreground)); }
.cbtn { border: 0; border-radius: 6px; padding: 2px 8px; font: inherit; cursor: pointer; background: transparent; color: hsl(var(--muted-foreground)); }
.cbtn:hover { background: hsl(var(--muted)); }
.cbtn.danger { background: #f43f5e; color: #fff; font-weight: 500; }
.cbtn.danger:hover { background: #e11d48; }
.body { border-top: 1px solid hsl(var(--border) / .6); padding: 6px 8px; }
.muted { font-size: 11px; color: hsl(var(--muted-foreground)); }
.err { font-size: 11px; color: #dc2626; }
html.dark .err { color: #f87171; }
.tail-meta { margin-bottom: 2px; font-size: 10px; color: hsl(var(--muted-foreground)); }
pre.tail {
margin: 0; max-height: 280px; overflow: auto; border-radius: 6px;
background: #171717; color: #e5e5e5; padding: 6px 10px;
font: 10.5px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
white-space: pre-wrap; word-break: break-word;
}
.tail-empty { color: #737373; }
.tail-ok { color: #34d399; }
.tail-bad { color: #fb7185; }
.tail-cur { color: #fbbf24; animation: pulse 1s ease-in-out infinite; }
.tl { margin-left: 4px; padding-left: 14px; border-left: 1.5px solid hsl(var(--border));
display: flex; flex-direction: column; gap: 4px; max-height: 280px; overflow-y: auto; }
.tl-row { position: relative; font-size: 11.5px; line-height: 1.35; min-width: 0; }
.tl-dot { position: absolute; left: -19px; top: 5px; width: 8px; height: 8px; border-radius: 999px;
border: 1.5px solid hsl(var(--muted-foreground)); background: hsl(var(--card)); }
.tl-dot.event { border-color: hsl(var(--primary)); }
.tl-dot.ended { border-color: #10b981; background: #10b981; }
.tl-dot.expired { border-color: #f59e0b; }
.tl-dot.failed, .tl-dot.killed { border-color: #ef4444; background: #ef4444; }
.tl-t { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 10px;
color: hsl(var(--muted-foreground)); margin-right: 6px; }
.tl-k { color: hsl(var(--muted-foreground)); margin-right: 6px; }
.tl-txt { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11px;
white-space: pre-wrap; word-break: break-word; }
.fold-btn {
display: flex; align-items: center; gap: 4px; width: 100%; border: 0; border-radius: 6px;
background: transparent; padding: 2px 4px; text-align: left; font: 11px/1.4 inherit;
color: hsl(var(--muted-foreground)); cursor: pointer;
}
.fold-btn:hover { background: hsl(var(--muted) / .5); color: hsl(var(--foreground)); }
.fold-btn svg { width: 12px; height: 12px; transition: transform .15s; }
.fold-btn.open svg { transform: rotate(90deg); }
.more-btn {
width: 100%; border: 0; border-radius: 6px; background: transparent; padding: 2px 0;
font: 11px/1.4 inherit; color: hsl(var(--muted-foreground)); cursor: pointer;
}
.more-btn:hover { background: hsl(var(--muted) / .5); color: hsl(var(--foreground)); }
@media (prefers-reduced-motion: reduce) { .head .ico-amb, .pill .dot, .tail-cur { animation: none; } }
</style>
</head>
<body>
<div id="root"></div>
<script>
(function () {
"use strict";
var P = window.aiAgentPlugin || {};
var init = P.init || {};
var first = init.update || {};
var root = document.getElementById("root");
// reuseFrame: the host keeps this frame across conversation switches, so the
// ids live in init.update / onUpdate (init.* only on older hosts).
var cid = String(first.conversationId || init.conversationId || "");
var sid = String(first.sessionId || init.sessionId || "");
var running = !!first.running;
var drawerOpen = first.drawerOpen !== false;
var TAIL_LINES = 20;
var SHELL_DONE = { completed: 1, failed: 1, killed: 1, stopped: 1 };
var MON_DONE = { completed: 1, expired: 1, stopped: 1, failed: 1, killed: 1 };
var LANG = "en";
function setLang(l) {
LANG = String(l || document.documentElement.lang || navigator.language || "en").slice(0, 2).toLowerCase() === "fr" ? "fr" : "en";
}
setLang(init.lang || first.lang);
var FR = {
"Background shells": "Shells en arrière-plan",
"{n} running": "{n} en cours",
"Finished ({n})": "Terminés ({n})",
"Show {n} more": "Afficher {n} de plus",
"stopped by you": "arrêté par toi",
"no end notice": "pas d'avis de fin",
"the run ended before the shell reported back": "la session s'est arrêtée avant que le shell ne donne de nouvelles",
"Stopped (it needed a SIGKILL)": "Arrêté (il a fallu un SIGKILL)",
"Stopped": "Arrêté",
"Couldn't stop it: {err}": "Impossible de l'arrêter : {err}",
"Fold": "Replier",
"Show output": "Afficher la sortie",
"stopping…": "arrêt…",
"ran {dur}": "a tourné {dur}",
"Jump to its card in the thread": "Aller à sa carte dans le fil",
"Copy command": "Copier la commande",
"Copied!": "Copié !",
"Stop it": "L'arrêter",
"Stop this Monitor? Claude gets its end notice.": "Arrêter ce Monitor ? Claude reçoit son avis de fin.",
"Stop this shell? Claude sees it exit.": "Arrêter ce shell ? Claude le voit se terminer.",
"Cancel": "Annuler",
"Stop": "Arrêter",
"no events yet": "pas encore d'événement",
"Reading its output…": "Lecture de sa sortie…",
"Output not available: {why}": "Sortie indisponible : {why}",
"no output file": "pas de fichier de sortie",
"last {n} lines": "{n} dernières lignes",
"(no output yet)": "(pas encore de sortie)",
"armed": "armé",
"arming": "démarrage",
"watching": "surveillance",
"watching · {dur}": "surveillance · {dur}",
"ended · {events}": "terminé · {events}",
"expired · {events}": "expiré · {events}",
"stopped · {events}": "arrêté · {events}",
"no end notice · {events}": "fin non signalée · {events}",
"no notification closed this watch": "aucune notification n'a clôturé cette surveillance",
"no events": "aucun événement",
"{n} event": "{n} événement",
"{n} events": "{n} événements",
"{n} earlier event": "{n} événement précédent",
"{n} earlier events": "{n} événements précédents",
"ended": "terminé", "expired": "expiré", "stopped": "arrêté", "failed": "échec", "killed": "tué",
"exit {code}": "code {code}",
"done · exit {code}": "fini · code {code}",
"done": "fini",
"in background": "en arrière-plan",
"not read yet · {dur}": "pas encore lu · {dur}",
"It ended, but Claude reads it only after its current step: one long response holds it back.": "Il est fini, mais Claude ne le lit qu'après son étape en cours : une seule longue réponse le retient.",
"never read": "jamais lu",
"The run stopped before Claude Code handed Claude this result.": "La session s'est arrêtée avant que Claude Code ne remette ce résultat à Claude.",
"read {dur} later": "lu {dur} plus tard",
"Claude was mid-response when it ended, and read it {dur} after.": "Claude était en pleine réponse quand il a fini, et l'a lu {dur} après."
};
function t(s, vars) {
var out = LANG === "fr" && FR[s] ? FR[s] : s;
return out.replace(/\{(\w+)\}/g, function (m, k) { return vars && vars[k] != null ? String(vars[k]) : m; });
}
function tn(n, one, many) { return t(n === 1 ? one : many, { n: n }); }
function esc(s) {
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
});
}
function msOf(iso) { if (!iso) return null; var n = Date.parse(iso); return isNaN(n) ? null : n; }
function fmtDur(ms) {
var s = Math.max(0, Math.round(ms / 1000));
if (s < 60) return s + "s";
var m = Math.floor(s / 60), rs = s % 60;
if (m < 60) return rs ? m + "m " + rs + "s" : m + "m";
var h = Math.floor(m / 60), rm = m % 60;
return rm ? h + "h " + rm + "m" : h + "h";
}
function fmtSize(n) {
if (n < 1024) return n + " B";
if (n < 1048576) return (n / 1024).toFixed(1) + " KB";
return (n / 1048576).toFixed(1) + " MB";
}
function clock(ms, secs) {
return new Date(ms).toLocaleTimeString(LANG === "fr" ? "fr-FR" : "en-US",
secs ? { hour: "2-digit", minute: "2-digit", second: "2-digit" } : { hour: "2-digit", minute: "2-digit" });
}
function svg(body, cls) {
return '<svg class="' + (cls || "") + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + body + "</svg>";
}
var ICO = {
term: '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="m7 11 2-2-2-2"/><path d="M11 13h4"/>',
act: '<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/>',
spin: '<path d="M21 12a9 9 0 1 1-6.219-8.56"/>',
chev: '<path d="m9 18 6-6-6-6"/>',
jump: '<polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/>',
copy: '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
check: '<path d="M20 6 9 17l-5-5"/>',
stop: '<circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/>'
};
function monState(task, now) {
if (task.isError) return "failed";
if (MON_DONE[task.taskState]) return task.taskState;
if (!task.result) return "starting";
var armedAt = msOf(task.ts);
var m = /expires in (\d+)\s*(m|s|min)\b/.exec(task.result || "");
var ttl = m ? Number(m[1]) * (m[2] === "s" ? 1000 : 60000) : (typeof task.timeoutMs === "number" ? task.timeoutMs : null);
if (armedAt != null && ttl != null && now > armedAt + ttl + 60000) return "silent";
return "watching";
}
function monCount(task) {
var evs = task.taskEvents || [];
var c = task.taskEventsDropped || 0;
for (var i = 0; i < evs.length; i++) {
if (evs[i].kind === "event" || (evs[i].kind === "ended" && String(evs[i].text || "").trim())) c++;
}
return c;
}
function isLive(task, now) {
if (!running) return false;
if (task.kind === "monitor") {
var s = monState(task, now);
return s === "watching" || s === "starting";
}
return !SHELL_DONE[task.taskState || ""];
}
function rowChip(task, live, now) {
if (task.stoppedAt != null && !live) return { label: t("stopped by you"), tone: "muted" };
if (!live && task.kind === "shell" && !SHELL_DONE[task.taskState || ""]) {
return { label: t("no end notice"), tone: "muted", title: t("the run ended before the shell reported back") };
}
if (task.kind === "monitor") {
var st = monState(task, now);
var cnt = monCount(task);
var evs = cnt ? tn(cnt, "{n} event", "{n} events") : t("no events");
var armedAt = msOf(task.ts);
if (st === "starting") return { label: t("arming"), tone: "amber", pulse: true };
if (st === "watching") return { label: armedAt != null ? t("watching · {dur}", { dur: fmtDur(now - armedAt) }) : t("watching"), tone: "amber", pulse: true };
if (st === "completed") return { label: t("ended · {events}", { events: evs }), tone: "green" };
if (st === "expired") return { label: t("expired · {events}", { events: evs }), tone: "muted" };
if (st === "stopped") return { label: t("stopped · {events}", { events: evs }), tone: "muted" };
if (st === "silent") return { label: t("no end notice · {events}", { events: evs }), tone: "muted", title: t("no notification closed this watch") };
return { label: t(st === "killed" ? "killed" : "failed"), tone: "red" };
}
var code = task.taskExitCode;
if (task.taskState === "completed") {
return code != null && code !== 0
? { label: t("exit {code}", { code: code }), tone: "red" }
: { label: code != null ? t("done · exit {code}", { code: code }) : t("done"), tone: "green" };
}
if (task.taskState === "failed" && code != null) return { label: t("exit {code}", { code: code }), tone: "red" };
if (task.taskState === "failed" || task.taskState === "killed") {
return { label: t(task.taskState), tone: "red" };
}
if (task.taskState === "stopped") return { label: t("stopped"), tone: "muted" };
return { label: t("in background"), tone: "amber", pulse: true };
}
function readChip(task, now) {
if (task.kind !== "shell") return null;
var unread = msOf(task.taskUnreadAt);
if (unread != null) {
return running
? { label: t("not read yet · {dur}", { dur: fmtDur(now - unread) }), tone: "amber", pulse: true,
title: t("It ended, but Claude reads it only after its current step: one long response holds it back.") }
: { label: t("never read"), tone: "muted",
title: t("The run stopped before Claude Code handed Claude this result.") };
}
var readAt = msOf(task.taskReadAt);
var evs = task.taskEvents || [];
var ended = null;
for (var i = evs.length - 1; i >= 0; i--) { if (evs[i].kind !== "event") { ended = msOf(evs[i].ts); break; } }
if (readAt == null || ended == null || readAt - ended < 30000) return null;
var dur = fmtDur(readAt - ended);
return { label: t("read {dur} later", { dur: dur }), tone: "muted",
title: t("Claude was mid-response when it ended, and read it {dur} after.", { dur: dur }) };
}
function lastEventLine(task) {
var evs = task.taskEvents || [];
for (var i = evs.length - 1; i >= 0; i--) {
var txt = String(evs[i].text || "").trim();
if (txt) {
var lines = txt.split("\n").filter(Boolean);
if (lines.length) return lines[lines.length - 1];
}
}
return "";
}
function endMs(task) {
var evs = task.taskEvents || [];
for (var i = evs.length - 1; i >= 0; i--) { if (evs[i].kind !== "event") return msOf(evs[i].ts); }
return null;
}
var state = {
data: null,
open: {},
confirm: {},
copied: {},
stopping: {},
outputs: {}, // taskId -> { loading, data, error }
showDone: null, // null = auto (true when no live rows)
limit: 8
};
var lastH = -1;
function fit() {
var h = root.firstChild ? Math.ceil(root.getBoundingClientRect().height) : 0;
if (h === lastH) return;
lastH = h;
if (P.setEmpty) P.setEmpty(h === 0);
if (P.resize) P.resize(h);
}
if (window.ResizeObserver) new ResizeObserver(fit).observe(root);
// agy's task ids are "<conversation>/task-N": no tasks/<id>.output to tail
// on its runner and nothing the hub can stop — its card shows the events.
function hasTail(task) { return task.kind === "shell" && String(task.taskId || "").indexOf("/") < 0; }
function fetchOutput(taskId) {
if (!cid || !P.action) return;
var cur = state.outputs[taskId];
if (!cur) state.outputs[taskId] = { loading: true, data: null, error: null };
var forCid = cid;
P.action("output", { conversationId: cid, sessionId: sid, taskId: taskId, lines: TAIL_LINES }).then(
function (res) {
if (forCid !== cid) return; // answer for a conversation we left
state.outputs[taskId] = { loading: false, data: res, error: null };
render();
},
function (err) {
if (forCid !== cid) return;
state.outputs[taskId] = { loading: false, data: null, error: String((err && err.message) || err) };
render();
}
);
}
function renderPill(chip, overrideLabel) {
if (!chip) return "";
return '<span class="pill ' + esc(chip.tone || "muted") + '"' + (chip.title ? ' title="' + esc(chip.title) + '"' : "") + '>' +
(chip.pulse ? '<span class="dot"></span>' : "") + esc(overrideLabel || chip.label) + "</span>";
}
function renderTimeline(task) {
var armedAt = msOf(task.ts);
var evs = task.taskEvents || [];
var dropped = task.taskEventsDropped || 0;
if (!evs.length && armedAt == null) return '<div class="muted">' + esc(t("no events yet")) + "</div>";
var h = '<div class="tl">';
if (armedAt != null) {
h += '<div class="tl-row"><span class="tl-dot"></span><span class="tl-t">' + esc(clock(armedAt, true)) + '</span><span class="tl-k">' + esc(t("armed")) + "</span></div>";
}
if (dropped > 0) {
h += '<div class="tl-row"><span class="tl-dot"></span><span class="tl-k">… ' + esc(tn(dropped, "{n} earlier event", "{n} earlier events")) + "</span></div>";
}
for (var i = 0; i < evs.length; i++) {
var e = evs[i], at = msOf(e.ts), txt = String(e.text || "").trim();
if (txt.length > 600) txt = txt.slice(0, 600) + "…";
h += '<div class="tl-row"><span class="tl-dot ' + esc(e.kind || "") + '"></span>' +
(at != null ? '<span class="tl-t">' + esc(clock(at, true)) + "</span>" : "") +
(e.kind && e.kind !== "event" ? '<span class="tl-k">' + esc(t(e.kind)) + "</span>" : "") +
(txt ? '<span class="tl-txt">' + esc(txt) + "</span>" : "") + "</div>";
}
return h + "</div>";
}
function renderTail(task, live) {
var o = state.outputs[task.taskId];
if (!o || o.loading) return '<div class="muted">' + esc(t("Reading its output…")) + "</div>";
if (o.error) return '<div class="err">' + esc(o.error) + "</div>";
var d = o.data;
if (!d) return "";
if (!d.available) {
return '<div class="muted">' + esc(t("Output not available: {why}", { why: d.reason || t("no output file") })) + "</div>";
}
var lines = Array.isArray(d.lines) ? d.lines : [];
var h = "";
if (d.more) {
h += '<div class="tail-meta">' + esc(t("last {n} lines", { n: TAIL_LINES })) +
(d.size != null ? " · " + esc(fmtSize(d.size)) : "") + "</div>";
}
h += '<pre class="tail">';
h += lines.length ? esc(lines.join("\n")) : '<span class="tail-empty">' + esc(t("(no output yet)")) + "</span>";
if (d.end) {
var ok = /code 0$/.test(d.end);
h += '\n<span class="' + (ok ? "tail-ok" : "tail-bad") + '">[' + esc(d.end) + "]</span>";
} else if (live) {
h += '\n<span class="tail-cur">▍</span>';
}
return h + "</pre>";
}
function renderRow(task, canStop, now) {
var tid = task.taskId;
var live = isLive(task, now);
var open = !!state.open[tid];
var confirm = !!state.confirm[tid] && live;
var copied = !!state.copied[tid];
var stopping = !!state.stopping[tid];
var chip = rowChip(task, live, now);
var rchip = readChip(task, now);
var startedAt = msOf(task.ts);
var span = startedAt != null ? (live ? now : (endMs(task) || task.stoppedAt || null)) : null;
var dur = startedAt != null && span != null ? fmtDur(Math.max(0, span - startedAt)) : null;
var o = state.outputs[tid];
var tail = hasTail(task) && o && o.data && o.data.available && Array.isArray(o.data.lines) ? o.data.lines : [];
var last = task.kind === "shell" ? (tail.length ? tail[tail.length - 1] : lastEventLine(task)) : lastEventLine(task);
var h = '<div class="row' + (live ? " live" : "") + (open ? " open" : "") + '" data-tid="' + esc(tid) + '"><div class="row-pad">';
h += '<button type="button" class="row-btn" data-act="toggle" data-tid="' + esc(tid) + '" aria-expanded="' + (open ? "true" : "false") + '" title="' + esc(t(open ? "Fold" : "Show output")) + '">' +
svg(ICO.chev, "chev") + svg(task.kind === "monitor" ? ICO.act : ICO.term, "tico") +
'<span class="lbl"' + (task.command ? ' title="' + esc(task.command) + '"' : "") + ">" + esc(task.label || tid) + "</span></button>";
h += '<div class="meta-line"><div class="meta-left">' +
renderPill(chip, stopping ? t("stopping…") : null) +
(dur && task.kind === "shell" ? '<span class="meta-time">' + esc(live ? dur : t("ran {dur}", { dur: dur })) + "</span>" : "") +
(startedAt != null ? '<span class="meta-time">· ' + esc(clock(startedAt, false)) + "</span>" : "") +
'</div><div class="acts">';
h += '<button type="button" class="ibtn" data-act="jump" data-tu="' + esc(task.toolUseId || "") + '" title="' + esc(t("Jump to its card in the thread")) + '"' + (!task.toolUseId ? " disabled" : "") + ">" + svg(ICO.jump) + "</button>";
if (task.command) {
h += '<button type="button" class="ibtn' + (copied ? " ok" : "") + '" data-act="copy" data-tid="' + esc(tid) + '" title="' + esc(t(copied ? "Copied!" : "Copy command")) + '">' + svg(copied ? ICO.check : ICO.copy) + "</button>";
}
if (live && canStop && String(tid).indexOf("/") < 0) {
h += '<button type="button" class="ibtn stop" data-act="ask-stop" data-tid="' + esc(tid) + '" title="' + esc(t("Stop it")) + '"' + (stopping ? " disabled" : "") + ">" + svg(stopping ? ICO.spin : ICO.stop, stopping ? "spin" : "") + "</button>";
}
h += "</div></div>";
if (rchip) h += '<div class="read-line">' + renderPill(rchip) + "</div>";
if (last && !open) {
h += '<button type="button" class="preview" data-act="open" data-tid="' + esc(tid) + '" title="' + esc(last) + '">' + esc(last) + "</button>";
}
h += "</div>";
if (confirm) {
h += '<div class="confirm"><span>' + esc(t(task.kind === "monitor" ? "Stop this Monitor? Claude gets its end notice." : "Stop this shell? Claude sees it exit.")) + "</span>" +
'<button type="button" class="cbtn" data-act="cancel-stop" data-tid="' + esc(tid) + '">' + esc(t("Cancel")) + "</button>" +
'<button type="button" class="cbtn danger" data-act="do-stop" data-tid="' + esc(tid) + '">' + esc(t("Stop")) + "</button></div>";
}
if (open) {
h += '<div class="body">' + (hasTail(task) ? renderTail(task, live) : renderTimeline(task)) + "</div>";
}
return h + "</div>";
}
var tasksById = {};
function render() {
var d = state.data;
var tasks = d && d.found && Array.isArray(d.tasks) ? d.tasks : [];
tasksById = {};
if (!tasks.length) {
root.innerHTML = "";
return fit();
}
var now = Date.now();
var canStop = !!(d && d.canStop);
var live = [], done = [], nRunning = 0;
for (var i = 0; i < tasks.length; i++) {
var tk = tasks[i];
tasksById[tk.taskId] = tk;
var lv = isLive(tk, now);
if (lv) nRunning++;
if (!lv && state.stopping[tk.taskId]) delete state.stopping[tk.taskId];
var onTop = lv || (running && tk.kind === "shell" && !!tk.taskUnreadAt);
if (onTop) live.unshift(tk); else done.unshift(tk);
}
var showDone = state.showDone == null ? live.length === 0 : state.showDone;
var h = '<div class="card" role="group" aria-label="' + esc(t("Background shells")) + '">';
h += '<div class="head">' +
(nRunning > 0 ? svg(ICO.spin, "ico-amb") : svg(ICO.term, "ico-pri")) +
"<span>" + esc(t("Background shells")) + '</span><span class="cnt">(' + tasks.length + ")</span>" +
(nRunning > 0 ? '<span class="run">' + esc(t("{n} running", { n: nRunning })) + "</span>" : "") + "</div>";
if (live.length) {
h += '<div class="list">' + live.map(function (tk) { return renderRow(tk, canStop, now); }).join("") + "</div>";
}
if (done.length && (live.length || !showDone)) {
h += '<button type="button" class="fold-btn' + (showDone ? " open" : "") + '" data-act="toggle-done" aria-expanded="' + (showDone ? "true" : "false") + '">' +
svg(ICO.chev) + esc(t("Finished ({n})", { n: done.length })) + "</button>";
}
if (done.length && showDone) {
var shown = done.slice(0, state.limit);
h += '<div class="list">' + shown.map(function (tk) { return renderRow(tk, canStop, now); }).join("");
if (done.length > state.limit) {
h += '<button type="button" class="more-btn" data-act="more">' + esc(t("Show {n} more", { n: Math.min(8, done.length - state.limit) })) + "</button>";
}
h += "</div>";
}
root.innerHTML = h + "</div>";
fit();
}
root.addEventListener("click", function (e) {
var btn = e.target.closest("[data-act]");
if (!btn) return;
var act = btn.getAttribute("data-act");
var tid = btn.getAttribute("data-tid") || "";
var tk = tasksById[tid];
if (act === "toggle" || act === "open") {
state.open[tid] = act === "open" ? true : !state.open[tid];
if (state.open[tid] && tk && hasTail(tk) && drawerOpen && !state.outputs[tid]) fetchOutput(tid);
render();
} else if (act === "toggle-done") {
var d = state.data;
var tasks = d && d.tasks || [];
var now = Date.now();
var hasLive = tasks.some(function (x) { return isLive(x, now) || (running && x.kind === "shell" && !!x.taskUnreadAt); });
var cur = state.showDone == null ? !hasLive : state.showDone;
state.showDone = !cur;
render();
} else if (act === "more") {
state.limit += 8;
render();
} else if (act === "jump") {
var tu = btn.getAttribute("data-tu");
if (tu && P.scrollTo) P.scrollTo({ toolUseId: tu });
} else if (act === "copy" && tk && tk.command) {
if (P.copy) P.copy(tk.command).then(function () {
state.copied[tid] = true; render();
setTimeout(function () { delete state.copied[tid]; render(); }, 1500);
}, function () {});
} else if (act === "ask-stop") {
state.confirm[tid] = true; render();
} else if (act === "cancel-stop") {
delete state.confirm[tid]; render();
} else if (act === "do-stop" && tk) {
delete state.confirm[tid];
state.stopping[tid] = true;
render();
if (P.action) {
P.action("stop", { conversationId: cid, sessionId: sid, taskId: tid }).then(
function (res) {
if (P.toast) P.toast(t(res && res.forced ? "Stopped (it needed a SIGKILL)" : "Stopped"), "success");
if (q) q.refresh();
if (tk.kind === "shell") fetchOutput(tid);
},
function (err) {
delete state.stopping[tid];
if (P.toast) P.toast(t("Couldn't stop it: {err}", { err: String((err && err.message) || err) }), "error");
render();
}
);
}
}
});
function pollOutputs() {
if (!drawerOpen || document.hidden || !state.data || !state.data.tasks) return;
var now = Date.now();
state.data.tasks.forEach(function (tk) {
if (!hasTail(tk)) return;
if (isLive(tk, now)) fetchOutput(tk.taskId);
else if (state.open[tk.taskId] && !state.outputs[tk.taskId]) fetchOutput(tk.taskId);
});
}
var outTimer = null;
function schedulePoll() {
clearInterval(outTimer);
outTimer = null;
if (!drawerOpen || !state.data || !state.data.tasks) return;
var now = Date.now();
var anyLiveShell = state.data.tasks.some(function (tk) { return tk.kind === "shell" && isLive(tk, now); });
pollOutputs();
if (anyLiveShell) outTimer = setInterval(pollOutputs, 2000);
}
// Tick durations every 1 s while any task is live or unread-while-live.
setInterval(function () {
if (document.hidden || !state.data || !state.data.tasks || !state.data.tasks.length) return;
var now = Date.now();
var anyTick = state.data.tasks.some(function (tk) { return isLive(tk, now) || (running && tk.kind === "shell" && !!tk.taskUnreadAt); });
if (anyTick) render();
}, 1000);
// The payload is the manifest's slot "query" ({conversationId: "$conversationId",
// sessionId: "$sessionId"}) to the key, so the host's batched preload answers it.
function read(payload, cb) {
if (P.query) return P.query("tasks", payload, cb);
var stopped = false;
function go() {
if (stopped || !P.action) return Promise.resolve();
return P.action("tasks", payload).then(
function (d) { if (!stopped) cb(d, { fromCache: false, fetching: false, at: Date.now() }); },
function (e) { if (!stopped) cb(null, { error: String((e && e.message) || e) }); }
);
}
go();
return { stop: function () { stopped = true; }, refresh: go };
}
var q = null;
function start() {
if (q && q.stop) q.stop();
q = null;
if (!cid && !sid) { fit(); return; }
q = read({ conversationId: cid, sessionId: sid }, function (d, meta) {
if (meta && meta.error && !d) return;
if (d && typeof d === "object") {
state.data = d;
if (typeof d.running === "boolean" && !runningKnown) running = d.running;
render();
schedulePoll();
}
});
}
var runningKnown = typeof first.running === "boolean";
var timer = null, due = 0, lastRead = Date.now();
function soon(ms) {
var at = Date.now() + ms;
if (timer && due <= at) return;
clearTimeout(timer);
due = at;
timer = setTimeout(function () { timer = null; lastRead = Date.now(); if (q) q.refresh(); }, ms);
}
// Another conversation in the same frame: drop everything of the last one.
function switchTo(ncid, nsid, u) {
if (q && q.stop) q.stop();
q = null;
clearTimeout(timer); timer = null; due = 0;
clearInterval(outTimer); outTimer = null;
cid = ncid; sid = nsid;
runningKnown = typeof u.running === "boolean";
running = runningKnown ? u.running : false;
state.data = null; state.open = {}; state.confirm = {}; state.copied = {};
state.stopping = {}; state.outputs = {}; state.showDone = null; state.limit = 8;
lastRead = Date.now();
render();
start();
}
if (P.onEvent) P.onEvent(function (ev) {
if (!ev || !ev.type || !q) return;
if (ev.type === "meta" && (!ev.id || ev.id === sid)) soon(300);
else if (ev.type === "transcript" && cid && (ev.ids || []).indexOf(cid) >= 0) {
soon(Math.max(400, 2000 - (Date.now() - lastRead)));
}
});
if (P.onUpdate) P.onUpdate(function (u) {
if (!u || typeof u !== "object") return;
if (u.lang) { var was = LANG; setLang(u.lang); if (LANG !== was) render(); }
var drawerChanged = typeof u.drawerOpen === "boolean" && u.drawerOpen !== drawerOpen;
if (drawerChanged) drawerOpen = u.drawerOpen;
if ((u.conversationId !== undefined || u.sessionId !== undefined)) {
var ncid = u.conversationId !== undefined ? String(u.conversationId || "") : cid;
var nsid = u.sessionId !== undefined ? String(u.sessionId || "") : sid;
if (ncid !== cid || nsid !== sid) { switchTo(ncid, nsid, u); return; }
}
var changed = false;
if (typeof u.running === "boolean" && u.running !== running) {
running = u.running;
runningKnown = true;
changed = true;
soon(300);
}
if (drawerChanged) schedulePoll();
if (changed) { render(); schedulePoll(); }
});
start();
if (P.onTheme) P.onTheme(function () { render(); });
})();
</script>
</body>
</html>