@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.
Files changed (159) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-zm3C1FvM.js → CodeMirrorCommentWidgets-CmKmyb9T.js} +1 -1
  2. package/dist/assets/{DiffView-DNExNi1z.js → DiffView-8-PFpZ2p.js} +1 -1
  3. package/dist/assets/{FilesView-DUCLmHBi.js → FilesView-0Ie20mEk.js} +9 -9
  4. package/dist/assets/{GitView-Bz9z6gZA.js → GitView-DNUSu00w.js} +1 -1
  5. package/dist/assets/{GuestAttachDialog-UGp4KDlK.js → GuestAttachDialog-Cv6QzjHC.js} +1 -1
  6. package/dist/assets/{GuestSurfacePane-B3pdB_2u.js → GuestSurfacePane-Bt3jB_Ye.js} +1 -1
  7. package/dist/assets/{JsonTreeView-7lVecnZl.js → JsonTreeView-BlyHTRhM.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-CTGRS9Vq.js → LinearIssuesView-CSl2MUfA.js} +1 -1
  9. package/dist/assets/MarkdownImageGallery-2UXJF-5B.js +1 -0
  10. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +12 -0
  11. package/dist/assets/{OnboardingScreen-CBx6cXPP.js → OnboardingScreen-CIdXJpfc.js} +1 -1
  12. package/dist/assets/{PatchDiff-D7VVpR_l.js → PatchDiff-ByvnbG5T.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-Gbfks1pk.js → PierreDiffViewer-BXieg0mH.js} +1 -1
  14. package/dist/assets/{PlanView-CPSK0x97.js → PlanView-DEIi3Q7M.js} +3 -3
  15. package/dist/assets/PluginPane-BEPUWVho.js +3 -0
  16. package/dist/assets/{SettingsView-Dql7z6Ww.js → SettingsView-CiNh-RbW.js} +16 -16
  17. package/dist/assets/{SettingsWindow-D6oi-UmV.js → SettingsWindow-BIz224xs.js} +1 -1
  18. package/dist/assets/{SubmoduleDiffSummary-BXA0FAWj.js → SubmoduleDiffSummary-CXKmlps9.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-BQJsSbDm.js → ToolOutputDialog-BsgAK8xu.js} +6 -6
  20. package/dist/assets/{ToolPartDiffPreview-FY9w0TVT.js → ToolPartDiffPreview-vdPObXOf.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-B9YhAya5.js → VirtualizedFileDiff-BkFNKWS5.js} +1 -1
  22. package/dist/assets/{WalkthroughView-CmFgOUFN.js → WalkthroughView-6oE-MuDL.js} +2 -2
  23. package/dist/assets/{appThemeRegistry-BebxalUt.js → appThemeRegistry-aHUNHoqP.js} +1 -1
  24. package/dist/assets/{commitAndPush-Wfxng_IK.js → commitAndPush-Bon9r94r.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-BCOqgixN.js → computeVirtualFileMetrics-DKqr_1AQ.js} +1 -1
  26. package/dist/assets/de-CgAJ51z7.js +10 -0
  27. package/dist/assets/es-zGi_ravM.js +16 -0
  28. package/dist/assets/fr-CPfogrWx.js +14 -0
  29. package/dist/assets/index-CHfphYL3.js +41 -0
  30. package/dist/assets/{index-3TiDNtfN.js → index-DpFttslC.js} +1 -1
  31. package/dist/assets/index-DvMJ3w6V.css +1 -0
  32. package/dist/assets/{isDiffPlainText-DnDYQmWK.js → isDiffPlainText-kzAgpIgi.js} +1 -1
  33. package/dist/assets/{isFilePlainText-BA_AHX7d.js → isFilePlainText-Uj6y-jzz.js} +1 -1
  34. package/dist/assets/ja-DMk6wd-U.js +16 -0
  35. package/dist/assets/ko-BFpzJ8jc.js +16 -0
  36. package/dist/assets/{main-DtUmJp9B.js → main-CbfMxn-I.js} +2 -2
  37. package/dist/assets/main-anyZFMIs.js +896 -0
  38. package/dist/assets/{markdownCore-BSnlUXBf.js → markdownCore-CmM47cAE.js} +5 -5
  39. package/dist/assets/{miniChat-BYfLUnDK.js → miniChat-CiAKBC10.js} +2 -2
  40. package/dist/assets/{mobile-DH3hI6gd.js → mobile-CsT4sJwC.js} +2 -2
  41. package/dist/assets/{patchFileDiff--L7lt_GZ.js → patchFileDiff-DeaE08W0.js} +1 -1
  42. package/dist/assets/{pl-BkI_xHqz.js → pl-VdRPcZrB.js} +5 -5
  43. package/dist/assets/pt-BR-BRys_lOW.js +16 -0
  44. package/dist/assets/{renderElectronMiniChatApp-C7kpNW_-.js → renderElectronMiniChatApp-C5677jy0.js} +2 -2
  45. package/dist/assets/{renderMobileApp-i0nq7Dwy.js → renderMobileApp-D4dBBAqQ.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +27 -0
  47. package/dist/assets/{scheduledTasksApi-Cy7uZCaI.js → scheduledTasksApi-BZCNJ588.js} +1 -1
  48. package/dist/assets/{shikiHighlight-D4vxipfr.js → shikiHighlight-BSUEa3yF.js} +1 -1
  49. package/dist/assets/{textMateThemeFromAppTheme-BYAHtJwQ.js → textMateThemeFromAppTheme-CsATFZIV.js} +1 -1
  50. package/dist/assets/tr-CA9ckNnm.js +7 -0
  51. package/dist/assets/uk-byjR-y8D.js +16 -0
  52. package/dist/assets/{useAppFontEffects-DHZ9-L30.js → useAppFontEffects-BWQZ5DeI.js} +153 -150
  53. package/dist/assets/{useInlineCommentController-CvpOMK-R.js → useInlineCommentController-DlFyVfBu.js} +1 -1
  54. package/dist/assets/{useRootScrollLock-DzNFi-fn.js → useRootScrollLock-Cp1eFoM2.js} +2 -2
  55. package/dist/assets/{vendor-codemirror-language-data-j3fhlwUM.js → vendor-codemirror-language-data-BwwommM0.js} +2 -2
  56. package/dist/assets/{web-components-BvHNFSEG.js → web-components-D3Yjr4Zx.js} +1 -1
  57. package/dist/assets/zh-CN-DRabgxdG.js +16 -0
  58. package/dist/assets/zh-TW-rbY5c9UK.js +16 -0
  59. package/dist/index.html +3 -3
  60. package/dist/mini-chat.html +3 -3
  61. package/dist/mobile.html +3 -3
  62. package/package.json +2 -2
  63. package/server/index.js +64 -0
  64. package/server/lib/event-stream/global-hub.js +23 -1
  65. package/server/lib/event-stream/global-hub.test.js +35 -0
  66. package/server/lib/event-stream/global-ws-bridge.js +3 -1
  67. package/server/lib/event-stream/upstream-reader.js +3 -2
  68. package/server/lib/opencode/DOCUMENTATION.md +6 -2
  69. package/server/lib/opencode/bootstrap-runtime.js +2 -1
  70. package/server/lib/opencode/config-entity-v2.test.js +27 -0
  71. package/server/lib/opencode/config-paths.test.js +12 -0
  72. package/server/lib/opencode/core-routes.js +17 -4
  73. package/server/lib/opencode/core-routes.test.js +26 -0
  74. package/server/lib/opencode/mcp.js +7 -2
  75. package/server/lib/opencode/project-directory-runtime.js +8 -0
  76. package/server/lib/opencode/project-directory-runtime.test.js +13 -0
  77. package/server/lib/opencode/proxy.js +38 -2
  78. package/server/lib/opencode/routes.js +18 -0
  79. package/server/lib/opencode/server-utils-runtime.js +5 -0
  80. package/server/lib/opencode/settings-helpers.js +3 -0
  81. package/server/lib/opencode/settings-helpers.test.js +1 -1
  82. package/server/lib/opencode/settings-registry.json +3 -0
  83. package/server/lib/opencode/shared.js +17 -2
  84. package/server/lib/opencode/shutdown-runtime.js +3 -0
  85. package/server/lib/opencode/watcher.js +3 -1
  86. package/server/lib/realtime-proxy.js +5 -1
  87. package/server/lib/realtime-proxy.test.js +29 -0
  88. package/server/lib/relay/tunnel-host.js +4 -1
  89. package/server/lib/relay/tunnel-host.test.js +11 -0
  90. package/server/lib/small-model/DOCUMENTATION.md +11 -10
  91. package/server/lib/small-model/index.js +27 -32
  92. package/server/lib/small-model/index.test.js +28 -16
  93. package/server/lib/spaces/DOCUMENTATION.md +381 -20
  94. package/server/lib/spaces/code-in-bait.js +145 -6
  95. package/server/lib/spaces/code-in.js +10 -150
  96. package/server/lib/spaces/code-in.test.js +7 -83
  97. package/server/lib/spaces/code-out.js +1819 -0
  98. package/server/lib/spaces/code-out.test.js +3945 -0
  99. package/server/lib/spaces/code-transfer.js +173 -0
  100. package/server/lib/spaces/command-stream.test.js +181 -0
  101. package/server/lib/spaces/dispatcher.js +670 -0
  102. package/server/lib/spaces/dispatcher.test.js +582 -0
  103. package/server/lib/spaces/gatekeeper-channel.js +2 -0
  104. package/server/lib/spaces/gatekeeper-channel.test.js +9 -3
  105. package/server/lib/spaces/gatekeeper-program.cjs +4 -1
  106. package/server/lib/spaces/gatekeeper-program.test.js +3 -0
  107. package/server/lib/spaces/hardening.js +20 -4
  108. package/server/lib/spaces/hardening.test.js +18 -3
  109. package/server/lib/spaces/host-git.js +7 -4
  110. package/server/lib/spaces/host-git.test.js +6 -2
  111. package/server/lib/spaces/host.js +304 -0
  112. package/server/lib/spaces/host.test.js +273 -0
  113. package/server/lib/spaces/journey.js +393 -0
  114. package/server/lib/spaces/journey.test.js +384 -0
  115. package/server/lib/spaces/layout.js +26 -2
  116. package/server/lib/spaces/manager.js +4 -3
  117. package/server/lib/spaces/manager.test.js +6 -0
  118. package/server/lib/spaces/places/code-out.docker.live.test.js +412 -0
  119. package/server/lib/spaces/places/contract-suite.js +36 -0
  120. package/server/lib/spaces/places/dispatcher.docker.live.test.js +296 -0
  121. package/server/lib/spaces/places/docker.js +15 -3
  122. package/server/lib/spaces/places/docker.test.js +33 -2
  123. package/server/lib/spaces/places/escape-suite.js +86 -14
  124. package/server/lib/spaces/places/memory-place.js +24 -1
  125. package/server/lib/spaces/places/registry.js +1 -1
  126. package/server/lib/spaces/places/server.docker.live.test.js +69 -33
  127. package/server/lib/spaces/places/sessions.docker.live.test.js +220 -0
  128. package/server/lib/spaces/routes.js +207 -0
  129. package/server/lib/spaces/routes.test.js +211 -0
  130. package/server/lib/spaces/run-command.js +261 -8
  131. package/server/lib/spaces/run-command.test.js +193 -3
  132. package/server/lib/spaces/space-events.js +153 -0
  133. package/server/lib/spaces/space-events.test.js +160 -0
  134. package/server/lib/spaces/space-records.js +98 -0
  135. package/server/lib/spaces/space-records.test.js +73 -0
  136. package/server/lib/spaces/space-sessions.js +210 -0
  137. package/server/lib/spaces/space-sessions.test.js +161 -0
  138. package/server/lib/spaces/websocket.js +329 -0
  139. package/server/lib/spaces/websocket.test.js +345 -0
  140. package/server/lib/ui-auth/ui-auth.js +8 -2
  141. package/server/lib/ui-auth/ui-auth.test.js +29 -0
  142. package/server/opencode-proxy.test.js +113 -0
  143. package/dist/assets/MarkdownImageGallery-DQk5adUs.js +0 -1
  144. package/dist/assets/MarkdownRendererImpl-DPF8fZpX.js +0 -12
  145. package/dist/assets/PluginPane-BIGsUx69.js +0 -3
  146. package/dist/assets/de-CMA45TC-.js +0 -10
  147. package/dist/assets/es-DPL4fBtl.js +0 -16
  148. package/dist/assets/fr-OHBKBseP.js +0 -14
  149. package/dist/assets/index-BLUZa5u0.js +0 -41
  150. package/dist/assets/index-Cm2rrq69.css +0 -1
  151. package/dist/assets/ja-DvX4WSRf.js +0 -16
  152. package/dist/assets/ko-BUcLd8YZ.js +0 -16
  153. package/dist/assets/main-B_jri4i-.js +0 -896
  154. package/dist/assets/pt-BR-7wFtQlV9.js +0 -16
  155. package/dist/assets/runtimeEndpointReset-CfEYbcCc.js +0 -27
  156. package/dist/assets/tr-TsD-AqEH.js +0 -7
  157. package/dist/assets/uk-B-qspCmD.js +0 -16
  158. package/dist/assets/zh-CN-DYuPJV5i.js +0 -16
  159. package/dist/assets/zh-TW-BX_2D_lV.js +0 -16
@@ -0,0 +1,384 @@
1
+ // The journey over the memory place, with stand-ins for the gatekeeper channel, code in and code
2
+ // out that record what they were asked. What is under test is the order of the steps, what the
3
+ // host remembers, what it announces, and what a failure leaves.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+
9
+ import { afterEach, describe, expect, it } from 'vitest';
10
+
11
+ import { SpaceError } from './errors.js';
12
+ import { createSpaceJourney } from './journey.js';
13
+ import { createSpaceManager } from './manager.js';
14
+ import { createMemoryPlace } from './places/memory-place.js';
15
+ import { createPlaceRegistry } from './places/registry.js';
16
+ import { createSpaceRecords } from './space-records.js';
17
+
18
+ const PROJECT = '/home/me/project';
19
+ const NETWORK = { mode: 'allowlist', domains: ['api.anthropic.com'] };
20
+ const BASE = 'b'.repeat(40);
21
+ const quiet = { warn: () => {} };
22
+ const folders = [];
23
+ const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
24
+ const until = async (check, timeoutMs = 3_000) => {
25
+ const deadline = Date.now() + timeoutMs;
26
+ while (!check() && Date.now() < deadline) await sleep(5);
27
+ return check();
28
+ };
29
+
30
+ afterEach(() => {
31
+ for (const folder of folders.splice(0)) fs.rmSync(folder, { recursive: true, force: true });
32
+ });
33
+
34
+ /** A journey on fresh stand-ins. `failAt` names a stand-in step that rejects. */
35
+ const journeyWith = ({ failAt = null, place = createMemoryPlace(), projects = [PROJECT], historyStatus = 'sent', holdCodeIn = false, holdCodeOut = false } = {}) => {
36
+ // With `holdCodeIn`, code in waits until the test lets it go, so a creation stays under way;
37
+ // `holdCodeOut` does the same for the fetch of an apply.
38
+ let releaseCodeIn = () => {};
39
+ const codeInHeld = new Promise((resolve) => { releaseCodeIn = resolve; });
40
+ let releaseCodeOut = () => {};
41
+ const codeOutHeld = new Promise((resolve) => { releaseCodeOut = resolve; });
42
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-journey-'));
43
+ folders.push(dataDir);
44
+ const calls = [];
45
+ const events = [];
46
+ const changes = { count: 0 };
47
+ const fail = (step) => { if (failAt === step) throw new SpaceError(`${step}_failed`, `the stand-in for ${step} failed`); };
48
+ const gatekeeper = {
49
+ setNetwork: async (spaceId, network) => { calls.push(['setNetwork', spaceId, network]); fail('setNetwork'); },
50
+ readJournal: async (spaceId) => { calls.push(['readJournal', spaceId]); return { records: [], dropped: 0, since: '2026-09-26T10:00:00.000Z' }; },
51
+ };
52
+ const codeIn = {
53
+ bringCodeIn: async (request) => {
54
+ calls.push(['bringCodeIn', request]);
55
+ if (holdCodeIn) await codeInHeld;
56
+ fail('bringCodeIn');
57
+ return { spacePath: `/spaces/${request.spaceId}/project`, projectPath: `/spaces/${request.spaceId}/project`, base: BASE, identityCopied: { name: true, email: false } };
58
+ },
59
+ sendHistory: async (request) => { calls.push(['sendHistory', request]); fail('sendHistory'); return { status: historyStatus }; },
60
+ removeSpaceRefs: async (request) => { calls.push(['removeSpaceRefs', request]); fail('removeSpaceRefs'); },
61
+ };
62
+ const codeOut = {
63
+ bringCodeOut: async (request) => { calls.push(['bringCodeOut', request]); if (holdCodeOut) await codeOutHeld; fail('bringCodeOut'); return { result: 'c'.repeat(40), changedPaths: 3, changedBytes: 10, nestedRepositories: { count: 0, paths: [] }, unmerged: { count: 0, paths: [] } }; },
64
+ describeApplyState: async (request) => { calls.push(['describeApplyState', request]); return { closed: false, newPaths: 3 }; },
65
+ applyAsBranch: async (request) => { calls.push(['applyAsBranch', request]); fail('applyAsBranch'); return { branch: request.branch, commit: 'c'.repeat(40) }; },
66
+ applyAsChanges: async (request) => { calls.push(['applyAsChanges', request]); fail('applyAsChanges'); return { status: failAt === 'nothing' ? 'nothing_to_apply' : 'applied', appliedPaths: 3, remembered: true }; },
67
+ };
68
+ const records = createSpaceRecords({ dataDir, logger: quiet });
69
+ const manager = createSpaceManager({ registry: createPlaceRegistry([place]), now: () => new Date('2026-09-26T10:00:00.000Z') });
70
+ const journey = createSpaceJourney({
71
+ manager, place, gatekeeper, codeIn, codeOut, records,
72
+ listProjectDirectories: async () => projects,
73
+ announce: (spaceId, payload) => { events.push({ spaceId, ...payload.properties }); },
74
+ onSpacesChanged: () => { changes.count += 1; },
75
+ logger: quiet,
76
+ now: () => new Date('2026-09-26T10:00:00.000Z'),
77
+ });
78
+ return { journey, place, records, calls, events, changes, manager, releaseCodeIn, releaseCodeOut };
79
+ };
80
+
81
+ const REQUEST = { projectDirectory: PROJECT, name: ' Fix login ', start: 'uncommitted', network: NETWORK };
82
+ const steps = (events, spaceId) => events.filter((event) => event.spaceId === spaceId).map((event) => event.step);
83
+
84
+ describe('the journey: create', () => {
85
+ it('answers at once, then makes the space, sets its network, brings the code in and sends the history behind it', async () => {
86
+ const { journey, place, records, calls, events, changes } = journeyWith();
87
+
88
+ const answer = await journey.createSpace(REQUEST);
89
+ expect(answer).toMatchObject({ id: expect.stringMatching(/^[0-9a-f]{12}$/), name: 'Fix login', placeId: 'memory', projectDirectory: PROJECT, directory: `/spaces/${answer.id}/project`, state: 'preparing', step: 'checking_place', network: NETWORK, history: 'pending' });
90
+ // Listed as preparing while the steps run, whether or not the place has it yet.
91
+ expect((await journey.listSpaces()).find((space) => space.id === answer.id)).toMatchObject({ state: 'preparing' });
92
+
93
+ expect(await until(() => steps(events, answer.id).includes('ready'))).toBe(true);
94
+ expect(steps(events, answer.id)).toEqual(['checking_place', 'creating', 'setting_network', 'bringing_code', 'ready']);
95
+ expect(await place.list()).toEqual([expect.objectContaining({ id: answer.id, name: 'Fix login', state: 'running' })]);
96
+ expect(calls.map(([name]) => name).slice(0, 3)).toEqual(['setNetwork', 'bringCodeIn', 'sendHistory']);
97
+ expect(calls[0]).toEqual(['setNetwork', answer.id, NETWORK]);
98
+ expect(calls[1][1]).toEqual({ repository: PROJECT, spaceId: answer.id, mode: 'uncommitted' });
99
+ expect(calls[2][1]).toEqual({ repository: PROJECT, spaceId: answer.id, spacePath: `/spaces/${answer.id}/project`, base: BASE });
100
+ expect(await until(() => records.read(answer.id).record?.history === 'sent')).toBe(true);
101
+ expect(records.read(answer.id).record).toMatchObject({ network: NETWORK, repository: PROJECT, spacePath: `/spaces/${answer.id}/project`, base: BASE });
102
+ expect(changes.count).toBeGreaterThan(0);
103
+
104
+ const listed = await journey.listSpaces();
105
+ expect(listed).toEqual([expect.objectContaining({ id: answer.id, state: 'running', step: null, failure: null, network: NETWORK, history: 'sent', damaged: false })]);
106
+ });
107
+
108
+ it('keeps the space and marks the history failed when only the history did not arrive', async () => {
109
+ const { journey, records, events } = journeyWith({ failAt: 'sendHistory' });
110
+ const { id } = await journey.createSpace(REQUEST);
111
+ expect(await until(() => steps(events, id).includes('ready'))).toBe(true);
112
+ expect(await until(() => records.read(id).record?.history === 'failed')).toBe(true);
113
+ expect((await journey.listSpaces())[0]).toMatchObject({ id, state: 'running', history: 'failed' });
114
+ });
115
+
116
+ it.each(['setNetwork', 'bringCodeIn'])('removes what it made when %s fails, and lists the failure until it is dismissed', async (failAt) => {
117
+ const { journey, place, records, calls, events } = journeyWith({ failAt });
118
+ const { id } = await journey.createSpace(REQUEST);
119
+ expect(await until(() => steps(events, id).includes('failed'))).toBe(true);
120
+
121
+ expect(await place.list()).toEqual([]);
122
+ expect(records.read(id)).toEqual({ status: 'missing', record: null });
123
+ expect(calls.find(([name]) => name === 'removeSpaceRefs')?.[1]).toEqual({ repository: PROJECT, spaceId: id });
124
+ const failure = events.find((event) => event.spaceId === id && event.step === 'failed').failure;
125
+ expect(failure).toMatchObject({ code: `${failAt}_failed`, message: expect.stringContaining(failAt) });
126
+ expect(await journey.listSpaces()).toEqual([expect.objectContaining({ id, state: 'failed', step: 'failed', failure: expect.objectContaining({ code: `${failAt}_failed` }) })]);
127
+
128
+ // The failure is dismissed by removing it; the place is not asked, there is nothing there.
129
+ expect(await journey.removeSpace(id)).toEqual({ id, removed: true, refsRemoved: null, failures: [] });
130
+ expect(await journey.listSpaces()).toEqual([]);
131
+ });
132
+
133
+ it('does not make a space when the place is unavailable, and names the reason', async () => {
134
+ const place = { ...createMemoryPlace(), check: async () => ({ available: false, code: 'docker_daemon_unreachable', message: 'Docker is installed but not running.' }) };
135
+ const { journey, events } = journeyWith({ place });
136
+ const { id } = await journey.createSpace(REQUEST);
137
+ expect(await until(() => steps(events, id).includes('failed'))).toBe(true);
138
+ expect(steps(events, id)).toEqual(['checking_place', 'failed']);
139
+ expect(events.at(-1).failure).toMatchObject({ code: 'docker_daemon_unreachable', message: 'Docker is installed but not running.' });
140
+ expect(await place.list()).toEqual([]);
141
+ });
142
+
143
+ it('refuses an allowlist on a place that cannot keep the space away from its host', async () => {
144
+ const place = { ...createMemoryPlace(), check: async () => ({ available: true, version: '26.0.0', hostIsolation: false }) };
145
+ const { journey, events } = journeyWith({ place });
146
+ const { id } = await journey.createSpace(REQUEST);
147
+ expect(await until(() => steps(events, id).includes('failed'))).toBe(true);
148
+ expect(events.at(-1).failure.code).toBe('place_cannot_restrict_network');
149
+ expect(await place.list()).toEqual([]);
150
+ // Open is taken there, with the design's warning left to the funnel.
151
+ const open = await journey.createSpace({ ...REQUEST, network: { mode: 'open' } });
152
+ expect(await until(() => steps(events, open.id).includes('ready'))).toBe(true);
153
+ });
154
+
155
+ it('refuses a bad request before anything runs', async () => {
156
+ const { journey, place, events } = journeyWith();
157
+ await expect(journey.createSpace({ ...REQUEST, projectDirectory: '/home/me/other' })).rejects.toMatchObject({ code: 'project_not_registered' });
158
+ await expect(journey.createSpace({ ...REQUEST, projectDirectory: '' })).rejects.toMatchObject({ code: 'project_not_registered' });
159
+ await expect(journey.createSpace({ ...REQUEST, start: 'yesterday' })).rejects.toMatchObject({ code: 'invalid_snapshot_mode' });
160
+ await expect(journey.createSpace({ ...REQUEST, network: { mode: 'allowlist', domains: ['10.0.0.1'] } })).rejects.toMatchObject({ code: 'invalid_network' });
161
+ await expect(journey.createSpace({ ...REQUEST, network: { mode: 'everything' } })).rejects.toMatchObject({ code: 'invalid_network' });
162
+ await expect(journey.createSpace({ ...REQUEST, name: ' ' })).rejects.toMatchObject({ code: 'invalid_space_name' });
163
+ await expect(journey.createSpace({ ...REQUEST, name: 7 })).rejects.toMatchObject({ code: 'invalid_space_name' });
164
+ expect(events).toEqual([]);
165
+ expect(await place.list()).toEqual([]);
166
+ });
167
+ });
168
+
169
+ describe('the journey: start, stop, remove', () => {
170
+ const ready = async (options) => {
171
+ const made = journeyWith(options);
172
+ const { id } = await made.journey.createSpace(REQUEST);
173
+ await until(() => steps(made.events, id).includes('ready'));
174
+ await until(() => made.records.read(id).record?.history !== 'pending');
175
+ made.calls.splice(0);
176
+ return { ...made, id };
177
+ };
178
+
179
+ it('stops a space and starts it again with its network said again to the gatekeeper', async () => {
180
+ const { journey, place, calls, id, changes } = await ready();
181
+ const before = changes.count;
182
+ expect(await journey.stopSpace(id)).toMatchObject({ id, state: 'exited', network: NETWORK });
183
+ expect(await place.list()).toEqual([expect.objectContaining({ state: 'exited' })]);
184
+ expect(calls).toEqual([]);
185
+
186
+ const started = await journey.startSpace(id);
187
+ expect(started).toMatchObject({ id, state: 'running', networkRestored: true });
188
+ expect(calls).toEqual([['setNetwork', id, NETWORK]]);
189
+ expect(changes.count).toBe(before + 2);
190
+ });
191
+
192
+ it('starts a space whose record is gone with its network left closed, and says so', async () => {
193
+ const { journey, records, calls, id } = await ready();
194
+ await journey.stopSpace(id);
195
+ records.remove(id);
196
+ expect(await journey.startSpace(id)).toMatchObject({ id, state: 'running', networkRestored: false, network: null, history: 'unknown' });
197
+ expect(calls).toEqual([]);
198
+ });
199
+
200
+ it('sends the history again at start when it never arrived or failed', async () => {
201
+ const { journey, records, calls, id } = await ready({ failAt: 'sendHistory' });
202
+ expect(records.read(id).record.history).toBe('failed');
203
+ await journey.stopSpace(id);
204
+ await journey.startSpace(id);
205
+ expect(calls.map(([name]) => name)).toEqual(['setNetwork', 'sendHistory']);
206
+ calls.splice(0);
207
+ records.update(id, { history: 'sent' });
208
+ await journey.stopSpace(id);
209
+ await journey.startSpace(id);
210
+ expect(calls.map(([name]) => name)).toEqual(['setNetwork']);
211
+ });
212
+
213
+ it('removes the space, the refs in the user\'s repository and the record', async () => {
214
+ const { journey, place, records, calls, id } = await ready();
215
+ expect(await journey.removeSpace(id)).toEqual({ id, removed: true, refsRemoved: true, failures: [] });
216
+ expect(calls).toEqual([['removeSpaceRefs', { repository: PROJECT, spaceId: id }]]);
217
+ expect(await place.list()).toEqual([]);
218
+ expect(records.read(id).status).toBe('missing');
219
+ await expect(journey.removeSpace(id)).rejects.toMatchObject({ code: 'space_not_found' });
220
+ });
221
+
222
+ it('reports refs that could not be removed, with the space gone all the same', async () => {
223
+ const { journey, place, id } = await ready({ failAt: 'removeSpaceRefs' });
224
+ const outcome = await journey.removeSpace(id);
225
+ expect(outcome).toMatchObject({ id, removed: true, refsRemoved: false, failures: [expect.objectContaining({ code: 'removeSpaceRefs_failed' })] });
226
+ expect(await place.list()).toEqual([]);
227
+ });
228
+
229
+ it('refuses to start, stop or remove a space that is still being made', async () => {
230
+ const { journey, events, releaseCodeIn } = journeyWith({ holdCodeIn: true });
231
+ const { id } = await journey.createSpace(REQUEST);
232
+ expect(await until(() => steps(events, id).includes('bringing_code'))).toBe(true);
233
+ await expect(journey.stopSpace(id)).rejects.toMatchObject({ code: 'space_preparing' });
234
+ await expect(journey.startSpace(id)).rejects.toMatchObject({ code: 'space_preparing' });
235
+ await expect(journey.removeSpace(id)).rejects.toMatchObject({ code: 'space_preparing' });
236
+ await expect(journey.previewApply(id)).rejects.toMatchObject({ code: 'space_preparing' });
237
+ releaseCodeIn();
238
+ expect(await until(() => steps(events, id).includes('ready'))).toBe(true);
239
+ expect(await journey.stopSpace(id)).toMatchObject({ state: 'exited' });
240
+ });
241
+
242
+ it('stops every running space for the switch, and reports the one that would not stop as still running', async () => {
243
+ const { journey, place, manager } = await ready();
244
+ const second = await manager.createSpace({ placeId: 'memory', projectDirectory: PROJECT, name: 'Second' });
245
+ const third = await manager.createSpace({ placeId: 'memory', projectDirectory: PROJECT, name: 'Third' });
246
+ await place.stop(third.id);
247
+ const stop = place.stop;
248
+ place.stop = async (spaceId) => { if (spaceId === second.id) throw new SpaceError('docker_command_failed', 'docker stop exited 1'); return stop(spaceId); };
249
+
250
+ const outcome = await journey.stopAllSpaces();
251
+ expect(outcome.stopped).toEqual([expect.objectContaining({ name: 'Fix login' })]);
252
+ expect(outcome.stillRunning).toEqual([{ id: second.id, name: 'Second', code: 'docker_command_failed', message: 'docker stop exited 1', details: null }]);
253
+ expect((await place.list()).map((space) => space.state).sort()).toEqual(['exited', 'exited', 'running']);
254
+ });
255
+
256
+ it('does not turn the switch off while a space is being made', async () => {
257
+ const { journey, events, releaseCodeIn } = journeyWith({ holdCodeIn: true });
258
+ const { id } = await journey.createSpace(REQUEST);
259
+ expect(await until(() => steps(events, id).includes('bringing_code'))).toBe(true);
260
+ await expect(journey.stopAllSpaces()).rejects.toMatchObject({ code: 'space_preparing', details: { spaces: [id] } });
261
+ releaseCodeIn();
262
+ expect(await until(() => steps(events, id).includes('ready'))).toBe(true);
263
+ expect(await journey.stopAllSpaces()).toEqual({ stopped: [{ id, name: 'Fix login' }], stillRunning: [] });
264
+ });
265
+
266
+ it('takes no creation and no start once the switch is being turned off, until the turn-off is undone', async () => {
267
+ const { journey, manager } = journeyWith();
268
+ const stopped = await manager.createSpace({ placeId: 'memory', projectDirectory: PROJECT, name: 'Stopped' });
269
+ await journey.stopAllSpaces();
270
+ await expect(journey.createSpace(REQUEST)).rejects.toMatchObject({ code: 'isolated_spaces_off' });
271
+ await expect(journey.startSpace(stopped.id)).rejects.toMatchObject({ code: 'isolated_spaces_off' });
272
+ journey.reopen();
273
+ expect((await journey.startSpace(stopped.id)).state).toBe('running');
274
+ const { id } = await journey.createSpace(REQUEST);
275
+ expect(id).toMatch(/^[0-9a-f]{12}$/);
276
+ });
277
+
278
+ it('removes the containers of a failed creation whose clean-up failed when it is dismissed', async () => {
279
+ const place = createMemoryPlace();
280
+ const remove = place.remove;
281
+ let refusals = 1;
282
+ place.remove = async (spaceId) => {
283
+ if (refusals > 0) { refusals -= 1; throw new SpaceError('docker_command_failed', 'docker rm exited 1'); }
284
+ return remove(spaceId);
285
+ };
286
+ const { journey, events } = journeyWith({ place, failAt: 'bringCodeIn' });
287
+ const { id } = await journey.createSpace(REQUEST);
288
+ expect(await until(() => steps(events, id).includes('failed'))).toBe(true);
289
+ expect(events.at(-1).failure.cleanup).toEqual([expect.objectContaining({ code: 'docker_command_failed' })]);
290
+ expect(await place.list()).toHaveLength(1);
291
+ await expect(journey.startSpace(id)).rejects.toMatchObject({ code: 'space_creation_failed' });
292
+
293
+ expect(await journey.removeSpace(id)).toMatchObject({ id, removed: true });
294
+ expect(await place.list()).toEqual([]);
295
+ expect(await journey.listSpaces()).toEqual([]);
296
+ });
297
+ });
298
+
299
+ describe('the journey: journal and apply', () => {
300
+ const ready = async (options) => {
301
+ const made = journeyWith(options);
302
+ const { id } = await made.journey.createSpace(REQUEST);
303
+ await until(() => steps(made.events, id).includes('ready'));
304
+ await until(() => made.records.read(id).record?.history !== 'pending');
305
+ made.calls.splice(0);
306
+ return { ...made, id };
307
+ };
308
+
309
+ it('reads the journal of a running space and refuses one that is stopped, because the record is gone', async () => {
310
+ const { journey, id, calls } = await ready();
311
+ expect(await journey.readJournal(id)).toEqual({ records: [], dropped: 0, since: '2026-09-26T10:00:00.000Z' });
312
+ expect(calls).toEqual([['readJournal', id]]);
313
+ await journey.stopSpace(id);
314
+ await expect(journey.readJournal(id)).rejects.toMatchObject({ code: 'space_not_running', message: expect.stringContaining('gone') });
315
+ await expect(journey.readJournal('0f0f0f0f0f0f')).rejects.toMatchObject({ code: 'space_not_found' });
316
+ });
317
+
318
+ it('previews an apply by bringing the work out and describing the state, writing nothing', async () => {
319
+ const { journey, id, calls } = await ready();
320
+ const preview = await journey.previewApply(id);
321
+ expect(preview).toMatchObject({ result: 'c'.repeat(40), changedPaths: 3, closed: false, newPaths: 3 });
322
+ expect(calls).toEqual([
323
+ ['bringCodeOut', { repository: PROJECT, spaceId: id, spacePath: `/spaces/${id}/project` }],
324
+ ['describeApplyState', { repository: PROJECT, spaceId: id }],
325
+ ]);
326
+ });
327
+
328
+ it('applies as a branch, then removes the space when asked, and only after the apply went through', async () => {
329
+ const { journey, place, id, calls } = await ready();
330
+ const outcome = await journey.applySpace(id, { as: 'branch', branch: 'space/fix-login', removeAfterwards: true });
331
+ expect(outcome.applied).toEqual({ status: 'applied', branch: 'space/fix-login', commit: 'c'.repeat(40) });
332
+ expect(outcome.removal).toMatchObject({ id, removed: true, refsRemoved: true });
333
+ expect(calls.map(([name]) => name)).toEqual(['bringCodeOut', 'applyAsBranch', 'removeSpaceRefs']);
334
+ expect(await place.list()).toEqual([]);
335
+ });
336
+
337
+ it('applies as changes and keeps the space when not asked to remove it', async () => {
338
+ const { journey, place, id, calls } = await ready();
339
+ const outcome = await journey.applySpace(id, { as: 'changes' });
340
+ expect(outcome.applied).toEqual({ status: 'applied', appliedPaths: 3, remembered: true });
341
+ expect(outcome.removal).toBeNull();
342
+ expect(calls.map(([name]) => name)).toEqual(['bringCodeOut', 'applyAsChanges']);
343
+ expect(await place.list()).toHaveLength(1);
344
+ });
345
+
346
+ it('does not remove the space when there was nothing to apply, or when the apply refused', async () => {
347
+ const nothing = await ready({ failAt: 'nothing' });
348
+ expect((await nothing.journey.applySpace(nothing.id, { as: 'changes', removeAfterwards: true })).removal).toBeNull();
349
+ expect(await nothing.place.list()).toHaveLength(1);
350
+
351
+ const refused = await ready({ failAt: 'applyAsChanges' });
352
+ await expect(refused.journey.applySpace(refused.id, { as: 'changes', removeAfterwards: true })).rejects.toMatchObject({ code: 'applyAsChanges_failed' });
353
+ expect(await refused.place.list()).toHaveLength(1);
354
+ });
355
+
356
+ it('runs one action per space at a time: a remove during an apply is refused as busy', async () => {
357
+ const { journey, place, id, releaseCodeOut } = await ready({ holdCodeOut: true });
358
+ const applying = journey.applySpace(id, { as: 'changes' });
359
+ await sleep(20);
360
+ await expect(journey.removeSpace(id)).rejects.toMatchObject({ code: 'space_busy' });
361
+ await expect(journey.stopSpace(id)).rejects.toMatchObject({ code: 'space_busy' });
362
+ await expect(journey.readJournal(id)).rejects.toMatchObject({ code: 'space_busy' });
363
+ // Other spaces are not held up.
364
+ const other = await journey.createSpace({ ...REQUEST, name: 'Other' });
365
+ releaseCodeOut();
366
+ expect((await applying).applied.status).toBe('applied');
367
+ expect(await journey.removeSpace(id)).toMatchObject({ removed: true });
368
+ expect((await place.list()).map((space) => space.id)).toEqual([other.id]);
369
+ });
370
+
371
+ it('refuses an apply it cannot place: a bad way, a space still being made, or a project no longer registered', async () => {
372
+ const { journey, id, records, calls } = await ready();
373
+ await expect(journey.applySpace(id, { as: 'merge' })).rejects.toMatchObject({ code: 'invalid_apply_request' });
374
+ records.remove(id);
375
+ // Without a record the registered project still says where the work goes.
376
+ await journey.previewApply(id);
377
+ expect(calls[0]).toEqual(['bringCodeOut', { repository: PROJECT, spaceId: id, spacePath: `/spaces/${id}/project` }]);
378
+
379
+ const orphan = journeyWith({ projects: [] });
380
+ const other = await orphan.manager.createSpace({ placeId: 'memory', projectDirectory: PROJECT, name: 'Orphan' });
381
+ await expect(orphan.journey.previewApply(other.id)).rejects.toMatchObject({ code: 'project_not_registered' });
382
+ expect((await orphan.journey.listSpaces())[0]).toMatchObject({ id: other.id, projectDirectory: null, directory: null });
383
+ });
384
+ });
@@ -103,8 +103,9 @@ export const IMAGE_TIMEOUT = '/usr/bin/timeout';
103
103
  export const IMAGE_ONLY_PATH = `PATH=${IMAGE_PATH};`;
104
104
 
105
105
  /**
106
- * The environment of a space. The password of the server inside and
107
- * OPENCODE_AUTH_CONTENT never go here: container env is readable through `inspect`.
106
+ * The environment of a space. Neither the password of the server inside nor any credential ever
107
+ * goes here: container env is readable through `inspect`, and the hardening check allows no
108
+ * variable beyond these and the base image's own.
108
109
  */
109
110
  export const SPACE_ENVIRONMENT = Object.freeze({
110
111
  HOME: SPACE_HOME,
@@ -145,6 +146,29 @@ const SERVER_SCRIPT = [
145
146
  /** The command of a space container. A fixed script, nothing in it varies per space. */
146
147
  export const SPACE_SERVER_COMMAND = Object.freeze([IMAGE_SH, '-c', SERVER_SCRIPT]);
147
148
 
149
+ // The bridge of `connect`: runs inside the space over `docker exec --interactive`, joins its stdin
150
+ // and stdout to the loopback port of the server inside, and ends when either side ends. It
151
+ // leaves only after its last write to stdout has gone out: an exit on the socket's close would
152
+ // drop what is still buffered. The two standard streams are Node's own, which cope with a pipe
153
+ // that is full; a plain file stream on the descriptor failed with a system error there,
154
+ // measured on macOS with a four-megabyte answer. One line, as every fixed program that travels
155
+ // as an argument. It uses `net`, which no proxy variable of the space touches, and reads nothing
156
+ // from the space but its two arguments.
157
+ export const CONNECT_BRIDGE_PROGRAM = [
158
+ 'const net = require("node:net");',
159
+ 'const [host, port] = process.argv.slice(1);',
160
+ 'const socket = net.connect({ host, port: Number(port) });',
161
+ 'const leave = (code) => process.stdout.write("", () => process.exit(code));',
162
+ 'socket.on("error", (error) => { process.stderr.write(String(error.code || error.message)); leave(1); });',
163
+ 'socket.on("connect", () => { process.stdin.pipe(socket); socket.pipe(process.stdout, { end: false }); });',
164
+ 'socket.on("close", () => leave(0));',
165
+ 'process.stdin.on("error", () => socket.destroy());',
166
+ 'process.stdout.on("error", () => socket.destroy());',
167
+ ].join(' ');
168
+
169
+ /** The command that `connect` runs inside a space: the bridge to the server inside, on the image's Node. */
170
+ export const SPACE_CONNECT_COMMAND = Object.freeze([IMAGE_NODE, '-e', CONNECT_BRIDGE_PROGRAM, SPACE_SERVER_HOST, String(SPACE_SERVER_PORT)]);
171
+
148
172
  /**
149
173
  * The environment of a gatekeeper. It holds no secret and never will: grants arrive on the
150
174
  * stdin of an `exec` and live in the program's memory. HOME points into the tmpfs, because the
@@ -1,5 +1,5 @@
1
1
  import { SpaceError } from './errors.js';
2
- import { createSpaceId, hashProjectDirectory, normalizeSpaceName } from './labels.js';
2
+ import { createSpaceId, hashProjectDirectory, normalizeSpaceName, requireSpaceId } from './labels.js';
3
3
 
4
4
  // Memory limit of a new space. Swap adds nothing on top of it.
5
5
  const DEFAULT_SPACE_MEMORY_BYTES = 4 * 1024 * 1024 * 1024;
@@ -29,10 +29,11 @@ export function createSpaceManager({ registry, now = () => new Date() }) {
29
29
  return result;
30
30
  };
31
31
 
32
- const createSpace = async ({ placeId, projectDirectory, name }) => {
32
+ // `id` may be given, so a caller that announces a creation before it is done names the same space.
33
+ const createSpace = async ({ placeId, projectDirectory, name, id = createSpaceId() }) => {
33
34
  const place = requirePlace(placeId);
34
35
  const spec = {
35
- id: createSpaceId(),
36
+ id: requireSpaceId(id),
36
37
  name: normalizeSpaceName(name),
37
38
  project: hashProjectDirectory(projectDirectory),
38
39
  created: now().toISOString(),
@@ -29,6 +29,12 @@ describe('createSpaceManager', () => {
29
29
  expect(await manager.listSpaces({ placeId: 'memory' })).toEqual([{ ...listedFields, state: 'running', orphans: [], damaged: false, missing: [] }]);
30
30
  });
31
31
 
32
+ it('takes the id a caller announced before the creation, and refuses one that is not a space id', async () => {
33
+ const manager = managerFor(createMemoryPlace());
34
+ expect((await manager.createSpace({ ...REQUEST, id: 'a1b2c3d4e5f6' })).id).toBe('a1b2c3d4e5f6');
35
+ await expect(manager.createSpace({ ...REQUEST, id: 'not-an-id' })).rejects.toMatchObject({ code: 'invalid_space_id' });
36
+ });
37
+
32
38
  it('names the place that does not exist', async () => {
33
39
  const manager = managerFor(createMemoryPlace());
34
40