claude-code-kanban 7.32.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/cli.js +12 -2
- package/lib/parsers.js +0 -43
- package/lib/terminal.js +2 -1
- package/package.json +1 -1
- package/plugin/plugins/claude-code-kanban/.claude-plugin/plugin.json +1 -1
- package/plugin/plugins/claude-code-kanban/skills/kanban/SKILL.md +4 -0
- package/public/app.js +69 -90
- package/public/style.css +6 -6
- package/public/terminal-frame.js +47 -2
- package/server.js +1 -119
- package/lib/scratch-servers.js +0 -119
package/cli.js
CHANGED
|
@@ -68,7 +68,7 @@ const COMMANDS = {
|
|
|
68
68
|
summary: 'Add a pane to a session; it opens as a tab next to Board, in the background',
|
|
69
69
|
usage: 'claude-code-kanban pane add <url|file> | --shell [<folder>] [--run <cmd>] [--title <text>] [--session <id>] [--json]',
|
|
70
70
|
flags: {
|
|
71
|
-
'<url|file>': 'An http(s) URL,
|
|
71
|
+
'<url|file>': 'An http(s) URL, a local HTML, markdown, text or image file, or a scratchpad (its folder or scratchpad.json; needs the scratch CLI). Relative paths resolve against the current dir',
|
|
72
72
|
'--shell [<folder>]': 'A plain shell (the terminal shell, no claude) in <folder> (default: the current dir). Needs the board\'s terminal. Each add opens a new shell; closing the pane ends it',
|
|
73
73
|
'--run <cmd>': 'With --shell: a one-line command the shell runs when it starts, and again on each restart',
|
|
74
74
|
'--title <text>': 'Tab title (default: the host or file name)',
|
|
@@ -806,6 +806,13 @@ const cliTarget = (arg) => linkUrl(arg) || cliPath(arg);
|
|
|
806
806
|
|
|
807
807
|
const PANES_WHY = 'panes are stored per session.';
|
|
808
808
|
|
|
809
|
+
function scratchpadTarget(arg) {
|
|
810
|
+
if (linkUrl(arg)) return null;
|
|
811
|
+
const abs = cliPath(arg);
|
|
812
|
+
if (path.basename(abs).toLowerCase() === 'scratchpad.json') return abs;
|
|
813
|
+
return fs.existsSync(path.join(abs, 'scratchpad.json')) ? abs : null;
|
|
814
|
+
}
|
|
815
|
+
|
|
809
816
|
const panesPath = (sessionId, paneId) =>
|
|
810
817
|
`/api/panes/${encodeURIComponent(sessionId)}${paneId ? `/${encodeURIComponent(paneId)}` : ''}`;
|
|
811
818
|
|
|
@@ -822,9 +829,12 @@ async function runPaneAddCli(args, entry) {
|
|
|
822
829
|
if (!resolved) return 1;
|
|
823
830
|
try {
|
|
824
831
|
const title = getArgValue(args, 'title') || '';
|
|
832
|
+
const pad = shell ? null : scratchpadTarget(target);
|
|
825
833
|
const body = shell
|
|
826
834
|
? { kind: 'shell', target: canonicalDir(target || '.'), title, ...(run && { run }) }
|
|
827
|
-
:
|
|
835
|
+
: pad
|
|
836
|
+
? { kind: 'scratchpad', target: pad, title }
|
|
837
|
+
: { target: cliTarget(target), title };
|
|
828
838
|
const out = await cliPostJson(panesPath(resolved.id), body, 'Pane add');
|
|
829
839
|
if (!out) return 1;
|
|
830
840
|
const { pane } = out;
|
package/lib/parsers.js
CHANGED
|
@@ -1658,48 +1658,6 @@ async function readArtifactLinks(jsonlPath) {
|
|
|
1658
1658
|
return [...byUrl.values()].sort((x, y) => (x.firstSeen < y.firstSeen ? -1 : x.firstSeen > y.firstSeen ? 1 : 0));
|
|
1659
1659
|
}
|
|
1660
1660
|
|
|
1661
|
-
const SCRATCH_NEW_RE = /\bscratch new\b/;
|
|
1662
|
-
// `scratch new` reports where it put the pad; the two spaces are the CLI's own column
|
|
1663
|
-
// padding, which is what makes the prefilter below narrow enough to be worth having.
|
|
1664
|
-
const SCRATCH_MANIFEST_RE = /^\s*manifest\s*:\s*(.+?)\s*$/m;
|
|
1665
|
-
// The name must sit immediately after `new`, and the bare-word branch must refuse a
|
|
1666
|
-
// leading `-`, so that a flag or a flag's value cannot be read as the name.
|
|
1667
|
-
const SCRATCH_NAME_RE = /\bscratch\s+new\s+(?:"([^"]+)"|'([^']+)'|(?!-)(\S+))/;
|
|
1668
|
-
|
|
1669
|
-
// The `scratch new` calls in a transcript, `{ ts, path, name }` per call. `path` is null
|
|
1670
|
-
// whenever the command piped the CLI's output away — the common case, not an edge one:
|
|
1671
|
-
// the manifest is the 4th of ~13 printed lines, so any `| tail -N` cuts it off. `name`
|
|
1672
|
-
// stands in because it is what the manifest stores as its own `name`; the path is not
|
|
1673
|
-
// recovered from the command, which would mean tracking the `cd` and a relative `--dir`.
|
|
1674
|
-
async function readScratchpadCreations(jsonlPath) {
|
|
1675
|
-
const calls = new Map();
|
|
1676
|
-
try {
|
|
1677
|
-
for await (const line of readLines(jsonlPath)) {
|
|
1678
|
-
// Substring reject before JSON.parse: transcripts reach tens of megabytes and
|
|
1679
|
-
// only a handful of lines can ever match.
|
|
1680
|
-
const isCall = line.includes('scratch new');
|
|
1681
|
-
if (!isCall && !line.includes('manifest :')) continue;
|
|
1682
|
-
let obj;
|
|
1683
|
-
try { obj = JSON.parse(line); } catch (_) { continue; }
|
|
1684
|
-
const blocks = obj?.message?.content;
|
|
1685
|
-
if (!Array.isArray(blocks)) continue;
|
|
1686
|
-
const ts = Date.parse(obj.timestamp);
|
|
1687
|
-
for (const b of blocks) {
|
|
1688
|
-
if (b?.type === 'tool_use' && b.name === 'Bash' && SCRATCH_NEW_RE.test(b.input?.command || '')) {
|
|
1689
|
-
if (b.id && Number.isFinite(ts)) {
|
|
1690
|
-
const named = SCRATCH_NAME_RE.exec(b.input.command);
|
|
1691
|
-
calls.set(b.id, { ts, path: null, name: named?.slice(1).find(Boolean) ?? null });
|
|
1692
|
-
}
|
|
1693
|
-
} else if (b?.type === 'tool_result' && calls.has(b.tool_use_id)) {
|
|
1694
|
-
const m = SCRATCH_MANIFEST_RE.exec(toolResultText(b.content));
|
|
1695
|
-
if (m) calls.get(b.tool_use_id).path = m[1];
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
} catch (_) {}
|
|
1700
|
-
return [...calls.values()];
|
|
1701
|
-
}
|
|
1702
|
-
|
|
1703
1661
|
async function readCompactSummaries(jsonlPath) {
|
|
1704
1662
|
const results = [];
|
|
1705
1663
|
// Inline format: newer Claude Code stores the summary directly in the parent
|
|
@@ -2137,7 +2095,6 @@ module.exports = {
|
|
|
2137
2095
|
readCompactSummaries,
|
|
2138
2096
|
fillCompactSummaries,
|
|
2139
2097
|
readArtifactLinks,
|
|
2140
|
-
readScratchpadCreations,
|
|
2141
2098
|
findTerminatedTeammates,
|
|
2142
2099
|
extractPromptFromTranscript,
|
|
2143
2100
|
extractModelFromTranscript,
|
package/lib/terminal.js
CHANGED
|
@@ -782,7 +782,8 @@ function createTerminalService(o) {
|
|
|
782
782
|
ws.unacked = 0;
|
|
783
783
|
s.sockets.add(ws);
|
|
784
784
|
syncBoost(s);
|
|
785
|
-
|
|
785
|
+
// ConPTY drops DEC 2026, and a clear inside a 2026 block hits xterm #5801 unless noFlicker is on.
|
|
786
|
+
send(ws, { t: 'ready', attached, holdRedraw: process.platform === 'win32' && config.noFlicker });
|
|
786
787
|
const snapshot = s.serializer.serialize();
|
|
787
788
|
if (snapshot) sendOutput(ws, Buffer.from(snapshot, 'utf8'));
|
|
788
789
|
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-code-kanban",
|
|
3
|
-
"version": "3.11.
|
|
3
|
+
"version": "3.11.1",
|
|
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
|
}
|
|
@@ -39,6 +39,10 @@ The user works in other windows while you run, so pick the quiet command. `doc l
|
|
|
39
39
|
|
|
40
40
|
To show the user a page, a prototype or a collage of screenshots, write it as HTML and link or preview that file. The preview renders HTML as authored in a sandboxed iframe and inlines its local stylesheets, scripts and images, so the file alone is enough.
|
|
41
41
|
|
|
42
|
+
## Scratchpads
|
|
43
|
+
|
|
44
|
+
A scratchpad (a folder with `scratchpad.json`) is one document: `doc link` or `pane add` its `scratchpad.json`, never its files one by one.
|
|
45
|
+
|
|
42
46
|
## Another session
|
|
43
47
|
|
|
44
48
|
Read its transcript. `session view <id>` and `session search <text> --json` print the path.
|
package/public/app.js
CHANGED
|
@@ -4867,11 +4867,6 @@ function renderSession() {
|
|
|
4867
4867
|
const session = sessions.find((s) => s.id === currentSessionId);
|
|
4868
4868
|
if (!session) return;
|
|
4869
4869
|
|
|
4870
|
-
// Opening the session, not opening a linked-docs surface: the card badge is the
|
|
4871
|
-
// first place a pad shows up, and it would otherwise stay at zero until the user
|
|
4872
|
-
// happened to open the info modal or zen panel.
|
|
4873
|
-
loadSessionPads(currentSessionId);
|
|
4874
|
-
|
|
4875
4870
|
const displayName = session.name || session.description || currentSessionId;
|
|
4876
4871
|
|
|
4877
4872
|
sessionTitle.textContent = displayName;
|
|
@@ -10326,37 +10321,8 @@ async function loadPreviewKinds(sessionId, paths) {
|
|
|
10326
10321
|
afterLinkedDocsChanged(sessionId);
|
|
10327
10322
|
}
|
|
10328
10323
|
|
|
10329
|
-
//
|
|
10330
|
-
// The server derives the pads on every read, so this record of the ones already
|
|
10331
|
-
// linked is what stops the next read undoing an unlink.
|
|
10324
|
+
// Nothing writes these keys now; the orphan sweep still clears the ones older boards left.
|
|
10332
10325
|
const PAD_LINKED_PREFIX = 'autolinked-pads-';
|
|
10333
|
-
const padsFetched = new Set();
|
|
10334
|
-
|
|
10335
|
-
function getOfferedPadPaths(sessionId) {
|
|
10336
|
-
return readStoredList(PAD_LINKED_PREFIX + sessionId);
|
|
10337
|
-
}
|
|
10338
|
-
|
|
10339
|
-
function setOfferedPadPaths(sessionId, paths) {
|
|
10340
|
-
store.writeJson(PAD_LINKED_PREFIX + sessionId, paths);
|
|
10341
|
-
}
|
|
10342
|
-
|
|
10343
|
-
async function loadSessionPads(sessionId) {
|
|
10344
|
-
if (!sessionId || padsFetched.has(sessionId)) return;
|
|
10345
|
-
padsFetched.add(sessionId);
|
|
10346
|
-
const data = await getJson(apiPath`/api/sessions/${sessionId}/pads`);
|
|
10347
|
-
if (!data) {
|
|
10348
|
-
padsFetched.delete(sessionId);
|
|
10349
|
-
return;
|
|
10350
|
-
}
|
|
10351
|
-
const pads = data.pads || [];
|
|
10352
|
-
const offered = new Set(getOfferedPadPaths(sessionId).map(canonicalPath));
|
|
10353
|
-
const fresh = pads.map((p) => p.path).filter((p) => !offered.has(canonicalPath(p)));
|
|
10354
|
-
if (!fresh.length) return;
|
|
10355
|
-
// Recorded before the link, so a render triggered by the link already sees a pad
|
|
10356
|
-
// that will not be offered again.
|
|
10357
|
-
setOfferedPadPaths(sessionId, [...offered, ...fresh]);
|
|
10358
|
-
for (const p of fresh) setSessionDocLink(sessionId, p, false);
|
|
10359
|
-
}
|
|
10360
10326
|
|
|
10361
10327
|
// A scratchpad manifest opens in the external `scratch` viewer, not the editor —
|
|
10362
10328
|
// the raw JSON is a manifest, not the document the user linked.
|
|
@@ -10366,12 +10332,17 @@ function isScratchpadPath(p) {
|
|
|
10366
10332
|
|
|
10367
10333
|
// `linkedDocOpener` is the only place a linked path is classified; the row's tag,
|
|
10368
10334
|
// tooltip and action are all read from here, so a new destination is one entry.
|
|
10335
|
+
const SCRATCHPAD_OPEN = 'scratchpad.open';
|
|
10369
10336
|
const LINKED_DOC_OPENERS = {
|
|
10370
10337
|
preview: { tag: '', hint: '', cls: '', noun: 'path' },
|
|
10371
10338
|
url: { tag: '', hint: ' — opens in a new tab', cls: ' is-url', noun: 'URL' },
|
|
10372
10339
|
scratch: {
|
|
10373
10340
|
tag: '(scratchpad)',
|
|
10374
|
-
hint
|
|
10341
|
+
get hint() {
|
|
10342
|
+
return hub.can(SCRATCHPAD_OPEN)
|
|
10343
|
+
? ' — opens in a pane; Shift+click opens the Scratchpads tab; Ctrl+click opens the scratch viewer'
|
|
10344
|
+
: ' — opens in the scratch viewer';
|
|
10345
|
+
},
|
|
10375
10346
|
cls: ' is-editor',
|
|
10376
10347
|
noun: 'path',
|
|
10377
10348
|
url: '/api/scratchpad/open',
|
|
@@ -10834,9 +10805,14 @@ function bindLinkedDocsHandlers(container, sessionId) {
|
|
|
10834
10805
|
removeSessionPreviewPath(sessionId, hit.dataset.path);
|
|
10835
10806
|
forgetServerLinkedDoc(sessionId, hit.dataset.path);
|
|
10836
10807
|
afterLinkedDocsChanged(sessionId);
|
|
10837
|
-
} else if (
|
|
10808
|
+
} else if (
|
|
10809
|
+
!(e.ctrlKey || e.metaKey) &&
|
|
10810
|
+
linkedDocOpener(hit.dataset.path) === 'scratch' &&
|
|
10811
|
+
hub.can(SCRATCHPAD_OPEN)
|
|
10812
|
+
) {
|
|
10838
10813
|
if (container.closest('#team-modal')) closeTeamModal();
|
|
10839
|
-
|
|
10814
|
+
if (e.shiftKey) openScratchpadTab(sessionId, hit.dataset.path);
|
|
10815
|
+
else openScratchpadPane(sessionId, hit.dataset.path);
|
|
10840
10816
|
} else {
|
|
10841
10817
|
openLinkedDoc(hit.dataset.path, getSessionBaseDir(sessionId));
|
|
10842
10818
|
}
|
|
@@ -10957,8 +10933,6 @@ function setupEventSource() {
|
|
|
10957
10933
|
fetchSessions().catch(() => {});
|
|
10958
10934
|
if (currentSessionId) fetchTasks(currentSessionId);
|
|
10959
10935
|
refetchPaneLayout();
|
|
10960
|
-
// A restarted board started none of the viewers the frames still point at.
|
|
10961
|
-
onScratchpadExited(null);
|
|
10962
10936
|
if (sgRev === null) syncSessionGroups();
|
|
10963
10937
|
else if (sgUnsent) persistSessionGroups();
|
|
10964
10938
|
else sgRefresh();
|
|
@@ -11098,10 +11072,6 @@ function setupEventSource() {
|
|
|
11098
11072
|
applyPaneLayout(data.sessionId, data.layout);
|
|
11099
11073
|
}
|
|
11100
11074
|
|
|
11101
|
-
if (data.type === 'scratchpad:exited') {
|
|
11102
|
-
onScratchpadExited(data.manifest);
|
|
11103
|
-
}
|
|
11104
|
-
|
|
11105
11075
|
if (data.type === 'addon:changed' && dockSid) {
|
|
11106
11076
|
fetchDockAddons(dockSid);
|
|
11107
11077
|
}
|
|
@@ -12901,7 +12871,6 @@ function initSidebarResize() {
|
|
|
12901
12871
|
onStart() {
|
|
12902
12872
|
if (sidebar.classList.contains('collapsed')) return false;
|
|
12903
12873
|
startWidth = sidebar.offsetWidth;
|
|
12904
|
-
sidebar.classList.add('resizing');
|
|
12905
12874
|
},
|
|
12906
12875
|
onMove(dx) {
|
|
12907
12876
|
const w = Math.min(600, Math.max(200, startWidth + dx));
|
|
@@ -12909,7 +12878,6 @@ function initSidebarResize() {
|
|
|
12909
12878
|
sidebar.style.width = `${w}px`;
|
|
12910
12879
|
},
|
|
12911
12880
|
onEnd() {
|
|
12912
|
-
sidebar.classList.remove('resizing');
|
|
12913
12881
|
store.setItem(SIDEBAR_WIDTH_KEY, sidebar.style.getPropertyValue('--sidebar-width'));
|
|
12914
12882
|
},
|
|
12915
12883
|
});
|
|
@@ -12960,10 +12928,6 @@ async function showSessionInfoModal(sessionId) {
|
|
|
12960
12928
|
const cachedTasks = currentSessionId === sessionId ? currentTasks : [];
|
|
12961
12929
|
showInfoModal(session, null, cachedTasks, null, null);
|
|
12962
12930
|
artifactsSection.load(sessionId);
|
|
12963
|
-
// The modal reaches any card's session, not just the open one, so this is the second
|
|
12964
|
-
// place a pad can first be seen. Linking belongs on the two open events rather than
|
|
12965
|
-
// in renderLinkedDocsHtml, which only builds a string and runs on every repaint.
|
|
12966
|
-
loadSessionPads(sessionId);
|
|
12967
12931
|
|
|
12968
12932
|
const rerender = (teamConfig, tasks, planContent, parentInfo) => {
|
|
12969
12933
|
if (_planSessionId !== sessionId) return; // user opened a different modal
|
|
@@ -14898,6 +14862,7 @@ function paneUrlFrame(pane, className) {
|
|
|
14898
14862
|
frame.addEventListener('load', () => {
|
|
14899
14863
|
postToShowFrames(() => ({ type: `${SHOW_MSG}tokens`, tokens: showTokens() }), [frame]);
|
|
14900
14864
|
frame.hostKeysSig = null;
|
|
14865
|
+
frame.hostPlainKeys = null;
|
|
14901
14866
|
pushTerminalClaims();
|
|
14902
14867
|
});
|
|
14903
14868
|
return frame;
|
|
@@ -14932,7 +14897,7 @@ async function loadPaneView(sid, pane, view, scroll) {
|
|
|
14932
14897
|
return;
|
|
14933
14898
|
}
|
|
14934
14899
|
if (pane.kind === 'scratchpad') {
|
|
14935
|
-
await loadScratchpadPaneView(pane, view);
|
|
14900
|
+
await loadScratchpadPaneView(sid, pane, view);
|
|
14936
14901
|
return;
|
|
14937
14902
|
}
|
|
14938
14903
|
if (pane.kind === 'shell') {
|
|
@@ -14973,38 +14938,28 @@ async function loadPaneView(sid, pane, view, scroll) {
|
|
|
14973
14938
|
view.insertAdjacentHTML('beforeend', paneCardHtml(title, text, button));
|
|
14974
14939
|
}
|
|
14975
14940
|
|
|
14976
|
-
// The viewer
|
|
14977
|
-
//
|
|
14978
|
-
|
|
14979
|
-
|
|
14980
|
-
|
|
14981
|
-
|
|
14982
|
-
|
|
14983
|
-
)
|
|
14984
|
-
|
|
14985
|
-
|
|
14986
|
-
if (!
|
|
14941
|
+
// The pad's viewer belongs to the hub's Scratchpads app; the board asks it for the URL each time it
|
|
14942
|
+
// mounts the view, because the app stops a viewer that no page has open.
|
|
14943
|
+
function scratchpadOpenArgs(sid, path) {
|
|
14944
|
+
return { path, project: sessions.find((s) => s.id === sid)?.project || '', session: sid };
|
|
14945
|
+
}
|
|
14946
|
+
|
|
14947
|
+
async function loadScratchpadPaneView(sid, pane, view) {
|
|
14948
|
+
const { url } = hub.can(SCRATCHPAD_OPEN)
|
|
14949
|
+
? await hub.invoke(SCRATCHPAD_OPEN, scratchpadOpenArgs(sid, pane.target), { open: 'pane' })
|
|
14950
|
+
: {};
|
|
14951
|
+
if (!url) {
|
|
14987
14952
|
view.insertAdjacentHTML(
|
|
14988
14953
|
'beforeend',
|
|
14989
|
-
paneCardHtml(
|
|
14954
|
+
paneCardHtml(
|
|
14955
|
+
'Scratchpads app unavailable',
|
|
14956
|
+
'Install the Scratchpads hub app to view pads in a pane.',
|
|
14957
|
+
'Open in scratch viewer',
|
|
14958
|
+
),
|
|
14990
14959
|
);
|
|
14991
14960
|
return;
|
|
14992
14961
|
}
|
|
14993
|
-
mountPaneUrlFrame({ ...pane, target:
|
|
14994
|
-
}
|
|
14995
|
-
|
|
14996
|
-
// A viewer that exited leaves its frames on a dead port; the views on screen mount again now,
|
|
14997
|
-
// the others when shown.
|
|
14998
|
-
function onScratchpadExited(manifest) {
|
|
14999
|
-
const dead = [];
|
|
15000
|
-
for (const key of paneFrames.keys()) {
|
|
15001
|
-
const [sid, paneId] = key.split('/');
|
|
15002
|
-
const pane = paneLayout(sid).panes.find((p) => p.id === paneId);
|
|
15003
|
-
if (pane?.kind === 'scratchpad' && (!manifest || canonicalPath(pane.target) === manifest)) dead.push([sid, paneId]);
|
|
15004
|
-
}
|
|
15005
|
-
if (!dead.length) return;
|
|
15006
|
-
for (const [sid, paneId] of dead) unmountPane(sid, paneId);
|
|
15007
|
-
syncPanes();
|
|
14962
|
+
mountPaneUrlFrame({ ...pane, target: url }, view);
|
|
15008
14963
|
}
|
|
15009
14964
|
|
|
15010
14965
|
// The target is the message's pin id, `type|timestamp|text`. The log holds only the latest pages,
|
|
@@ -15613,6 +15568,9 @@ function openPaneMenu(x, y, id) {
|
|
|
15613
15568
|
? 'Open in scratch viewer'
|
|
15614
15569
|
: 'Open in preview',
|
|
15615
15570
|
)) +
|
|
15571
|
+
(pane.kind === 'scratchpad' && hub.can(SCRATCHPAD_OPEN)
|
|
15572
|
+
? paneMenuItem('openTab', 'Open in Scratchpads tab')
|
|
15573
|
+
: '') +
|
|
15616
15574
|
(message || shell
|
|
15617
15575
|
? ''
|
|
15618
15576
|
: paneMenuItem('link', paneIsLinked(pane) ? 'Remove from linked documents' : 'Add to linked documents')) +
|
|
@@ -15672,6 +15630,10 @@ function showPaneMenu(x, y, id, ariaLabel, html) {
|
|
|
15672
15630
|
const PANE_MENU_ACTIONS = {
|
|
15673
15631
|
copy: copyPaneTarget,
|
|
15674
15632
|
open: openPaneExternally,
|
|
15633
|
+
openTab: (id) => {
|
|
15634
|
+
const pane = paneById(id);
|
|
15635
|
+
if (pane) openScratchpadTab(paneSessionId(), pane.target);
|
|
15636
|
+
},
|
|
15675
15637
|
link: togglePaneLink,
|
|
15676
15638
|
rename: beginPaneRename,
|
|
15677
15639
|
reload: reloadPane,
|
|
@@ -15733,11 +15695,14 @@ function applyPaneLine(view) {
|
|
|
15733
15695
|
markSourceLine(body, line);
|
|
15734
15696
|
}
|
|
15735
15697
|
|
|
15736
|
-
// The same pad again returns its pane, so a second
|
|
15698
|
+
// The same pad again returns its pane, so a second click only shows it.
|
|
15737
15699
|
async function openScratchpadPane(sid, manifest) {
|
|
15738
15700
|
const onScreen = await postPane(sid, { kind: 'scratchpad', target: manifest });
|
|
15739
|
-
if (onScreen)
|
|
15740
|
-
|
|
15701
|
+
if (onScreen !== null) revealPane(sid, onScreen);
|
|
15702
|
+
}
|
|
15703
|
+
|
|
15704
|
+
function openScratchpadTab(sid, manifest) {
|
|
15705
|
+
hub.invoke(SCRATCHPAD_OPEN, scratchpadOpenArgs(sid, manifest));
|
|
15741
15706
|
}
|
|
15742
15707
|
|
|
15743
15708
|
async function openPaneAtLine(sid, { path, line }, base) {
|
|
@@ -16775,11 +16740,14 @@ function sendBridgeClaimsAll(frames, base) {
|
|
|
16775
16740
|
}
|
|
16776
16741
|
|
|
16777
16742
|
// A hub app in a URL pane runs the SDK, which hands back these keys (hub protocol §5.2). Only keys with
|
|
16778
|
-
// Ctrl, Alt or Meta
|
|
16743
|
+
// Ctrl, Alt or Meta, so the page keeps Escape, brackets and its own letter keys, plus the plain keys
|
|
16744
|
+
// its hub:hostReady named.
|
|
16779
16745
|
function sendHostKeys(frames, bridged) {
|
|
16780
|
-
const
|
|
16781
|
-
const sig = JSON.stringify(keys);
|
|
16746
|
+
const modified = (k) => k.ctrlKey || k.altKey || k.metaKey;
|
|
16782
16747
|
for (const f of frames) {
|
|
16748
|
+
const plain = f.hostPlainKeys || [];
|
|
16749
|
+
const keys = bridged.keys.filter((k) => modified(k) || plain.includes(k.key));
|
|
16750
|
+
const sig = JSON.stringify(keys);
|
|
16783
16751
|
const origin = URL.parse(f.src)?.origin;
|
|
16784
16752
|
if (!origin || origin === 'null' || f.hostKeysSig === sig) continue;
|
|
16785
16753
|
f.hostKeysSig = sig;
|
|
@@ -16797,6 +16765,11 @@ window.addEventListener('message', (e) => {
|
|
|
16797
16765
|
if (!frame || URL.parse(frame.src)?.origin !== e.origin) return;
|
|
16798
16766
|
if (type === 'hub:hostReady') {
|
|
16799
16767
|
if (!dock) frame.parentElement.classList.add('keys-bridged');
|
|
16768
|
+
const plain = Array.isArray(e.data.plainKeys) ? e.data.plainKeys.filter((k) => typeof k === 'string') : [];
|
|
16769
|
+
if (plain.length) {
|
|
16770
|
+
frame.hostPlainKeys = plain;
|
|
16771
|
+
pushTerminalClaims();
|
|
16772
|
+
}
|
|
16800
16773
|
return;
|
|
16801
16774
|
}
|
|
16802
16775
|
// A page has focus when it gets a keydown, even one that never posts its focus.
|
|
@@ -18550,14 +18523,20 @@ window.addEventListener('message', (e) => {
|
|
|
18550
18523
|
|
|
18551
18524
|
// The same body attributes the terminal theme watches; a markdown card follows the board's CSS.
|
|
18552
18525
|
// The body's style also changes on every drag, so a push with the same tokens is dropped.
|
|
18526
|
+
// A theme switch changes the class and the style in separate steps, so one frame collects them.
|
|
18553
18527
|
let sentTokens = '';
|
|
18528
|
+
let tokensRaf = 0;
|
|
18554
18529
|
new MutationObserver(() => {
|
|
18555
|
-
|
|
18556
|
-
|
|
18557
|
-
|
|
18558
|
-
|
|
18559
|
-
|
|
18560
|
-
|
|
18530
|
+
if (tokensRaf) return;
|
|
18531
|
+
tokensRaf = requestAnimationFrame(() => {
|
|
18532
|
+
tokensRaf = 0;
|
|
18533
|
+
postToShowFrames(() => {
|
|
18534
|
+
const tokens = showTokens();
|
|
18535
|
+
const key = JSON.stringify(tokens);
|
|
18536
|
+
if (key === sentTokens) return null;
|
|
18537
|
+
sentTokens = key;
|
|
18538
|
+
return { type: `${SHOW_MSG}tokens`, tokens };
|
|
18539
|
+
});
|
|
18561
18540
|
});
|
|
18562
18541
|
}).observe(document.body, { attributes: true, attributeFilter: ['class', 'data-color-theme', 'style'] });
|
|
18563
18542
|
|
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 {
|
|
@@ -1918,6 +1912,12 @@ body.booting .boot-splash {
|
|
|
1918
1912
|
color: var(--text-primary);
|
|
1919
1913
|
}
|
|
1920
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
1921
|
.home-key-kbd {
|
|
1922
1922
|
display: inline-flex;
|
|
1923
1923
|
align-items: center;
|
package/public/terminal-frame.js
CHANGED
|
@@ -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 }) =>
|
|
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 });
|
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
|
|
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) => {
|
package/lib/scratch-servers.js
DELETED
|
@@ -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 };
|