@openchamber/web 1.23.2 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{CodeMirrorCommentWidgets-DdNGwbBw.js → CodeMirrorCommentWidgets-C9kV-n7r.js} +1 -1
- package/dist/assets/DiffView-B7YkbY-u.js +4 -0
- package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +1 -0
- package/dist/assets/FilesView-vjJx7VaM.js +13 -0
- package/dist/assets/GitView-BLhlMYEY.js +6 -0
- package/dist/assets/GuestAttachDialog-B-fwE8r3.js +3 -0
- package/dist/assets/{JsonTreeView-Chzx5Y6N.js → JsonTreeView-D_4G5X6-.js} +1 -1
- package/dist/assets/LinearIssuesView-1uKhePfH.js +1 -0
- package/dist/assets/{MarkdownImageGallery-CugnrZ6f.js → MarkdownImageGallery-Ix7N_2wp.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-Deel_y5S.js +12 -0
- package/dist/assets/{OnboardingScreen-hH9xcTjA.js → OnboardingScreen-ToIakxb_.js} +1 -1
- package/dist/assets/{PatchDiff-DRgNYc9l.js → PatchDiff-BjMgezr1.js} +1 -1
- package/dist/assets/{PierreDiffViewer-ZT2CKuzJ.js → PierreDiffViewer-53Ghfnlr.js} +5 -5
- package/dist/assets/PlanView-BGAzxDwD.js +5 -0
- package/dist/assets/SettingsView-n2X-jfBB.js +29 -0
- package/dist/assets/SettingsWindow-Bi8LE9XI.js +1 -0
- package/dist/assets/SubmoduleDiffSummary--YFqK6Ih.js +1 -0
- package/dist/assets/ToolOutputDialog-DRWBvdaJ.js +15 -0
- package/dist/assets/{ToolPartDiffPreview-oWxWCu-4.js → ToolPartDiffPreview-BxZJCU28.js} +2 -2
- package/dist/assets/{VirtualizedFileDiff-CiyrAq_I.js → VirtualizedFileDiff-DCXjBGRf.js} +3 -3
- package/dist/assets/{WalkthroughView-CKTevaea.js → WalkthroughView-CfIPvWWa.js} +2 -2
- package/dist/assets/appThemeRegistry-DDROzcUO.js +1 -0
- package/dist/assets/{computeVirtualFileMetrics-SUWoTyPe.js → computeVirtualFileMetrics-DHgQIkUq.js} +1 -1
- package/dist/assets/de-CX_f-T5U.js +10 -0
- package/dist/assets/es-BERmWNn_.js +16 -0
- package/dist/assets/fr-BjYYE_-z.js +14 -0
- package/dist/assets/index-DpzTz2UH.css +1 -0
- package/dist/assets/index-Dy8xgawx.js +40 -0
- package/dist/assets/{index-C4jJ3Ur5.js → index-WjufPkIV.js} +1 -1
- package/dist/assets/{isDiffPlainText-DfG0cZxr.js → isDiffPlainText-D9faP70y.js} +1 -1
- package/dist/assets/{isFilePlainText-CyNivOCU.js → isFilePlainText-6qOcz5Ky.js} +1 -1
- package/dist/assets/ja-DxqeAk9N.js +16 -0
- package/dist/assets/ko-Dty1aUod.js +16 -0
- package/dist/assets/main-BOYSXfYn.js +896 -0
- package/dist/assets/{main-B8cGozKr.js → main-Bjcre_GE.js} +2 -2
- package/dist/assets/{markdown-shiki.worker-D5fBU-lw.js → markdown-shiki.worker-CahLvHIq.js} +5 -5
- package/dist/assets/{markdownCore-kyGrWGsn.js → markdownCore-DPrwM1rU.js} +5 -5
- package/dist/assets/{miniChat-Cay99IxR.js → miniChat-Dz_bPgMc.js} +2 -2
- package/dist/assets/{mobile-Zfhix7nz.js → mobile-BbZPBJrK.js} +2 -2
- package/dist/assets/{patchFileDiff-CJ5AN9Ql.js → patchFileDiff-BvU6KOQC.js} +3 -3
- package/dist/assets/pl-CX-_ROkr.js +16 -0
- package/dist/assets/{pt-BR-CLosVawq.js → pt-BR-DhRR1arx.js} +4 -4
- package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +2 -0
- package/dist/assets/renderMobileApp-BK1kFlcJ.js +25 -0
- package/dist/assets/runtimeEndpointReset-BULHvOwb.js +25 -0
- package/dist/assets/{scheduledTasksApi-CGFV4Pap.js → scheduledTasksApi-DW3xqMQ8.js} +1 -1
- package/dist/assets/shikiHighlight-DsxD9QEa.js +1 -0
- package/dist/assets/textMateThemeFromAppTheme-Da7ed8qM.js +1 -0
- package/dist/assets/tr-cIQtYBpg.js +7 -0
- package/dist/assets/uk-CD21CXFV.js +16 -0
- package/dist/assets/{useAppFontEffects-DgCHy6Mr.js → useAppFontEffects-hfv2s6mZ.js} +198 -147
- package/dist/assets/useInlineCommentController-BmtfVbo8.js +2 -0
- package/dist/assets/useRootScrollLock-Cwc4kSl2.js +1 -0
- package/dist/assets/{vendor-base-ui-BY_5qla_.js → vendor-base-ui-CsXYnR5c.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-ES33GhKK.js → vendor-codemirror-language-data-BPMJpOpT.js} +2 -2
- package/dist/assets/vendor-framer-motion-Bq3iTZ6r.js +1 -0
- package/dist/assets/{vendor-motion-dom-D_o3BTI3.js → vendor-motion-dom-DcCgeG69.js} +1 -1
- package/dist/assets/vendor-strip-json-comments-5dJlOkP1.js +4 -0
- package/dist/assets/{vendor-zod-B6551dwG.js → vendor-zod-fZppILAM.js} +4 -4
- package/dist/assets/{web-components-CJZwV5BE.js → web-components-U-hWbgJo.js} +2 -2
- package/dist/assets/zh-CN-BWvlPHY-.js +16 -0
- package/dist/assets/zh-TW-CRp5dJU2.js +16 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +7 -5
- package/server/built-in-extensions/registry.json +4 -0
- package/server/index.d.ts +2 -0
- package/server/index.js +15 -3
- package/server/lib/fs/DOCUMENTATION.md +8 -0
- package/server/lib/fs/git-process.test.js +77 -0
- package/server/lib/fs/routes.js +2 -1
- package/server/lib/fs/search.js +2 -1
- package/server/lib/git/DOCUMENTATION.md +3 -1
- package/server/lib/git/routes.js +16 -3
- package/server/lib/git/service.js +112 -8
- package/server/lib/git/service.test.js +127 -0
- package/server/lib/guests/DOCUMENTATION.md +66 -0
- package/server/lib/guests/auth-store.js +184 -0
- package/server/lib/guests/auth-store.test.js +112 -0
- package/server/lib/guests/builtins.js +34 -0
- package/server/lib/guests/builtins.test.js +174 -0
- package/server/lib/guests/catalog.js +466 -0
- package/server/lib/guests/catalog.test.js +390 -0
- package/server/lib/guests/clone.js +297 -0
- package/server/lib/guests/extract-zip.js +136 -0
- package/server/lib/guests/extract-zip.test.js +109 -0
- package/server/lib/guests/files.js +308 -0
- package/server/lib/guests/files.test.js +262 -0
- package/server/lib/guests/grant-scope.js +81 -0
- package/server/lib/guests/grant-scope.test.js +75 -0
- package/server/lib/guests/host-session.js +73 -0
- package/server/lib/guests/host-session.test.js +30 -0
- package/server/lib/guests/html-styles.js +6 -0
- package/server/lib/guests/html-styles.test.js +45 -0
- package/server/lib/guests/html-tokens.js +73 -0
- package/server/lib/guests/html-tokens.test.js +53 -0
- package/server/lib/guests/install.js +406 -0
- package/server/lib/guests/install.test.js +338 -0
- package/server/lib/guests/oauth.js +501 -0
- package/server/lib/guests/oauth.test.js +481 -0
- package/server/lib/guests/persist.js +336 -0
- package/server/lib/guests/persist.test.js +288 -0
- package/server/lib/guests/request.js +112 -0
- package/server/lib/guests/request.test.js +206 -0
- package/server/lib/guests/routes.js +838 -0
- package/server/lib/guests/service.js +538 -0
- package/server/lib/guests/service.test.js +277 -0
- package/server/lib/guests/sockets.js +129 -0
- package/server/lib/guests/sockets.test.js +110 -0
- package/server/lib/guests/ssh-install.test.js +188 -0
- package/server/lib/guests/storage.js +68 -0
- package/server/lib/guests/storage.test.js +59 -0
- package/server/lib/guests/updates.js +294 -0
- package/server/lib/guests/updates.test.js +334 -0
- package/server/lib/guests/upload.js +50 -0
- package/server/lib/guests/upload.test.js +131 -0
- package/server/lib/linear/DOCUMENTATION.md +1 -1
- package/server/lib/openchamber-control/DOCUMENTATION.md +6 -0
- package/server/lib/openchamber-sessions/routes.js +44 -11
- package/server/lib/openchamber-sessions/routes.test.js +47 -0
- package/server/lib/opencode/DOCUMENTATION.md +40 -0
- package/server/lib/opencode/core-routes.js +39 -1
- package/server/lib/opencode/feature-routes-runtime.js +10 -0
- package/server/lib/opencode/lifecycle-process.test.js +84 -0
- package/server/lib/opencode/lifecycle.js +54 -67
- package/server/lib/opencode/settings-normalization-runtime.js +2 -0
- package/server/lib/opencode/settings-normalization-runtime.test.js +13 -0
- package/server/lib/opencode/settings-registry.json +4 -0
- package/server/lib/opencode/shutdown-runtime.js +3 -0
- package/server/lib/opencode/shutdown-runtime.test.js +24 -0
- package/server/lib/opencode/theme-archive.js +53 -0
- package/server/lib/opencode/theme-catalog.js +171 -0
- package/server/lib/opencode/theme-catalog.test.js +125 -0
- package/server/lib/opencode/theme-import.test.js +144 -0
- package/server/lib/opencode/theme-runtime.js +100 -28
- package/server/lib/opencode/theme-runtime.test.js +15 -0
- package/server/lib/quota/DOCUMENTATION.md +0 -1
- package/server/lib/quota/providers/index.js +0 -7
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +17 -2
- package/server/lib/terminal/runtime.test.js +45 -0
- package/server/lib/ui-auth/ui-auth.js +43 -8
- package/server/lib/ui-auth/ui-auth.test.js +40 -0
- package/dist/assets/DiffView-GYriC0Wk.js +0 -4
- package/dist/assets/DirtyBranchSwitchDialog-Bv0C99hc.js +0 -1
- package/dist/assets/FilesView-2Lin13wx.js +0 -13
- package/dist/assets/GitView-9wKba3UO.js +0 -6
- package/dist/assets/LinearIssuesView-DXS9QJiR.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CaMyct2Q.js +0 -12
- package/dist/assets/PlanView-DiTBm2BD.js +0 -5
- package/dist/assets/SettingsView-CN8VeM99.js +0 -28
- package/dist/assets/SettingsWindow-DisOghhD.js +0 -1
- package/dist/assets/ToolOutputDialog-BqiKydxR.js +0 -15
- package/dist/assets/appThemeRegistry-BK0dHKa6.js +0 -1
- package/dist/assets/de-DQWC94VK.js +0 -10
- package/dist/assets/es-DixFUD3m.js +0 -16
- package/dist/assets/fr-D6u8tvfA.js +0 -14
- package/dist/assets/index-BvpFzhLs.js +0 -40
- package/dist/assets/index-n5p3SnES.css +0 -1
- package/dist/assets/ja-4u4pCorB.js +0 -16
- package/dist/assets/ko-C27-LW_b.js +0 -16
- package/dist/assets/main-tEA-fFPg.js +0 -930
- package/dist/assets/pl-FtCjsNdW.js +0 -16
- package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-CuHOGlF4.js +0 -2
- package/dist/assets/renderMobileApp-C4X_KUH8.js +0 -25
- package/dist/assets/runtimeEndpointReset-CMg-KUx3.js +0 -41
- package/dist/assets/shikiHighlight-DdKWYWrV.js +0 -1
- package/dist/assets/tr-D2j6wUez.js +0 -7
- package/dist/assets/uk-C6IzmwM_.js +0 -16
- package/dist/assets/useGitComparison-BIaI0WZI.js +0 -1
- package/dist/assets/useInlineCommentController-2wcCtpM3.js +0 -2
- package/dist/assets/useRootScrollLock-CbWA03xR.js +0 -1
- package/dist/assets/vendor-framer-motion-livSKyyV.js +0 -1
- package/dist/assets/zh-CN-Wl6tIDz1.js +0 -16
- package/dist/assets/zh-TW-hgphoWSN.js +0 -16
- package/server/lib/quota/providers/crof.js +0 -96
- package/server/lib/quota/providers/crof.test.js +0 -98
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import express from 'express';
|
|
2
2
|
import { createOpencodeClient } from '@opencode-ai/sdk/v2';
|
|
3
|
-
import { createWorktree, getWorktreeBootstrapStatus } from '../git/index.js';
|
|
3
|
+
import { createWorktree, getWorktreeBootstrapStatus, resolvePrimaryWorktreeRoot } from '../git/index.js';
|
|
4
4
|
import { expandSnippets } from '../opencode/snippets.js';
|
|
5
5
|
import { expandCommandGoalObjective, parseScheduledCommandPrompt } from '../scheduled-tasks/runtime.js';
|
|
6
6
|
import { buildGoalIntroText, createSessionGoal } from '../session-goal/create.js';
|
|
@@ -75,6 +75,7 @@ const resolveVariant = (providers, providerID, modelID, variant) => {
|
|
|
75
75
|
if (!normalized) return undefined;
|
|
76
76
|
const provider = providers.find((entry) => entry?.id === providerID);
|
|
77
77
|
const model = providerModels(provider).find((entry) => entry?.id === modelID);
|
|
78
|
+
if (!model) return normalized;
|
|
78
79
|
return model?.variants && Object.prototype.hasOwnProperty.call(model.variants, normalized)
|
|
79
80
|
? normalized
|
|
80
81
|
: undefined;
|
|
@@ -82,6 +83,18 @@ const resolveVariant = (providers, providerID, modelID, variant) => {
|
|
|
82
83
|
|
|
83
84
|
const parseConfigModel = (value) => splitModel(value);
|
|
84
85
|
|
|
86
|
+
const resolveProjectDefaults = (settings, directory, projectId) => {
|
|
87
|
+
const projects = Array.isArray(settings?.projects) ? settings.projects : [];
|
|
88
|
+
const matchedProject = projectId
|
|
89
|
+
? projects.find((entry) => entry?.id === projectId) || null
|
|
90
|
+
: projects.find((entry) => entry?.path === directory) || null;
|
|
91
|
+
return {
|
|
92
|
+
defaultAgent: asNonEmptyString(matchedProject?.defaultAgent),
|
|
93
|
+
defaultModel: asNonEmptyString(matchedProject?.defaultModel),
|
|
94
|
+
defaultVariant: asNonEmptyString(matchedProject?.defaultVariant),
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
85
98
|
const buildDirectoryHeaders = (directory) => ({
|
|
86
99
|
// OpenCode rejects non-ASCII header values; the official SDK sends this
|
|
87
100
|
// header percent-encoded, so match that wire format (non-ASCII checkout
|
|
@@ -121,11 +134,15 @@ const fetchSelectionInputs = async ({ buildOpenCodeUrl, authHeaders, directory,
|
|
|
121
134
|
};
|
|
122
135
|
};
|
|
123
136
|
|
|
124
|
-
const resolveDefaultSelection = ({ agents, providers, settings, opencodeDefaultAgent, opencodeDefaultModel }) => {
|
|
137
|
+
const resolveDefaultSelection = ({ agents, providers, settings, projectDefaults, opencodeDefaultAgent, opencodeDefaultModel }) => {
|
|
125
138
|
const primaryAgents = agents.filter((agent) => isPrimaryAgentMode(agent?.mode) && agent?.hidden !== true);
|
|
126
139
|
let resolvedAgent = null;
|
|
140
|
+
const projectDefaultAgent = asNonEmptyString(projectDefaults?.defaultAgent);
|
|
127
141
|
const settingsDefaultAgent = asNonEmptyString(settings?.defaultAgent);
|
|
128
|
-
if (
|
|
142
|
+
if (projectDefaultAgent) {
|
|
143
|
+
resolvedAgent = agents.find((agent) => agent?.name === projectDefaultAgent) || null;
|
|
144
|
+
}
|
|
145
|
+
if (!resolvedAgent && settingsDefaultAgent) {
|
|
129
146
|
resolvedAgent = agents.find((agent) => agent?.name === settingsDefaultAgent) || null;
|
|
130
147
|
}
|
|
131
148
|
if (!resolvedAgent && opencodeDefaultAgent) {
|
|
@@ -140,20 +157,24 @@ const resolveDefaultSelection = ({ agents, providers, settings, opencodeDefaultA
|
|
|
140
157
|
|
|
141
158
|
let model = null;
|
|
142
159
|
let variant;
|
|
160
|
+
const projectDefaultModel = parseConfigModel(projectDefaults?.defaultModel);
|
|
143
161
|
const settingsDefaultModel = parseConfigModel(settings?.defaultModel);
|
|
144
|
-
if (
|
|
162
|
+
if (projectDefaultModel) {
|
|
163
|
+
model = projectDefaultModel;
|
|
164
|
+
variant = resolveVariant(providers, model.providerID, model.modelID, projectDefaults?.defaultVariant);
|
|
165
|
+
}
|
|
166
|
+
if (!model && settingsDefaultModel) {
|
|
145
167
|
model = settingsDefaultModel;
|
|
146
168
|
variant = resolveVariant(providers, model.providerID, model.modelID, settings?.defaultVariant);
|
|
147
169
|
}
|
|
148
170
|
|
|
149
|
-
if (!model && resolvedAgent?.model?.providerID && resolvedAgent?.model?.modelID
|
|
150
|
-
&& hasProviderModel(providers, resolvedAgent.model.providerID, resolvedAgent.model.modelID)) {
|
|
171
|
+
if (!model && resolvedAgent?.model?.providerID && resolvedAgent?.model?.modelID) {
|
|
151
172
|
model = { providerID: resolvedAgent.model.providerID, modelID: resolvedAgent.model.modelID };
|
|
152
173
|
variant = resolveVariant(providers, model.providerID, model.modelID, resolvedAgent.variant);
|
|
153
174
|
}
|
|
154
175
|
|
|
155
176
|
const opencodeModel = parseConfigModel(opencodeDefaultModel);
|
|
156
|
-
if (!model && opencodeModel
|
|
177
|
+
if (!model && opencodeModel) {
|
|
157
178
|
model = opencodeModel;
|
|
158
179
|
}
|
|
159
180
|
|
|
@@ -304,9 +325,15 @@ const resolveRequestedDirectory = async ({ payload, readSettingsFromDiskMigrated
|
|
|
304
325
|
|
|
305
326
|
const directory = asNonEmptyString(payload?.directory);
|
|
306
327
|
const validated = await validateDirectoryPath(directory);
|
|
307
|
-
return validated.
|
|
308
|
-
|
|
309
|
-
|
|
328
|
+
if (!validated.ok) return { ok: false, status: 400, error: validated.error || 'Invalid directory' };
|
|
329
|
+
const settings = await readSettingsFromDiskMigrated();
|
|
330
|
+
const projects = sanitizeProjects(settings?.projects || []);
|
|
331
|
+
let project = projects.find((entry) => entry.path === validated.directory);
|
|
332
|
+
if (!project && projects.length > 0) {
|
|
333
|
+
const { root } = await resolvePrimaryWorktreeRoot(validated.directory);
|
|
334
|
+
project = projects.find((entry) => entry.path === root);
|
|
335
|
+
}
|
|
336
|
+
return { ok: true, directory: validated.directory, ...(project ? { projectId: project.id } : {}) };
|
|
310
337
|
};
|
|
311
338
|
|
|
312
339
|
const PROMPT_LANDED_TIMEOUT_MS = 5_000;
|
|
@@ -468,6 +495,7 @@ export const createOpenChamberSessionService = (dependencies) => {
|
|
|
468
495
|
authHeaders,
|
|
469
496
|
sessionID,
|
|
470
497
|
directory,
|
|
498
|
+
projectId,
|
|
471
499
|
prompt,
|
|
472
500
|
goalInput,
|
|
473
501
|
requestedModel,
|
|
@@ -495,7 +523,10 @@ export const createOpenChamberSessionService = (dependencies) => {
|
|
|
495
523
|
directory,
|
|
496
524
|
readSettingsFromDiskMigrated,
|
|
497
525
|
});
|
|
498
|
-
const defaults = resolveDefaultSelection(
|
|
526
|
+
const defaults = resolveDefaultSelection({
|
|
527
|
+
...inputs,
|
|
528
|
+
projectDefaults: resolveProjectDefaults(inputs.settings, directory, projectId),
|
|
529
|
+
});
|
|
499
530
|
if (!model) {
|
|
500
531
|
model = defaults.model;
|
|
501
532
|
if (variant == null) variant = defaults.variant;
|
|
@@ -735,6 +766,7 @@ export const createOpenChamberSessionService = (dependencies) => {
|
|
|
735
766
|
authHeaders,
|
|
736
767
|
sessionID,
|
|
737
768
|
directory: sessionDirectory,
|
|
769
|
+
projectId: resolvedDirectory.projectId,
|
|
738
770
|
prompt,
|
|
739
771
|
goalInput,
|
|
740
772
|
requestedModel: model,
|
|
@@ -838,6 +870,7 @@ export const createOpenChamberSessionService = (dependencies) => {
|
|
|
838
870
|
authHeaders,
|
|
839
871
|
sessionID: targetSessionID,
|
|
840
872
|
directory,
|
|
873
|
+
projectId: resolvedDirectory.projectId,
|
|
841
874
|
prompt,
|
|
842
875
|
goalInput,
|
|
843
876
|
requestedModel,
|
|
@@ -90,6 +90,7 @@ vi.mock('@opencode-ai/sdk/v2', () => ({
|
|
|
90
90
|
vi.mock('../git/index.js', () => ({
|
|
91
91
|
createWorktree: (...args) => globalThis.__openchamberCreateWorktreeMock(...args),
|
|
92
92
|
getWorktreeBootstrapStatus: (...args) => globalThis.__openchamberGetWorktreeBootstrapStatusMock(...args),
|
|
93
|
+
resolvePrimaryWorktreeRoot: async (directory) => ({ root: directory === '/repo/worktrees/side-task' ? '/repo/app' : directory }),
|
|
93
94
|
}));
|
|
94
95
|
|
|
95
96
|
const createApp = (overrides = {}, options = {}) => {
|
|
@@ -360,6 +361,52 @@ describe('openchamber session routes', () => {
|
|
|
360
361
|
}
|
|
361
362
|
});
|
|
362
363
|
|
|
364
|
+
it.each([
|
|
365
|
+
['', { projectId: 'proj_1' }],
|
|
366
|
+
['', { directory: '/repo/app', worktree: { name: 'side-task' } }],
|
|
367
|
+
['', { directory: '/repo/worktrees/side-task' }],
|
|
368
|
+
['/ses_existing/send', { directory: '/repo/worktrees/side-task' }],
|
|
369
|
+
['/ses_existing/fork', { directory: '/repo/worktrees/side-task' }],
|
|
370
|
+
])('prefers project defaults for %s with %j', async (endpoint, scope) => {
|
|
371
|
+
const originalFetch = globalThis.fetch;
|
|
372
|
+
const fetchMock = vi.fn(async (url) => {
|
|
373
|
+
const text = String(url);
|
|
374
|
+
if (text.includes('/prompt_async')) {
|
|
375
|
+
return { ok: true, text: async () => '' };
|
|
376
|
+
}
|
|
377
|
+
if (text.includes('/config/providers')) {
|
|
378
|
+
return { ok: true, json: async () => ({ providers: [{ id: 'openai', models: { 'gpt-5.5': { id: 'gpt-5.5' } } }] }) };
|
|
379
|
+
}
|
|
380
|
+
if (text.includes('/agent')) {
|
|
381
|
+
return { ok: true, json: async () => [{ name: 'build', mode: 'primary' }, { name: 'plan', mode: 'primary' }] };
|
|
382
|
+
}
|
|
383
|
+
if (text.includes('/config')) {
|
|
384
|
+
return { ok: true, json: async () => ({}) };
|
|
385
|
+
}
|
|
386
|
+
return { ok: true, json: async () => ({ id: 'ses_123' }) };
|
|
387
|
+
});
|
|
388
|
+
globalThis.fetch = fetchMock;
|
|
389
|
+
const { app } = createApp({
|
|
390
|
+
readSettingsFromDiskMigrated: async () => ({
|
|
391
|
+
defaultModel: 'openai/gpt-5.5',
|
|
392
|
+
defaultAgent: 'build',
|
|
393
|
+
projects: [{ id: 'proj_1', path: '/repo/app', defaultAgent: 'plan' }],
|
|
394
|
+
}),
|
|
395
|
+
});
|
|
396
|
+
try {
|
|
397
|
+
const response = await request(app)
|
|
398
|
+
.post(`/api/openchamber/sessions${endpoint}`)
|
|
399
|
+
.send({ ...scope, prompt: 'Run this' })
|
|
400
|
+
.expect(200);
|
|
401
|
+
|
|
402
|
+
expect(response.body.agent).toBe('plan');
|
|
403
|
+
const promptCall = fetchMock.mock.calls.find(([url]) => String(url).includes('/prompt_async'));
|
|
404
|
+
expect(JSON.parse(promptCall?.[1]?.body)).toMatchObject({ agent: 'plan' });
|
|
405
|
+
} finally {
|
|
406
|
+
globalThis.fetch = originalFetch;
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
363
410
|
it('dispatches an initial prompt when model is provided', async () => {
|
|
364
411
|
const originalFetch = globalThis.fetch;
|
|
365
412
|
const fetchMock = vi.fn(async (url) => {
|
|
@@ -44,6 +44,28 @@ This module provides OpenCode server integration utilities for the web server ru
|
|
|
44
44
|
- `packages/web/server/lib/opencode/settings-helpers.js`: Settings payload sanitization/format helpers runtime for response shaping and persisted merge prep.
|
|
45
45
|
- `packages/web/server/lib/opencode/settings-normalization-runtime.js`: path/settings/tunnel normalization and sanitization helpers runtime used by settings/routes/config wiring.
|
|
46
46
|
- `packages/web/server/lib/opencode/theme-runtime.js`: custom theme JSON validation and theme directory loading runtime for settings utility routes.
|
|
47
|
+
|
|
48
|
+
`POST /api/config/themes` saves a converted VS Code palette. The runtime validates
|
|
49
|
+
literal colors and required authored roles, assigns a content-derived filename,
|
|
50
|
+
and publishes through a same-directory hard link so partial files and overwrites
|
|
51
|
+
are impossible. Identical retries reuse the existing file; a manually edited
|
|
52
|
+
collision returns 409. Temporary files are ignored by the loader and removed
|
|
53
|
+
after publication or failure. Non-missing-directory read failures propagate to
|
|
54
|
+
the route instead of returning an authoritative empty library.
|
|
55
|
+
|
|
56
|
+
The common request middleware parses theme POST bodies before these routes;
|
|
57
|
+
integration tests must use that middleware rather than an unrestricted test parser.
|
|
58
|
+
`DELETE /api/config/themes/:id` finds a valid regular JSON file by its metadata ID
|
|
59
|
+
inside the custom themes directory. IDs are never used as filenames. Hand-added
|
|
60
|
+
themes are supported; symlinks and bundled themes are outside deletion ownership.
|
|
61
|
+
Duplicate matching IDs fail explicitly. Missing themes are an idempotent success;
|
|
62
|
+
filesystem failures remain errors.
|
|
63
|
+
`theme-catalog.js` owns POST catalog search/package routes under
|
|
64
|
+
`/api/config/themes/catalog/`. It fetches only Open VSX and its Eclipse CDN over
|
|
65
|
+
HTTPS, validates redirects and checksums, and verifies packaged identity.
|
|
66
|
+
`theme-archive.js` reads selected JSON entries in memory with bounded decompression.
|
|
67
|
+
JSON includes and token references stay inside the package. Each failed variant
|
|
68
|
+
is reported separately so valid siblings remain available. No extension code runs.
|
|
47
69
|
- `packages/web/server/lib/opencode/proxy.js`: OpenCode API/SSE forwarding and readiness-gate route registration.
|
|
48
70
|
- `packages/web/server/lib/opencode/session-runtime.js`: session status/attention/activity runtime for OpenCode SSE events.
|
|
49
71
|
- `packages/web/server/lib/opencode/watcher.js`: global SSE watcher runtime for push/session event fanout.
|
|
@@ -156,6 +178,23 @@ Transport-triggered health checks share the periodic monitor's failure accountin
|
|
|
156
178
|
|
|
157
179
|
Managed health failures are classified as `timeout`, `connection_refused`, `connection_reset`, `invalid_response`, or `error`. The lifecycle retains the latest counted failure with a bounded detail string and source. Managed process wrappers continue capturing a sanitized, bounded stderr tail after readiness and retain exit code/signal. Before replacing a managed process, lifecycle snapshots the reason, latest health failure, process diagnostics/aliveness, busy-session count, and timestamp into `lastOpenCodeRestartDiagnostics`; successful startup does not clear this snapshot, and `/health` exposes it for post-restart diagnosis without process environment or credentials.
|
|
158
180
|
|
|
181
|
+
Managed process ownership starts at spawn. The registry and runtime process
|
|
182
|
+
handle include children that have not announced readiness yet, so shutdown can
|
|
183
|
+
stop an in-flight startup. Readiness timeout, malformed startup output, and
|
|
184
|
+
health-probe errors close that child before retrying. Shutdown cancels further
|
|
185
|
+
startup attempts. Closing a process is single-flight and unregisters it only
|
|
186
|
+
after it exits.
|
|
187
|
+
|
|
188
|
+
On Windows, managed teardown invokes the existing tree termination command
|
|
189
|
+
before terminating the root. Calling `child.kill()` first loses the ancestry
|
|
190
|
+
needed to find Git, shell, and MCP descendants. On POSIX, the managed child
|
|
191
|
+
starts in its own process group and teardown escalates against that group even
|
|
192
|
+
if the root has already exited. A tool ignoring SIGTERM must not survive just
|
|
193
|
+
because the server closed its own pipes. The
|
|
194
|
+
`lifecycle-process.test.js` regressions launch real parent/child fixtures and
|
|
195
|
+
check PID exit plus registry cleanup. macOS results do not validate Windows
|
|
196
|
+
ConPTY or Console Window Host behavior.
|
|
197
|
+
|
|
159
198
|
## Public exports (env-runtime.js)
|
|
160
199
|
- `createOpenCodeEnvRuntime(dependencies)`: creates runtime that owns OpenCode CLI environment and binary discovery state.
|
|
161
200
|
- OpenCode CLI resolution order is persisted settings, environment overrides, bundled Desktop CLI when available, PATH, known install locations, then platform shell discovery.
|
|
@@ -332,6 +371,7 @@ Managed health failures are classified as `timeout`, `connection_refused`, `conn
|
|
|
332
371
|
|
|
333
372
|
## Public exports (shutdown-runtime.js)
|
|
334
373
|
- `createGracefulShutdownRuntime(dependencies)`: creates graceful shutdown runtime for managed OpenCode and web server teardown sequencing.
|
|
374
|
+
- After stopping owned runtimes and OpenCode, HTTP shutdown closes active connections as well as the listener. A remaining SSE response must not hold Desktop open until its fallback deadline. Upgraded sockets remain the responsibility of their owning runtime.
|
|
335
375
|
- Returned API:
|
|
336
376
|
- `gracefulShutdown(options?)`
|
|
337
377
|
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { buildExternalManualRestartResponse } from './config-mutation-response.js';
|
|
2
|
+
import { ThemeImportStorageError } from './theme-runtime.js';
|
|
3
|
+
import { registerThemeCatalogRoutes } from './theme-catalog.js';
|
|
2
4
|
|
|
3
5
|
const parseLoopbackUrl = (rawUrl) => {
|
|
4
6
|
if (typeof rawUrl !== 'string') {
|
|
@@ -589,7 +591,15 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
|
|
|
589
591
|
res.status(statusCode).json({ error: 'Invalid or expired pairing session' });
|
|
590
592
|
};
|
|
591
593
|
|
|
594
|
+
const isGuestOauthCallback = (req) => (
|
|
595
|
+
req.method === 'GET'
|
|
596
|
+
&& /^\/guests\/[a-z][a-z0-9-]*\/oauth\/callback$/.test(req.path || '')
|
|
597
|
+
);
|
|
598
|
+
|
|
592
599
|
const requireApiAuth = async (req, res, next) => {
|
|
600
|
+
if (isGuestOauthCallback(req)) {
|
|
601
|
+
return next();
|
|
602
|
+
}
|
|
593
603
|
const requestScope = tunnelAuthController.classifyRequestScope(req);
|
|
594
604
|
if (requestScope === 'tunnel' || requestScope === 'unknown-public') {
|
|
595
605
|
return tunnelAuthController.requireTunnelSession(req, res, next);
|
|
@@ -995,6 +1005,8 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
|
|
|
995
1005
|
export const registerSettingsUtilityRoutes = (app, dependencies) => {
|
|
996
1006
|
const {
|
|
997
1007
|
readCustomThemesFromDisk,
|
|
1008
|
+
saveImportedTheme,
|
|
1009
|
+
deleteImportedTheme,
|
|
998
1010
|
refreshOpenCodeAfterConfigChange,
|
|
999
1011
|
clientReloadDelayMs,
|
|
1000
1012
|
} = dependencies;
|
|
@@ -1009,6 +1021,30 @@ export const registerSettingsUtilityRoutes = (app, dependencies) => {
|
|
|
1009
1021
|
}
|
|
1010
1022
|
});
|
|
1011
1023
|
|
|
1024
|
+
app.post('/api/config/themes', async (req, res) => {
|
|
1025
|
+
try {
|
|
1026
|
+
const theme = await saveImportedTheme(req.body?.theme);
|
|
1027
|
+
res.status(201).json({ theme });
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
if (error instanceof ThemeImportStorageError) {
|
|
1030
|
+
res.status(error.status).json({ error: error.code });
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
console.error('[themes] Failed to save imported theme');
|
|
1034
|
+
res.status(500).json({ error: 'save' });
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
registerThemeCatalogRoutes(app);
|
|
1039
|
+
app.delete('/api/config/themes/:id', async (req, res) => {
|
|
1040
|
+
try {
|
|
1041
|
+
await deleteImportedTheme(req.params.id);
|
|
1042
|
+
res.json({ success: true });
|
|
1043
|
+
} catch (error) {
|
|
1044
|
+
res.status(error instanceof ThemeImportStorageError ? error.status : 500).json({ error: 'delete' });
|
|
1045
|
+
}
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1012
1048
|
app.post('/api/config/reload', async (_req, res) => {
|
|
1013
1049
|
try {
|
|
1014
1050
|
console.log('[Server] Manual configuration reload requested');
|
|
@@ -1041,7 +1077,9 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
|
|
|
1041
1077
|
const { express, verboseRequestLogs = false } = dependencies;
|
|
1042
1078
|
|
|
1043
1079
|
app.use((req, res, next) => {
|
|
1044
|
-
if (req.path.startsWith('/api/
|
|
1080
|
+
if (req.path === '/api/config/themes' || req.path.startsWith('/api/config/themes/')) {
|
|
1081
|
+
express.json({ limit: '1mb' })(req, res, next);
|
|
1082
|
+
} else if (req.path.startsWith('/api/behavior')) {
|
|
1045
1083
|
const contentLength = parseInt(req.headers['content-length'] || '0', 10);
|
|
1046
1084
|
if (contentLength > 1024 * 1024) {
|
|
1047
1085
|
return res.status(413).json({ error: 'Content exceeds maximum size of 1048576 bytes' });
|
|
@@ -5,6 +5,9 @@ import { registerWalkthroughRoutes } from '../walkthrough/routes.js';
|
|
|
5
5
|
import { registerSessionGoalRoutes } from '../session-goal/routes.js';
|
|
6
6
|
import { registerGitHubRoutes } from '../github/routes.js';
|
|
7
7
|
import { registerLinearRoutes } from '../linear/routes.js';
|
|
8
|
+
import { registerGuestRoutes } from '../guests/routes.js';
|
|
9
|
+
import { registerBuiltInGuests } from '../guests/catalog.js';
|
|
10
|
+
import { extensionsPersistPath } from '../guests/persist.js';
|
|
8
11
|
import { registerGitRoutes } from '../git/routes.js';
|
|
9
12
|
import { registerDevServerRoutes } from '../dev-servers/routes.js';
|
|
10
13
|
import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
|
|
@@ -105,6 +108,8 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
105
108
|
resolveOptionalProjectDirectory,
|
|
106
109
|
validateDirectoryPath,
|
|
107
110
|
readCustomThemesFromDisk,
|
|
111
|
+
saveImportedTheme,
|
|
112
|
+
deleteImportedTheme,
|
|
108
113
|
refreshOpenCodeAfterConfigChange,
|
|
109
114
|
getOpenCodeResolutionSnapshot,
|
|
110
115
|
getOpenCodeUpgradeCapability,
|
|
@@ -136,10 +141,13 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
136
141
|
emitSessionCreatedEvent,
|
|
137
142
|
permissionAutoAcceptRuntime,
|
|
138
143
|
messageQueueRuntime,
|
|
144
|
+
openchamberVersion,
|
|
139
145
|
} = routeDependencies;
|
|
140
146
|
|
|
141
147
|
registerSettingsUtilityRoutes(app, {
|
|
142
148
|
readCustomThemesFromDisk,
|
|
149
|
+
saveImportedTheme,
|
|
150
|
+
deleteImportedTheme,
|
|
143
151
|
refreshOpenCodeAfterConfigChange,
|
|
144
152
|
clientReloadDelayMs,
|
|
145
153
|
});
|
|
@@ -307,6 +315,8 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
307
315
|
registerSessionGoalRoutes(app);
|
|
308
316
|
registerGitHubRoutes(app);
|
|
309
317
|
registerLinearRoutes(app);
|
|
318
|
+
await registerBuiltInGuests({ persistPath: extensionsPersistPath(openchamberDataDir), root: routeDependencies.builtInExtensionsDir });
|
|
319
|
+
registerGuestRoutes(app, { openchamberDataDir, openchamberVersion, resolveGitBinaryForSpawn, resolveOptionalProjectDirectory, getSmallModelService });
|
|
310
320
|
registerGitRoutes(app, {
|
|
311
321
|
emitWorktreeChanged: ({ directories, at }) => {
|
|
312
322
|
const clients = getOpenChamberEventClients();
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { createOpenCodeLifecycleRuntime } from './lifecycle.js';
|
|
6
|
+
|
|
7
|
+
const alive = (pid) => {
|
|
8
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const createRuntime = (waitForReady, state) => createOpenCodeLifecycleRuntime({
|
|
12
|
+
state,
|
|
13
|
+
env: { ENV_CONFIGURED_OPENCODE_PORT: 45678, ENV_CONFIGURED_OPENCODE_HOSTNAME: '127.0.0.1' },
|
|
14
|
+
syncToHmrState() {}, syncFromHmrState() {},
|
|
15
|
+
ensureOpencodeCliEnv: () => process.execPath,
|
|
16
|
+
applyOpencodeBinaryFromSettings: async () => {},
|
|
17
|
+
ensureLocalOpenCodeServerPassword: async () => 'fixture-only',
|
|
18
|
+
resolveManagedOpenCodeLaunchSpec: (binary) => ({ binary, args: [] }),
|
|
19
|
+
normalizeApiPrefix: (value) => value,
|
|
20
|
+
setOpenCodePort() {}, setDetectedOpenCodeApiPrefix() {},
|
|
21
|
+
waitForReady,
|
|
22
|
+
managedStartupTimeoutMs: 1500,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe('managed process lifecycle with real children', () => {
|
|
26
|
+
for (const failure of ['invalid-readiness', 'health-error', 'startup-timeout', 'shutdown-during-startup', 'none']) {
|
|
27
|
+
it(`reaps the server and its child after ${failure}`, async () => {
|
|
28
|
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'oc-process-'));
|
|
29
|
+
const previousRegistry = process.env.OPENCHAMBER_MANAGED_PROCESS_REGISTRY;
|
|
30
|
+
process.env.OPENCHAMBER_MANAGED_PROCESS_REGISTRY = path.join(root, 'registry');
|
|
31
|
+
const marker = path.join(root, 'pids');
|
|
32
|
+
const childScript = `process.on('SIGTERM', () => {}); require('node:fs').appendFileSync(${JSON.stringify(marker)}, process.pid + '\\n'); process.stdout.write('ready\\n'); setInterval(() => {}, 1000);`;
|
|
33
|
+
let readinessMessage = 'opencode server listening on http://127.0.0.1:45678\n';
|
|
34
|
+
if (failure === 'invalid-readiness') readinessMessage = 'opencode server listening without a URL\n';
|
|
35
|
+
if (failure === 'startup-timeout' || failure === 'shutdown-during-startup') readinessMessage = '';
|
|
36
|
+
// Node is an isolated stand-in for the native OpenCode binary. Lifecycle
|
|
37
|
+
// still launches its real `serve --hostname ... --port ...` command.
|
|
38
|
+
await fs.writeFile(path.join(root, 'serve'), `
|
|
39
|
+
const fs = require('node:fs');
|
|
40
|
+
fs.appendFileSync(${JSON.stringify(marker)}, process.pid + '\\n');
|
|
41
|
+
const child = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(childScript)}], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
42
|
+
child.stdout.once('data', () => {
|
|
43
|
+
process.stdout.write(${JSON.stringify(readinessMessage)});
|
|
44
|
+
});
|
|
45
|
+
setInterval(() => {}, 1000);
|
|
46
|
+
`);
|
|
47
|
+
try {
|
|
48
|
+
const state = { openCodeWorkingDirectory: root, useWslForOpencode: false };
|
|
49
|
+
const runtime = createRuntime(async () => {
|
|
50
|
+
if (failure === 'health-error') throw new Error('fixture health failure');
|
|
51
|
+
return true;
|
|
52
|
+
}, state);
|
|
53
|
+
if (failure === 'none') {
|
|
54
|
+
const server = await runtime.startOpenCode();
|
|
55
|
+
await Promise.all([server.close(), server.close()]);
|
|
56
|
+
} else if (failure === 'shutdown-during-startup') {
|
|
57
|
+
const starting = runtime.startOpenCode();
|
|
58
|
+
const rejected = expect(starting).rejects.toThrow('exited before serving');
|
|
59
|
+
await expect.poll(async () => (await fs.readFile(marker, 'utf8').catch(() => '')).trim().split('\n').filter(Boolean).length).toBe(2);
|
|
60
|
+
state.isShuttingDown = true;
|
|
61
|
+
await state.openCodeProcess.close();
|
|
62
|
+
await rejected;
|
|
63
|
+
} else if (failure === 'startup-timeout') {
|
|
64
|
+
await expect(runtime.startOpenCode()).rejects.toThrow('Timeout waiting for OpenCode');
|
|
65
|
+
} else {
|
|
66
|
+
await expect(runtime.startOpenCode()).rejects.toThrow(failure === 'health-error' ? 'fixture health failure' : 'Failed to parse server url');
|
|
67
|
+
}
|
|
68
|
+
const pids = (await fs.readFile(marker, 'utf8')).trim().split('\n').map(Number);
|
|
69
|
+
expect(pids).toHaveLength(failure === 'none' || failure === 'shutdown-during-startup' ? 2 : 4);
|
|
70
|
+
await expect.poll(() => pids.filter(alive), { timeout: 3000 }).toEqual([]);
|
|
71
|
+
expect(await fs.readdir(path.join(root, 'registry')).catch(() => [])).toEqual([]);
|
|
72
|
+
} finally {
|
|
73
|
+
const pids = (await fs.readFile(marker, 'utf8').catch(() => '')).trim().split('\n').map(Number).filter((pid) => pid > 0);
|
|
74
|
+
for (const pid of pids.reverse()) {
|
|
75
|
+
if (!alive(pid)) continue;
|
|
76
|
+
try { process.kill(pid, 'SIGKILL'); } catch { /* already exited */ }
|
|
77
|
+
}
|
|
78
|
+
if (previousRegistry === undefined) delete process.env.OPENCHAMBER_MANAGED_PROCESS_REGISTRY;
|
|
79
|
+
else process.env.OPENCHAMBER_MANAGED_PROCESS_REGISTRY = previousRegistry;
|
|
80
|
+
await fs.rm(root, { recursive: true, force: true });
|
|
81
|
+
}
|
|
82
|
+
}, 15_000);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
@@ -109,6 +109,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
109
109
|
reapManagedOrphanedProcesses = reapOrphanedProcesses,
|
|
110
110
|
getWarmupDirectories = async () => [],
|
|
111
111
|
onOpenCodeRestarted = null,
|
|
112
|
+
managedStartupTimeoutMs = 30_000,
|
|
112
113
|
now = Date.now,
|
|
113
114
|
} = deps;
|
|
114
115
|
|
|
@@ -287,7 +288,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
287
288
|
}
|
|
288
289
|
|
|
289
290
|
const pid = child.pid;
|
|
290
|
-
if (!pid || hasChildProcessExited(child)) {
|
|
291
|
+
if (!pid || (process.platform === 'win32' && hasChildProcessExited(child))) {
|
|
291
292
|
await waitForChildProcessClose(child, 250);
|
|
292
293
|
return;
|
|
293
294
|
}
|
|
@@ -301,34 +302,14 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
301
302
|
}
|
|
302
303
|
|
|
303
304
|
try {
|
|
304
|
-
child.kill(signal);
|
|
305
|
+
if (!hasChildProcessExited(child)) child.kill(signal);
|
|
305
306
|
} catch {
|
|
306
307
|
}
|
|
307
308
|
};
|
|
308
309
|
|
|
309
310
|
if (process.platform === 'win32') {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
} catch {
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
if (await waitForChildProcessClose(child, 800)) {
|
|
316
|
-
return;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
try {
|
|
320
|
-
spawnSync('taskkill', ['/pid', String(pid), '/t'], {
|
|
321
|
-
stdio: 'ignore',
|
|
322
|
-
timeout: 3000,
|
|
323
|
-
windowsHide: true,
|
|
324
|
-
});
|
|
325
|
-
} catch {
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
if (await waitForChildProcessClose(child, 1500)) {
|
|
329
|
-
return;
|
|
330
|
-
}
|
|
331
|
-
|
|
311
|
+
// Windows child.kill() terminates only the parent. Kill the owned tree
|
|
312
|
+
// while its parent still exists, otherwise /T cannot find its children.
|
|
332
313
|
try {
|
|
333
314
|
spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], {
|
|
334
315
|
stdio: 'ignore',
|
|
@@ -343,11 +324,9 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
343
324
|
}
|
|
344
325
|
|
|
345
326
|
signalProcessTree('SIGTERM');
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
}
|
|
350
|
-
|
|
327
|
+
await waitForChildProcessClose(child, 2500);
|
|
328
|
+
// Parent exit does not prove group exit. Tools can ignore SIGTERM and keep
|
|
329
|
+
// running after their server has exited and closed its own stdio.
|
|
351
330
|
signalProcessTree('SIGKILL');
|
|
352
331
|
|
|
353
332
|
await waitForChildProcessClose(child, 1000);
|
|
@@ -452,7 +431,29 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
452
431
|
child.on('exit', recordManagedProcessExit);
|
|
453
432
|
child.on('close', recordManagedProcessExit);
|
|
454
433
|
|
|
455
|
-
|
|
434
|
+
// Ownership starts at spawn, including processes that never become ready.
|
|
435
|
+
const registration = registerManagedProcess({
|
|
436
|
+
pid: child.pid,
|
|
437
|
+
ownerPid: process.pid,
|
|
438
|
+
port,
|
|
439
|
+
binary,
|
|
440
|
+
runtime: process.env.OPENCHAMBER_RUNTIME || 'web',
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
let closePromise = null;
|
|
444
|
+
const serverProcess = {
|
|
445
|
+
url: null,
|
|
446
|
+
pid: child.pid || null,
|
|
447
|
+
get exitCode() { return observedExitCode ?? child.exitCode; },
|
|
448
|
+
get signalCode() { return observedSignalCode ?? child.signalCode; },
|
|
449
|
+
get stderrTail() { return getManagedProcessSnapshot().stderrTail; },
|
|
450
|
+
close() {
|
|
451
|
+
if (!closePromise) closePromise = registration.then(() => closeManagedOpenCodeChild(child));
|
|
452
|
+
return closePromise;
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
const readiness = new Promise((resolve, reject) => {
|
|
456
457
|
let stdout = '';
|
|
457
458
|
let stderr = '';
|
|
458
459
|
let done = false;
|
|
@@ -507,37 +508,21 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
507
508
|
child.stderr?.on('data', onStderr);
|
|
508
509
|
child.on('exit', onExit);
|
|
509
510
|
child.on('error', onError);
|
|
511
|
+
}).catch(async (error) => {
|
|
512
|
+
await serverProcess.close();
|
|
513
|
+
if (state.openCodeProcess === serverProcess) {
|
|
514
|
+
state.openCodeProcess = null;
|
|
515
|
+
syncToHmrState();
|
|
516
|
+
}
|
|
517
|
+
throw error;
|
|
510
518
|
});
|
|
511
519
|
|
|
512
|
-
//
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
pid: child.pid,
|
|
519
|
-
ownerPid: process.pid,
|
|
520
|
-
port,
|
|
521
|
-
binary,
|
|
522
|
-
runtime: process.env.OPENCHAMBER_RUNTIME || 'web',
|
|
523
|
-
});
|
|
524
|
-
|
|
525
|
-
return {
|
|
526
|
-
url,
|
|
527
|
-
pid: child.pid || null,
|
|
528
|
-
get exitCode() {
|
|
529
|
-
return observedExitCode ?? child.exitCode;
|
|
530
|
-
},
|
|
531
|
-
get signalCode() {
|
|
532
|
-
return observedSignalCode ?? child.signalCode;
|
|
533
|
-
},
|
|
534
|
-
get stderrTail() {
|
|
535
|
-
return getManagedProcessSnapshot().stderrTail;
|
|
536
|
-
},
|
|
537
|
-
async close() {
|
|
538
|
-
await closeManagedOpenCodeChild(child);
|
|
539
|
-
},
|
|
540
|
-
};
|
|
520
|
+
// Shutdown must be able to close an in-flight startup, not only a ready server.
|
|
521
|
+
state.openCodeProcess = serverProcess;
|
|
522
|
+
syncToHmrState();
|
|
523
|
+
serverProcess.url = await readiness;
|
|
524
|
+
await registration;
|
|
525
|
+
return serverProcess;
|
|
541
526
|
};
|
|
542
527
|
|
|
543
528
|
const resolveManagedOpenCodePort = async (requestedPort, hostname = '127.0.0.1') => {
|
|
@@ -719,12 +704,14 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
719
704
|
});
|
|
720
705
|
phaseStartedAt = performance.now();
|
|
721
706
|
|
|
707
|
+
let serverInstance;
|
|
722
708
|
try {
|
|
723
|
-
|
|
709
|
+
if (state.isShuttingDown) throw new Error('OpenCode startup cancelled during shutdown');
|
|
710
|
+
serverInstance = await createManagedOpenCodeServerProcess({
|
|
724
711
|
resolvedBinary,
|
|
725
712
|
hostname: env.ENV_CONFIGURED_OPENCODE_HOSTNAME,
|
|
726
713
|
port: spawnPort,
|
|
727
|
-
timeout:
|
|
714
|
+
timeout: managedStartupTimeoutMs,
|
|
728
715
|
cwd: state.openCodeWorkingDirectory,
|
|
729
716
|
shellEnvKeysCount: Object.keys(shellEnv).length,
|
|
730
717
|
env: stripAppImageArgv0Leak(applyProviderEnvAliases({
|
|
@@ -750,7 +737,9 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
750
737
|
const port = parseInt(url.port, 10);
|
|
751
738
|
const prefix = normalizeApiPrefix(url.pathname);
|
|
752
739
|
|
|
753
|
-
|
|
740
|
+
const ready = await waitForReady(serverInstance.url, 10000);
|
|
741
|
+
if (state.isShuttingDown) throw new Error('OpenCode startup cancelled during shutdown');
|
|
742
|
+
if (ready) {
|
|
754
743
|
setOpenCodePort(port);
|
|
755
744
|
setDetectedOpenCodeApiPrefix(prefix);
|
|
756
745
|
|
|
@@ -768,12 +757,10 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
768
757
|
return serverInstance;
|
|
769
758
|
}
|
|
770
759
|
|
|
771
|
-
try {
|
|
772
|
-
await serverInstance.close();
|
|
773
|
-
} catch {
|
|
774
|
-
}
|
|
775
760
|
throw new Error('Server started but health check failed (timeout)');
|
|
776
761
|
} catch (error) {
|
|
762
|
+
await serverInstance?.close();
|
|
763
|
+
if (serverInstance && state.openCodeProcess === serverInstance) state.openCodeProcess = null;
|
|
777
764
|
const message = error instanceof Error ? error.message : String(error);
|
|
778
765
|
state.lastOpenCodeError = message;
|
|
779
766
|
state.openCodePort = null;
|
|
@@ -795,7 +782,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
|
|
795
782
|
return await startOpenCodeOnce(attempt);
|
|
796
783
|
} catch (error) {
|
|
797
784
|
lastError = error;
|
|
798
|
-
if (error?.code === 'OPENCODE_BINARY_INVALID') {
|
|
785
|
+
if (state.isShuttingDown || error?.code === 'OPENCODE_BINARY_INVALID') {
|
|
799
786
|
break;
|
|
800
787
|
}
|
|
801
788
|
if (attempt >= START_OPEN_CODE_MAX_ATTEMPTS) {
|