@bakapiano/ccsm 0.14.0 → 0.15.1

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 (53) hide show
  1. package/CLAUDE.md +474 -475
  2. package/README.md +189 -190
  3. package/bin/ccsm.js +194 -194
  4. package/lib/cliActivity.js +118 -0
  5. package/lib/codexSeed.js +147 -0
  6. package/lib/config.js +205 -188
  7. package/lib/folders.js +105 -105
  8. package/lib/localCliSessions.js +489 -489
  9. package/lib/persistedSessions.js +144 -142
  10. package/lib/webTerminal.js +224 -224
  11. package/lib/workspace.js +230 -230
  12. package/package.json +57 -57
  13. package/public/css/base.css +99 -99
  14. package/public/css/cards.css +183 -183
  15. package/public/css/feedback.css +303 -303
  16. package/public/css/forms.css +405 -405
  17. package/public/css/layout.css +160 -160
  18. package/public/css/modal.css +190 -190
  19. package/public/css/responsive.css +10 -10
  20. package/public/css/sidebar.css +613 -608
  21. package/public/css/terminals.css +294 -294
  22. package/public/css/tokens.css +81 -81
  23. package/public/css/wco.css +98 -98
  24. package/public/css/widgets.css +1628 -1628
  25. package/public/index.html +111 -105
  26. package/public/js/api.js +296 -280
  27. package/public/js/components/AdoptModal.js +343 -343
  28. package/public/js/components/App.js +35 -35
  29. package/public/js/components/DirectoryPicker.js +203 -203
  30. package/public/js/components/EntityFormModal.js +141 -141
  31. package/public/js/components/Modal.js +51 -51
  32. package/public/js/components/OfflineBanner.js +93 -93
  33. package/public/js/components/PageTitleBar.js +13 -13
  34. package/public/js/components/Picker.js +179 -179
  35. package/public/js/components/Popover.js +55 -55
  36. package/public/js/components/Sidebar.js +299 -299
  37. package/public/js/components/TerminalView.js +314 -314
  38. package/public/js/components/useDragSort.js +67 -67
  39. package/public/js/dialog.js +67 -67
  40. package/public/js/icons.js +177 -177
  41. package/public/js/main.js +132 -132
  42. package/public/js/pages/AboutPage.js +173 -165
  43. package/public/js/pages/ConfigurePage.js +513 -475
  44. package/public/js/pages/LaunchPage.js +369 -369
  45. package/public/js/pages/SessionsPage.js +101 -97
  46. package/public/js/state.js +231 -231
  47. package/scripts/dev.js +44 -11
  48. package/scripts/install.js +158 -158
  49. package/scripts/restart-helper.js +96 -0
  50. package/scripts/upgrade-helper.js +6 -1
  51. package/server.js +1282 -1254
  52. package/lib/cliSessionWatcher.js +0 -275
  53. package/public/manifest.webmanifest +0 -15
