@causyne/agent 1.20.127 → 1.20.128

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 (69) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  2. package/package.json +3 -1
  3. package/src/agentLoop.js +59 -26
  4. package/src/agentLoop.ts +59 -24
  5. package/src/browser/causyneBrowser.js +31 -0
  6. package/src/browser/causyneBrowser.ts +32 -0
  7. package/src/commands.js +177 -13
  8. package/src/commands.ts +194 -13
  9. package/src/memory/episodicStore.js +40 -0
  10. package/src/memory/episodicStore.ts +46 -0
  11. package/src/memory.js +67 -0
  12. package/src/memory.ts +65 -0
  13. package/src/personalization.js +365 -0
  14. package/src/personalization.ts +471 -0
  15. package/src/projectInstructions.js +30 -10
  16. package/src/projectInstructions.ts +31 -12
  17. package/src/providers/acp.js +3 -2
  18. package/src/providers/acp.ts +3 -2
  19. package/src/providers/antigravity.js +2 -0
  20. package/src/providers/antigravity.ts +2 -0
  21. package/src/tools/memoryWrite.js +15 -1
  22. package/src/tools/memoryWrite.ts +16 -1
  23. package/src/tools/osSandbox.js +1 -1
  24. package/src/tools/osSandbox.ts +1 -1
  25. package/src/tools/ptyTerminal.js +17 -5
  26. package/src/tools/ptyTerminal.ts +19 -5
  27. package/src/web/client/browserPanel.js +234 -31
  28. package/src/web/client/browserPanel.ts +240 -31
  29. package/src/web/client/chatStream.js +19 -7
  30. package/src/web/client/chatStream.ts +17 -9
  31. package/src/web/client/cliPanel.js +3 -3
  32. package/src/web/client/cliPanel.ts +3 -3
  33. package/src/web/client/dom.js +53 -2
  34. package/src/web/client/dom.ts +54 -3
  35. package/src/web/client/filesAndCanvas.js +3 -1
  36. package/src/web/client/filesAndCanvas.ts +3 -1
  37. package/src/web/client/main.js +28 -13
  38. package/src/web/client/main.ts +35 -12
  39. package/src/web/client/settingsModal.js +641 -8
  40. package/src/web/client/settingsModal.ts +791 -8
  41. package/src/web/client/state.js +31 -1
  42. package/src/web/client/state.ts +27 -1
  43. package/src/web/client/studioLayout.js +39 -4
  44. package/src/web/client/studioLayout.ts +47 -4
  45. package/src/web/client/studioShell.js +370 -37
  46. package/src/web/client/studioShell.ts +368 -36
  47. package/src/web/client/terminalPanel.js +378 -129
  48. package/src/web/client/terminalPanel.ts +394 -107
  49. package/src/web/client/terminalTheme.js +249 -0
  50. package/src/web/client/terminalTheme.ts +258 -0
  51. package/src/web/client/types.ts +3 -0
  52. package/src/web/client/validators.js +51 -10
  53. package/src/web/client/validators.ts +54 -10
  54. package/src/web/server/routesBrowser.js +64 -10
  55. package/src/web/server/routesBrowser.ts +62 -13
  56. package/src/web/server/routesSettings.js +344 -0
  57. package/src/web/server/routesSettings.ts +397 -0
  58. package/src/web/server/staticAssets.js +24 -0
  59. package/src/web/server/staticAssets.ts +25 -0
  60. package/src/web/skybridgeServer.js +3 -0
  61. package/src/web/skybridgeServer.ts +2 -0
  62. package/src/web/skybridgeUi.js +5 -1
  63. package/src/web/skybridgeUi.ts +8 -1
  64. package/src/web/styles/overlays.css +499 -0
  65. package/src/web/styles/studio.css +274 -46
  66. package/src/web/ui/modalsTemplate.js +320 -71
  67. package/src/web/ui/modalsTemplate.ts +320 -71
  68. package/src/web/ui/studioTemplate.js +19 -21
  69. package/src/web/ui/studioTemplate.ts +19 -21
@@ -1,12 +1,17 @@
1
+ import type { IDisposable, ITerminalInitOnlyOptions, ITerminalOptions, Terminal } from '@xterm/xterm';
2
+ import type { FitAddon } from '@xterm/addon-fit';
1
3
  import { announceAlert, dom } from './dom.js';
2
4
  import { apiUrl, authHeaders, state } from './state.js';
3
5
  import { hydrateStartShellOptions } from './studioStart.js';
6
+ import { setStudioTabDynamicTitle } from './studioShell.js';
7
+ import { TerminalTheme, observeTerminalCursor } from './terminalTheme.js';
4
8
  import type { AvailableShellPayload, TerminalSessionPayload } from './types.js';
