@bakapiano/ccsm 0.10.3 → 0.11.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.
Files changed (48) hide show
  1. package/CLAUDE.md +475 -475
  2. package/README.md +190 -190
  3. package/bin/ccsm.js +194 -194
  4. package/lib/cliSessionWatcher.js +249 -249
  5. package/lib/config.js +185 -185
  6. package/lib/folders.js +96 -96
  7. package/lib/localCliSessions.js +489 -177
  8. package/lib/persistedSessions.js +134 -134
  9. package/lib/webTerminal.js +208 -208
  10. package/lib/workspace.js +230 -255
  11. package/package.json +57 -57
  12. package/public/css/base.css +99 -99
  13. package/public/css/cards.css +183 -183
  14. package/public/css/feedback.css +303 -303
  15. package/public/css/forms.css +405 -405
  16. package/public/css/layout.css +160 -160
  17. package/public/css/modal.css +190 -183
  18. package/public/css/responsive.css +10 -10
  19. package/public/css/sidebar.css +616 -601
  20. package/public/css/terminals.css +294 -294
  21. package/public/css/tokens.css +81 -79
  22. package/public/css/wco.css +98 -98
  23. package/public/css/widgets.css +1596 -1375
  24. package/public/index.html +105 -103
  25. package/public/js/api.js +272 -260
  26. package/public/js/components/AdoptModal.js +343 -171
  27. package/public/js/components/App.js +35 -35
  28. package/public/js/components/DirectoryPicker.js +203 -203
  29. package/public/js/components/EntityFormModal.js +105 -105
  30. package/public/js/components/Modal.js +51 -51
  31. package/public/js/components/OfflineBanner.js +93 -93
  32. package/public/js/components/PageTitleBar.js +13 -13
  33. package/public/js/components/Picker.js +179 -179
  34. package/public/js/components/Popover.js +55 -55
  35. package/public/js/components/Sidebar.js +270 -270
  36. package/public/js/components/TerminalView.js +298 -298
  37. package/public/js/components/useDragSort.js +67 -67
  38. package/public/js/dialog.js +67 -67
  39. package/public/js/icons.js +177 -177
  40. package/public/js/main.js +140 -140
  41. package/public/js/pages/AboutPage.js +165 -165
  42. package/public/js/pages/ConfigurePage.js +475 -487
  43. package/public/js/pages/LaunchPage.js +369 -369
  44. package/public/js/pages/SessionsPage.js +97 -97
  45. package/public/js/state.js +231 -231
  46. package/public/manifest.webmanifest +15 -15
  47. package/scripts/install.js +137 -137
  48. package/server.js +1126 -1117
