claude-code-kanban 7.36.0 → 7.38.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.38.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,94 @@ 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="openBackgroundOutput('${escAttrJs(t.taskId)}')"` : '');
3621
+
3622
+ function backgroundStatusRowHtml(t, now) {
3623
+ const running = !t.endedAt;
3624
+ const status = running ? 'running' : t.status === 'completed' ? 'done' : t.status;
3625
+ const elapsed = (running ? now : Date.parse(t.endedAt)) - Date.parse(t.startedAt);
3626
+ return `<span class="agent-status"><span class="agent-dot ${running ? 'active' : 'stopped'}"></span>${escapeHtml(status)}</span><span class="agent-duration">${formatDuration(elapsed)}</span>`;
3627
+ }
3628
+
3629
+ // The output file holds only what the task printed, so the modal shows the task above it.
3630
+ // biome-ignore lint/correctness/noUnusedVariables: used in HTML
3631
+ async function openBackgroundOutput(taskId) {
3632
+ const t = currentBackground.find((x) => x.taskId === taskId);
3633
+ if (!t?.outputFile || !(await openPreviewByPath(t.outputFile))) return;
3634
+ const el = document.getElementById('preview-task');
3635
+ el.innerHTML = `<div class="agent-status-row preview-task-meta">${backgroundKindHtml(t)}${backgroundStatusRowHtml(t, Date.now())}</div>
3636
+ ${t.description ? `<div class="preview-task-desc">${escapeHtml(t.description)}</div>` : ''}
3637
+ ${t.command ? `<div class="preview-task-cmd"><pre class="perm-code">${escapeHtml(t.command)}</pre><button type="button" class="icon-btn" aria-label="Copy command" title="Copy command">${ICON_COPY}</button></div>` : ''}`;
3638
+ el.querySelector('.preview-task-cmd button')?.addEventListener('click', (e) =>
3639
+ copyWithFeedback(t.command, e.currentTarget),
3640
+ );
3641
+ el.hidden = false;
3642
+ }
3643
+
3644
+ function zenBackgroundHtml(running) {
3645
+ if (!running.length) return '';
3646
+ const rows = running.slice(0, ZEN_AGENTS_MAX).map((t) => {
3647
+ const label = truncateAtWord(backgroundLabel(t), 200);
3648
+ return `<button type="button" class="zen-agent" title="${escapeHtml(t.command || label)}"${backgroundClickAttr(t)}>
3649
+ <span class="agent-dot active"></span>
3650
+ <span class="zen-agent-text"><span class="zen-agent-task">${escapeHtml(label)}</span><span class="agent-ident-row">${backgroundKindHtml(t)}</span></span>
3651
+ <span class="zen-agent-time"></span>
3652
+ </button>`;
3653
+ });
3654
+ return `<div class="panel-section-header"><span>Background</span><span class="panel-section-count">${running.length}</span></div>${rows.join('')}`;
3655
+ }
3656
+
3657
+ function backgroundCardHtml(t, now) {
3658
+ const running = !t.endedAt;
3659
+ const label = backgroundLabel(t);
3660
+ return `<div class="agent-card background-card ${running ? 'active' : 'stopped'}${t.outputFile ? ' has-output' : ''}" title="${escapeHtml(t.command || label)}"${backgroundClickAttr(t)}>
3661
+ <div class="agent-task">${escapeHtml(label)}</div>
3662
+ <div class="agent-ident-row">${backgroundKindHtml(t)}</div>
3663
+ <div class="agent-status-row">${backgroundStatusRowHtml(t, now)}</div>
3664
+ </div>`;
3665
+ }
3666
+
3667
+ function agentCardHtml(a, now) {
3668
+ const status = agentStatus(a);
3669
+ const displayText = agentTaskText(a);
3670
+ const nameColor = a.agentName ? resolveNamedColor(a.color) || getOwnerColor(a.agentName) : null;
3671
+ const nameBadgeHtml = nameColor
3672
+ ? `<span class="task-owner-badge task-owner-badge--compact" style="background:${nameColor.bg};color:${nameColor.color}">${escapeHtml(a.agentName)}</span>`
3673
+ : '';
3674
+ const selectedClass = a.agentId === currentAgentModalId ? ' selected' : '';
3675
+ return `<div class="agent-card ${status}${selectedClass}" data-agent-id="${escapeHtml(a.agentId)}" onclick="showAgentModal('${escAttrJs(a.agentId)}')">
3676
+ ${agentLogButton(a.agentId, 'agent-card-log-btn')}
3677
+ <div class="agent-task" title="${escapeHtml(displayText)}">${escapeHtml(displayText)}</div>
3678
+ <div class="agent-ident-row">${agentIdentHtml(a)}${nameBadgeHtml}</div>
3679
+ <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>
3680
+ </div>`;
3681
+ }
3682
+
3591
3683
  function renderAgentFooter() {
3592
3684
  schedulePublish();
3593
3685
  const footer = document.getElementById('agent-footer');
@@ -3595,6 +3687,7 @@ function renderAgentFooter() {
3595
3687
  const label = document.getElementById('agent-footer-label');
3596
3688
  const now = Date.now();
3597
3689
  const agents = visibleAgents();
3690
+ const background = visibleBackground(now);
3598
3691
  renderZenAgents(agents);
3599
3692
  renderAgentViews(agents);
3600
3693
  const expanded = footer.classList.contains('expanded');
@@ -3602,8 +3695,9 @@ function renderAgentFooter() {
3602
3695
  const hidden = agents.length - visible.length;
3603
3696
 
3604
3697
  const permFresh = isWaitingFresh();
3698
+ const backgroundRunning = background.filter((t) => !t.endedAt).length;
3605
3699
 
3606
- if (visible.length === 0 && !permFresh) {
3700
+ if (visible.length === 0 && !permFresh && !background.length) {
3607
3701
  footer.classList.remove('visible');
3608
3702
  clearInterval(agentDurationInterval);
3609
3703
  agentDurationInterval = null;
@@ -3614,41 +3708,36 @@ function renderAgentFooter() {
3614
3708
 
3615
3709
  footer.classList.add('visible');
3616
3710
  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>` : ''}`;
3711
+ const labelPart = (n, word) => (n ? `<span class="agent-footer-running">· ${n} ${word}</span>` : '');
3712
+ label.innerHTML = `Agents log <span class="agent-footer-count">${agents.length}</span>${labelPart(running, 'running')}${labelPart(backgroundRunning, 'in background')}`;
3618
3713
 
3619
3714
  const permHtml = permFresh
3620
3715
  ? `<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
