claude-code-kanban 7.31.0 → 7.33.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/public/index.html CHANGED
@@ -82,6 +82,19 @@
82
82
  <span class="section-header-label">Sessions</span>
83
83
  <span id="filter-summary" class="filter-summary" title=""></span>
84
84
  <span class="section-header-actions">
85
+ <button
86
+ id="home-btn"
87
+ class="icon-btn section-btn"
88
+ onclick="event.stopPropagation(); goHome()"
89
+ title="Home: close the session (H)"
90
+ aria-label="Home: close the session"
91
+ >
92
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
93
+ <path d="M3 11l9-8 9 8"/>
94
+ <path d="M5 10v10h14V10"/>
95
+ <path d="M10 20v-6h4v6"/>
96
+ </svg>
97
+ </button>
85
98
  <button
86
99
  id="zen-mode-btn"
87
100
  class="icon-btn section-btn"
@@ -227,8 +240,9 @@
227
240
  <div class="idle-clawd" data-hub-part="idle-mascot" aria-hidden="true">
228
241
  <svg class="clawd" viewBox="1 0 16 10" shape-rendering="crispEdges"><use href="#clawd-shape"/></svg>
229
242
  </div>
230
- <p class="idle-title">Select a session to view tasks</p>
231
- <div class="idle-hint sp-hint"><kbd>↑</kbd><kbd>↓</kbd> move <span>·</span> <kbd>Enter</kbd> open <span>·</span> <kbd>?</kbd> shortcuts</div>
243
+ <p class="idle-title">No session open</p>
244
+ <div id="home-keys" class="home-keys"></div>
245
+ <div class="idle-hint sp-hint"><kbd>↑</kbd><kbd>↓</kbd> move <span>·</span> <kbd>Enter</kbd> open</div>
232
246
  </div>
233
247
  </div>
234
248
 
@@ -1002,7 +1016,8 @@
1002
1016
  <div id="session-picker-list" class="sp-list"></div>
1003
1017
  <div id="session-picker-peek" class="sp-peek"></div>
1004
1018
  </div>
1005
- <div class="sp-hint"><kbd>&uarr;</kbd><kbd>&darr;</kbd> move &middot; <kbd>Enter</kbd> open &middot; <kbd>Tab</kbd> board / all &middot; <kbd>Ctrl</kbd><kbd>Space</kbd> peek &middot; <kbd>Esc</kbd> close</div>
1019
+ <div class="sp-hint sp-hint-sessions"><kbd>&uarr;</kbd><kbd>&darr;</kbd> move &middot; <kbd>Enter</kbd> open &middot; <kbd>Tab</kbd> board / all &middot; <kbd>Ctrl</kbd><kbd>Space</kbd> peek &middot; <kbd>&gt;</kbd> commands &middot; <kbd>Esc</kbd> close</div>
1020
+ <div class="sp-hint sp-hint-commands"><kbd>&uarr;</kbd><kbd>&darr;</kbd> move &middot; <kbd>Enter</kbd> run &middot; <kbd>Backspace</kbd> on <kbd>&gt;</kbd> back to sessions &middot; <kbd>Esc</kbd> close</div>
1006
1021
  </div>
1007
1022
  </div>
1008
1023
 
package/public/style.css CHANGED
@@ -163,11 +163,6 @@ body::before {
163
163
  flex-shrink: 0;
164
164
  position: relative;
165
165
  overflow: hidden;
166
- transition: width 0.25s cubic-bezier(0.4, 0, 0.2, 1);
167
- }
168
-
169
- .sidebar.resizing {
170
- transition: none;
171
166
  }
172
167
 
