@openchamber/web 1.18.2 → 1.18.4

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 (140) hide show
  1. package/bin/lib/commands-models.js +1 -1
  2. package/dist/assets/{CodeMirrorCommentWidgets-CxcJ5x9h.js → CodeMirrorCommentWidgets-4qZbrEXU.js} +1 -1
  3. package/dist/assets/{CommitSection-C9sBBYAJ.js → CommitSection-MJmntVPJ.js} +1 -1
  4. package/dist/assets/{DiagramEditor-C7nUw7p3.js → DiagramEditor-jnG3Hbxg.js} +1 -1
  5. package/dist/assets/{DiagramView-cYxZP-HS.js → DiagramView-CFXxgg_a.js} +1 -1
  6. package/dist/assets/{DiffView-1zd0slLu.js → DiffView-DZIoOnV7.js} +2 -2
  7. package/dist/assets/FilesView-BKL6YlKG.js +14 -0
  8. package/dist/assets/{GitView-OSVIn5V1.js → GitView-DBFrDDBv.js} +1 -1
  9. package/dist/assets/{JsonTreeView-Kgepz4pR.js → JsonTreeView-DLW2Wy1g.js} +1 -1
  10. package/dist/assets/MarkdownImageGallery-DKIylIK7.js +1 -0
  11. package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +12 -0
  12. package/dist/assets/OnboardingScreen-D2Y6djMw.js +1 -0
  13. package/dist/assets/{PatchDiff-Cddz02Ya.js → PatchDiff-BuLPx7AN.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-B5k0KvPW.js → PierreDiffViewer-BHm4Yr0X.js} +2 -2
  15. package/dist/assets/{PlanView-BYgHBHDt.js → PlanView-ZYEJn8A_.js} +3 -3
  16. package/dist/assets/{SessionSwitcherDropdown-ig2OT22Z.js → SessionSwitcherDropdown-rro-SsaO.js} +1 -1
  17. package/dist/assets/SettingsView-5RmswFZe.js +28 -0
  18. package/dist/assets/{SettingsWindow-CNHM8ifT.js → SettingsWindow-BZhAYFdS.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-DrGeYq2p.js → ToolOutputDialog-Za6V4VMJ.js} +7 -7
  20. package/dist/assets/{ToolPartDiffPreview-BRmPpe94.js → ToolPartDiffPreview-BL-9ixyC.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-Dcu8Q-5P.js → VirtualizedFileDiff-CwGocYQd.js} +1 -1
  22. package/dist/assets/{WalkthroughView-HStEYdD2.js → WalkthroughView-5DyvN03T.js} +2 -2
  23. package/dist/assets/{computeVirtualFileMetrics-DQE7R9IY.js → computeVirtualFileMetrics-Da00Jg7M.js} +2 -2
  24. package/dist/assets/contextPanelEmbeddedChat-B-bSg3P5.js +1 -0
  25. package/dist/assets/de-u7gSnqWs.js +9 -0
  26. package/dist/assets/es-T9O7aAOr.js +15 -0
  27. package/dist/assets/fr-Oor7ewbE.js +13 -0
  28. package/dist/assets/index-BzIpNlNE.css +1 -0
  29. package/dist/assets/{index-BgQEgA2a.js → index-C0yNhuZw.js} +1 -1
  30. package/dist/assets/index-DRpChWux.js +7 -0
  31. package/dist/assets/{isDiffPlainText-XyBCe4eD.js → isDiffPlainText-D9YpoLrV.js} +1 -1
  32. package/dist/assets/{isFilePlainText-JbqDfa3n.js → isFilePlainText-gTibdNIe.js} +1 -1
  33. package/dist/assets/ja-DHpqbVmr.js +15 -0
  34. package/dist/assets/ko-CwLkS3nx.js +15 -0
  35. package/dist/assets/{main-LfcbGv7C.js → main-D7UcL3VQ.js} +2 -2
  36. package/dist/assets/main-DPMd2iKS.js +915 -0
  37. package/dist/assets/markdownCore-DDrHVneM.js +2 -0
  38. package/dist/assets/{miniChat-CUp_elRz.js → miniChat-O_GVoEbc.js} +2 -2
  39. package/dist/assets/{mobile-CBSN7BsH.js → mobile-Br4TtAqc.js} +2 -2
  40. package/dist/assets/{patchFileDiff-DCIXUHRJ.js → patchFileDiff-KNkxM1C1.js} +2 -2
  41. package/dist/assets/{pl-tHTP6XQx.js → pl-CcZILN8q.js} +4 -4
  42. package/dist/assets/pt-BR-DYHhVK6o.js +15 -0
  43. package/dist/assets/{renderElectronMiniChatApp-eZl-5STF.js → renderElectronMiniChatApp-CJpdxTT1.js} +2 -2
  44. package/dist/assets/renderMobileApp-toj9cXoh.js +25 -0
  45. package/dist/assets/runtimeEndpointReset-BVmispdD.js +13 -0
  46. package/dist/assets/scheduledTasksApi-ByKya3Un.js +1 -0
  47. package/dist/assets/{shikiHighlight-eU8abJ3T.js → shikiHighlight-C7LTbwFx.js} +1 -1
  48. package/dist/assets/uk-BA2kZR38.js +15 -0
  49. package/dist/assets/{useAppFontEffects-Bbpz77To.js → useAppFontEffects-BikB6enL.js} +138 -138
  50. package/dist/assets/useInlineCommentController-CYPvYJDt.js +2 -0
  51. package/dist/assets/{vendor-codemirror-language-data-Dzt9rWZZ.js → vendor-codemirror-language-data-CLHw8NWn.js} +2 -2
  52. package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
  53. package/dist/assets/{web-components-DGvnI0zx.js → web-components-GMc3oR3i.js} +1 -1
  54. package/dist/assets/zh-CN-dlOQK6v9.js +15 -0
  55. package/dist/assets/zh-TW-BnqQ-WL5.js +15 -0
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +2 -2
  60. package/server/index.js +65 -19
  61. package/server/lib/agent-tool/DOCUMENTATION.md +21 -6
  62. package/server/lib/agent-tool/runtime.js +90 -16
  63. package/server/lib/agent-tool/runtime.test.js +86 -0
  64. package/server/lib/browser-control/DOCUMENTATION.md +50 -0
  65. package/server/lib/browser-control/broker.js +154 -0
  66. package/server/lib/browser-control/broker.test.js +191 -0
  67. package/server/lib/browser-control/routes.js +48 -0
  68. package/server/lib/browser-control/routes.test.js +108 -0
  69. package/server/lib/dev-servers/parse.js +203 -0
  70. package/server/lib/dev-servers/parse.test.js +174 -0
  71. package/server/lib/dev-servers/routes.js +135 -0
  72. package/server/lib/dev-tunnel/DOCUMENTATION.md +57 -0
  73. package/server/lib/dev-tunnel/client.js +193 -0
  74. package/server/lib/dev-tunnel/runtime.js +189 -0
  75. package/server/lib/dev-tunnel/tunnel.test.js +291 -0
  76. package/server/lib/git/credentials.js +0 -33
  77. package/server/lib/github/DOCUMENTATION.md +1 -1
  78. package/server/lib/markdown-image-grants/DOCUMENTATION.md +36 -0
  79. package/server/lib/markdown-image-grants/routes.js +340 -0
  80. package/server/lib/markdown-image-grants/routes.test.js +221 -0
  81. package/server/lib/openchamber-control/DOCUMENTATION.md +9 -0
  82. package/server/lib/openchamber-control/actions.js +33 -1
  83. package/server/lib/openchamber-control/screenshots.js +83 -0
  84. package/server/lib/openchamber-control/screenshots.test.js +84 -0
  85. package/server/lib/openchamber-control/service.js +141 -2
  86. package/server/lib/openchamber-control/service.test.js +55 -0
  87. package/server/lib/opencode/core-routes.js +31 -52
  88. package/server/lib/opencode/core-routes.test.js +37 -9
  89. package/server/lib/opencode/feature-routes-runtime.js +15 -0
  90. package/server/lib/opencode/server-startup-runtime.js +22 -1
  91. package/server/lib/opencode/server-startup-runtime.test.js +44 -0
  92. package/server/lib/opencode/settings-helpers.js +3 -9
  93. package/server/lib/projects/project-config.js +181 -2
  94. package/server/lib/projects/project-config.test.js +295 -0
  95. package/server/lib/quota/DOCUMENTATION.md +4 -2
  96. package/server/lib/quota/credentials/providers.js +0 -7
  97. package/server/lib/quota/credentials/store.js +11 -1
  98. package/server/lib/quota/credentials/store.test.js +9 -1
  99. package/server/lib/quota/providers/opencode-go.js +35 -35
  100. package/server/lib/quota/providers/opencode-go.test.js +52 -7
  101. package/server/lib/quota/routes.js +0 -2
  102. package/server/lib/relay/DOCUMENTATION.md +2 -0
  103. package/server/lib/relay/tunnel-host.js +157 -33
  104. package/server/lib/relay/tunnel-host.test.js +147 -0
  105. package/server/lib/scheduled-tasks/DOCUMENTATION.md +49 -0
  106. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +488 -0
  107. package/server/lib/scheduled-tasks/routes.js +6 -0
  108. package/server/lib/scheduled-tasks/runtime.js +369 -108
  109. package/server/lib/scheduled-tasks/service.js +7 -1
  110. package/server/lib/scheduled-tasks/service.test.js +20 -0
  111. package/server/lib/walkthrough/index.js +0 -2
  112. package/server/sse-routes.test.js +3 -0
  113. package/dist/assets/FilesView-WkxsWHBE.js +0 -14
  114. package/dist/assets/MarkdownRendererImpl-CKAsRfIk.js +0 -12
  115. package/dist/assets/OnboardingScreen-BCgYA7J5.js +0 -1
  116. package/dist/assets/SettingsView-e7Fmxnz8.js +0 -28
  117. package/dist/assets/contextPanelEmbeddedChat-5VGWIT_J.js +0 -1
  118. package/dist/assets/de-B6t6T54h.js +0 -9
  119. package/dist/assets/es-DH9NUKge.js +0 -15
  120. package/dist/assets/fr-Do4t2KmA.js +0 -13
  121. package/dist/assets/index-B45s9aAX.css +0 -1
  122. package/dist/assets/index-CNrN5qDs.js +0 -7
  123. package/dist/assets/ja-DJT9EM80.js +0 -15
  124. package/dist/assets/ko-CfWRq2p4.js +0 -15
  125. package/dist/assets/main-B4oBRI9u.js +0 -193
  126. package/dist/assets/markdownCore-A3_L34oS.js +0 -2
  127. package/dist/assets/pt-BR-BDEzzltP.js +0 -15
  128. package/dist/assets/renderMobileApp-DA7wpIBi.js +0 -23
  129. package/dist/assets/runtimeEndpointReset-D5izT-u5.js +0 -13
  130. package/dist/assets/scheduledTasksApi-CTJdfSWc.js +0 -1
  131. package/dist/assets/uk-B6Q32nyk.js +0 -15
  132. package/dist/assets/useInlineCommentController-D7zs7-BQ.js +0 -2
  133. package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
  134. package/dist/assets/zh-CN-7MGcwGaC.js +0 -15
  135. package/dist/assets/zh-TW-CFPfqxlL.js +0 -15
  136. package/server/lib/preview/proxy-runtime.js +0 -1604
  137. package/server/lib/preview/proxy-runtime.test.js +0 -528
  138. package/server/lib/quota/opencode-go-credentials.js +0 -11
  139. package/server/lib/quota/opencode-go-credentials.test.js +0 -32
  140. package/server/lib/quota/routes.test.js +0 -40
