@openchamber/web 1.22.1 → 1.22.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 (111) hide show
  1. package/bin/cli.js +4 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-BI-TY1UG.js} +1 -1
  6. package/dist/assets/{DiffView-CNnDxRmO.js → DiffView-cOmByCaX.js} +3 -3
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-BwSnDlNy.js} +1 -1
  8. package/dist/assets/FilesView-DRRy_6oZ.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-B7YCg1YM.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-CjzNsiIU.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BYlE0YrW.js} +1 -1
  12. package/dist/assets/{MarkdownImageGallery-DffjmciG.js → MarkdownImageGallery-DlTF-wua.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-CqgeZRlP.js +12 -0
  14. package/dist/assets/{OnboardingScreen-CTZe6HZn.js → OnboardingScreen-BsJU7oav.js} +1 -1
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CDNu968J.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BvwtCxW4.js → PierreDiffViewer-BoBsAanf.js} +1 -1
  17. package/dist/assets/{PlanView-C1qvAm7m.js → PlanView-Cxr8LQT1.js} +4 -4
  18. package/dist/assets/SettingsView-bsKpCZbB.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-B0rHQdw4.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-6zP8hwzX.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-Bvwh4Y31.js} +2 -2
  22. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-aaIfrRxl.js} +1 -1
  23. package/dist/assets/{WalkthroughView-D-HFgdmM.js → WalkthroughView-baZ0ssy9.js} +2 -2
  24. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-DfgllYQc.js} +2 -2
  25. package/dist/assets/{contextPanelEmbeddedChat-CV-DwAiX.js → contextPanelEmbeddedChat-prHos-tt.js} +1 -1
  26. package/dist/assets/{de-Cv_4FoXm.js → de-hknQLFxa.js} +2 -2
  27. package/dist/assets/{es-BIWNEbnS.js → es-C_bD3kvW.js} +2 -2
  28. package/dist/assets/{fr-SD3OfMHJ.js → fr-BVF-C2Nu.js} +2 -2
  29. package/dist/assets/index-B0aX0JeI.js +39 -0
  30. package/dist/assets/{index-DLiD86ge.js → index-DUwZ2cWA.js} +1 -1
  31. package/dist/assets/index-Dl3xbAB_.css +1 -0
  32. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-COIS9Df5.js} +1 -1
  33. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-D7LEG-KY.js} +1 -1
  34. package/dist/assets/{ja-D7I9HofF.js → ja-B2G5hD59.js} +2 -2
  35. package/dist/assets/{ko-BsVJM_PQ.js → ko-D6OrOdZ3.js} +2 -2
  36. package/dist/assets/main-BBuBZzoi.js +930 -0
  37. package/dist/assets/{main-DCB4JgVe.js → main-CwIEELQq.js} +2 -2
  38. package/dist/assets/{markdownCore-BoQVG5-a.js → markdownCore-BE_Hhps5.js} +2 -2
  39. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CeXAoWiF.js} +2 -2
  40. package/dist/assets/{mobile-DZV_sfX7.js → mobile-ilq39yLQ.js} +2 -2
  41. package/dist/assets/{patchFileDiff-Chmiz6hq.js → patchFileDiff-DLky6SYr.js} +5 -5
  42. package/dist/assets/{pl-XR9Bs8Be.js → pl-CVroZXt1.js} +2 -2
  43. package/dist/assets/{pt-BR-Due4be8g.js → pt-BR-eH3onaIW.js} +2 -2
  44. package/dist/assets/{renderElectronMiniChatApp-8tXADjfl.js → renderElectronMiniChatApp-BsywqmJT.js} +2 -2
  45. package/dist/assets/{renderMobileApp-Cji7Hma5.js → renderMobileApp-CDun1795.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-DebJIo5U.js +17 -0
  47. package/dist/assets/{scheduledTasksApi-9e-UX6im.js → scheduledTasksApi-B0tChXQC.js} +1 -1
  48. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-DJSXdcG4.js} +1 -1
  49. package/dist/assets/tr-BvtU2tXS.js +7 -0
  50. package/dist/assets/{uk-COYh2BaN.js → uk-nu36iqFz.js} +2 -2
  51. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-Bb1Zihd2.js} +134 -131
  52. package/dist/assets/useInlineCommentController-B8dQWRpH.js +2 -0
  53. package/dist/assets/{useRootScrollLock-KzOUytpn.js → useRootScrollLock-DrJ8gE-x.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-CNjvbb69.js} +2 -2
  55. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  56. package/dist/assets/{web-components-B6QgbmTo.js → web-components-C06MmTcR.js} +1 -1
  57. package/dist/assets/{zh-CN-Cjk6lzhc.js → zh-CN-BClBzZ64.js} +2 -2
  58. package/dist/assets/{zh-TW-Dk0dOg03.js → zh-TW-CXtSqJHF.js} +2 -2
  59. package/dist/index.html +5 -5
  60. package/dist/mini-chat.html +4 -4
  61. package/dist/mobile.html +4 -4
  62. package/package.json +3 -3
  63. package/server/index.js +7 -1
  64. package/server/lib/changelog/update-notes.js +82 -0
  65. package/server/lib/changelog/update-notes.test.js +59 -0
  66. package/server/lib/fs/DOCUMENTATION.md +2 -0
  67. package/server/lib/fs/routes.js +32 -21
  68. package/server/lib/fs/routes.test.js +77 -0
  69. package/server/lib/git/service.js +10 -0
  70. package/server/lib/git/service.test.js +18 -0
  71. package/server/lib/message-queue/DOCUMENTATION.md +17 -7
  72. package/server/lib/message-queue/runtime.js +59 -7
  73. package/server/lib/message-queue/runtime.test.js +59 -3
  74. package/server/lib/opencode/DOCUMENTATION.md +8 -4
  75. package/server/lib/opencode/config-paths.test.js +116 -0
  76. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  77. package/server/lib/opencode/input-history-scope.js +14 -0
  78. package/server/lib/opencode/plugins.js +2 -2
  79. package/server/lib/opencode/providers.js +44 -2
  80. package/server/lib/opencode/providers.test.js +131 -4
  81. package/server/lib/opencode/routes.js +4 -4
  82. package/server/lib/opencode/server-startup-runtime.js +1 -1
  83. package/server/lib/opencode/settings-helpers.js +28 -0
  84. package/server/lib/opencode/settings-helpers.test.js +177 -0
  85. package/server/lib/opencode/shared.js +4 -1
  86. package/server/lib/opencode/skill-routes.js +2 -1
  87. package/server/lib/opencode/snippets.js +1 -2
  88. package/server/lib/package-manager.js +3 -28
  89. package/server/lib/quota/utils/auth.js +1 -1
  90. package/server/lib/relay/host-client.test.js +9 -1
  91. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  92. package/server/lib/session-goal/runtime.js +76 -11
  93. package/server/lib/session-goal/runtime.test.js +426 -0
  94. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  95. package/server/lib/skills-catalog/install.js +3 -2
  96. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  97. package/server/lib/terminal/runtime.js +150 -19
  98. package/server/lib/terminal/runtime.test.js +553 -26
  99. package/server/lib/terminal/shells.js +17 -0
  100. package/server/lib/terminal/shells.test.js +32 -1
  101. package/server/lib/walkthrough/routes.test.js +26 -5
  102. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  103. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  104. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  105. package/dist/assets/index-CHUT_bDS.css +0 -1
  106. package/dist/assets/index-DDInLQDd.js +0 -40
  107. package/dist/assets/main-De8Z5w49.js +0 -928
  108. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  109. package/dist/assets/tr-DBJcAv4y.js +0 -7
  110. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  111. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