173
168
  .sidebar-header {
@@ -345,7 +340,6 @@ body::before {
345
340
  .sidebar-toggle-btn svg {
346
341
  width: 16px;
347
342
  height: 16px;
348
- transition: transform 0.25s ease;
349
343
  }
350
344
 
351
345
  .sidebar.collapsed .sidebar-toggle-btn svg {
@@ -1689,19 +1683,33 @@ body.booting .boot-splash {
1689
1683
  /* #endregion */
1690
1684
 
1691
1685
  .sidebar-footer .footer-plugin-warning {
1692
- padding: 0;
1693
- border: none;
1694
- background: none;
1686
+ display: inline-flex;
1687
+ align-items: center;
1688
+ gap: 3px;
1689
+ padding: 2px 7px 2px 5px;
1690
+ border: 1px solid color-mix(in srgb, var(--warning) 35%, transparent);
1691
+ border-radius: 999px;
1692
+ background: var(--warning-dim);
1695
1693
  font: inherit;
1696
- font-size: 11px;
1694
+ font-size: 10.5px;
1697
1695
  line-height: 1;
1698
1696
  color: var(--warning);
1699
1697
  cursor: pointer;
1700
1698
  }
1701
1699
 
1702
- .sidebar-footer .footer-plugin-warning:hover,
1700
+ .sidebar-footer .footer-plugin-warning svg {
1701
+ width: 11px;
1702
+ height: 11px;
1703
+ flex-shrink: 0;
1704
+ }
1705
+
1706
+ .sidebar-footer .footer-plugin-warning[data-state='disabled'] {
1707
+ cursor: default;
1708
+ }
1709
+
1710
+ .sidebar-footer .footer-plugin-warning:not([data-state='disabled']):hover,
1703
1711
  .sidebar-footer .footer-plugin-warning:focus-visible {
1704
- filter: brightness(1.2);
1712
+ background: color-mix(in srgb, var(--warning) 28%, transparent);
1705
1713
  }
1706
1714
 
1707
1715
  .sidebar.collapsed {
@@ -1874,6 +1882,50 @@ body.booting .boot-splash {
1874
1882
  opacity: 0.5;
1875
1883
  }
1876
1884
 
1885
+ .home-keys {
1886
+ display: grid;
1887
+ gap: 2px;
1888
+ width: min(420px, 90%);
1889
+ margin: 6px 0 4px;
1890
+ }
1891
+
1892
+ .home-key {
1893
+ display: flex;
1894
+ align-items: center;
1895
+ justify-content: space-between;
1896
+ gap: 16px;
1897
+ padding: 6px 10px;
1898
+ border: none;
1899
+ border-radius: 6px;
1900
+ background: none;
1901
+ color: var(--text-secondary);
1902
+ font: inherit;
1903
+ font-size: 13px;
1904
+ text-align: left;
1905
+ white-space: nowrap;
1906
+ cursor: pointer;
1907
+ }
1908
+
1909
+ .home-key:hover,
1910
+ .home-key:focus-visible {
1911
+ background: var(--bg-hover);
1912
+ color: var(--text-primary);
1913
+ }
1914
+
1915
+ /* keycaps share --bg-hover with the active row; lift them so they stay visible */
1916
+ .home-key:hover kbd,
1917
+ .home-key:focus-visible kbd {
1918
+ background: var(--bg-elevated);
1919
+ }
1920
+
1921
+ .home-key-kbd {
1922
+ display: inline-flex;
1923
+ align-items: center;
1924
+ gap: 3px;
1925
+ color: var(--text-muted);
1926
+ font-size: 11px;
1927
+ }
1928
+
1877
1929
  @media (prefers-reduced-motion: reduce) {
1878
1930
  .idle-glow span,
1879
1931
  .idle-clawd .clawd,
@@ -9161,6 +9213,8 @@ body.light .msg-assistant .msg-text {
9161
9213
 
9162
9214
  /* keycap chips: elevated fill + thicker bottom border reads as a key */
9163
9215
  .sp-hint kbd,
9216
+ .sp-keys kbd,
9217
+ .home-keys kbd,
9164
9218
  .shortcuts kbd,
9165
9219
  .terminal-boot-slow kbd,
9166
9220
  .review-offer-btn kbd {
@@ -9187,7 +9241,11 @@ body.light .msg-assistant .msg-text {
9187
9241
  }
9188
9242
 
9189
9243
  .shortcuts .sc-plus,
9190
- .shortcuts .sc-or {
9244
+ .shortcuts .sc-or,
9245
+ .home-keys .sc-plus,
9246
+ .home-keys .sc-or,
9247
+ .sp-keys .sc-plus,
9248
+ .sp-keys .sc-or {
9191
9249
  color: var(--text-muted);
9192
9250
  font-size: 11px;
9193
9251
  }
@@ -9948,6 +10006,32 @@ select.form-input option:checked {
9948
10006
  font-size: 11px;
9949
10007
  }
9950
10008
 
10009
+ .modal.session-picker.commands .sp-scope,
10010
+ .modal.session-picker.commands .sp-peek,
10011
+ .modal.session-picker.commands .sp-hint-sessions,
10012
+ .modal.session-picker:not(.commands) .sp-hint-commands {
10013
+ display: none;
10014
+ }
10015
+
10016
+ .sp-target {
10017
+ padding: 2px 8px 4px;
10018
+ color: var(--text-muted);
10019
+ font-family: var(--mono);
10020
+ font-size: 11.5px;
10021
+ }
10022
+
10023
+ .sp-keys {
10024
+ margin-left: auto;
10025
+ display: flex;
10026
+ align-items: center;
10027
+ gap: 3px;
10028
+ }
10029
+
10030
+ .sp-target b {
10031
+ color: var(--text-primary);
10032
+ font-weight: 500;
10033
+ }
10034
+
9951
10035
  .pp-chips {
9952
10036
  display: flex;
9953
10037
  gap: 6px;
@@ -10122,16 +10206,6 @@ select.form-input option:checked {
10122
10206
  color: var(--text-muted);
10123
10207
  }
10124
10208
 
10125
- .ns-empty {
10126
- display: flex;
10127
- align-items: center;
10128
- justify-content: space-between;
10129
- gap: 8px;
10130
- padding: 6px 8px;
10131
- font-size: 12px;
10132
- color: var(--text-muted);
10133
- }
10134
-
10135
10209
  .ns-check {
10136
10210
  display: inline-flex;
10137
10211
  flex: none;
@@ -123,12 +123,52 @@
123
123
  term.refresh(0, term.rows - 1);
124
124
  }
125
125
 
126
+ // A resize clears the WebGL canvas, and xterm 6 draws it again only on the next animation frame,
127
+ // so the terminal shows one blank frame. Its private _renderRows draws in this frame instead.
128
+ function paintNow() {
129
+ const rs = state.term?._core?._renderService;
130
+ if (typeof rs?._renderRows !== 'function') return;
131
+ try {
132
+ rs._renderRows(0, state.term.rows - 1);
133
+ } catch (_) {}
134
+ }
135
+
136
+ // ConPTY drops DEC 2026, so the app's redraw after a resize lands over several frames and shows
137
+ // as a sweep. Turning the mode on locally keeps the old screen until the output goes quiet.
138
+ const HOLD_CAP_MS = 250;
139
+ const HOLD_QUIET_MS = 40;
140
+ const hold = { cap: 0, quiet: 0 };
141
+
142
+ function holdForRedraw() {
143
+ if (!state.attached || !state.holdRedraw || hold.cap) return;
144
+ state.term.write('\x1b[?2026h');
145
+ hold.cap = win.setTimeout(releaseHold, HOLD_CAP_MS);
146
+ }
147
+
148
+ function releaseHold() {
149
+ win.clearTimeout(hold.cap);
150
+ win.clearTimeout(hold.quiet);
151
+ hold.cap = 0;
152
+ hold.quiet = 0;
153
+ state.term.write('\x1b[?2026l');
154
+ }
155
+
156
+ function noteOutput() {
157
+ if (!hold.cap) return;
158
+ win.clearTimeout(hold.quiet);
159
+ hold.quiet = win.setTimeout(releaseHold, HOLD_QUIET_MS);
160
+ }
161
+
126
162
  // The fit addon measures 0×0 while the board's pane (or the hub's iframe) is display:none.
127
163
  function fit() {
128
164
  if (!state.fit || !host.offsetWidth || !host.offsetHeight) return;
165
+ const { cols, rows } = state.term;
129
166
  try {
130
167
  state.fit.fit();
131
168
  } catch (_) {}
169
+ if (state.term.cols === cols && state.term.rows === rows) return false;
170
+ paintNow();
171
+ return true;
132
172
  }
133
173
 
134
174
  function setBg(options) {
@@ -144,7 +184,7 @@
144
184
  function applyFont(size) {
145
185
  const term = state.term;
146
186
  term.options.fontSize = size;
147
- fit();
187
+ if (!fit()) paintNow();
148
188
  doc.fonts
149
189
  ?.load(`${size}px ${term.options.fontFamily}`)
150
190
  .then(repaint)
@@ -253,7 +293,10 @@
253
293
  });
254
294
  }
255
295
  term.onData((d) => send({ t: 'in', d }));
256
- term.onResize(({ cols, rows }) => send({ t: 'resize', cols, rows }));
296
+ term.onResize(({ cols, rows }) => {
297
+ send({ t: 'resize', cols, rows });
298
+ holdForRedraw();
299
+ });
257
300
  // One fit per frame while a drag resizes the pane. The atlas is rebuilt only when the frame comes
258
301
  // back from 0×0, which is also how a hidden hub iframe or pane shows again.
259
302
  let frame = 0;
@@ -336,6 +379,7 @@
336
379
  const bytes = new Uint8Array(ev.data);
337
380
  term.write(bytes, () => {
338
381
  ack(ws, bytes.length);
382
+ noteOutput();
339
383
  if (!outputSent && state.ws === ws && tailOf(term.buffer.active, 1)) {
340
384
  outputSent = true;
341
385
  up('output', { socketId });
@@ -351,6 +395,7 @@
351
395
  }
352
396
  if (msg.t === 'ready') {
353
397
  state.attached = true;
398
+ state.holdRedraw = !!msg.holdRedraw;
354
399
  // A retry keeps the last screen until the replay arrives.
355
400
  if (!reset) clearScreen();
356
401
  send({ t: 'resize', cols: term.cols, rows: term.rows });
@@ -1,4 +1,4 @@
1
- // claude-hub-sdk 1.11.0 (sha256 841f6c771631). Copied by npm run sdk:sync in claude-code-hub. Do not edit.
1
+ // claude-hub-sdk 1.12.0 (sha256 6fb679e4d801). Copied by npm run sdk:sync in claude-code-hub. Do not edit.
2
2
  // Claude Code Hub SDK: the one rule that names a key press, shared by the hub page, client.js and
3
3
  // stub.js. The hub serves it to its page as /sdk/keys.js; mount() and sdk:sync put it in front of
4
4
  // client.js and stub.js, so an app still loads one file.
@@ -10,19 +10,62 @@ var ClaudeHubKeys = (() => {
10
10
  // Modifiers in ctrl, alt, shift, meta order, joined by '+' to the key. macOS composes
11
11
  // Option+<key> into a character (Option+1 is '¡', Option+P is 'π') and holding Control does not
12
12
  // undo it, so e.key alone cannot name these presses there. e.code is the physical key, which is
13
- // wrong for non-US layouts, hence only as a fallback. No fallback under AltGraph: Chromium sets it
14
- // when AltGr types a character, and that press is text. Takes a real KeyboardEvent or a forwarded
15
- // {key, code} payload; a payload without code degrades to key. A payload needs no AltGraph: the
16
- // SDK forwards only a press whose key already names a bound combo.
17
- // Self-contained on purpose: cck puts its source text into a sandboxed frame.
13
+ // wrong for non-US layouts, hence only as a fallback. A letter or punctuation key falls back to its
14
+ // US character only when e.key is not ASCII (a non-Latin layout, or Option on macOS), so AZERTY's
15
+ // ',' on the M key stays ','. The digit row always falls back, so AZERTY's '&' key is 1, as Windows
16
+ // and VS Code treat it. No fallback under AltGraph: Chromium sets it when AltGr types a character, and that
17
+ // press is text. Takes a real KeyboardEvent or a forwarded {key, code} payload; a payload without
18
+ // code degrades to key. A payload needs no AltGraph: the SDK forwards only a press whose key
19
+ // already names a bound combo.
20
+ // Self-contained on purpose, the table too: cck puts its source text into a sandboxed frame.
21
+ // codeOf() lists the same keys the other way round.
18
22
  function comboOf(e) {
19
- const lower = typeof e.key === 'string' ? e.key.toLowerCase() : '';
20
- const m = !e.getModifierState?.('AltGraph') && /^(?:Key|Digit)([A-Z1-9])$/.exec(e.code || '');
21
- const key = /^[a-z1-9]$/.test(lower) ? lower : m ? m[1].toLowerCase() : e.key === ' ' ? 'Space' : e.key;
23
+ const raw = typeof e.key === 'string' ? e.key : '';
24
+ const lower = raw.toLowerCase();
25
+ const code = e.getModifierState?.('AltGraph') ? '' : e.code || '';
26
+ const latin = !/[^\x20-\x7e]/.test(raw);
27
+ const digit = /^Digit([0-9])$/.exec(code)?.[1];
28
+ const us =
29
+ !latin &&
30
+ (/^Key([A-Z])$/.exec(code)?.[1].toLowerCase() ||
31
+ {
32
+ Minus: '-',
33
+ Equal: '=',
34
+ BracketLeft: '[',
35
+ BracketRight: ']',
36
+ Backslash: '\\',
37
+ Semicolon: ';',
38
+ Quote: "'",
39
+ Backquote: '`',
40
+ Comma: ',',
41
+ Period: '.',
42
+ Slash: '/',
43
+ }[code]);
44
+ const key = /^[a-z0-9]$/.test(lower) ? lower : digit || us || (e.key === ' ' ? 'Space' : e.key);
22
45
  const mods = [e.ctrlKey && 'ctrl', e.altKey && 'alt', e.shiftKey && 'shift', e.metaKey && 'meta'];
23
46
  return [...mods, key].filter(Boolean).join('+');
24
47
  }
25
48
 
49
+ // The physical key (e.code) that types a combo's key on a US layout, or null for a named key.
50
+ function codeOf(key) {
51
+ if (/^[a-z]$/.test(key)) return `Key${key.toUpperCase()}`;
52
+ if (/^[0-9]$/.test(key)) return `Digit${key}`;
53
+ const codes = {
54
+ '-': 'Minus',
55
+ '=': 'Equal',
56
+ '[': 'BracketLeft',
57
+ ']': 'BracketRight',
58
+ '\\': 'Backslash',
59
+ ';': 'Semicolon',
60
+ "'": 'Quote',
61
+ '`': 'Backquote',
62
+ ',': 'Comma',
63
+ '.': 'Period',
64
+ '/': 'Slash',
65
+ };
66
+ return codes[key] ?? null;
67
+ }
68
+
26
69
  // The keys of a combo as a help row shows them: ['Ctrl', 'Alt', 'P'], or ['⌃', '⌥', 'P'] on macOS.
27
70
  // The {n} of a numbered combo reads 1…9.
28
71
  function keyParts(combo, mac) {
@@ -47,7 +90,7 @@ var ClaudeHubKeys = (() => {
47
90
  ].filter(Boolean);
48
91
  }
49
92
 
50
- return { comboOf, keyParts, keySigs };
93
+ return { comboOf, codeOf, keyParts, keySigs };
51
94
  })();
52
95
 
53
96
  if (typeof module === 'object' && module.exports) module.exports = ClaudeHubKeys;
@@ -93,6 +136,7 @@ if (typeof module === 'object' && module.exports) module.exports = ClaudeHubKeys
93
136
  can: (action) => !!standaloneFn(action),
94
137
  forwards: () => false,
95
138
  forwardCombos: () => [],
139
+ onKeys: () => off,
96
140
  keyLabel: () => null,
97
141
  voiceCommands: () => [],
98
142
  closeGuard() {},
package/server.js CHANGED
@@ -43,7 +43,6 @@ const {
43
43
  readCompactSummaries,
44
44
  fillCompactSummaries,
45
45
  readArtifactLinks,
46
- readScratchpadCreations,
47
46
  extractPromptFromTranscript,
48
47
  extractModelFromTranscript,
49
48
  readSubagentMeta,
@@ -77,7 +76,6 @@ const { createDispatchedStore, scanTranscripts, pruneSessionDirs, pruneContextSt
77
76
  const { freshRateLimits } = require('./lib/rate-limits');
78
77
  const { createWorktreeStore } = require('./lib/worktrees');
79
78
  const { createScratchpadDirResolver, scratchpadRoot } = require('./lib/scratchpad-dir');
80
- const { createScratchServers } = require('./lib/scratch-servers');
81
79
  const { readSettings } = require('./lib/claude-settings');
82
80
  const { readGitBranch, sessionGitBranch } = require('./lib/git-branch');
83
81
  const { createLinkedDocStore, linkUrl } = require('./lib/linked-docs');
@@ -1901,108 +1899,9 @@ app.get('/api/sessions/:sessionId/artifacts', async (req, res) => {
1901
1899
 
1902
1900
  // A scratchpad is a folder plus a `scratchpad.json` manifest, rendered by the
1903
1901
  // external `scratch` CLI. cck only recognizes the shape and launches the viewer —
1904
- // it reads nothing from the manifest but `name`, `created` and `id`, so the two stay
1905
- // independently versioned.
1902
+ // it reads nothing from the manifest, so the two stay independently versioned.
1906
1903
  const SCRATCHPAD_MANIFEST = 'scratchpad.json';
1907
1904
 
1908
- // Fallback only, for a `scratch new` whose output the transcript never captured. A pad
1909
- // has no central registry — the CLI treats the folder path as the pad's identity and
1910
- // finds pads by scanning — and `_scratchpads/` is one user's habit, not a convention it
1911
- // knows, so there is no layout to guess. Depth 3 rather than a deeper walk for the
1912
- // reason docs/session-scanning.md records: pruned, it measures 0-3 ms on the worst-case
1913
- // project dirs, while an unpruned walk of the same dirs costs ~800 ms.
1914
- const PAD_SCAN_IGNORE = new Set(['node_modules', '.git', '.hg', '.svn', 'dist', 'build']);
1915
- const PAD_SCAN_MAX_DEPTH = 3;
1916
- // A pad manifest's `created` is written after the tool call starts, so the match is
1917
- // a window, not an instant. Measured lag on a real `scratch new` was 4.1 s; the
1918
- // window is wide enough to survive a slow disk and far too narrow to reach a pad
1919
- // made in an earlier session.
1920
- const PAD_CREATE_WINDOW_MS = 120000;
1921
-
1922
- async function findPads(root, depth = 0) {
1923
- let entries;
1924
- try { entries = await fs.readdir(root, { withFileTypes: true }); } catch (_) { return []; }
1925
- // A pad is never nested inside another pad, so a manifest ends the descent.
1926
- if (entries.some((e) => e.isFile() && e.name === SCRATCHPAD_MANIFEST)) return [root];
1927
- if (depth >= PAD_SCAN_MAX_DEPTH) return [];
1928
- const nested = await Promise.all(
1929
- entries
1930
- .filter((e) => e.isDirectory() && !PAD_SCAN_IGNORE.has(e.name))
1931
- .map((e) => findPads(path.join(root, e.name), depth + 1)),
1932
- );
1933
- return nested.flat();
1934
- }
1935
-
1936
- // The pads a session made, as linked-doc rows. Derived on every read rather than
1937
- // stored, so re-reading a transcript cannot drift; the client links each pad once
1938
- // and records that it did, which is what stops a re-read undoing an unlink.
1939
- async function readCreatedPads(meta) {
1940
- const creations = await readScratchpadCreations(meta.jsonlPath);
1941
- // No `scratch new` in the transcript means no disk work at all, so sessions that
1942
- // never touch the CLI pay a substring pass over the transcript and nothing more.
1943
- if (!creations.length) return [];
1944
- const reported = new Set(creations.filter((c) => c.path).map((c) => c.path));
1945
- const unresolved = creations.filter((c) => !c.path);
1946
- const askedFor = new Set(unresolved.map((c) => c.name).filter(Boolean));
1947
- // Only a call whose name could not be read falls back to the clock, and it compares
1948
- // against the call's second, not the call: the manifest records `created` to the
1949
- // second while the transcript timestamps to the millisecond, so a pad written during
1950
- // the same second as its own command otherwise reads as older than it.
1951
- const byClock = unresolved.filter((c) => !c.name).map((c) => Math.floor(c.ts / 1000) * 1000);
1952
- const sessionId = path.basename(meta.jsonlPath, '.jsonl');
1953
- // The project, not `meta.cwd`: cwd is wherever the session last stood, which drifts
1954
- // into subdirectories — a session that made a pad and then worked inside it reports
1955
- // a cwd below the pad, and a scan from there finds nothing above it.
1956
- // The session's own scratchpad dir too: a pad made there sits outside the project.
1957
- const roots = unresolved.length ? [meta.project || meta.cwd, getScratchpadDir(sessionId, meta)] : [];
1958
- const scanned = (await Promise.all(roots.filter(Boolean).map((r) => findPads(r)))).flat();
1959
- const candidates = [...new Set([...reported, ...scanned.map((dir) => path.join(dir, SCRATCHPAD_MANIFEST))])];
1960
- const rows = await Promise.all(
1961
- candidates.map(async (file) => {
1962
- let manifest;
1963
- try { manifest = JSON.parse(await fs.readFile(file, 'utf8')); } catch (_) { return null; }
1964
- const created = Date.parse(manifest?.created);
1965
- if (!Number.isFinite(created)) return null;
1966
- const name = manifest.name || path.basename(path.dirname(file));
1967
- // A path the CLI printed names its pad outright. Otherwise `scratch new --id`
1968
- // settles it: the flag stamps the session that asked for the pad into the
1969
- // manifest, so an id decides ownership both ways — one naming another session
1970
- // disowns the pad whatever the name or the clock say. Only a pad with no id is
1971
- // guessed at, by the name the command asked for and then by the clock.
1972
- const claimed =
1973
- reported.has(file) ||
1974
- (manifest.id
1975
- ? manifest.id === sessionId
1976
- : askedFor.has(name) || byClock.some((from) => created >= from && created - from <= PAD_CREATE_WINDOW_MS));
1977
- if (!claimed) return null;
1978
- return { path: file, name, created: manifest.created, ts: created };
1979
- }),
1980
- );
1981
- return rows
1982
- .filter(Boolean)
1983
- .sort((a, b) => a.ts - b.ts)
1984
- .map(({ ts: _ts, ...row }) => row);
1985
- }
1986
-
1987
- // Cold path — a full transcript scan, and a directory walk when the transcript did not
1988
- // carry the pad paths, so the result is held until the transcript grows.
1989
- const padsByPath = new Map();
1990
-
1991
- function getCreatedPads(meta) {
1992
- return cachedByFileStat(padsByPath, meta.jsonlPath, () => readCreatedPads(meta)) || [];
1993
- }
1994
-
1995
- app.get('/api/sessions/:sessionId/pads', async (req, res) => {
1996
- try {
1997
- const meta = sessionMetaFor(req.params.sessionId);
1998
- if (!meta?.jsonlPath) return res.json({ pads: [] });
1999
- res.json({ pads: await getCreatedPads(meta) });
2000
- } catch (error) {
2001
- console.error('Error reading created pads:', error);
2002
- res.status(500).json({ error: 'Failed to read created pads' });
2003
- }
2004
- });
2005
-
2006
1905
  // API: List one level of a session's scratchpad dir — the root, or the folder named by
2007
1906
  // `?path=`, which is the absolute path a previous listing handed out and must still sit
2008
1907
  // under the root. One readdir per request, never a walk: sessions drop clones and
@@ -2404,23 +2303,6 @@ function scratchExecutable() {
2404
2303
  return file ? { file } : { error: 'scratch CLI cannot be launched without a shell' };
2405
2304
  }
2406
2305
 
2407
- const scratchServers = createScratchServers({
2408
- resolveBin: () => scratchExecutable().file || null,
2409
- spawn,
2410
- onExit: (pad) => broadcast({ type: 'scratchpad:exited', manifest: `${pad}/${SCRATCHPAD_MANIFEST}` }),
2411
- });
2412
-
2413
- // API: The URL of a pad's browser viewer for a scratchpad pane, started on first use.
2414
- app.post('/api/scratchpad/serve', async (req, res) => {
2415
- try {
2416
- res.json({ url: await scratchServers.serve(resolveScratchpad(req.body?.path).dir) });
2417
- } catch (error) {
2418
- if (error.status) return res.status(error.status).json({ error: error.message });
2419
- console.error('Error serving scratchpad:', error.message);
2420
- res.status(502).json({ error: error.message });
2421
- }
2422
- });
2423
-
2424
2306
  // API: Open a scratchpad in the external `scratch` viewer — the window outlives
2425
2307
  // this request and cck never waits on it.
2426
2308
  app.post('/api/scratchpad/open', (req, res) => {
@@ -1,119 +0,0 @@
1
- // One `scratch ui --json` browser viewer per pad, for scratchpad panes. Each child holds a pipe on
2
- // its stdin that cck never writes to: when cck exits, the pipe closes and the viewer exits with it.
3
-
4
- const path = require('node:path');
5
- const { canonicalPath } = require('./linked-docs');
6
-
7
- const READY_TIMEOUT_MS = 15000;
8
- const HEALTH_TIMEOUT_MS = 1500;
9
-
10
- /**
11
- * @param {object} o
12
- * @param {() => string|null} o.resolveBin the `scratch` executable, or null when it cannot be launched
13
- * @param {(file: string, args: string[], opts: object) => import('node:child_process').ChildProcess} o.spawn
14
- * @param {(pad: string) => void} [o.onExit] the canonical pad dir of a viewer that exited
15
- */
16
- function createScratchServers({ resolveBin, spawn, fetch = globalThis.fetch, onExit = () => {}, max = 4, readyTimeoutMs = READY_TIMEOUT_MS }) {
17
- // Map order is recency: the first entry is the one stopped when a new pad needs room.
18
- const live = new Map();
19
- const starting = new Map();
20
-
21
- function stop(key) {
22
- const entry = live.get(key);
23
- if (!entry) return;
24
- live.delete(key);
25
- entry.child.kill();
26
- }
27
-
28
- async function healthy(entry, key) {
29
- try {
30
- const res = await fetch(new URL(`/__scratch/health${new URL(entry.url).search}`, entry.url), {
31
- signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
32
- });
33
- if (!res.ok) return false;
34
- const { pid, pads } = await res.json();
35
- return pid === entry.pid && Array.isArray(pads) && pads.some((p) => canonicalPath(p) === key);
36
- } catch {
37
- return false;
38
- }
39
- }
40
-
41
- async function start(dir, key) {
42
- const file = resolveBin();
43
- if (!file) {
44
- const err = new Error('scratch CLI not found on PATH');
45
- err.status = 501;
46
- throw err;
47
- }
48
- // No `detached`: on Windows it overrides `windowsHide` and the bun shim opens a console window.
49
- const child = spawn(file, ['ui', path.basename(dir), '--dir', path.dirname(dir), '--json'], {
50
- stdio: ['pipe', 'pipe', 'pipe'],
51
- windowsHide: true,
52
- });
53
- child.stdin.on('error', () => {});
54
- let stderr = '';
55
- child.stderr.on('data', (b) => {
56
- stderr = (stderr + b).slice(-2000);
57
- });
58
- return new Promise((resolve, reject) => {
59
- let buf = '';
60
- let entry = null;
61
- const fail = (msg) => {
62
- clearTimeout(timer);
63
- child.kill();
64
- reject(new Error(`${msg}${stderr.trim() ? `: ${stderr.trim().split('\n').pop()}` : ''}`));
65
- };
66
- const timer = setTimeout(() => fail('scratch viewer did not start'), readyTimeoutMs);
67
- // Read stdout to the end, so a chatty viewer never fills the pipe and blocks.
68
- child.stdout.on('data', (b) => {
69
- if (entry) return;
70
- buf += b;
71
- const nl = buf.indexOf('\n');
72
- if (nl < 0) return;
73
- clearTimeout(timer);
74
- try {
75
- const ready = JSON.parse(buf.slice(0, nl));
76
- entry = { child, url: ready.url, pid: ready.pid };
77
- } catch {
78
- fail('scratch viewer printed no ready line (needs scratch with `ui --json`)');
79
- return;
80
- }
81
- buf = '';
82
- while (live.size >= max) stop(live.keys().next().value);
83
- live.set(key, entry);
84
- resolve(entry);
85
- });
86
- child.on('error', (e) => fail(`scratch viewer failed to start (${e.message})`));
87
- child.on('exit', (code) => {
88
- if (!entry) {
89
- fail(`scratch viewer exited (${code})`);
90
- return;
91
- }
92
- if (live.get(key) === entry) live.delete(key);
93
- onExit(key);
94
- });
95
- child.unref();
96
- child.stdin.unref?.();
97
- child.stdout.unref?.();
98
- child.stderr.unref?.();
99
- });
100
- }
101
-
102
- /** The viewer URL for the pad at `dir`, started when no live one answers for it. */
103
- async function serve(dir) {
104
- const key = canonicalPath(dir);
105
- const entry = live.get(key);
106
- if (entry && (await healthy(entry, key))) {
107
- live.delete(key);
108
- live.set(key, entry);
109
- return entry.url;
110
- }
111
- if (entry) stop(key);
112
- if (!starting.has(key)) starting.set(key, start(dir, key).finally(() => starting.delete(key)));
113
- return (await starting.get(key)).url;
114
- }
115
-
116
- return { serve, size: () => live.size };
117
- }
118
-
119
- module.exports = { createScratchServers };