claude-code-kanban 4.10.0 → 4.12.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/parsers.js CHANGED
@@ -551,6 +551,7 @@ function readRecentMessages(jsonlPath, limit = 10) {
551
551
  const messages = [];
552
552
  const toolResults = new Map();
553
553
  const toolResultExtras = new Map();
554
+ const toolResultImageCounts = new Map();
554
555
  let readSize = Math.min(65536, stat.size);
555
556
 
556
557
  while (messages.length < limit) {
@@ -567,6 +568,7 @@ function readRecentMessages(jsonlPath, limit = 10) {
567
568
  messages.length = 0;
568
569
  toolResults.clear();
569
570
  toolResultExtras.clear();
571
+ toolResultImageCounts.clear();
570
572
  for (const line of clean.split('\n')) {
571
573
  if (!line.trim()) continue;
572
574
  try {
@@ -823,6 +825,15 @@ function readRecentMessages(jsonlPath, limit = 10) {
823
825
  .filter(c => c.type === 'text' && c.text)
824
826
  .map(c => c.text)
825
827
  .join('\n');
828
+ // A Read on an image file (e.g. .png) returns the image as a
829
+ // base64 block inside the tool_result. Count them so the
830
+ // renderer can request each by index and show what the agent
831
+ // saw; the bytes are fetched lazily per image via the endpoint.
832
+ let imgCount = 0;
833
+ for (const c of block.content) {
834
+ if (c && c.type === 'image' && c.source && c.source.type === 'base64') imgCount++;
835
+ }
836
+ if (imgCount) toolResultImageCounts.set(block.tool_use_id, imgCount);
826
837
  }
827
838
  if (resultText) {
828
839
  toolResults.set(block.tool_use_id, resultText);
@@ -900,6 +911,9 @@ function readRecentMessages(jsonlPath, limit = 10) {
900
911
  }
901
912
  msg.toolResultTruncated = truncated;
902
913
  }
914
+ if (msg.type === 'tool_use' && msg.toolUseId && toolResultImageCounts.has(msg.toolUseId)) {
915
+ msg.toolResultImageCount = toolResultImageCounts.get(msg.toolUseId);
916
+ }
903
917
  if (msg.type === 'tool_use' && msg.tool === 'AskUserQuestion'
904
918
  && msg.toolUseId && toolResultExtras.has(msg.toolUseId)) {
905
919
  const extra = toolResultExtras.get(msg.toolUseId);
@@ -981,6 +995,36 @@ function readUserImage(jsonlPath, msgUuid, blockIndex) {
981
995
  return null;
982
996
  }
983
997
 
998
+ // Read the Nth base64 image embedded in a tool_result block (e.g. the output of
999
+ // a Read on an image file). Scans for the tool_result matching toolUseId.
1000
+ function readToolResultImage(jsonlPath, toolUseId, n) {
1001
+ if (!toolUseId || !jsonlPath) return null;
1002
+ const idx = Number(n);
1003
+ if (!Number.isInteger(idx) || idx < 0) return null;
1004
+ try {
1005
+ const content = readFileSync(jsonlPath, 'utf8');
1006
+ const lines = content.split('\n');
1007
+ for (const line of lines) {
1008
+ if (!line || line.indexOf(toolUseId) === -1) continue;
1009
+ let obj;
1010
+ try { obj = JSON.parse(line); } catch (_) { continue; }
1011
+ const blocks = obj?.message?.content;
1012
+ if (!Array.isArray(blocks)) continue;
1013
+ for (const block of blocks) {
1014
+ if (block?.type !== 'tool_result' || block.tool_use_id !== toolUseId) continue;
1015
+ if (!Array.isArray(block.content)) continue;
1016
+ const images = block.content.filter(
1017
+ (c) => c && c.type === 'image' && c.source && c.source.type === 'base64',
1018
+ );
1019
+ const img = images[idx];
1020
+ if (!img) return null;
1021
+ return { mediaType: img.source.media_type || 'image/png', data: img.source.data };
1022
+ }
1023
+ }
1024
+ } catch (_) {}
1025
+ return null;
1026
+ }
1027
+
984
1028
  const CACHED_IMAGE_MIME = {
985
1029
  png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp',
986
1030
  };
@@ -1438,6 +1482,7 @@ module.exports = {
1438
1482
  readMessagesPage,
1439
1483
  readFullToolResult,
1440
1484
  readUserImage,
1485
+ readToolResultImage,
1441
1486
  readCachedImage,
1442
1487
  updateLoopInfo,
1443
1488
  buildLoopInfoFromState,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-kanban",
3
- "version": "4.10.0",
3
+ "version": "4.12.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
  "bin": {
package/public/app.js CHANGED
@@ -1643,17 +1643,24 @@ function _renderPinToDetail(pin) {
1643
1643
  if (pin.type === 'tool_use') {
1644
1644
  document.getElementById('msg-detail-title').textContent = pin.tool || 'Tool';
1645
1645
  const fullText = pin.fullDetail || pin.detail || '';
1646
- const pinParamsHtml = renderToolParamsHtml(pin.params);
1647
- const pinResultHtml = renderToolResultHtml(
1648
- pin.toolResult,
1649
- pin.toolResultTruncated,
1650
- pin.toolResultFull,
1651
- pin.toolUseId,
1652
- );
1646
+ const pinFindings = pin.tool === 'ReportFindings';
1647
+ const pinParamsHtml = pinFindings
1648
+ ? renderFindingsReport(pin.params, pin.toolResult)
1649
+ : renderToolParamsHtml(pin.params);
1650
+ const pinResultHtml = pinFindings
1651
+ ? ''
1652
+ : renderToolResultHtml(pin.toolResult, pin.toolResultTruncated, pin.toolResultFull, pin.toolUseId);
1653
1653
  const pinDetailEscaped = escapeHtml(fullText);
1654
1654
  const pinDetailRendered = pin.tool === 'Bash' ? highlightBash(pinDetailEscaped) : pinDetailEscaped;
1655
+ // Tool-result images are intentionally omitted here: their URL is built from
1656
+ // the global currentSessionId, but a pin can belong to a different session,
1657
+ // so rendering them would point at the wrong session's image.
1655
1658
  body.innerHTML =
1656
- (fullText ? `<pre class="${TINTED_PRE_CLASS}">${pinDetailRendered}</pre>` : '<em>No details</em>') +
1659
+ (fullText
1660
+ ? `<pre class="${TINTED_PRE_CLASS}">${pinDetailRendered}</pre>`
1661
+ : pinFindings
1662
+ ? ''
1663
+ : '<em>No details</em>') +
1657
1664
  pinParamsHtml +
1658
1665
  pinResultHtml;
1659
1666
  } else if (pin.type === 'agent') {
@@ -1679,6 +1686,17 @@ const linkSvg = (size) =>
1679
1686
  //#endregion
1680
1687
 
1681
1688
  //#region MODALS
1689
+ // Shared markup for an attachment image and the labeled section that holds a grid
1690
+ // of them — used by both user-pasted images and agent tool-result images.
1691
+ function attachImageTag(url, alt) {
1692
+ return `<img src="${url}" loading="lazy" alt="${alt}" class="user-attach-image" />`;
1693
+ }
1694
+ function attachImageSection(label, imgsHtml) {
1695
+ return imgsHtml
1696
+ ? `<div class="user-attach-section"><div class="user-attach-label">${label}</div><div class="user-attach-images">${imgsHtml}</div></div>`
1697
+ : '';
1698
+ }
1699
+
1682
1700
  function renderUserAttachments(m) {
1683
1701
  const parts = [];
1684
1702
  if (m.images?.length && currentSessionId) {
@@ -1687,20 +1705,17 @@ function renderUserAttachments(m) {
1687
1705
  .map((img) => {
1688
1706
  // Cache-kind images live on disk (image-cache/<sessionId>/<n>.png); base64
1689
1707
  // images are read from the JSONL block and need the message uuid.
1690
- let url;
1691
- if (img.kind === 'cache') {
1692
- url = `/api/sessions/${sid}/cached-image/${img.n}`;
1693
- } else if (m.uuid) {
1694
- url = `/api/sessions/${sid}/user-image/${encodeURIComponent(m.uuid)}/${img.blockIndex}`;
1695
- } else {
1696
- return '';
1697
- }
1698
- return `<img src="${url}" loading="lazy" alt="user image" class="user-attach-image" />`;
1708
+ if (img.kind === 'cache') return attachImageTag(`/api/sessions/${sid}/cached-image/${img.n}`, 'user image');
1709
+ if (m.uuid)
1710
+ return attachImageTag(
1711
+ `/api/sessions/${sid}/user-image/${encodeURIComponent(m.uuid)}/${img.blockIndex}`,
1712
+ 'user image',
1713
+ );
1714
+ return '';
1699
1715
  })
1700
1716
  .join('');
1701
- parts.push(
1702
- `<div class="user-attach-section"><div class="user-attach-label">Attached images</div><div class="user-attach-images">${imgs}</div></div>`,
1703
- );
1717
+ const section = attachImageSection('Attached images', imgs);
1718
+ if (section) parts.push(section);
1704
1719
  }
1705
1720
  if (m.toolResultRefs?.length) {
1706
1721
  const refs = m.toolResultRefs
@@ -1761,11 +1776,15 @@ function showMsgDetail(idx) {
1761
1776
  agentBtn.style.display = 'none';
1762
1777
  }
1763
1778
  const sendProto = m.tool === 'SendMessage' && m.params?.protocol;
1764
- const toolParamsHtml = renderToolParamsHtml(
1765
- sendProto ? Object.fromEntries(Object.entries(m.params).filter(([k]) => k !== 'protocol')) : m.params,
1766
- );
1767
- const hideResult = m.tool === 'SendMessage' || TASK_TOOLS.has(m.tool);
1779
+ const isFindings = m.tool === 'ReportFindings';
1780
+ const toolParamsHtml = isFindings
1781
+ ? ''
1782
+ : renderToolParamsHtml(
1783
+ sendProto ? Object.fromEntries(Object.entries(m.params).filter(([k]) => k !== 'protocol')) : m.params,
1784
+ );
1785
+ const hideResult = m.tool === 'SendMessage' || TASK_TOOLS.has(m.tool) || isFindings;
1768
1786
  const taskResultHtml = TASK_TOOLS.has(m.tool) ? renderTaskResult(m.toolResult) : '';
1787
+ const findingsHtml = isFindings ? renderFindingsReport(m.params, m.toolResult) : '';
1769
1788
  const toolResultHtml = hideResult
1770
1789
  ? ''
1771
1790
  : renderToolResultHtml(m.toolResult, m.toolResultTruncated, m.toolResultFull, m.toolUseId);
@@ -1777,8 +1796,8 @@ function showMsgDetail(idx) {
1777
1796
  mainHtml = `${descHtml}<div class="markdown-body">${renderMarkdown(fullText)}</div>`;
1778
1797
  } else if (hasAgentTabs) {
1779
1798
  mainHtml = descHtml || '';
1780
- } else if (taskResultHtml) {
1781
- mainHtml = '';
1799
+ } else if (taskResultHtml || findingsHtml) {
1800
+ mainHtml = descHtml || '';
1782
1801
  } else if (fullText) {
1783
1802
  const detailEscaped = escapeHtml(fullText);
1784
1803
  const detailRendered = m.tool === 'Bash' ? highlightBash(detailEscaped) : detailEscaped;
@@ -1787,8 +1806,16 @@ function showMsgDetail(idx) {
1787
1806
  mainHtml = TASK_TOOLS.has(m.tool) ? '' : '<em>No details</em>';
1788
1807
  }
1789
1808
  const answersHtml = m.answerPayload ? renderAnswerPayloadHtml(m.answerPayload) : '';
1809
+ const toolResultImagesHtml = renderToolResultImagesHtml(m.toolResultImageCount, m.toolUseId);
1790
1810
  body.innerHTML =
1791
- mainHtml + toolParamsHtml + answersHtml + taskResultHtml + (hasAgentTabs ? '' : toolResultHtml) + agentExtraHtml;
1811
+ mainHtml +
1812
+ toolParamsHtml +
1813
+ answersHtml +
1814
+ taskResultHtml +
1815
+ findingsHtml +
1816
+ (hasAgentTabs ? '' : toolResultHtml) +
1817
+ toolResultImagesHtml +
1818
+ agentExtraHtml;
1792
1819
  } else if (m.type === 'teammate') {
1793
1820
  document.getElementById('msg-detail-title').textContent = m.teammateId || 'Teammate';
1794
1821
  document.getElementById('msg-detail-agent-btn').style.display = 'none';
@@ -1978,6 +2005,7 @@ function formatTaskToolDetail(params) {
1978
2005
  }
1979
2006
  function getToolDetail(tool, params, detail) {
1980
2007
  if (TASK_TOOLS.has(tool)) return formatTaskToolDetail(params);
2008
+ if (tool === 'ReportFindings') return formatFindingsToolDetail(params);
1981
2009
  if (!detail) return '';
1982
2010
  let extra = '';
1983
2011
  if (tool === 'Read' && params) {
@@ -2044,6 +2072,66 @@ function renderAnswerPayloadHtml(answerPayload) {
2044
2072
  </div>`;
2045
2073
  }
2046
2074
 
2075
+ //#region FINDINGS
2076
+ const FINDING_VERDICT_COLORS = {
2077
+ CONFIRMED: 'var(--danger, #ef5350)',
2078
+ PLAUSIBLE: 'var(--warning, #f0b429)',
2079
+ };
2080
+ const FINDING_OUTCOME_COLORS = {
2081
+ fixed: 'var(--success, #3ecf8e)',
2082
+ no_change_needed: 'var(--info, #60a5fa)',
2083
+ skipped: 'var(--text-muted)',
2084
+ };
2085
+ function findingBadge(label, color) {
2086
+ return `<span class="finding-badge" style="color:${color}">${escapeHtml(label)}</span>`;
2087
+ }
2088
+ function formatFindingsToolDetail(params) {
2089
+ const findings = Array.isArray(params?.findings) ? params.findings : [];
2090
+ const parts = [
2091
+ `<span style="color:var(--text-secondary)">${findings.length} finding${findings.length === 1 ? '' : 's'}</span>`,
2092
+ ];
2093
+ const confirmed = findings.filter((f) => f && f.verdict === 'CONFIRMED').length;
2094
+ const plausible = findings.filter((f) => f && f.verdict === 'PLAUSIBLE').length;
2095
+ if (confirmed) parts.push(`<span style="color:${FINDING_VERDICT_COLORS.CONFIRMED}">${confirmed} confirmed</span>`);
2096
+ if (plausible) parts.push(`<span style="color:${FINDING_VERDICT_COLORS.PLAUSIBLE}">${plausible} plausible</span>`);
2097
+ if (params?.level) parts.push(findingBadge(params.level, 'var(--text-muted)'));
2098
+ return ` ${parts.join(' <span style="color:var(--text-muted)">·</span> ')}`;
2099
+ }
2100
+ function renderFindingsReport(params, toolResult) {
2101
+ const findings = Array.isArray(params?.findings) ? params.findings : [];
2102
+ let html = '<div class="protocol-detail findings-report">';
2103
+ html += `<span class="protocol-type-badge">${findings.length} finding${findings.length === 1 ? '' : 's'}</span>`;
2104
+ if (params?.level) html += ` ${findingBadge(`level: ${params.level}`, 'var(--text-muted)')}`;
2105
+ if (!findings.length) {
2106
+ html += '<div class="finding-scenario">No findings survived verification.</div>';
2107
+ } else {
2108
+ html += '<div class="findings-list">';
2109
+ findings.forEach((f, i) => {
2110
+ if (!f || typeof f !== 'object') return;
2111
+ const badges = [];
2112
+ if (f.verdict && FINDING_VERDICT_COLORS[f.verdict]) {
2113
+ badges.push(findingBadge(f.verdict, FINDING_VERDICT_COLORS[f.verdict]));
2114
+ }
2115
+ if (f.outcome && FINDING_OUTCOME_COLORS[f.outcome]) {
2116
+ badges.push(findingBadge(f.outcome.replace(/_/g, ' '), FINDING_OUTCOME_COLORS[f.outcome]));
2117
+ }
2118
+ const loc = f.file ? `${f.file}${f.line != null ? `:${f.line}` : ''}` : '';
2119
+ html += `<div class="finding-card">
2120
+ <span class="finding-rank">${i + 1}</span>
2121
+ <div class="finding-main">
2122
+ ${badges.length || loc ? `<div class="finding-badges">${badges.join('')}${loc ? `<span class="finding-file">${escapeHtml(loc)}</span>` : ''}</div>` : ''}
2123
+ ${f.summary ? `<div class="finding-summary">${escapeHtml(f.summary)}</div>` : ''}
2124
+ ${f.failure_scenario ? `<div class="finding-scenario">${escapeHtml(f.failure_scenario)}</div>` : ''}
2125
+ </div>
2126
+ </div>`;
2127
+ });
2128
+ html += '</div>';
2129
+ }
2130
+ if (toolResult) html += `<div class="findings-result-note">${escapeHtml(toolResult.trim())}</div>`;
2131
+ return `${html}</div>`;
2132
+ }
2133
+ //#endregion
2134
+
2047
2135
  function renderToolParamsHtml(params) {
2048
2136
  if (!params) return '';
2049
2137
  const BLOCK_KEYS = new Set(['old_string', 'new_string', 'content', 'contentFull', 'plan']);
@@ -2240,6 +2328,18 @@ function renderToolResultHtml(toolResult, isTruncated, fullResult, toolUseId) {
2240
2328
  </div>`;
2241
2329
  }
2242
2330
 
2331
+ // Render base64 images returned by a tool (e.g. a Read on a .png) so the user
2332
+ // can see what the agent saw, mirroring how user-attached images are shown.
2333
+ function renderToolResultImagesHtml(count, toolUseId) {
2334
+ if (!count || !currentSessionId || !toolUseId) return '';
2335
+ const sid = encodeURIComponent(currentSessionId);
2336
+ const tid = encodeURIComponent(toolUseId);
2337
+ const imgs = Array.from({ length: count }, (_, i) =>
2338
+ attachImageTag(`/api/sessions/${sid}/tool-result-image/${tid}/${i}`, 'tool result image'),
2339
+ ).join('');
2340
+ return attachImageSection('Image output', imgs);
2341
+ }
2342
+
2243
2343
  async function _toggleToolResultExpand(btn) {
2244
2344
  const f = document.getElementById(btn.dataset.expandId);
2245
2345
  if (!f) return;
package/public/style.css CHANGED
@@ -2337,7 +2337,7 @@ body::before {
2337
2337
  z-index: 1;
2338
2338
  line-height: 0;
2339
2339
  }
2340
- .session-item:hover .session-pin-btn:not(.pinned) {
2340
+ .session-item:hover .session-pin-btn:not(.pinned):not(.sticky) {
2341
2341
  opacity: 0.5;
2342
2342
  }
2343
2343
  .session-pin-btn:hover {
@@ -2833,6 +2833,75 @@ body::before {
2833
2833
 
2834
2834
  /* #endregion */
2835
2835
 
2836
+ /* #region FINDINGS */
2837
+ .findings-list {
2838
+ display: flex;
2839
+ flex-direction: column;
2840
+ gap: 8px;
2841
+ margin-top: 8px;
2842
+ }
2843
+ .finding-card {
2844
+ display: flex;
2845
+ gap: 10px;
2846
+ padding: 8px 10px;
2847
+ border: 1px solid var(--border);
2848
+ border-radius: 6px;
2849
+ background: var(--bg-surface);
2850
+ }
2851
+ .finding-rank {
2852
+ color: var(--text-muted);
2853
+ font-weight: 600;
2854
+ font-size: 0.8rem;
2855
+ min-width: 1.6em;
2856
+ text-align: right;
2857
+ line-height: 1.7;
2858
+ }
2859
+ .finding-main {
2860
+ flex: 1;
2861
+ min-width: 0;
2862
+ }
2863
+ .finding-badges {
2864
+ display: flex;
2865
+ flex-wrap: wrap;
2866
+ align-items: baseline;
2867
+ gap: 6px;
2868
+ margin-bottom: 4px;
2869
+ }
2870
+ .finding-badge {
2871
+ display: inline-block;
2872
+ font-size: 0.68rem;
2873
+ font-weight: 700;
2874
+ letter-spacing: 0.04em;
2875
+ text-transform: uppercase;
2876
+ padding: 1px 6px;
2877
+ border-radius: 3px;
2878
+ border: 1px solid currentColor;
2879
+ white-space: nowrap;
2880
+ }
2881
+ .finding-file {
2882
+ font-family: var(--mono);
2883
+ font-size: 0.78rem;
2884
+ color: var(--text-secondary);
2885
+ word-break: break-all;
2886
+ }
2887
+ .finding-summary {
2888
+ font-size: 0.88rem;
2889
+ color: var(--text-primary);
2890
+ margin-bottom: 2px;
2891
+ }
2892
+ .finding-scenario {
2893
+ font-size: 0.8rem;
2894
+ color: var(--text-muted);
2895
+ }
2896
+ .findings-result-note {
2897
+ margin-top: 10px;
2898
+ padding-top: 8px;
2899
+ border-top: 1px solid var(--border);
2900
+ font-size: 0.8rem;
2901
+ color: var(--text-muted);
2902
+ }
2903
+ /* #endregion */
2904
+
2836
2905
  /* #region AGENT_FOOTER */
2837
2906
  .agent-footer {
2838
2907
  display: none;
@@ -4355,7 +4424,8 @@ pre.mermaid svg {
4355
4424
  }
4356
4425
  .session-item.stale:hover,
4357
4426
  .session-item.stale.active,
4358
- .session-item.stale.kb-selected {
4427
+ .session-item.stale.kb-selected,
4428
+ .session-item.stale:has(.session-pin-btn.sticky) {
4359
4429
  opacity: 1;
4360
4430
  }
4361
4431
  .session-item.stale .session-time {
package/server.js CHANGED
@@ -22,6 +22,7 @@ const {
22
22
  extractModelFromTranscript,
23
23
  readFullToolResult,
24
24
  readUserImage,
25
+ readToolResultImage,
25
26
  readCachedImage,
26
27
  updateLoopInfo,
27
28
  buildLoopInfoFromState
@@ -74,6 +75,7 @@ const TASKS_DIR = path.join(CLAUDE_DIR, 'tasks');
74
75
  const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
75
76
  const TEAMS_DIR = path.join(CLAUDE_DIR, 'teams');
76
77
  const PLANS_DIR = path.join(CLAUDE_DIR, 'plans');
78
+ const SESSIONS_DIR = path.join(CLAUDE_DIR, 'sessions');
77
79
  const CCK_DIR = path.join(CLAUDE_DIR, '.cck');
78
80
  const AGENT_ACTIVITY_DIR = path.join(CCK_DIR, 'agent-activity');
79
81
  const CONTEXT_STATUS_DIR = path.join(CCK_DIR, 'context-status');
@@ -231,13 +233,13 @@ function checkAgentStatus(agentDir, stale, logMtime, isTeam) {
231
233
  for (const file of readdirSync(agentDir).filter(f => f.endsWith('.jsonl') && !f.startsWith('_'))) {
232
234
  try {
233
235
  const agent = readAgentJsonl(path.join(agentDir, file));
234
- if (isTeam && isAgentLive(agent)) {
236
+ // Idle agents never mark a session active (an idle teammate lingers and
237
+ // would pin the filter). Teams skip freshness so long-running teammates stay visible.
238
+ if (agent.status === 'active' && (isTeam || isAgentFresh(agent))) {
235
239
  result.hasActive = true;
236
- if (agent.status === 'active') result.hasRunning = true;
237
- } else if (isAgentFresh(agent)) {
238
- if (agent.status === 'active') { result.hasActive = true; result.hasRunning = true; }
240
+ result.hasRunning = true;
239
241
  }
240
- if (result.hasRunning && result.hasActive) break;
242
+ if (result.hasRunning) break;
241
243
  } catch (e) { /* skip invalid */ }
242
244
  }
243
245
  } catch (e) { /* ignore */ }
@@ -284,6 +286,87 @@ function isAutoSelfTeam(cfg) {
284
286
  return namedSession && soleLead;
285
287
  }
286
288
 
289
+ // Claude Code 2.1.x stores a session's tasks in its self-team list (tasks/session-<id>/).
290
+ // Usually `cfg.leadSessionId` is that session and already has a card. But a resumed /
291
+ // continued session keeps writing to the original team's list while running under a new
292
+ // session id, so `leadSessionId` points at the original (often a ghost with no card) and
293
+ // the tasks can't be matched to the live session by id. The on-disk bridge is the
294
+ // live-session registry (~/.claude/sessions/<pid>.json): the team's `createdAt` ≈ the
295
+ // owning session's `startedAt` (both written at boot) and they share a cwd. Match on that.
296
+ const SELF_TEAM_BOOT_WINDOW_MS = 60 * 1000;
297
+ let liveSessionsCache = null;
298
+ let lastLiveSessionsScan = 0;
299
+ const LIVE_SESSIONS_TTL = 5000;
300
+
301
+ function loadLiveSessions() {
302
+ const now = Date.now();
303
+ if (liveSessionsCache && now - lastLiveSessionsScan < LIVE_SESSIONS_TTL) return liveSessionsCache;
304
+ const sessions = [];
305
+ if (existsSync(SESSIONS_DIR)) {
306
+ try {
307
+ for (const file of readdirSync(SESSIONS_DIR).filter(f => f.endsWith('.json'))) {
308
+ try {
309
+ const s = JSON.parse(readFileSync(path.join(SESSIONS_DIR, file), 'utf8'));
310
+ if (s?.sessionId && s.kind === 'interactive') {
311
+ sessions.push({ sessionId: s.sessionId, cwd: s.cwd || null, startedAt: s.startedAt || 0, status: s.status || null });
312
+ }
313
+ } catch (_) { /* skip invalid */ }
314
+ }
315
+ } catch (_) { /* ignore */ }
316
+ }
317
+ liveSessionsCache = sessions;
318
+ lastLiveSessionsScan = now;
319
+ return sessions;
320
+ }
321
+
322
+ // An open-but-idle interactive session keeps touching its JSONL (metadata-line
323
+ // rewrites), so mtime alone reads as activity for as long as the terminal stays
324
+ // open. Claude Code's live-session registry knows the real state — trust its
325
+ // 'idle' over the mtime. No registry entry (or any other status) falls back to
326
+ // the mtime rule.
327
+ function isRegistryIdle(sessionId) {
328
+ const live = loadLiveSessions().find(s => s.sessionId === sessionId);
329
+ return live?.status === 'idle';
330
+ }
331
+
332
+ function hasRecentLogActivity(sessionId, logAge) {
333
+ return logAge <= SESSION_STALE_MS && !isRegistryIdle(sessionId);
334
+ }
335
+
336
+ // Given a self-team config, return the live interactive session id that owns it
337
+ // (same cwd, startedAt within the boot window of the team's createdAt), or null.
338
+ function resolveSelfTeamOwner(cfg) {
339
+ if (!cfg?.createdAt) return null;
340
+ const teamCwd = cfg.members?.[0]?.cwd;
341
+ if (!teamCwd) return null;
342
+ let best = null, bestDelta = Infinity;
343
+ for (const s of loadLiveSessions()) {
344
+ if (s.cwd !== teamCwd) continue;
345
+ const delta = Math.abs(s.startedAt - cfg.createdAt);
346
+ if (delta <= SELF_TEAM_BOOT_WINDOW_MS && delta < bestDelta) {
347
+ best = s.sessionId;
348
+ bestDelta = delta;
349
+ }
350
+ }
351
+ return best;
352
+ }
353
+
354
+ // Attach a team-named task dir's counts to a session card, preferring it over an empty or
355
+ // smaller task dir (a team session can also have a near-empty UUID-named dir). Caller passes
356
+ // the already-computed counts.
357
+ function attachTeamTasks(card, teamTaskDir, teamName, counts) {
358
+ if (!card.tasksDir || counts.taskCount > (card.taskCount || 0)) {
359
+ Object.assign(card, {
360
+ taskCount: counts.taskCount,
361
+ completed: counts.completed,
362
+ inProgress: counts.inProgress,
363
+ pending: counts.pending,
364
+ tasksDir: teamTaskDir,
365
+ sharedTaskList: teamName,
366
+ });
367
+ }
368
+ }
369
+
287
370
  // SSE clients for live updates
288
371
  const clients = new Set();
289
372
 
@@ -381,17 +464,32 @@ function getCustomTaskDir(sessionId) {
381
464
  const dir = path.join(TASKS_DIR, taskListName);
382
465
  if (existsSync(dir)) return dir;
383
466
  }
384
- // Check team-named task directory (teams store tasks under ~/.claude/tasks/<teamName>/)
467
+ // Check team-named task directory (teams store tasks under ~/.claude/tasks/<teamName>/).
468
+ // Match either the recorded leadSessionId, or — for 2.1.x self-teams whose lead is a
469
+ // team-lead agent id — the live interactive session that owns the team (see resolveSelfTeamOwner).
470
+ // A live session can own several team dirs at once — its own (often empty) self-team plus a
471
+ // resumed session's dir holding the real tasks — so pick the richest, mirroring attachTeamTasks'
472
+ // "prefer more tasks" rule. Returning the first match (readdir order) can pick the empty dir,
473
+ // making the board show 0 tasks while the session card counts the other dir.
385
474
  if (existsSync(TEAMS_DIR)) {
386
475
  try {
476
+ let bestDir = null, bestCount = -1;
387
477
  for (const dir of readdirSync(TEAMS_DIR, { withFileTypes: true })) {
388
478
  if (!dir.isDirectory()) continue;
389
479
  const cfg = loadTeamConfig(dir.name);
390
- if (cfg?.leadSessionId === sessionId) {
391
- const teamTaskDir = path.join(TASKS_DIR, dir.name);
392
- if (existsSync(teamTaskDir)) return teamTaskDir;
480
+ if (!cfg) continue;
481
+ const owns = cfg.leadSessionId === sessionId
482
+ || (isAutoSelfTeam(cfg) && resolveSelfTeamOwner(cfg) === sessionId);
483
+ if (!owns) continue;
484
+ const teamTaskDir = path.join(TASKS_DIR, dir.name);
485
+ if (!existsSync(teamTaskDir)) continue;
486
+ const count = getTaskCounts(teamTaskDir).taskCount;
487
+ if (count > bestCount) {
488
+ bestCount = count;
489
+ bestDir = teamTaskDir;
393
490
  }
394
491
  }
492
+ if (bestDir) return bestDir;
395
493
  } catch (_) {}
396
494
  }
397
495
  return null;
@@ -735,7 +833,7 @@ function buildSessionObject(id, meta, overrides = {}) {
735
833
  hasActiveAgents: false,
736
834
  hasRunningAgents: false,
737
835
  hasWaitingForUser: false,
738
- hasRecentLog: logAge <= SESSION_STALE_MS,
836
+ hasRecentLog: hasRecentLogActivity(id, logAge),
739
837
  jsonlPath: meta.jsonlPath || null,
740
838
  tasksDir: null,
741
839
  projectDir: meta.jsonlPath ? path.dirname(meta.jsonlPath) : null,
@@ -793,7 +891,7 @@ app.get('/api/sessions', async (req, res) => {
793
891
  // Cheap-probe: when filter=active, skip expensive enrichment for inactive non-pinned sessions.
794
892
  // Mirrors the post-filter predicate using only signals already computed above.
795
893
  if (activeFilter && !pinnedIds.has(entry.name)) {
796
- const hasRecentLog = logAge <= SESSION_STALE_MS;
894
+ const hasRecentLog = hasRecentLogActivity(entry.name, logAge);
797
895
  const cheaplyActive = logStat.hasMessages && (
798
896
  hasRecentLog
799
897
  || agentStatus.hasActive
@@ -894,7 +992,7 @@ app.get('/api/sessions', async (req, res) => {
894
992
 
895
993
  // Cheap-probe: no tasks here (metadata-only), so active = recent log OR live agent.
896
994
  if (activeFilter && !pinnedIds.has(sessionId)) {
897
- const hasRecentLog = logAge <= SESSION_STALE_MS;
995
+ const hasRecentLog = hasRecentLogActivity(sessionId, logAge);
898
996
  const cheaplyActive = logStat.hasMessages && (
899
997
  hasRecentLog || metaAgentStatus.hasActive || !!metaAgentStatus.waitingForUser
900
998
  );
@@ -949,7 +1047,42 @@ app.get('/api/sessions', async (req, res) => {
949
1047
  // auto-created session-<uuid> self-team dir leaves a duplicate session card whose
950
1048
  // id (session-<uuid>) resolves no messages, so switching to it shows a stale log.
951
1049
  if (sessionsMap.has(dir.name) && dir.name !== leaderId) sessionsMap.delete(dir.name);
952
- if (isAutoSelfTeam(cfg)) continue;
1050
+ if (isAutoSelfTeam(cfg)) {
1051
+ // Self-teams are normally noise with an empty team-named task dir. But 2.1.x stores a
1052
+ // session's tasks in the self-team list (tasks/session-<id>/), so when it's non-empty
1053
+ // the tasks would be silently orphaned. Recover them (gated on taskCount > 0 to keep
1054
+ // the empty-self-team noise case suppressed): attach to the owning card — the recorded
1055
+ // leadSessionId when it has one, else the live session continuing it (resolved from the
1056
+ // session registry), else a freshly-built fallback lead card.
1057
+ const teamTaskDir = path.join(TASKS_DIR, dir.name);
1058
+ if (!existsSync(teamTaskDir)) continue;
1059
+ const counts = getTaskCounts(teamTaskDir);
1060
+ if (counts.taskCount === 0) continue;
1061
+
1062
+ const ownerCard = sessionsMap.get(leaderId) || sessionsMap.get(resolveSelfTeamOwner(cfg));
1063
+ if (ownerCard) {
1064
+ attachTeamTasks(ownerCard, teamTaskDir, dir.name, counts);
1065
+ } else {
1066
+ const meta = metadata[leaderId] || {};
1067
+ const logStat = getSessionLogStat(meta);
1068
+ const logMtime = logStat.mtime;
1069
+ const logAge = logMtime ? Date.now() - logMtime : Infinity;
1070
+ const agentDir = path.join(AGENT_ACTIVITY_DIR, leaderId);
1071
+ const agentStatus = checkAgentStatus(agentDir, logAge > AGENT_STALE_MS, logMtime, false);
1072
+ const taskMtime = counts.newestTaskMtime ? counts.newestTaskMtime.getTime() : 0;
1073
+ const card = buildSessionObject(leaderId, meta, {
1074
+ _logStat: logStat,
1075
+ name: getSessionDisplayName(leaderId, meta) || cfg.name || dir.name,
1076
+ modifiedAt: new Date(Math.max(taskMtime, logMtime || 0)).toISOString(),
1077
+ hasActiveAgents: agentStatus.hasActive,
1078
+ hasRunningAgents: agentStatus.hasRunning,
1079
+ hasWaitingForUser: !!agentStatus.waitingForUser,
1080
+ });
1081
+ attachTeamTasks(card, teamTaskDir, dir.name, counts);
1082
+ sessionsMap.set(leaderId, card);
1083
+ }
1084
+ continue;
1085
+ }
953
1086
  const existing = sessionsMap.get(leaderId);
954
1087
  if (existing) {
955
1088
  existing.isTeam = true;
@@ -963,15 +1096,7 @@ app.get('/api/sessions', async (req, res) => {
963
1096
  // holding the real tasks, the leader card otherwise shows 0/0.
964
1097
  const teamTaskDir = path.join(TASKS_DIR, dir.name);
965
1098
  if (existsSync(teamTaskDir)) {
966
- const counts = getTaskCounts(teamTaskDir);
967
- if (!existing.tasksDir || counts.taskCount > (existing.taskCount || 0)) {
968
- existing.taskCount = counts.taskCount;
969
- existing.completed = counts.completed;
970
- existing.inProgress = counts.inProgress;
971
- existing.pending = counts.pending;
972
- existing.tasksDir = teamTaskDir;
973
- existing.sharedTaskList = dir.name;
974
- }
1099
+ attachTeamTasks(existing, teamTaskDir, dir.name, getTaskCounts(teamTaskDir));
975
1100
  }
976
1101
  // Re-check agent status with isTeam=true
977
1102
  const agentDir = path.join(AGENT_ACTIVITY_DIR, leaderId);
@@ -1827,9 +1952,11 @@ app.get('/api/sessions/:sessionId/messages', (req, res) => {
1827
1952
  compactedMsgs[i].compactSummary = compactSummaries[i].summary;
1828
1953
  }
1829
1954
  }
1955
+ // The client keeps needing toolUseId when it builds a follow-up URL from it:
1956
+ // lazy-fetching a truncated tool result, or fetching each tool-result image.
1957
+ const clientNeedsToolUseId = (msg) => msg.toolResultTruncated || msg.toolResultImageCount;
1830
1958
  for (const msg of messages) {
1831
- // Keep toolUseId on truncated tool results so the client can lazy-fetch the full text
1832
- if (msg.toolUseId && !msg.toolResultTruncated) delete msg.toolUseId;
1959
+ if (msg.toolUseId && !clientNeedsToolUseId(msg)) delete msg.toolUseId;
1833
1960
  delete msg.promptId;
1834
1961
  }
1835
1962
  res.json({ messages, hasMore, sessionId: req.params.sessionId });
@@ -1969,6 +2096,19 @@ app.get('/api/sessions/:sessionId/user-image/:msgUuid/:blockIndex', (req, res) =
1969
2096
  res.end(buf);
1970
2097
  });
1971
2098
 
2099
+ app.get('/api/sessions/:sessionId/tool-result-image/:toolUseId/:n', (req, res) => {
2100
+ const metadata = loadSessionMetadata();
2101
+ const meta = metadata[req.params.sessionId] || metadata[resolveSessionId(req.params.sessionId)];
2102
+ const jsonlPath = meta?.jsonlPath;
2103
+ if (!jsonlPath) return res.status(404).end();
2104
+ const img = readToolResultImage(jsonlPath, req.params.toolUseId, req.params.n);
2105
+ if (!img) return res.status(404).end();
2106
+ const buf = Buffer.from(img.data, 'base64');
2107
+ res.setHeader('Content-Type', img.mediaType);
2108
+ res.setHeader('Cache-Control', 'no-store');
2109
+ res.end(buf);
2110
+ });
2111
+
1972
2112
  app.get('/api/sessions/:sessionId/cached-image/:n', (req, res) => {
1973
2113
  const img = readCachedImage(req.params.sessionId, req.params.n);
1974
2114
  if (!img) return res.status(404).end();