claude-code-kanban 7.36.0 → 7.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/kanbot.js CHANGED
@@ -20,43 +20,71 @@ function kanbotModel(cfg) {
20
20
  return MODELS.has(model) ? model : null;
21
21
  }
22
22
 
23
- function costSection(costCli) {
24
- if (!costCli) return '';
25
- return [
26
- '\n# Costs\n',
27
- `\`${costCli} help\` lists the commands for Claude Code costs: by day, model, project, session and subagent.`,
28
- 'To show a session, or one of its subagents, to the user: `claude-code-kanban session cost <id> [--agent <agent id>]`.\n',
29
- ].join('\n');
30
- }
31
-
32
- function writeHelpPrompt(cwd, boardUrl, costCli) {
23
+ const COST_DIR = '.cost';
24
+
25
+ // The apps' skills start by command only, so Kanbot cannot pick one: its prompt names the file.
26
+ const skillLine = (skill, topic) => (skill ? [`Before you answer a question about ${topic}, read \`${skill}\`: it says how to answer.`] : []);
27
+
28
+ // `dir` holds the app's server.json in the config dir; `skill` is its skill file, from the root of
29
+ // the app's package. The app's script and its bin sit at that root.
30
+ const APPS = [
31
+ {
32
+ dir: COST_DIR,
33
+ bin: 'claude-code-cost',
34
+ skill: 'plugin/plugins/cost-dashboard/skills/cost/SKILL.md',
35
+ section: (cli, skill) =>
36
+ [
37
+ '\n# Costs\n',
38
+ `\`${cli} help\` lists the commands for Claude Code costs: by day, model, project, session and subagent.`,
39
+ ...skillLine(skill, 'costs, spend or plan usage limits'),
40
+ 'To show a session, or one of its subagents, to the user: `claude-code-kanban session cost <id> [--agent <agent id>]`.',
41
+ '',
42
+ ].join('\n'),
43
+ },
44
+ {
45
+ dir: '.memory',
46
+ bin: 'claude-code-memory-explorer',
47
+ skill: 'plugin/plugins/memory-diagnoser/skills/memory-analysis/SKILL.md',
48
+ section: (cli, skill) =>
49
+ [
50
+ '\n# Memory analysis\n',
51
+ `\`${cli} help\` lists the commands for the Memory Diagnoser's saved analysis results: the projects that have them, and the findings of one project.`,
52
+ ...skillLine(skill, 'the memory analysis, memory health or findings in memory files'),
53
+ '',
54
+ ].join('\n'),
55
+ },
56
+ ];
57
+
58
+ function writeHelpPrompt(cwd, boardUrl, apps) {
33
59
  const file = path.join(cwd, 'cli-help.md');
34
60
  const board = boardUrl ? `This board runs at ${boardUrl}; \`$CCK_URL\` holds the same URL, so the CLI talks to it.\n\n` : '';
35
- fs.writeFileSync(file, `# claude-code-kanban CLI\n\n${board}\`claude-code-kanban help\` prints:\n\n\`\`\`\n${topHelp()}\n\`\`\`\n${costSection(costCli)}`);
61
+ const sections = apps.map((a) => a.section).join('');
62
+ fs.writeFileSync(file, `# claude-code-kanban CLI\n\n${board}\`claude-code-kanban help\` prints:\n\n\`\`\`\n${topHelp()}\n\`\`\`\n${sections}`);
36
63
  return file;
37
64
  }
38
65
 
39
- function kanbotArgs(cwd, claudeDir, boardUrl, costCli) {
40
- return ['--plugin-dir', PLUGIN_DIR, '--agent', AGENT, '--append-system-prompt-file', writeHelpPrompt(cwd, boardUrl, costCli), '--add-dir', claudeDir];
66
+ function kanbotArgs(cwd, claudeDir, boardUrl, apps) {
67
+ const readable = [claudeDir, ...apps.map((a) => a.skillDir).filter(Boolean)].flatMap((dir) => ['--add-dir', dir]);
68
+ return ['--plugin-dir', PLUGIN_DIR, '--agent', AGENT, '--append-system-prompt-file', writeHelpPrompt(cwd, boardUrl, apps), ...readable];
41
69
  }
42
70
 
43
- // A claude-code-cost before its CLI starts a dashboard on any command, so a bin on PATH counts only
71
+ // An app package from before its CLI starts a dashboard on any command, so a bin on PATH counts only
44
72
  // when its package has lib/cli.js. npm puts the package next to a Windows shim, and a POSIX bin is
45
73
  // a symlink to server.js.
46
- function costPackageHasCli(bin) {
47
- const dirs = [path.join(path.dirname(bin), 'node_modules', 'claude-code-cost')];
74
+ function packageWithCli(bin, pkg) {
75
+ const dirs = [path.join(path.dirname(bin), 'node_modules', pkg)];
48
76
  try {
49
77
  dirs.push(path.dirname(fs.realpathSync(bin)));
50
78
  } catch {}
51
- return dirs.some((d) => fs.existsSync(path.join(d, 'lib', 'cli.js')));
79
+ return dirs.find((d) => fs.existsSync(path.join(d, 'lib', 'cli.js'))) || null;
52
80
  }
53
81
 
54
- // The hub gives cck no cost URL. The cost server of this config dir records itself in server.json
82
+ // The hub gives cck no app URL. An app server of this config dir records itself in server.json
55
83
  // ({pid, port, script}); a killed one leaves the file behind.
56
- function readCostServer(claudeDir) {
84
+ function readAppServer(claudeDir, dir) {
57
85
  let rec;
58
86
  try {
59
- rec = JSON.parse(fs.readFileSync(path.join(claudeDir, '.cost', 'server.json'), 'utf8'));
87
+ rec = JSON.parse(fs.readFileSync(path.join(claudeDir, dir, 'server.json'), 'utf8'));
60
88
  } catch {
61
89
  return null;
62
90
  }
@@ -64,14 +92,29 @@ function readCostServer(claudeDir) {
64
92
  return { url: `http://localhost:${rec.port}`, script: typeof rec.script === 'string' ? rec.script : null };
65
93
  }
66
94
 
67
- // Under the hub the CLI is not on PATH, so the running cost server names its own script.
68
- function findCostCli({ claudeDir, which }) {
69
- const script = readCostServer(claudeDir)?.script;
70
- if (script) return `node "${script.replace(/\\/g, '/')}"`;
71
- const bin = which('claude-code-cost');
72
- return bin && costPackageHasCli(bin) ? 'claude-code-cost' : null;
95
+ // Under the hub the CLI is not on PATH, so the running app server names its own script.
96
+ function findApp(app, { claudeDir, which }) {
97
+ const script = readAppServer(claudeDir, app.dir)?.script;
98
+ let root;
99
+ let command = app.bin;
100
+ if (script) {
101
+ root = path.dirname(script);
102
+ command = `node "${script.replace(/\\/g, '/')}"`;
103
+ } else {
104
+ const bin = which(app.bin);
105
+ root = bin && packageWithCli(bin, app.bin);
106
+ }
107
+ if (!root) return null;
108
+ // Kanbot reads the skill from the app's package, so the user installs nothing and the skill
109
+ // matches the app that runs.
110
+ const file = path.join(root, app.skill);
111
+ const skill = fs.existsSync(file) ? file.replace(/\\/g, '/') : null;
112
+ return { section: app.section(command, skill), skillDir: skill && path.dirname(file) };
73
113
  }
74
114
 
115
+ const findKanbotApps = (opts) => APPS.map((app) => findApp(app, opts)).filter(Boolean);
116
+ const readCostServer = (claudeDir) => readAppServer(claudeDir, COST_DIR);
117
+
75
118
  function createKanbot({ cckDir, projectsDir }) {
76
119
  const cwd = path.join(cckDir, 'kanbot');
77
120
  const projectDir = path.join(projectsDir, encodeProjectDirName(cwd));
@@ -112,10 +155,10 @@ function createKanbot({ cckDir, projectsDir }) {
112
155
  sessionId = id;
113
156
  ownIds.add(id);
114
157
  },
115
- startSpec({ model = null, boardUrl = null, costCli = null } = {}) {
158
+ startSpec({ model = null, boardUrl = null, apps = [] } = {}) {
116
159
  fs.mkdirSync(cwd, { recursive: true });
117
160
  sessionId = newestTranscript();
118
- const extraArgs = kanbotArgs(cwd, path.dirname(cckDir), boardUrl, costCli);
161
+ const extraArgs = kanbotArgs(cwd, path.dirname(cckDir), boardUrl, apps);
119
162
  // Not restored on a cck restart: a restore would bring it back without the agent args.
120
163
  return { cwd, name: 'kanbot', model, extraArgs, restore: false, ...(sessionId && { resume: sessionId }) };
121
164
  },
@@ -125,4 +168,4 @@ function createKanbot({ cckDir, projectsDir }) {
125
168
  };
126
169
  }
127
170
 
128
- module.exports = { kanbotOn, kanbotModel, createKanbot, findCostCli, readCostServer, KANBOT_AGENT: AGENT, KANBOT_PLUGIN_DIR: PLUGIN_DIR };
171
+ module.exports = { kanbotOn, kanbotModel, createKanbot, findKanbotApps, readCostServer, KANBOT_AGENT: AGENT, KANBOT_PLUGIN_DIR: PLUGIN_DIR };
package/lib/parsers.js CHANGED
@@ -1449,6 +1449,8 @@ async function buildSessionDigest(jsonlPath) {
1449
1449
  const rejectedToolUseIds = new Set();
1450
1450
  const promptByToolUseId = {};
1451
1451
  const killedAgentIds = new Set();
1452
+ const background = new Map();
1453
+ const backgroundInputs = new Map();
1452
1454
  try {
1453
1455
  const re = /"type":"agent_progress"[^}]*"agentId":"([^"]+)"/;
1454
1456
  const parentRe = /"parentToolUseID":"([^"]+)"/;
@@ -1457,11 +1459,11 @@ async function buildSessionDigest(jsonlPath) {
1457
1459
  const bgAgentIdRe = /agentId: ([a-zA-Z0-9_@-]+)/;
1458
1460
  const tmToolIdRe = /"tool_use_id":"([^"]+)"/;
1459
1461
  const tmAgentIdRe = /agent_id: ([a-zA-Z0-9_@-]+)/;
1460
- const taskIdRe = /<task-id>([a-zA-Z0-9_-]+)<\/task-id>/;
1461
1462
  const nameByToolUseId = {};
1462
1463
  const descByToolUseId = {};
1463
1464
  const usageByToolUseId = {};
1464
1465
  for await (const line of readLines(jsonlPath)) {
1466
+ noteBackgroundTask(line, background, backgroundInputs);
1465
1467
  // Terminated-teammate detection: check first since cheap substring guards
1466
1468
  if (line.includes('teammate-message') &&
1467
1469
  (line.includes('teammate_terminated') || line.includes('shutdown_response'))) {
@@ -1538,7 +1540,7 @@ async function buildSessionDigest(jsonlPath) {
1538
1540
  // This covers every delivery shape (user message, queue-operation,
1539
1541
  // queued_command attachment) without enumerating them.
1540
1542
  if (line.includes('<status>killed</status>') || line.includes('<status>error</status>')) {
1541
- const idMatch = taskIdRe.exec(line);
1543
+ const idMatch = TASK_ID_RE.exec(line);
1542
1544
  if (idMatch) killedAgentIds.add(idMatch[1]);
1543
1545
  }
1544
1546
  if (line.includes('<subagent_tokens>')) {
@@ -1589,7 +1591,91 @@ async function buildSessionDigest(jsonlPath) {
1589
1591
  const prompt = entry?.prompt || promptByToolUseId[toolUseId];
1590
1592
  if (prompt) rejectedPrompts.add(prompt);
1591
1593
  }
1592
- return { progressMap: map, terminated, rejectedAgentIds, rejectedPrompts, killedAgentIds };
1594
+ return { progressMap: map, terminated, rejectedAgentIds, rejectedPrompts, killedAgentIds, backgroundTasks: fillBackgroundOutputFiles([...background.values()]) };
1595
+ }
1596
+
1597
+ const TASK_ID_RE = /<task-id>([a-zA-Z0-9_-]+)<\/task-id>/;
1598
+ const LINE_TIMESTAMP_RE = /"timestamp":"([^"\\]+)"/;
1599
+ const BG_OUTPUT_TEXT_RE = /Output is being written to: (.+?\.output)/;
1600
+
1601
+ // A Monitor's start names no output file, but every task of a session writes to one folder.
1602
+ function fillBackgroundOutputFiles(tasks) {
1603
+ const known = tasks.find((t) => t.outputFile);
1604
+ if (!known) return tasks;
1605
+ const dir = path.dirname(known.outputFile);
1606
+ for (const t of tasks) t.outputFile ||= path.join(dir, `${t.taskId}.output`);
1607
+ return tasks;
1608
+ }
1609
+
1610
+ // Background shells (Bash with run_in_background) and Monitors of the main session. A session
1611
+ // that exits writes no notification, so the caller decides whether a task with no end still
1612
+ // runs. `inputs` holds the tool calls whose result has not come yet.
1613
+ function noteBackgroundTask(line, tasks, inputs) {
1614
+ if ((line.includes('"run_in_background":true') || line.includes('"name":"Monitor"')) && line.includes('"tool_use"')) {
1615
+ try {
1616
+ const blocks = JSON.parse(line).message?.content;
1617
+ for (const b of Array.isArray(blocks) ? blocks : []) {
1618
+ if (b.type !== 'tool_use' || !b.id) continue;
1619
+ const kind = b.name === 'Monitor' ? 'monitor' : b.name === 'Bash' && b.input?.run_in_background ? 'shell' : null;
1620
+ if (!kind) continue;
1621
+ inputs.set(b.id, {
1622
+ kind,
1623
+ description: b.input?.description || null,
1624
+ command: b.input?.command || b.input?.ws?.url || null,
1625
+ });
1626
+ }
1627
+ } catch (_) {}
1628
+ return;
1629
+ }
1630
+ const starts = line.includes('"backgroundTaskId"') || (inputs.size > 0 && line.includes('"taskId"'));
1631
+ const stops = tasks.size > 0 && line.includes('"task_id"');
1632
+ if ((starts || stops) && line.includes('"toolUseResult"')) {
1633
+ try {
1634
+ const obj = JSON.parse(line);
1635
+ const tur = obj.toolUseResult;
1636
+ // TaskStop ends a task with a tool result and no notification.
1637
+ const stopped = typeof tur?.task_id === 'string' ? tasks.get(tur.task_id) : null;
1638
+ if (stopped) {
1639
+ if (!stopped.endedAt) {
1640
+ stopped.status = 'stopped';
1641
+ stopped.endedAt = obj.timestamp || stopped.startedAt;
1642
+ }
1643
+ return;
1644
+ }
1645
+ const blocks = obj.message?.content;
1646
+ const result = Array.isArray(blocks) ? blocks.find((b) => b.type === 'tool_result') : null;
1647
+ const input = inputs.get(result?.tool_use_id);
1648
+ const taskId = typeof tur?.backgroundTaskId === 'string'
1649
+ ? tur.backgroundTaskId
1650
+ : input?.kind === 'monitor' && typeof tur?.taskId === 'string' ? tur.taskId : null;
1651
+ if (!taskId || tasks.has(taskId)) return;
1652
+ inputs.delete(result?.tool_use_id);
1653
+ tasks.set(taskId, {
1654
+ taskId,
1655
+ kind: input?.kind || 'shell',
1656
+ description: input?.description || null,
1657
+ command: input?.command || null,
1658
+ startedAt: obj.timestamp || null,
1659
+ endedAt: null,
1660
+ outputFile: (typeof result?.content === 'string' && BG_OUTPUT_TEXT_RE.exec(result.content)?.[1]) || null,
1661
+ });
1662
+ } catch (_) {}
1663
+ return;
1664
+ }
1665
+ // A Monitor's events are notifications without a <status>.
1666
+ if (tasks.size > 0 && line.includes('<task-notification>') && line.includes('<status>')) {
1667
+ const task = tasks.get(TASK_ID_RE.exec(line)?.[1]);
1668
+ if (!task || task.endedAt) return;
1669
+ const notif = parseTaskNotification(line);
1670
+ if (!task.outputFile) {
1671
+ try {
1672
+ const file = JSON.parse(`"${notif.outputFile || ''}"`);
1673
+ if (path.isAbsolute(file)) task.outputFile = file;
1674
+ } catch (_) {}
1675
+ }
1676
+ task.status = notif.status || 'completed';
1677
+ task.endedAt = LINE_TIMESTAMP_RE.exec(line)?.[1] || task.startedAt;
1678
+ }
1593
1679
  }
1594
1680
 
1595
1681
  async function buildAgentProgressMap(jsonlPath) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-kanban",
3
- "version": "7.36.0",
3
+ "version": "7.37.0",
4
4
  "description": "A web-based Kanban board for viewing Claude Code tasks with agent teams support",
5
5
  "main": "server.js",
6
6
  "type": "commonjs",
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "claude-code-kanban",
3
- "version": "3.11.1",
3
+ "version": "3.11.2",
4
4
  "description": "claude-code-kanban dashboard integration: agent activity tracking, context and cost tracking, board moves and reviews delivered to the session, and skills to drive the board from a session"
5
5
  }
@@ -28,7 +28,16 @@ The URL is the page's only input from the board. The page reads the values the b
28
28
 
29
29
  ## 3. Take the board's theme
30
30
 
31
- Style the page with the variables of the HTML contract in [the show skill](../../show/SKILL.md#html-contract), in its flat style. Set fallback values for them in `:where(:root)`, and set `:root { color-scheme: var(--color-scheme, light dark); }` so scrollbars and form controls follow the board, not the OS. Apply the board's values from its message, which it sends on each load and each theme change:
31
+ Style the page with the variables of the HTML contract in [the show skill](../../show/SKILL.md#html-contract), in its flat style. Set fallback values for them in `:where(:root)`, and set `:root { color-scheme: var(--color-scheme, light dark); }` so scrollbars and form controls follow the board, not the OS. Scrollbars still take the OS shape, so copy the board's thin scrollbar:
32
+
33
+ ```css
34
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
35
+ ::-webkit-scrollbar-track { background: transparent; }
36
+ ::-webkit-scrollbar-thumb { background: var(--color-border); border-radius: 3px; }
37
+ ::-webkit-scrollbar-thumb:hover { background: var(--color-text-muted); }
38
+ ```
39
+
40
+ Apply the board's values from its message, which it sends on each load and each theme change:
32
41
 
33
42
  ```js
34
43
  addEventListener('message', (e) => {
@@ -77,7 +86,7 @@ Run the static check, `scripts/theme-check.mjs` in this skill's base directory,
77
86
  node <skill base dir>/scripts/theme-check.mjs <folder>/index.html
78
87
  ```
79
88
 
80
- It fails on a literal color (hex, `rgb()`, `hsl()`, `oklch()`, a named color) in CSS, a `style` attribute, an SVG `fill` or `stroke`, or a JS string, and on a page with no `cck-show:tokens` listener. It warns on a variable that is not a board token, a token with no fallback, a literal font, and a missing `color-scheme`. A literal color is allowed only as a token's fallback in `:where(:root)`. For a shade, mix a token: `color-mix(in srgb, var(--color-accent) 14%, transparent)`.
89
+ It fails on a literal color (hex, `rgb()`, `hsl()`, `oklch()`, a named color) in CSS, a `style` attribute, an SVG `fill` or `stroke`, or a JS string, and on a page with no `cck-show:tokens` listener. It warns on a variable that is not a board token, a token with no fallback, a literal font, a missing `color-scheme`, and a missing `::-webkit-scrollbar` rule. A literal color is allowed only as a token's fallback in `:where(:root)`. For a shade, mix a token: `color-mix(in srgb, var(--color-accent) 14%, transparent)`.
81
90
 
82
91
  A pass does not prove the page follows the theme. The check reads one file, so it does not see colors built at runtime (`'#' + hex`, colors from the server), linked stylesheets, library CSS, canvas or images. Keep those on tokens too, and when the page has any of them, open it on the rail and switch the board between light and dark.
83
92
 
@@ -79,6 +79,8 @@ for (const m of src.matchAll(/<script[^>]*>([\s\S]*?)<\/script>/gi)) {
79
79
 
80
80
  if (!/color-scheme\s*:\s*var\(\s*--color-scheme/.test(src))
81
81
  report('warn', null, 'no-color-scheme', 'color-scheme does not follow var(--color-scheme): scrollbars and native controls follow the OS');
82
+ if (!/::-webkit-scrollbar\s*\{/.test(src))
83
+ report('warn', null, 'no-thin-scrollbar', "no ::-webkit-scrollbar rule: the page shows the OS scrollbar, not the board's thin one");
82
84
  if (!hasListener) report('error', null, 'no-token-listener', "no 'cck-show:tokens' message listener");
83
85
  for (const v of usedVars) {
84
86
  if (!CONTRACT.has(v) && !definedVars.has(v)) report('warn', null, 'unknown-var', `${v} is not a board token and is not defined`);
package/public/app.js CHANGED
@@ -121,6 +121,7 @@ let searchQuery = ''; // Search query for fuzzy search
121
121
  let allTasksCache = []; // Cache all tasks for search
122
122
  let ownerFilter = '';
123
123
  let currentAgents = [];
124
+ let currentBackground = [];
124
125
  let currentWaiting = null;
125
126
  let lastWaitingHash = '';
126
127
  let lastAgentsHash = '';
@@ -886,11 +887,13 @@ let agentLogLimit = AGENT_LOG_PAGE;
886
887
  const ZEN_AGENTS_MAX = 5;
887
888
  const LIVE_INDICATOR_MS = 10 * 1000;
888
889
  const JUST_NOW_MS = 60 * 1000;
890
+ const BACKGROUND_KEEP_MS = 5 * 60 * 1000;
889
891
  //#endregion
890
892
 
891
893
  //#region AGENT_FETCHING
892
894
  function resetAgentState() {
893
895
  currentAgents = [];
896
+ currentBackground = [];
894
897
  currentWaiting = null;
895
898
  lastAgentsHash = '';
896
899
  lastWaitingHash = '';
@@ -911,6 +914,7 @@ async function fetchAgents(sessionId) {
911
914
  if (hash === lastAgentsHash) return;
912
915
  lastAgentsHash = hash;
913
916
  currentAgents = agents;
917
+ currentBackground = data.background || [];
914
918
  updateTeamColors(agents, data.teamColors);
915
919
  for (const k of Object.keys(ownerColorCache)) delete ownerColorCache[k];
916
920
  renderAgentFooter();
@@ -970,6 +974,7 @@ async function fetchProjectView(projectPath) {
970
974
  if (r.waitingForUser && !mergedWaiting) mergedWaiting = r.waitingForUser;
971
975
  }
972
976
  currentWaiting = mergedWaiting;
977
+ currentBackground = agentResults.flatMap((r) => r.background || []);
973
978
  Object.assign(teamColorMap, mergedColors);
974
979
 
975
980
  renderProjectView();
@@ -1003,7 +1008,8 @@ async function refreshProjectAgents() {
1003
1008
  if (r.waitingForUser && !mergedWaiting) mergedWaiting = r.waitingForUser;
1004
1009
  }
1005
1010
  currentWaiting = mergedWaiting;
1006
- const hash = JSON.stringify({ agents: currentAgents, waiting: currentWaiting });
1011
+ currentBackground = agentResults.flatMap((r) => r.background || []);
1012
+ const hash = JSON.stringify({ agents: currentAgents, waiting: currentWaiting, background: currentBackground });
1007
1013
  if (hash === lastAgentsHash) return;
1008
1014
  lastAgentsHash = hash;
1009
1015
  renderAgentFooter();
@@ -2883,7 +2889,8 @@ function adjustShowZoom(delta) {
2883
2889
 
2884
2890
  // The markup decides what scales: `.modal-zoomable` marks a modal's reading
2885
2891
  // surface, and style.css hangs the zoom on that same class. Confirm dialogs
2886
- // carry no such body — nothing there is worth enlarging.
2892
+ // carry no such body — nothing there is worth enlarging. Page Up and Page Down
2893
+ // scroll from that class too (pageTopModal).
2887
2894
  function isZoomableModalOpen() {
2888
2895
  return document.querySelector('.modal-overlay.visible .modal-zoomable') !== null;
2889
2896
  }
@@ -3542,14 +3549,19 @@ function renderZenAgents(agents) {
3542
3549
  const el = zenMode && sessionsList.querySelector('.zen-agents');
3543
3550
  if (!el) return;
3544
3551
  const active = agents.filter((a) => a.status === 'active');
3545
- const html = zenAgentsHtml(active);
3552
+ const running = currentBackground.filter((t) => !t.endedAt);
3553
+ const html = zenAgentsHtml(active) + zenBackgroundHtml(running);
3546
3554
  if (html !== el.dataset.shape) {
3547
3555
  el.dataset.shape = html;
3548
3556
  el.innerHTML = html;
3549
3557
  }
3550
3558
  const now = Date.now();
3559
+ const elapsed = [
3560
+ ...active.slice(0, ZEN_AGENTS_MAX).map((a) => agentElapsed(a, now)),
3561
+ ...running.slice(0, ZEN_AGENTS_MAX).map((t) => now - Date.parse(t.startedAt)),
3562
+ ];
3551
3563
  el.querySelectorAll('.zen-agent-time').forEach((t, i) => {
3552
- t.textContent = formatDuration(agentElapsed(active[i], now));
3564
+ t.textContent = formatDuration(elapsed[i]);
3553
3565
  });
3554
3566
  }
3555
3567
 
@@ -3580,14 +3592,74 @@ function visibleAgents() {
3580
3592
  }
3581
3593
  }
3582
3594
  // Sort: active/idle first, then by updatedAt desc
3583
- const statusOrder = { active: 0, idle: 1, stopped: 2 };
3584
3595
  return filtered.sort(
3585
3596
  (a, b) =>
3586
- (statusOrder[a.status] ?? 2) - (statusOrder[b.status] ?? 2) ||
3597
+ (AGENT_STATUS_ORDER[a.status] ?? 2) - (AGENT_STATUS_ORDER[b.status] ?? 2) ||
3587
3598
  new Date(b.updatedAt || 0) - new Date(a.updatedAt || 0),
3588
3599
  );
3589
3600
  }
3590
3601
 
3602
+ const BACKGROUND_KINDS = {
3603
+ shell: { name: 'Background shell', icon: ICON_TERMINAL },
3604
+ monitor: {
3605
+ name: 'Monitor',
3606
+ icon: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>',
3607
+ },
3608
+ };
3609
+
3610
+ const AGENT_STATUS_ORDER = { active: 0, idle: 1, stopped: 2 };
3611
+
3612
+ function visibleBackground(now) {
3613
+ return currentBackground.filter((t) => !t.endedAt || now - Date.parse(t.endedAt) < BACKGROUND_KEEP_MS);
3614
+ }
3615
+
3616
+ const backgroundKind = (t) => BACKGROUND_KINDS[t.kind] || BACKGROUND_KINDS.shell;
3617
+ const backgroundLabel = (t) => t.description || t.command || backgroundKind(t).name;
3618
+ const backgroundKindHtml = (t) =>
3619
+ `<span class="background-kind">${backgroundKind(t).icon}${backgroundKind(t).name}</span>`;
3620
+ const backgroundClickAttr = (t) => (t.outputFile ? ` onclick="openPreviewByPath('${escAttrJs(t.outputFile)}')"` : '');
3621
+
3622
+ function zenBackgroundHtml(running) {
3623
+ if (!running.length) return '';
3624
+ const rows = running.slice(0, ZEN_AGENTS_MAX).map((t) => {
3625
+ const label = truncateAtWord(backgroundLabel(t), 200);
3626
+ return `<button type="button" class="zen-agent" title="${escapeHtml(t.command || label)}"${backgroundClickAttr(t)}>
3627
+ <span class="agent-dot active"></span>
3628
+ <span class="zen-agent-text"><span class="zen-agent-task">${escapeHtml(label)}</span><span class="agent-ident-row">${backgroundKindHtml(t)}</span></span>
3629
+ <span class="zen-agent-time"></span>
3630
+ </button>`;
3631
+ });
3632
+ return `<div class="panel-section-header"><span>Background</span><span class="panel-section-count">${running.length}</span></div>${rows.join('')}`;
3633
+ }
3634
+
3635
+ function backgroundCardHtml(t, now) {
3636
+ const running = !t.endedAt;
3637
+ const label = backgroundLabel(t);
3638
+ const elapsed = (running ? now : Date.parse(t.endedAt)) - Date.parse(t.startedAt);
3639
+ const status = running ? 'running' : t.status === 'completed' ? 'done' : t.status;
3640
+ return `<div class="agent-card background-card ${running ? 'active' : 'stopped'}${t.outputFile ? ' has-output' : ''}" title="${escapeHtml(t.command || label)}"${backgroundClickAttr(t)}>
3641
+ <div class="agent-task">${escapeHtml(label)}</div>
3642
+ <div class="agent-ident-row">${backgroundKindHtml(t)}</div>
3643
+ <div class="agent-status-row"><span class="agent-status"><span class="agent-dot ${running ? 'active' : 'stopped'}"></span>${escapeHtml(status)}</span><span class="agent-duration">${formatDuration(elapsed)}</span></div>
3644
+ </div>`;
3645
+ }
3646
+
3647
+ function agentCardHtml(a, now) {
3648
+ const status = agentStatus(a);
3649
+ const displayText = agentTaskText(a);
3650
+ const nameColor = a.agentName ? resolveNamedColor(a.color) || getOwnerColor(a.agentName) : null;
3651
+ const nameBadgeHtml = nameColor
3652
+ ? `<span class="task-owner-badge task-owner-badge--compact" style="background:${nameColor.bg};color:${nameColor.color}">${escapeHtml(a.agentName)}</span>`
3653
+ : '';
3654
+ const selectedClass = a.agentId === currentAgentModalId ? ' selected' : '';
3655
+ return `<div class="agent-card ${status}${selectedClass}" data-agent-id="${escapeHtml(a.agentId)}" onclick="showAgentModal('${escAttrJs(a.agentId)}')">
3656
+ ${agentLogButton(a.agentId, 'agent-card-log-btn')}
3657
+ <div class="agent-task" title="${escapeHtml(displayText)}">${escapeHtml(displayText)}</div>
3658
+ <div class="agent-ident-row">${agentIdentHtml(a)}${nameBadgeHtml}</div>
3659
+ <div class="agent-status-row"><span class="agent-status"><span class="agent-dot ${status}"></span>${status}</span><span class="agent-duration">${formatDuration(agentElapsed(a, now))}</span></div>
3660
+ </div>`;
3661
+ }
3662
+
3591
3663
  function renderAgentFooter() {
3592
3664
  schedulePublish();
3593
3665
  const footer = document.getElementById('agent-footer');
@@ -3595,6 +3667,7 @@ function renderAgentFooter() {
3595
3667
  const label = document.getElementById('agent-footer-label');
3596
3668
  const now = Date.now();
3597
3669
  const agents = visibleAgents();
3670
+ const background = visibleBackground(now);
3598
3671
  renderZenAgents(agents);
3599
3672
  renderAgentViews(agents);
3600
3673
  const expanded = footer.classList.contains('expanded');
@@ -3602,8 +3675,9 @@ function renderAgentFooter() {
3602
3675
  const hidden = agents.length - visible.length;
3603
3676
 
3604
3677
  const permFresh = isWaitingFresh();
3678
+ const backgroundRunning = background.filter((t) => !t.endedAt).length;
3605
3679
 
3606
- if (visible.length === 0 && !permFresh) {
3680
+ if (visible.length === 0 && !permFresh && !background.length) {
3607
3681
  footer.classList.remove('visible');
3608
3682
  clearInterval(agentDurationInterval);
3609
3683
  agentDurationInterval = null;
@@ -3614,41 +3688,36 @@ function renderAgentFooter() {
3614
3688
 
3615
3689
  footer.classList.add('visible');
3616
3690
  const running = agents.filter((a) => a.status === 'active').length;
3617
- label.innerHTML = `Agents log <span class="agent-footer-count">${agents.length}</span>${running ? `<span class="agent-footer-running">· ${running} running</span>` : ''}`;
3691
+ const labelPart = (n, word) => (n ? `<span class="agent-footer-running">· ${n} ${word}</span>` : '');
3692
+ label.innerHTML = `Agents log <span class="agent-footer-count">${agents.length}</span>${labelPart(running, 'running')}${labelPart(backgroundRunning, 'in background')}`;
3618
3693
 
3619
3694
  const permHtml = permFresh
3620
3695
  ? `<button type="button" class="permission-badge" onclick="showWaitingDetail()">${currentWaiting.kind === 'question' ? '❓ Question pending' : currentWaiting.kind === 'plan' ? '📋 Plan pending' : `⏳ Awaiting: ${escapeHtml(currentWaiting.toolName || 'unknown')}`}</button>`
3621
3696
  : '';
3622
3697
 
3698
+ const cards = [
3699
+ ...background.map((t) => ({
3700
+ rank: t.endedAt ? AGENT_STATUS_ORDER.stopped : AGENT_STATUS_ORDER.active,
3701
+ at: Date.parse(t.endedAt || t.startedAt),
3702
+ html: backgroundCardHtml(t, now),
3703
+ })),
3704
+ ...visible.map((a) => ({
3705
+ rank: AGENT_STATUS_ORDER[a.status] ?? AGENT_STATUS_ORDER.stopped,
3706
+ at: new Date(a.updatedAt || 0).getTime(),
3707
+ html: agentCardHtml(a, now),
3708
+ })),
3709
+ ].sort((a, b) => a.rank - b.rank || b.at - a.at);
3710
+
3623
3711
  content.innerHTML =
3624
3712
  permHtml +
3625
- visible
3626
- .map((a) => {
3627
- const elapsed = agentElapsed(a, now);
3628
- const status = agentStatus(a);
3629
- const displayText = agentTaskText(a);
3630
- const taskHtml = `<div class="agent-task" title="${escapeHtml(displayText)}">${escapeHtml(displayText)}</div>`;
3631
- const agentNameVal = a.agentName || null;
3632
- const nameColor = agentNameVal ? resolveNamedColor(a.color) || getOwnerColor(agentNameVal) : null;
3633
- const nameBadgeHtml = nameColor
3634
- ? `<span class="task-owner-badge task-owner-badge--compact" style="background:${nameColor.bg};color:${nameColor.color}">${escapeHtml(agentNameVal)}</span>`
3635
- : '';
3636
- const selectedClass = a.agentId === currentAgentModalId ? ' selected' : '';
3637
- return `<div class="agent-card ${status}${selectedClass}" data-agent-id="${escapeHtml(a.agentId)}" onclick="showAgentModal('${escAttrJs(a.agentId)}')">
3638
- ${agentLogButton(a.agentId, 'agent-card-log-btn')}
3639
- ${taskHtml}
3640
- <div class="agent-ident-row">${agentIdentHtml(a)}${nameBadgeHtml}</div>
3641
- <div class="agent-status-row"><span class="agent-status"><span class="agent-dot ${status}"></span>${status}</span><span class="agent-duration">${formatDuration(elapsed)}</span></div>
3642
- </div>`;
3643
- })
3644
- .join('') +
3713
+ cards.map((c) => c.html).join('') +
3645
3714
  (expanded && hidden > 0
3646
3715
  ? `<button type="button" class="agent-footer-more" onclick="showMoreAgents()">Show ${Math.min(hidden, AGENT_LOG_PAGE)} more${hidden > AGENT_LOG_PAGE ? ` <span>of ${hidden}</span>` : ''}</button>`
3647
3716
  : '');
3648
3717
  updateScrollFades(content);
3649
3718
 
3650
3719
  clearInterval(agentDurationInterval);
3651
- if (visible.some((a) => a.status === 'active' || a.status === 'idle')) {
3720
+ if (backgroundRunning || visible.some((a) => a.status === 'active' || a.status === 'idle')) {
3652
3721
  agentDurationInterval = setInterval(() => isOnScreen() && renderAgentFooter(), 1000);
3653
3722
  if (!agentPollInterval) {
3654
3723
  agentPollInterval = setInterval(() => {
@@ -5785,7 +5854,8 @@ function sgHostOf(group, placed) {
5785
5854
  }
5786
5855
  // `opts.under` places the session under another project block of the group; `opts.loose` lifts it
5787
5856
  // out of its project block onto the group's own level. `opts.parent` follows the server's place():
5788
- // left out, a move inside the group keeps it; null clears it.
5857
+ // left out, a move inside the group keeps it; null clears it. `opts.project` is the project of a
5858
+ // session that is not in `sessions` yet.
5789
5859
  function sgAssign(groupId, type, ref, opts = {}) {
5790
5860
  const group = sgGroupById(groupId);
5791
5861
  if (!group) return;
@@ -5796,7 +5866,7 @@ function sgAssign(groupId, type, ref, opts = {}) {
5796
5866
  if (type === 'project') {
5797
5867
  for (const s of sessions) if (sessionProjectKey(s) === ref) sgDetach('session', s.id);
5798
5868
  }
5799
- const own = type === 'session' ? sessionProjectKey(sessions.find((s) => s.id === ref)) : null;
5869
+ const own = type === 'session' ? (opts.project ?? sessionProjectKey(sessions.find((s) => s.id === ref))) : null;
5800
5870
  // Under its own project block is simply the natural placement - no override needed.
5801
5871
  const under = opts.under && opts.under !== own ? opts.under : null;
5802
5872
  const loose = !under && !!opts.loose;
@@ -5814,6 +5884,15 @@ function sgAssign(groupId, type, ref, opts = {}) {
5814
5884
  persistSessionGroups();
5815
5885
  }
5816
5886
 
5887
+ function sgDefaultFolder(group) {
5888
+ let recent = null;
5889
+ for (const s of sessions) {
5890
+ if (s.placeholder || sgGroupForSession(s) !== group) continue;
5891
+ if (!recent || (s.modifiedAt || '') > (recent.modifiedAt || '')) recent = s;
5892
+ }
5893
+ return sessionProjectKey(recent) || group.members.find((m) => m.type === 'project')?.ref || null;
5894
+ }
5895
+
5817
5896
  function sgCreateGroup(name) {
5818
5897
  const group = {
5819
5898
  id: `g_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
@@ -5904,8 +5983,9 @@ function sgHeaderHtml(group, countHtml) {
5904
5983
  const hint = group.transient ? 'goes when its sessions leave the Active view' : 'drop sessions or projects here';
5905
5984
  const attrs = `class="session-group-header${group.transient ? ' sg-transient' : ''}${collapsed ? ' collapsed' : ''}${group.id === zenGroup ? ' sg-zen' : ''}" draggable="${editing ? 'false' : 'true'}" data-group-id="${escapeHtml(group.id)}" title="${escapeHtml(group.name)} — ${hint}"`;
5906
5985
  const actions = `${group.transient ? '<span class="sg-action sg-keep" title="Keep this group after its sessions end">Keep</span>' : ''}
5986
+ ${terminalAvailable() ? `<span class="sg-action sg-new" title="New session in ${escapeHtml(group.name)}">${PLUS_SVG}</span>` : ''}
5907
5987
  <span class="sg-action sg-rename" title="Rename group"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></span>
5908
- <span class="sg-action sg-delete" title="Delete group (members return to Projects)">&times;</span>
5988
+ <span class="sg-action sg-delete" title="Delete group (members return to Projects)"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg></span>
5909
5989
  ${headerPadBtnHtml(_groupScratchpadKey(group.id), group.name)}`;
5910
5990
  return `
5911
5991
  <div ${attrs} data-group-path="${escapeHtml(sgKey(group.id))}">
@@ -8570,6 +8650,23 @@ const MODAL_CLOSERS = {
8570
8650
  'pane-pop': () => closePanePop(),
8571
8651
  };
8572
8652
 
8653
+ function topModalId() {
8654
+ const visible = [...document.querySelectorAll('.modal-overlay.visible')];
8655
+ return MODAL_ESC_PRIORITY.find((id) => visible.some((m) => m.id === id)) || visible[visible.length - 1].id;
8656
+ }
8657
+
8658
+ // Focus is on the dialog, a button or the page behind, not inside the text, so the browser finds no
8659
+ // scroll box for Page Up and Page Down.
8660
+ function pageTopModal(e) {
8661
+ const overlay = document.getElementById(topModalId());
8662
+ let box = overlay.querySelector('.modal-zoomable');
8663
+ const scrolls = (el) => el.scrollHeight > el.clientHeight && /auto|scroll/.test(getComputedStyle(el).overflowY);
8664
+ while (box && box !== overlay && !scrolls(box)) box = box.parentElement;
8665
+ if (!box || box === overlay || box.contains(e.target)) return false;
8666
+ box.scrollBy({ top: (e.key === 'PageDown' ? 1 : -1) * box.clientHeight * 0.9 });
8667
+ return true;
8668
+ }
8669
+
8573
8670
  document.addEventListener('keydown', (e) => {
8574
8671
  // Scale the open modal's reading surface, or the file pane's, instead of letting the browser zoom
8575
8672
  // the whole page. Sits above the text-field guard so it still works with the
@@ -8627,12 +8724,13 @@ document.addEventListener('keydown', (e) => {
8627
8724
  return;
8628
8725
  }
8629
8726
  // Close only the topmost so a child Esc doesn't also dismiss its parent.
8630
- const visible = [...document.querySelectorAll('.modal-overlay.visible')];
8631
- const topId = MODAL_ESC_PRIORITY.find((id) => visible.some((m) => m.id === id)) || visible[visible.length - 1].id;
8727
+ const topId = topModalId();
8632
8728
  const close = MODAL_CLOSERS[topId];
8633
8729
  if (close) close();
8634
8730
  else document.getElementById(topId).classList.remove('visible');
8635
8731
  e.stopImmediatePropagation();
8732
+ } else if (matchKey(e, 'PageDown', 'PageUp')) {
8733
+ if (pageTopModal(e)) e.preventDefault();
8636
8734
  } else if (e.key === '?' && document.getElementById('help-modal').classList.contains('visible')) {
8637
8735
  e.preventDefault();
8638
8736
  closeHelpModal();
@@ -10115,7 +10213,7 @@ function renderSourcePreview(filePath, content) {
10115
10213
  // Every kind but html, which needs a frame.
10116
10214
  function renderPreviewContent(bodyEl, filePath, content, kind) {
10117
10215
  if (kind === 'text') {
10118
- bodyEl.innerHTML = renderSourcePreview(filePath, content);
10216
+ bodyEl.innerHTML = renderSourcePreview(filePath, stripAnsi(content));
10119
10217
  } else if (kind === 'image') {
10120
10218
  const img = document.createElement('img');
10121
10219
  img.className = 'preview-image';
@@ -12787,6 +12885,10 @@ document.addEventListener('click', (e) => {
12787
12885
  sgConfirmDelete(group);
12788
12886
  return;
12789
12887
  }
12888
+ if (e.target.closest('.sg-new')) {
12889
+ openNewSession(sgDefaultFolder(group), false, group.id);
12890
+ return;
12891
+ }
12790
12892
  }
12791
12893
 
12792
12894
  const header = e.target.closest(COLLAPSIBLE_HEADER_SELECTOR);
@@ -15055,10 +15157,20 @@ function paneBlockedHtml(pane) {
15055
15157
  );
15056
15158
  }
15057
15159
 
15160
+ function isLoopbackUrl(url) {
15161
+ try {
15162
+ return PANE_LOOPBACK.has(new URL(url, location.href).hostname);
15163
+ } catch {
15164
+ return false;
15165
+ }
15166
+ }
15167
+
15058
15168
  function paneUrlFrame(pane, className) {
15059
15169
  const frame = document.createElement('iframe');
15060
15170
  frame.className = className;
15061
15171
  frame.setAttribute('sandbox', PANE_URL_SANDBOX);
15172
+ // A cross-origin frame cannot write the clipboard without this; only local apps get it.
15173
+ if (isLoopbackUrl(pane.target)) frame.allow = 'clipboard-write';
15062
15174
  frame.setAttribute('referrerpolicy', 'no-referrer');
15063
15175
  frame.title = pane.title;
15064
15176
  frame.src = pane.target;
@@ -19542,6 +19654,10 @@ function dropPlaceholder(id) {
19542
19654
 
19543
19655
  function forgetPlaceholder(id) {
19544
19656
  if (!newSpecs.delete(id)) return false;
19657
+ if (sgGroupOf('session', id)) {
19658
+ sgDetach('session', id);
19659
+ persistSessionGroups();
19660
+ }
19545
19661
  setTerminalMode(id, false);
19546
19662
  // Before the socket's close handler runs, or it would reconnect and start the session again.
19547
19663
  if (termState.sessionId === id) detachTerminal();
@@ -19660,10 +19776,26 @@ function showSessionTerminal(sessionId) {
19660
19776
  else fetchTasks(sessionId);
19661
19777
  }
19662
19778
 
19663
- function openNewSession(folder, resume = false) {
19779
+ function setNewSessionGroup(groupId) {
19780
+ const select = document.getElementById('ns-group');
19781
+ select.innerHTML = `<option value="">No group</option>${sessionGroups
19782
+ .map((g) => `<option value="${escapeHtml(g.id)}">${escapeHtml(sgPathOf(g))}</option>`)
19783
+ .join('')}`;
19784
+ select.value = groupId ?? '';
19785
+ document.getElementById('ns-group-row').hidden = !sessionGroups.length;
19786
+ }
19787
+
19788
+ // Before the placeholder's first merge, so that merge reveals the group and not the project.
19789
+ function joinNewSessionGroup(id) {
19790
+ const groupId = document.getElementById('ns-group').value;
19791
+ if (groupId) sgAssign(groupId, 'session', id, { project: newSpecs.get(id).cwd });
19792
+ }
19793
+
19794
+ function openNewSession(folder, resume = false, groupId = null) {
19664
19795
  if (!terminalAvailable() || document.getElementById('new-session-modal').classList.contains('visible')) return;
19665
19796
  if (terminalPaneFocused()) leaveTerminalPane();
19666
19797
  ns.resume = resume;
19798
+ setNewSessionGroup(resume ? null : groupId);
19667
19799
  ns.extraArgs = [];
19668
19800
  document.querySelector('.new-session-modal').classList.toggle('ns-resume', resume);
19669
19801
  document.getElementById('ns-title').textContent = resume ? 'Resume session' : 'New session';
@@ -19946,6 +20078,7 @@ async function startNewSession() {
19946
20078
  }
19947
20079
  newSpecs.set(id, { ...(ns.resume ? { cwd: v.cwd } : v), mode: ns.resume ? 'pick' : 'new', startedAt: Date.now() });
19948
20080
  setTerminalMode(id, true);
20081
+ joinNewSessionGroup(id);
19949
20082
  if (v.stay) return startNewSessionInBackground(id, v);
19950
20083
  closeNewSession();
19951
20084
  openPlaceholder(id);
@@ -19985,6 +20118,7 @@ async function startNewSessionInBackground(id, v) {
19985
20118
  forgetPlaceholder(id);
19986
20119
  newSpecs.set(r.session, spec);
19987
20120
  setTerminalMode(r.session, true);
20121
+ joinNewSessionGroup(r.session);
19988
20122
  refreshPlaceholders();
19989
20123
  }
19990
20124
  closeNewSession();
package/public/index.html CHANGED
@@ -903,6 +903,12 @@
903
903
  <div id="ns-images" class="ns-images" hidden></div>
904
904
  </div>
905
905
  </div>
906
+ <div id="ns-group-row" class="ns-row ns-extra" hidden>
907
+ <label class="ns-label" for="ns-group">Group</label>
908
+ <div class="ns-field">
909
+ <select id="ns-group" class="form-input"></select>
910
+ </div>
911
+ </div>
906
912
  <div class="ns-row ns-extra">
907
913
  <span class="ns-label">Worktree</span>
908
914
  <div class="ns-field">
@@ -913,7 +919,7 @@
913
919
  <div id="ns-wt-hint" class="ns-hint" hidden></div>
914
920
  </div>
915
921
  </div>
916
- <div class="ns-row ns-extra">
922
+ <div class="ns-row ns-extra ns-divided">
917
923
  <span class="ns-label"></span>
918
924
  <div class="ns-field">
919
925
  <div class="ns-inline">
package/public/style.css CHANGED
@@ -7769,6 +7769,20 @@ button.agent-map-node:hover {
7769
7769
  .agent-card.fading {
7770
7770
  opacity: 0.4;
7771
7771
  }
7772
+ .agent-card.background-card {
7773
+ border-style: dashed;
7774
+ }
7775
+ .agent-card.background-card:not(.has-output) {
7776
+ cursor: default;
7777
+ }
7778
+ .agent-card.background-card:not(.has-output):hover {
7779
+ border-color: var(--border);
7780
+ }
7781
+ .background-kind {
7782
+ display: inline-flex;
7783
+ align-items: center;
7784
+ gap: 4px;
7785
+ }
7772
7786
  .agent-task {
7773
7787
  max-width: 240px;
7774
7788
  padding-right: 14px;
@@ -10173,6 +10187,12 @@ select.form-input option:checked {
10173
10187
  display: none;
10174
10188
  }
10175
10189
 
10190
+ .ns-divided {
10191
+ margin-top: 4px;
10192
+ padding-top: 16px;
10193
+ border-top: 1px solid var(--border);
10194
+ }
10195
+
10176
10196
  .ns-label {
10177
10197
  padding-top: 9px;
10178
10198
  font-size: 12px;
@@ -11529,7 +11549,8 @@ pre.mermaid[data-mermaid-error]::before {
11529
11549
  }
11530
11550
 
11531
11551
  .pinned-sub-header:hover .pinned-ungroup-btn,
11532
- .session-group-header:hover .sg-action {
11552
+ .session-group-header:hover .sg-action,
11553
+ .session-group-header.kb-selected .sg-action {
11533
11554
  opacity: 1;
11534
11555
  }
11535
11556
 
@@ -11641,15 +11662,16 @@ pre.mermaid[data-mermaid-error]::before {
11641
11662
  outline: none;
11642
11663
  }
11643
11664
 
11644
- .sg-action.sg-rename {
11645
- margin-left: auto;
11665
+ .sg-action.sg-new,
11666
+ .sg-action.sg-rename,
11667
+ .sg-action.sg-delete {
11646
11668
  display: flex;
11647
11669
  align-items: center;
11648
11670
  }
11649
11671
 
11650
- .sg-action.sg-delete {
11651
- font-size: 15px;
11652
- padding: 0 2px;
11672
+ .sg-action.sg-new,
11673
+ :not(.sg-new) + .sg-action.sg-rename {
11674
+ margin-left: auto;
11653
11675
  }
11654
11676
 
11655
11677
  .session-group-sessions {
package/server.js CHANGED
@@ -62,7 +62,7 @@ const { buildDecision, decisionFileName, isDecisionFile, approvalsFrom, boardRef
62
62
  const { getClaudeDir, getArgValue, storageNamespace, isDefaultClaudeDir } = require('./lib/claude-dir');
63
63
  const { readTerminalConfig } = require('./lib/terminal');
64
64
  const { createTerminalClient } = require('./lib/terminal-client');
65
- const { kanbotOn, kanbotModel, createKanbot, findCostCli, readCostServer } = require('./lib/kanbot');
65
+ const { kanbotOn, kanbotModel, createKanbot, findKanbotApps, readCostServer } = require('./lib/kanbot');
66
66
  const { AGENT_ID_RE } = require('./cli');
67
67
  const { createShowStore, mountShowRoutes, showBodyParser, SHOW_PATH } = require('./lib/show');
68
68
  const { createAskStore, mountAskRoutes, askBodyParser, ASK_PATH } = require('./lib/ask');
@@ -266,6 +266,8 @@ const SESSION_STALE_MS = 5 * 60 * 1000;
266
266
  // never the "active" status (which stays accurate via hasRecentLog).
267
267
  const SESSION_GRACE_MS = 2 * 60 * 1000;
268
268
  const WAITING_RESOLVE_GRACE_MS = 15 * 1000;
269
+ // A finished background task stays in the agents answer this long; the client uses the same window.
270
+ const BACKGROUND_KEEP_MS = 5 * 60 * 1000;
269
271
  const CLEANUP_MAX_AGE_MS = 2 * 24 * 60 * 60 * 1000;
270
272
  const CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
271
273
  const RETENTION_FIRST_RUN_MS = 5 * 60 * 1000;
@@ -2372,10 +2374,36 @@ const RESULT_SCAN = 3;
2372
2374
  // Same for the modelUnavailable latch and extractModelFromTranscript.
2373
2375
  const MODEL_SCAN = 2;
2374
2376
 
2377
+ // A background task dies with its claude process and leaves no notification, so one with no
2378
+ // end counts as running only while the process that started it is alive.
2379
+ async function sessionBackgroundTasks(sessionId, digest) {
2380
+ try {
2381
+ const live = loadLiveSessions().find((s) => s.sessionId === sessionId && s.pid && isPidAlive(s.pid));
2382
+ const now = Date.now();
2383
+ if (!digest) {
2384
+ const meta = loadSessionMetadata()[sessionId];
2385
+ if (!meta?.jsonlPath) return [];
2386
+ // No process and no recent write: nothing can run and every end is past the window.
2387
+ if (!live && now - (getSessionLogStat(meta).mtime || 0) > BACKGROUND_KEEP_MS) return [];
2388
+ digest = await getSessionDigest(meta.jsonlPath);
2389
+ }
2390
+ const tasks = digest?.backgroundTasks;
2391
+ if (!tasks?.length) return [];
2392
+ return tasks.filter((t) => {
2393
+ if (t.endedAt) return now - Date.parse(t.endedAt) < BACKGROUND_KEEP_MS;
2394
+ return !!live && Date.parse(t.startedAt) >= live.startedAt;
2395
+ });
2396
+ } catch (_) {
2397
+ return [];
2398
+ }
2399
+ }
2400
+
2375
2401
  app.get('/api/sessions/:sessionId/agents', async (req, res) => {
2376
2402
  const sessionId = resolveSessionId(req.params.sessionId);
2377
2403
  const agentDir = path.join(AGENT_ACTIVITY_DIR, sessionId);
2378
- if (!existsSync(agentDir)) return res.json({ agents: [], waitingForUser: null });
2404
+ if (!existsSync(agentDir)) {
2405
+ return res.json({ agents: [], waitingForUser: null, background: await sessionBackgroundTasks(sessionId) });
2406
+ }
2379
2407
  try {
2380
2408
  const metadata = loadSessionMetadata();
2381
2409
  const meta = metadata[sessionId] || {};
@@ -2629,9 +2657,9 @@ app.get('/api/sessions/:sessionId/agents', async (req, res) => {
2629
2657
  const usage = byAgentId[agent.agentId]?.usage;
2630
2658
  if (usage) agent.usage = usage;
2631
2659
  }
2632
- res.json({ agents: visibleAgents, waitingForUser, teamColors });
2660
+ res.json({ agents: visibleAgents, waitingForUser, teamColors, background: await sessionBackgroundTasks(sessionId, digest) });
2633
2661
  } catch {
2634
- res.json({ agents: [], waitingForUser: null });
2662
+ res.json({ agents: [], waitingForUser: null, background: [] });
2635
2663
  }
2636
2664
  });
2637
2665
 
@@ -3644,7 +3672,7 @@ async function ensureKanbot() {
3644
3672
  const started = await terminal.startNew(kanbot.startSpec({
3645
3673
  model: kanbotModelSetting(),
3646
3674
  boardUrl: `http://127.0.0.1:${boardPort}`,
3647
- costCli: findCostCli({ claudeDir: CLAUDE_DIR, which: whichSync }),
3675
+ apps: findKanbotApps({ claudeDir: CLAUDE_DIR, which: whichSync }),
3648
3676
  }));
3649
3677
  if (started.error) return started;
3650
3678
  kanbot.ptyId = started.id;