package/public/js/api.js CHANGED
@@ -1,280 +1,296 @@
1
- // Fetch wrapper + every loader. Loaders push into signals from ./state.js.
2
- // Cross-origin (hosted frontend → local backend) flows through httpBase().
3
-
4
- import * as S from './state.js';
5
- import { httpBase } from './backend.js';
6
-
7
- export async function api(method, url, body) {
8
- const opts = { method, headers: { 'Content-Type': 'application/json' } };
9
- if (body !== undefined) opts.body = JSON.stringify(body);
10
- const r = await fetch(httpBase() + url, opts);
11
- const text = await r.text();
12
- let json;
13
- try { json = text ? JSON.parse(text) : {}; } catch { json = { raw: text }; }
14
- if (!r.ok) throw new Error(json.error || `HTTP ${r.status}`);
15
- return json;
16
- }
17
-
18
- export async function loadConfig() {
19
- const [cfg, caps] = await Promise.all([
20
- api('GET', '/api/config'),
21
- api('GET', '/api/capabilities').catch(() => ({ webTerminal: false })),
22
- ]);
23
- S.config.value = cfg;
24
- S.capabilities.value = caps;
25
- }
26
-
27
- // Update an existing CLI by id. patch is shallow-merged into the record.
28
- export async function updateCli(id, patch) {
29
- const cfg = S.config.value || (await api('GET', '/api/config'));
30
- const target = (cfg.clis || []).find((c) => c.id === id);
31
- // Built-in CLIs lock down structural fields (id + builtin flag) but
32
- // allow command edits — users routinely need to point at an absolute
33
- // path (e.g. C:\Users\you\.local\bin\claude.exe) or a wrapper script
34
- // when the bare name isn't on the spawn-time PATH.
35
- if (target?.builtin) {
36
- delete patch.id;
37
- delete patch.builtin;
38
- }
39
- const toArr = (v, fallback) => Array.isArray(v) ? v :
40
- typeof v === 'string' ? v.split(/\s+/).filter(Boolean) : fallback;
41
- const next = {
42
- ...cfg,
43
- clis: (cfg.clis || []).map((c) => c.id === id ? {
44
- ...c, ...patch,
45
- args: toArr(patch.args, c.args),
46
- resumeArgs: toArr(patch.resumeArgs, c.resumeArgs || []),
47
- shell: ['direct', 'pwsh', 'cmd'].includes(patch.shell ?? c.shell) ? (patch.shell ?? c.shell) : 'direct',
48
- } : c),
49
- };
50
- const saved = await api('PUT', '/api/config', next);
51
- S.config.value = saved;
52
- return id;
53
- }
54
-
55
- // Probe a (possibly-unsaved) CLI config: spawn its command with
56
- // `--version`, capture output, see if it looks like the claimed type.
57
- // `args` is intentionally ignored server-side — runtime flags can
58
- // disturb a quick probe.
59
- export async function testCli({ command, shell, type }) {
60
- return api('POST', '/api/clis/test', { command, shell, type });
61
- }
62
-
63
- export async function deleteCli(id) {
64
- const cfg = S.config.value || (await api('GET', '/api/config'));
65
- const target = (cfg.clis || []).find((c) => c.id === id);
66
- if (target?.builtin) throw new Error(`"${target.name}" is built-in and can't be deleted`);
67
- const clis = (cfg.clis || []).filter((c) => c.id !== id);
68
- if (clis.length === 0) throw new Error('cannot delete the last CLI');
69
- const next = { ...cfg, clis };
70
- if (next.defaultCliId === id) next.defaultCliId = clis[0].id;
71
- const saved = await api('PUT', '/api/config', next);
72
- S.config.value = saved;
73
- }
74
-
75
- export async function updateRepo(name, patch) {
76
- const cfg = S.config.value || (await api('GET', '/api/config'));
77
- const next = {
78
- ...cfg,
79
- repos: (cfg.repos || []).map((r) => r.name === name ? {
80
- ...r,
81
- name: (patch.name ?? r.name).trim(),
82
- url: (patch.url ?? r.url).trim(),
83
- defaultSelected: patch.defaultSelected ?? r.defaultSelected,
84
- } : r),
85
- };
86
- const saved = await api('PUT', '/api/config', next);
87
- S.config.value = saved;
88
- }
89
-
90
- export async function deleteRepo(name) {
91
- const cfg = S.config.value || (await api('GET', '/api/config'));
92
- const next = { ...cfg, repos: (cfg.repos || []).filter((r) => r.name !== name) };
93
- const saved = await api('PUT', '/api/config', next);
94
- S.config.value = saved;
95
- }
96
-
97
- export async function setDefaultCli(id) {
98
- const cfg = S.config.value || (await api('GET', '/api/config'));
99
- const saved = await api('PUT', '/api/config', { ...cfg, defaultCliId: id });
100
- S.config.value = saved;
101
- }
102
-
103
- // Add a new CLI to config.clis and return its id. Generates a fresh id
104
- // from the command name + an integer suffix when collisions exist.
105
- export async function createCli({ name, command, args, resumeArgs, shell, type }) {
106
- const cfg = S.config.value || (await api('GET', '/api/config'));
107
- const base = (name || command || 'cli').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'cli';
108
- let id = base, n = 1;
109
- while ((cfg.clis || []).some((c) => c.id === id)) { id = `${base}-${++n}`; }
110
- const toArr = (v) => Array.isArray(v) ? v : (typeof v === 'string' ? v.split(/\s+/).filter(Boolean) : []);
111
- const next = {
112
- ...cfg,
113
- clis: [...(cfg.clis || []), {
114
- id,
115
- name: (name || command || id).trim(),
116
- command: (command || '').trim(),
117
- args: toArr(args),
118
- resumeArgs: toArr(resumeArgs),
119
- shell: ['direct', 'pwsh', 'cmd'].includes(shell) ? shell : 'direct',
120
- type: ['claude', 'codex', 'other'].includes(type) ? type : 'other',
121
- }],
122
- };
123
- const saved = await api('PUT', '/api/config', next);
124
- S.config.value = saved;
125
- return id;
126
- }
127
-
128
- // Add a new repo to config.repos. Repos are addressed by name (which must
129
- // be unique). Returns the name on success, throws on duplicate.
130
- export async function createRepo({ name, url, defaultSelected }) {
131
- const cfg = S.config.value || (await api('GET', '/api/config'));
132
- const cleanName = (name || '').trim();
133
- const cleanUrl = (url || '').trim();
134
- if (!cleanName) throw new Error('repo name required');
135
- if (!cleanUrl) throw new Error('repo url required');
136
- if ((cfg.repos || []).some((r) => r.name === cleanName)) {
137
- throw new Error(`repo "${cleanName}" already exists`);
138
- }
139
- const next = {
140
- ...cfg,
141
- repos: [...(cfg.repos || []), {
142
- name: cleanName,
143
- url: cleanUrl,
144
- defaultSelected: !!defaultSelected,
145
- }],
146
- };
147
- const saved = await api('PUT', '/api/config', next);
148
- S.config.value = saved;
149
- return cleanName;
150
- }
151
-
152
- export async function loadSessions() {
153
- const r = await api('GET', '/api/sessions');
154
- S.sessions.value = r.sessions || [];
155
- try { localStorage.setItem('ccsm.sessions-cache', JSON.stringify(S.sessions.value)); } catch {}
156
- }
157
-
158
- export async function loadFolders() {
159
- const r = await api('GET', '/api/folders');
160
- S.folders.value = (r.folders || []).sort((a, b) => (a.order || 0) - (b.order || 0));
161
- try { localStorage.setItem('ccsm.folders-cache', JSON.stringify(S.folders.value)); } catch {}
162
- }
163
-
164
- export async function createFolder(name) {
165
- const r = await api('POST', '/api/folders', { name });
166
- await loadFolders();
167
- return r.folder;
168
- }
169
-
170
- export async function renameFolder(id, name) {
171
- const r = await api('PUT', `/api/folders/${id}`, { name });
172
- await loadFolders();
173
- return r.folder;
174
- }
175
-
176
- export async function deleteFolder(id) {
177
- await api('DELETE', `/api/folders/${id}`);
178
- await Promise.all([loadFolders(), loadSessions()]);
179
- }
180
-
181
- export async function reorderFolders(ids) {
182
- const r = await api('POST', '/api/folders/reorder', { ids });
183
- await loadFolders();
184
- return r.folders;
185
- }
186
-
187
- export async function setSessionFolder(sessionId, folderId) {
188
- await api('PUT', `/api/sessions/${sessionId}`, { folderId: folderId || null });
189
- await loadSessions();
190
- }
191
-
192
- export async function setSessionTitle(sessionId, title) {
193
- await api('PUT', `/api/sessions/${sessionId}`, { title });
194
- await loadSessions();
195
- }
196
-
197
- export async function deleteSession(sessionId) {
198
- await api('DELETE', `/api/sessions/${sessionId}`);
199
- await loadSessions();
200
- }
201
-
202
- // Per-session in-flight resume promise. Sidebar.onClick and the
203
- // SessionsPage auto-resume effect can both fire for the same exited
204
- // session in the same tick (clicking an exited row mounts SessionsPage
205
- // which runs its effect AND awaits Sidebar's own POST). Without this
206
- // dedup the backend gets two concurrent /resume requests and may spawn
207
- // two PTYs against the same record. Cleared on resolve/reject.
208
- const resumeInFlight = new Map(); // sessionId Promise
209
-
210
- export function resumeSession(sessionId) {
211
- const cached = resumeInFlight.get(sessionId);
212
- if (cached) return cached;
213
- const p = (async () => {
214
- const r = await api('POST', `/api/sessions/${sessionId}/resume`);
215
- await loadSessions();
216
- return r.launched;
217
- })();
218
- resumeInFlight.set(sessionId, p);
219
- p.finally(() => { resumeInFlight.delete(sessionId); });
220
- return p;
221
- }
222
-
223
- export async function loadWorkspaces() {
224
- const r = await api('GET', '/api/workspaces');
225
- S.workspaces.value = r.workspaces;
226
- }
227
-
228
- export async function deleteWorkspace(name) {
229
- await api('DELETE', `/api/workspaces/${encodeURIComponent(name)}`);
230
- }
231
-
232
- export async function refreshAll() {
233
- await Promise.all([
234
- loadSessions(),
235
- loadFolders(),
236
- loadWorkspaces(),
237
- ]);
238
- S.lastRefreshAt.value = Date.now();
239
- }
240
-
241
- // List existing CLI sessions discovered on disk for a given cli type.
242
- // Paginated: page 0 returns all currently-active sessions + the first
243
- // `limit` non-active (sorted mtime desc). Subsequent pages return the
244
- // next slice of non-active sessions.
245
- // Returns { sessions, totalActive, totalNonActive, total, offset, limit, hasMore }.
246
- export async function listLocalCliSessions(cliType, { offset = 0, limit = 30 } = {}) {
247
- const qs = `offset=${offset}&limit=${limit}`;
248
- const r = await api('GET', `/api/cli-sessions/${cliType}?${qs}`);
249
- return {
250
- sessions: r.sessions || [],
251
- totalActive: r.totalActive ?? 0,
252
- totalNonActive: r.totalNonActive ?? 0,
253
- total: r.total ?? (r.sessions?.length || 0),
254
- offset: r.offset ?? offset,
255
- limit: r.limit ?? limit,
256
- hasMore: !!r.hasMore,
257
- };
258
- }
259
-
260
- // Adopt an existing upstream CLI session into ccsm. Returns the created
261
- // (or existing) persistedSessions record.
262
- export async function adoptSession({ cliId, cliSessionId, cwd, title, folderId }) {
263
- const r = await api('POST', '/api/sessions/adopt', { cliId, cliSessionId, cwd, title, folderId });
264
- return r;
265
- }
266
-
267
- export async function pollHealth() {
268
- const ctrl = new AbortController();
269
- const t = setTimeout(() => ctrl.abort(), 3000);
270
- try {
271
- const r = await fetch(httpBase() + '/api/health', { signal: ctrl.signal });
272
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
273
- const j = await r.json();
274
- S.serverHealth.value = { state: 'online', version: j.version, pid: j.pid };
275
- } catch (e) {
276
- S.serverHealth.value = { state: 'offline', error: String(e.message || e) };
277
- } finally {
278
- clearTimeout(t);
279
- }
280
- }
1
+ // Fetch wrapper + every loader. Loaders push into signals from ./state.js.
2
+ // Cross-origin (hosted frontend → local backend) flows through httpBase().
3
+
4
+ import * as S from './state.js';
5
+ import { httpBase } from './backend.js';
6
+
7
+ export async function api(method, url, body) {
8
+ const opts = { method, headers: { 'Content-Type': 'application/json' } };
9
+ if (body !== undefined) opts.body = JSON.stringify(body);
10
+ const r = await fetch(httpBase() + url, opts);
11
+ const text = await r.text();
12
+ let json;
13
+ try { json = text ? JSON.parse(text) : {}; } catch { json = { raw: text }; }
14
+ if (!r.ok) throw new Error(json.error || `HTTP ${r.status}`);
15
+ return json;
16
+ }
17
+
18
+ export async function loadConfig() {
19
+ const [cfg, caps] = await Promise.all([
20
+ api('GET', '/api/config'),
21
+ api('GET', '/api/capabilities').catch(() => ({ webTerminal: false })),
22
+ ]);
23
+ S.config.value = cfg;
24
+ S.capabilities.value = caps;
25
+ }
26
+
27
+ // Update an existing CLI by id. patch is shallow-merged into the record.
28
+ export async function updateCli(id, patch) {
29
+ const cfg = S.config.value || (await api('GET', '/api/config'));
30
+ const target = (cfg.clis || []).find((c) => c.id === id);
31
+ // Built-in CLIs lock down structural fields (id + builtin flag) but
32
+ // allow command edits — users routinely need to point at an absolute
33
+ // path (e.g. C:\Users\you\.local\bin\claude.exe) or a wrapper script
34
+ // when the bare name isn't on the spawn-time PATH.
35
+ if (target?.builtin) {
36
+ delete patch.id;
37
+ delete patch.builtin;
38
+ }
39
+ const toArr = (v, fallback) => Array.isArray(v) ? v :
40
+ typeof v === 'string' ? v.split(/\s+/).filter(Boolean) : fallback;
41
+ const next = {
42
+ ...cfg,
43
+ clis: (cfg.clis || []).map((c) => c.id === id ? {
44
+ ...c, ...patch,
45
+ args: toArr(patch.args, c.args),
46
+ shell: ['direct', 'pwsh', 'cmd'].includes(patch.shell ?? c.shell) ? (patch.shell ?? c.shell) : 'direct',
47
+ } : c),
48
+ };
49
+ const saved = await api('PUT', '/api/config', next);
50
+ S.config.value = saved;
51
+ return id;
52
+ }
53
+
54
+ // Probe a (possibly-unsaved) CLI config: spawn its command with
55
+ // `--version`, capture output, see if it looks like the claimed type.
56
+ // `args` is intentionally ignored server-side runtime flags can
57
+ // disturb a quick probe.
58
+ export async function testCli({ command, shell, type }) {
59
+ return api('POST', '/api/clis/test', { command, shell, type });
60
+ }
61
+
62
+ export async function deleteCli(id) {
63
+ const cfg = S.config.value || (await api('GET', '/api/config'));
64
+ const target = (cfg.clis || []).find((c) => c.id === id);
65
+ if (target?.builtin) throw new Error(`"${target.name}" is built-in and can't be deleted`);
66
+ const clis = (cfg.clis || []).filter((c) => c.id !== id);
67
+ if (clis.length === 0) throw new Error('cannot delete the last CLI');
68
+ const next = { ...cfg, clis };
69
+ if (next.defaultCliId === id) next.defaultCliId = clis[0].id;
70
+ const saved = await api('PUT', '/api/config', next);
71
+ S.config.value = saved;
72
+ }
73
+
74
+ export async function updateRepo(name, patch) {
75
+ const cfg = S.config.value || (await api('GET', '/api/config'));
76
+ const next = {
77
+ ...cfg,
78
+ repos: (cfg.repos || []).map((r) => r.name === name ? {
79
+ ...r,
80
+ name: (patch.name ?? r.name).trim(),
81
+ url: (patch.url ?? r.url).trim(),
82
+ defaultSelected: patch.defaultSelected ?? r.defaultSelected,
83
+ } : r),
84
+ };
85
+ const saved = await api('PUT', '/api/config', next);
86
+ S.config.value = saved;
87
+ }
88
+
89
+ export async function deleteRepo(name) {
90
+ const cfg = S.config.value || (await api('GET', '/api/config'));
91
+ const next = { ...cfg, repos: (cfg.repos || []).filter((r) => r.name !== name) };
92
+ const saved = await api('PUT', '/api/config', next);
93
+ S.config.value = saved;
94
+ }
95
+
96
+ export async function setDefaultCli(id) {
97
+ const cfg = S.config.value || (await api('GET', '/api/config'));
98
+ const saved = await api('PUT', '/api/config', { ...cfg, defaultCliId: id });
99
+ S.config.value = saved;
100
+ }
101
+
102
+ // Add a new CLI to config.clis and return its id. Generates a fresh id
103
+ // from the command name + an integer suffix when collisions exist.
104
+ export async function createCli({ name, command, args, shell, type }) {
105
+ const cfg = S.config.value || (await api('GET', '/api/config'));
106
+ const base = (name || command || 'cli').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'cli';
107
+ let id = base, n = 1;
108
+ while ((cfg.clis || []).some((c) => c.id === id)) { id = `${base}-${++n}`; }
109
+ const toArr = (v) => Array.isArray(v) ? v : (typeof v === 'string' ? v.split(/\s+/).filter(Boolean) : []);
110
+ const next = {
111
+ ...cfg,
112
+ clis: [...(cfg.clis || []), {
113
+ id,
114
+ name: (name || command || id).trim(),
115
+ command: (command || '').trim(),
116
+ args: toArr(args),
117
+ shell: ['direct', 'pwsh', 'cmd'].includes(shell) ? shell : 'direct',
118
+ type: ['claude', 'codex', 'copilot', 'other'].includes(type) ? type : 'other',
119
+ }],
120
+ };
121
+ const saved = await api('PUT', '/api/config', next);
122
+ S.config.value = saved;
123
+ return id;
124
+ }
125
+
126
+ // Add a new repo to config.repos. Repos are addressed by name (which must
127
+ // be unique). Returns the name on success, throws on duplicate.
128
+ export async function createRepo({ name, url, defaultSelected }) {
129
+ const cfg = S.config.value || (await api('GET', '/api/config'));
130
+ const cleanName = (name || '').trim();
131
+ const cleanUrl = (url || '').trim();
132
+ if (!cleanName) throw new Error('repo name required');
133
+ if (!cleanUrl) throw new Error('repo url required');
134
+ if ((cfg.repos || []).some((r) => r.name === cleanName)) {
135
+ throw new Error(`repo "${cleanName}" already exists`);
136
+ }
137
+ const next = {
138
+ ...cfg,
139
+ repos: [...(cfg.repos || []), {
140
+ name: cleanName,
141
+ url: cleanUrl,
142
+ defaultSelected: !!defaultSelected,
143
+ }],
144
+ };
145
+ const saved = await api('PUT', '/api/config', next);
146
+ S.config.value = saved;
147
+ return cleanName;
148
+ }
149
+
150
+ export async function loadSessions() {
151
+ const r = await api('GET', '/api/sessions');
152
+ S.sessions.value = r.sessions || [];
153
+ try { localStorage.setItem('ccsm.sessions-cache', JSON.stringify(S.sessions.value)); } catch {}
154
+ }
155
+
156
+ export async function loadFolders() {
157
+ const r = await api('GET', '/api/folders');
158
+ S.folders.value = (r.folders || []).sort((a, b) => (a.order || 0) - (b.order || 0));
159
+ try { localStorage.setItem('ccsm.folders-cache', JSON.stringify(S.folders.value)); } catch {}
160
+ }
161
+
162
+ export async function createFolder(name) {
163
+ const r = await api('POST', '/api/folders', { name });
164
+ await loadFolders();
165
+ return r.folder;
166
+ }
167
+
168
+ export async function renameFolder(id, name) {
169
+ const r = await api('PUT', `/api/folders/${id}`, { name });
170
+ await loadFolders();
171
+ return r.folder;
172
+ }
173
+
174
+ export async function deleteFolder(id) {
175
+ await api('DELETE', `/api/folders/${id}`);
176
+ await Promise.all([loadFolders(), loadSessions()]);
177
+ }
178
+
179
+ export async function reorderFolders(ids) {
180
+ const r = await api('POST', '/api/folders/reorder', { ids });
181
+ await loadFolders();
182
+ return r.folders;
183
+ }
184
+
185
+ export async function setSessionFolder(sessionId, folderId) {
186
+ await api('PUT', `/api/sessions/${sessionId}`, { folderId: folderId || null });
187
+ await loadSessions();
188
+ }
189
+
190
+ export async function setSessionTitle(sessionId, title) {
191
+ await api('PUT', `/api/sessions/${sessionId}`, { title });
192
+ await loadSessions();
193
+ }
194
+
195
+ export async function deleteSession(sessionId) {
196
+ await api('DELETE', `/api/sessions/${sessionId}`);
197
+ await loadSessions();
198
+ }
199
+
200
+ // Per-session in-flight resume promise. Sidebar.onClick and the
201
+ // SessionsPage auto-resume effect can both fire for the same exited
202
+ // session in the same tick (clicking an exited row mounts SessionsPage
203
+ // which runs its effect AND awaits Sidebar's own POST). Without this
204
+ // dedup the backend gets two concurrent /resume requests and may spawn
205
+ // two PTYs against the same record. Cleared on resolve/reject.
206
+ const resumeInFlight = new Map(); // sessionId Promise
207
+ // Sticky failure cache: once a resume fails, subsequent calls reject
208
+ // immediately with the cached error until clearResumeFailure(id) is
209
+ // called. Stops the SessionsPage auto-resume effect from looping on a
210
+ // session whose CLI keeps exiting (bad command, missing flag, etc.).
211
+ const resumeFailed = new Map(); // sessionId → Error
212
+
213
+ export function clearResumeFailure(sessionId) {
214
+ resumeFailed.delete(sessionId);
215
+ }
216
+
217
+ export function resumeSession(sessionId) {
218
+ const failed = resumeFailed.get(sessionId);
219
+ if (failed) return Promise.reject(failed);
220
+ const cached = resumeInFlight.get(sessionId);
221
+ if (cached) return cached;
222
+ const p = (async () => {
223
+ const r = await api('POST', `/api/sessions/${sessionId}/resume`);
224
+ await loadSessions();
225
+ return r.launched;
226
+ })();
227
+ resumeInFlight.set(sessionId, p);
228
+ p.then(
229
+ () => { resumeInFlight.delete(sessionId); },
230
+ (e) => { resumeInFlight.delete(sessionId); resumeFailed.set(sessionId, e); },
231
+ );
232
+ return p;
233
+ }
234
+
235
+ export async function loadWorkspaces() {
236
+ const r = await api('GET', '/api/workspaces');
237
+ S.workspaces.value = r.workspaces;
238
+ }
239
+
240
+ export async function deleteWorkspace(name) {
241
+ await api('DELETE', `/api/workspaces/${encodeURIComponent(name)}`);
242
+ }
243
+
244
+ export async function refreshAll() {
245
+ await Promise.all([
246
+ loadSessions(),
247
+ loadFolders(),
248
+ loadWorkspaces(),
249
+ ]);
250
+ S.lastRefreshAt.value = Date.now();
251
+ }
252
+
253
+ // List existing CLI sessions discovered on disk for a given cli type.
254
+ // Paginated: page 0 returns all currently-active sessions + the first
255
+ // `limit` non-active (sorted mtime desc). Subsequent pages return the
256
+ // next slice of non-active sessions.
257
+ // Returns { sessions, totalActive, totalNonActive, total, offset, limit, hasMore }.
258
+ export async function listLocalCliSessions(cliType, { offset = 0, limit = 30 } = {}) {
259
+ const qs = `offset=${offset}&limit=${limit}`;
260
+ const r = await api('GET', `/api/cli-sessions/${cliType}?${qs}`);
261
+ return {
262
+ sessions: r.sessions || [],
263
+ totalActive: r.totalActive ?? 0,
264
+ totalNonActive: r.totalNonActive ?? 0,
265
+ total: r.total ?? (r.sessions?.length || 0),
266
+ offset: r.offset ?? offset,
267
+ limit: r.limit ?? limit,
268
+ hasMore: !!r.hasMore,
269
+ };
270
+ }
271
+
272
+ // Adopt an existing upstream CLI session into ccsm. Returns the created
273
+ // (or existing) persistedSessions record.
274
+ export async function adoptSession({ cliId, cliSessionId, cwd, title, folderId }) {
275
+ const r = await api('POST', '/api/sessions/adopt', { cliId, cliSessionId, cwd, title, folderId });
276
+ return r;
277
+ }
278
+
279
+ export async function restartBackend() {
280
+ return api('POST', '/api/restart');
281
+ }
282
+
283
+ export async function pollHealth() {
284
+ const ctrl = new AbortController();
285
+ const t = setTimeout(() => ctrl.abort(), 3000);
286
+ try {
287
+ const r = await fetch(httpBase() + '/api/health', { signal: ctrl.signal });
288
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
289
+ const j = await r.json();
290
+ S.serverHealth.value = { state: 'online', version: j.version, pid: j.pid };
291
+ } catch (e) {
292
+ S.serverHealth.value = { state: 'offline', error: String(e.message || e) };
293
+ } finally {
294
+ clearTimeout(t);
295
+ }
296
+ }