@openchamber/web 2.0.1 → 2.0.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/{CodeMirrorCommentWidgets-zm3C1FvM.js → CodeMirrorCommentWidgets-CmKmyb9T.js} +1 -1
- package/dist/assets/{DiffView-DNExNi1z.js → DiffView-8-PFpZ2p.js} +1 -1
- package/dist/assets/{FilesView-DUCLmHBi.js → FilesView-0Ie20mEk.js} +9 -9
- package/dist/assets/{GitView-Bz9z6gZA.js → GitView-DNUSu00w.js} +1 -1
- package/dist/assets/{GuestAttachDialog-UGp4KDlK.js → GuestAttachDialog-Cv6QzjHC.js} +1 -1
- package/dist/assets/{GuestSurfacePane-B3pdB_2u.js → GuestSurfacePane-Bt3jB_Ye.js} +1 -1
- package/dist/assets/{JsonTreeView-7lVecnZl.js → JsonTreeView-BlyHTRhM.js} +1 -1
- package/dist/assets/{LinearIssuesView-CTGRS9Vq.js → LinearIssuesView-CSl2MUfA.js} +1 -1
- package/dist/assets/MarkdownImageGallery-2UXJF-5B.js +1 -0
- package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +12 -0
- package/dist/assets/{OnboardingScreen-CBx6cXPP.js → OnboardingScreen-CIdXJpfc.js} +1 -1
- package/dist/assets/{PatchDiff-D7VVpR_l.js → PatchDiff-ByvnbG5T.js} +1 -1
- package/dist/assets/{PierreDiffViewer-Gbfks1pk.js → PierreDiffViewer-BXieg0mH.js} +1 -1
- package/dist/assets/{PlanView-CPSK0x97.js → PlanView-DEIi3Q7M.js} +3 -3
- package/dist/assets/PluginPane-BEPUWVho.js +3 -0
- package/dist/assets/{SettingsView-Dql7z6Ww.js → SettingsView-CiNh-RbW.js} +16 -16
- package/dist/assets/{SettingsWindow-D6oi-UmV.js → SettingsWindow-BIz224xs.js} +1 -1
- package/dist/assets/{SubmoduleDiffSummary-BXA0FAWj.js → SubmoduleDiffSummary-CXKmlps9.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BQJsSbDm.js → ToolOutputDialog-BsgAK8xu.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-FY9w0TVT.js → ToolPartDiffPreview-vdPObXOf.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-B9YhAya5.js → VirtualizedFileDiff-BkFNKWS5.js} +1 -1
- package/dist/assets/{WalkthroughView-CmFgOUFN.js → WalkthroughView-6oE-MuDL.js} +2 -2
- package/dist/assets/{appThemeRegistry-BebxalUt.js → appThemeRegistry-aHUNHoqP.js} +1 -1
- package/dist/assets/{commitAndPush-Wfxng_IK.js → commitAndPush-Bon9r94r.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BCOqgixN.js → computeVirtualFileMetrics-DKqr_1AQ.js} +1 -1
- package/dist/assets/de-CgAJ51z7.js +10 -0
- package/dist/assets/es-zGi_ravM.js +16 -0
- package/dist/assets/fr-CPfogrWx.js +14 -0
- package/dist/assets/index-CHfphYL3.js +41 -0
- package/dist/assets/{index-3TiDNtfN.js → index-DpFttslC.js} +1 -1
- package/dist/assets/index-DvMJ3w6V.css +1 -0
- package/dist/assets/{isDiffPlainText-DnDYQmWK.js → isDiffPlainText-kzAgpIgi.js} +1 -1
- package/dist/assets/{isFilePlainText-BA_AHX7d.js → isFilePlainText-Uj6y-jzz.js} +1 -1
- package/dist/assets/ja-DMk6wd-U.js +16 -0
- package/dist/assets/ko-BFpzJ8jc.js +16 -0
- package/dist/assets/{main-DtUmJp9B.js → main-CbfMxn-I.js} +2 -2
- package/dist/assets/main-anyZFMIs.js +896 -0
- package/dist/assets/{markdownCore-BSnlUXBf.js → markdownCore-CmM47cAE.js} +5 -5
- package/dist/assets/{miniChat-BYfLUnDK.js → miniChat-CiAKBC10.js} +2 -2
- package/dist/assets/{mobile-DH3hI6gd.js → mobile-CsT4sJwC.js} +2 -2
- package/dist/assets/{patchFileDiff--L7lt_GZ.js → patchFileDiff-DeaE08W0.js} +1 -1
- package/dist/assets/{pl-BkI_xHqz.js → pl-VdRPcZrB.js} +5 -5
- package/dist/assets/pt-BR-BRys_lOW.js +16 -0
- package/dist/assets/{renderElectronMiniChatApp-C7kpNW_-.js → renderElectronMiniChatApp-C5677jy0.js} +2 -2
- package/dist/assets/{renderMobileApp-i0nq7Dwy.js → renderMobileApp-D4dBBAqQ.js} +7 -7
- package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +27 -0
- package/dist/assets/{scheduledTasksApi-Cy7uZCaI.js → scheduledTasksApi-BZCNJ588.js} +1 -1
- package/dist/assets/{shikiHighlight-D4vxipfr.js → shikiHighlight-BSUEa3yF.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-BYAHtJwQ.js → textMateThemeFromAppTheme-CsATFZIV.js} +1 -1
- package/dist/assets/tr-CA9ckNnm.js +7 -0
- package/dist/assets/uk-byjR-y8D.js +16 -0
- package/dist/assets/{useAppFontEffects-DHZ9-L30.js → useAppFontEffects-BWQZ5DeI.js} +153 -150
- package/dist/assets/{useInlineCommentController-CvpOMK-R.js → useInlineCommentController-DlFyVfBu.js} +1 -1
- package/dist/assets/{useRootScrollLock-DzNFi-fn.js → useRootScrollLock-Cp1eFoM2.js} +2 -2
- package/dist/assets/{vendor-codemirror-language-data-j3fhlwUM.js → vendor-codemirror-language-data-BwwommM0.js} +2 -2
- package/dist/assets/{web-components-BvHNFSEG.js → web-components-D3Yjr4Zx.js} +1 -1
- package/dist/assets/zh-CN-DRabgxdG.js +16 -0
- package/dist/assets/zh-TW-rbY5c9UK.js +16 -0
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/index.js +64 -0
- package/server/lib/event-stream/global-hub.js +23 -1
- package/server/lib/event-stream/global-hub.test.js +35 -0
- package/server/lib/event-stream/global-ws-bridge.js +3 -1
- package/server/lib/event-stream/upstream-reader.js +3 -2
- package/server/lib/opencode/DOCUMENTATION.md +6 -2
- package/server/lib/opencode/bootstrap-runtime.js +2 -1
- package/server/lib/opencode/config-entity-v2.test.js +27 -0
- package/server/lib/opencode/config-paths.test.js +12 -0
- package/server/lib/opencode/core-routes.js +17 -4
- package/server/lib/opencode/core-routes.test.js +26 -0
- package/server/lib/opencode/mcp.js +7 -2
- package/server/lib/opencode/project-directory-runtime.js +8 -0
- package/server/lib/opencode/project-directory-runtime.test.js +13 -0
- package/server/lib/opencode/proxy.js +38 -2
- package/server/lib/opencode/routes.js +18 -0
- package/server/lib/opencode/server-utils-runtime.js +5 -0
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-helpers.test.js +1 -1
- package/server/lib/opencode/settings-registry.json +3 -0
- package/server/lib/opencode/shared.js +17 -2
- package/server/lib/opencode/shutdown-runtime.js +3 -0
- package/server/lib/opencode/watcher.js +3 -1
- package/server/lib/realtime-proxy.js +5 -1
- package/server/lib/realtime-proxy.test.js +29 -0
- package/server/lib/relay/tunnel-host.js +4 -1
- package/server/lib/relay/tunnel-host.test.js +11 -0
- package/server/lib/small-model/DOCUMENTATION.md +11 -10
- package/server/lib/small-model/index.js +27 -32
- package/server/lib/small-model/index.test.js +28 -16
- package/server/lib/spaces/DOCUMENTATION.md +381 -20
- package/server/lib/spaces/code-in-bait.js +145 -6
- package/server/lib/spaces/code-in.js +10 -150
- package/server/lib/spaces/code-in.test.js +7 -83
- package/server/lib/spaces/code-out.js +1819 -0
- package/server/lib/spaces/code-out.test.js +3945 -0
- package/server/lib/spaces/code-transfer.js +173 -0
- package/server/lib/spaces/command-stream.test.js +181 -0
- package/server/lib/spaces/dispatcher.js +670 -0
- package/server/lib/spaces/dispatcher.test.js +582 -0
- package/server/lib/spaces/gatekeeper-channel.js +2 -0
- package/server/lib/spaces/gatekeeper-channel.test.js +9 -3
- package/server/lib/spaces/gatekeeper-program.cjs +4 -1
- package/server/lib/spaces/gatekeeper-program.test.js +3 -0
- package/server/lib/spaces/hardening.js +20 -4
- package/server/lib/spaces/hardening.test.js +18 -3
- package/server/lib/spaces/host-git.js +7 -4
- package/server/lib/spaces/host-git.test.js +6 -2
- package/server/lib/spaces/host.js +304 -0
- package/server/lib/spaces/host.test.js +273 -0
- package/server/lib/spaces/journey.js +393 -0
- package/server/lib/spaces/journey.test.js +384 -0
- package/server/lib/spaces/layout.js +26 -2
- package/server/lib/spaces/manager.js +4 -3
- package/server/lib/spaces/manager.test.js +6 -0
- package/server/lib/spaces/places/code-out.docker.live.test.js +412 -0
- package/server/lib/spaces/places/contract-suite.js +36 -0
- package/server/lib/spaces/places/dispatcher.docker.live.test.js +296 -0
- package/server/lib/spaces/places/docker.js +15 -3
- package/server/lib/spaces/places/docker.test.js +33 -2
- package/server/lib/spaces/places/escape-suite.js +86 -14
- package/server/lib/spaces/places/memory-place.js +24 -1
- package/server/lib/spaces/places/registry.js +1 -1
- package/server/lib/spaces/places/server.docker.live.test.js +69 -33
- package/server/lib/spaces/places/sessions.docker.live.test.js +220 -0
- package/server/lib/spaces/routes.js +207 -0
- package/server/lib/spaces/routes.test.js +211 -0
- package/server/lib/spaces/run-command.js +261 -8
- package/server/lib/spaces/run-command.test.js +193 -3
- package/server/lib/spaces/space-events.js +153 -0
- package/server/lib/spaces/space-events.test.js +160 -0
- package/server/lib/spaces/space-records.js +98 -0
- package/server/lib/spaces/space-records.test.js +73 -0
- package/server/lib/spaces/space-sessions.js +210 -0
- package/server/lib/spaces/space-sessions.test.js +161 -0
- package/server/lib/spaces/websocket.js +329 -0
- package/server/lib/spaces/websocket.test.js +345 -0
- package/server/lib/ui-auth/ui-auth.js +8 -2
- package/server/lib/ui-auth/ui-auth.test.js +29 -0
- package/server/opencode-proxy.test.js +113 -0
- package/dist/assets/MarkdownImageGallery-DQk5adUs.js +0 -1
- package/dist/assets/MarkdownRendererImpl-DPF8fZpX.js +0 -12
- package/dist/assets/PluginPane-BIGsUx69.js +0 -3
- package/dist/assets/de-CMA45TC-.js +0 -10
- package/dist/assets/es-DPL4fBtl.js +0 -16
- package/dist/assets/fr-OHBKBseP.js +0 -14
- package/dist/assets/index-BLUZa5u0.js +0 -41
- package/dist/assets/index-Cm2rrq69.css +0 -1
- package/dist/assets/ja-DvX4WSRf.js +0 -16
- package/dist/assets/ko-BUcLd8YZ.js +0 -16
- package/dist/assets/main-B_jri4i-.js +0 -896
- package/dist/assets/pt-BR-7wFtQlV9.js +0 -16
- package/dist/assets/runtimeEndpointReset-CfEYbcCc.js +0 -27
- package/dist/assets/tr-TsD-AqEH.js +0 -7
- package/dist/assets/uk-B-qspCmD.js +0 -16
- package/dist/assets/zh-CN-DYuPJV5i.js +0 -16
- package/dist/assets/zh-TW-BX_2D_lV.js +0 -16
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// The host of the feature: what `server/index.js` builds when the switch is on.
|
|
2
|
+
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
import express from 'express';
|
|
9
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
10
|
+
|
|
11
|
+
import { createSpacesHost, readOrCreateOwner } from './host.js';
|
|
12
|
+
import { hashProjectDirectory } from './labels.js';
|
|
13
|
+
import { createMemoryPlace } from './places/memory-place.js';
|
|
14
|
+
|
|
15
|
+
const folders = [];
|
|
16
|
+
const servers = [];
|
|
17
|
+
const hosts = [];
|
|
18
|
+
const temporary = () => {
|
|
19
|
+
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-spaces-host-test-'));
|
|
20
|
+
folders.push(folder);
|
|
21
|
+
return folder;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
afterEach(async () => {
|
|
25
|
+
for (const host of hosts.splice(0)) host.close();
|
|
26
|
+
for (const server of servers.splice(0)) await new Promise((resolve) => server.close(() => resolve()));
|
|
27
|
+
for (const folder of folders.splice(0)) fs.rmSync(folder, { recursive: true, force: true });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('readOrCreateOwner', () => {
|
|
31
|
+
it('makes a random owner once, readable by the user only, and keeps it', () => {
|
|
32
|
+
const dataDir = temporary();
|
|
33
|
+
const owner = readOrCreateOwner(dataDir);
|
|
34
|
+
expect(owner).toMatch(/^[0-9a-f]{24}$/);
|
|
35
|
+
expect(readOrCreateOwner(dataDir)).toBe(owner);
|
|
36
|
+
const file = path.join(dataDir, 'spaces', 'owner');
|
|
37
|
+
expect(fs.readFileSync(file, 'utf8')).toBe(`${owner}\n`);
|
|
38
|
+
if (process.platform !== 'win32') expect(fs.statSync(file).mode & 0o777).toBe(0o600);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('replaces a file that does not hold an owner', () => {
|
|
42
|
+
const dataDir = temporary();
|
|
43
|
+
fs.mkdirSync(path.join(dataDir, 'spaces'));
|
|
44
|
+
fs.writeFileSync(path.join(dataDir, 'spaces', 'owner'), 'not an owner\n');
|
|
45
|
+
expect(readOrCreateOwner(dataDir)).toMatch(/^[0-9a-f]{24}$/);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('createSpacesHost', () => {
|
|
50
|
+
it('starts no process of its own when it is made, and answers through the place it was given', async () => {
|
|
51
|
+
let started = 0;
|
|
52
|
+
const place = createMemoryPlace();
|
|
53
|
+
const host = createSpacesHost({
|
|
54
|
+
dataDir: temporary(),
|
|
55
|
+
place,
|
|
56
|
+
runCommand: async () => { started += 1; throw new Error('no process here'); },
|
|
57
|
+
openCommandStream: () => { started += 1; throw new Error('no process here'); },
|
|
58
|
+
logger: { warn: () => {} },
|
|
59
|
+
});
|
|
60
|
+
hosts.push(host);
|
|
61
|
+
const { id } = await host.manager.createSpace({ placeId: 'memory', projectDirectory: '/home/me/project', name: 'Host test' });
|
|
62
|
+
|
|
63
|
+
const app = express();
|
|
64
|
+
app.use(host.middleware);
|
|
65
|
+
app.get('/api/host', (req, res) => res.json({ directory: req.query.directory ?? null }));
|
|
66
|
+
const server = http.createServer(app);
|
|
67
|
+
servers.push(server);
|
|
68
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
69
|
+
const url = (suffix) => `http://127.0.0.1:${server.address().port}${suffix}`;
|
|
70
|
+
|
|
71
|
+
// The memory place has no token file to read, so the login step stops there: what this
|
|
72
|
+
// shows is the wiring, from the prefix through the manager's list to the space's channel.
|
|
73
|
+
const forwarded = await fetch(url(`/api/spaces/${id}/health`));
|
|
74
|
+
expect(forwarded.status).toBe(502);
|
|
75
|
+
expect(await forwarded.json()).toMatchObject({ code: 'space_setup_failed' });
|
|
76
|
+
const unknown = await fetch(url('/api/spaces/0f0f0f0f0f0f/health'));
|
|
77
|
+
expect(unknown.status).toBe(404);
|
|
78
|
+
const guarded = await fetch(url(`/api/host?directory=/spaces/${id}/repo`));
|
|
79
|
+
expect(guarded.status).toBe(400);
|
|
80
|
+
expect((await fetch(url('/api/host?directory=/home/me'))).status).toBe(200);
|
|
81
|
+
|
|
82
|
+
expect(host.skipsBodyParsing({ path: `/api/spaces/${id}/fs/raw` })).toBe(true);
|
|
83
|
+
expect(host.skipsBodyParsing({ path: '/api/fs/raw' })).toBe(false);
|
|
84
|
+
expect(host.refuseDirectory(`/spaces/${id}/repo`)).toMatch(/isolated space/);
|
|
85
|
+
expect(host.refuseDirectory('/home/me/spaces')).toBeNull();
|
|
86
|
+
expect(started).toBe(0);
|
|
87
|
+
await place.remove(id);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('carries the journey and its places, and takes no upgrade before the forwarder is made', async () => {
|
|
91
|
+
const place = createMemoryPlace();
|
|
92
|
+
const host = createSpacesHost({ dataDir: temporary(), place, listProjectDirectories: async () => ['/home/me/project'], logger: { warn: () => {} } });
|
|
93
|
+
hosts.push(host);
|
|
94
|
+
expect(host.places().map((entry) => entry.id)).toEqual(['memory']);
|
|
95
|
+
expect(await host.journey.listSpaces()).toEqual([]);
|
|
96
|
+
// The slot in index.js calls this whether or not the forwarder exists yet.
|
|
97
|
+
expect(() => host.upgradeHandler({ url: '/api/spaces/a1b2c3d4e5f6/api/event/ws', headers: {} }, { destroy: () => {} }, Buffer.alloc(0))).not.toThrow();
|
|
98
|
+
// The middleware is the dispatcher's: a request outside the prefix passes through.
|
|
99
|
+
let passed = false;
|
|
100
|
+
host.middleware({ path: '/api/host', url: '/api/host', headers: {}, query: {}, method: 'GET' }, {}, () => { passed = true; });
|
|
101
|
+
expect(passed).toBe(true);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// A stand-in place whose spaces are Express apps with the host's real UI auth: the merged
|
|
106
|
+
// session list, the event connections and the socket forwarding, wired the way `index.js` wires them.
|
|
107
|
+
import net from 'node:net';
|
|
108
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
109
|
+
import { createGlobalMessageStreamHub } from '../event-stream/global-hub.js';
|
|
110
|
+
import { SpaceError } from './errors.js';
|
|
111
|
+
import { IMAGE_CAT } from './layout.js';
|
|
112
|
+
|
|
113
|
+
const TOKEN = 'tok_' + 'a'.repeat(40);
|
|
114
|
+
const ID = 'a1b2c3d4e5f6';
|
|
115
|
+
const OTHER = '0f0f0f0f0f0f';
|
|
116
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
117
|
+
const until = async (check, timeoutMs = 3_000) => {
|
|
118
|
+
const deadline = Date.now() + timeoutMs;
|
|
119
|
+
while (!check() && Date.now() < deadline) await sleep(10);
|
|
120
|
+
return check();
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** One space's server: the sessions it lists, in pages of two, an event stream, and an echo socket. */
|
|
124
|
+
const startSpaceServer = async ({ sessions, status = {} }) => {
|
|
125
|
+
const { createUiAuth } = await import('../ui-auth/ui-auth.js');
|
|
126
|
+
const auth = createUiAuth({ password: TOKEN, readSettingsFromDiskMigrated: async () => ({}) });
|
|
127
|
+
const state = { eventStreams: [], sessions, listRequests: 0 };
|
|
128
|
+
const app = express();
|
|
129
|
+
app.post('/auth/session', express.json(), auth.handleSessionCreate);
|
|
130
|
+
app.use('/api', auth.requireAuth);
|
|
131
|
+
app.get('/api/session', (req, res) => {
|
|
132
|
+
state.listRequests += 1;
|
|
133
|
+
const start = Number.parseInt(req.query.cursor ?? '0', 10);
|
|
134
|
+
const page = state.sessions.slice(start, start + 2);
|
|
135
|
+
res.json({ data: page, cursor: { next: start + 2 < state.sessions.length ? String(start + 2) : undefined } });
|
|
136
|
+
});
|
|
137
|
+
app.get('/api/sessions/status', (_req, res) => res.json({ sessions: status }));
|
|
138
|
+
app.get('/api/event', (req, res) => {
|
|
139
|
+
res.setHeader('content-type', 'text/event-stream');
|
|
140
|
+
res.flushHeaders();
|
|
141
|
+
res.write(':ready\n\n');
|
|
142
|
+
state.eventStreams.push(res);
|
|
143
|
+
req.on('close', () => { state.eventStreams.splice(state.eventStreams.indexOf(res), 1); });
|
|
144
|
+
});
|
|
145
|
+
const server = http.createServer(app);
|
|
146
|
+
const wsServer = new WebSocketServer({ noServer: true });
|
|
147
|
+
wsServer.on('connection', (socket) => { socket.on('message', (data) => socket.send(`echo:${data}`)); });
|
|
148
|
+
server.on('upgrade', (req, socket, head) => {
|
|
149
|
+
void auth.ensureSessionToken(req, null).then((token) => {
|
|
150
|
+
if (!token || new URL(req.headers.origin ?? 'http://x').host !== req.headers.host) { socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); socket.destroy(); return; }
|
|
151
|
+
wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit('connection', ws, req));
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
155
|
+
servers.push(server);
|
|
156
|
+
return { port: server.address().port, state, wsServer, server };
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const fakePlace = (spaces) => ({
|
|
160
|
+
id: 'fake',
|
|
161
|
+
check: async () => ({ available: true }),
|
|
162
|
+
create: async () => {},
|
|
163
|
+
list: async () => Array.from(spaces.entries(), ([id, space]) => ({ id, name: id, project: space.project ?? 'p', created: '', state: space.running ? 'running' : 'exited', orphans: [], damaged: false, missing: [] })),
|
|
164
|
+
exec: async (_spaceId, argv) => (argv[0] === IMAGE_CAT ? { code: 0, stdout: `${TOKEN}\n`, stderr: '' } : { code: 127, stdout: '', stderr: 'not found' }),
|
|
165
|
+
execArgv: async () => [],
|
|
166
|
+
connect: async (spaceId) => {
|
|
167
|
+
const space = spaces.get(spaceId);
|
|
168
|
+
if (!space) throw new SpaceError('space_not_found', 'gone');
|
|
169
|
+
if (!space.running) throw new SpaceError('space_not_running', `Space ${spaceId} is stopped`);
|
|
170
|
+
return net.connect({ host: '127.0.0.1', port: space.port });
|
|
171
|
+
},
|
|
172
|
+
stop: async (spaceId) => { spaces.get(spaceId).running = false; },
|
|
173
|
+
start: async (spaceId) => { spaces.get(spaceId).running = true; },
|
|
174
|
+
remove: async (spaceId) => { spaces.delete(spaceId); return { removed: [], failed: [] }; },
|
|
175
|
+
verify: async () => [],
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe('createSpacesHost: sessions and events', () => {
|
|
179
|
+
const logs = [];
|
|
180
|
+
const logger = { warn: (line) => logs.push(line) };
|
|
181
|
+
afterEach(() => { logs.length = 0; });
|
|
182
|
+
|
|
183
|
+
it('merges every reachable space\'s sessions after the host\'s, drops what a space may not claim, and keeps a stopped space\'s last list as stale', async () => {
|
|
184
|
+
const first = await startSpaceServer({ sessions: [
|
|
185
|
+
{ id: 'a1', location: { directory: `/spaces/${ID}/repo` }, title: 'one', permissions: { x: 1 } },
|
|
186
|
+
{ id: 'a2', location: { directory: `/spaces/${ID}/repo/sub` }, title: 'two' },
|
|
187
|
+
{ id: 'a3', location: { directory: `/spaces/${ID}` }, title: 'three' },
|
|
188
|
+
{ id: 'host-1', location: { directory: `/spaces/${ID}/repo` }, title: 'a host session, claimed' },
|
|
189
|
+
{ id: 'a4', location: { directory: '/home/me/project' }, title: 'outside' },
|
|
190
|
+
] });
|
|
191
|
+
// Two spaces that list the same id are read at the same time, so which one keeps it is not
|
|
192
|
+
// fixed; that rule is proved in `space-sessions.test.js`, and here the two lists are apart.
|
|
193
|
+
const second = await startSpaceServer({ sessions: [{ id: 'b1', location: { directory: `/spaces/${OTHER}/repo` } }] });
|
|
194
|
+
// The first space was made for a registered project, the second for one this host no longer has.
|
|
195
|
+
const spaces = new Map([[ID, { port: first.port, running: true, project: hashProjectDirectory('/home/me/project') }], [OTHER, { port: second.port, running: true }]]);
|
|
196
|
+
const host = createSpacesHost({ dataDir: temporary(), place: fakePlace(spaces), logger, setTimer: () => null, clearTimer: () => {}, listProjectDirectories: async () => ['/home/me/project', '/home/me/other'] });
|
|
197
|
+
hosts.push(host);
|
|
198
|
+
const hostList = { data: [{ id: 'host-1', location: { directory: '/home/me' } }], cursor: {} };
|
|
199
|
+
const first_mark = { id: ID, name: ID, state: 'complete', sessions: 3, projectDirectory: '/home/me/project', directory: `/spaces/${ID}/project` };
|
|
200
|
+
const other_mark = (state, sessions) => ({ id: OTHER, name: OTHER, state, sessions, projectDirectory: null, directory: null });
|
|
201
|
+
|
|
202
|
+
const merged = await host.mergeSessionList(hostList);
|
|
203
|
+
expect(merged.data.map((item) => item.id)).toEqual(['host-1', 'a1', 'a2', 'a3', 'b1']);
|
|
204
|
+
// Within two seconds a second merge serves the accepted lists without asking the spaces again.
|
|
205
|
+
const pagesRead = first.state.listRequests;
|
|
206
|
+
expect(pagesRead).toBe(3);
|
|
207
|
+
expect((await host.mergeSessionList(hostList)).data.map((item) => item.id)).toEqual(['host-1', 'a1', 'a2', 'a3', 'b1']);
|
|
208
|
+
expect(first.state.listRequests).toBe(pagesRead);
|
|
209
|
+
await sleep(2_100);
|
|
210
|
+
expect(merged.data[1]).not.toHaveProperty('permissions');
|
|
211
|
+
expect(merged.spaces).toEqual([first_mark, other_mark('complete', 1)]);
|
|
212
|
+
expect(logs.join('\n')).toContain('space_session_host_id');
|
|
213
|
+
expect(logs.join('\n')).toContain('space_session_outside_root');
|
|
214
|
+
expect(logs.join('\n')).not.toContain('a host session, claimed');
|
|
215
|
+
|
|
216
|
+
// A stopped space takes the pooled streams with it: the stand-in drops its connections too.
|
|
217
|
+
await host.manager.stopSpace({ placeId: 'fake', spaceId: OTHER });
|
|
218
|
+
second.server.closeAllConnections();
|
|
219
|
+
second.state.sessions.length = 0;
|
|
220
|
+
const stale = await host.mergeSessionList(hostList);
|
|
221
|
+
expect(stale.data.map((item) => item.id)).toEqual(['host-1', 'a1', 'a2', 'a3', 'b1']);
|
|
222
|
+
expect(stale.spaces).toEqual([first_mark, other_mark('stale', 1)]);
|
|
223
|
+
expect(logs.join('\n')).toContain(`the session list of space ${OTHER} did not come`);
|
|
224
|
+
|
|
225
|
+
// Back, and empty: an empty answer is an answer.
|
|
226
|
+
await host.manager.startSpace({ placeId: 'fake', spaceId: OTHER });
|
|
227
|
+
const empty = await host.mergeSessionList(hostList);
|
|
228
|
+
expect(empty.spaces[1]).toEqual(other_mark('complete', 0));
|
|
229
|
+
|
|
230
|
+
// A space that is gone is not listed; a host without spaces answers with the very same object.
|
|
231
|
+
spaces.clear();
|
|
232
|
+
await sleep(2_100);
|
|
233
|
+
expect(await host.mergeSessionList(hostList)).toBe(hostList);
|
|
234
|
+
}, 10_000);
|
|
235
|
+
|
|
236
|
+
it('follows the spaces into the hub: their events arrive marked, the host\'s ids are learned from the hub, and sockets are forwarded', async () => {
|
|
237
|
+
const space = await startSpaceServer({ sessions: [], status: { busy1: { status: 'busy' } } });
|
|
238
|
+
const spaces = new Map([[ID, { port: space.port, running: true }]]);
|
|
239
|
+
const host = createSpacesHost({ dataDir: temporary(), place: fakePlace(spaces), logger, setTimer: () => null, clearTimer: () => {} });
|
|
240
|
+
hosts.push(host);
|
|
241
|
+
const hub = createGlobalMessageStreamHub({ buildOpenCodeUrl: (p) => `http://127.0.0.1:1${p}`, getOpenCodeAuthHeaders: () => ({}), deltaCoalesceWindowMs: 0, fetchImpl: async () => { throw new Error('no host upstream here'); } });
|
|
242
|
+
const received = [];
|
|
243
|
+
hub.subscribeEvent((event) => received.push(event), { spaces: true });
|
|
244
|
+
await host.startEvents(hub);
|
|
245
|
+
expect(await until(() => space.state.eventStreams.length === 1)).toBe(true);
|
|
246
|
+
expect(await until(() => received.some((event) => event.payload.type === 'session.status' && event.payload.data.sessionID === 'busy1'))).toBe(true);
|
|
247
|
+
|
|
248
|
+
hub.injectEvent({ payload: { type: 'session.created', data: { sessionID: 'host-new' } }, directory: '/home/me', spaceId: null });
|
|
249
|
+
space.state.eventStreams[0].write(`data: ${JSON.stringify({ id: 'e1', type: 'session.execution.started', data: { sessionID: 'host-new' } })}\n\n`);
|
|
250
|
+
space.state.eventStreams[0].write(`data: ${JSON.stringify({ id: 'e2', type: 'session.execution.started', data: { sessionID: 'mine' }, location: { directory: `/spaces/${ID}/repo` } })}\n\n`);
|
|
251
|
+
expect(await until(() => received.some((event) => event.payload.id === 'e2'))).toBe(true);
|
|
252
|
+
expect(received.find((event) => event.payload.id === 'e2')).toMatchObject({ spaceId: ID, directory: `/spaces/${ID}/repo` });
|
|
253
|
+
expect(received.some((event) => event.payload.id === 'e1')).toBe(false);
|
|
254
|
+
expect(logs.join('\n')).toContain('space_event_host_session');
|
|
255
|
+
|
|
256
|
+
const server = http.createServer((_req, res) => { res.statusCode = 404; res.end(); });
|
|
257
|
+
servers.push(server);
|
|
258
|
+
host.prepareUpgrades({ uiAuthController: { enabled: false }, isRequestOriginAllowed: async () => true });
|
|
259
|
+
server.on('upgrade', host.upgradeHandler);
|
|
260
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
261
|
+
const socket = new WebSocket(`ws://127.0.0.1:${server.address().port}/api/spaces/${ID}/terminal/ws`, { headers: { origin: 'http://app.test' } });
|
|
262
|
+
const echoed = await new Promise((resolve, reject) => {
|
|
263
|
+
socket.on('open', () => socket.send('hi'));
|
|
264
|
+
socket.on('message', (data) => resolve(data.toString('utf8')));
|
|
265
|
+
socket.on('error', reject);
|
|
266
|
+
});
|
|
267
|
+
expect(echoed).toBe('echo:hi');
|
|
268
|
+
socket.close();
|
|
269
|
+
host.close();
|
|
270
|
+
expect(await until(() => space.state.eventStreams.length === 0)).toBe(true);
|
|
271
|
+
space.wsServer.close();
|
|
272
|
+
});
|
|
273
|
+
});
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// The journey of a space as the host drives it: made with its network choice and the project's
|
|
2
|
+
// code, listed with its state, started again with its network said again to a gatekeeper that
|
|
3
|
+
// forgot it, stopped, removed with everything the host kept for it, its journal read, and its
|
|
4
|
+
// work brought out and applied. Everything here is written once on top of the manager, the
|
|
5
|
+
// gatekeeper channel, code in and code out; the routes in `routes.js` only translate HTTP.
|
|
6
|
+
//
|
|
7
|
+
// A creation runs in the background: the request comes back at once with the space's id, and the
|
|
8
|
+
// steps are announced as `openchamber:space-progress` events on the host's hub, so the group in
|
|
9
|
+
// the sidebar can say what is happening now (DESIGN.md, journey step 2). A creation that fails
|
|
10
|
+
// after the containers exist removes them again, and its failure stays listed until the user
|
|
11
|
+
// dismisses it, so an error is never silent.
|
|
12
|
+
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
|
|
15
|
+
import { SpaceError } from './errors.js';
|
|
16
|
+
import { createSpaceId, hashProjectDirectory } from './labels.js';
|
|
17
|
+
import { spaceProjectPath } from './layout.js';
|
|
18
|
+
import { networkSchema } from './space-records.js';
|
|
19
|
+
|
|
20
|
+
// The four choices of the create dialog, parsed at the boundary. Each field refuses with a code
|
|
21
|
+
// of its own, so the dialog can point at the field.
|
|
22
|
+
const createRequestSchema = z.object({
|
|
23
|
+
projectDirectory: z.string().min(1),
|
|
24
|
+
name: z.string().trim().min(1),
|
|
25
|
+
start: z.enum(['clean', 'uncommitted']).default('uncommitted'),
|
|
26
|
+
network: networkSchema.default({ mode: 'allowlist', domains: [] }),
|
|
27
|
+
});
|
|
28
|
+
const CREATE_REFUSALS = {
|
|
29
|
+
projectDirectory: ['project_not_registered', 'A space is made for a project this OpenChamber knows. Add the project first, then create the space.'],
|
|
30
|
+
name: ['invalid_space_name', 'A space needs a name.'],
|
|
31
|
+
start: ['invalid_snapshot_mode', 'A space starts from a clean commit or with the uncommitted changes.'],
|
|
32
|
+
network: ['invalid_network', 'The network of a space is allowlist or open, with a list of domain names for the allowlist.'],
|
|
33
|
+
};
|
|
34
|
+
const applyRequestSchema = z.discriminatedUnion('as', [
|
|
35
|
+
z.object({ as: z.literal('branch'), branch: z.string(), removeAfterwards: z.boolean().default(false) }),
|
|
36
|
+
z.object({ as: z.literal('changes'), removeAfterwards: z.boolean().default(false) }),
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
const failureOf = (error) => ({
|
|
40
|
+
code: error instanceof SpaceError ? error.code : 'space_journey_failed',
|
|
41
|
+
message: error?.message ?? String(error),
|
|
42
|
+
details: error instanceof SpaceError ? error.details ?? null : null,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* `listProjectDirectories` answers the host's registered projects; a space is made for one of them
|
|
47
|
+
* and its label carries the project's hash. `announce(spaceId, payload)` enters an event into the
|
|
48
|
+
* host's hub, `onSpacesChanged()` tells the host to read its list again at once.
|
|
49
|
+
*/
|
|
50
|
+
export function createSpaceJourney({
|
|
51
|
+
manager,
|
|
52
|
+
place,
|
|
53
|
+
gatekeeper,
|
|
54
|
+
codeIn,
|
|
55
|
+
codeOut,
|
|
56
|
+
records,
|
|
57
|
+
listProjectDirectories,
|
|
58
|
+
announce = () => {},
|
|
59
|
+
onSpacesChanged = () => {},
|
|
60
|
+
logger = console,
|
|
61
|
+
now = () => new Date(),
|
|
62
|
+
}) {
|
|
63
|
+
// Creations under way or failed, by space id, until they succeed or the user dismisses them.
|
|
64
|
+
const pending = new Map();
|
|
65
|
+
// Spaces with an action under way: start, stop, remove, journal or apply. One at a time per space,
|
|
66
|
+
// so a remove cannot pull the refs from under an apply that is writing them.
|
|
67
|
+
const busy = new Set();
|
|
68
|
+
// Set while the switch is being turned off: no creation may slip in between the stop of the
|
|
69
|
+
// spaces and the moment the feature is gone.
|
|
70
|
+
let closing = false;
|
|
71
|
+
|
|
72
|
+
const exclusive = async (spaceId, work) => {
|
|
73
|
+
if (busy.has(spaceId)) throw new SpaceError('space_busy', 'Another action on this space is still running. Wait for it to finish.');
|
|
74
|
+
busy.add(spaceId);
|
|
75
|
+
try {
|
|
76
|
+
return await work();
|
|
77
|
+
} finally {
|
|
78
|
+
busy.delete(spaceId);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Refuses an action on a creation under way, and names a failed one for what it is. */
|
|
83
|
+
const requireNotPending = (spaceId) => {
|
|
84
|
+
const waiting = pending.get(spaceId);
|
|
85
|
+
if (!waiting) return;
|
|
86
|
+
if (waiting.state === 'failed') throw new SpaceError('space_creation_failed', 'Making this space failed. Dismiss it, then create a new one.');
|
|
87
|
+
throw new SpaceError('space_preparing', 'This space is still being made.');
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const registeredProjects = async () => {
|
|
91
|
+
const directories = await listProjectDirectories();
|
|
92
|
+
return new Map(directories.map((directory) => [hashProjectDirectory(directory), directory]));
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const requireRegisteredProject = async (directory) => {
|
|
96
|
+
const projects = await registeredProjects();
|
|
97
|
+
if (projects.get(hashProjectDirectory(directory)) !== directory) {
|
|
98
|
+
throw new SpaceError(...CREATE_REFUSALS.projectDirectory);
|
|
99
|
+
}
|
|
100
|
+
return directory;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const progress = (entry, step, failure = null) => {
|
|
104
|
+
entry.step = step;
|
|
105
|
+
entry.state = step === 'failed' ? 'failed' : step === 'ready' ? 'running' : 'preparing';
|
|
106
|
+
entry.failure = failure;
|
|
107
|
+
announce(entry.id, { type: 'openchamber:space-progress', properties: { spaceId: entry.id, step, failure, timestamp: now().getTime() } });
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Removes the space and everything the host kept for it, and says what did not go. */
|
|
111
|
+
const removeEverything = async (spaceId, repository) => {
|
|
112
|
+
const outcome = { removed: false, refsRemoved: null, failures: [] };
|
|
113
|
+
try {
|
|
114
|
+
await manager.removeSpace({ placeId: place.id, spaceId });
|
|
115
|
+
outcome.removed = true;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
outcome.failures.push(failureOf(error));
|
|
118
|
+
}
|
|
119
|
+
if (repository) {
|
|
120
|
+
try {
|
|
121
|
+
await codeIn.removeSpaceRefs({ repository, spaceId });
|
|
122
|
+
outcome.refsRemoved = true;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
outcome.refsRemoved = false;
|
|
125
|
+
outcome.failures.push(failureOf(error));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
records.remove(spaceId);
|
|
129
|
+
return outcome;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const sendHistoryInBackground = ({ repository, spaceId, spacePath, base }) => {
|
|
133
|
+
codeIn.sendHistory({ repository, spaceId, spacePath, base })
|
|
134
|
+
.then((result) => { records.update(spaceId, { history: result.status }); })
|
|
135
|
+
.catch((error) => {
|
|
136
|
+
logger.warn?.(`[spaces] the history of space ${spaceId} did not arrive: ${error?.details?.cause ?? error?.code ?? error?.message}`);
|
|
137
|
+
records.update(spaceId, { history: 'failed' });
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const prepare = async (entry, { projectDirectory, name, start, network }) => {
|
|
142
|
+
let created = false;
|
|
143
|
+
try {
|
|
144
|
+
progress(entry, 'checking_place');
|
|
145
|
+
const check = await place.check();
|
|
146
|
+
if (!check.available) throw new SpaceError(check.code, check.message);
|
|
147
|
+
if (network.mode === 'allowlist' && check.hostIsolation !== true) {
|
|
148
|
+
throw new SpaceError('place_cannot_restrict_network', 'This place cannot keep a space away from the machine it runs on, so an allowlist would not hold. Use a newer Docker engine, or choose the open network with that in mind.');
|
|
149
|
+
}
|
|
150
|
+
progress(entry, 'creating');
|
|
151
|
+
await manager.createSpace({ id: entry.id, placeId: place.id, projectDirectory, name });
|
|
152
|
+
created = true;
|
|
153
|
+
records.write(entry.id, { network, repository: projectDirectory });
|
|
154
|
+
progress(entry, 'setting_network');
|
|
155
|
+
await gatekeeper.setNetwork(entry.id, network);
|
|
156
|
+
progress(entry, 'bringing_code');
|
|
157
|
+
const arrived = await codeIn.bringCodeIn({ repository: projectDirectory, spaceId: entry.id, mode: start });
|
|
158
|
+
records.update(entry.id, { spacePath: arrived.spacePath, base: arrived.base });
|
|
159
|
+
entry.identityCopied = arrived.identityCopied;
|
|
160
|
+
pending.delete(entry.id);
|
|
161
|
+
progress(entry, 'ready');
|
|
162
|
+
onSpacesChanged();
|
|
163
|
+
sendHistoryInBackground({ repository: projectDirectory, spaceId: entry.id, spacePath: arrived.spacePath, base: arrived.base });
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const failure = failureOf(error);
|
|
166
|
+
if (created) {
|
|
167
|
+
const cleanup = await removeEverything(entry.id, projectDirectory);
|
|
168
|
+
if (cleanup.failures.length > 0) failure.cleanup = cleanup.failures;
|
|
169
|
+
}
|
|
170
|
+
logger.warn?.(`[spaces] creating space ${entry.id} failed at ${entry.step}: ${failure.code}`);
|
|
171
|
+
progress(entry, 'failed', failure);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Starts making a space and answers at once with the entry the list will carry. The four
|
|
177
|
+
* choices of the create dialog come in: the project, the name, the starting point and the
|
|
178
|
+
* network. The place is checked inside, as decision 19 asks: nothing probes a runtime before
|
|
179
|
+
* the user acts.
|
|
180
|
+
*/
|
|
181
|
+
const createSpace = async (request) => {
|
|
182
|
+
if (closing) throw new SpaceError('isolated_spaces_off', 'Isolated spaces are being turned off.');
|
|
183
|
+
const parsed = createRequestSchema.safeParse(request ?? {});
|
|
184
|
+
if (!parsed.success) {
|
|
185
|
+
const [code, message] = CREATE_REFUSALS[parsed.error.issues[0]?.path?.[0]] ?? CREATE_REFUSALS.network;
|
|
186
|
+
throw new SpaceError(code, message);
|
|
187
|
+
}
|
|
188
|
+
const { name, start, network } = parsed.data;
|
|
189
|
+
const projectDirectory = await requireRegisteredProject(parsed.data.projectDirectory);
|
|
190
|
+
const id = createSpaceId();
|
|
191
|
+
const entry = {
|
|
192
|
+
id,
|
|
193
|
+
name,
|
|
194
|
+
placeId: place.id,
|
|
195
|
+
projectDirectory,
|
|
196
|
+
directory: spaceProjectPath(id, projectDirectory),
|
|
197
|
+
created: now().toISOString(),
|
|
198
|
+
state: 'preparing',
|
|
199
|
+
step: 'checking_place',
|
|
200
|
+
failure: null,
|
|
201
|
+
network,
|
|
202
|
+
};
|
|
203
|
+
pending.set(entry.id, entry);
|
|
204
|
+
void prepare(entry, { projectDirectory, name, start, network });
|
|
205
|
+
return describePending(entry);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const describePending = (entry) => ({
|
|
209
|
+
id: entry.id,
|
|
210
|
+
name: entry.name,
|
|
211
|
+
placeId: entry.placeId,
|
|
212
|
+
projectDirectory: entry.projectDirectory,
|
|
213
|
+
directory: entry.directory,
|
|
214
|
+
created: entry.created,
|
|
215
|
+
state: entry.state,
|
|
216
|
+
step: entry.step,
|
|
217
|
+
failure: entry.failure,
|
|
218
|
+
network: entry.network,
|
|
219
|
+
history: 'pending',
|
|
220
|
+
damaged: false,
|
|
221
|
+
missing: [],
|
|
222
|
+
orphans: [],
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Every space of this host: the place's list with what the host remembers about each, the
|
|
227
|
+
* creations under way in their place, and the failed ones after it. A record the host cannot read leaves `network` null,
|
|
228
|
+
* which the UI must show as "unknown" and never as "open".
|
|
229
|
+
*/
|
|
230
|
+
const listSpaces = async () => {
|
|
231
|
+
const [spaces, projects] = await Promise.all([manager.listSpaces({ placeId: place.id }), registeredProjects()]);
|
|
232
|
+
const listed = spaces.map((space) => {
|
|
233
|
+
const projectDirectory = projects.get(space.project) ?? null;
|
|
234
|
+
const { record } = records.read(space.id);
|
|
235
|
+
return {
|
|
236
|
+
id: space.id,
|
|
237
|
+
name: space.name,
|
|
238
|
+
placeId: space.placeId,
|
|
239
|
+
projectDirectory,
|
|
240
|
+
directory: projectDirectory === null ? null : spaceProjectPath(space.id, projectDirectory),
|
|
241
|
+
created: space.created,
|
|
242
|
+
state: space.state,
|
|
243
|
+
step: null,
|
|
244
|
+
failure: null,
|
|
245
|
+
network: record?.network ?? null,
|
|
246
|
+
history: record?.history ?? 'unknown',
|
|
247
|
+
damaged: space.damaged,
|
|
248
|
+
missing: space.missing,
|
|
249
|
+
orphans: space.orphans,
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
// A creation under way wins over the place's view of it: the containers run before the code is there.
|
|
253
|
+
const waiting = new Map(Array.from(pending.values(), (entry) => [entry.id, describePending(entry)]));
|
|
254
|
+
const merged = listed.map((space) => waiting.get(space.id) ?? space);
|
|
255
|
+
const known = new Set(listed.map((space) => space.id));
|
|
256
|
+
return [...merged, ...Array.from(waiting.values()).filter((entry) => !known.has(entry.id))];
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const requireListed = async (spaceId) => {
|
|
260
|
+
const space = (await listSpaces()).find((entry) => entry.id === spaceId);
|
|
261
|
+
if (!space) throw new SpaceError('space_not_found', `There is no space ${spaceId}`);
|
|
262
|
+
return space;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Starts a stopped space. Its gatekeeper comes up allowing nothing, so the network the user
|
|
267
|
+
* chose is said again from the record; without a readable record the space stays closed, and
|
|
268
|
+
* the answer says so with `networkRestored` false.
|
|
269
|
+
*/
|
|
270
|
+
const startSpace = (spaceId) => exclusive(spaceId, async () => {
|
|
271
|
+
// As for a creation: no start may slip in while the switch is stopping the spaces one by one.
|
|
272
|
+
if (closing) throw new SpaceError('isolated_spaces_off', 'Isolated spaces are being turned off.');
|
|
273
|
+
requireNotPending(spaceId);
|
|
274
|
+
await manager.startSpace({ placeId: place.id, spaceId });
|
|
275
|
+
const { record } = records.read(spaceId);
|
|
276
|
+
let networkRestored = false;
|
|
277
|
+
if (record) {
|
|
278
|
+
await gatekeeper.setNetwork(spaceId, record.network);
|
|
279
|
+
networkRestored = true;
|
|
280
|
+
// A history that never arrived, or that failed, is sent again: a stop right after the
|
|
281
|
+
// creation is the usual way it fails, and the space would otherwise stay shallow for good.
|
|
282
|
+
if ((record.history === 'pending' || record.history === 'failed') && record.repository && record.spacePath && record.base) {
|
|
283
|
+
sendHistoryInBackground({ repository: record.repository, spaceId, spacePath: record.spacePath, base: record.base });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
onSpacesChanged();
|
|
287
|
+
return { ...(await requireListed(spaceId)), networkRestored };
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const stopSpace = (spaceId) => exclusive(spaceId, async () => {
|
|
291
|
+
requireNotPending(spaceId);
|
|
292
|
+
await manager.stopSpace({ placeId: place.id, spaceId });
|
|
293
|
+
onSpacesChanged();
|
|
294
|
+
return requireListed(spaceId);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Removes a space and everything the host kept for it: the containers, networks and volumes,
|
|
299
|
+
* the service refs in the user's repository and the record. A failed creation is forgotten here.
|
|
300
|
+
* The chat archive of decision 9 is a later stage; today the sessions go with the space.
|
|
301
|
+
*/
|
|
302
|
+
const removeUnlocked = async (spaceId) => {
|
|
303
|
+
const waiting = pending.get(spaceId);
|
|
304
|
+
if (waiting) {
|
|
305
|
+
if (waiting.state !== 'failed') throw new SpaceError('space_preparing', 'This space is still being made. Wait for it, then remove it.');
|
|
306
|
+
pending.delete(spaceId);
|
|
307
|
+
// A failed creation whose clean-up failed still has containers; those go now, or the space
|
|
308
|
+
// comes back in the list as damaged. One that was cleaned up has nothing left to remove.
|
|
309
|
+
const still = (await manager.listSpaces({ placeId: place.id })).some((space) => space.id === spaceId);
|
|
310
|
+
if (!still) return { id: spaceId, removed: true, refsRemoved: null, failures: [] };
|
|
311
|
+
return { id: spaceId, ...(await removeEverything(spaceId, waiting.projectDirectory)) };
|
|
312
|
+
}
|
|
313
|
+
const space = await requireListed(spaceId);
|
|
314
|
+
const { record } = records.read(spaceId);
|
|
315
|
+
const outcome = await removeEverything(spaceId, record?.repository ?? space.projectDirectory);
|
|
316
|
+
onSpacesChanged();
|
|
317
|
+
return { id: spaceId, ...outcome };
|
|
318
|
+
};
|
|
319
|
+
const removeSpace = (spaceId) => exclusive(spaceId, () => removeUnlocked(spaceId));
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Stops every running space, for the switch being turned off. Each space is tried on its own:
|
|
323
|
+
* one that could not be stopped is reported as still running, never counted as stopped.
|
|
324
|
+
*/
|
|
325
|
+
const stopAllSpaces = async () => {
|
|
326
|
+
const preparing = Array.from(pending.values()).filter((entry) => entry.state === 'preparing');
|
|
327
|
+
if (preparing.length > 0) throw new SpaceError('space_preparing', `${preparing.length === 1 ? 'A space is' : `${preparing.length} spaces are`} still being made. Wait for that to finish first.`, { spaces: preparing.map((entry) => entry.id) });
|
|
328
|
+
closing = true;
|
|
329
|
+
const spaces = await manager.listSpaces({ placeId: place.id });
|
|
330
|
+
const stopped = [];
|
|
331
|
+
const stillRunning = [];
|
|
332
|
+
for (const space of spaces) {
|
|
333
|
+
if (space.state !== 'running') continue;
|
|
334
|
+
try {
|
|
335
|
+
await manager.stopSpace({ placeId: place.id, spaceId: space.id });
|
|
336
|
+
stopped.push({ id: space.id, name: space.name });
|
|
337
|
+
} catch (error) {
|
|
338
|
+
stillRunning.push({ id: space.id, name: space.name, ...failureOf(error) });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return { stopped, stillRunning };
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
/** For a turn-off that did not go through after the spaces were stopped: creations are taken again. */
|
|
345
|
+
const reopen = () => { closing = false; };
|
|
346
|
+
|
|
347
|
+
/** What the gatekeeper allowed and refused since it last started; a stopped space has no journal. */
|
|
348
|
+
const readJournal = (spaceId) => exclusive(spaceId, async () => {
|
|
349
|
+
const space = await requireListed(spaceId);
|
|
350
|
+
if (space.state !== 'running') {
|
|
351
|
+
throw new SpaceError('space_not_running', 'The journal lives in the memory of the space\'s gatekeeper and is gone with a stop. Start the space to record new attempts.');
|
|
352
|
+
}
|
|
353
|
+
return gatekeeper.readJournal(spaceId);
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
const requireRepository = async (spaceId) => {
|
|
357
|
+
requireNotPending(spaceId);
|
|
358
|
+
const space = await requireListed(spaceId);
|
|
359
|
+
const { record } = records.read(spaceId);
|
|
360
|
+
const repository = record?.repository ?? space.projectDirectory;
|
|
361
|
+
if (!repository) throw new SpaceError('project_not_registered', 'The project this space was made for is no longer registered, so its work has nowhere to go.');
|
|
362
|
+
return { space, repository, spacePath: record?.spacePath ?? space.directory };
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
/** Brings the work out and describes what an apply would do, for the apply dialog. */
|
|
366
|
+
const previewApply = (spaceId) => exclusive(spaceId, async () => {
|
|
367
|
+
const { repository, spacePath } = await requireRepository(spaceId);
|
|
368
|
+
const brought = await codeOut.bringCodeOut({ repository, spaceId, spacePath });
|
|
369
|
+
const state = await codeOut.describeApplyState({ repository, spaceId });
|
|
370
|
+
return { ...brought, ...state };
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Brings the work out once more and applies it as a branch or as uncommitted changes. What is
|
|
375
|
+
* applied is what this call fetched, whatever a preview showed. With `removeAfterwards` the
|
|
376
|
+
* space goes once the apply went through, and only then.
|
|
377
|
+
*/
|
|
378
|
+
const applySpace = (spaceId, request) => exclusive(spaceId, async () => {
|
|
379
|
+
const parsed = applyRequestSchema.safeParse(request ?? {});
|
|
380
|
+
if (!parsed.success) throw new SpaceError('invalid_apply_request', 'The work is applied as a branch, with its name, or as uncommitted changes.');
|
|
381
|
+
const { as, removeAfterwards } = parsed.data;
|
|
382
|
+
const branch = as === 'branch' ? parsed.data.branch : null;
|
|
383
|
+
const { repository, spacePath } = await requireRepository(spaceId);
|
|
384
|
+
const brought = await codeOut.bringCodeOut({ repository, spaceId, spacePath });
|
|
385
|
+
const applied = as === 'branch'
|
|
386
|
+
? { status: 'applied', ...(await codeOut.applyAsBranch({ repository, spaceId, branch })) }
|
|
387
|
+
: await codeOut.applyAsChanges({ repository, spaceId });
|
|
388
|
+
const removal = removeAfterwards && applied.status === 'applied' ? await removeUnlocked(spaceId) : null;
|
|
389
|
+
return { brought, applied, removal };
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
return { createSpace, listSpaces, startSpace, stopSpace, removeSpace, stopAllSpaces, reopen, readJournal, previewApply, applySpace };
|
|
393
|
+
}
|