@@ -9,7 +9,7 @@ import {
9
9
  } from './terminal-ws-protocol.js';
10
10
  import { sanitizeTerminalHistoryChunk } from './history.js';
11
11
  import { consumeTerminalThemeQueries, terminalThemeModeReport } from './theme-response.js';
12
- import { createTerminalShellResolver, getTerminalShellLoginArgs, normalizeTerminalShell } from './shells.js';
12
+ import { buildTerminalShellLaunch, createTerminalShellResolver, normalizeTerminalShell } from './shells.js';
13
13
  import { stripAppImageArgv0Leak, resolveLinuxPtyLaunch } from '../inherited-env.js';
14
14
 
15
15
  const MAX_SESSIONS = 20;
@@ -17,7 +17,69 @@ const MAX_HISTORY_BYTES = 512 * 1024;
17
17
  const MAX_INPUT_CHARS = 65_536;
18
18
  const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
19
19
  const TERMINATION_GRACE_MS = 1000;
20
+ const INTERACTIVE_TERMINAL_MODE = 'interactive';
21
+ const COMMAND_TERMINAL_MODE = 'command';
22
+ // Error code the create/restart routes attach when the requested cwd no longer
23
+ // exists. Mirrored by `TERMINAL_CWD_MISSING_CODE` in packages/ui/src/lib/terminalApi.ts.
24
+ const TERMINAL_CWD_MISSING_CODE = 'TERMINAL_CWD_MISSING';
25
+ const TERMINAL_PURPOSE = Object.freeze({ type: 'terminal' });
26
+ const MAX_PURPOSE_ID_CHARS = 128;
27
+ const OBJECT_TAG = '[object Object]';
20
28
  const validateSize = (value, max) => Number.isInteger(value) && value >= 1 && value <= max;