@@ -1,298 +1,298 @@
1
- // xterm.js wrapper. Mounts a terminal into a ref'd div, opens a WebSocket
2
- // to /ws/terminal/<id>, forwards keystrokes/resize as JSON frames, renders
3
- // output frames into xterm. Disposes everything on unmount or id change.
4
-
5
- import { html } from '../html.js';
6
- import { useEffect, useRef } from 'preact/hooks';
7
- import { Terminal } from '@xterm/xterm';
8
- import { FitAddon } from '@xterm/addon-fit';
9
- import { WebLinksAddon } from '@xterm/addon-web-links';
10
- import { ClipboardAddon } from '@xterm/addon-clipboard';
11
- import { WebglAddon } from '@xterm/addon-webgl';
12
- import { wsBase } from '../backend.js';
13
-
14
- // Dark xterm theme. We give the terminal a near-black ink background to
15
- // match what claude code's TUI assumes (it paints its own input box +
16
- // prompt with hardcoded dark backgrounds — a light terminal makes those
17
- // regions look like black blocks). Cursor uses the favorite-star gold so
18
- // it pops against the ink without dragging brand orange back in.
19
- const THEME = {
20
- background: '#1a1815',
21
- foreground: '#e8e3d5',
22
- cursor: '#e3b341',
23
- cursorAccent: '#1a1815',
24
- selectionBackground: '#3a3530',
25
- black: '#1a1815', brightBlack: '#534e44',
26
- red: '#e07b6e', brightRed: '#f0a098',
27
- green: '#7fb670', brightGreen: '#a0d28f',
28
- yellow: '#e3b341', brightYellow: '#f0c860',
29
- blue: '#7d9fc4', brightBlue: '#9bb8d8',
30
- magenta: '#c08fd0', brightMagenta: '#d8aae2',
31
- cyan: '#6fb0b0', brightCyan: '#90c8c8',
32
- white: '#e8e3d5', brightWhite: '#faf9f5',
33
- };
34
-
35
- export function TerminalView({ terminalId }) {
36
- const hostRef = useRef(null);
37
- const termRef = useRef(null);
38
- const wsRef = useRef(null);
39
-
40
- useEffect(() => {
41
- if (!terminalId || !hostRef.current) return;
42
-
43
- const term = new Terminal({
44
- fontFamily: '"Cascadia Mono", "Geist Mono", "JetBrains Mono", Consolas, monospace',
45
- fontSize: 13,
46
- lineHeight: 1.2,
47
- cursorBlink: true,
48
- cursorStyle: 'bar',
49
- scrollback: 5000,
50
- allowProposedApi: true,
51
- theme: THEME,
52
- // Modern keyboard protocols. Without these, xterm.js encodes
53
- // Shift+Enter, Ctrl+Enter, Ctrl+Shift+key etc. the same as their
54
- // unmodified versions (e.g. both Enter and Shift+Enter send \r),
55
- // so TUIs like claude code can't tell them apart.
56
- //
57
- // - kittyKeyboard: opt-in protocol that apps enable per-session;
58
- // xterm emits CSI u sequences that uniquely encode every modifier
59
- // combo. Claude / vim / fish recognise it.
60
- // - win32InputMode: ConPTY-specific protocol that surfaces raw
61
- // Win32 KEY_EVENT_RECORD to the child process, again preserving
62
- // modifier info. Required for full key fidelity on Windows.
63
- // (Same set VSCode enables — see vscode/src/.../xtermTerminal.ts)
64
- vtExtensions: {
65
- kittyKeyboard: true,
66
- win32InputMode: true,
67
- },
68
- });
69
- const fit = new FitAddon();
70
- term.loadAddon(fit);
71
- term.loadAddon(new WebLinksAddon());
72
- // OSC 52 clipboard integration. Lets TUI apps initiate clipboard reads/
73
- // writes via escape sequences (e.g. `tmux set-buffer` or claude code
74
- // saying "copied to clipboard"). Does NOT handle the browser-side
75
- // Ctrl+V — that's still our document-level paste handler below.
76
- term.loadAddon(new ClipboardAddon());
77
- // WebGL renderer for performance. The default DOM renderer struggles
78
- // when claude code produces dense color output (its diff panels,
79
- // syntax-highlighted code). WebGL paints onto a canvas, much smoother
80
- // at thousands-of-cells per frame. Falls back to DOM if WebGL is
81
- // unavailable (e.g. older GPU, hardware accel disabled).
82
- try {
83
- const webgl = new WebglAddon();
84
- webgl.onContextLoss(() => { try { webgl.dispose(); } catch {} });
85
- term.loadAddon(webgl);
86
- } catch (e) {
87
- console.warn('[ccsm] WebGL addon failed, using DOM renderer:', e);
88
- }
89
- const host = hostRef.current;
90
- term.open(host);
91
- // Defer fit one tick so the container has measured layout
92
- requestAnimationFrame(() => { try { fit.fit(); } catch {} });
93
- termRef.current = term;
94
-
95
- const ws = new WebSocket(`${wsBase()}/ws/terminal/${encodeURIComponent(terminalId)}`);
96
- ws.binaryType = 'arraybuffer';
97
- wsRef.current = ws;
98
-
99
- ws.onopen = () => {
100
- // tell server the initial size (cols/rows after fit)
101
- ws.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }));
102
- };
103
- ws.onmessage = (ev) => {
104
- let frame;
105
- try { frame = JSON.parse(ev.data); } catch { return; }
106
- if (frame.type === 'output') {
107
- term.write(frame.data);
108
- } else if (frame.type === 'exit') {
109
- term.write(`\r\n\x1b[2m[process exited · code ${frame.code}]\x1b[0m\r\n`);
110
- }
111
- };
112
- ws.onclose = () => {
113
- term.write('\r\n\x1b[2m[disconnected]\x1b[0m\r\n');
114
- };
115
-
116
- const onData = (data) => {
117
- if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'input', data }));
118
- };
119
- const onResize = ({ cols, rows }) => {
120
- if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'resize', cols, rows }));
121
- };
122
- term.onData(onData);
123
- term.onResize(onResize);
124
-
125
- const ro = new ResizeObserver(() => { try { fit.fit(); } catch {} });
126
- ro.observe(hostRef.current);
127
-
128
- // Tab-switch refresh. The terminal lives inside a .tab-panel which gets
129
- // display:none when another tab is active. WebGL renderers keep a glyph
130
- // texture atlas in GPU memory; when the canvas hides + redisplays at a
131
- // potentially different devicePixelRatio, the atlas isn't invalidated
132
- // and old glyphs blend with newly-rasterized ones — visible as scrolling
133
- // text ghosting / double-strikes. Watching the tab-panel's data-active
134
- // attribute and clearing the atlas + re-fitting + forcing a full
135
- // refresh wipes the cache cleanly.
136
- const panel = host.closest('.tab-panel');
137
- let panelMo = null;
138
- if (panel) {
139
- panelMo = new MutationObserver(() => {
140
- if (panel.hasAttribute('data-active')) {
141
- requestAnimationFrame(() => {
142
- try { term.clearTextureAtlas?.(); } catch {}
143
- try { fit.fit(); } catch {}
144
- try { term.refresh(0, term.rows - 1); } catch {}
145
- });
146
- }
147
- });
148
- panelMo.observe(panel, { attributes: true, attributeFilter: ['data-active'] });
149
- }
150
-
151
- // give focus to terminal so user can type immediately
152
- term.focus();
153
-
154
- // Explicit paste handler. xterm.js relies on the browser routing paste
155
- // events to its hidden .xterm-helper-textarea, which only works if that
156
- // textarea has focus at the moment of Ctrl+V. When the user clicks
157
- // elsewhere then hits Ctrl+V over the terminal, or pastes via the
158
- // right-click menu on the host div, the event lands on the host and
159
- // xterm never sees it. Catch it here and route through term.paste()
160
- // so xterm wraps the text in bracketed-paste markers when the app
161
- // (claude code) has DECSET 2004 enabled — that's what makes claude
162
- // show the "[Pasted text]" affordance instead of treating it as
163
- // typed input.
164
- const isOurs = () => {
165
- const ae = document.activeElement;
166
- return ae && host.contains(ae);
167
- };
168
- const doPaste = (text) => {
169
- if (!text) return;
170
- if (ws.readyState !== 1) return;
171
- // Normalize line endings to \r (CR / Enter). This mirrors VSCode's
172
- // terminal sendText path (terminalInstance.ts ~L1385):
173
- // text = text.replace(/\r?\n/g, '\r');
174
- // Bracketed-paste markers protect each \r from being interpreted
175
- // as a submit by the host app — claude / pwsh / vim all treat
176
- // bracketed contents as opaque payload regardless of what's inside.
177
- // Use \n instead and you trip apps that look for "real" line breaks.
178
- const normalized = text.replace(/\r?\n/g, '\r');
179
- // Wrap in bracketed-paste markers. Claude Code enables DECSET 2004
180
- // on startup, so the markers let it detect a paste and render
181
- // "[Pasted text]". If the host app doesn't have bracketed paste on,
182
- // it just sees two ignored escape sequences plus the text.
183
- const wrapped = `\x1b[200~${normalized}\x1b[201~`;
184
- ws.send(JSON.stringify({ type: 'input', data: wrapped }));
185
- };
186
- const onPaste = async (ev) => {
187
- if (!isOurs()) return;
188
- let text = '';
189
- if (ev.clipboardData) text = ev.clipboardData.getData('text');
190
- if (!text && navigator.clipboard) {
191
- try { text = await navigator.clipboard.readText(); } catch {}
192
- }
193
- if (!text) return;
194
- ev.preventDefault();
195
- ev.stopPropagation();
196
- doPaste(text);
197
- };
198
- document.addEventListener('paste', onPaste, true);
199
-
200
- // Ctrl/Cmd+V fallback for cases the paste event is suppressed (some
201
- // extensions, or when our IME workaround moved the helper textarea
202
- // off-screen and the browser refuses to fire paste on it).
203
- // IMPORTANT: preventDefault must happen synchronously, BEFORE the
204
- // await on navigator.clipboard.readText(). If we let the event tick
205
- // run first, xterm's keystroke handler converts Ctrl+V into the raw
206
- // ^V (0x16) control byte and ships it before our async paste even
207
- // resolves.
208
- const onKey = (ev) => {
209
- const meta = ev.ctrlKey || ev.metaKey;
210
- if (!meta || ev.key.toLowerCase() !== 'v') return;
211
- if (ev.shiftKey || ev.altKey) return;
212
- if (!isOurs()) return;
213
- if (!navigator.clipboard?.readText) return;
214
- ev.preventDefault();
215
- ev.stopPropagation();
216
- ev.stopImmediatePropagation();
217
- navigator.clipboard.readText().then((text) => {
218
- if (text) doPaste(text);
219
- }).catch(() => {});
220
- };
221
- document.addEventListener('keydown', onKey, true);
222
-
223
- // Shift+Enter / Ctrl+Enter → insert literal newline, don't submit.
224
- // Background: xterm.js encodes BOTH plain Enter and Shift+Enter and
225
- // Ctrl+Enter as \r (0x0D / CR). The kitty keyboard / win32 input
226
- // protocols (enabled in vtExtensions above) WOULD distinguish them,
227
- // but they're opt-in by the running app — claude code doesn't enable
228
- // either, so we never get the distinction "for free".
229
- //
230
- // Send the LF (0x0A) explicitly. Claude code (and most modern TUIs)
231
- // treat \n inside a prompt as a literal newline insert, \r as submit.
232
- // Alt+Enter already works (xterm sends \x1b\r → meta-enter) so we
233
- // leave that alone.
234
- const onShiftEnter = (ev) => {
235
- if (ev.key !== 'Enter') return;
236
- if (!(ev.shiftKey || ev.ctrlKey)) return;
237
- if (ev.metaKey || ev.altKey) return;
238
- if (!isOurs()) return;
239
- ev.preventDefault();
240
- ev.stopPropagation();
241
- ev.stopImmediatePropagation();
242
- if (ws.readyState === 1) {
243
- ws.send(JSON.stringify({ type: 'input', data: '\n' }));
244
- }
245
- };
246
- document.addEventListener('keydown', onShiftEnter, true);
247
-
248
- // IME fix: xterm positions .xterm-helper-textarea via `left: <col-px>`
249
- // following the cursor. When the cursor is near the right edge and the
250
- // user starts composing (e.g. Chinese pinyin), the textarea + native
251
- // composition popup grow with the composed string and overflow the
252
- // terminal host — which visually pushes the layout right. We can't cap
253
- // width / change wrapping (that breaks Chromium's IME event flow), but
254
- // we CAN re-anchor the textarea to the right edge while composing so
255
- // it grows leftward instead. Toggling a class on the host is enough;
256
- // the CSS in terminals.css does the rest.
257
- const onCompStart = () => {
258
- if (host) host.classList.add('is-composing');
259
- // The terminal cursor is rendered on canvas (THEME.cursor), so CSS
260
- // can't hide it. Theme swap alone doesn't reliably stop the blink
261
- // frame loop, so also issue the DECTCEM hide sequence which the
262
- // renderer honours immediately.
263
- try { term.options.theme = { ...THEME, cursor: 'transparent', cursorAccent: 'transparent' }; } catch {}
264
- try { term.write('\x1b[?25l'); } catch {}
265
- };
266
- const onCompEnd = () => {
267
- if (host) host.classList.remove('is-composing');
268
- try { term.options.theme = THEME; } catch {}
269
- try { term.write('\x1b[?25h'); } catch {}
270
- };
271
- const helper = host?.querySelector('.xterm-helper-textarea');
272
- if (helper) {
273
- helper.addEventListener('compositionstart', onCompStart);
274
- helper.addEventListener('compositionend', onCompEnd);
275
- }
276
-
277
- return () => {
278
- document.removeEventListener('paste', onPaste, true);
279
- document.removeEventListener('keydown', onKey, true);
280
- document.removeEventListener('keydown', onShiftEnter, true);
281
- if (helper) {
282
- helper.removeEventListener('compositionstart', onCompStart);
283
- helper.removeEventListener('compositionend', onCompEnd);
284
- }
285
- ro.disconnect();
286
- if (panelMo) panelMo.disconnect();
287
- try { ws.close(); } catch {}
288
- try { term.dispose(); } catch {}
289
- termRef.current = null;
290
- wsRef.current = null;
291
- };
292
- }, [terminalId]);
293
-
294
- if (!terminalId) {
295
- return html`<div class="terminal-empty">Select a terminal on the left, or launch a new one.</div>`;
296
- }
297
- return html`<div ref=${hostRef} class="terminal-host"></div>`;
298
- }
1
+ // xterm.js wrapper. Mounts a terminal into a ref'd div, opens a WebSocket
2
+ // to /ws/terminal/<id>, forwards keystrokes/resize as JSON frames, renders
3
+ // output frames into xterm. Disposes everything on unmount or id change.
4
+
5
+ import { html } from '../html.js';
6
+ import { useEffect, useRef } from 'preact/hooks';
7
+ import { Terminal } from '@xterm/xterm';
8
+ import { FitAddon } from '@xterm/addon-fit';
9
+ import { WebLinksAddon } from '@xterm/addon-web-links';
10
+ import { ClipboardAddon } from '@xterm/addon-clipboard';
11
+ import { WebglAddon } from '@xterm/addon-webgl';
12
+ import { wsBase } from '../backend.js';
13
+
14
+ // Dark xterm theme. We give the terminal a near-black ink background to
15
+ // match what claude code's TUI assumes (it paints its own input box +
16
+ // prompt with hardcoded dark backgrounds — a light terminal makes those
17
+ // regions look like black blocks). Cursor uses the favorite-star gold so
18
+ // it pops against the ink without dragging brand orange back in.
19
+ const THEME = {
20
+ background: '#1a1815',
21
+ foreground: '#e8e3d5',
22
+ cursor: '#e3b341',
23
+ cursorAccent: '#1a1815',
24
+ selectionBackground: '#3a3530',
25
+ black: '#1a1815', brightBlack: '#534e44',
26
+ red: '#e07b6e', brightRed: '#f0a098',
27
+ green: '#7fb670', brightGreen: '#a0d28f',
28
+ yellow: '#e3b341', brightYellow: '#f0c860',
29
+ blue: '#7d9fc4', brightBlue: '#9bb8d8',
30
+ magenta: '#c08fd0', brightMagenta: '#d8aae2',
31
+ cyan: '#6fb0b0', brightCyan: '#90c8c8',
32
+ white: '#e8e3d5', brightWhite: '#faf9f5',
33
+ };
34
+
35
+ export function TerminalView({ terminalId }) {
36
+ const hostRef = useRef(null);
37
+ const termRef = useRef(null);
38
+ const wsRef = useRef(null);
39
+
40
+ useEffect(() => {
41
+ if (!terminalId || !hostRef.current) return;
42
+
43
+ const term = new Terminal({
44
+ fontFamily: '"Cascadia Mono", "Geist Mono", "JetBrains Mono", Consolas, monospace',
45
+ fontSize: 13,
46
+ lineHeight: 1.2,
47
+ cursorBlink: true,
48
+ cursorStyle: 'bar',
49
+ scrollback: 5000,
50
+ allowProposedApi: true,
51
+ theme: THEME,
52
+ // Modern keyboard protocols. Without these, xterm.js encodes
53
+ // Shift+Enter, Ctrl+Enter, Ctrl+Shift+key etc. the same as their
54
+ // unmodified versions (e.g. both Enter and Shift+Enter send \r),
55
+ // so TUIs like claude code can't tell them apart.
56
+ //
57
+ // - kittyKeyboard: opt-in protocol that apps enable per-session;
58
+ // xterm emits CSI u sequences that uniquely encode every modifier
59
+ // combo. Claude / vim / fish recognise it.
60
+ // - win32InputMode: ConPTY-specific protocol that surfaces raw
61
+ // Win32 KEY_EVENT_RECORD to the child process, again preserving
62
+ // modifier info. Required for full key fidelity on Windows.
63
+ // (Same set VSCode enables — see vscode/src/.../xtermTerminal.ts)
64
+ vtExtensions: {
65
+ kittyKeyboard: true,
66
+ win32InputMode: true,
67
+ },
68
+ });
69
+ const fit = new FitAddon();
70
+ term.loadAddon(fit);
71
+ term.loadAddon(new WebLinksAddon());
72
+ // OSC 52 clipboard integration. Lets TUI apps initiate clipboard reads/
73
+ // writes via escape sequences (e.g. `tmux set-buffer` or claude code
74
+ // saying "copied to clipboard"). Does NOT handle the browser-side
75
+ // Ctrl+V — that's still our document-level paste handler below.
76
+ term.loadAddon(new ClipboardAddon());
77
+ // WebGL renderer for performance. The default DOM renderer struggles
78
+ // when claude code produces dense color output (its diff panels,
79
+ // syntax-highlighted code). WebGL paints onto a canvas, much smoother
80
+ // at thousands-of-cells per frame. Falls back to DOM if WebGL is
81
+ // unavailable (e.g. older GPU, hardware accel disabled).
82
+ try {
83
+ const webgl = new WebglAddon();
84
+ webgl.onContextLoss(() => { try { webgl.dispose(); } catch {} });
85
+ term.loadAddon(webgl);
86
+ } catch (e) {
87
+ console.warn('[ccsm] WebGL addon failed, using DOM renderer:', e);
88
+ }
89
+ const host = hostRef.current;
90
+ term.open(host);
91
+ // Defer fit one tick so the container has measured layout
92
+ requestAnimationFrame(() => { try { fit.fit(); } catch {} });
93
+ termRef.current = term;
94
+
95
+ const ws = new WebSocket(`${wsBase()}/ws/terminal/${encodeURIComponent(terminalId)}`);
96
+ ws.binaryType = 'arraybuffer';
97
+ wsRef.current = ws;
98
+
99
+ ws.onopen = () => {
100
+ // tell server the initial size (cols/rows after fit)
101
+ ws.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }));
102
+ };
103
+ ws.onmessage = (ev) => {
104
+ let frame;
105
+ try { frame = JSON.parse(ev.data); } catch { return; }
106
+ if (frame.type === 'output') {
107
+ term.write(frame.data);
108
+ } else if (frame.type === 'exit') {
109
+ term.write(`\r\n\x1b[2m[process exited · code ${frame.code}]\x1b[0m\r\n`);
110
+ }
111
+ };
112
+ ws.onclose = () => {
113
+ term.write('\r\n\x1b[2m[disconnected]\x1b[0m\r\n');
114
+ };
115
+
116
+ const onData = (data) => {
117
+ if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'input', data }));
118
+ };
119
+ const onResize = ({ cols, rows }) => {
120
+ if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'resize', cols, rows }));
121
+ };
122
+ term.onData(onData);
123
+ term.onResize(onResize);
124
+
125
+ const ro = new ResizeObserver(() => { try { fit.fit(); } catch {} });
126
+ ro.observe(hostRef.current);
127
+
128
+ // Tab-switch refresh. The terminal lives inside a .tab-panel which gets
129
+ // display:none when another tab is active. WebGL renderers keep a glyph
130
+ // texture atlas in GPU memory; when the canvas hides + redisplays at a
131
+ // potentially different devicePixelRatio, the atlas isn't invalidated
132
+ // and old glyphs blend with newly-rasterized ones — visible as scrolling
133
+ // text ghosting / double-strikes. Watching the tab-panel's data-active
134
+ // attribute and clearing the atlas + re-fitting + forcing a full
135
+ // refresh wipes the cache cleanly.
136
+ const panel = host.closest('.tab-panel');
137
+ let panelMo = null;
138
+ if (panel) {
139
+ panelMo = new MutationObserver(() => {
140
+ if (panel.hasAttribute('data-active')) {
141
+ requestAnimationFrame(() => {
142
+ try { term.clearTextureAtlas?.(); } catch {}
143
+ try { fit.fit(); } catch {}
144
+ try { term.refresh(0, term.rows - 1); } catch {}
145
+ });
146
+ }
147
+ });
148
+ panelMo.observe(panel, { attributes: true, attributeFilter: ['data-active'] });
149
+ }
150
+
151
+ // give focus to terminal so user can type immediately
152
+ term.focus();
153
+
154
+ // Explicit paste handler. xterm.js relies on the browser routing paste
155
+ // events to its hidden .xterm-helper-textarea, which only works if that
156
+ // textarea has focus at the moment of Ctrl+V. When the user clicks
157
+ // elsewhere then hits Ctrl+V over the terminal, or pastes via the
158
+ // right-click menu on the host div, the event lands on the host and
159
+ // xterm never sees it. Catch it here and route through term.paste()
160
+ // so xterm wraps the text in bracketed-paste markers when the app
161
+ // (claude code) has DECSET 2004 enabled — that's what makes claude
162
+ // show the "[Pasted text]" affordance instead of treating it as
163
+ // typed input.
164
+ const isOurs = () => {
165
+ const ae = document.activeElement;
166
+ return ae && host.contains(ae);
167
+ };
168
+ const doPaste = (text) => {
169
+ if (!text) return;
170
+ if (ws.readyState !== 1) return;
171
+ // Normalize line endings to \r (CR / Enter). This mirrors VSCode's
172
+ // terminal sendText path (terminalInstance.ts ~L1385):
173
+ // text = text.replace(/\r?\n/g, '\r');
174
+ // Bracketed-paste markers protect each \r from being interpreted
175
+ // as a submit by the host app — claude / pwsh / vim all treat
176
+ // bracketed contents as opaque payload regardless of what's inside.
177
+ // Use \n instead and you trip apps that look for "real" line breaks.
178
+ const normalized = text.replace(/\r?\n/g, '\r');
179
+ // Wrap in bracketed-paste markers. Claude Code enables DECSET 2004
180
+ // on startup, so the markers let it detect a paste and render
181
+ // "[Pasted text]". If the host app doesn't have bracketed paste on,
182
+ // it just sees two ignored escape sequences plus the text.
183
+ const wrapped = `\x1b[200~${normalized}\x1b[201~`;
184
+ ws.send(JSON.stringify({ type: 'input', data: wrapped }));
185
+ };
186
+ const onPaste = async (ev) => {
187
+ if (!isOurs()) return;
188
+ let text = '';
189
+ if (ev.clipboardData) text = ev.clipboardData.getData('text');
190
+ if (!text && navigator.clipboard) {
191
+ try { text = await navigator.clipboard.readText(); } catch {}
192
+ }
193
+ if (!text) return;
194
+ ev.preventDefault();
195
+ ev.stopPropagation();
196
+ doPaste(text);
197
+ };
198
+ document.addEventListener('paste', onPaste, true);
199
+
200
+ // Ctrl/Cmd+V fallback for cases the paste event is suppressed (some
201
+ // extensions, or when our IME workaround moved the helper textarea
202
+ // off-screen and the browser refuses to fire paste on it).
203
+ // IMPORTANT: preventDefault must happen synchronously, BEFORE the
204
+ // await on navigator.clipboard.readText(). If we let the event tick
205
+ // run first, xterm's keystroke handler converts Ctrl+V into the raw
206
+ // ^V (0x16) control byte and ships it before our async paste even
207
+ // resolves.
208
+ const onKey = (ev) => {
209
+ const meta = ev.ctrlKey || ev.metaKey;
210
+ if (!meta || ev.key.toLowerCase() !== 'v') return;
211
+ if (ev.shiftKey || ev.altKey) return;
212
+ if (!isOurs()) return;
213
+ if (!navigator.clipboard?.readText) return;
214
+ ev.preventDefault();
215
+ ev.stopPropagation();
216
+ ev.stopImmediatePropagation();
217
+ navigator.clipboard.readText().then((text) => {
218
+ if (text) doPaste(text);
219
+ }).catch(() => {});
220
+ };
221
+ document.addEventListener('keydown', onKey, true);
222
+
223
+ // Shift+Enter / Ctrl+Enter → insert literal newline, don't submit.
224
+ // Background: xterm.js encodes BOTH plain Enter and Shift+Enter and
225
+ // Ctrl+Enter as \r (0x0D / CR). The kitty keyboard / win32 input
226
+ // protocols (enabled in vtExtensions above) WOULD distinguish them,
227
+ // but they're opt-in by the running app — claude code doesn't enable
228
+ // either, so we never get the distinction "for free".
229
+ //
230
+ // Send the LF (0x0A) explicitly. Claude code (and most modern TUIs)
231
+ // treat \n inside a prompt as a literal newline insert, \r as submit.
232
+ // Alt+Enter already works (xterm sends \x1b\r → meta-enter) so we
233
+ // leave that alone.
234
+ const onShiftEnter = (ev) => {
235
+ if (ev.key !== 'Enter') return;
236
+ if (!(ev.shiftKey || ev.ctrlKey)) return;
237
+ if (ev.metaKey || ev.altKey) return;
238
+ if (!isOurs()) return;
239
+ ev.preventDefault();
240
+ ev.stopPropagation();
241
+ ev.stopImmediatePropagation();
242
+ if (ws.readyState === 1) {
243
+ ws.send(JSON.stringify({ type: 'input', data: '\n' }));
244
+ }
245
+ };
246
+ document.addEventListener('keydown', onShiftEnter, true);
247
+
248
+ // IME fix: xterm positions .xterm-helper-textarea via `left: <col-px>`
249
+ // following the cursor. When the cursor is near the right edge and the
250
+ // user starts composing (e.g. Chinese pinyin), the textarea + native
251
+ // composition popup grow with the composed string and overflow the
252
+ // terminal host — which visually pushes the layout right. We can't cap
253
+ // width / change wrapping (that breaks Chromium's IME event flow), but
254
+ // we CAN re-anchor the textarea to the right edge while composing so
255
+ // it grows leftward instead. Toggling a class on the host is enough;
256
+ // the CSS in terminals.css does the rest.
257
+ const onCompStart = () => {
258
+ if (host) host.classList.add('is-composing');
259
+ // The terminal cursor is rendered on canvas (THEME.cursor), so CSS
260
+ // can't hide it. Theme swap alone doesn't reliably stop the blink
261
+ // frame loop, so also issue the DECTCEM hide sequence which the
262
+ // renderer honours immediately.
263
+ try { term.options.theme = { ...THEME, cursor: 'transparent', cursorAccent: 'transparent' }; } catch {}
264
+ try { term.write('\x1b[?25l'); } catch {}
265
+ };
266
+ const onCompEnd = () => {
267
+ if (host) host.classList.remove('is-composing');
268
+ try { term.options.theme = THEME; } catch {}
269
+ try { term.write('\x1b[?25h'); } catch {}
270
+ };
271
+ const helper = host?.querySelector('.xterm-helper-textarea');
272
+ if (helper) {
273
+ helper.addEventListener('compositionstart', onCompStart);
274
+ helper.addEventListener('compositionend', onCompEnd);
275
+ }
276
+
277
+ return () => {
278
+ document.removeEventListener('paste', onPaste, true);
279
+ document.removeEventListener('keydown', onKey, true);
280
+ document.removeEventListener('keydown', onShiftEnter, true);
281
+ if (helper) {
282
+ helper.removeEventListener('compositionstart', onCompStart);
283
+ helper.removeEventListener('compositionend', onCompEnd);
284
+ }
285
+ ro.disconnect();
286
+ if (panelMo) panelMo.disconnect();
287
+ try { ws.close(); } catch {}
288
+ try { term.dispose(); } catch {}
289
+ termRef.current = null;
290
+ wsRef.current = null;
291
+ };
292
+ }, [terminalId]);
293
+
294
+ if (!terminalId) {
295
+ return html`<div class="terminal-empty">Select a terminal on the left, or launch a new one.</div>`;
296
+ }
297
+ return html`<div ref=${hostRef} class="terminal-host"></div>`;
298
+ }