claude-code-session-manager 0.131.0 → 0.133.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/README.md +3 -3
- package/dist/assets/{AgentLibrary-CYXre0J-.js → AgentLibrary-DOAG-mcG.js} +1 -1
- package/dist/assets/{AppSettings-xNSfCj8e.js → AppSettings-BHKM_AKh.js} +2 -2
- package/dist/assets/{Button-BWljh5IK.js → Button-CmO1wmPw.js} +1 -1
- package/dist/assets/{DocumentEditorPane-FUC2hZlp.js → DocumentEditorPane-8QMNrNRt.js} +1 -1
- package/dist/assets/{Extensions-CsyUoklz.js → Extensions-Boo21B3b.js} +2 -2
- package/dist/assets/{History-BvNmY9OQ.js → History-C4epd1hp.js} +1 -1
- package/dist/assets/{Library-DVXk77zA.js → Library-CrgzRQzL.js} +1 -1
- package/dist/assets/{ListDetail-DAAx__24.js → ListDetail-DA7y1DQ-.js} +1 -1
- package/dist/assets/{Panel-g2D-e-RM.js → Panel-D-WMBhKH.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BDuHJwaO.js → ProjectClaudeConfig-CuUADpIu.js} +1 -1
- package/dist/assets/{ProvenanceBadge-wew4_nf3.js → ProvenanceBadge-B7AsoRk6.js} +1 -1
- package/dist/assets/{Scheduler-CbeUIqD-.js → Scheduler-C86gRh51.js} +1 -1
- package/dist/assets/{Settings-B23RsRfm.js → Settings-B4Q9DwVS.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BxQPCfsg.js → SkillReferenceGraph-DX4ZgvlY.js} +1 -1
- package/dist/assets/{Skills-4AR2FQrI.js → Skills-DqKI37yi.js} +1 -1
- package/dist/assets/{SourceChip-jrC0vjfw.js → SourceChip-C974LROr.js} +1 -1
- package/dist/assets/{SystemPrompt-hHoBEnYb.js → SystemPrompt-C502jIwO.js} +1 -1
- package/dist/assets/{TiptapBody-FkUqxO9u.js → TiptapBody-DwNXN6Ki.js} +1 -1
- package/dist/assets/{Toggle-DQMNWZKT.js → Toggle-C2OsxnPK.js} +1 -1
- package/dist/assets/{ViewTabs-DGU0ZuxB.js → ViewTabs-DBxKGbAK.js} +1 -1
- package/dist/assets/{VoiceButton-BPPvDllh.js → VoiceButton-C680wpmX.js} +1 -1
- package/dist/assets/{historyTotals-D8Oc3wUK.js → historyTotals-Cz-VYPEc.js} +1 -1
- package/dist/assets/{index-oXqzajWV.css → index-CMwAikUb.css} +1 -1
- package/dist/assets/index-Dh5geJe3.js +3111 -0
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +428 -414
- package/package.json +1 -1
- package/scripts/scheduler-mcp-server.cjs +12 -4
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +77 -14
- package/src/main/index.cjs +15 -0
- package/src/main/ipcSchemas.cjs +54 -0
- package/src/main/lib/CLAUDE.md +2 -0
- package/src/main/lib/agent-cli/adapters/antigravity.cjs +147 -0
- package/src/main/lib/agent-cli/adapters/codex.cjs +170 -0
- package/src/main/lib/agent-cli/adapters/cursor.cjs +138 -0
- package/src/main/lib/agent-cli/adapters/gemini.cjs +119 -0
- package/src/main/lib/agent-cli/adapters/opencode.cjs +117 -0
- package/src/main/lib/agent-cli/agentCliEvents.cjs +94 -0
- package/src/main/lib/agent-cli/agentCliIpc.cjs +109 -0
- package/src/main/lib/agent-cli/agentCliRegistry.cjs +213 -0
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +152 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +99 -0
- package/src/main/lib/app-preview/appPreviewIpc.cjs +125 -0
- package/src/main/lib/app-preview/appPreviewManager.cjs +317 -0
- package/src/main/lib/app-preview/appPreviewScripts.cjs +106 -0
- package/src/main/lib/app-preview/appPreviewSweep.cjs +92 -0
- package/src/main/lib/chatBootRecovery.cjs +41 -1
- package/src/main/lib/claude/agentEffortResolve.cjs +11 -3
- package/src/main/lib/epic/activeIndexMerge.cjs +25 -2
- package/src/main/lib/epic/archivedTranscript.cjs +39 -6
- package/src/main/lib/epic/epicChanges.cjs +466 -0
- package/src/main/lib/epic/epicMint.cjs +45 -1
- package/src/main/lib/epic/epicReopen.cjs +8 -2
- package/src/main/lib/epic/epicSpawnPlan.cjs +12 -0
- package/src/main/lib/epic/epicWorktreeMerge.cjs +39 -4
- package/src/main/lib/epic/promptSessionsCreateEpic.cjs +9 -4
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
- package/src/main/lib/git/gitExec.cjs +9 -1
- package/src/main/lib/git/gitWorktree.cjs +94 -0
- package/src/main/lib/git/unifiedDiff.cjs +207 -0
- package/src/main/lib/mcpToolCatalog.cjs +15 -6
- package/src/main/lib/mdDocCensus.cjs +364 -0
- package/src/main/lib/mdDocRefs.cjs +249 -0
- package/src/main/lib/mdNetworkScan.cjs +158 -15
- package/src/main/lib/persona-macro/builtinMacros.cjs +17 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +4 -1
- package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
- package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
- package/src/main/lib/prd/prdCreate.cjs +7 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +10 -3
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/remoteTranscriptTail.cjs +23 -4
- package/src/main/lib/scheduler/landedSinceRun.cjs +2 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
- package/src/main/projectPages.cjs +19 -4
- package/src/main/promptSessionEvents.cjs +10 -6
- package/src/main/scheduler/gitTreeGuard.cjs +2 -1
- package/src/main/scheduler/prdParser.cjs +2 -1
- package/src/main/scheduler.cjs +7 -2
- package/src/main/transcripts.cjs +18 -4
- package/src/main/webRemote.cjs +10 -5
- package/src/preload/api.d.ts +150 -3
- package/src/preload/apiSurface.json +56 -0
- package/src/preload/index.cjs +22 -0
- package/dist/assets/index-9ajPMXBg.js +0 -3097
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* appPreviewIpc.cjs — IPC wiring for an Epic's "Run preview" dev server.
|
|
5
|
+
*
|
|
6
|
+
* One shared appPreviewManager (lazy singleton) owns every preview process;
|
|
7
|
+
* its state changes broadcast to the renderer as 'appPreview:changed'.
|
|
8
|
+
*
|
|
9
|
+
* The renderer sends only { cwd, epicId } — main resolves WHERE the dev
|
|
10
|
+
* server runs from the project's active index itself (the Epic's live
|
|
11
|
+
* worktree, else the project folder), never from a renderer-supplied path.
|
|
12
|
+
* A restorable worktree whose folder is gone is refused rather than silently
|
|
13
|
+
* previewing the main checkout.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const fs = require('node:fs');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
const { createAppPreviewManager } = require('./appPreviewManager.cjs');
|
|
19
|
+
const { listPreviewScripts } = require('./appPreviewScripts.cjs');
|
|
20
|
+
const { sendIfAlive } = require('../sendToRenderer.cjs');
|
|
21
|
+
|
|
22
|
+
let manager = null;
|
|
23
|
+
/** @type {() => any} */
|
|
24
|
+
let currentGetWindow = () => null;
|
|
25
|
+
|
|
26
|
+
function getAppPreviewManager() {
|
|
27
|
+
if (!manager) {
|
|
28
|
+
manager = createAppPreviewManager({
|
|
29
|
+
broadcast: (state) => sendIfAlive(currentGetWindow(), 'appPreview:changed', state),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return manager;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isUsableDir(dir, statImpl) {
|
|
36
|
+
try {
|
|
37
|
+
return statImpl(dir).isDirectory();
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* resolveAppPreviewDir({ cwd, epicId, deps }) — never throws.
|
|
45
|
+
* @returns {{ ok: true, dir: string, inWorktree: boolean } | { ok: false, error: string }}
|
|
46
|
+
*/
|
|
47
|
+
function resolveAppPreviewDir({ cwd, epicId, deps = {} } = {}) {
|
|
48
|
+
try {
|
|
49
|
+
const validatePath = deps.validatePath || require('../../config.cjs').validatePath;
|
|
50
|
+
const readActiveIndex = deps.readActiveIndex || require('../epic/epicMint.cjs').readActiveIndex;
|
|
51
|
+
const statSync = deps.statSync || fs.statSync;
|
|
52
|
+
validatePath(cwd);
|
|
53
|
+
const index = readActiveIndex(cwd);
|
|
54
|
+
const sessions = index && index.sessions ? index.sessions : {};
|
|
55
|
+
const session = Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId] : null;
|
|
56
|
+
if (!session) return { ok: false, error: `Session ${epicId} not found in this project` };
|
|
57
|
+
if (session.status !== 'active') {
|
|
58
|
+
return { ok: false, error: `Session ${epicId} is not active (status: ${session.status || 'unknown'})` };
|
|
59
|
+
}
|
|
60
|
+
const wt = session.worktree;
|
|
61
|
+
if (wt && wt.dir && wt.status !== 'merged' && wt.status !== 'disabled') {
|
|
62
|
+
if (isUsableDir(wt.dir, statSync)) return { ok: true, dir: wt.dir, inWorktree: true };
|
|
63
|
+
return {
|
|
64
|
+
ok: false,
|
|
65
|
+
error: `This session's worktree folder is missing (${wt.dir}). Open its Chat or Terminal once to restore it, then run the preview again.`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return { ok: true, dir: cwd, inWorktree: false };
|
|
69
|
+
} catch (e) {
|
|
70
|
+
return { ok: false, error: (e && e.message) || String(e) };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* ensureWorktreeDeps — a worktree restored after a reboot / tmp sweep
|
|
76
|
+
* (restoreEpicWorktree) is a bare `git worktree add` with no node_modules, so
|
|
77
|
+
* `npm run dev` would fail. Link the main checkout's dependency dirs when the
|
|
78
|
+
* worktree lacks node_modules and the main checkout has one. Never throws and
|
|
79
|
+
* never blocks the start: a skip or error is logged, and any resulting
|
|
80
|
+
* dev-server failure reaches the user as the preview's failed-state toast.
|
|
81
|
+
*/
|
|
82
|
+
async function ensureWorktreeDeps({ cwd, dir, inWorktree, deps = {} }) {
|
|
83
|
+
if (!inWorktree) return;
|
|
84
|
+
const existsSync = deps.existsSync || fs.existsSync;
|
|
85
|
+
const log = deps.log || ((...a) => console.warn(...a));
|
|
86
|
+
try {
|
|
87
|
+
if (existsSync(path.join(dir, 'node_modules')) || !existsSync(path.join(cwd, 'node_modules'))) return;
|
|
88
|
+
const link = deps.linkDependencyDirs || require('../git/worktreeDeps.cjs').linkDependencyDirs;
|
|
89
|
+
const res = await link({ mainCwd: cwd, worktreeCwd: dir });
|
|
90
|
+
if (res && Array.isArray(res.skipped) && res.skipped.includes('node_modules')) {
|
|
91
|
+
log(`[appPreview] node_modules was not linked into ${dir}; starting the preview anyway`);
|
|
92
|
+
}
|
|
93
|
+
} catch (e) {
|
|
94
|
+
log(`[appPreview] linking dependency dirs into ${dir} failed: ${(e && e.message) || String(e)}; starting the preview anyway`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @param {{ handle: (channel: string, fn: (...args: any[]) => any) => void }} ipcMain
|
|
100
|
+
* @param {{ getWindow?: () => any, deps?: { resolveDeps?: any, existsSync?: (p: string) => boolean, linkDependencyDirs?: (a: { mainCwd: string, worktreeCwd: string }) => any, getManager?: () => any, log?: (...a: any[]) => void } }} [opts]
|
|
101
|
+
*/
|
|
102
|
+
function registerAppPreviewHandlers(ipcMain, { getWindow, deps = {} } = {}) {
|
|
103
|
+
if (typeof getWindow === 'function') currentGetWindow = getWindow;
|
|
104
|
+
const getManager = deps.getManager || getAppPreviewManager;
|
|
105
|
+
const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
|
|
106
|
+
|
|
107
|
+
ipcMain.handle('appPreview:scripts', v(s.appPreviewScripts, ({ cwd, epicId }) => {
|
|
108
|
+
const r = resolveAppPreviewDir({ cwd, epicId, deps: deps.resolveDeps });
|
|
109
|
+
if (!r.ok) return { ok: false, error: r.error };
|
|
110
|
+
return { ...listPreviewScripts(r.dir), dir: r.dir, inWorktree: r.inWorktree };
|
|
111
|
+
}));
|
|
112
|
+
|
|
113
|
+
ipcMain.handle('appPreview:start', v(s.appPreviewStart, async ({ cwd, epicId, script }) => {
|
|
114
|
+
const r = resolveAppPreviewDir({ cwd, epicId, deps: deps.resolveDeps });
|
|
115
|
+
if (!r.ok) return { ok: false, error: r.error };
|
|
116
|
+
await ensureWorktreeDeps({ cwd, dir: r.dir, inWorktree: r.inWorktree, deps });
|
|
117
|
+
return getManager().start({ cwd, epicId, dir: r.dir, script });
|
|
118
|
+
}));
|
|
119
|
+
|
|
120
|
+
ipcMain.handle('appPreview:stop', v(s.appPreviewStop, ({ epicId }) => getManager().stop(epicId)));
|
|
121
|
+
|
|
122
|
+
ipcMain.handle('appPreview:list', () => getManager().list());
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = { getAppPreviewManager, resolveAppPreviewDir, ensureWorktreeDeps, registerAppPreviewHandlers };
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Single owner of every Epic "Run preview" dev-server process. At most one
|
|
4
|
+
// preview per Epic (the only bound — no machine-wide cap, per
|
|
5
|
+
// src/main/lib/CLAUDE.md). start() runs `npm run <script>` in the Epic's folder
|
|
6
|
+
// on a free port, watches stdout+stderr for the first loopback URL, opens it in
|
|
7
|
+
// the system browser, and stop()/stopAll() kill the whole process group, then
|
|
8
|
+
// sweep(epicId) kills any setsid escapee by its SM_PREVIEW_EPIC_ID env marker.
|
|
9
|
+
// IPC, Epic-close and app-quit wiring live in later modules.
|
|
10
|
+
|
|
11
|
+
const { killTree: defaultKillTree, detachedSpawnOpts } = require('../process/killTree.cjs');
|
|
12
|
+
const { cleanChildEnv, pathWithUserBins } = require('../process/cleanEnv.cjs');
|
|
13
|
+
const { resolveSpawn: defaultResolveSpawn } = require('../process/winSpawn.cjs');
|
|
14
|
+
const { createHeadTailBuffer } = require('../util/headTailBuffer.cjs');
|
|
15
|
+
const { killPreviewProcesses } = require('./appPreviewSweep.cjs');
|
|
16
|
+
const {
|
|
17
|
+
isValidScriptName,
|
|
18
|
+
listPreviewScripts,
|
|
19
|
+
detectLocalUrl,
|
|
20
|
+
stripAnsi,
|
|
21
|
+
findFreePort: defaultFindFreePort,
|
|
22
|
+
} = require('./appPreviewScripts.cjs');
|
|
23
|
+
|
|
24
|
+
const RECENT_MAX = 4096;
|
|
25
|
+
const ERROR_BUFFER_MAX = 16384;
|
|
26
|
+
const TAIL_LINES = 8;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {'starting'|'running'|'failed'|'stopped'} AppPreviewStatus
|
|
30
|
+
* @typedef {{ epicId: string, cwd: string, dir: string, script: string, command: string,
|
|
31
|
+
* port: number, url: string|null, status: AppPreviewStatus, error: string|null,
|
|
32
|
+
* pid: number|null, startedAt: string }} AppPreviewState
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
function createAppPreviewManager(deps = {}) {
|
|
36
|
+
const spawn = deps.spawn || require('node:child_process').spawn;
|
|
37
|
+
const killTree = deps.killTree || defaultKillTree;
|
|
38
|
+
const sweep = deps.sweep || killPreviewProcesses;
|
|
39
|
+
const openExternal = deps.openExternal || ((url) => require('electron').shell.openExternal(url));
|
|
40
|
+
const broadcast = deps.broadcast || (() => {});
|
|
41
|
+
const findFreePort = deps.findFreePort || defaultFindFreePort;
|
|
42
|
+
const listScripts = deps.listScripts || listPreviewScripts;
|
|
43
|
+
const resolveSpawn = deps.resolveSpawn || defaultResolveSpawn;
|
|
44
|
+
const platform = deps.platform || process.platform;
|
|
45
|
+
const urlTimeoutMs = Number.isFinite(deps.urlTimeoutMs) ? deps.urlTimeoutMs : 90000;
|
|
46
|
+
const killGraceMs = Number.isFinite(deps.killGraceMs) ? deps.killGraceMs : 5000;
|
|
47
|
+
const now = deps.now || Date.now;
|
|
48
|
+
const log = deps.log || ((msg) => { try { console.warn(msg); } catch { /* ignore */ } });
|
|
49
|
+
|
|
50
|
+
/** epicId -> entry */
|
|
51
|
+
const entries = new Map();
|
|
52
|
+
/** epicId -> in-flight start promise (before spawn) */
|
|
53
|
+
const pending = new Map();
|
|
54
|
+
/** epicIds whose pending start was cancelled by stop/stopAll */
|
|
55
|
+
const cancelled = new Set();
|
|
56
|
+
|
|
57
|
+
const copy = (state) => ({ ...state });
|
|
58
|
+
const emit = (entry) => {
|
|
59
|
+
try { broadcast(copy(entry.state)); } catch (e) { log(`[appPreview] broadcast failed: ${e && e.message}`); }
|
|
60
|
+
};
|
|
61
|
+
const isLive = (entry) => !!entry && !!entry.child && !entry.exited;
|
|
62
|
+
// Kill processes that left the preview's process group (setsid). Skipped when
|
|
63
|
+
// a newer preview of the same Epic replaced this entry — it would hit that one.
|
|
64
|
+
const sweepEpic = (entry) => {
|
|
65
|
+
if (entries.get(entry.state.epicId) !== entry) return;
|
|
66
|
+
try { sweep(entry.state.epicId); } catch (e) { log(`[appPreview] sweep failed: ${e && e.message}`); }
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
function clearTimers(entry) {
|
|
70
|
+
if (entry.urlTimer) { clearTimeout(entry.urlTimer); entry.urlTimer = null; }
|
|
71
|
+
if (entry.killTimer) { clearTimeout(entry.killTimer); entry.killTimer = null; }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function tailLines(entry) {
|
|
75
|
+
return stripAnsi(entry.buffer.matchText())
|
|
76
|
+
.split(/\r\n|\r|\n/)
|
|
77
|
+
.map((l) => l.trimEnd())
|
|
78
|
+
.filter((l) => l.trim() !== '')
|
|
79
|
+
.slice(-TAIL_LINES)
|
|
80
|
+
.join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function withTail(entry, msg) {
|
|
84
|
+
const tail = tailLines(entry);
|
|
85
|
+
return tail ? `${msg}\n${tail}` : msg;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function fail(entry, cause) {
|
|
89
|
+
clearTimers(entry);
|
|
90
|
+
const { script } = entry.state;
|
|
91
|
+
entry.state = { ...entry.state, status: 'failed', error: withTail(entry, `npm run ${script} failed: ${cause}`) };
|
|
92
|
+
emit(entry);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function markDead(entry) {
|
|
96
|
+
entry.exited = true;
|
|
97
|
+
entry.child = null;
|
|
98
|
+
entry.state = { ...entry.state, pid: null };
|
|
99
|
+
clearTimers(entry);
|
|
100
|
+
const waiters = entry.stopWaiters.splice(0);
|
|
101
|
+
for (const w of waiters) w({ ok: true });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function onOutput(entry, chunk) {
|
|
105
|
+
const text = typeof chunk === 'string' ? chunk : String(chunk);
|
|
106
|
+
entry.buffer.append(text);
|
|
107
|
+
if (entry.state.status !== 'starting') return;
|
|
108
|
+
entry.recent = (entry.recent + text).slice(-RECENT_MAX);
|
|
109
|
+
const url = detectLocalUrl(entry.recent);
|
|
110
|
+
if (!url) return;
|
|
111
|
+
if (entry.urlTimer) { clearTimeout(entry.urlTimer); entry.urlTimer = null; }
|
|
112
|
+
entry.state = { ...entry.state, status: 'running', url };
|
|
113
|
+
emit(entry);
|
|
114
|
+
try {
|
|
115
|
+
Promise.resolve(openExternal(url)).catch((e) => log(`[appPreview] openExternal(${url}) failed: ${e && e.message}`));
|
|
116
|
+
} catch (e) {
|
|
117
|
+
log(`[appPreview] openExternal(${url}) failed: ${e && e.message}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function onExit(entry, code, signal) {
|
|
122
|
+
if (entry.exited) return;
|
|
123
|
+
const prev = entry.state.status;
|
|
124
|
+
markDead(entry);
|
|
125
|
+
sweepEpic(entry);
|
|
126
|
+
const how = signal ? `signal ${signal}` : `code ${code}`;
|
|
127
|
+
if (entry.stopRequested) {
|
|
128
|
+
if (prev !== 'stopped' || entry.state.error !== null) {
|
|
129
|
+
entry.state = { ...entry.state, status: 'stopped', error: null };
|
|
130
|
+
emit(entry);
|
|
131
|
+
}
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (prev === 'starting') {
|
|
135
|
+
fail(entry, `exited with ${how} before printing a local URL`);
|
|
136
|
+
} else if (prev === 'running') {
|
|
137
|
+
entry.state = {
|
|
138
|
+
...entry.state,
|
|
139
|
+
status: 'stopped',
|
|
140
|
+
error: withTail(entry, `Preview stopped unexpectedly (npm run ${entry.state.script} exited with ${how})`),
|
|
141
|
+
};
|
|
142
|
+
emit(entry);
|
|
143
|
+
} else {
|
|
144
|
+
emit(entry); // already failed/stopped: publish pid: null
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function onError(entry, err) {
|
|
149
|
+
const cause = (err && (err.code ? `${err.code}: ${err.message}` : err.message)) || String(err);
|
|
150
|
+
const noProcess = !entry.child || entry.child.pid === undefined;
|
|
151
|
+
if (noProcess) markDead(entry);
|
|
152
|
+
if (entry.state.status === 'starting') fail(entry, cause);
|
|
153
|
+
else log(`[appPreview] ${entry.state.epicId}: child error: ${cause}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function doStart({ cwd, epicId, dir, script }) {
|
|
157
|
+
let port;
|
|
158
|
+
try {
|
|
159
|
+
port = await findFreePort();
|
|
160
|
+
} catch (e) {
|
|
161
|
+
return { ok: false, error: `Could not allocate a port for the preview: ${e && e.message}` };
|
|
162
|
+
}
|
|
163
|
+
if (cancelled.has(epicId)) {
|
|
164
|
+
cancelled.delete(epicId);
|
|
165
|
+
return { ok: false, error: 'Preview start was cancelled' };
|
|
166
|
+
}
|
|
167
|
+
const scripts = listScripts(dir);
|
|
168
|
+
const found = scripts && scripts.ok ? scripts.scripts.find((s) => s.name === script) : null;
|
|
169
|
+
const command = found ? found.command : '';
|
|
170
|
+
const env = cleanChildEnv({
|
|
171
|
+
PATH: pathWithUserBins({ platform }),
|
|
172
|
+
PORT: String(port),
|
|
173
|
+
BROWSER: 'none',
|
|
174
|
+
SM_PROC_ROLE: 'preview',
|
|
175
|
+
SM_PREVIEW_EPIC_ID: String(epicId),
|
|
176
|
+
SM_PREVIEW_OWNER_PID: String(process.pid),
|
|
177
|
+
});
|
|
178
|
+
const resolved = resolveSpawn('npm', ['run', script], { platform, env });
|
|
179
|
+
const opts = {
|
|
180
|
+
cwd: dir,
|
|
181
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
182
|
+
...detachedSpawnOpts({ platform }),
|
|
183
|
+
env,
|
|
184
|
+
};
|
|
185
|
+
if (resolved.windowsVerbatimArguments) opts.windowsVerbatimArguments = true;
|
|
186
|
+
|
|
187
|
+
const entry = {
|
|
188
|
+
state: {
|
|
189
|
+
epicId, cwd, dir, script, command, port,
|
|
190
|
+
url: null, status: 'starting', error: null, pid: null,
|
|
191
|
+
startedAt: new Date(now()).toISOString(),
|
|
192
|
+
},
|
|
193
|
+
child: null,
|
|
194
|
+
exited: false,
|
|
195
|
+
urlTimer: null,
|
|
196
|
+
killTimer: null,
|
|
197
|
+
stopRequested: false,
|
|
198
|
+
stopWaiters: [],
|
|
199
|
+
buffer: createHeadTailBuffer(ERROR_BUFFER_MAX),
|
|
200
|
+
recent: '',
|
|
201
|
+
};
|
|
202
|
+
entries.set(epicId, entry);
|
|
203
|
+
|
|
204
|
+
let child;
|
|
205
|
+
try {
|
|
206
|
+
child = spawn(resolved.command, resolved.args, opts);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
entry.exited = true;
|
|
209
|
+
fail(entry, (e && e.message) || String(e));
|
|
210
|
+
return { ok: true, state: copy(entry.state) };
|
|
211
|
+
}
|
|
212
|
+
entry.child = child;
|
|
213
|
+
entry.state = { ...entry.state, pid: Number.isInteger(child.pid) ? child.pid : null };
|
|
214
|
+
if (child.stdout) child.stdout.on('data', (c) => onOutput(entry, c));
|
|
215
|
+
if (child.stderr) child.stderr.on('data', (c) => onOutput(entry, c));
|
|
216
|
+
child.on('error', (err) => onError(entry, err));
|
|
217
|
+
child.on('exit', (code, signal) => onExit(entry, code, signal));
|
|
218
|
+
entry.urlTimer = setTimeout(() => {
|
|
219
|
+
entry.urlTimer = null;
|
|
220
|
+
if (entry.state.status !== 'starting') return;
|
|
221
|
+
const pid = entry.state.pid;
|
|
222
|
+
fail(entry, `no local URL printed within ${Math.round(urlTimeoutMs / 1000)}s`);
|
|
223
|
+
if (isLive(entry) && pid) killTree(pid, 'SIGKILL');
|
|
224
|
+
sweepEpic(entry);
|
|
225
|
+
}, urlTimeoutMs);
|
|
226
|
+
if (entry.urlTimer && typeof entry.urlTimer.unref === 'function') entry.urlTimer.unref();
|
|
227
|
+
emit(entry);
|
|
228
|
+
return { ok: true, state: copy(entry.state) };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** @returns {Promise<{ok:true, state:AppPreviewState} | {ok:false, error:string}>} */
|
|
232
|
+
async function start(input = {}) {
|
|
233
|
+
const { cwd, epicId, dir, script } = input;
|
|
234
|
+
if (typeof epicId !== 'string' || epicId === '') return { ok: false, error: 'Preview needs an Epic id' };
|
|
235
|
+
if (pending.has(epicId)) return pending.get(epicId);
|
|
236
|
+
const existing = entries.get(epicId);
|
|
237
|
+
if (existing && (existing.state.status === 'starting' || existing.state.status === 'running')) {
|
|
238
|
+
return { ok: true, state: copy(existing.state) };
|
|
239
|
+
}
|
|
240
|
+
if (!isValidScriptName(script)) return { ok: false, error: `Invalid script name: ${String(script)}` };
|
|
241
|
+
const scripts = listScripts(dir);
|
|
242
|
+
if (!scripts || !scripts.ok) return { ok: false, error: (scripts && scripts.error) || `Could not read scripts in ${dir}` };
|
|
243
|
+
if (!scripts.scripts.some((s) => s.name === script)) {
|
|
244
|
+
return { ok: false, error: `package.json in ${dir} has no "${script}" script` };
|
|
245
|
+
}
|
|
246
|
+
if (existing && isLive(existing)) {
|
|
247
|
+
// A failed preview whose process is still dying: finish killing it first.
|
|
248
|
+
killTree(existing.state.pid, 'SIGKILL');
|
|
249
|
+
sweepEpic(existing);
|
|
250
|
+
}
|
|
251
|
+
cancelled.delete(epicId);
|
|
252
|
+
const p = doStart({ cwd, epicId, dir, script }).finally(() => pending.delete(epicId));
|
|
253
|
+
pending.set(epicId, p);
|
|
254
|
+
return p;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** @returns {Promise<{ok:true}>} */
|
|
258
|
+
async function stop(epicId) {
|
|
259
|
+
if (pending.has(epicId)) {
|
|
260
|
+
await pending.get(epicId).catch(() => {});
|
|
261
|
+
}
|
|
262
|
+
const entry = entries.get(epicId);
|
|
263
|
+
if (!entry) return { ok: true };
|
|
264
|
+
if (!isLive(entry)) {
|
|
265
|
+
clearTimers(entry);
|
|
266
|
+
if (entry.state.status !== 'stopped' || entry.state.error !== null) {
|
|
267
|
+
entry.state = { ...entry.state, status: 'stopped', error: null };
|
|
268
|
+
emit(entry);
|
|
269
|
+
}
|
|
270
|
+
return { ok: true };
|
|
271
|
+
}
|
|
272
|
+
const done = new Promise((resolve) => entry.stopWaiters.push(resolve));
|
|
273
|
+
if (!entry.stopRequested) {
|
|
274
|
+
entry.stopRequested = true;
|
|
275
|
+
if (entry.urlTimer) { clearTimeout(entry.urlTimer); entry.urlTimer = null; }
|
|
276
|
+
const pid = entry.state.pid;
|
|
277
|
+
killTree(pid, 'SIGTERM');
|
|
278
|
+
entry.killTimer = setTimeout(() => {
|
|
279
|
+
entry.killTimer = null;
|
|
280
|
+
if (isLive(entry)) { killTree(pid, 'SIGKILL'); sweepEpic(entry); }
|
|
281
|
+
}, killGraceMs);
|
|
282
|
+
}
|
|
283
|
+
return done;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Synchronously SIGKILL every live preview (app quit). */
|
|
287
|
+
function stopAll() {
|
|
288
|
+
for (const epicId of pending.keys()) cancelled.add(epicId);
|
|
289
|
+
let killed = 0;
|
|
290
|
+
for (const entry of entries.values()) {
|
|
291
|
+
if (!isLive(entry)) continue;
|
|
292
|
+
entry.stopRequested = true;
|
|
293
|
+
clearTimers(entry);
|
|
294
|
+
killTree(entry.state.pid, 'SIGKILL');
|
|
295
|
+
sweepEpic(entry);
|
|
296
|
+
killed += 1;
|
|
297
|
+
if (entry.state.status !== 'stopped' || entry.state.error !== null) {
|
|
298
|
+
entry.state = { ...entry.state, status: 'stopped', error: null };
|
|
299
|
+
emit(entry);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return { ok: true, killed };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function get(epicId) {
|
|
306
|
+
const entry = entries.get(epicId);
|
|
307
|
+
return entry ? copy(entry.state) : null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function list() {
|
|
311
|
+
return Array.from(entries.values(), (e) => copy(e.state));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return { start, stop, stopAll, list, get };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
module.exports = { createAppPreviewManager };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Pure helpers for the Epic "Run preview" feature: start the project's dev
|
|
4
|
+
// script inside the Epic worktree and open the local URL it prints in the
|
|
5
|
+
// system browser (no embedded webview). This module only lists package.json
|
|
6
|
+
// scripts, finds the first loopback http(s) URL in dev-server output, and
|
|
7
|
+
// allocates a free local TCP port. Spawning and IPC live in later modules.
|
|
8
|
+
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const path = require('node:path');
|
|
11
|
+
const net = require('node:net');
|
|
12
|
+
|
|
13
|
+
// First char excludes '-' so a name can never be parsed as an npm flag
|
|
14
|
+
// (--inspect); no spaces or shell metacharacters anywhere.
|
|
15
|
+
const SCRIPT_NAME_RE = /^[A-Za-z0-9@_][A-Za-z0-9:_.@/-]{0,99}$/;
|
|
16
|
+
const MAX_SCRIPTS = 200;
|
|
17
|
+
const MAX_COMMAND_CHARS = 500;
|
|
18
|
+
const SUGGESTED_ORDER = ['dev', 'start', 'serve', 'preview', 'develop'];
|
|
19
|
+
|
|
20
|
+
function isValidScriptName(name) {
|
|
21
|
+
return typeof name === 'string' && SCRIPT_NAME_RE.test(name);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @returns {{ok:true, scripts:{name:string,command:string}[], suggested:string|null} | {ok:false, error:string}} */
|
|
25
|
+
function listPreviewScripts(dir) {
|
|
26
|
+
let raw;
|
|
27
|
+
try {
|
|
28
|
+
raw = fs.readFileSync(path.join(String(dir), 'package.json'), 'utf8');
|
|
29
|
+
} catch {
|
|
30
|
+
return { ok: false, error: `No package.json in ${dir}` };
|
|
31
|
+
}
|
|
32
|
+
let pkg;
|
|
33
|
+
try {
|
|
34
|
+
pkg = JSON.parse(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
return { ok: false, error: `package.json in ${dir} is not valid JSON` };
|
|
37
|
+
}
|
|
38
|
+
const src = pkg && typeof pkg === 'object' && !Array.isArray(pkg) ? pkg.scripts : null;
|
|
39
|
+
const scripts = [];
|
|
40
|
+
if (src && typeof src === 'object' && !Array.isArray(src)) {
|
|
41
|
+
for (const [name, value] of Object.entries(src)) {
|
|
42
|
+
if (scripts.length >= MAX_SCRIPTS) break;
|
|
43
|
+
if (!isValidScriptName(name) || typeof value !== 'string' || value.trim() === '') continue;
|
|
44
|
+
scripts.push({ name, command: value.slice(0, MAX_COMMAND_CHARS) });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (scripts.length === 0) return { ok: false, error: `package.json in ${dir} has no runnable scripts` };
|
|
48
|
+
const names = new Set(scripts.map((s) => s.name));
|
|
49
|
+
const suggested = SUGGESTED_ORDER.find((n) => names.has(n)) || null;
|
|
50
|
+
return { ok: true, scripts, suggested };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// CSI: ESC [ params intermediates final-byte. OSC: ESC ] ... (BEL | ESC \).
|
|
54
|
+
const CSI_RE = /\u001b\[[0-?]*[ -/]*[@-~]/g;
|
|
55
|
+
const OSC_RE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
|
|
56
|
+
|
|
57
|
+
function stripAnsi(text) {
|
|
58
|
+
if (typeof text !== 'string' || text === '') return '';
|
|
59
|
+
return text.replace(OSC_RE, '').replace(CSI_RE, '');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const URL_RE = /(?<![A-Za-z0-9+.-])(https?):\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|\[::\])(?::(\d+))?([^\s"'<>]*)/gi;
|
|
63
|
+
const TRAILING_RE = /[.,;)]+$/;
|
|
64
|
+
|
|
65
|
+
/** First loopback http(s) URL in dev-server output, or null. */
|
|
66
|
+
function detectLocalUrl(text) {
|
|
67
|
+
const clean = stripAnsi(text);
|
|
68
|
+
if (!clean) return null;
|
|
69
|
+
URL_RE.lastIndex = 0;
|
|
70
|
+
let m;
|
|
71
|
+
while ((m = URL_RE.exec(clean)) !== null) {
|
|
72
|
+
const [, scheme, rawHost, portStr, rawRest] = m;
|
|
73
|
+
const rest = rawRest.replace(TRAILING_RE, '');
|
|
74
|
+
// Host must end here (rejects localhost.evil.com, localhost:3000abc).
|
|
75
|
+
if (rest && !/^[/?#]/.test(rest)) continue;
|
|
76
|
+
if (portStr !== undefined) {
|
|
77
|
+
const port = Number(portStr);
|
|
78
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
|
|
79
|
+
}
|
|
80
|
+
const lowerHost = rawHost.toLowerCase();
|
|
81
|
+
const host = lowerHost === '0.0.0.0' || lowerHost === '[::]' ? 'localhost' : lowerHost;
|
|
82
|
+
return `${scheme.toLowerCase()}://${host}${portStr !== undefined ? `:${portStr}` : ''}${rest}`;
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Resolves an OS-assigned free port on 127.0.0.1. */
|
|
88
|
+
function findFreePort() {
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const server = net.createServer();
|
|
91
|
+
server.once('error', reject);
|
|
92
|
+
server.listen(0, '127.0.0.1', () => {
|
|
93
|
+
const { port } = server.address();
|
|
94
|
+
server.close(() => resolve(port));
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = {
|
|
100
|
+
SCRIPT_NAME_RE,
|
|
101
|
+
isValidScriptName,
|
|
102
|
+
listPreviewScripts,
|
|
103
|
+
detectLocalUrl,
|
|
104
|
+
stripAnsi,
|
|
105
|
+
findFreePort,
|
|
106
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// appPreviewSweep.cjs — find and kill "Run preview" dev-server processes by
|
|
4
|
+
// their environment markers, not by process group.
|
|
5
|
+
//
|
|
6
|
+
// Why: dev servers often move children into their own session (concurrently,
|
|
7
|
+
// tsx watch, vite under pnpm), so a process-group kill misses them — the same
|
|
8
|
+
// leak scheduler/jobLeftovers.cjs documents for jobs. Every preview process
|
|
9
|
+
// inherits SM_PROC_ROLE=preview, SM_PREVIEW_EPIC_ID and SM_PREVIEW_OWNER_PID
|
|
10
|
+
// from appPreviewManager, and a setsid child keeps its environment, so /proc
|
|
11
|
+
// environ is the identity. Linux only; elsewhere every function is a no-op.
|
|
12
|
+
|
|
13
|
+
const fs = require('node:fs');
|
|
14
|
+
const path = require('node:path');
|
|
15
|
+
const { pidAlive: defaultPidAlive } = require('../process/pidAlive.cjs');
|
|
16
|
+
|
|
17
|
+
const ROLE_MARKER = 'SM_PROC_ROLE=preview';
|
|
18
|
+
const EPIC_MARKER = 'SM_PREVIEW_EPIC_ID=';
|
|
19
|
+
const OWNER_MARKER = 'SM_PREVIEW_OWNER_PID=';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @returns {{ pid: number, epicId: string, ownerPid: number|null }[]}
|
|
23
|
+
*/
|
|
24
|
+
function scanPreviewProcesses({ fsImpl = fs, procRoot = process.env.SM_PROC_ROOT || '/proc', platform = process.platform } = {}) {
|
|
25
|
+
if (platform !== 'linux') return [];
|
|
26
|
+
let names;
|
|
27
|
+
try {
|
|
28
|
+
names = fsImpl.readdirSync(procRoot);
|
|
29
|
+
} catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const name of names) {
|
|
34
|
+
const n = String(name);
|
|
35
|
+
if (!/^\d+$/.test(n)) continue;
|
|
36
|
+
let env;
|
|
37
|
+
try {
|
|
38
|
+
env = String(fsImpl.readFileSync(path.join(procRoot, n, 'environ'), 'utf8')).split('\0');
|
|
39
|
+
} catch { continue; }
|
|
40
|
+
if (!env.includes(ROLE_MARKER)) continue;
|
|
41
|
+
const epicEntry = env.find((e) => e.startsWith(EPIC_MARKER));
|
|
42
|
+
const epicId = epicEntry ? epicEntry.slice(EPIC_MARKER.length) : '';
|
|
43
|
+
if (!epicId) continue;
|
|
44
|
+
const ownerEntry = env.find((e) => e.startsWith(OWNER_MARKER));
|
|
45
|
+
const owner = ownerEntry ? Number(ownerEntry.slice(OWNER_MARKER.length)) : NaN;
|
|
46
|
+
out.push({ pid: Number(n), epicId, ownerPid: Number.isInteger(owner) && owner > 0 ? owner : null });
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function signalAll(pids, kill) {
|
|
52
|
+
let count = 0;
|
|
53
|
+
for (const pid of pids) {
|
|
54
|
+
try {
|
|
55
|
+
kill(pid, 'SIGKILL');
|
|
56
|
+
count += 1;
|
|
57
|
+
} catch { /* already gone or not ours */ }
|
|
58
|
+
}
|
|
59
|
+
return count;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** SIGKILL every preview process of `epicId` (never this process). Returns the count signalled. */
|
|
63
|
+
function killPreviewProcesses(epicId, opts = {}) {
|
|
64
|
+
try {
|
|
65
|
+
if (typeof epicId !== 'string' || epicId === '') return 0;
|
|
66
|
+
const kill = opts.kill || process.kill.bind(process);
|
|
67
|
+
const selfPid = opts.selfPid || process.pid;
|
|
68
|
+
const pids = scanPreviewProcesses(opts)
|
|
69
|
+
.filter((p) => p.epicId === epicId && p.pid !== selfPid)
|
|
70
|
+
.map((p) => p.pid);
|
|
71
|
+
return signalAll(pids, kill);
|
|
72
|
+
} catch {
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** SIGKILL preview processes whose owning app is gone (boot sweep). Returns the count signalled. */
|
|
78
|
+
function sweepOrphanedPreviews(opts = {}) {
|
|
79
|
+
try {
|
|
80
|
+
const kill = opts.kill || process.kill.bind(process);
|
|
81
|
+
const pidAlive = opts.pidAlive || defaultPidAlive;
|
|
82
|
+
const selfPid = opts.selfPid || process.pid;
|
|
83
|
+
const pids = scanPreviewProcesses(opts)
|
|
84
|
+
.filter((p) => p.pid !== selfPid && p.ownerPid !== selfPid && !pidAlive(p.ownerPid))
|
|
85
|
+
.map((p) => p.pid);
|
|
86
|
+
return signalAll(pids, kill);
|
|
87
|
+
} catch {
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { scanPreviewProcesses, killPreviewProcesses, sweepOrphanedPreviews };
|