29
+ const isString = (value) => String(value) === value;
30
+ const isObjectRecord = (value) => value != null && !Array.isArray(value) && Object.prototype.toString.call(value) === OBJECT_TAG;
31
+ const normalizeCreateMode = ({ mode, command }) => {
32
+ const normalizedMode = mode == null ? INTERACTIVE_TERMINAL_MODE : mode;
33
+ if (normalizedMode !== INTERACTIVE_TERMINAL_MODE && normalizedMode !== COMMAND_TERMINAL_MODE) throw new Error('Invalid terminal mode');
34
+ if (normalizedMode === INTERACTIVE_TERMINAL_MODE) {
35
+ if (command != null) throw new Error('Interactive terminal create does not accept a command');
36
+ return { mode: INTERACTIVE_TERMINAL_MODE, command: null };
37
+ }
38
+ if (!isString(command) || !command.trim()) throw new Error('Terminal command is required');
39
+ const trimmedCommand = command.trim();
40
+ if (trimmedCommand.length > MAX_INPUT_CHARS) throw new Error('Terminal command exceeds the input limit');
41
+ return { mode: COMMAND_TERMINAL_MODE, command: trimmedCommand };
42
+ };
43
+ const normalizePurposeId = (value, errorMessage) => {
44
+ if (!isString(value) || !value.trim()) throw new Error(errorMessage);
45
+ const normalized = value.trim();
46
+ if (normalized.length > MAX_PURPOSE_ID_CHARS) throw new Error(errorMessage);
47
+ return normalized;
48
+ };
49
+ const normalizeTerminalPurpose = (value) => {
50
+ if (value == null) return TERMINAL_PURPOSE;
51
+ if (!isObjectRecord(value)) throw new Error('Invalid terminal purpose');
52
+ if (value.type === 'terminal') return TERMINAL_PURPOSE;
53
+ if (value.type !== 'project-action') throw new Error('Invalid terminal purpose');
54
+ return {
55
+ type: 'project-action',
56
+ actionId: normalizePurposeId(value.actionId, 'Terminal project action id is required'),
57
+ executionId: normalizePurposeId(value.executionId, 'Terminal execution id is required'),
58
+ };
59
+ };
60
+ const getSessionPurpose = (session) => session.purpose ?? TERMINAL_PURPOSE;
61
+ const isPurposeActionMatch = (left, right) => {
62
+ if (left.type !== right.type) return false;
63
+ return left.type !== 'project-action' || left.actionId === right.actionId;
64
+ };
65
+ const findRunningActionSession = (sessions, resolvedCwd, purpose, path) => {
66
+ if (purpose.type !== 'project-action') return null;
67
+ for (const session of sessions.values()) {
68
+ if (session.status !== 'running') continue;
69
+ if (path.resolve(session.cwd) !== resolvedCwd) continue;
70
+ const sessionPurpose = getSessionPurpose(session);
71
+ if (sessionPurpose.type === 'project-action' && sessionPurpose.actionId === purpose.actionId) return session;
72
+ }
73
+ return null;
74
+ };
75
+ const findPendingActionCreate = (pendingSessionCreates, resolvedCwd, purpose) => {
76
+ if (purpose.type !== 'project-action') return null;
77
+ for (const pending of pendingSessionCreates.values()) {
78
+ if (pending.cancelled || pending.cwd !== resolvedCwd) continue;
79
+ if (pending.purpose?.type === 'project-action' && pending.purpose.actionId === purpose.actionId) return pending;
80
+ }
81
+ return null;
82
+ };
21
83
  const trimHistory = (history) => {
22
84
  const bytes = Buffer.from(history);
23
85
  if (bytes.byteLength <= MAX_HISTORY_BYTES) return history;
@@ -54,13 +116,11 @@ export function createTerminalRuntime({
54
116
  return ptyProviderPromise;
55
117
  };
56
118
 
57
- const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell }) => {
119
+ const spawnPty = async ({ cwd, cols, rows, themeMode, shell, loginShell, mode, command }) => {
58
120
  const provider = await getPtyProvider();
59
121
  const resolvedShell = await shellResolver.resolve(shell);
60
122
  let lastError = null;
61
123
  for (const executable of resolvedShell.executables) {
62
- const args = loginShell ? getTerminalShellLoginArgs(executable) : [];
63
- if (!args) throw new Error(`Terminal shell "${resolvedShell.id}" does not support login mode`);
64
124
  try {
65
125
  const env = { ...process.env, PATH: buildAugmentedPath(), TERM: 'xterm-256color', COLORTERM: 'truecolor', COLORFGBG: themeMode === 'light' ? '0;15' : '15;0' };
66
126
  // The daemon's IPC fd is closed inside the PTY. An explicit override is
@@ -70,9 +130,11 @@ export function createTerminalRuntime({
70
130
  // AppImage exports ARGV0; zsh would otherwise rewrite argv[0] for every command (#2588).
71
131
  // bun-pty also merges the native OS environ, so wrap with `env -u ARGV0` on Linux.
72
132
  stripAppImageArgv0Leak(env);
73
- const launch = resolveLinuxPtyLaunch(executable, args);
74
- const options = { name: 'xterm-256color', cwd, cols, rows, env, ...(process.platform === 'win32' ? { useConpty: true } : {}) };
75
- return { process: provider.spawn(launch.executable, launch.args, options), backend: provider.backend, shell: resolvedShell.id, loginShell };
133
+ const shellLaunch = buildTerminalShellLaunch(executable, { mode, command, loginShell });
134
+ const launch = resolveLinuxPtyLaunch(shellLaunch.executable, shellLaunch.args);
135
+ const options = { name: 'xterm-256color', cwd, cols, rows, env };
136
+ if (process.platform === 'win32') options.useConpty = true;
137
+ return { process: await provider.spawn(launch.executable, launch.args, options), backend: provider.backend, shell: resolvedShell.id, loginShell };
76
138
  } catch (error) { lastError = error; }
77
139
  }
78
140
  throw lastError ?? new Error('No executable shell found');
@@ -123,6 +185,7 @@ export function createTerminalRuntime({
123
185
  const snapshot = (session) => ({
124
186
  t: 'snapshot', v: 3, s: session.id, q: session.sequence, history: session.history,
125
187
  status: session.status, exitCode: session.exitCode, signal: session.signal,
188
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE, purpose: getSessionPurpose(session),
126
189
  runtime, ptyBackend: session.backend,
127
190
  });
128
191
 
@@ -175,11 +238,18 @@ export function createTerminalRuntime({
175
238
  ptyProcess.onExit(({ exitCode, signal }) => { session.eventQueue.push({ type: 'exit', process: ptyProcess, exitCode, signal }); drainEvents(session); });
176
239
  };
177
240
 
241
+ // A working directory that no longer exists (a deleted worktree) is the one
242
+ // rejection the client can recover from by moving the session to its
243
+ // project, so the response names it. Every other rejection stays generic.
244
+ const invalidWorkingDirectory = (code) => Object.assign(new Error('Invalid working directory'), code ? { code } : {});
178
245
  const validateCwd = async (cwd) => {
179
246
  if (typeof cwd !== 'string' || !cwd.trim()) throw new Error('cwd is required');
180
- const stats = await fs.promises.stat(cwd).catch(() => null);
181
- if (!stats?.isDirectory()) throw new Error('Invalid working directory');
247
+ let stats;
248
+ try { stats = await fs.promises.stat(cwd); }
249
+ catch (error) { throw invalidWorkingDirectory(error?.code === 'ENOENT' || error?.code === 'ENOTDIR' ? TERMINAL_CWD_MISSING_CODE : undefined); }
250
+ if (!stats?.isDirectory()) throw invalidWorkingDirectory();
182
251
  };
252
+ const errorBody = (error, fallback) => ({ error: error?.message || fallback, ...(typeof error?.code === 'string' ? { code: error.code } : {}) });
183
253
 
184
254
  const applyAppearance = (session, { themeMode, terminalBackground, terminalForeground }) => {
185
255
  const previous = [session.themeMode, session.terminalBackground, session.terminalForeground];
@@ -192,48 +262,87 @@ export function createTerminalRuntime({
192
262
  }
193
263
  };
194
264
 
195
- const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell }, clear = true) => {
265
+ const startSession = async (session, { cwd, cols, rows, themeMode = 'dark', terminalBackground, terminalForeground, shell, loginShell, mode = INTERACTIVE_TERMINAL_MODE, command = null, purpose = TERMINAL_PURPOSE }, clear = true) => {
196
266
  await validateCwd(cwd);
197
- const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell });
267
+ const spawned = await spawnPty({ cwd, cols, rows, themeMode, shell, loginShell, mode, command });
198
268
  if (clear) { session.history = ''; session.pendingHistoryControlSequence = ''; session.pendingThemeControlSequence = ''; session.themeModeEnabled = false; }
199
269
  session.cwd = cwd; session.cols = cols; session.rows = rows; session.process = spawned.process;
200
270
  session.backend = spawned.backend; session.shell = spawned.shell; session.loginShell = spawned.loginShell; session.status = 'running'; session.exitCode = null; session.signal = null;
271
+ session.mode = mode; session.command = mode === COMMAND_TERMINAL_MODE ? command : null;
272
+ session.purpose = purpose;
201
273
  session.themeMode = themeMode === 'light' ? 'light' : 'dark'; session.terminalBackground = terminalBackground; session.terminalForeground = terminalForeground;
202
274
  session.lastActivity = Date.now(); session.eventQueue.length = 0;
203
275
  wire(session, spawned.process);
276
+ return spawned.process;
204
277
  };
205
278
 
206
- const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false }) => {
279
+ const createSession = async ({ sessionId, cwd, cols = 80, rows = 24, themeMode, terminalBackground, terminalForeground, shell = 'auto', loginShell = false, mode, command, purpose }) => {
207
280
  if (!validateSize(cols, 1000) || !validateSize(rows, 500)) throw new Error('Invalid terminal dimensions');
208
281
  if (typeof loginShell !== 'boolean') throw new Error('Invalid terminal login mode');
209
282
  const normalizedShell = normalizeTerminalShell(shell);
210
283
  if (!normalizedShell) throw new Error('Invalid terminal shell');
284
+ const launchMode = normalizeCreateMode({ mode, command });
285
+ const normalizedPurpose = normalizeTerminalPurpose(purpose);
211
286
  const id = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : randomUUID();
212
287
  if (id.length > 128) throw new Error('Invalid terminal session id');
213
288
  const existing = sessions.get(id);
214
289
  const resolvedCwd = path.resolve(cwd);
215
290
  if (existing?.status === 'running') {
216
291
  if (path.resolve(existing.cwd) !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
292
+ if (!isPurposeActionMatch(getSessionPurpose(existing), normalizedPurpose)) throw new Error('Terminal session is already running with a different purpose');
293
+ if (normalizedPurpose.type === 'project-action') { applyAppearance(existing, { themeMode, terminalBackground, terminalForeground }); return existing; }
294
+ if ((existing.mode ?? INTERACTIVE_TERMINAL_MODE) !== launchMode.mode) throw new Error('Terminal session is already running with a different mode');
295
+ if (launchMode.mode === COMMAND_TERMINAL_MODE && existing.command !== launchMode.command) throw new Error('Terminal session is already running with a different command');
217
296
  applyAppearance(existing, { themeMode, terminalBackground, terminalForeground });
218
297
  return existing;
219
298
  }
299
+ const runningActionSession = findRunningActionSession(sessions, resolvedCwd, normalizedPurpose, path);
300
+ if (runningActionSession) {
301
+ applyAppearance(runningActionSession, { themeMode, terminalBackground, terminalForeground });
302
+ return runningActionSession;
303
+ }
220
304
  const pending = pendingSessionCreates.get(id);
221
305
  if (pending) {
222
306
  if (pending.cwd !== resolvedCwd) throw new Error('Terminal session belongs to a different working directory');
307
+ if (!isPurposeActionMatch(pending.purpose, normalizedPurpose)) throw new Error('Terminal session is already being created with a different purpose');
308
+ if (normalizedPurpose.type === 'project-action') return pending.promise;
223
309
  if (pending.shell !== normalizedShell) throw new Error('Terminal session is already being created with a different shell');
224
310
  if (pending.loginShell !== loginShell) throw new Error('Terminal session is already being created with a different login mode');
311
+ if (pending.mode !== launchMode.mode) throw new Error('Terminal session is already being created with a different mode');
312
+ if (launchMode.mode === COMMAND_TERMINAL_MODE && pending.command !== launchMode.command) throw new Error('Terminal session is already being created with a different command');
225
313
  const session = await pending.promise;
226
314
  applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
227
315
  return session;
228
316
  }
229
- if (!existing && sessions.size + pendingSessionCreates.size >= MAX_SESSIONS) throw new Error('Maximum terminal sessions reached');
317
+ const pendingActionCreate = findPendingActionCreate(pendingSessionCreates, resolvedCwd, normalizedPurpose);
318
+ if (pendingActionCreate) {
319
+ const session = await pendingActionCreate.promise;
320
+ applyAppearance(session, { themeMode, terminalBackground, terminalForeground });
321
+ return session;
322
+ }
323
+ const superseded = normalizedPurpose.type === 'project-action'
324
+ ? [...sessions.values()].filter((session) => session.id !== id && session.status === 'exited'
325
+ && path.resolve(session.cwd) === resolvedCwd && isPurposeActionMatch(getSessionPurpose(session), normalizedPurpose))
326
+ : [];
327
+ if (!existing && sessions.size - superseded.length + pendingSessionCreates.size >= MAX_SESSIONS) throw new Error('Maximum terminal sessions reached');
328
+ const pendingEntry = { cwd: resolvedCwd, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose, cancelled: false, promise: null };
230
329
  const creation = (async () => {
231
330
  const session = existing ?? { id, sequence: 0, history: '', pendingHistoryControlSequence: '', pendingThemeControlSequence: '', eventQueue: [], draining: false, createdAt: Date.now() };
232
- await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell });
331
+ const ptyProcess = await startSession(session, { cwd, cols, rows, themeMode, terminalBackground, terminalForeground, shell: normalizedShell, loginShell, mode: launchMode.mode, command: launchMode.command, purpose: normalizedPurpose });
332
+ if (pendingEntry.cancelled) {
333
+ session.process = null;
334
+ await terminateProcess(ptyProcess, true);
335
+ throw new Error('Terminal session was closed during creation');
336
+ }
337
+ for (const previous of superseded) {
338
+ if (sessions.get(previous.id) !== previous || previous.status !== 'exited') continue;
339
+ sessions.delete(previous.id);
340
+ closeAttachments(previous.id, 'SUPERSEDED', 'Terminal replaced by a new action run');
341
+ }
233
342
  sessions.set(id, session);
234
343
  return session;
235
344
  })();
236
- const pendingEntry = { cwd: resolvedCwd, shell: normalizedShell, loginShell, promise: creation };
345
+ pendingEntry.promise = creation;
237
346
  pendingSessionCreates.set(id, pendingEntry);
238
347
  try { return await creation; }
239
348
  finally { if (pendingSessionCreates.get(id) === pendingEntry) pendingSessionCreates.delete(id); }
@@ -331,6 +440,8 @@ export function createTerminalRuntime({
331
440
  cwd: session.cwd,
332
441
  status: session.status,
333
442
  createdAt: Number.isInteger(session.createdAt) ? session.createdAt : null,
443
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
444
+ purpose: getSessionPurpose(session),
334
445
  });
335
446
  }
336
447
  res.json({ sessions: list });
@@ -349,8 +460,18 @@ export function createTerminalRuntime({
349
460
  res.json({ touched });
350
461
  });
351
462
  app.post('/api/terminal/create', async (req, res) => {
352
- try { const session = await createSession(req.body ?? {}); res.json({ sessionId: session.id, cols: session.cols, rows: session.rows, status: session.status }); }
353
- catch (error) { res.status(error?.message === 'Maximum terminal sessions reached' ? 429 : 400).json({ error: error?.message || 'Failed to create terminal session' }); }
463
+ try {
464
+ const session = await createSession(req.body ?? {});
465
+ res.json({
466
+ sessionId: session.id,
467
+ cols: session.cols,
468
+ rows: session.rows,
469
+ status: session.status,
470
+ mode: session.mode ?? INTERACTIVE_TERMINAL_MODE,
471
+ purpose: getSessionPurpose(session),
472
+ });
473
+ }
474
+ catch (error) { res.status(error?.message === 'Maximum terminal sessions reached' ? 429 : 400).json(errorBody(error, 'Failed to create terminal session')); }
354
475
  });
355
476
  app.post('/api/terminal/:sessionId/resize', (req, res) => {
356
477
  const session = sessions.get(req.params.sessionId);
@@ -369,6 +490,7 @@ export function createTerminalRuntime({
369
490
  app.post('/api/terminal/:sessionId/restart', async (req, res) => {
370
491
  const session = sessions.get(req.params.sessionId);
371
492
  if (!session) return res.status(404).json({ error: 'Terminal session not found' });
493
+ if ((session.mode ?? INTERACTIVE_TERMINAL_MODE) === COMMAND_TERMINAL_MODE) return res.status(400).json({ error: 'Command-mode terminal sessions cannot be restarted' });
372
494
  const cwd = req.body?.cwd ?? session.cwd;
373
495
  const cols = req.body?.cols ?? session.cols;
374
496
  const rows = req.body?.rows ?? session.rows;
@@ -393,12 +515,21 @@ export function createTerminalRuntime({
393
515
  try {
394
516
  await restart;
395
517
  res.json({ sessionId: session.id, cols, rows, status: session.status });
396
- } catch (error) { res.status(400).json({ error: error?.message || 'Failed to restart terminal' }); }
518
+ } catch (error) { res.status(400).json(errorBody(error, 'Failed to restart terminal')); }
397
519
  finally { if (pendingSessionRestarts.get(session.id) === restart) pendingSessionRestarts.delete(session.id); }
398
520
  });
399
521
  app.delete('/api/terminal/:sessionId', async (req, res) => {
400
522
  const session = sessions.get(req.params.sessionId);
401
- if (!session) return res.status(404).json({ error: 'Terminal session not found' });
523
+ if (!session) {
524
+ const pending = pendingSessionCreates.get(req.params.sessionId);
525
+ if (!pending) return res.status(404).json({ error: 'Terminal session not found' });
526
+ pending.cancelled = true;
527
+ try { await pending.promise; }
528
+ catch (error) {
529
+ if (error?.message !== 'Terminal session was closed during creation') throw error;
530
+ }
531
+ return res.json({ success: true });
532
+ }
402
533
  sessions.delete(session.id);
403
534
  closeAttachments(session.id, 'CLOSED', 'Terminal closed');
404
535
  await terminateProcess(session.process);