5
9
 
6
10
  interface TerminalStreamChunk {
7
11
  type?: string;
8
12
  sessionId?: string;
9
13
  data?: string;
14
+ rawData?: string;
10
15
  control?: 'user' | 'agent';
11
16
  status?: 'running' | 'exited';
12
17
  exitCode?: number | null;
@@ -14,12 +19,49 @@ interface TerminalStreamChunk {
14
19
  rows?: number;
15
20
  }
16
21
 
17
- const MAX_CLIENT_VIEWPORT_CHARS = 180_000;
18
- const cmdHistory: string[] = [];
19
- let historyIdx = -1;
22
+ type XtermCtor = new (options?: ITerminalOptions & ITerminalInitOnlyOptions) => Terminal;
23
+ type FitAddonCtor = new () => FitAddon;
24
+
25
+ interface XtermWindowGlobals {
26
+ Terminal?: XtermCtor;
27
+ FitAddon?: { FitAddon?: FitAddonCtor } | FitAddonCtor;
28
+ }
29
+
30
+ interface MountedTerminal {
31
+ sessionId: string;
32
+ hostEl: HTMLDivElement;
33
+ xterm: Terminal;
34
+ fitAddon: FitAddon;
35
+ palette: TerminalTheme;
36
+ cursorSub: IDisposable;
37
+ dataSub: IDisposable;
38
+ cleanupGestures: () => void;
39
+ lastSyncedCols: number;
40
+ lastSyncedRows: number;
41
+ resizeTimer: ReturnType<typeof setTimeout> | null;
42
+ pendingInput: Array<{ data: string; typed: boolean }>;
43
+ flushingInput: boolean;
44
+ }
45
+
46
+ const TYPED_INPUT_WINDOW_MS = 250;
47
+ const INPUT_GESTURES = ['keydown', 'beforeinput', 'paste', 'compositionend', 'drop', 'mousedown', 'touchstart'] as const;
48
+ const FOCUS_REPORTS = new Set(['\x1b[I', '\x1b[O']);
49
+ const TERMINAL_FONT_STACK = 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';
50
+
51
+ const mountedTerminals = new Map<string, MountedTerminal>();
52
+ let viewportResizeObserver: ResizeObserver | null = null;
53
+ let themeObserver: MutationObserver | null = null;
20
54
  let streamAbort: AbortController | null = null;
21
55
  let streamedSessionId: string | null = null;
22
56
 
57
+ function resolveXtermConstructors(): { TerminalCtor: XtermCtor; FitCtor: FitAddonCtor } | null {
58
+ const g = window as unknown as XtermWindowGlobals;
59
+ const TerminalCtor = g.Terminal;
60
+ const FitCtor = typeof g.FitAddon === 'function' ? g.FitAddon : g.FitAddon?.FitAddon;
61
+ if (typeof TerminalCtor !== 'function' || typeof FitCtor !== 'function') return null;
62
+ return { TerminalCtor, FitCtor };
63
+ }
64
+
23
65
  function stopTerminalStream(): void {
24
66
  if (streamAbort) {
25
67
  try { streamAbort.abort(); } catch { /* ignore */ }
@@ -33,11 +75,51 @@ function activeSession(): TerminalSessionPayload | null {
33
75
  return state.terminalSessions.find((s) => s.id === state.activeTerminalId) ?? null;
34
76
  }
35
77
 
78
+ function readViewportThemeColors(): { background: string; foreground: string; isLight: boolean } {
79
+ const isLight = document.documentElement.getAttribute('data-theme') === 'light';
80
+ const fallbackBg = isLight ? '#f6f8f6' : '#0d100d';
81
+ const fallbackFg = isLight ? '#182018' : '#e6ece4';
82
+ if (!dom.termViewport) return { background: fallbackBg, foreground: fallbackFg, isLight };
83
+ const style = window.getComputedStyle(dom.termViewport);
84
+ return {
85
+ background: style.backgroundColor || fallbackBg,
86
+ foreground: style.color || fallbackFg,
87
+ isLight
88
+ };
89
+ }
90
+
91
+ function applyThemeToAllMounted(): void {
92
+ const { background, foreground, isLight } = readViewportThemeColors();
93
+ for (const inst of mountedTerminals.values()) {
94
+ inst.palette.update(background, foreground, isLight);
95
+ }
96
+ }
97
+
98
+ function estimateInitialDimensions(): { cols: number; rows: number } {
99
+ const curMounted = state.activeTerminalId ? mountedTerminals.get(state.activeTerminalId) : undefined;
100
+ if (curMounted) {
101
+ const proposed = curMounted.fitAddon.proposeDimensions();
102
+ if (proposed && Number.isFinite(proposed.cols) && Number.isFinite(proposed.rows)) {
103
+ return {
104
+ cols: Math.max(20, Math.min(400, proposed.cols)),
105
+ rows: Math.max(6, Math.min(160, proposed.rows))
106
+ };
107
+ }
108
+ }
109
+ const rect = dom.termViewport?.getBoundingClientRect();
110
+ if (rect && rect.width > 120 && rect.height > 80) {
111
+ const cols = Math.max(20, Math.min(400, Math.floor((rect.width - 28) / 7.8)));
112
+ const rows = Math.max(6, Math.min(160, Math.floor((rect.height - 16) / 18)));
113
+ return { cols, rows };
114
+ }
115
+ return { cols: 88, rows: 26 };
116
+ }
117
+
36
118
  function syncTerminalChrome(): void {
37
119
  const cur = activeSession();
38
120
  const hasSession = Boolean(cur);
39
121
  if (dom.termEmpty) dom.termEmpty.style.display = hasSession ? 'none' : 'flex';
40
- if (dom.termViewport) dom.termViewport.style.display = hasSession ? 'block' : 'none';
122
+ if (dom.termViewport) dom.termViewport.style.display = hasSession ? 'flex' : 'none';
41
123
  if (dom.termControlBanner) {
42
124
  const showAgentBanner = Boolean(cur && cur.status === 'running' && cur.control === 'agent');
43
125
  dom.termControlBanner.classList.toggle('visible', showAgentBanner);
@@ -57,6 +139,210 @@ function syncTerminalChrome(): void {
57
139
  if (dom.termMeta) {
58
140
  dom.termMeta.textContent = cur ? `${cur.shellLabel} · ${cur.cols}×${cur.rows}` : '';
59
141
  }
142
+ setStudioTabDynamicTitle('terminal', cur ? cur.name : null);
143
+ }
144
+
145
+ function syncVisibleTerminalInstance(): void {
146
+ for (const [id, inst] of mountedTerminals) {
147
+ const isActive = id === state.activeTerminalId;
148
+ inst.hostEl.classList.toggle('active', isActive);
149
+ }
150
+ }
151
+
152
+ function scheduleRemoteResize(inst: MountedTerminal, cols: number, rows: number): void {
153
+ if (inst.lastSyncedCols === cols && inst.lastSyncedRows === rows) return;
154
+ const sess = state.terminalSessions.find((s) => s.id === inst.sessionId);
155
+ if (!sess || sess.status !== 'running') return;
156
+ if (inst.resizeTimer) clearTimeout(inst.resizeTimer);
157
+ inst.resizeTimer = setTimeout(() => {
158
+ inst.resizeTimer = null;
159
+ if (inst.lastSyncedCols === cols && inst.lastSyncedRows === rows) return;
160
+ inst.lastSyncedCols = cols;
161
+ inst.lastSyncedRows = rows;
162
+ sess.cols = cols;
163
+ sess.rows = rows;
164
+ if (state.activeTerminalId === inst.sessionId && dom.termMeta) {
165
+ dom.termMeta.textContent = `${sess.shellLabel} · ${cols}×${rows}`;
166
+ }
167
+ void fetch(apiUrl('/api/terminal/input'), {
168
+ method: 'POST',
169
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
170
+ body: JSON.stringify({ id: inst.sessionId, cols, rows })
171
+ }).catch(() => null);
172
+ }, 60);
173
+ }
174
+
175
+ function fitTerminalInstance(inst: MountedTerminal): void {
176
+ if (!dom.termViewport || !inst.hostEl.classList.contains('active')) return;
177
+ if (inst.hostEl.clientWidth < 40 || inst.hostEl.clientHeight < 30) return;
178
+ const dims = inst.fitAddon.proposeDimensions();
179
+ if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return;
180
+ const cols = Math.max(20, Math.min(400, dims.cols));
181
+ const rows = Math.max(6, Math.min(160, dims.rows));
182
+ if (inst.xterm.cols !== cols || inst.xterm.rows !== rows) {
183
+ inst.xterm.resize(cols, rows);
184
+ }
185
+ scheduleRemoteResize(inst, cols, rows);
186
+ }
187
+
188
+ export function fitActiveTerminal(): void {
189
+ if (!state.activeTerminalId) return;
190
+ const inst = mountedTerminals.get(state.activeTerminalId);
191
+ if (!inst) return;
192
+ requestAnimationFrame(() => {
193
+ fitTerminalInstance(inst);
194
+ });
195
+ }
196
+
197
+ export function focusActiveTerminal(): void {
198
+ if (!state.activeTerminalId) return;
199
+ const inst = mountedTerminals.get(state.activeTerminalId);
200
+ if (inst) inst.xterm.focus();
201
+ }
202
+
203
+ function flushInputQueue(inst: MountedTerminal): void {
204
+ if (inst.flushingInput || inst.pendingInput.length === 0) return;
205
+ inst.flushingInput = true;
206
+
207
+ void (async () => {
208
+ try {
209
+ while (inst.pendingInput.length > 0) {
210
+ const first = inst.pendingInput.shift()!;
211
+ let combined = first.data;
212
+ let typed = first.typed;
213
+ while (inst.pendingInput.length > 0 && inst.pendingInput[0]!.typed === typed) {
214
+ combined += inst.pendingInput.shift()!.data;
215
+ }
216
+ const res = await fetch(apiUrl('/api/terminal/input'), {
217
+ method: 'POST',
218
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
219
+ body: JSON.stringify({ id: inst.sessionId, data: combined, typed })
220
+ }).catch(() => null);
221
+ if (res && res.ok) {
222
+ const body = await res.json().catch(() => ({})) as { control?: 'user' | 'agent' };
223
+ const target = state.terminalSessions.find((s) => s.id === inst.sessionId);
224
+ if (target && body.control && target.control !== body.control) {
225
+ target.control = body.control;
226
+ syncTerminalChrome();
227
+ }
228
+ }
229
+ }
230
+ } finally {
231
+ inst.flushingInput = false;
232
+ }
233
+ })();
234
+ }
235
+
236
+ function enqueueTerminalInput(sessionId: string, data: string, typed: boolean): void {
237
+ const inst = mountedTerminals.get(sessionId);
238
+ if (!inst) return;
239
+ inst.pendingInput.push({ data, typed });
240
+ flushInputQueue(inst);
241
+ }
242
+
243
+ function disposeMountedTerminal(sessionId: string): void {
244
+ const inst = mountedTerminals.get(sessionId);
245
+ if (!inst) return;
246
+ if (inst.resizeTimer) clearTimeout(inst.resizeTimer);
247
+ inst.cleanupGestures();
248
+ inst.dataSub.dispose();
249
+ inst.cursorSub.dispose();
250
+ inst.palette.dispose();
251
+ inst.xterm.dispose();
252
+ inst.hostEl.remove();
253
+ mountedTerminals.delete(sessionId);
254
+ }
255
+
256
+ function ensureMountedTerminal(session: TerminalSessionPayload): MountedTerminal | null {
257
+ const existing = mountedTerminals.get(session.id);
258
+ if (existing) return existing;
259
+ if (!dom.termViewport) return null;
260
+ const ctors = resolveXtermConstructors();
261
+ if (!ctors) {
262
+ announceAlert('Terminal emulator assets failed to load.');
263
+ return null;
264
+ }
265
+
266
+ const hostEl = document.createElement('div');
267
+ hostEl.className = 'term-instance';
268
+ hostEl.dataset.sessionId = session.id;
269
+ if (session.id === state.activeTerminalId) hostEl.classList.add('active');
270
+ dom.termViewport.appendChild(hostEl);
271
+
272
+ const xterm = new ctors.TerminalCtor({
273
+ cols: Math.max(20, Math.min(400, session.cols || 88)),
274
+ rows: Math.max(6, Math.min(160, session.rows || 26)),
275
+ cursorBlink: true,
276
+ cursorStyle: 'block',
277
+ fontFamily: TERMINAL_FONT_STACK,
278
+ fontSize: 13,
279
+ lineHeight: 1.25,
280
+ minimumContrastRatio: 4.5,
281
+ scrollback: 5000,
282
+ convertEol: session.transport !== 'pty',
283
+ allowProposedApi: false
284
+ });
285
+ const fitAddon = new ctors.FitCtor();
286
+ xterm.loadAddon(fitAddon);
287
+ xterm.open(hostEl);
288
+ xterm.textarea?.setAttribute('aria-label', `${session.name} interactive terminal`);
289
+
290
+ const palette = new TerminalTheme(xterm);
291
+ const { background, foreground, isLight } = readViewportThemeColors();
292
+ palette.update(background, foreground, isLight);
293
+ const cursorSub = observeTerminalCursor(xterm, hostEl, () => palette.cursor);
294
+
295
+ // Copy on Ctrl+C / Cmd+C when text is selected instead of sending SIGINT; allow paste naturally
296
+ xterm.attachCustomKeyEventHandler((ev: KeyboardEvent) => {
297
+ const key = ev.key.toLowerCase();
298
+ if ((ev.metaKey || ev.ctrlKey) && key === 'c' && xterm.hasSelection()) {
299
+ if (ev.type === 'keydown' && navigator.clipboard?.writeText) {
300
+ void navigator.clipboard.writeText(xterm.getSelection()).catch(() => {});
301
+ }
302
+ return false;
303
+ }
304
+ if ((ev.metaKey || (ev.ctrlKey && ev.shiftKey)) && key === 'v') {
305
+ return false;
306
+ }
307
+ if (ev.ctrlKey && !ev.metaKey && !ev.altKey && ev.key === '`') {
308
+ return false;
309
+ }
310
+ return true;
311
+ });
312
+
313
+ let gestureAt = Number.NEGATIVE_INFINITY;
314
+ const markGesture = (): void => { gestureAt = performance.now(); };
315
+ for (const type of INPUT_GESTURES) {
316
+ hostEl.addEventListener(type, markGesture, { capture: true, passive: true });
317
+ }
318
+ const cleanupGestures = (): void => {
319
+ for (const type of INPUT_GESTURES) {
320
+ hostEl.removeEventListener(type, markGesture, { capture: true });
321
+ }
322
+ };
323
+
324
+ const dataSub = xterm.onData((data) => {
325
+ const isTyped = (performance.now() - gestureAt < TYPED_INPUT_WINDOW_MS) && !FOCUS_REPORTS.has(data);
326
+ enqueueTerminalInput(session.id, data, isTyped);
327
+ });
328
+
329
+ const inst: MountedTerminal = {
330
+ sessionId: session.id,
331
+ hostEl,
332
+ xterm,
333
+ fitAddon,
334
+ palette,
335
+ cursorSub,
336
+ dataSub,
337
+ cleanupGestures,
338
+ lastSyncedCols: session.cols,
339
+ lastSyncedRows: session.rows,
340
+ resizeTimer: null,
341
+ pendingInput: [],
342
+ flushingInput: false
343
+ };
344
+ mountedTerminals.set(session.id, inst);
345
+ return inst;
60
346
  }
61
347
 
62
348
  function renderTerminalTabs(): void {
@@ -65,6 +351,12 @@ function renderTerminalTabs(): void {
65
351
  for (const sess of state.terminalSessions) {
66
352
  const pill = document.createElement('div');
67
353
  pill.className = `btab${sess.id === state.activeTerminalId ? ' active' : ''}`;
354
+ pill.addEventListener('auxclick', (e) => {
355
+ if (e.button === 1) {
356
+ e.preventDefault();
357
+ void closeTerminalSession(sess.id);
358
+ }
359
+ });
68
360
  const lbl = document.createElement('button');
69
361
  lbl.type = 'button';
70
362
  lbl.className = 'btab-label';
@@ -75,6 +367,7 @@ function renderTerminalTabs(): void {
75
367
  cls.className = 'btab-close';
76
368
  cls.textContent = '×';
77
369
  cls.title = 'Close terminal';
370
+ cls.setAttribute('aria-label', `Close ${sess.name}`);
78
371
  cls.addEventListener('click', () => { void closeTerminalSession(sess.id); });
79
372
  pill.appendChild(lbl);
80
373
  pill.appendChild(cls);
@@ -82,20 +375,20 @@ function renderTerminalTabs(): void {
82
375
  }
83
376
  dom.termTabs.appendChild(dom.termNewBtn);
84
377
  syncTerminalChrome();
85
- }
86
-
87
- function appendViewportText(chunk: string, replace = false): void {
88
- if (!dom.termViewport) return;
89
- const next = replace ? chunk : ((dom.termViewport.textContent || '') + chunk);
90
- dom.termViewport.textContent = next.length > MAX_CLIENT_VIEWPORT_CHARS
91
- ? next.slice(next.length - MAX_CLIENT_VIEWPORT_CHARS)
92
- : next;
93
- dom.termViewport.scrollTop = dom.termViewport.scrollHeight;
378
+ syncVisibleTerminalInstance();
94
379
  }
95
380
 
96
381
  function startTerminalStream(sessionId: string): void {
97
382
  if (streamedSessionId === sessionId && streamAbort) return;
98
383
  stopTerminalStream();
384
+ const sess = state.terminalSessions.find((s) => s.id === sessionId);
385
+ if (!sess) return;
386
+ const inst = ensureMountedTerminal(sess);
387
+ syncVisibleTerminalInstance();
388
+ if (inst) {
389
+ requestAnimationFrame(() => fitTerminalInstance(inst));
390
+ }
391
+
99
392
  const ctrl = new AbortController();
100
393
  streamAbort = ctrl;
101
394
  streamedSessionId = sessionId;
@@ -122,20 +415,35 @@ function startTerminalStream(sessionId: string): void {
122
415
  try {
123
416
  const ev = JSON.parse(line) as TerminalStreamChunk;
124
417
  const target = state.terminalSessions.find((s) => s.id === sessionId);
418
+ const mounted = mountedTerminals.get(sessionId);
125
419
  if (ev.type === 'snapshot') {
126
- if (sessionId === state.activeTerminalId) {
127
- appendViewportText(ev.data || '', true);
128
- }
129
420
  if (target) {
130
421
  if (ev.control) target.control = ev.control;
131
422
  if (ev.status) target.status = ev.status;
132
423
  if (ev.exitCode !== undefined) target.exitCode = ev.exitCode;
424
+ if (typeof ev.cols === 'number') target.cols = ev.cols;
425
+ if (typeof ev.rows === 'number') target.rows = ev.rows;
426
+ }
427
+ if (mounted) {
428
+ mounted.xterm.reset();
429
+ const payload = typeof ev.rawData === 'string' ? ev.rawData : (ev.data || '');
430
+ if (payload) mounted.xterm.write(payload);
431
+ requestAnimationFrame(() => fitTerminalInstance(mounted));
133
432
  }
134
433
  syncTerminalChrome();
135
- } else if (ev.type === 'output' && typeof ev.data === 'string') {
136
- if (sessionId === state.activeTerminalId) {
137
- appendViewportText(ev.data, false);
434
+ } else if (ev.type === 'output') {
435
+ const payload = typeof ev.rawData === 'string' ? ev.rawData : (ev.data || '');
436
+ if (mounted && payload) {
437
+ mounted.xterm.write(payload);
438
+ }
439
+ } else if (ev.type === 'meta') {
440
+ if (target) {
441
+ if (typeof ev.cols === 'number') target.cols = ev.cols;
442
+ if (typeof ev.rows === 'number') target.rows = ev.rows;
443
+ if (ev.control) target.control = ev.control;
444
+ if (ev.status) target.status = ev.status;
138
445
  }
446
+ syncTerminalChrome();
139
447
  } else if (ev.type === 'control' && ev.control) {
140
448
  if (target) target.control = ev.control;
141
449
  syncTerminalChrome();
@@ -144,13 +452,13 @@ function startTerminalStream(sessionId: string): void {
144
452
  target.status = 'exited';
145
453
  target.exitCode = ev.exitCode ?? 0;
146
454
  }
147
- if (sessionId === state.activeTerminalId) {
148
- appendViewportText(`\n[process exited with code ${ev.exitCode ?? 0}]\n`, false);
455
+ if (mounted) {
456
+ mounted.xterm.write(`\r\n\x1b[2m[process exited with code ${ev.exitCode ?? 0}]\x1b[0m\r\n`);
149
457
  }
150
458
  renderTerminalTabs();
151
459
  }
152
460
  } catch {
153
- // Ignore malformed line
461
+ // Ignore malformed stream line
154
462
  }
155
463
  }
156
464
  nl = buf.indexOf('\n');
@@ -169,8 +477,12 @@ function startTerminalStream(sessionId: string): void {
169
477
 
170
478
  export function selectTerminalSession(sessionId: string): void {
171
479
  state.activeTerminalId = sessionId;
480
+ const sess = activeSession();
481
+ if (sess) ensureMountedTerminal(sess);
172
482
  renderTerminalTabs();
173
483
  startTerminalStream(sessionId);
484
+ fitActiveTerminal();
485
+ focusActiveTerminal();
174
486
  }
175
487
 
176
488
  export async function loadTerminalSessions(): Promise<void> {
@@ -184,26 +496,35 @@ export async function loadTerminalSessions(): Promise<void> {
184
496
  state.availableShells = data.shells;
185
497
  hydrateStartShellOptions(data.shells);
186
498
  }
187
- state.terminalSessions = Array.isArray(data.sessions) ? data.sessions : [];
188
- if (state.activeTerminalId && !state.terminalSessions.some((s) => s.id === state.activeTerminalId)) {
499
+ const incoming = Array.isArray(data.sessions) ? data.sessions : [];
500
+ const validIds = new Set(incoming.map((s) => s.id));
501
+ for (const id of [...mountedTerminals.keys()]) {
502
+ if (!validIds.has(id)) disposeMountedTerminal(id);
503
+ }
504
+ state.terminalSessions = incoming;
505
+ if (state.activeTerminalId && !validIds.has(state.activeTerminalId)) {
189
506
  state.activeTerminalId = null;
190
507
  stopTerminalStream();
191
508
  }
192
509
  if (!state.activeTerminalId && state.terminalSessions.length > 0) {
193
510
  state.activeTerminalId = state.terminalSessions[0]!.id;
194
511
  }
512
+ const cur = activeSession();
513
+ if (cur) ensureMountedTerminal(cur);
195
514
  renderTerminalTabs();
196
515
  if (state.activeTerminalId) {
197
516
  startTerminalStream(state.activeTerminalId);
517
+ fitActiveTerminal();
198
518
  }
199
519
  }
200
520
 
201
521
  export async function openNewTerminalSession(shell?: string): Promise<void> {
202
522
  const chosenShell = shell || dom.termShellSelect?.value || dom.startShellSelect?.value || undefined;
523
+ const { cols, rows } = estimateInitialDimensions();
203
524
  const res = await fetch(apiUrl('/api/terminal/sessions'), {
204
525
  method: 'POST',
205
526
  headers: authHeaders({ 'Content-Type': 'application/json' }),
206
- body: JSON.stringify({ shell: chosenShell, cols: 100, rows: 28 })
527
+ body: JSON.stringify({ shell: chosenShell, cols, rows })
207
528
  }).catch(() => null);
208
529
  if (!res) { announceAlert('Failed to open workspace terminal.'); return; }
209
530
  const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` })) as {
@@ -217,7 +538,6 @@ export async function openNewTerminalSession(shell?: string): Promise<void> {
217
538
  }
218
539
  state.terminalSessions.push(data.session);
219
540
  selectTerminalSession(data.session.id);
220
- dom.termInput?.focus();
221
541
  }
222
542
 
223
543
  export async function closeTerminalSession(sessionId: string): Promise<void> {
@@ -225,35 +545,32 @@ export async function closeTerminalSession(sessionId: string): Promise<void> {
225
545
  method: 'DELETE',
226
546
  headers: authHeaders()
227
547
  }).catch(() => null);
548
+ disposeMountedTerminal(sessionId);
228
549
  state.terminalSessions = state.terminalSessions.filter((s) => s.id !== sessionId);
229
550
  if (state.activeTerminalId === sessionId) {
230
551
  stopTerminalStream();
231
552
  state.activeTerminalId = state.terminalSessions[0]?.id ?? null;
232
- if (dom.termViewport && !state.activeTerminalId) dom.termViewport.textContent = '';
233
553
  }
234
554
  renderTerminalTabs();
235
- if (state.activeTerminalId) startTerminalStream(state.activeTerminalId);
555
+ if (state.activeTerminalId) {
556
+ startTerminalStream(state.activeTerminalId);
557
+ fitActiveTerminal();
558
+ }
236
559
  }
237
560
 
238
- async function sendTerminalData(data: string, typed = true): Promise<void> {
239
- if (!state.activeTerminalId) {
240
- await openNewTerminalSession();
241
- }
242
- const id = state.activeTerminalId;
243
- if (!id) return;
244
- const res = await fetch(apiUrl('/api/terminal/input'), {
245
- method: 'POST',
246
- headers: authHeaders({ 'Content-Type': 'application/json' }),
247
- body: JSON.stringify({ id, data, typed })
248
- }).catch(() => null);
249
- if (res && res.ok) {
250
- const body = await res.json().catch(() => ({})) as { control?: 'user' | 'agent' };
251
- const cur = activeSession();
252
- if (cur && body.control) {
253
- cur.control = body.control;
254
- syncTerminalChrome();
255
- }
561
+ export async function closeAllTerminalSessions(): Promise<void> {
562
+ const ids = state.terminalSessions.map((s) => s.id);
563
+ stopTerminalStream();
564
+ for (const id of ids) {
565
+ disposeMountedTerminal(id);
566
+ await fetch(apiUrl(`/api/terminal/sessions/${encodeURIComponent(id)}`), {
567
+ method: 'DELETE',
568
+ headers: authHeaders()
569
+ }).catch(() => null);
256
570
  }
571
+ state.terminalSessions = [];
572
+ state.activeTerminalId = null;
573
+ renderTerminalTabs();
257
574
  }
258
575
 
259
576
  async function sendTerminalSignal(signal: 'SIGINT' | 'SIGTERM' | 'SIGTSTP'): Promise<void> {
@@ -273,73 +590,43 @@ export function deactivateTerminalPanel(): void {
273
590
  export function bindTerminalPanelEvents(): void {
274
591
  dom.termNewBtn?.addEventListener('click', () => { void openNewTerminalSession(); });
275
592
  dom.termEmptyStartBtn?.addEventListener('click', () => { void openNewTerminalSession(); });
276
- dom.termSigintBtn?.addEventListener('click', () => { void sendTerminalSignal('SIGINT'); });
593
+ dom.termSigintBtn?.addEventListener('click', () => {
594
+ void sendTerminalSignal('SIGINT');
595
+ focusActiveTerminal();
596
+ });
277
597
  dom.termClearBtn?.addEventListener('click', () => {
278
- if (dom.termViewport) dom.termViewport.textContent = '';
598
+ if (!state.activeTerminalId) return;
599
+ const inst = mountedTerminals.get(state.activeTerminalId);
600
+ if (inst) {
601
+ inst.xterm.clear();
602
+ inst.xterm.focus();
603
+ }
279
604
  });
280
605
  dom.termTakeControlBtn?.addEventListener('click', () => {
281
- void sendTerminalData('', true);
282
- dom.termInput?.focus();
606
+ if (!state.activeTerminalId) return;
607
+ enqueueTerminalInput(state.activeTerminalId, '', true);
608
+ focusActiveTerminal();
283
609
  });
284
610
 
285
- const submitCommandLine = (): void => {
286
- if (!dom.termInput) return;
287
- const line = dom.termInput.value;
288
- if (line.trim()) {
289
- cmdHistory.push(line);
290
- if (cmdHistory.length > 100) cmdHistory.shift();
291
- historyIdx = cmdHistory.length;
292
- }
293
- dom.termInput.value = '';
294
- void sendTerminalData(`${line}\n`, true);
295
- };
611
+ if (dom.termViewport && typeof ResizeObserver !== 'undefined') {
612
+ viewportResizeObserver = new ResizeObserver(() => {
613
+ if (!state.activeTerminalId) return;
614
+ const inst = mountedTerminals.get(state.activeTerminalId);
615
+ if (inst) fitTerminalInstance(inst);
616
+ });
617
+ viewportResizeObserver.observe(dom.termViewport);
618
+ }
296
619
 
297
- dom.termSendBtn?.addEventListener('click', submitCommandLine);
298
- dom.termInput?.addEventListener('keydown', (e) => {
299
- if (e.key === 'Enter') {
300
- e.preventDefault();
301
- submitCommandLine();
302
- } else if (e.ctrlKey && e.key.toLowerCase() === 'c') {
303
- e.preventDefault();
304
- void sendTerminalSignal('SIGINT');
305
- } else if (e.key === 'ArrowUp' && cmdHistory.length > 0) {
306
- e.preventDefault();
307
- historyIdx = Math.max(0, (historyIdx < 0 ? cmdHistory.length : historyIdx) - 1);
308
- if (dom.termInput) dom.termInput.value = cmdHistory[historyIdx] ?? '';
309
- } else if (e.key === 'ArrowDown' && cmdHistory.length > 0) {
310
- e.preventDefault();
311
- historyIdx = Math.min(cmdHistory.length, historyIdx + 1);
312
- if (dom.termInput) dom.termInput.value = cmdHistory[historyIdx] ?? '';
313
- }
314
- });
620
+ if (typeof MutationObserver !== 'undefined') {
621
+ themeObserver = new MutationObserver(() => {
622
+ applyThemeToAllMounted();
623
+ });
624
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
625
+ }
315
626
 
316
- // Direct interactive keyboard forwarding when viewport itself is focused
317
- dom.termViewport?.addEventListener('keydown', (e) => {
318
- if (!state.activeTerminalId) return;
319
- if (e.metaKey) return;
320
- if (e.ctrlKey && e.key.toLowerCase() === 'c') {
321
- e.preventDefault();
322
- void sendTerminalSignal('SIGINT');
323
- return;
324
- }
325
- if (e.ctrlKey && e.key.toLowerCase() === 'd') {
326
- e.preventDefault();
327
- void sendTerminalData('\x04', true);
328
- return;
329
- }
330
- if (e.ctrlKey && e.key.toLowerCase() === 'l') {
331
- e.preventDefault();
332
- if (dom.termViewport) dom.termViewport.textContent = '';
333
- return;
334
- }
335
- if (e.key === 'Enter') { e.preventDefault(); void sendTerminalData('\n', true); return; }
336
- if (e.key === 'Backspace') { e.preventDefault(); void sendTerminalData('\x7f', true); return; }
337
- if (e.key === 'Tab') { e.preventDefault(); void sendTerminalData('\t', true); return; }
338
- if (e.key.length === 1 && !e.ctrlKey && !e.altKey) {
339
- e.preventDefault();
340
- void sendTerminalData(e.key, true);
341
- }
627
+ window.addEventListener('beforeunload', () => {
628
+ stopTerminalStream();
629
+ viewportResizeObserver?.disconnect();
630
+ themeObserver?.disconnect();
342
631
  });
343
-
344
- window.addEventListener('beforeunload', stopTerminalStream);
345
632
  }