@pi-chamber/web 1.0.8-rc.1 → 1.0.8-rc.2
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/dist/assets/{AgentsSurface-BmHImX8m.js → AgentsSurface-CcWBqAWV.js} +1 -1
- package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-Kk-qvrSB.js} +1 -1
- package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-DZUBo1uP.js} +1 -1
- package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CiZy4jFA.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-DZ9NDwOO.js} +1 -1
- package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-DqiZ9kw9.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-DM2DH7o8.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-ChB8NZ1h.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-CibDiJGq.js} +1 -1
- package/dist/assets/{GitView-MIDG5RYW.js → GitView--EaZQrBr.js} +5 -5
- package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-CySTpaD1.js} +3 -3
- package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-_yMHKKQZ.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-D_-2fQw0.js} +1 -1
- package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-bHObDlhD.js} +1 -1
- package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-UY7Cse-s.js} +1 -1
- package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-iXy6chwc.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CDOX-5Y2.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-Dwc3MdvA.js} +1 -1
- package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
- package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-CUg49Mfh.js} +1 -1
- package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-DUZX9tDe.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-BuZZaRw4.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-CKncG6i2.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-BGZiLPe_.js} +1 -1
- package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
- package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
- package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-Bro9KrfM.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DJQqK49u.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-ByWK3Sru.js} +1 -1
- package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CyJ3TOYD.js} +1 -1
- package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-BsXrwngT.js} +1 -1
- package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-g2bmC0qi.js} +1 -1
- package/dist/assets/index-B_L9GVYw.css +1 -0
- package/dist/assets/{index-DMX9wT1Z.js → index-C9rUUQ_Y.js} +1 -1
- package/dist/assets/index-CKKWVoND.js +11 -0
- package/dist/assets/{main-BW9J3Y72.js → main-DT-4_fhe.js} +2 -2
- package/dist/assets/{main-BirYxac2.js → main-DsLMU9CT.js} +4 -4
- package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-QmM_aOnZ.js} +1 -1
- package/dist/assets/{miniChat-BRB11eEs.js → miniChat-BqGslD2z.js} +2 -2
- package/dist/assets/{mobile-DJZYYCuB.js → mobile-C5JOcDIC.js} +2 -2
- package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-DSMsJqXM.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Cc_S4zi1.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CiSkecEE.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
- package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
- package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
- package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-0K7vuUpd.js} +1 -1
- package/dist/assets/{selection-BTEdLRVK.js → selection-CnYkEsu_.js} +1 -1
- package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
- package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-CgP-zEBj.js} +1 -1
- package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-C8G5F0hs.js} +1 -1
- package/dist/assets/{web-components-C_DsTJis.js → web-components-BpncHjnV.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/plugins/featured.json +12 -0
- package/plugins/subagents/package.json +1 -1
- package/plugins/visuals/extension.js +7 -4
- package/plugins/visuals/package.json +1 -1
- package/server/index.js +86 -27
- package/server/lib/git/DOCUMENTATION.md +4 -0
- package/server/lib/git/service.js +70 -5
- package/server/lib/git/service.test.js +179 -0
- package/server/lib/github/DOCUMENTATION.md +2 -0
- package/server/lib/marketplace/DOCUMENTATION.md +95 -0
- package/server/lib/marketplace/featured.js +176 -0
- package/server/lib/marketplace/featured.test.js +207 -0
- package/server/lib/marketplace/npm-registry.js +255 -0
- package/server/lib/marketplace/npm-registry.test.js +227 -0
- package/server/lib/marketplace/routes.js +64 -0
- package/server/lib/marketplace/routes.test.js +119 -0
- package/server/lib/marketplace/service.js +225 -0
- package/server/lib/marketplace/service.test.js +174 -0
- package/server/lib/notifications/DOCUMENTATION.md +10 -4
- package/server/lib/notifications/pi-notification-watcher.js +92 -33
- package/server/lib/notifications/pi-notification-watcher.test.js +79 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -0
- package/server/lib/pi/merged-event-stream.js +316 -0
- package/server/lib/pi/merged-event-stream.test.js +95 -0
- package/server/lib/pi/routes-daemon-pool.test.js +348 -0
- package/server/lib/pi/routes-merged-events.test.js +327 -0
- package/server/lib/pi/routes-sandbox.test.js +1684 -0
- package/server/lib/pi/routes.js +491 -90
- package/server/lib/pi/routes.test.js +87 -2
- package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
- package/server/lib/pi/sandbox/launcher.js +122 -0
- package/server/lib/pi/sandbox/launcher.test.js +91 -0
- package/server/lib/pi/sandbox/nono-launcher.js +455 -0
- package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
- package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
- package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
- package/server/lib/pi/sandbox/nono-profile.json +22 -0
- package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
- package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
- package/server/lib/pi/sandbox/project-sandbox.js +207 -0
- package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
- package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
- package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
- package/server/lib/pi/sandbox/trust-ask.js +135 -0
- package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
- package/server/lib/pi/sandbox/worktree-ids.js +96 -0
- package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +26 -6
- package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
- package/server/lib/pi/session-daemon/daemon-process.js +10 -1
- package/server/lib/pi/session-daemon/extension-config.js +206 -23
- package/server/lib/pi/session-daemon/extension-config.test.js +180 -0
- package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
- package/server/lib/pi/session-daemon/session-daemon.js +368 -56
- package/server/lib/pi/session-daemon/session-daemon.test.js +227 -0
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
- package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
- package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
- package/server/lib/pi/session-daemon/session-lease.js +93 -15
- package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
- package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
- package/server/lib/pi/session-daemon/supervisor.js +386 -35
- package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
- package/server/lib/pi/ui-settings-store.js +88 -2
- package/server/lib/pi/ui-settings-store.test.js +118 -0
- package/server/lib/plugins/DOCUMENTATION.md +17 -5
- package/server/lib/plugins/daemon-sync.js +16 -6
- package/server/lib/plugins/daemon-sync.test.js +12 -0
- package/server/lib/plugins/impact.test.js +2 -1
- package/server/lib/plugins/manifest.js +25 -0
- package/server/lib/plugins/manifest.test.js +9 -0
- package/server/lib/plugins/routes.test.js +28 -0
- package/server/lib/plugins/service.js +24 -2
- package/server/lib/server/cross-process-lock.js +28 -3
- package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
- package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
- package/dist/assets/index-B2v0_mez.js +0 -11
- package/dist/assets/index-D3F4JrPN.css +0 -1
- package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { mkdir,
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
|
|
5
|
-
import { withCrossProcessLock } from '../../server/cross-process-lock.js';
|
|
5
|
+
import { readSmallRegularFile, withCrossProcessLock } from '../../server/cross-process-lock.js';
|
|
6
6
|
|
|
7
7
|
export class SessionLeaseError extends Error {
|
|
8
8
|
constructor(code, message = 'The Pi session lease is unavailable.') {
|
|
@@ -20,6 +20,15 @@ const isPidAlive = (processLike, pid) => {
|
|
|
20
20
|
}
|
|
21
21
|
};
|
|
22
22
|
|
|
23
|
+
const isSignallablePid = (processLike, pid) => {
|
|
24
|
+
try {
|
|
25
|
+
processLike.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
23
32
|
export const canonicalizeLeaseDir = (value, platform = process.platform) => {
|
|
24
33
|
const resolved = resolve(String(value ?? ''));
|
|
25
34
|
if (platform === 'win32') {
|
|
@@ -33,15 +42,38 @@ const leaseHash = ({ agentDir, cwd, sessionId }) => createHash('sha256')
|
|
|
33
42
|
.digest('hex')
|
|
34
43
|
.slice(0, 32);
|
|
35
44
|
|
|
36
|
-
|
|
45
|
+
const LEASE_SCOPE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
46
|
+
|
|
47
|
+
/** The folder holding every sandbox's own lease folder, one per scope. */
|
|
48
|
+
const scopedLeaseRoot = (agentDir, platform = process.platform) => (
|
|
49
|
+
join(canonicalizeLeaseDir(agentDir, platform), '.pichamber', 'locks', 'sandbox-sessions')
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
/** The lease folder of one scope: all a sandbox daemon is granted. */
|
|
53
|
+
export const scopedLeaseDir = (agentDir, scope, platform = process.platform) => {
|
|
54
|
+
if (typeof scope !== 'string' || !LEASE_SCOPE.test(scope)) throw new SessionLeaseError('INVALID_LEASE_SCOPE');
|
|
55
|
+
return join(scopedLeaseRoot(agentDir, platform), scope);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Where a session's lease lives. A daemon with a `scope` (a sandbox daemon)
|
|
60
|
+
* keeps its leases in its own folder, the only lease folder it can reach;
|
|
61
|
+
* every other daemon uses the shared one. The file name is the same in
|
|
62
|
+
* both, so a daemon outside a sandbox can look a session up in each scope.
|
|
63
|
+
*/
|
|
64
|
+
export const resolveSessionLeaseFile = ({ agentDir, cwd, sessionId, scope, platform = process.platform } = {}) => {
|
|
37
65
|
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
38
66
|
throw new SessionLeaseError('INVALID_SESSION_ID');
|
|
39
67
|
}
|
|
40
68
|
const canonicalAgentDir = canonicalizeLeaseDir(agentDir, platform);
|
|
41
69
|
const canonicalCwd = canonicalizeLeaseDir(cwd, platform);
|
|
42
70
|
const name = `${leaseHash({ agentDir: canonicalAgentDir, cwd: canonicalCwd, sessionId })}.json`;
|
|
71
|
+
const directory = scope === undefined
|
|
72
|
+
? join(canonicalAgentDir, '.pichamber', 'locks', 'sessions')
|
|
73
|
+
: scopedLeaseDir(canonicalAgentDir, scope, platform);
|
|
43
74
|
return {
|
|
44
|
-
file: join(
|
|
75
|
+
file: join(directory, name),
|
|
76
|
+
name,
|
|
45
77
|
canonicalAgentDir,
|
|
46
78
|
canonicalCwd,
|
|
47
79
|
};
|
|
@@ -67,6 +99,35 @@ const isOwnLease = (lease, owner) => (
|
|
|
67
99
|
&& lease?.daemonPid === owner?.daemonPid
|
|
68
100
|
);
|
|
69
101
|
|
|
102
|
+
// A live lease a sandbox daemon holds on this session, read from the scope
|
|
103
|
+
// folders. Those folders are written by sandboxed code: a file there is read
|
|
104
|
+
// as a small regular file or not at all, and only a lease for this very
|
|
105
|
+
// session counts.
|
|
106
|
+
const scopedLeaseHolder = async ({ canonicalAgentDir, name, sessionId, owner, platform, processLike }) => {
|
|
107
|
+
const root = scopedLeaseRoot(canonicalAgentDir, platform);
|
|
108
|
+
let scopes;
|
|
109
|
+
try {
|
|
110
|
+
scopes = await readdir(root, { withFileTypes: true });
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
for (const scope of scopes) {
|
|
115
|
+
if (!scope.isDirectory() || !LEASE_SCOPE.test(scope.name)) continue;
|
|
116
|
+
let lease;
|
|
117
|
+
try {
|
|
118
|
+
lease = JSON.parse(await readSmallRegularFile(join(root, scope.name, name)));
|
|
119
|
+
} catch {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (!isValidLease(lease) || lease.sessionId !== sessionId || isOwnLease(lease, owner)) continue;
|
|
123
|
+
// A sandbox daemon runs as this user, so its pid can be signalled. A
|
|
124
|
+
// pid that answers EPERM (pid 1, another user's process) was written by
|
|
125
|
+
// sandboxed code to hold the session forever; it is not a holder.
|
|
126
|
+
if (isSignallablePid(processLike, lease.daemonPid)) return lease;
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
};
|
|
130
|
+
|
|
70
131
|
/**
|
|
71
132
|
* Acquire exclusive cross-daemon ownership of one Pi session.
|
|
72
133
|
*
|
|
@@ -83,14 +144,15 @@ export const acquireSessionLease = async ({
|
|
|
83
144
|
platform = process.platform,
|
|
84
145
|
processLike = process,
|
|
85
146
|
timeoutMs = 5_000,
|
|
147
|
+
scope,
|
|
86
148
|
} = {}) => {
|
|
87
149
|
if (!owner || typeof owner !== 'object') throw new SessionLeaseError('INVALID_OWNER');
|
|
88
|
-
const { file, canonicalAgentDir, canonicalCwd } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, platform });
|
|
150
|
+
const { file, name, canonicalAgentDir, canonicalCwd } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, scope, platform });
|
|
89
151
|
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
90
152
|
return withCrossProcessLock(`${file}.lock`, async () => {
|
|
91
153
|
let current = null;
|
|
92
154
|
try {
|
|
93
|
-
current = JSON.parse(await
|
|
155
|
+
current = JSON.parse(await readSmallRegularFile(file));
|
|
94
156
|
} catch (error) {
|
|
95
157
|
if (error?.code !== 'ENOENT') throw new SessionLeaseError('LEASE_UNREADABLE');
|
|
96
158
|
}
|
|
@@ -99,6 +161,12 @@ export const acquireSessionLease = async ({
|
|
|
99
161
|
return { acquired: false, owner: current };
|
|
100
162
|
}
|
|
101
163
|
}
|
|
164
|
+
// A sandbox daemon may be running the session. It cannot see this
|
|
165
|
+
// daemon's leases, so the check is made from this side only.
|
|
166
|
+
if (scope === undefined) {
|
|
167
|
+
const holder = await scopedLeaseHolder({ canonicalAgentDir, name, sessionId, owner, platform, processLike });
|
|
168
|
+
if (holder) return { acquired: false, owner: holder };
|
|
169
|
+
}
|
|
102
170
|
const lease = {
|
|
103
171
|
profileKey: owner.profileKey,
|
|
104
172
|
serverInstanceId: owner.serverInstanceId,
|
|
@@ -109,9 +177,18 @@ export const acquireSessionLease = async ({
|
|
|
109
177
|
agentDir: canonicalAgentDir,
|
|
110
178
|
acquiredAt: new Date().toISOString(),
|
|
111
179
|
};
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
180
|
+
// Sandbox daemons share this folder, so a name that can be guessed could
|
|
181
|
+
// be planted as a symlink to any file. A random name created with `wx`
|
|
182
|
+
// never writes through one, and the rename replaces whatever sits at the
|
|
183
|
+
// lease path rather than following it.
|
|
184
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
185
|
+
try {
|
|
186
|
+
await writeFile(temporary, JSON.stringify(lease), { flag: 'wx', mode: 0o600 });
|
|
187
|
+
await rename(temporary, file);
|
|
188
|
+
} catch {
|
|
189
|
+
await rm(temporary, { force: true }).catch(() => {});
|
|
190
|
+
throw new SessionLeaseError('LEASE_UNREADABLE');
|
|
191
|
+
}
|
|
115
192
|
return { acquired: true, lease };
|
|
116
193
|
}, { timeoutMs, processLike });
|
|
117
194
|
};
|
|
@@ -124,12 +201,13 @@ export const releaseSessionLease = async ({
|
|
|
124
201
|
platform = process.platform,
|
|
125
202
|
processLike = process,
|
|
126
203
|
timeoutMs = 5_000,
|
|
204
|
+
scope,
|
|
127
205
|
} = {}) => {
|
|
128
|
-
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, platform });
|
|
206
|
+
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, scope, platform });
|
|
129
207
|
return withCrossProcessLock(`${file}.lock`, async () => {
|
|
130
208
|
let current = null;
|
|
131
209
|
try {
|
|
132
|
-
current = JSON.parse(await
|
|
210
|
+
current = JSON.parse(await readSmallRegularFile(file));
|
|
133
211
|
} catch (error) {
|
|
134
212
|
if (error?.code === 'ENOENT') return { released: false };
|
|
135
213
|
throw new SessionLeaseError('LEASE_UNREADABLE');
|
|
@@ -140,10 +218,10 @@ export const releaseSessionLease = async ({
|
|
|
140
218
|
}, { timeoutMs, processLike });
|
|
141
219
|
};
|
|
142
220
|
|
|
143
|
-
export const readSessionLeaseOwner = async ({ agentDir, cwd, sessionId, platform = process.platform } = {}) => {
|
|
144
|
-
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, platform });
|
|
221
|
+
export const readSessionLeaseOwner = async ({ agentDir, cwd, sessionId, scope, platform = process.platform } = {}) => {
|
|
222
|
+
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId, scope, platform });
|
|
145
223
|
try {
|
|
146
|
-
const current = JSON.parse(await
|
|
224
|
+
const current = JSON.parse(await readSmallRegularFile(file));
|
|
147
225
|
return isValidLease(current) ? current : null;
|
|
148
226
|
} catch {
|
|
149
227
|
return null;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import {
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { mkdir, mkdtemp, readFile, symlink, writeFile } from 'node:fs/promises';
|
|
3
4
|
import { tmpdir } from 'node:os';
|
|
4
5
|
import { join } from 'node:path';
|
|
5
6
|
|
|
@@ -7,6 +8,8 @@ import {
|
|
|
7
8
|
acquireSessionLease,
|
|
8
9
|
readSessionLeaseOwner,
|
|
9
10
|
releaseSessionLease,
|
|
11
|
+
resolveSessionLeaseFile,
|
|
12
|
+
scopedLeaseDir,
|
|
10
13
|
} from './session-lease.js';
|
|
11
14
|
|
|
12
15
|
const ownerA = {
|
|
@@ -105,4 +108,107 @@ describe('session lease', () => {
|
|
|
105
108
|
acquired: true,
|
|
106
109
|
});
|
|
107
110
|
});
|
|
111
|
+
// Sandbox daemons can write the lease folder, so nothing in it is trusted.
|
|
112
|
+
describe.skipIf(process.platform === 'win32')('a lease folder untrusted code can write', () => {
|
|
113
|
+
const setup = async () => {
|
|
114
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-lease-'));
|
|
115
|
+
const agentDir = join(root, 'agent');
|
|
116
|
+
const cwd = join(root, 'project');
|
|
117
|
+
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId: 'session-1' });
|
|
118
|
+
await mkdir(join(file, '..'), { recursive: true });
|
|
119
|
+
const victim = join(root, 'victim.txt');
|
|
120
|
+
await writeFile(victim, 'keep me');
|
|
121
|
+
return { agentDir, cwd, file, victim };
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
it('never writes through a symlink planted at the old temp name', async () => {
|
|
125
|
+
const { agentDir, cwd, file, victim } = await setup();
|
|
126
|
+
await symlink(victim, `${file}.${process.pid}.tmp`);
|
|
127
|
+
|
|
128
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA }))
|
|
129
|
+
.resolves.toMatchObject({ acquired: true });
|
|
130
|
+
expect(await readFile(victim, 'utf8')).toBe('keep me');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('does not follow a symlink planted as the lease file', async () => {
|
|
134
|
+
const { agentDir, cwd, file, victim } = await setup();
|
|
135
|
+
await writeFile(victim, JSON.stringify({ ...ownerB, sessionId: 'session-1' }));
|
|
136
|
+
await symlink(victim, file);
|
|
137
|
+
|
|
138
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA }))
|
|
139
|
+
.rejects.toMatchObject({ code: 'LEASE_UNREADABLE' });
|
|
140
|
+
expect(await readSessionLeaseOwner({ agentDir, cwd, sessionId: 'session-1' })).toBeNull();
|
|
141
|
+
expect(JSON.parse(await readFile(victim, 'utf8')).daemonId).toBe('daemon-b');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('does not wait on a FIFO planted as the lease file', async () => {
|
|
145
|
+
const { agentDir, cwd, file } = await setup();
|
|
146
|
+
execFileSync('mkfifo', [file]);
|
|
147
|
+
|
|
148
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA, timeoutMs: 500 }))
|
|
149
|
+
.rejects.toMatchObject({ code: 'LEASE_UNREADABLE' });
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
// A sandbox daemon keeps its leases in its own folder (its scope).
|
|
153
|
+
describe('a sandbox daemon\'s lease folder', () => {
|
|
154
|
+
const dirs = async () => {
|
|
155
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-lease-'));
|
|
156
|
+
return { agentDir: join(root, 'agent'), cwd: join(root, 'project') };
|
|
157
|
+
};
|
|
158
|
+
const sandboxOwner = { ...ownerB, daemonId: 'daemon-sandbox' };
|
|
159
|
+
|
|
160
|
+
it('holds the lease where no other project\'s leases are', async () => {
|
|
161
|
+
const { agentDir, cwd } = await dirs();
|
|
162
|
+
await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: sandboxOwner, scope: 'proj-a' });
|
|
163
|
+
const { file } = resolveSessionLeaseFile({ agentDir, cwd, sessionId: 'session-1', scope: 'proj-a' });
|
|
164
|
+
expect(file.startsWith(`${scopedLeaseDir(agentDir, 'proj-a')}/`)).toBe(true);
|
|
165
|
+
expect(await readSessionLeaseOwner({ agentDir, cwd, sessionId: 'session-1' })).toBeNull();
|
|
166
|
+
expect((await readSessionLeaseOwner({ agentDir, cwd, sessionId: 'session-1', scope: 'proj-a' }))?.daemonId).toBe('daemon-sandbox');
|
|
167
|
+
expect(() => resolveSessionLeaseFile({ agentDir, cwd, sessionId: 'session-1', scope: '../sessions' })).toThrow();
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('keeps a daemon outside the sandbox out of a session the sandbox runs, until it lets go', async () => {
|
|
171
|
+
const { agentDir, cwd } = await dirs();
|
|
172
|
+
await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: sandboxOwner, scope: 'proj-a' });
|
|
173
|
+
|
|
174
|
+
const contention = await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA });
|
|
175
|
+
expect(contention).toMatchObject({ acquired: false, owner: { daemonId: 'daemon-sandbox' } });
|
|
176
|
+
// Another session is not affected.
|
|
177
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-2', owner: ownerA })).resolves.toMatchObject({ acquired: true });
|
|
178
|
+
|
|
179
|
+
await releaseSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: sandboxOwner, scope: 'proj-a' });
|
|
180
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA })).resolves.toMatchObject({ acquired: true });
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('lets a replacement daemon of the same project see the lease', async () => {
|
|
184
|
+
const { agentDir, cwd } = await dirs();
|
|
185
|
+
await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: sandboxOwner, scope: 'proj-a' });
|
|
186
|
+
const next = await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: { ...sandboxOwner, daemonId: 'daemon-next' }, scope: 'proj-a' });
|
|
187
|
+
expect(next.acquired).toBe(false);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('ignores a file in a sandbox folder that is not a lease for the session', async () => {
|
|
191
|
+
const { agentDir, cwd } = await dirs();
|
|
192
|
+
const { name } = resolveSessionLeaseFile({ agentDir, cwd, sessionId: 'session-1' });
|
|
193
|
+
const scope = scopedLeaseDir(agentDir, 'proj-a');
|
|
194
|
+
await mkdir(scope, { recursive: true });
|
|
195
|
+
// A lease for another session copied under this session's name.
|
|
196
|
+
await writeFile(join(scope, name), JSON.stringify({ ...sandboxOwner, sessionId: 'session-9' }));
|
|
197
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA })).resolves.toMatchObject({ acquired: true });
|
|
198
|
+
});
|
|
199
|
+
it('ignores a forged lease that names a process this user cannot signal', async () => {
|
|
200
|
+
const { agentDir, cwd } = await dirs();
|
|
201
|
+
// Written through the real path so the file is a well-formed lease.
|
|
202
|
+
await acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: { ...sandboxOwner, daemonPid: 1 }, scope: 'proj-a' });
|
|
203
|
+
const processLike = {
|
|
204
|
+
pid: process.pid,
|
|
205
|
+
kill: (pid) => {
|
|
206
|
+
if (pid === 1) throw Object.assign(new Error('EPERM'), { code: 'EPERM' });
|
|
207
|
+
return true;
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
await expect(acquireSessionLease({ agentDir, cwd, sessionId: 'session-1', owner: ownerA, processLike }))
|
|
211
|
+
.resolves.toMatchObject({ acquired: true });
|
|
212
|
+
});
|
|
213
|
+
});
|
|
108
214
|
});
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { spawn as spawnChildProcess } from 'node:child_process';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
import { createPiSessionDaemonSupervisor } from './supervisor.js';
|
|
9
|
+
|
|
10
|
+
const DAEMON_ENTRYPOINT = fileURLToPath(new URL('./daemon-process.js', import.meta.url));
|
|
11
|
+
const SERVER_PID = 1000;
|
|
12
|
+
const LAUNCHER_PID = 4242;
|
|
13
|
+
const DAEMON_PID = 4243;
|
|
14
|
+
// A process the sandbox would like the server to kill (the server itself,
|
|
15
|
+
// the main daemon, anything the user owns).
|
|
16
|
+
const VICTIM_PID = 777;
|
|
17
|
+
|
|
18
|
+
const exists = async (file) => access(file).then(() => true, () => false);
|
|
19
|
+
|
|
20
|
+
const argValue = (args, flag) => args[args.indexOf(flag) + 1];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A fake host: a process table, a launcher that wraps the daemon command, and
|
|
24
|
+
* a daemon whose health answer echoes whatever its state sidecar says, the
|
|
25
|
+
* way a sandboxed daemon under an attacker's control would.
|
|
26
|
+
*/
|
|
27
|
+
const createWorld = async ({ withLauncher = true } = {}) => {
|
|
28
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-launcher-stop-'));
|
|
29
|
+
const dataDir = join(root, 'data');
|
|
30
|
+
// Short on purpose: nothing binds it, but the path must stay local.
|
|
31
|
+
const runtimeDir = await mkdtemp('/tmp/pls-');
|
|
32
|
+
const processes = new Map([
|
|
33
|
+
[1, { identity: 'start:1', alive: true }],
|
|
34
|
+
[SERVER_PID, { identity: 'start:1000', alive: true }],
|
|
35
|
+
[VICTIM_PID, { identity: 'start:777', alive: true }],
|
|
36
|
+
]);
|
|
37
|
+
const signals = [];
|
|
38
|
+
const requests = [];
|
|
39
|
+
const processLike = {
|
|
40
|
+
pid: SERVER_PID,
|
|
41
|
+
execPath: '/opt/node/bin/node',
|
|
42
|
+
versions: { node: '24.0.0' },
|
|
43
|
+
kill(pid, signal) {
|
|
44
|
+
if (signal !== 0) signals.push([pid, signal]);
|
|
45
|
+
const entry = processes.get(pid);
|
|
46
|
+
if (!entry?.alive) {
|
|
47
|
+
const error = new Error('ESRCH');
|
|
48
|
+
error.code = 'ESRCH';
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
if (signal === 'SIGTERM' && (pid === LAUNCHER_PID || pid === DAEMON_PID)) {
|
|
52
|
+
// The launcher forwards SIGTERM to the daemon and exits after it.
|
|
53
|
+
for (const own of [LAUNCHER_PID, DAEMON_PID]) {
|
|
54
|
+
if (processes.has(own)) processes.get(own).alive = false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return true;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
const readProcessIdentity = async (pid) => {
|
|
61
|
+
const entry = processes.get(pid);
|
|
62
|
+
return entry?.alive ? entry.identity : null;
|
|
63
|
+
};
|
|
64
|
+
let stateFile;
|
|
65
|
+
const spawn = (command, args) => {
|
|
66
|
+
const daemonArgs = withLauncher ? args.slice(1) : args;
|
|
67
|
+
stateFile = argValue(daemonArgs, '--state-file');
|
|
68
|
+
processes.set(LAUNCHER_PID, { identity: 'start:4242', alive: true });
|
|
69
|
+
processes.set(DAEMON_PID, { identity: 'start:4243', alive: true });
|
|
70
|
+
const state = {
|
|
71
|
+
protocolVersion: 1,
|
|
72
|
+
pid: withLauncher ? DAEMON_PID : LAUNCHER_PID,
|
|
73
|
+
endpoint: argValue(daemonArgs, '--endpoint'),
|
|
74
|
+
profileKey: argValue(daemonArgs, '--profile-key'),
|
|
75
|
+
serverInstanceId: argValue(daemonArgs, '--server-instance-id'),
|
|
76
|
+
serverPid: Number(argValue(daemonArgs, '--server-pid')),
|
|
77
|
+
daemonId: argValue(daemonArgs, '--daemon-id'),
|
|
78
|
+
buildId: argValue(daemonArgs, '--build-id'),
|
|
79
|
+
entrypoint: DAEMON_ENTRYPOINT,
|
|
80
|
+
startedAt: new Date().toISOString(),
|
|
81
|
+
};
|
|
82
|
+
void mkdir(dirname(stateFile), { recursive: true }).then(() => writeFile(stateFile, JSON.stringify(state)));
|
|
83
|
+
return { pid: LAUNCHER_PID, unref() {}, once() {} };
|
|
84
|
+
};
|
|
85
|
+
const request = async ({ command, payload }) => {
|
|
86
|
+
requests.push({ command, payload });
|
|
87
|
+
const daemonAlive = processes.get(DAEMON_PID)?.alive && processes.get(LAUNCHER_PID)?.alive;
|
|
88
|
+
if (!daemonAlive || !stateFile) {
|
|
89
|
+
const error = new Error('refused');
|
|
90
|
+
error.code = 'DAEMON_CONNECTION_REFUSED';
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
const state = JSON.parse(await readFile(stateFile, 'utf8'));
|
|
94
|
+
if (command === 'runtime.health') {
|
|
95
|
+
return {
|
|
96
|
+
state: 'ready',
|
|
97
|
+
daemonPid: state.pid,
|
|
98
|
+
profileKey: state.profileKey,
|
|
99
|
+
daemonId: state.daemonId,
|
|
100
|
+
serverInstanceId: state.serverInstanceId,
|
|
101
|
+
serverPid: state.serverPid,
|
|
102
|
+
buildId: state.buildId,
|
|
103
|
+
capabilities: [],
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// runtime.shutdown is acknowledged but the daemon keeps running, so the
|
|
107
|
+
// stop has to fall back to the signal.
|
|
108
|
+
return {};
|
|
109
|
+
};
|
|
110
|
+
const supervisor = createPiSessionDaemonSupervisor({
|
|
111
|
+
env: { PATH: process.env.PATH, PICHAMBER_DATA_DIR: dataDir, XDG_RUNTIME_DIR: runtimeDir },
|
|
112
|
+
dataDir,
|
|
113
|
+
port: 3000,
|
|
114
|
+
cwd: root,
|
|
115
|
+
platform: 'linux',
|
|
116
|
+
processLike,
|
|
117
|
+
request,
|
|
118
|
+
spawn,
|
|
119
|
+
wait: async () => {},
|
|
120
|
+
startupTimeoutMs: 200,
|
|
121
|
+
daemonReadyTimeoutMs: 2_000,
|
|
122
|
+
readProcessIdentity,
|
|
123
|
+
...(withLauncher
|
|
124
|
+
? { launch: async ({ command, args, env }) => ({ command: '/usr/bin/fake-launcher', args: [command, ...args], env }) }
|
|
125
|
+
: {}),
|
|
126
|
+
});
|
|
127
|
+
const forgeState = async (changes) => {
|
|
128
|
+
const state = JSON.parse(await readFile(supervisor.paths.stateFile, 'utf8'));
|
|
129
|
+
await writeFile(supervisor.paths.stateFile, JSON.stringify({ ...state, ...changes }));
|
|
130
|
+
};
|
|
131
|
+
return { root, dataDir, processes, signals, requests, supervisor, forgeState };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
describe('launcher daemon stop', () => {
|
|
135
|
+
it('keeps the launcher record and operation lock outside the profile folder the sandbox can write', async () => {
|
|
136
|
+
const world = await createWorld();
|
|
137
|
+
const { paths } = world.supervisor;
|
|
138
|
+
expect(paths.lockFile).toBe(join(world.dataDir, 'pi', 'launchers', paths.profileKey, 'operation.lock'));
|
|
139
|
+
expect(paths.launcherFile).toBe(join(world.dataDir, 'pi', 'launchers', paths.profileKey, 'launcher.json'));
|
|
140
|
+
expect(paths.lockFile.startsWith(`${paths.profileDir}/`)).toBe(false);
|
|
141
|
+
|
|
142
|
+
await expect(world.supervisor.start()).resolves.toMatchObject({ state: 'ready', reused: false });
|
|
143
|
+
expect(JSON.parse(await readFile(paths.launcherFile, 'utf8'))).toMatchObject({
|
|
144
|
+
pid: LAUNCHER_PID,
|
|
145
|
+
identity: 'start:4242',
|
|
146
|
+
profileKey: paths.profileKey,
|
|
147
|
+
serverInstanceId: paths.serverInstanceId,
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('never signals a foreign pid written into the state sidecar', async () => {
|
|
152
|
+
const world = await createWorld();
|
|
153
|
+
await world.supervisor.start();
|
|
154
|
+
// The sandbox rewrites its sidecar; the health answer echoes it.
|
|
155
|
+
await world.forgeState({ pid: VICTIM_PID });
|
|
156
|
+
|
|
157
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
158
|
+
expect(world.signals.filter(([pid]) => pid === VICTIM_PID)).toEqual([]);
|
|
159
|
+
expect(world.processes.get(VICTIM_PID).alive).toBe(true);
|
|
160
|
+
expect(world.signals).toEqual([[LAUNCHER_PID, 'SIGTERM']]);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('asks for the authenticated shutdown, then signals the recorded launcher and removes its record', async () => {
|
|
164
|
+
const world = await createWorld();
|
|
165
|
+
await world.supervisor.start();
|
|
166
|
+
|
|
167
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
168
|
+
expect(world.requests.map(({ command }) => command)).toContain('runtime.shutdown');
|
|
169
|
+
expect(world.signals).toEqual([[LAUNCHER_PID, 'SIGTERM']]);
|
|
170
|
+
expect(world.processes.get(LAUNCHER_PID).alive).toBe(false);
|
|
171
|
+
expect(await exists(world.supervisor.paths.launcherFile)).toBe(false);
|
|
172
|
+
expect(await exists(world.supervisor.paths.stateFile)).toBe(false);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('stops the recorded launcher even when the sandbox removed its credential and sidecar', async () => {
|
|
176
|
+
const world = await createWorld();
|
|
177
|
+
await world.supervisor.start();
|
|
178
|
+
await rm(world.supervisor.paths.credentialFile);
|
|
179
|
+
await rm(world.supervisor.paths.stateFile);
|
|
180
|
+
|
|
181
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
182
|
+
expect(world.signals).toEqual([[LAUNCHER_PID, 'SIGTERM']]);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('signals nothing when the recorded pid now belongs to another process', async () => {
|
|
186
|
+
const world = await createWorld();
|
|
187
|
+
await world.supervisor.start();
|
|
188
|
+
// The launcher exited and its pid went to an unrelated process.
|
|
189
|
+
world.processes.set(LAUNCHER_PID, { identity: 'start:9999', alive: true });
|
|
190
|
+
world.processes.get(DAEMON_PID).alive = false;
|
|
191
|
+
|
|
192
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
193
|
+
expect(world.signals).toEqual([]);
|
|
194
|
+
expect(world.processes.get(LAUNCHER_PID).alive).toBe(true);
|
|
195
|
+
expect(await exists(world.supervisor.paths.launcherFile)).toBe(false);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('signals nothing for a launcher daemon without a record, whatever its sidecar says', async () => {
|
|
199
|
+
const world = await createWorld();
|
|
200
|
+
await world.supervisor.start();
|
|
201
|
+
await rm(world.supervisor.paths.launcherFile);
|
|
202
|
+
await world.forgeState({ pid: VICTIM_PID });
|
|
203
|
+
|
|
204
|
+
// The victim stays alive, so the wait for the forged pid times out.
|
|
205
|
+
await expect(world.supervisor.stop()).rejects.toMatchObject({ code: 'DAEMON_STOP_TIMEOUT' });
|
|
206
|
+
expect(world.signals).toEqual([]);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it('refuses to stop a launcher daemon whose record names another server instance', async () => {
|
|
210
|
+
const world = await createWorld();
|
|
211
|
+
await world.supervisor.start();
|
|
212
|
+
const record = JSON.parse(await readFile(world.supervisor.paths.launcherFile, 'utf8'));
|
|
213
|
+
await writeFile(world.supervisor.paths.launcherFile, JSON.stringify({ ...record, serverInstanceId: 'newer-instance' }));
|
|
214
|
+
|
|
215
|
+
await expect(world.supervisor.stop()).rejects.toMatchObject({ code: 'DAEMON_OWNERSHIP_MISMATCH' });
|
|
216
|
+
expect(world.signals).toEqual([]);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('is not blocked by an operation lock planted in the profile folder', async () => {
|
|
220
|
+
const world = await createWorld();
|
|
221
|
+
const { paths } = world.supervisor;
|
|
222
|
+
await mkdir(paths.profileDir, { recursive: true });
|
|
223
|
+
// pid 1 is alive, so this lock would never be stolen.
|
|
224
|
+
await writeFile(join(paths.profileDir, 'operation.lock'), JSON.stringify({ pid: 1 }));
|
|
225
|
+
|
|
226
|
+
await expect(world.supervisor.start()).resolves.toMatchObject({ state: 'ready' });
|
|
227
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
228
|
+
expect(world.signals).toEqual([[LAUNCHER_PID, 'SIGTERM']]);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('does not start a second daemon beside a recorded launcher that is still running', async () => {
|
|
232
|
+
const world = await createWorld();
|
|
233
|
+
await world.supervisor.start();
|
|
234
|
+
// The daemon stops answering and its sidecar is gone, but the launcher runs.
|
|
235
|
+
world.processes.get(DAEMON_PID).alive = false;
|
|
236
|
+
await rm(world.supervisor.paths.stateFile);
|
|
237
|
+
|
|
238
|
+
await expect(world.supervisor.start()).rejects.toMatchObject({ code: 'DAEMON_UNAVAILABLE' });
|
|
239
|
+
expect(world.signals).toEqual([]);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
describe.runIf(process.platform === 'linux')('launcher identity on Linux', () => {
|
|
244
|
+
it('records a real launcher by its /proc start time', async () => {
|
|
245
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-launcher-identity-'));
|
|
246
|
+
const dataDir = join(root, 'data');
|
|
247
|
+
const runtimeDir = await mkdtemp('/tmp/pli-');
|
|
248
|
+
let child;
|
|
249
|
+
const supervisor = createPiSessionDaemonSupervisor({
|
|
250
|
+
env: { PATH: process.env.PATH, PICHAMBER_DATA_DIR: dataDir, XDG_RUNTIME_DIR: runtimeDir },
|
|
251
|
+
dataDir,
|
|
252
|
+
port: 3000,
|
|
253
|
+
cwd: root,
|
|
254
|
+
platform: 'linux',
|
|
255
|
+
// A stand-in launcher that never answers, so the start times out and
|
|
256
|
+
// signals the child it spawned.
|
|
257
|
+
spawn: (_command, _args, options) => {
|
|
258
|
+
child = spawnChildProcess('sleep', ['30'], { ...options, stdio: 'ignore' });
|
|
259
|
+
return child;
|
|
260
|
+
},
|
|
261
|
+
request: async () => {
|
|
262
|
+
const error = new Error('refused');
|
|
263
|
+
error.code = 'DAEMON_CONNECTION_REFUSED';
|
|
264
|
+
throw error;
|
|
265
|
+
},
|
|
266
|
+
wait: (ms) => new Promise((resolveWait) => setTimeout(resolveWait, ms)),
|
|
267
|
+
startupTimeoutMs: 500,
|
|
268
|
+
daemonReadyTimeoutMs: 300,
|
|
269
|
+
launch: async ({ command, args, env }) => ({ command, args, env }),
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
await expect(supervisor.start()).rejects.toMatchObject({ code: 'DAEMON_START_TIMEOUT' });
|
|
273
|
+
const record = JSON.parse(await readFile(supervisor.paths.launcherFile, 'utf8'));
|
|
274
|
+
const stat = await readFile(`/proc/${child.pid}/stat`, 'utf8').catch(() => '');
|
|
275
|
+
expect(record.pid).toBe(child.pid);
|
|
276
|
+
expect(record.identity).toMatch(/^linux-start:\d+$/);
|
|
277
|
+
if (stat) expect(record.identity).toBe(`linux-start:${stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]}`);
|
|
278
|
+
child.kill('SIGKILL');
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
describe('main daemon stop', () => {
|
|
283
|
+
it('still signals the pid in its state sidecar and keeps its lock in the profile folder', async () => {
|
|
284
|
+
const world = await createWorld({ withLauncher: false });
|
|
285
|
+
const { paths } = world.supervisor;
|
|
286
|
+
expect(paths.lockFile).toBe(join(paths.profileDir, 'operation.lock'));
|
|
287
|
+
expect(paths.launcherFile).toBeUndefined();
|
|
288
|
+
|
|
289
|
+
await world.supervisor.start();
|
|
290
|
+
await expect(world.supervisor.stop()).resolves.toEqual({ state: 'stopped' });
|
|
291
|
+
expect(world.requests.map(({ command }) => command)).toContain('runtime.shutdown');
|
|
292
|
+
expect(world.signals).toEqual([[LAUNCHER_PID, 'SIGTERM']]);
|
|
293
|
+
expect(await exists(join(world.dataDir, 'pi', 'launchers'))).toBe(false);
|
|
294
|
+
});
|
|
295
|
+
});
|