@bakapiano/ccsm 0.6.0 → 0.8.3

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.
Files changed (67) hide show
  1. package/README.md +172 -38
  2. package/bin/ccsm.js +194 -0
  3. package/lib/favorites.js +23 -45
  4. package/lib/jsonStore.js +60 -0
  5. package/lib/labels.js +21 -41
  6. package/lib/webTerminal.js +173 -0
  7. package/package.json +11 -3
  8. package/public/css/base.css +82 -0
  9. package/public/css/cards.css +149 -0
  10. package/public/css/feedback.css +219 -0
  11. package/public/css/forms.css +282 -0
  12. package/public/css/layout.css +107 -0
  13. package/public/css/modal.css +169 -0
  14. package/public/css/responsive.css +10 -0
  15. package/public/css/sidebar.css +165 -0
  16. package/public/css/tables.css +266 -0
  17. package/public/css/terminals.css +112 -0
  18. package/public/css/tokens.css +63 -0
  19. package/public/css/wco.css +70 -0
  20. package/public/css/widgets.css +204 -0
  21. package/public/favicon.svg +1 -1
  22. package/public/index.html +52 -490
  23. package/public/js/actions.js +87 -0
  24. package/public/js/api.js +103 -0
  25. package/public/js/backend.js +28 -0
  26. package/public/js/components/App.js +45 -0
  27. package/public/js/components/Card.js +24 -0
  28. package/public/js/components/DialogHost.js +45 -0
  29. package/public/js/components/Fab.js +11 -0
  30. package/public/js/components/FavoritesTable.js +81 -0
  31. package/public/js/components/Footer.js +12 -0
  32. package/public/js/components/NewSessionModal.js +142 -0
  33. package/public/js/components/OfflineBanner.js +52 -0
  34. package/public/js/components/PageHead.js +33 -0
  35. package/public/js/components/Pagination.js +27 -0
  36. package/public/js/components/ProgressList.js +32 -0
  37. package/public/js/components/RecentTable.js +68 -0
  38. package/public/js/components/RepoPicker.js +40 -0
  39. package/public/js/components/ReposEditor.js +74 -0
  40. package/public/js/components/ServerStatus.js +18 -0
  41. package/public/js/components/SessionsTable.js +71 -0
  42. package/public/js/components/Sidebar.js +52 -0
  43. package/public/js/components/SnapshotPanel.js +77 -0
  44. package/public/js/components/TerminalView.js +108 -0
  45. package/public/js/components/TitleCell.js +40 -0
  46. package/public/js/components/Toast.js +8 -0
  47. package/public/js/components/WorkspacePicker.js +19 -0
  48. package/public/js/components/WorkspacesGrid.js +41 -0
  49. package/public/js/dialog.js +59 -0
  50. package/public/js/html.js +6 -0
  51. package/public/js/icons.js +114 -0
  52. package/public/js/main.js +81 -0
  53. package/public/js/pages/AboutPage.js +85 -0
  54. package/public/js/pages/ConfigurePage.js +194 -0
  55. package/public/js/pages/LaunchPage.js +117 -0
  56. package/public/js/pages/SessionsPage.js +47 -0
  57. package/public/js/pages/TerminalsPage.js +74 -0
  58. package/public/js/state.js +87 -0
  59. package/public/js/streaming.js +96 -0
  60. package/public/js/toast.js +14 -0
  61. package/public/js/util.js +24 -0
  62. package/public/manifest.webmanifest +14 -0
  63. package/scripts/install.js +111 -0
  64. package/scripts/uninstall.js +56 -0
  65. package/server.js +286 -30
  66. package/public/app.js +0 -1353
  67. package/public/styles.css +0 -1639