@@ -5,6 +5,7 @@ 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 { registerGitRoutes } from '../git/routes.js';
8
+ import { registerDevServerRoutes } from '../dev-servers/routes.js';
8
9
  import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
9
10
  import { registerSessionFoldersRoutes } from '../session-folders/routes.js';
10
11
  import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
@@ -14,6 +15,7 @@ import { registerProjectIconRoutes } from './project-icon-routes.js';
14
15
  import { registerScheduledTaskRoutes } from '../scheduled-tasks/routes.js';
15
16
  import { registerOpenChamberSessionRoutes } from '../openchamber-sessions/routes.js';
16
17
  import { registerOpenChamberControlRoutes } from '../openchamber-control/routes.js';
18
+ import { registerMarkdownImageGrantRoutes } from '../markdown-image-grants/routes.js';
17
19
  import { registerSkillRoutes } from './skill-routes.js';
18
20
  import { registerPluginRoutes } from './plugin-routes.js';
19
21
  import { getNpmInfo, clearCache as clearNpmCache } from './npm-registry.js';
@@ -110,6 +112,8 @@ export const createFeatureRoutesRuntime = (dependencies) => {
110
112
  buildOpenCodeUrl,
111
113
  getOpenCodeAuthHeaders,
112
114
  getOpenCodePort,
115
+ getOwnPorts,
116
+ devServerScanner,
113
117
  buildAugmentedPath,
114
118
  projectConfigRuntime,
115
119
  scheduledTasksRuntime,
@@ -187,6 +191,16 @@ export const createFeatureRoutesRuntime = (dependencies) => {
187
191
 
188
192
  registerOpenChamberControlRoutes(app, { controlService: openChamberControlService });
189
193
 
194
+ registerMarkdownImageGrantRoutes(app, {
195
+ fsPromises,
196
+ path,
197
+ os,
198
+ crypto,
199
+ validateDirectoryPath,
200
+ buildOpenCodeUrl,
201
+ getOpenCodeAuthHeaders,
202
+ });
203
+
190
204
  registerConfigEntityRoutes(app, {
191
205
  resolveProjectDirectory,
192
206
  resolveOptionalProjectDirectory,
@@ -284,6 +298,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
284
298
  registerSessionGoalRoutes(app);
285
299
  registerGitHubRoutes(app);
286
300
  registerGitRoutes(app);
301
+ registerDevServerRoutes(app, { scanner: devServerScanner, getOwnPorts });
287
302
  registerMagicPromptRoutes(app, {
288
303
  fsPromises,
289
304
  path,
@@ -1,3 +1,7 @@
1
+ /** One stray uncaught exception is survivable; a storm means the process is broken. */
2
+ const UNCAUGHT_STORM_LIMIT = 10;
3
+ const UNCAUGHT_STORM_WINDOW_MS = 60_000;
4
+
1
5
  export const createServerStartupRuntime = (dependencies) => {
2
6
  const {
3
7
  process,
@@ -148,9 +152,26 @@ export const createServerStartupRuntime = (dependencies) => {
148
152
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
149
153
  });
150
154
 
155
+ // A single stray exception — a socket teardown race, a Node-internal bug
156
+ // like `setTypeOfService EINVAL` — must not take the server down. Nothing
157
+ // restarts this process (it is embedded in the desktop app or run by hand
158
+ // in a terminal), so shutting down turns every such stray into "the
159
+ // instance is unreachable until I restart it". Mirror the
160
+ // unhandledRejection policy above: log and keep serving. A sustained storm
161
+ // of exceptions is a different situation — the process is genuinely
162
+ // broken — so that still shuts down rather than limping along half-alive.
163
+ const exceptionTimes = [];
151
164
  process.on('uncaughtException', (error) => {
152
165
  console.error('Uncaught Exception:', error);
153
- gracefulShutdown();
166
+ const now = Date.now();
167
+ exceptionTimes.push(now);
168
+ while (exceptionTimes.length > 0 && now - exceptionTimes[0] > UNCAUGHT_STORM_WINDOW_MS) {
169
+ exceptionTimes.shift();
170
+ }
171
+ if (exceptionTimes.length > UNCAUGHT_STORM_LIMIT) {
172
+ console.error(`More than ${UNCAUGHT_STORM_LIMIT} uncaught exceptions within a minute; shutting down.`);
173
+ gracefulShutdown();
174
+ }
154
175
  });
155
176
  };
156
177
 
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { EventEmitter } from 'node:events';
3
+ import { createServerStartupRuntime } from './server-startup-runtime.js';
4
+
5
+ /**
6
+ * The desktop app embeds this server and nothing restarts it, so shutting down
7
+ * on a single uncaught exception turned every stray socket error into "the
8
+ * instance is unreachable until restarted". Only a sustained storm shuts down.
9
+ */
10
+ describe('uncaught exception policy', () => {
11
+ const setup = () => {
12
+ const fakeProcess = new EventEmitter();
13
+ let shutdowns = 0;
14
+ const runtime = createServerStartupRuntime({
15
+ process: fakeProcess,
16
+ gracefulShutdown: () => { shutdowns += 1; },
17
+ getSignalsAttached: () => true,
18
+ setSignalsAttached: () => {},
19
+ syncToHmrState: () => {},
20
+ });
21
+ runtime.attachProcessHandlers({ attachSignals: false });
22
+ return { fakeProcess, shutdowns: () => shutdowns };
23
+ };
24
+
25
+ test('a single uncaught exception keeps the server running', () => {
26
+ const { fakeProcess, shutdowns } = setup();
27
+ fakeProcess.emit('uncaughtException', new Error('setTypeOfService EINVAL'));
28
+ expect(shutdowns()).toBe(0);
29
+ });
30
+
31
+ test('a storm of uncaught exceptions still shuts down', () => {
32
+ const { fakeProcess, shutdowns } = setup();
33
+ for (let i = 0; i < 11; i += 1) {
34
+ fakeProcess.emit('uncaughtException', new Error(`stray ${i}`));
35
+ }
36
+ expect(shutdowns()).toBeGreaterThan(0);
37
+ });
38
+
39
+ test('an unhandled rejection is logged without shutting down', () => {
40
+ const { fakeProcess, shutdowns } = setup();
41
+ fakeProcess.emit('unhandledRejection', new Error('late failure'), Promise.resolve());
42
+ expect(shutdowns()).toBe(0);
43
+ });
44
+ });
@@ -362,18 +362,9 @@ export const createSettingsHelpers = (dependencies) => {
362
362
  if (typeof candidate.maxLastMessageLength === 'number' && Number.isFinite(candidate.maxLastMessageLength)) {
363
363
  result.maxLastMessageLength = Math.max(10, Math.round(candidate.maxLastMessageLength));
364
364
  }
365
- if (typeof candidate.usageAutoRefresh === 'boolean') {
366
- result.usageAutoRefresh = candidate.usageAutoRefresh;
367
- }
368
- if (typeof candidate.usageRefreshIntervalMs === 'number' && Number.isFinite(candidate.usageRefreshIntervalMs)) {
369
- result.usageRefreshIntervalMs = Math.max(30000, Math.min(300000, Math.round(candidate.usageRefreshIntervalMs)));
370
- }
371
365
  if (candidate.usageDisplayMode === 'usage' || candidate.usageDisplayMode === 'remaining') {
372
366
  result.usageDisplayMode = candidate.usageDisplayMode;
373
367
  }
374
- if (typeof candidate.usageShowPredValues === 'boolean') {
375
- result.usageShowPredValues = candidate.usageShowPredValues;
376
- }
377
368
  if (Array.isArray(candidate.usageDropdownProviders)) {
378
369
  result.usageDropdownProviders = normalizeStringArray(candidate.usageDropdownProviders);
379
370
  }
@@ -511,6 +502,9 @@ export const createSettingsHelpers = (dependencies) => {
511
502
  if (typeof candidate.showOpenCodeUpdateNotifications === 'boolean') {
512
503
  result.showOpenCodeUpdateNotifications = candidate.showOpenCodeUpdateNotifications;
513
504
  }
505
+ if (typeof candidate.agentWebToolEnabled === 'boolean') {
506
+ result.agentWebToolEnabled = candidate.agentWebToolEnabled;
507
+ }
514
508
  if (typeof candidate.agentControlToolEnabled === 'boolean') {
515
509
  result.agentControlToolEnabled = candidate.agentControlToolEnabled;
516
510
  }
@@ -254,6 +254,12 @@ const normalizeState = (value, fallback) => {
254
254
  const nextRunAt = typeof source.nextRunAt === 'number' && Number.isFinite(source.nextRunAt)
255
255
  ? Math.max(0, Math.round(source.nextRunAt))
256
256
  : undefined;
257
+ // Absolute ms of the schedule occurrence last claimed for dispatch. Used so
258
+ // two OpenChamber server instances sharing this config cannot both start a
259
+ // run for the same daily/weekly/cron/once slot (see issue #2710).
260
+ const lastScheduledFor = typeof source.lastScheduledFor === 'number' && Number.isFinite(source.lastScheduledFor)
261
+ ? Math.max(0, Math.round(source.lastScheduledFor))
262
+ : undefined;
257
263
  const lastSessionId = asNonEmptyString(source.lastSessionId);
258
264
  const lastErrorRaw = asNonEmptyString(source.lastError);
259
265
  const lastError = lastErrorRaw ? clampLength(lastErrorRaw, MAX_LAST_ERROR_LENGTH) : undefined;
@@ -269,6 +275,7 @@ const normalizeState = (value, fallback) => {
269
275
  ...(typeof lastRunAt === 'number' ? { lastRunAt } : {}),
270
276
  ...(typeof lastDurationMs === 'number' ? { lastDurationMs } : {}),
271
277
  ...(typeof nextRunAt === 'number' ? { nextRunAt } : {}),
278
+ ...(typeof lastScheduledFor === 'number' ? { lastScheduledFor } : {}),
272
279
  ...(lastSessionId ? { lastSessionId } : {}),
273
280
  ...(lastError ? { lastError } : {}),
274
281
  };
@@ -360,6 +367,9 @@ export const createProjectConfigRuntime = (deps) => {
360
367
  });
361
368
 
362
369
  const writeLocks = new Map();
370
+ const PROJECT_FILE_LOCK_WAIT_MS = 10_000;
371
+ const PROJECT_FILE_LOCK_STALE_MS = 60_000;
372
+ const PROJECT_FILE_LOCK_RETRY_MS = 20;
363
373
 
364
374
  const sanitizeProjectID = (projectID) => {
365
375
  const value = asNonEmptyString(projectID);
@@ -377,6 +387,104 @@ export const createProjectConfigRuntime = (deps) => {
377
387
  return path.join(projectsDirPath, `${safeProjectID}.json`);
378
388
  };
379
389
 
390
+ const isProcessAlive = (pid) => {
391
+ if (!Number.isInteger(pid) || pid <= 0) {
392
+ return false;
393
+ }
394
+ try {
395
+ process.kill(pid, 0);
396
+ return true;
397
+ } catch (error) {
398
+ // EPERM: process exists but belongs to another user — treat as alive.
399
+ return error?.code === 'EPERM';
400
+ }
401
+ };
402
+
403
+ /**
404
+ * Cross-process exclusive lock for a project config file.
405
+ * In-process chaining alone cannot serialize Electron (port 57123) and CLI
406
+ * serve (port 3000) writers that share the same on-disk projects dir.
407
+ */
408
+ const acquireProjectFileLock = async (projectID) => {
409
+ const configPath = resolveProjectConfigPath(projectID);
410
+ const lockPath = `${configPath}.lock`;
411
+ const startedAt = Date.now();
412
+
413
+ await fsPromises.mkdir(path.dirname(configPath), { recursive: true });
414
+
415
+ while (Date.now() - startedAt < PROJECT_FILE_LOCK_WAIT_MS) {
416
+ let handle;
417
+ try {
418
+ handle = await fsPromises.open(lockPath, 'wx');
419
+ const lockPayload = {
420
+ pid: process.pid,
421
+ at: Date.now(),
422
+ };
423
+ await handle.writeFile(JSON.stringify(lockPayload));
424
+ return {
425
+ release: async () => {
426
+ try {
427
+ await handle.close();
428
+ } catch {
429
+ }
430
+ // Only unlink if we still own the lock. A stale-recovery steal can
431
+ // replace the file; unlinking blindly would drop the new owner's lock.
432
+ try {
433
+ const raw = await fsPromises.readFile(lockPath, 'utf8');
434
+ const parsed = JSON.parse(raw);
435
+ if (Number(parsed?.pid) !== process.pid) {
436
+ return;
437
+ }
438
+ await fsPromises.unlink(lockPath);
439
+ } catch {
440
+ }
441
+ },
442
+ };
443
+ } catch (error) {
444
+ if (handle) {
445
+ try {
446
+ await handle.close();
447
+ } catch {
448
+ }
449
+ }
450
+ if (error?.code !== 'EEXIST') {
451
+ throw error;
452
+ }
453
+
454
+ try {
455
+ const raw = await fsPromises.readFile(lockPath, 'utf8');
456
+ const parsed = JSON.parse(raw);
457
+ const lockPid = Number(parsed?.pid);
458
+ const lockAt = Number(parsed?.at);
459
+ const staleByPid = Number.isInteger(lockPid) && lockPid > 0 && !isProcessAlive(lockPid);
460
+ const staleByAge = Number.isFinite(lockAt) && (Date.now() - lockAt) > PROJECT_FILE_LOCK_STALE_MS;
461
+ if (staleByPid || staleByAge || !Number.isInteger(lockPid)) {
462
+ await fsPromises.unlink(lockPath).catch(() => {});
463
+ continue;
464
+ }
465
+ } catch {
466
+ // Crash between open(wx) and writeFile (or a partial write) leaves an
467
+ // unparseable lock. Fall back to mtime age so recovery is not wedged.
468
+ try {
469
+ const stat = await fsPromises.stat(lockPath);
470
+ const mtimeMs = Number(stat?.mtimeMs);
471
+ if (Number.isFinite(mtimeMs) && (Date.now() - mtimeMs) > PROJECT_FILE_LOCK_STALE_MS) {
472
+ await fsPromises.unlink(lockPath).catch(() => {});
473
+ continue;
474
+ }
475
+ } catch {
476
+ }
477
+ }
478
+
479
+ await new Promise((resolve) => {
480
+ setTimeout(resolve, PROJECT_FILE_LOCK_RETRY_MS);
481
+ });
482
+ }
483
+ }
484
+
485
+ throw new Error(`timeout acquiring project config lock for ${projectID}`);
486
+ };
487
+
380
488
  const readRawProjectConfigFromDisk = async (projectID) => {
381
489
  const filePath = resolveProjectConfigPath(projectID);
382
490
  try {
@@ -443,8 +551,16 @@ export const createProjectConfigRuntime = (deps) => {
443
551
  writeLocks.set(key, chained);
444
552
 
445
553
  await previous;
554
+ // Acquire sits outside the mutate try — if it throws (10s lock timeout),
555
+ // we must still release the in-process chain or every later write for this
556
+ // project hangs forever on await previous.
446
557
  try {
447
- return await mutate();
558
+ const fileLock = await acquireProjectFileLock(projectID);
559
+ try {
560
+ return await mutate();
561
+ } finally {
562
+ await fileLock.release();
563
+ }
448
564
  } finally {
449
565
  release();
450
566
  const current = writeLocks.get(key);
@@ -533,10 +649,71 @@ export const createProjectConfigRuntime = (deps) => {
533
649
  const current = await readProjectConfigFromDisk(projectID);
534
650
  const taskIndex = current.scheduledTasks.findIndex((task) => task.id === normalizedTaskID);
535
651
  if (taskIndex === -1) {
536
- return { task: null, tasks: current.scheduledTasks };
652
+ return { task: null, tasks: current.scheduledTasks, updated: false };
653
+ }
654
+
655
+ const currentTask = current.scheduledTasks[taskIndex];
656
+ const patchObject = statePatch && typeof statePatch === 'object' ? statePatch : {};
657
+ const nextTask = {
658
+ ...currentTask,
659
+ state: normalizeState(
660
+ {
661
+ ...currentTask.state,
662
+ ...patchObject,
663
+ updatedAt: Date.now(),
664
+ },
665
+ currentTask.state,
666
+ ),
667
+ };
668
+
669
+ const nextTasks = current.scheduledTasks.slice();
670
+ nextTasks[taskIndex] = nextTask;
671
+
672
+ await writeProjectConfigToDisk(projectID, {
673
+ version: PROJECT_CONFIG_VERSION,
674
+ scheduledTasks: nextTasks,
675
+ });
676
+
677
+ return {
678
+ task: nextTask,
679
+ tasks: nextTasks,
680
+ updated: true,
681
+ };
682
+ });
683
+ };
684
+
685
+ /**
686
+ * Conditionally patch task runtime state under the project write lock.
687
+ * `predicate(currentTask)` is evaluated after the latest on-disk read; when
688
+ * it returns false the write is skipped and `{ updated: false }` is returned.
689
+ * Used by the scheduled-tasks runtime to claim a single schedule occurrence
690
+ * across concurrent OpenChamber server instances.
691
+ */
692
+ const updateScheduledTaskStateIf = async (projectID, taskID, predicate, statePatch) => {
693
+ return withProjectWriteLock(projectID, async () => {
694
+ const normalizedTaskID = asNonEmptyString(taskID);
695
+ if (!normalizedTaskID) {
696
+ throw new Error('taskId is required');
697
+ }
698
+ if (typeof predicate !== 'function') {
699
+ throw new Error('predicate is required');
700
+ }
701
+
702
+ const current = await readProjectConfigFromDisk(projectID);
703
+ const taskIndex = current.scheduledTasks.findIndex((task) => task.id === normalizedTaskID);
704
+ if (taskIndex === -1) {
705
+ return { task: null, tasks: current.scheduledTasks, updated: false };
537
706
  }
538
707
 
539
708
  const currentTask = current.scheduledTasks[taskIndex];
709
+ if (!predicate(currentTask)) {
710
+ return {
711
+ task: currentTask,
712
+ tasks: current.scheduledTasks,
713
+ updated: false,
714
+ };
715
+ }
716
+
540
717
  const patchObject = statePatch && typeof statePatch === 'object' ? statePatch : {};
541
718
  const nextTask = {
542
719
  ...currentTask,
@@ -561,6 +738,7 @@ export const createProjectConfigRuntime = (deps) => {
561
738
  return {
562
739
  task: nextTask,
563
740
  tasks: nextTasks,
741
+ updated: true,
564
742
  };
565
743
  });
566
744
  };
@@ -699,6 +877,7 @@ export const createProjectConfigRuntime = (deps) => {
699
877
  upsertScheduledTask,
700
878
  deleteScheduledTask,
701
879
  updateScheduledTaskState,
880
+ updateScheduledTaskStateIf,
702
881
  reconcileLoopTasks,
703
882
  resolveProjectConfigPath,
704
883
  };