3716
  : '';
3622
3717
 
3718
+ const cards = [
3719
+ ...background.map((t) => ({
3720
+ rank: t.endedAt ? AGENT_STATUS_ORDER.stopped : AGENT_STATUS_ORDER.active,
3721
+ at: Date.parse(t.endedAt || t.startedAt),
3722
+ html: backgroundCardHtml(t, now),
3723
+ })),
3724
+ ...visible.map((a) => ({
3725
+ rank: AGENT_STATUS_ORDER[a.status] ?? AGENT_STATUS_ORDER.stopped,
3726
+ at: new Date(a.updatedAt || 0).getTime(),
3727
+ html: agentCardHtml(a, now),
3728
+ })),
3729
+ ].sort((a, b) => a.rank - b.rank || b.at - a.at);
3730
+
3623
3731
  content.innerHTML =
3624
3732
  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('') +
3733
+ cards.map((c) => c.html).join('') +
3645
3734
  (expanded && hidden > 0
3646
3735
  ? `<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
3736
  : '');
3648
3737
  updateScrollFades(content);
3649
3738
 
3650
3739
  clearInterval(agentDurationInterval);
3651
- if (visible.some((a) => a.status === 'active' || a.status === 'idle')) {
3740
+ if (backgroundRunning || visible.some((a) => a.status === 'active' || a.status === 'idle')) {
3652
3741
  agentDurationInterval = setInterval(() => isOnScreen() && renderAgentFooter(), 1000);
3653
3742
  if (!agentPollInterval) {
3654
3743
  agentPollInterval = setInterval(() => {
@@ -4619,7 +4708,7 @@ function renderSessions() {
4619
4708
  renderZenAgents(visibleAgents());
4620
4709
  bindLinkedDocsHandlers(sessionsList.querySelector('.linked-docs-section'), zenSession.id);
4621
4710
  artifactsSection.load(zenSession.id);
4622
- scratchFilesSection.load(zenSession.id);
4711
+ loadScratchFiles(zenSession.id);
4623
4712
  if (zenSession.hasWorkflow) pollWorkflowLive(zenSession.id);
4624
4713
  restoreSessionCursor();
4625
4714
  return;
@@ -5785,7 +5874,8 @@ function sgHostOf(group, placed) {
5785
5874
  }
5786
5875
  // `opts.under` places the session under another project block of the group; `opts.loose` lifts it
5787
5876
  // 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.
5877
+ // left out, a move inside the group keeps it; null clears it. `opts.project` is the project of a
5878
+ // session that is not in `sessions` yet.
5789
5879
  function sgAssign(groupId, type, ref, opts = {}) {
5790
5880
  const group = sgGroupById(groupId);
5791
5881
  if (!group) return;
@@ -5796,7 +5886,7 @@ function sgAssign(groupId, type, ref, opts = {}) {
5796
5886
  if (type === 'project') {
5797
5887
  for (const s of sessions) if (sessionProjectKey(s) === ref) sgDetach('session', s.id);
5798
5888
  }
5799
- const own = type === 'session' ? sessionProjectKey(sessions.find((s) => s.id === ref)) : null;
5889
+ const own = type === 'session' ? (opts.project ?? sessionProjectKey(sessions.find((s) => s.id === ref))) : null;
5800
5890
  // Under its own project block is simply the natural placement - no override needed.
5801
5891
  const under = opts.under && opts.under !== own ? opts.under : null;
5802
5892
  const loose = !under && !!opts.loose;
@@ -5814,6 +5904,15 @@ function sgAssign(groupId, type, ref, opts = {}) {
5814
5904
  persistSessionGroups();
5815
5905
  }
5816
5906
 
5907
+ function sgDefaultFolder(group) {
5908
+ let recent = null;
5909
+ for (const s of sessions) {
5910
+ if (s.placeholder || sgGroupForSession(s) !== group) continue;
5911
+ if (!recent || (s.modifiedAt || '') > (recent.modifiedAt || '')) recent = s;
5912
+ }
5913
+ return sessionProjectKey(recent) || group.members.find((m) => m.type === 'project')?.ref || null;
5914
+ }
5915
+
5817
5916
  function sgCreateGroup(name) {
5818
5917
  const group = {
5819
5918
  id: `g_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
@@ -5904,8 +6003,9 @@ function sgHeaderHtml(group, countHtml) {
5904
6003
  const hint = group.transient ? 'goes when its sessions leave the Active view' : 'drop sessions or projects here';
5905
6004
  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
6005
  const actions = `${group.transient ? '<span class="sg-action sg-keep" title="Keep this group after its sessions end">Keep</span>' : ''}
6006
+ ${terminalAvailable() ? `<span class="sg-action sg-new" title="New session in ${escapeHtml(group.name)}">${PLUS_SVG}</span>` : ''}
5907
6007
  <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>
6008
+ <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
6009
  ${headerPadBtnHtml(_groupScratchpadKey(group.id), group.name)}`;
5910
6010
  return `
5911
6011
  <div ${attrs} data-group-path="${escapeHtml(sgKey(group.id))}">
@@ -8570,6 +8670,23 @@ const MODAL_CLOSERS = {
8570
8670
  'pane-pop': () => closePanePop(),
8571
8671
  };
8572
8672
 
8673
+ function topModalId() {
8674
+ const visible = [...document.querySelectorAll('.modal-overlay.visible')];
8675
+ return MODAL_ESC_PRIORITY.find((id) => visible.some((m) => m.id === id)) || visible[visible.length - 1].id;
8676
+ }
8677
+
8678
+ // Focus is on the dialog, a button or the page behind, not inside the text, so the browser finds no
8679
+ // scroll box for Page Up and Page Down.
8680
+ function pageTopModal(e) {
8681
+ const overlay = document.getElementById(topModalId());
8682
+ let box = overlay.querySelector('.modal-zoomable');
8683
+ const scrolls = (el) => el.scrollHeight > el.clientHeight && /auto|scroll/.test(getComputedStyle(el).overflowY);
8684
+ while (box && box !== overlay && !scrolls(box)) box = box.parentElement;
8685
+ if (!box || box === overlay || box.contains(e.target)) return false;
8686
+ box.scrollBy({ top: (e.key === 'PageDown' ? 1 : -1) * box.clientHeight * 0.9 });
8687
+ return true;
8688
+ }
8689
+
8573
8690
  document.addEventListener('keydown', (e) => {
8574
8691
  // Scale the open modal's reading surface, or the file pane's, instead of letting the browser zoom
8575
8692
  // the whole page. Sits above the text-field guard so it still works with the
@@ -8627,12 +8744,13 @@ document.addEventListener('keydown', (e) => {
8627
8744
  return;
8628
8745
  }
8629
8746
  // 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;
8747
+ const topId = topModalId();
8632
8748
  const close = MODAL_CLOSERS[topId];
8633
8749
  if (close) close();
8634
8750
  else document.getElementById(topId).classList.remove('visible');
8635
8751
  e.stopImmediatePropagation();
8752
+ } else if (matchKey(e, 'PageDown', 'PageUp')) {
8753
+ if (pageTopModal(e)) e.preventDefault();
8636
8754
  } else if (e.key === '?' && document.getElementById('help-modal').classList.contains('visible')) {
8637
8755
  e.preventDefault();
8638
8756
  closeHelpModal();
@@ -10115,7 +10233,7 @@ function renderSourcePreview(filePath, content) {
10115
10233
  // Every kind but html, which needs a frame.
10116
10234
  function renderPreviewContent(bodyEl, filePath, content, kind) {
10117
10235
  if (kind === 'text') {
10118
- bodyEl.innerHTML = renderSourcePreview(filePath, content);
10236
+ bodyEl.innerHTML = renderSourcePreview(filePath, stripAnsi(content));
10119
10237
  } else if (kind === 'image') {
10120
10238
  const img = document.createElement('img');
10121
10239
  img.className = 'preview-image';
@@ -10156,6 +10274,7 @@ function localImageUrl(src, base) {
10156
10274
  }
10157
10275
 
10158
10276
  function openPreviewModal(filePath, content, kind, sessionId) {
10277
+ document.getElementById('preview-task').hidden = true;
10159
10278
  currentPreviewPath = filePath;
10160
10279
  currentPreviewContent = kind === 'image' ? null : content;
10161
10280
  document.getElementById('preview-copy-content-btn').style.display = currentPreviewContent == null ? 'none' : '';
@@ -10314,6 +10433,7 @@ async function openPreviewByPath(
10314
10433
  return;
10315
10434
  }
10316
10435
  openPreviewModal(data.path, data.content, data.kind, sessionId);
10436
+ return true;
10317
10437
  } catch {
10318
10438
  showToast('Failed to load preview', 'error');
10319
10439
  }
@@ -10850,6 +10970,8 @@ const scratchFilesSection = makeSectionLoader({
10850
10970
  // Outlives the cache entries on purpose: a refetch on the TTL must not collapse a list
10851
10971
  // the user opened.
10852
10972
  const scratchFilesExpanded = new Set();
10973
+ const SCRATCHPAD_FOLDED_KEY = sectionCollapsedKey('zen-scratchpad');
10974
+ let scratchpadFolded = store.getItem(SCRATCHPAD_FOLDED_KEY) === 'true';
10853
10975
  // Open folders only, keyed by absolute path: path -> { status: 'loading' | 'ready' |
10854
10976
  // 'error', children }. Closing a folder drops its entry, so the cache is bounded by
10855
10977
  // what is on screen and a reopen shows fresh contents for one readdir.
@@ -10904,6 +11026,11 @@ function scratchFilesInnerHtml(sessionId) {
10904
11026
  // Delegated at the document because the whole zen panel is re-rendered on every SSE tick,
10905
11027
  // which would drop a listener bound on the section.
10906
11028
  document.addEventListener('click', (e) => {
11029
+ const row = e.target.closest('.zen-scratchpad');
11030
+ if (row && !e.target.closest('.row-actions')) {
11031
+ toggleScratchpadFolded(row);
11032
+ return;
11033
+ }
10907
11034
  const toggle = e.target.closest('.scratch-folder-toggle');
10908
11035
  if (!toggle) return;
10909
11036
  const section = toggle.closest('[data-scratch-files-for]');
@@ -10928,8 +11055,21 @@ async function toggleScratchFolder(sessionId, dirPath) {
10928
11055
  }
10929
11056
  }
10930
11057
 
10931
- function renderScratchFilesHtml(sessionId) {
10932
- return `<div class="scratch-files-section" data-scratch-files-for="${escapeHtml(sessionId)}">${scratchFilesInnerHtml(sessionId)}</div>`;
11058
+ function loadScratchFiles(sessionId) {
11059
+ if (!scratchpadFolded) scratchFilesSection.load(sessionId);
11060
+ }
11061
+
11062
+ function toggleScratchpadFolded(row) {
11063
+ scratchpadFolded = !scratchpadFolded;
11064
+ store.setItem(SCRATCHPAD_FOLDED_KEY, scratchpadFolded);
11065
+ row.classList.toggle('collapsed', scratchpadFolded);
11066
+ const sessionId = row.dataset.scratchSession;
11067
+ paintSectionSlots('data-scratch-files-for', sessionId, scratchpadFolded ? '' : scratchFilesInnerHtml(sessionId));
11068
+ loadScratchFiles(sessionId);
11069
+ }
11070
+
11071
+ function renderScratchFilesSlot(sessionId, inner) {
11072
+ return `<div class="scratch-files-section" data-scratch-files-for="${escapeHtml(sessionId)}">${inner}</div>`;
10933
11073
  }
10934
11074
 
10935
11075
  // biome-ignore lint/correctness/noUnusedVariables: used in HTML
@@ -12787,6 +12927,10 @@ document.addEventListener('click', (e) => {
12787
12927
  sgConfirmDelete(group);
12788
12928
  return;
12789
12929
  }
12930
+ if (e.target.closest('.sg-new')) {
12931
+ openNewSession(sgDefaultFolder(group), false, group.id);
12932
+ return;
12933
+ }
12790
12934
  }
12791
12935
 
12792
12936
  const header = e.target.closest(COLLAPSIBLE_HEADER_SELECTOR);
@@ -13156,15 +13300,15 @@ function abbreviateScratchpadDir(dir) {
13156
13300
  function renderScratchpadRow(session) {
13157
13301
  const dir = session?.scratchpadDir;
13158
13302
  if (!dir) return '';
13159
- return `<div class="zen-scratchpad">
13160
- <span class="zen-scratchpad-label">Scratchpad</span>
13161
- <span class="zen-scratchpad-path" title="${escapeHtml(dir)}">${escapeHtml(abbreviateScratchpadDir(dir))}</span>
13303
+ return `<div class="zen-scratchpad panel-section-header${scratchpadFolded ? ' collapsed' : ''}" data-scratch-session="${escapeHtml(session.id)}" title="${escapeHtml(dir)}">
13304
+ ${groupChevronSvg(12)}
13305
+ <span>Scratchpad</span>
13162
13306
  <span class="row-actions">
13163
13307
  <button onclick="copyWithFeedback('${escAttrJs(dir)}', this)" title="Copy">${ICON_COPY}</button>
13164
13308
  <button data-folder="${escapeHtml(dir)}" onclick="openFolderInEditor(this.dataset.folder)" title="Open in editor">${ICON_OPEN_EXTERNAL}</button>
13165
13309
  </span>
13166
13310
  </div>
13167
- ${renderScratchFilesHtml(session.id)}`;
13311
+ ${renderScratchFilesSlot(session.id, scratchpadFolded ? '' : scratchFilesInnerHtml(session.id))}`;
13168
13312
  }
13169
13313
 
13170
13314
  function showInfoModal(session, teamConfig, tasks, planContent, parentInfo) {
@@ -15055,10 +15199,20 @@ function paneBlockedHtml(pane) {
15055
15199
  );
15056
15200
  }
15057
15201
 
15202
+ function isLoopbackUrl(url) {
15203
+ try {
15204
+ return PANE_LOOPBACK.has(new URL(url, location.href).hostname);
15205
+ } catch {
15206
+ return false;
15207
+ }
15208
+ }
15209
+
15058
15210
  function paneUrlFrame(pane, className) {
15059
15211
  const frame = document.createElement('iframe');
15060
15212
  frame.className = className;
15061
15213
  frame.setAttribute('sandbox', PANE_URL_SANDBOX);
15214
+ // A cross-origin frame cannot write the clipboard without this; only local apps get it.
15215
+ if (isLoopbackUrl(pane.target)) frame.allow = 'clipboard-write';
15062
15216
  frame.setAttribute('referrerpolicy', 'no-referrer');
15063
15217
  frame.title = pane.title;
15064
15218
  frame.src = pane.target;
@@ -19542,6 +19696,10 @@ function dropPlaceholder(id) {
19542
19696
 
19543
19697
  function forgetPlaceholder(id) {
19544
19698
  if (!newSpecs.delete(id)) return false;
19699
+ if (sgGroupOf('session', id)) {
19700
+ sgDetach('session', id);
19701
+ persistSessionGroups();
19702
+ }
19545
19703
  setTerminalMode(id, false);
19546
19704
  // Before the socket's close handler runs, or it would reconnect and start the session again.
19547
19705
  if (termState.sessionId === id) detachTerminal();
@@ -19660,10 +19818,26 @@ function showSessionTerminal(sessionId) {
19660
19818
  else fetchTasks(sessionId);
19661
19819
  }
19662
19820
 
19663
- function openNewSession(folder, resume = false) {
19821
+ function setNewSessionGroup(groupId) {
19822
+ const select = document.getElementById('ns-group');
19823
+ select.innerHTML = `<option value="">No group</option>${sessionGroups
19824
+ .map((g) => `<option value="${escapeHtml(g.id)}">${escapeHtml(sgPathOf(g))}</option>`)
19825
+ .join('')}`;
19826
+ select.value = groupId ?? '';
19827
+ document.getElementById('ns-group-row').hidden = !sessionGroups.length;
19828
+ }
19829
+
19830
+ // Before the placeholder's first merge, so that merge reveals the group and not the project.
19831
+ function joinNewSessionGroup(id) {
19832
+ const groupId = document.getElementById('ns-group').value;
19833
+ if (groupId) sgAssign(groupId, 'session', id, { project: newSpecs.get(id).cwd });
19834
+ }
19835
+
19836
+ function openNewSession(folder, resume = false, groupId = null) {
19664
19837
  if (!terminalAvailable() || document.getElementById('new-session-modal').classList.contains('visible')) return;
19665
19838
  if (terminalPaneFocused()) leaveTerminalPane();
19666
19839
  ns.resume = resume;
19840
+ setNewSessionGroup(resume ? null : groupId);
19667
19841
  ns.extraArgs = [];
19668
19842
  document.querySelector('.new-session-modal').classList.toggle('ns-resume', resume);
19669
19843
  document.getElementById('ns-title').textContent = resume ? 'Resume session' : 'New session';
@@ -19946,6 +20120,7 @@ async function startNewSession() {
19946
20120
  }
19947
20121
  newSpecs.set(id, { ...(ns.resume ? { cwd: v.cwd } : v), mode: ns.resume ? 'pick' : 'new', startedAt: Date.now() });
19948
20122
  setTerminalMode(id, true);
20123
+ joinNewSessionGroup(id);
19949
20124
  if (v.stay) return startNewSessionInBackground(id, v);
19950
20125
  closeNewSession();
19951
20126
  openPlaceholder(id);
@@ -19985,6 +20160,7 @@ async function startNewSessionInBackground(id, v) {
19985
20160
  forgetPlaceholder(id);
19986
20161
  newSpecs.set(r.session, spec);
19987
20162
  setTerminalMode(r.session, true);
20163
+ joinNewSessionGroup(r.session);
19988
20164
  refreshPlaceholders();
19989
20165
  }
19990
20166
  closeNewSession();
package/public/index.html CHANGED
@@ -541,6 +541,7 @@
541
541
  </button>
542
542
  </div>
543
543
  </div>
544
+ <div id="preview-task" hidden></div>
544
545
  <div class="modal-body">
545
546
  <div class="preview-split">
546
547
  <div id="preview-modal-body" class="rendered-md modal-zoomable"></div>
@@ -903,6 +904,12 @@
903
904
  <div id="ns-images" class="ns-images" hidden></div>
904
905
  </div>
905
906
  </div>
907
+ <div id="ns-group-row" class="ns-row ns-extra" hidden>
908
+ <label class="ns-label" for="ns-group">Group</label>
909
+ <div class="ns-field">
910
+ <select id="ns-group" class="form-input"></select>
911
+ </div>
912
+ </div>
906
913
  <div class="ns-row ns-extra">
907
914
  <span class="ns-label">Worktree</span>
908
915
  <div class="ns-field">
@@ -913,7 +920,7 @@
913
920
  <div id="ns-wt-hint" class="ns-hint" hidden></div>
914
921
  </div>
915
922
  </div>
916
- <div class="ns-row ns-extra">
923
+ <div class="ns-row ns-extra ns-divided">
917
924
  <span class="ns-label"></span>
918
925
  <div class="ns-field">
919
926
  <div class="ns-inline">
package/public/style.css CHANGED
@@ -1540,31 +1540,18 @@ body.booting .boot-splash {
1540
1540
  }
1541
1541
 
1542
1542
  .zen-scratchpad {
1543
- display: flex;
1544
- align-items: center;
1545
- gap: 8px;
1546
1543
  margin-top: 12px;
1547
1544
  padding-top: 10px;
1548
1545
  border-top: 1px solid var(--border);
1549
- font-size: 11px;
1546
+ cursor: pointer;
1550
1547
  }
1551
1548
 
1552
- .zen-scratchpad-label {
1553
- font-weight: 500;
1554
- color: var(--text-muted);
1555
- text-transform: uppercase;
1556
- letter-spacing: 0.5px;
1557
- white-space: nowrap;
1549
+ .zen-scratchpad:hover {
1550
+ color: var(--text-primary);
1558
1551
  }
1559
1552
 
1560
- .zen-scratchpad-path {
1561
- flex: 1;
1562
- min-width: 0;
1563
- overflow: hidden;
1564
- text-overflow: ellipsis;
1565
- white-space: nowrap;
1566
- font-family: var(--font-mono);
1567
- color: var(--text-secondary);
1553
+ .zen-scratchpad .row-actions {
1554
+ margin-left: auto;
1568
1555
  }
1569
1556
 
1570
1557
  .zen-panel:hover .row-actions {
@@ -7769,6 +7756,20 @@ button.agent-map-node:hover {
7769
7756
  .agent-card.fading {
7770
7757
  opacity: 0.4;
7771
7758
  }
7759
+ .agent-card.background-card {
7760
+ border-style: dashed;
7761
+ }
7762
+ .agent-card.background-card:not(.has-output) {
7763
+ cursor: default;
7764
+ }
7765
+ .agent-card.background-card:not(.has-output):hover {
7766
+ border-color: var(--border);
7767
+ }
7768
+ .background-kind {
7769
+ display: inline-flex;
7770
+ align-items: center;
7771
+ gap: 4px;
7772
+ }
7772
7773
  .agent-task {
7773
7774
  max-width: 240px;
7774
7775
  padding-right: 14px;
@@ -8850,6 +8851,53 @@ body.light .msg-assistant .msg-text {
8850
8851
  color: var(--text-primary);
8851
8852
  }
8852
8853
 
8854
+ #preview-task {
8855
+ flex: none;
8856
+ display: grid;
8857
+ gap: 6px;
8858
+ padding: 10px 0;
8859
+ border-bottom: 1px solid var(--border);
8860
+ }
8861
+
8862
+ #preview-task[hidden] {
8863
+ display: none;
8864
+ }
8865
+
8866
+ .preview-task-meta {
8867
+ justify-content: flex-start;
8868
+ gap: 12px;
8869
+ font-size: 11px;
8870
+ color: var(--text-muted);
8871
+ }
8872
+
8873
+ .preview-task-meta .agent-status,
8874
+ .preview-task-meta .agent-duration {
8875
+ font-size: 11px;
8876
+ }
8877
+
8878
+ .preview-task-desc {
8879
+ font-size: 13px;
8880
+ font-weight: 600;
8881
+ color: var(--text-primary);
8882
+ }
8883
+
8884
+ .preview-task-cmd {
8885
+ position: relative;
8886
+ }
8887
+
8888
+ .preview-task-cmd pre {
8889
+ max-height: 7.5em;
8890
+ overflow: auto;
8891
+ padding-right: 40px;
8892
+ font-size: 12px;
8893
+ }
8894
+
8895
+ .preview-task-cmd .icon-btn {
8896
+ position: absolute;
8897
+ top: 4px;
8898
+ right: 4px;
8899
+ }
8900
+
8853
8901
  /* Rendered HTML pages need far more room than a markdown doc. */
8854
8902
  .modal.preview-modal-dialog.preview-html {
8855
8903
  width: 96vw;
@@ -10173,6 +10221,12 @@ select.form-input option:checked {
10173
10221
  display: none;
10174
10222
  }
10175
10223
 
10224
+ .ns-divided {
10225
+ margin-top: 4px;
10226
+ padding-top: 16px;
10227
+ border-top: 1px solid var(--border);
10228
+ }
10229
+
10176
10230
  .ns-label {
10177
10231
  padding-top: 9px;
10178
10232
  font-size: 12px;
@@ -11344,7 +11398,8 @@ pre.mermaid[data-mermaid-error]::before {
11344
11398
  .project-group-header .group-chevron,
11345
11399
  .session-group-header .group-chevron,
11346
11400
  .sg-section-toggle .group-chevron,
11347
- .scratch-folder-toggle .group-chevron {
11401
+ .scratch-folder-toggle .group-chevron,
11402
+ .zen-scratchpad .group-chevron {
11348
11403
  transition: transform 0.15s ease;
11349
11404
  flex-shrink: 0;
11350
11405
  display: block;
@@ -11353,7 +11408,8 @@ pre.mermaid[data-mermaid-error]::before {
11353
11408
  .project-group-header.collapsed .group-chevron,
11354
11409
  .session-group-header.collapsed .group-chevron,
11355
11410
  .sg-section-toggle.collapsed .group-chevron,
11356
- .scratch-folder-toggle.collapsed .group-chevron {
11411
+ .scratch-folder-toggle.collapsed .group-chevron,
11412
+ .zen-scratchpad.collapsed .group-chevron {
11357
11413
  transform: rotate(-90deg);
11358
11414
  }
11359
11415
 
@@ -11529,7 +11585,8 @@ pre.mermaid[data-mermaid-error]::before {
11529
11585
  }
11530
11586
 
11531
11587
  .pinned-sub-header:hover .pinned-ungroup-btn,
11532
- .session-group-header:hover .sg-action {
11588
+ .session-group-header:hover .sg-action,
11589
+ .session-group-header.kb-selected .sg-action {
11533
11590
  opacity: 1;
11534
11591
  }
11535
11592
 
@@ -11641,15 +11698,16 @@ pre.mermaid[data-mermaid-error]::before {
11641
11698
  outline: none;
11642
11699
  }
11643
11700
 
11644
- .sg-action.sg-rename {
11645
- margin-left: auto;
11701
+ .sg-action.sg-new,
11702
+ .sg-action.sg-rename,
11703
+ .sg-action.sg-delete {
11646
11704
  display: flex;
11647
11705
  align-items: center;
11648
11706
  }
11649
11707
 
11650
- .sg-action.sg-delete {
11651
- font-size: 15px;
11652
- padding: 0 2px;
11708
+ .sg-action.sg-new,
11709
+ :not(.sg-new) + .sg-action.sg-rename {
11710
+ margin-left: auto;
11653
11711
  }
11654
11712
 
11655
11713
  .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;
@@ -4011,7 +4039,11 @@ function resolvePreviewPath(rawPath, base) {
4011
4039
  // Normalized, not passed through: a linked document is identified by its path string,
4012
4040
  // and `C:/a/b` typed into the link editor has to reach the same string as the `C:\a\b`
4013
4041
  // a server-side `path.join` produces, or the same file is linked twice.
4014
- if (path.isAbsolute(filePath)) return dropUrlFragment(path.normalize(filePath));
4042
+ if (path.isAbsolute(filePath)) {
4043
+ const abs = dropUrlFragment(path.normalize(filePath));
4044
+ // Claude Code names its task output files under the 8.3 short temp dir (NIKIFO~1).
4045
+ return /~\d/.test(abs) ? realpathDeepest(abs) : abs;
4046
+ }
4015
4047
  if (base && typeof base === 'string' && path.isAbsolute(base)) {
4016
4048
  let baseDir = base;
4017
4049
  try {