@@ -0,0 +1,47 @@
1
+ import { html } from '../html.js';
2
+ import { sessions, recentTotal, favoritesList, clockTick } from '../state.js';
3
+ import { Card } from '../components/Card.js';
4
+ import { SessionsTable } from '../components/SessionsTable.js';
5
+ import { RecentTable } from '../components/RecentTable.js';
6
+ import { FavoritesTable } from '../components/FavoritesTable.js';
7
+ import { runFinder } from '../actions.js';
8
+ import { IconSearch, StarSmallFilled } from '../icons.js';
9
+ import { nowClock } from '../util.js';
10
+
11
+ export function SessionsPage() {
12
+ void clockTick.value;
13
+ const sessCount = sessions.value.length;
14
+ const favCount = favoritesList.value.length;
15
+
16
+ const sessionsMeta = sessCount
17
+ ? `${sessCount} live · refreshed ${nowClock()}`
18
+ : 'no live sessions';
19
+ const recentMeta = recentTotal.value
20
+ ? `${recentTotal.value} total · sorted by jsonl mtime, excluding live`
21
+ : 'no recent sessions';
22
+ const favMeta = favCount ? `${favCount} pinned` : 'click ☆ on any row to pin sessions here';
23
+
24
+ return html`
25
+ <div class="page-actions">
26
+ <span class="page-actions-hint">Looking through your past conversations?</span>
27
+ <button class="action primary" onClick=${runFinder}
28
+ title="open a Claude session with context on the ccsm data dir">
29
+ <${IconSearch} stroke=${2} /> Ask Claude to find a session
30
+ </button>
31
+ </div>
32
+
33
+ <${Card} foldKey="favorites"
34
+ title=${html`Favorites <${StarSmallFilled} />`}
35
+ meta=${favMeta}
36
+ flush=${true}>
37
+ <${FavoritesTable} />
38
+ </${Card}>
39
+
40
+ <${Card} foldKey="sessions" title="Live sessions" meta=${sessionsMeta} flush=${true}>
41
+ <${SessionsTable} />
42
+ </${Card}>
43
+
44
+ <${Card} foldKey="recent" title="Recently closed" meta=${recentMeta} flush=${true}>
45
+ <${RecentTable} />
46
+ </${Card}>`;
47
+ }
@@ -0,0 +1,74 @@
1
+ // Left rail · list of active web sessions + right pane with selected one's xterm.
2
+
3
+ import { html } from '../html.js';
4
+ import { useEffect } from 'preact/hooks';
5
+ import { webTerminals, activeTerminalId, selectTab } from '../state.js';
6
+ import { loadWebTerminals, killWebTerminal } from '../api.js';
7
+ import { setToast } from '../toast.js';
8
+ import { ccsmConfirm } from '../dialog.js';
9
+ import { TerminalView } from '../components/TerminalView.js';
10
+ import { fmtAgo } from '../util.js';
11
+
12
+ export function TerminalsPage() {
13
+ const list = webTerminals.value;
14
+ const activeId = activeTerminalId.value;
15
+
16
+ // Auto-select the first available terminal if nothing is active
17
+ useEffect(() => {
18
+ if (!activeId && list.length > 0) activeTerminalId.value = list[0].id;
19
+ if (activeId && !list.find((t) => t.id === activeId)) {
20
+ activeTerminalId.value = list[0]?.id || null;
21
+ }
22
+ }, [list.map((t) => t.id).join('|'), activeId]);
23
+
24
+ if (list.length === 0) {
25
+ return html`
26
+ <div class="terminal-empty-page">
27
+ <div class="card">
28
+ <div class="card-body" style="text-align: center; padding: 60px var(--s-6);">
29
+ <p style="font-size: 14px; color: var(--ink-mid); margin-bottom: var(--s-4);">
30
+ No terminals open yet.
31
+ </p>
32
+ <button class="action primary" onClick=${() => selectTab('launch')}>
33
+ + Launch a session
34
+ </button>
35
+ </div>
36
+ </div>
37
+ </div>`;
38
+ }
39
+
40
+ return html`
41
+ <div class="terminals-layout">
42
+ <aside class="terminals-rail">
43
+ <div class="terminals-rail-head">
44
+ <span>${list.length} active</span>
45
+ <button class="action subtle tiny" title="refresh list" onClick=${() => loadWebTerminals()}>↻</button>
46
+ </div>
47
+ ${list.map((t) => html`
48
+ <button key=${t.id} class=${`terminal-row${activeId === t.id ? ' is-active' : ''}`}
49
+ onClick=${() => (activeTerminalId.value = t.id)}>
50
+ <span class=${`status-mark ${t.exitedAt ? 'unknown' : 'busy'}`}></span>
51
+ <span class="terminal-row-title">${t.meta.title || t.id.slice(0, 12)}</span>
52
+ <span class="terminal-row-meta">${fmtAgo(t.meta.startedAt)}</span>
53
+ <span class="terminal-row-actions">
54
+ <button class="action tiny danger" title="kill this session"
55
+ onClick=${(ev) => { ev.stopPropagation(); confirmKill(t); }}>×</button>
56
+ </span>
57
+ </button>`)}
58
+ </aside>
59
+ <main class="terminals-main">
60
+ <${TerminalView} terminalId=${activeId} />
61
+ </main>
62
+ </div>`;
63
+ }
64
+
65
+ async function confirmKill(t) {
66
+ const ok = await ccsmConfirm(`Kill ${t.meta.title || t.id}? The PTY process will be terminated.`, {
67
+ title: 'Kill session', okLabel: 'Kill', danger: true,
68
+ });
69
+ if (!ok) return;
70
+ try {
71
+ await killWebTerminal(t.id);
72
+ setToast(`killed · ${t.id.slice(0, 12)}`);
73
+ } catch (e) { setToast(e.message, 'error'); }
74
+ }
@@ -0,0 +1,87 @@
1
+ // All shared reactive state. Importing a signal anywhere subscribes the
2
+ // reading component, so we never need a store / context wrapper.
3
+
4
+ import { signal, computed } from '@preact/signals';
5
+
6
+ // ── server-driven data ──────────────────────────────────────────
7
+ export const config = signal(null);
8
+ export const terminals = signal([]);
9
+ export const capabilities = signal({ webTerminal: false });
10
+ export const sessions = signal([]);
11
+ export const webTerminals = signal([]); // active in-page PTY sessions
12
+ export const activeTerminalId = signal(null); // which one's open in the right pane
13
+ export const recent = signal([]);
14
+ export const recentTotal = signal(0);
15
+ export const favorites = signal({}); // { sessionId: {sessionId, cwd, title, gitBranch, addedAt} }
16
+ export const labels = signal({}); // { sessionId: customLabel }
17
+ export const workspaces = signal([]);
18
+ export const snapshot = signal(null);
19
+ export const history = signal([]);
20
+ export const serverHealth = signal({ state: 'connecting' });
21
+
22
+ // ── ui state (persisted in localStorage where noted) ───────────
23
+ export const activeTab = signal('sessions');
24
+ export const sidebarCollapsed = signal(false);
25
+ // fold state for the three cards on the Sessions tab
26
+ export const cardFolded = signal({ favorites: false, sessions: false, recent: false });
27
+ export const configDirty = signal(false);
28
+ export const modalOpen = signal(false);
29
+ export const clockTick = signal(Date.now()); // re-ticked each second so fmtAgo refreshes
30
+ export const lastRefreshAt = signal(0); // ms timestamp of last successful refreshAll()
31
+ export const installPrompt = signal(null); // captured beforeinstallprompt event (PWA install)
32
+ export const isInstalledPwa = signal(false); // running inside an installed PWA window (display-mode: standalone+)
33
+
34
+ // ── pagination ──────────────────────────────────────────────────
35
+ export const sessionsOffset = signal(0);
36
+ export const sessionsLimit = signal(10);
37
+ export const favoritesOffset = signal(0);
38
+ export const favoritesLimit = signal(10);
39
+ export const recentOffset = signal(0);
40
+ export const recentLimit = signal(10);
41
+
42
+ // ── derived ─────────────────────────────────────────────────────
43
+ export const favoritesList = computed(() =>
44
+ Object.values(favorites.value).sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0))
45
+ );
46
+
47
+ export const TAB_HEADINGS = {
48
+ sessions: { title: 'Sessions', subtitle: 'Live and recently-closed Claude Code sessions on this machine.' },
49
+ launch: { title: 'Launch', subtitle: 'Spin up a new session in a fresh workspace, or restore from snapshot.' },
50
+ terminals: { title: 'Terminals', subtitle: 'Claude sessions running in this page.' },
51
+ configure: { title: 'Configure', subtitle: 'Persisted to ~/.ccsm/config.json.' },
52
+ about: { title: 'About', subtitle: 'ccsm — Claude Code Session Manager.' },
53
+ };
54
+
55
+ // ── persistence helpers (localStorage) ──────────────────────────
56
+ const LS_SIDEBAR = 'ccsm.sidebar-collapsed';
57
+ const LS_FOLD = (k) => `ccsm.fold.${k}`;
58
+
59
+ export function loadPersisted() {
60
+ sidebarCollapsed.value = localStorage.getItem(LS_SIDEBAR) === 'true';
61
+ const folds = { ...cardFolded.value };
62
+ for (const k of Object.keys(folds)) {
63
+ folds[k] = localStorage.getItem(LS_FOLD(k)) === '1';
64
+ }
65
+ cardFolded.value = folds;
66
+
67
+ const hash = location.hash.slice(1);
68
+ if (TAB_HEADINGS[hash]) activeTab.value = hash;
69
+ }
70
+
71
+ // ── actions ─────────────────────────────────────────────────────
72
+ export function selectTab(name) {
73
+ if (!TAB_HEADINGS[name]) name = 'sessions';
74
+ activeTab.value = name;
75
+ if (location.hash !== `#${name}`) window.history.replaceState(null, '', `#${name}`);
76
+ }
77
+
78
+ export function toggleSidebar() {
79
+ sidebarCollapsed.value = !sidebarCollapsed.value;
80
+ localStorage.setItem(LS_SIDEBAR, String(sidebarCollapsed.value));
81
+ }
82
+
83
+ export function toggleCardFold(key) {
84
+ const next = { ...cardFolded.value, [key]: !cardFolded.value[key] };
85
+ cardFolded.value = next;
86
+ localStorage.setItem(LS_FOLD(key), next[key] ? '1' : '0');
87
+ }
@@ -0,0 +1,96 @@
1
+ // NDJSON clone-progress stream + per-repo progress state.
2
+ // Items live in a signal keyed by repo so progress rows are reactive.
3
+
4
+ import { signal } from '@preact/signals';
5
+ import { httpBase } from './backend.js';
6
+
7
+ // progressByContext[rootId] = { repoName: { phase, percent, detail, state, indeterminate, name } }
8
+ export const progressByContext = signal({});
9
+
10
+ export function resetProgress(repos, rootId = 'newSessionProgress') {
11
+ const next = { ...progressByContext.value };
12
+ next[rootId] = {};
13
+ for (const r of repos) {
14
+ next[rootId][r] = { name: r, phase: 'queued', percent: null, detail: '', state: null, indeterminate: false };
15
+ }
16
+ progressByContext.value = next;
17
+ }
18
+
19
+ function patchProgress(rootId, repo, patch) {
20
+ const current = progressByContext.value[rootId] || {};
21
+ const item = current[repo];
22
+ if (!item) return;
23
+ const updated = { ...item, ...patch };
24
+ if (patch.state) {
25
+ updated.state = (patch.state === 'ok' || patch.state === 'error') ? patch.state : null;
26
+ }
27
+ progressByContext.value = {
28
+ ...progressByContext.value,
29
+ [rootId]: { ...current, [repo]: updated },
30
+ };
31
+ }
32
+
33
+ function applyEvent(ev, rootId) {
34
+ switch (ev.type) {
35
+ case 'clone-start':
36
+ patchProgress(rootId, ev.repo, { phase: 'starting', indeterminate: true, percent: null });
37
+ break;
38
+ case 'clone-progress':
39
+ patchProgress(rootId, ev.repo, {
40
+ phase: ev.phase,
41
+ percent: ev.percent,
42
+ detail: ev.detail || (ev.current != null ? `${ev.current}/${ev.total}` : ''),
43
+ indeterminate: false,
44
+ });
45
+ break;
46
+ case 'clone-end':
47
+ if (ev.ok) {
48
+ patchProgress(rootId, ev.repo, {
49
+ phase: ev.action || 'done', percent: 100, detail: ev.path || '', state: 'ok', indeterminate: false,
50
+ });
51
+ } else {
52
+ patchProgress(rootId, ev.repo, {
53
+ phase: 'error', detail: ev.error, state: 'error', indeterminate: false,
54
+ });
55
+ }
56
+ break;
57
+ }
58
+ }
59
+
60
+ // onMeta(event) is called for workspace/launched/done events so the caller can
61
+ // surface them in their own result text area.
62
+ export async function streamNewSession(body, { progressRootId = 'newSessionProgress', onMeta } = {}) {
63
+ const res = await fetch(httpBase() + '/api/sessions/new', {
64
+ method: 'POST',
65
+ headers: { 'Content-Type': 'application/json' },
66
+ body: JSON.stringify(body),
67
+ });
68
+ if (!res.ok && res.headers.get('content-type')?.startsWith('application/json')) {
69
+ const j = await res.json();
70
+ throw new Error(j.error || `HTTP ${res.status}`);
71
+ }
72
+ const reader = res.body.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buf = '';
75
+ let final = null;
76
+ const consume = (raw) => {
77
+ if (!raw.trim()) return;
78
+ let event;
79
+ try { event = JSON.parse(raw); } catch { return; }
80
+ applyEvent(event, progressRootId);
81
+ if (onMeta && (event.type === 'workspace' || event.type === 'launched' || event.type === 'done')) {
82
+ onMeta(event);
83
+ }
84
+ if (event.type === 'done') final = event;
85
+ };
86
+ while (true) {
87
+ const { done, value } = await reader.read();
88
+ if (done) break;
89
+ buf += decoder.decode(value, { stream: true });
90
+ const lines = buf.split('\n');
91
+ buf = lines.pop();
92
+ for (const line of lines) consume(line);
93
+ }
94
+ if (buf) consume(buf);
95
+ return final || { success: false, error: 'stream ended unexpectedly' };
96
+ }
@@ -0,0 +1,14 @@
1
+ // Single-slot toast. setToast('msg', 'ok'|'error') schedules an auto-hide.
2
+
3
+ import { signal } from '@preact/signals';
4
+
5
+ export const toastState = signal({ msg: '', kind: 'ok', visible: false });
6
+ let timer = null;
7
+
8
+ export function setToast(msg, kind = 'ok') {
9
+ toastState.value = { msg, kind, visible: true };
10
+ clearTimeout(timer);
11
+ timer = setTimeout(() => {
12
+ toastState.value = { ...toastState.value, visible: false };
13
+ }, 3200);
14
+ }
@@ -0,0 +1,24 @@
1
+ // Pure formatters · no DOM access.
2
+
3
+ export function fmtTime(ms) {
4
+ if (!ms) return '—';
5
+ return new Date(ms).toLocaleString(undefined, { hour12: false });
6
+ }
7
+
8
+ export function fmtAgo(ms) {
9
+ if (!ms) return '—';
10
+ const sec = Math.floor((Date.now() - ms) / 1000);
11
+ if (sec < 60) return `${sec}s`;
12
+ if (sec < 3600) return `${Math.floor(sec / 60)}m`;
13
+ if (sec < 86400) return `${Math.floor(sec / 3600)}h`;
14
+ return `${Math.floor(sec / 86400)}d`;
15
+ }
16
+
17
+ // label override beats claude's ai-title; both empty → "(no title)"
18
+ export function displayTitle(label, fallback) {
19
+ return label || fallback || '(no title)';
20
+ }
21
+
22
+ export function nowClock() {
23
+ return new Date().toLocaleTimeString(undefined, { hour12: false });
24
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "ccsm — Claude CLI Sessions Manager",
3
+ "short_name": "ccsm",
4
+ "description": "Single pane over every live claude session on this machine.",
5
+ "start_url": "./",
6
+ "scope": "./",
7
+ "display": "standalone",
8
+ "display_override": ["window-controls-overlay", "standalone"],
9
+ "background_color": "#faf9f5",
10
+ "theme_color": "#faf9f5",
11
+ "icons": [
12
+ { "src": "favicon.svg", "type": "image/svg+xml", "sizes": "any", "purpose": "any" }
13
+ ]
14
+ }
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // ccsm postinstall · Windows-only · runs after `npm install -g @bakapiano/ccsm`.
5
+ // Registers the `ccsm://` URL protocol in HKCU so the hosted frontend
6
+ // (https://bakapiano.github.io/cssm/v1/) can fire `<a href="ccsm://start">`
7
+ // from its OfflineBanner and have Windows spawn the backend on demand.
8
+ //
9
+ // Best-effort: any failure MUST NOT break npm install. Each step is in
10
+ // its own try/catch; we just log and move on.
11
+ //
12
+ // No .lnk file, no Start Menu shortcut — just the protocol handler.
13
+
14
+ const path = require('node:path');
15
+ const fs = require('node:fs');
16
+ const { spawnSync } = require('node:child_process');
17
+
18
+ function log(msg) { process.stdout.write(`[ccsm install] ${msg}\n`); }
19
+ function warn(msg) { process.stderr.write(`[ccsm install] ${msg}\n`); }
20
+
21
+ if (process.platform !== 'win32') {
22
+ log('non-Windows · skipping ccsm:// registration');
23
+ process.exit(0);
24
+ }
25
+ // Note: we DO register on npx-cache installs too (not just global). The
26
+ // npx cache path is stable across re-runs of the same package, and even
27
+ // if the user later cleans the cache, the only consequence is the
28
+ // OfflineBanner button no-ops — nothing actively broken. Registering
29
+ // always means a first-time `npx @bakapiano/ccsm` gets the full "click
30
+ // to wake" UX without needing a separate `npm i -g`.
31
+
32
+ function findCcsmCmd() {
33
+ const prefix = process.env.npm_config_prefix
34
+ || (() => {
35
+ try {
36
+ const r = spawnSync('npm', ['config', 'get', 'prefix'], { encoding: 'utf8', shell: true });
37
+ return r.stdout?.trim() || null;
38
+ } catch { return null; }
39
+ })();
40
+ if (!prefix) return null;
41
+ const candidate = path.join(prefix, 'ccsm.cmd');
42
+ return fs.existsSync(candidate) ? candidate : null;
43
+ }
44
+
45
+ // Write a tiny VBScript wrapper that ccsm:// dispatches into. Why VBS:
46
+ // wscript.exe is a Windows-subsystem host (no console window), and
47
+ // `Shell.Run(..., 0, False)` launches the target completely hidden — so
48
+ // when the user clicks ccsm://start, NOTHING flashes on screen, the
49
+ // backend just appears in the next health probe.
50
+ function writeLauncherVbs(ccsmCmd) {
51
+ const home = process.env.LOCALAPPDATA || process.env.APPDATA;
52
+ if (!home) throw new Error('no LOCALAPPDATA/APPDATA env var');
53
+ const dir = path.join(home, 'ccsm');
54
+ fs.mkdirSync(dir, { recursive: true });
55
+ const vbsPath = path.join(dir, 'launcher.vbs');
56
+ // Escape any double-quotes in the cmd path (rare but possible).
57
+ const cmdEsc = ccsmCmd.replace(/"/g, '""');
58
+ const vbs = [
59
+ "' ccsm protocol launcher · invoked by wscript.exe via the registered",
60
+ "' ccsm:// URL handler. Spawns ccsm.cmd with WindowStyle 0 (hidden) +",
61
+ "' bWaitOnReturn=False (async), so the click leaves zero visible trace.",
62
+ 'If WScript.Arguments.Count >= 1 Then',
63
+ ' arg = WScript.Arguments(0)',
64
+ 'Else',
65
+ ' arg = ""',
66
+ 'End If',
67
+ 'Set sh = CreateObject("WScript.Shell")',
68
+ `sh.Run """${cmdEsc}"" """ & arg & """", 0, False`,
69
+ '',
70
+ ].join('\r\n');
71
+ fs.writeFileSync(vbsPath, vbs, { encoding: 'utf8' });
72
+ return vbsPath;
73
+ }
74
+
75
+ function registerProtocol(vbsPath) {
76
+ // wscript.exe is a no-console host. The protocol-registered command
77
+ // hands the entire ccsm:// URL to launcher.vbs as argv[0]; the VBS
78
+ // forwards it to ccsm.cmd "%1" with a hidden window.
79
+ const command = `wscript.exe "${vbsPath}" "%1"`;
80
+ const root = 'HKCU\\Software\\Classes\\ccsm';
81
+ const calls = [
82
+ ['add', root, '/ve', '/d', 'URL:ccsm protocol', '/f'],
83
+ ['add', root, '/v', 'URL Protocol', '/d', '', '/f'],
84
+ ['add', `${root}\\shell\\open\\command`, '/ve', '/d', command, '/f'],
85
+ ];
86
+ for (const args of calls) {
87
+ const r = spawnSync('reg.exe', args, { windowsHide: true });
88
+ if (r.status !== 0) {
89
+ throw new Error(`reg ${args.join(' ')} → exit ${r.status}: ${r.stderr?.toString() || ''}`);
90
+ }
91
+ }
92
+ }
93
+
94
+ const ccsmCmd = (() => {
95
+ try { return findCcsmCmd(); } catch { return null; }
96
+ })();
97
+ if (!ccsmCmd) {
98
+ warn('could not locate ccsm.cmd · skipping protocol registration');
99
+ process.exit(0);
100
+ }
101
+
102
+ try {
103
+ const vbsPath = writeLauncherVbs(ccsmCmd);
104
+ registerProtocol(vbsPath);
105
+ log(`launcher · ${vbsPath}`);
106
+ log(`ccsm:// protocol registered (silent · via wscript.exe)`);
107
+ log('open https://bakapiano.github.io/cssm/v1/ and click "Start ccsm" on the offline banner to launch the backend.');
108
+ } catch (e) {
109
+ warn(`failed · ${e.message}`);
110
+ warn('the hosted frontend\'s "Start ccsm" button will not be able to launch the backend. You can still run `ccsm` manually in a terminal.');
111
+ }
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Reverse of install.js · unregister ccsm:// and ask any running backend
5
+ // to shut down. Triggered by `npm uninstall -g @bakapiano/ccsm`.
6
+
7
+ const path = require('node:path');
8
+ const fs = require('node:fs');
9
+ const http = require('node:http');
10
+ const { spawnSync } = require('node:child_process');
11
+
12
+ function log(msg) { process.stdout.write(`[ccsm uninstall] ${msg}\n`); }
13
+ function warn(msg) { process.stderr.write(`[ccsm uninstall] ${msg}\n`); }
14
+
15
+ if (process.platform !== 'win32') process.exit(0);
16
+
17
+ function shutdownIfRunning() {
18
+ return new Promise((resolve) => {
19
+ const req = http.request(
20
+ { hostname: 'localhost', port: 7777, path: '/api/shutdown', method: 'POST', timeout: 1500,
21
+ headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } },
22
+ (res) => { res.resume(); res.on('end', resolve); },
23
+ );
24
+ req.on('error', () => resolve());
25
+ req.on('timeout', () => { req.destroy(); resolve(); });
26
+ req.write('{}');
27
+ req.end();
28
+ });
29
+ }
30
+
31
+ function deleteRegKey() {
32
+ const r = spawnSync('reg.exe', ['delete', 'HKCU\\Software\\Classes\\ccsm', '/f'], { windowsHide: true });
33
+ // exit 1 means key didn't exist — fine.
34
+ if (r.status !== 0 && r.status !== 1) {
35
+ throw new Error(`reg delete → exit ${r.status}: ${r.stderr?.toString() || ''}`);
36
+ }
37
+ }
38
+
39
+ function deleteLauncherVbs() {
40
+ const home = process.env.LOCALAPPDATA || process.env.APPDATA;
41
+ if (!home) return;
42
+ const dir = path.join(home, 'ccsm');
43
+ const vbs = path.join(dir, 'launcher.vbs');
44
+ if (fs.existsSync(vbs)) fs.unlinkSync(vbs);
45
+ // Remove the (now-empty) folder if we created it.
46
+ try { fs.rmdirSync(dir); } catch {}
47
+ }
48
+
49
+ (async () => {
50
+ await shutdownIfRunning();
51
+ try { deleteRegKey(); log('ccsm:// protocol unregistered'); }
52
+ catch (e) { warn(`reg cleanup failed · ${e.message}`); }
53
+ try { deleteLauncherVbs(); log('launcher.vbs removed'); }
54
+ catch (e) { warn(`vbs cleanup failed · ${e.message}`); }
55
+ log('done.');
56
+ })();