townmouse 0.0.0-stage → 0.4.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 (108) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/DESIGN.md +153 -0
  3. package/LICENSE +661 -0
  4. package/README.md +600 -2
  5. package/SECURITY.md +60 -0
  6. package/TOWNMOUSE.md +91 -0
  7. package/assets/brand/mascot/README.md +23 -0
  8. package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
  9. package/assets/brand/mascot/townmouse-icon.svg +1 -0
  10. package/assets/brand/mascot/townmouse-monocled.png +0 -0
  11. package/bin/townmouse +68 -0
  12. package/docs/PACKAGING.md +371 -0
  13. package/docs/browser-workspace.md +237 -0
  14. package/docs/panes.md +442 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/npm-shrinkwrap.json +1282 -0
  17. package/package.json +93 -4
  18. package/public/apple-touch-icon.png +0 -0
  19. package/public/brand/floydslabs-credit.png +0 -0
  20. package/public/brand/floydslabs-credit.webp +0 -0
  21. package/public/brand/townmouse-aristocrat.webp +0 -0
  22. package/public/brand/townmouse-monocled.webp +0 -0
  23. package/public/browser-picture.mjs +159 -0
  24. package/public/clipboard-text.mjs +5 -0
  25. package/public/favicon-16x16.png +0 -0
  26. package/public/favicon-32x32.png +0 -0
  27. package/public/favicon.ico +0 -0
  28. package/public/favicon.svg +1 -0
  29. package/public/features/app-version.mjs +35 -0
  30. package/public/features/autosave.mjs +80 -0
  31. package/public/features/clipboard.mjs +69 -0
  32. package/public/features/command-palette.mjs +181 -0
  33. package/public/features/desktop-palette.mjs +19 -0
  34. package/public/features/export.mjs +37 -0
  35. package/public/features/file-drop.mjs +77 -0
  36. package/public/features/floating-palette.mjs +113 -0
  37. package/public/features/fontsize.mjs +72 -0
  38. package/public/features/haptic-keys.mjs +42 -0
  39. package/public/features/history-undo.mjs +102 -0
  40. package/public/features/keepalive.mjs +36 -0
  41. package/public/features/keybar-config.mjs +70 -0
  42. package/public/features/keyboard-shortcuts.mjs +74 -0
  43. package/public/features/links.mjs +139 -0
  44. package/public/features/multi-window-sync.mjs +76 -0
  45. package/public/features/osc-bridge.mjs +64 -0
  46. package/public/features/phone-landscape-focus.mjs +157 -0
  47. package/public/features/recent-commands.mjs +100 -0
  48. package/public/features/search.mjs +134 -0
  49. package/public/features/session-lock.mjs +96 -0
  50. package/public/features/session-manager.mjs +251 -0
  51. package/public/features/settings-sync.mjs +77 -0
  52. package/public/features/shortcut-help.mjs +85 -0
  53. package/public/features/smart-completions.mjs +101 -0
  54. package/public/features/smart-suggest.mjs +124 -0
  55. package/public/features/snippets.mjs +85 -0
  56. package/public/features/split-view.mjs +102 -0
  57. package/public/features/status-metrics.mjs +137 -0
  58. package/public/features/stylus-support.mjs +124 -0
  59. package/public/features/swipe-history.mjs +141 -0
  60. package/public/features/swipe-sessions.mjs +85 -0
  61. package/public/features/tab-reorder.mjs +70 -0
  62. package/public/features/theme-system.mjs +51 -0
  63. package/public/features/toast-status.mjs +118 -0
  64. package/public/features/two-finger-menu.mjs +87 -0
  65. package/public/features/voice-input.mjs +244 -0
  66. package/public/features/wake-fullscreen.mjs +67 -0
  67. package/public/features/window-title.mjs +47 -0
  68. package/public/features/zoom.mjs +80 -0
  69. package/public/icon-128.png +0 -0
  70. package/public/icon-180.png +0 -0
  71. package/public/icon-192.png +0 -0
  72. package/public/icon-48.png +0 -0
  73. package/public/icon-512-maskable.png +0 -0
  74. package/public/icon-512.png +0 -0
  75. package/public/icon.svg +1 -0
  76. package/public/index.html +2304 -0
  77. package/public/input-chunks.mjs +22 -0
  78. package/public/input-guard.mjs +218 -0
  79. package/public/manifest.json +56 -0
  80. package/public/panes.css +1433 -0
  81. package/public/panes.html +211 -0
  82. package/public/panes.mjs +3183 -0
  83. package/public/service-worker.js +67 -0
  84. package/public/workspace.css +1621 -0
  85. package/public/workspace.mjs +1715 -0
  86. package/scripts/install-service.sh +303 -0
  87. package/scripts/node-runtime.sh +138 -0
  88. package/scripts/panes +568 -0
  89. package/scripts/prepare-native.sh +35 -0
  90. package/scripts/retire-legacy-service.sh +76 -0
  91. package/scripts/run-hooks +69 -0
  92. package/scripts/townmouse.sh +152 -0
  93. package/scripts/uninstall-service.sh +65 -0
  94. package/src/agent-guide.js +329 -0
  95. package/src/attachments.js +128 -0
  96. package/src/browser-dom.js +548 -0
  97. package/src/browser-workspace.js +1733 -0
  98. package/src/chrome-resolve.js +80 -0
  99. package/src/owner-page.js +43 -0
  100. package/src/pty-permissions.js +99 -0
  101. package/src/regex-worker.js +13 -0
  102. package/src/replay-text.js +189 -0
  103. package/src/request-boundary.js +58 -0
  104. package/src/safe-regex.js +87 -0
  105. package/src/server.js +1582 -0
  106. package/src/shell-resolve.js +42 -0
  107. package/src/static-deps.js +61 -0
  108. package/src/workspace-panes.js +1431 -0
@@ -0,0 +1,2304 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
6
+ <meta name="apple-mobile-web-app-capable" content="yes">
7
+ <meta name="mobile-web-app-capable" content="yes">
8
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
+ <meta name="apple-mobile-web-app-title" content="Townmouse">
10
+ <meta name="description" content="Townmouse is a terminal and agent browser workspace. Its embedded TerminalOne engine supplies the PTY.">
11
+ <title>Townmouse</title>
12
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg">
13
+ <link rel="manifest" href="/manifest.json">
14
+ <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
15
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
16
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
17
+ <meta name="theme-color" content="#eef1f5">
18
+ <link rel="preconnect" href="https://fonts.googleapis.com">
19
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
20
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
21
+ <link rel="stylesheet" href="/node_modules/@xterm/xterm/css/xterm.css">
22
+ <style>
23
+ /* ── Theme variables (defaults: Graphite Studio). JS overrides per selected theme. ── */
24
+ :root {
25
+ --ui-bg: #14171b;
26
+ --ui-fg: #eceeea;
27
+ --ui-elevated: #242a30;
28
+ --ui-border: #7d8992;
29
+ --ui-accent: #d6ad68;
30
+ --ui-muted: #b5bdc4;
31
+ }
32
+
33
+ * { box-sizing: border-box; }
34
+ html {
35
+ height: 100%;
36
+ margin: 0;
37
+ overflow: hidden;
38
+ -webkit-font-smoothing: antialiased;
39
+ -moz-osx-font-smoothing: grayscale;
40
+ }
41
+ body { height: 100%; margin: 0; overflow: hidden; }
42
+ body {
43
+ background: var(--ui-bg);
44
+ color: var(--ui-fg);
45
+ font-family: 'JetBrains Mono', 'SF Mono', ui-monospace, monospace;
46
+ /* Prevent iOS text-size adjust and rubber-band overscroll on the chrome. */
47
+ -webkit-text-size-adjust: 100%;
48
+ overscroll-behavior: none;
49
+ /* Respect notches / home indicators. */
50
+ padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
51
+ }
52
+
53
+ /* Compatibility canvas (Evergreen preset) sits behind the app. */
54
+ #fxCanvas {
55
+ position: fixed;
56
+ inset: 0;
57
+ z-index: 0;
58
+ display: none;
59
+ pointer-events: none;
60
+ }
61
+
62
+ .app-shell {
63
+ position: relative;
64
+ z-index: 1;
65
+ display: flex;
66
+ flex-direction: column;
67
+ height: 100%;
68
+ width: 100%;
69
+ background: transparent;
70
+ }
71
+ .terminal-header {
72
+ display: flex;
73
+ align-items: center;
74
+ justify-content: space-between;
75
+ padding: 8px 16px;
76
+ background: var(--ui-elevated);
77
+ border-bottom: 1px solid var(--ui-border);
78
+ flex: 0 0 auto;
79
+ transition: background-color 0.15s ease, border-color 0.15s ease;
80
+ }
81
+ .terminal-title {
82
+ font-weight: 600;
83
+ font-size: 14px;
84
+ letter-spacing: 0.02em;
85
+ color: var(--ui-fg);
86
+ }
87
+ .statuswrap { display: flex; align-items: center; gap: 6px; }
88
+ .status-dot {
89
+ width: 8px;
90
+ height: 8px;
91
+ border-radius: 50%;
92
+ background: var(--ui-muted);
93
+ flex-shrink: 0;
94
+ transition: background-color 0.15s ease, box-shadow 0.15s ease;
95
+ }
96
+ .status-dot.connected { background: var(--ui-accent); box-shadow: none; }
97
+ .status-dot.error { background: #e2a69e; box-shadow: none; }
98
+ .status-dot.connecting { background: var(--ui-accent); animation: dotpulse 1.4s ease-in-out infinite; }
99
+ @keyframes dotpulse { 0%,100% { opacity: 1; } 50% { opacity: 0.3; } }
100
+ .terminal-status {
101
+ font-size: 12px;
102
+ padding: 2px 8px;
103
+ border-radius: 4px;
104
+ background: var(--ui-elevated);
105
+ border: 1px solid var(--ui-border);
106
+ color: var(--ui-muted);
107
+ font-variant-numeric: tabular-nums;
108
+ }
109
+ .terminal-status.connected { color: var(--ui-accent); }
110
+ .terminal-status.error { color: var(--ui-danger, #e2a69e); }
111
+ .terminal-actions { display: flex; gap: 8px; }
112
+ button {
113
+ background: var(--ui-elevated);
114
+ border: 1px solid var(--ui-border);
115
+ color: var(--ui-fg);
116
+ border-radius: 4px;
117
+ padding: 4px 10px;
118
+ font-family: inherit;
119
+ font-size: 12px;
120
+ cursor: pointer;
121
+ transition-property: background-color, color, border-color, transform;
122
+ transition-duration: 0.12s;
123
+ transition-timing-function: ease;
124
+ }
125
+ button:hover { border-color: var(--ui-accent); }
126
+ button:active { transform: scale(0.96); }
127
+ button:focus-visible {
128
+ outline: 2px solid var(--ui-accent);
129
+ outline-offset: 2px;
130
+ }
131
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
132
+ .terminal-container {
133
+ position: relative;
134
+ flex: 1 1 auto;
135
+ min-height: 0;
136
+ padding: 8px 12px 12px;
137
+ background: transparent;
138
+ /* Two-finger scroll is handled in JS; block the browser from also scrolling. */
139
+ touch-action: none;
140
+ }
141
+ #terminal { width: 100%; height: 100%; }
142
+
143
+ /* ── On-screen key bar (iPhone / iPad only). Hidden on desktop. ── */
144
+ .keybar {
145
+ flex: 0 0 auto;
146
+ display: none;
147
+ gap: 6px;
148
+ align-items: center;
149
+ padding: 6px 8px calc(6px + env(safe-area-inset-bottom));
150
+ background: var(--ui-elevated);
151
+ border-top: 1px solid var(--ui-border);
152
+ overflow-x: auto;
153
+ -webkit-overflow-scrolling: touch;
154
+ scrollbar-width: none;
155
+ }
156
+ .keybar::-webkit-scrollbar { display: none; }
157
+ body[data-device="iphone"] .keybar.iphone,
158
+ body[data-device="ipad"] .keybar.ipad { display: flex; }
159
+ .keybar .kb-group {
160
+ display: flex;
161
+ gap: 4px;
162
+ padding-right: 6px;
163
+ border-right: 1px solid var(--ui-border);
164
+ }
165
+ .keybar .kb-group:last-child { border-right: none; padding-right: 0; }
166
+ .keybar .kb-key {
167
+ flex: 0 0 auto;
168
+ min-width: 44px;
169
+ min-height: 44px;
170
+ display: inline-flex;
171
+ align-items: center;
172
+ justify-content: center;
173
+ background: var(--ui-bg);
174
+ border: 1px solid var(--ui-border);
175
+ border-radius: 6px;
176
+ color: var(--ui-fg);
177
+ font-family: inherit;
178
+ font-size: 13px;
179
+ padding: 0 8px;
180
+ /* Big touch target with no tap highlight. */
181
+ -webkit-tap-highlight-color: transparent;
182
+ touch-action: manipulation;
183
+ user-select: none;
184
+ -webkit-user-select: none;
185
+ transition-property: background-color, border-color, color, transform;
186
+ transition-duration: 0.08s;
187
+ transition-timing-function: ease;
188
+ }
189
+ body[data-device="ipad"] .keybar .kb-key { min-width: 44px; min-height: 44px; font-size: 14px; }
190
+ .keybar .kb-key:active { background: var(--ui-accent); color: #000; border-color: var(--ui-accent); transform: scale(0.96); }
191
+ .keybar .kb-key.toggle.active {
192
+ background: var(--ui-accent);
193
+ color: #000;
194
+ border-color: var(--ui-accent);
195
+ }
196
+ .keybar .kb-arrows { display: flex; flex-direction: column; gap: 6px; align-items: center; }
197
+ .keybar .kb-arrows .kb-row { display: flex; gap: 6px; }
198
+ .keybar .kb-spacer { flex: 0 1 6px; }
199
+
200
+ .terminal-footer {
201
+ flex: 0 0 auto;
202
+ display: flex;
203
+ justify-content: space-between;
204
+ align-items: center;
205
+ padding: 6px 16px;
206
+ background: var(--ui-elevated);
207
+ border-top: 1px solid var(--ui-border);
208
+ font-size: 11px;
209
+ color: var(--ui-muted);
210
+ font-variant-numeric: tabular-nums;
211
+ }
212
+ .banner {
213
+ position: fixed;
214
+ top: 0; left: 0; right: 0;
215
+ padding: 8px 16px;
216
+ font-size: 12px;
217
+ z-index: 300;
218
+ display: none;
219
+ }
220
+ .banner.error { background: #e2a69e; color: #14171b; display: block; }
221
+ .banner.warn { background: #dcc38b; color: #14171b; display: block; }
222
+
223
+ /* ── Compact studio typography ── */
224
+ body[data-style="floyd"] { font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace; }
225
+ body[data-style="floyd"] .terminal-header { padding: 3px 10px; }
226
+ body[data-style="floyd"] .terminal-title {
227
+ font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; color: var(--ui-accent);
228
+ }
229
+ body[data-style="floyd"] button {
230
+ font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;
231
+ padding: 3px 8px; border-radius: 3px;
232
+ }
233
+ body[data-style="floyd"] button:hover { background: var(--ui-accent); color: #000; }
234
+ body[data-style="floyd"] .terminal-status {
235
+ font-size: 8px; text-transform: uppercase; letter-spacing: 0.5px; background: transparent; border-color: transparent;
236
+ }
237
+ body[data-style="floyd"] .status-dot.connected { box-shadow: none; }
238
+ body[data-style="floyd"] .terminal-footer {
239
+ font-size: 9px; text-transform: uppercase; letter-spacing: 0.5px; padding: 3px 10px;
240
+ }
241
+
242
+ /* ── Evergreen compatibility surface ── */
243
+ body[data-theme="matrix"] { background: transparent; }
244
+ body[data-theme="matrix"] #fxCanvas { display: block; }
245
+ body[data-theme="matrix"] .terminal-header,
246
+ body[data-theme="matrix"] .terminal-footer,
247
+ body[data-theme="matrix"] .keybar { background: var(--ui-elevated); }
248
+
249
+ /* ── Settings modal ── */
250
+ #settingsModal {
251
+ position: fixed; inset: 0; z-index: 400;
252
+ display: none; align-items: center; justify-content: center;
253
+ background: rgba(0,0,0,0.6); backdrop-filter: blur(4px);
254
+ }
255
+ #settingsModal.open { display: flex; }
256
+ .settings-panel {
257
+ background: var(--ui-elevated);
258
+ border: 1px solid var(--ui-border);
259
+ border-radius: 10px;
260
+ padding: 18px;
261
+ width: 90%;
262
+ max-width: 340px;
263
+ box-shadow: 0 16px 48px rgba(0,0,0,0.5);
264
+ }
265
+ .settings-panel h2 { font-size: 13px; margin: 0 0 14px; color: var(--ui-accent); letter-spacing: 0.5px; }
266
+ .settings-row { margin-bottom: 14px; }
267
+ .settings-row label {
268
+ display: block; font-size: 11px; color: var(--ui-muted);
269
+ margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px;
270
+ }
271
+ .settings-row select {
272
+ width: 100%;
273
+ background: var(--ui-bg);
274
+ color: var(--ui-fg);
275
+ border: 1px solid var(--ui-border);
276
+ border-radius: 6px;
277
+ padding: 7px 9px;
278
+ font-family: inherit;
279
+ font-size: 13px;
280
+ cursor: pointer;
281
+ }
282
+ .settings-row select:focus { outline: none; border-color: var(--ui-accent); }
283
+ .settings-actions { display: flex; justify-content: flex-end; margin-top: 4px; }
284
+ .settings-section { margin: 0 0 14px; padding-top: 12px; border-top: 1px solid var(--ui-border); }
285
+ .settings-section h3 { font-size: 11px; margin: 0 0 12px; color: var(--ui-muted); text-transform: uppercase; letter-spacing: 0.5px; }
286
+ .settings-section .settings-row input { cursor: text; }
287
+ .settings-section textarea {
288
+ width: 100%;
289
+ background: var(--ui-bg);
290
+ color: var(--ui-fg);
291
+ border: 1px solid var(--ui-border);
292
+ border-radius: 6px;
293
+ padding: 7px 9px;
294
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
295
+ font-size: 12px;
296
+ line-height: 1.45;
297
+ min-height: 64px;
298
+ resize: vertical;
299
+ }
300
+ .settings-section textarea:focus { outline: none; border-color: var(--ui-accent); }
301
+ .settings-advanced { margin-bottom: 14px; }
302
+ .settings-advanced summary { cursor: pointer; font-size: 11px; color: var(--ui-muted); margin-bottom: 6px; }
303
+ .settings-advanced summary:focus { outline: 2px solid var(--ui-accent); outline-offset: 2px; }
304
+ .settings-voice-actions { align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
305
+ #voiceStatus { flex: 1 1 160px; min-height: 1.4em; font-size: 11px; line-height: 1.4; color: var(--ui-muted); overflow-wrap: anywhere; }
306
+ #voiceStatus[data-kind="ok"] { color: #9ccf9c; }
307
+ #voiceStatus[data-kind="warn"] { color: #dcc38b; }
308
+ #voiceStatus[data-kind="error"] { color: #e2a69e; }
309
+ #voiceSave { background: var(--ui-bg); color: var(--ui-fg); border: 1px solid var(--ui-border); border-radius: 6px; padding: 8px 12px; font-size: 12px; cursor: pointer; }
310
+ #voiceSave:hover { border-color: var(--ui-accent); }
311
+ #voiceSave:disabled { cursor: default; }
312
+ .t1toolbar {
313
+ display: flex;
314
+ flex-wrap: wrap;
315
+ gap: 6px;
316
+ padding: 6px 16px;
317
+ background: var(--ui-elevated);
318
+ border-bottom: 1px solid var(--ui-border);
319
+ flex: 0 0 auto;
320
+ }
321
+ .t1toolbar:empty { display: none; }
322
+ .t1button {
323
+ background: var(--ui-bg);
324
+ border: 1px solid var(--ui-border);
325
+ color: var(--ui-fg);
326
+ border-radius: 6px;
327
+ padding: 4px 10px;
328
+ font-size: 12px;
329
+ cursor: pointer;
330
+ }
331
+ .t1button:hover { border-color: var(--ui-accent); }
332
+ .t1button:active { transform: scale(0.96); }
333
+ .t1button.active { background: var(--ui-accent); color: #000; border-color: var(--ui-accent); }
334
+ /* Toast notifications — transient, stacked, auto-dismissing. */
335
+ .t1toast-host {
336
+ position: absolute;
337
+ top: 12px;
338
+ right: 12px;
339
+ z-index: 1000;
340
+ display: flex;
341
+ flex-direction: column;
342
+ gap: 8px;
343
+ max-width: min(360px, calc(100% - 24px));
344
+ pointer-events: none;
345
+ }
346
+ .t1toast {
347
+ pointer-events: auto;
348
+ background: var(--ui-elevated);
349
+ color: var(--ui-fg);
350
+ border: 1px solid var(--ui-border);
351
+ border-left: 3px solid var(--ui-muted);
352
+ border-radius: 6px;
353
+ padding: 9px 12px;
354
+ font-size: 12px;
355
+ line-height: 1.35;
356
+ box-shadow: 0 6px 22px rgba(0,0,0,0.45);
357
+ opacity: 1;
358
+ visibility: hidden;
359
+ word-wrap: break-word;
360
+ font-variant-numeric: tabular-nums;
361
+ }
362
+ .t1toast.show { visibility: visible; }
363
+ .t1toast-info { border-left-color: var(--ui-accent); }
364
+ .t1toast-warn { border-left-color: #dcc38b; }
365
+ .t1toast-error { border-left-color: #e2a69e; }
366
+ /* Commercial layout: controls occupy real flow space, never float over input. */
367
+ .terminal-header { flex-wrap: wrap; gap: 8px 12px; }
368
+ .terminal-title { display: flex; align-items: center; gap: 8px; }
369
+ .terminal-title::before { content: ''; width: 28px; height: 28px; background: url('/icon.svg') center / contain no-repeat; }
370
+ .terminal-actions { flex-wrap: wrap; }
371
+ button, select, .t1session-tab { min-height: 44px; }
372
+ button { min-width: 44px; border-radius: 7px; line-height: 1.3; }
373
+ button:disabled { opacity: 1; color: var(--ui-muted); }
374
+ input, select { font: inherit; }
375
+ .terminal-footer { gap: 12px; flex-wrap: wrap; line-height: 1.5; }
376
+ .t1toolbar { gap: 8px; padding: 8px 16px; }
377
+ .keybar { flex-wrap: wrap; gap: 6px; overflow: visible; }
378
+ .keybar .kb-group { flex-wrap: wrap; gap: 4px; border: 0; padding: 0; }
379
+ .terminal-actions { margin-left: auto; }
380
+ .terminal-header .t1-chrome-fab { margin: 0; }
381
+ .settings-panel { max-height: calc(100dvh - 24px); overflow-y: auto; }
382
+ .t1keybar-cfg label:focus-within { outline: 2px solid var(--ui-accent); outline-offset: 2px; }
383
+ @media (max-height: 500px) and (min-width: 600px) {
384
+ .settings-panel { max-width: 700px; display: grid; grid-template-columns: 1fr 1fr; gap: 12px 20px; padding: 16px; }
385
+ .settings-panel h2 { grid-column: 1 / -1; margin: 0; }
386
+ .settings-row { margin: 0; }
387
+ .settings-keybar-row, .settings-actions { grid-column: 1 / -1; }
388
+ .settings-section { grid-column: 1 / -1; }
389
+ .settings-keybar-row .t1keybar-cfg { grid-template-columns: repeat(5, 1fr); }
390
+ }
391
+ /* The session row keeps to one line and scrolls sideways when it is full. Its
392
+ styles live with the module that renders it (features/session-manager.mjs)
393
+ and in the workspace stylesheet. */
394
+ body[data-style="floyd"] button { font-size: 12px; }
395
+ body[data-style="floyd"] .terminal-status, body[data-style="floyd"] .terminal-footer { font-size: 11px; }
396
+ .keybar .kb-key:active, .keybar .kb-key.toggle.active, .t1button.active,
397
+ body[data-style="floyd"] button:hover { color: var(--ui-on-accent, #14171b); }
398
+ @media (max-width: 600px) {
399
+ .terminal-header { padding: 8px; gap: 8px; }
400
+ .terminal-title { font-size: 13px; }
401
+ .terminal-actions { order: 4; width: 100%; gap: 6px; }
402
+ .terminal-actions button { flex: 1; }
403
+ .statuswrap { margin-left: auto; }
404
+ .terminal-footer { padding: 6px 8px; }
405
+ #sessionInfo { overflow-wrap: anywhere; }
406
+ }
407
+ @media (prefers-reduced-motion: reduce) {
408
+ *, *::before, *::after { animation: none !important; transition: none !important; }
409
+ }
410
+ </style>
411
+ <link rel="stylesheet" href="/workspace.css">
412
+ </head>
413
+ <body class="workspace" data-style="default" data-theme="tokyo-night" data-device="desktop">
414
+ <canvas id="fxCanvas" aria-hidden="true"></canvas>
415
+
416
+ <div class="app-shell">
417
+ <div class="banner" id="banner"></div>
418
+ <header class="terminal-header">
419
+ <div class="terminal-title"><span>Townmouse<span class="terminal-title-session" id="titleSession"></span></span></div>
420
+ <div class="terminal-actions">
421
+ <button id="settingsBtn" type="button" title="Settings">Settings</button>
422
+ <button id="reconnectBtn" type="button">Reconnect</button>
423
+ <button id="closeBtn" type="button">Close</button>
424
+ </div>
425
+ <div class="statuswrap">
426
+ <span class="status-dot" id="statusDot"></span>
427
+ <span class="terminal-status" id="status">Ready</span>
428
+ </div>
429
+ </header>
430
+
431
+ <!-- Feature toolbar — buttons appended by public/features/*.mjs modules. -->
432
+ <div class="t1toolbar" id="t1toolbar" role="toolbar" aria-label="Features"></div>
433
+ <main class="terminal-container">
434
+ <div id="terminal"></div>
435
+ <!-- Shown instead of the terminal when no shell is open: what happened, and
436
+ the one way forward. A shell is never started on the person's behalf. -->
437
+ <div class="session-empty" id="session-empty" hidden>
438
+ <h2 id="session-empty-title">No shell is open</h2>
439
+ <p id="session-empty-detail"></p>
440
+ <pre class="session-empty-output" id="session-empty-output" hidden></pre>
441
+ <button id="session-empty-start" type="button">Start a shell</button>
442
+ </div>
443
+ </main>
444
+
445
+ <!-- iPhone key bar: compact single row of essentials. -->
446
+ <div class="keybar iphone" id="keybarIphone" role="toolbar" aria-label="Control keys"></div>
447
+ <!-- iPad key bar: wide — modifiers, navigation, arrows, symbols. -->
448
+ <div class="keybar ipad" id="keybarIpad" role="toolbar" aria-label="Control keys"></div>
449
+
450
+ <footer class="terminal-footer">
451
+ <span id="footerMeta">Your shell, in focus</span>
452
+ <span id="sessionInfo"></span>
453
+ </footer>
454
+ </div>
455
+
456
+ <!-- Settings modal -->
457
+ <div id="settingsModal" role="dialog" aria-label="Settings">
458
+ <div class="settings-panel">
459
+ <div class="settings-dock-bar">
460
+ <div class="settings-heading">
461
+ <h2>Settings</h2>
462
+ <p class="settings-version" data-app-version-label>Townmouse</p>
463
+ </div>
464
+ <button id="settingsCloseTop" type="button">Done</button>
465
+ </div>
466
+ <div class="settings-row">
467
+ <label for="styleSelect">Terminal style</label>
468
+ <select id="styleSelect">
469
+ <option value="default">Townmouse (default)</option>
470
+ <option value="floyd">Floyd TTY Bridge</option>
471
+ </select>
472
+ </div>
473
+ <div class="settings-row">
474
+ <label for="themeSelect">Color theme</label>
475
+ <select id="themeSelect"></select>
476
+ </div>
477
+ <div class="settings-section" role="group" aria-labelledby="voiceHeading">
478
+ <h3 id="voiceHeading">Voice / speech-to-text</h3>
479
+ <div class="settings-row">
480
+ <label for="voiceCommand">STT command</label>
481
+ <input id="voiceCommand" type="text" placeholder="whisper or /path/to/whisper" autocomplete="off" spellcheck="false">
482
+ </div>
483
+ <div class="settings-row">
484
+ <label for="voiceModel">Voice model</label>
485
+ <input id="voiceModel" type="text" placeholder="tiny.en, medium, or model path" autocomplete="off" spellcheck="false">
486
+ </div>
487
+ <div class="settings-row">
488
+ <label for="voiceLanguage">Language</label>
489
+ <input id="voiceLanguage" type="text" placeholder="en or auto" autocomplete="off" spellcheck="false">
490
+ </div>
491
+ <details class="settings-advanced">
492
+ <summary>Advanced argument template</summary>
493
+ <div class="settings-row">
494
+ <label for="voiceArgs">Arguments</label>
495
+ <textarea id="voiceArgs" rows="4" spellcheck="false"></textarea>
496
+ </div>
497
+ </details>
498
+ <div class="settings-actions settings-voice-actions">
499
+ <span id="voiceStatus" role="status" aria-live="polite"></span>
500
+ <button id="voiceSave" type="button">Save voice settings</button>
501
+ </div>
502
+ </div>
503
+ <div class="settings-actions">
504
+ <button id="settingsClose" type="button">Done</button>
505
+ </div>
506
+ </div>
507
+ </div>
508
+
509
+ <script type="module">
510
+ import { Terminal } from '/node_modules/@xterm/xterm/lib/xterm.mjs';
511
+ import { FitAddon } from '/node_modules/@xterm/addon-fit/lib/addon-fit.mjs';
512
+ import { WebLinksAddon } from '/node_modules/@xterm/addon-web-links/lib/addon-web-links.mjs';
513
+ import { InputGuard, bindInputGuard } from './input-guard.mjs';
514
+
515
+ // ── Theme catalog ─────────────────────────────────────────────────────────
516
+ // Stable preference keys map to calm studio palettes. Existing saved choices
517
+ // remain valid without exposing their historical palette names in the UI.
518
+ function studioTheme(name, bg, accent, light = false, canvas = false) {
519
+ const ui = {
520
+ bg, accent, fg: light ? '#252b31' : '#eceeea',
521
+ elevated: light ? '#efeee9' : '#242a30',
522
+ border: light ? '#737b82' : '#7d8992', muted: light ? '#515b64' : '#b5bdc4'
523
+ };
524
+ const ansi = light
525
+ ? { black:'#252b31', red:'#9c342c', green:'#356343', yellow:'#79561b', blue:'#345e8a', magenta:'#73536e', cyan:'#35696a', white:'#515b64' }
526
+ : { black:'#a8b0b7', red:'#e2a69e', green:'#b3c8b4', yellow:'#dcc38b', blue:'#a8bed4', magenta:'#cbb5c8', cyan:'#a4c5c4', white:'#d9deda' };
527
+ const bright = Object.fromEntries(Object.entries(ansi).map(([key, value]) => ['bright' + key[0].toUpperCase() + key.slice(1), value]));
528
+ return { name, ui, xterm: {
529
+ background: canvas ? 'rgba(20,27,24,1)' : bg, foreground: ui.fg,
530
+ cursor: accent, cursorAccent: bg, selectionBackground: light ? '#d9dde1' : '#424c54',
531
+ ...ansi, ...bright
532
+ } };
533
+ }
534
+ const THEMES = {
535
+ 'tokyo-night': studioTheme('Graphite Studio', '#14171b', '#d6ad68'),
536
+ 'absolute-void': studioTheme('Obsidian', '#090b0e', '#d2b887'),
537
+ 'matrix': studioTheme('Evergreen', '#141b18', '#a8c4b1', false, true),
538
+ 'dracula': studioTheme('Slate', '#171c24', '#b4becf'),
539
+ 'gruvbox': studioTheme('Warm Graphite', '#1b1916', '#d8b47e'),
540
+ 'nord': studioTheme('Steel', '#1a2027', '#adc0d0'),
541
+ 'catppuccin': studioTheme('Charcoal', '#202024', '#c3b6b0'),
542
+ 'solarized-dark': studioTheme('Deep Ink', '#111b23', '#9ebfcb'),
543
+ 'solarized-light': studioTheme('Paper', '#faf9f5', '#6d491a', true),
544
+ 'monokai': studioTheme('Sepia', '#201d18', '#d3bd97'),
545
+ 'one-dark': studioTheme('Carbon', '#15191c', '#b3c4bc'),
546
+ 'github-dark': studioTheme('Midnight', '#10161c', '#adbfce')
547
+ };
548
+
549
+ const THEME_ORDER = ['tokyo-night','absolute-void','matrix','dracula','gruvbox','nord','catppuccin','solarized-dark','solarized-light','monokai','one-dark','github-dark'];
550
+ const STYLES = { 'default': "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', monospace", 'floyd': "ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace" };
551
+
552
+ const DEFAULT_THEME = 'tokyo-night';
553
+ const DEFAULT_STYLE = 'default';
554
+ const LS_THEME = 'terminalone.theme';
555
+ const LS_STYLE = 'terminalone.style';
556
+ // The shell this browser was last viewing. Each tab also keeps its own.
557
+ const LS_SESSION = 'terminalone.sessionId';
558
+ const LS_EPOCH = 'terminalone.epoch';
559
+ const SS_VIEWING = 'terminalone.viewing';
560
+ const SS_EPOCH = 'terminalone.epoch';
561
+ const SS_SHELLLESS = 'terminalone.shellless';
562
+ const SS_ACTIVATION = 'terminalone.activation';
563
+ const SS_NOTICE = 'terminalone.notice';
564
+ // An agent's "show this session" request is followed only while this fresh.
565
+ const ACTIVATION_TTL_MS = 60 * 1000;
566
+ // A notice about a restart survives the reload the page does to refresh its
567
+ // owner session, but not for long.
568
+ const NOTICE_TTL_MS = 2 * 60 * 1000;
569
+
570
+ // ── State ───────────────────────────────────────────────────────────────
571
+ let ws = null;
572
+ let term = null;
573
+ let fitAddon = null;
574
+ let reconnectAttempts = 0;
575
+ let reconnectTimer = null;
576
+ // No resize may reach the server before the first ready/shell handshake. A
577
+ // fit on the fresh page would otherwise overwrite the old PTY dimensions and
578
+ // hide the fact that resume is crossing widths.
579
+ let sessionReady = false;
580
+ let userInitiatedClose = false;
581
+ let currentSessionId = null;
582
+ // Shell sessions (see "Shell sessions" below). The server's list is the only
583
+ // record of which shells exist; this window remembers the one it views.
584
+ let currentSession = null; // how the server last described that shell
585
+ let sessionList = [];
586
+ let sessionMax = 0;
587
+ let sessionKnown = false; // the server has described its current run
588
+ let knownEpoch = ssGet(SS_EPOCH) || lsGet(LS_EPOCH, null);
589
+ // connecting: asking for a shell. live: viewing one. ended: no shell, by
590
+ // nobody's accident, with one clear action.
591
+ let viewerState = 'connecting';
592
+ let viewerResumed = false; // the viewed shell came back from the server
593
+ let attachRequest = null; // what the opening socket should ask for
594
+ let lastAttach = null; // the last such request, kept for its answer
595
+ let pendingNotice = null; // said once the next shell is up
596
+ let noticeShown = false; // once per document load
597
+ let closingOwn = null; // the session this window is closing itself
598
+ let suppressAutoFocus = false; // one-shot: the next terminal must not take focus
599
+ let commandSeq = 0;
600
+ const pendingCommands = new Map();
601
+ let currentTheme = DEFAULT_THEME;
602
+ let currentStyle = DEFAULT_STYLE;
603
+ let rain = null; // lazily created digital-rain controller
604
+ let fitTimer = null;
605
+ // Non-null while replaying a resumed session's old-width buffer. The xterm
606
+ // stays at the PTY's old dimensions so wrapped lines and cursor addressing
607
+ // survive; fitting waits until the replay-end marker arrives.
608
+ let resumeReplay = null;
609
+ let replayEnded = false;
610
+ let replayPending = 0;
611
+ let postReplayOutput = [];
612
+ let terminalResourceDisposers = [];
613
+
614
+ // Module-level input sender. initTerminal() (which owns the dictation guard
615
+ // and the real sendInput closure) sets this so key-bar buttons outside the
616
+ // closure can emit control sequences.
617
+ let sendInputFn = null;
618
+ // Modifier toggle state for the on-screen key bar (Ctrl / Alt as sticky).
619
+ let modState = { ctrl: false, alt: false };
620
+
621
+ // File/image drops become a server-side attachment plus a shell-quoted path
622
+ // in the terminal. Never paste a data: URI or base64 stream into the PTY.
623
+ let attachmentDropBound = false;
624
+ function shellQuotePath(value) {
625
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
626
+ }
627
+ async function uploadTerminalAttachment(file) {
628
+ const response = await fetch('/api/attachments', {
629
+ method: 'POST',
630
+ headers: {
631
+ 'Content-Type': file.type || 'application/octet-stream',
632
+ 'X-Filename': encodeURIComponent(file.name || 'attachment')
633
+ },
634
+ body: file
635
+ });
636
+ let payload = null;
637
+ try { payload = await response.json(); } catch (_) { payload = null; }
638
+ if (!response.ok) throw new Error((payload && payload.error) || `Upload failed (${response.status}).`);
639
+ return payload;
640
+ }
641
+ function bindAttachmentDrop() {
642
+ if (attachmentDropBound) return;
643
+ const host = document.getElementById('terminal');
644
+ if (!host) return;
645
+ attachmentDropBound = true;
646
+ const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes('Files');
647
+ host.addEventListener('dragover', (event) => {
648
+ if (!hasFiles(event)) return;
649
+ event.preventDefault();
650
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
651
+ });
652
+ document.addEventListener('dragover', (event) => {
653
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
654
+ }, true);
655
+ document.addEventListener('drop', (event) => {
656
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
657
+ }, true);
658
+ host.addEventListener('drop', async (event) => {
659
+ if (!event.dataTransfer?.files?.length) return;
660
+ event.preventDefault();
661
+ event.stopPropagation();
662
+ for (const file of Array.from(event.dataTransfer.files)) {
663
+ try {
664
+ const attachment = await uploadTerminalAttachment(file);
665
+ if (sendInputFn) sendInputFn(`${shellQuotePath(attachment.path)} `);
666
+ showBanner(`Attached ${file.name}`, 'info');
667
+ } catch (error) {
668
+ showBanner(error.message || `Could not attach ${file.name}.`, 'error');
669
+ }
670
+ }
671
+ });
672
+ // xterm's helper-textarea paste handler stops propagation, so capture at
673
+ // document level, before it sees the event, and handle clipboard files.
674
+ document.addEventListener('paste', async (event) => {
675
+ const target = event.target;
676
+ if (!target || !target.closest || !target.closest('#terminal')) return;
677
+ const files = Array.from(event.clipboardData?.items || [])
678
+ .filter((item) => item.kind === 'file')
679
+ .map((item) => item.getAsFile())
680
+ .filter(Boolean);
681
+ if (!files.length) return;
682
+ event.preventDefault();
683
+ event.stopImmediatePropagation();
684
+ for (const file of files) {
685
+ try {
686
+ const attachment = await uploadTerminalAttachment(file);
687
+ if (sendInputFn) sendInputFn(`${shellQuotePath(attachment.path)} `);
688
+ showBanner(`Attached ${file.name}`, 'info');
689
+ } catch (error) {
690
+ showBanner(error.message || `Could not attach ${file.name}.`, 'error');
691
+ }
692
+ }
693
+ }, true);
694
+ }
695
+
696
+ const $ = (sel) => document.querySelector(sel);
697
+
698
+ function addTerminalResource(disposer) {
699
+ if (!disposer) return;
700
+ if (typeof disposer === 'function') {
701
+ terminalResourceDisposers.push(disposer);
702
+ } else if (typeof disposer.dispose === 'function') {
703
+ terminalResourceDisposers.push(() => disposer.dispose());
704
+ }
705
+ }
706
+
707
+ function cleanupTerminalResources() {
708
+ if (fitTimer) {
709
+ clearTimeout(fitTimer);
710
+ fitTimer = null;
711
+ }
712
+ const disposers = terminalResourceDisposers.splice(0).reverse();
713
+ for (const dispose of disposers) {
714
+ try { dispose(); } catch (_) {}
715
+ }
716
+ }
717
+
718
+ // ── Settings persistence ──────────────────────────────────────────────────
719
+ function lsGet(key, fallback) {
720
+ try { const v = localStorage.getItem(key); return v == null ? fallback : v; } catch (_) { return fallback; }
721
+ }
722
+ function lsSet(key, value) {
723
+ try { localStorage.setItem(key, value); } catch (_) {}
724
+ }
725
+ function lsDel(key) {
726
+ try { localStorage.removeItem(key); } catch (_) {}
727
+ }
728
+ // Per-tab storage: a second tab keeps its own shell rather than inheriting
729
+ // the first tab's.
730
+ function ssGet(key) {
731
+ try { return sessionStorage.getItem(key); } catch (_) { return null; }
732
+ }
733
+ function ssSet(key, value) {
734
+ try { sessionStorage.setItem(key, value); } catch (_) {}
735
+ }
736
+ function ssDel(key) {
737
+ try { sessionStorage.removeItem(key); } catch (_) {}
738
+ }
739
+
740
+ // ── Device detection (iPhone vs iPad vs desktop) ──────────────────────────
741
+ // iPadOS 13+ requests desktop sites and reports platform 'MacIntel' with a
742
+ // touch screen, so the MacIntel+maxTouchPoints heuristic is required in
743
+ // addition to the legacy /iPad/ UA string.
744
+ function detectDevice() {
745
+ const ua = navigator.userAgent || '';
746
+ const isIPad = /iPad/.test(ua) || (navigator.platform === 'MacIntel' && (navigator.maxTouchPoints || 0) > 1);
747
+ const isIPhone = /iPhone|iPod/.test(ua);
748
+ if (isIPad) return 'ipad';
749
+ if (isIPhone) return 'iphone';
750
+ // Viewport/input fallback for touch browsers whose UA is not Apple.
751
+ if (window.matchMedia && window.matchMedia('(pointer: coarse)').matches) {
752
+ const short = Math.min(window.innerWidth, window.innerHeight);
753
+ if (short < 700) return 'iphone';
754
+ if (short < 1100) return 'ipad';
755
+ }
756
+ return 'desktop';
757
+ }
758
+
759
+ // ── Digital rain (ported from VOID MatrixRain.tsx) ─────────────────────────
760
+ function createRain(canvas) {
761
+ return { start() { canvas.getContext('2d')?.clearRect(0, 0, canvas.width, canvas.height); }, stop() {} };
762
+ }
763
+
764
+ function setRainActive(active) {
765
+ const canvas = $('#fxCanvas');
766
+ if (active) {
767
+ if (!rain) rain = createRain(canvas);
768
+ rain.start();
769
+ } else if (rain) {
770
+ rain.stop();
771
+ }
772
+ }
773
+
774
+ // ── Apply theme / style ────────────────────────────────────────────────────
775
+ function applyTheme(id) {
776
+ if (!THEMES[id]) id = DEFAULT_THEME;
777
+ currentTheme = id;
778
+ const t = THEMES[id];
779
+ const root = document.documentElement.style;
780
+ root.setProperty('--ui-bg', t.ui.bg);
781
+ root.setProperty('--ui-fg', t.ui.fg);
782
+ root.setProperty('--ui-elevated', t.ui.elevated);
783
+ root.setProperty('--ui-border', t.ui.border);
784
+ root.setProperty('--ui-accent', t.ui.accent);
785
+ root.setProperty('--ui-muted', t.ui.muted);
786
+ root.setProperty('--ui-on-accent', t.ui.bg);
787
+ root.setProperty('--ui-danger', id === 'solarized-light' ? '#9c342c' : '#e2a69e');
788
+ root.setProperty('--ui-warning', id === 'solarized-light' ? '#79561b' : '#dcc38b');
789
+ document.querySelector('meta[name="theme-color"]')?.setAttribute('content', t.ui.bg);
790
+ document.body.dataset.theme = id;
791
+ if (term) term.options.theme = t.xterm;
792
+ setRainActive(id === 'matrix');
793
+ lsSet(LS_THEME, id);
794
+ }
795
+
796
+ function applyStyle(id) {
797
+ if (!STYLES[id]) id = DEFAULT_STYLE;
798
+ currentStyle = id;
799
+ document.body.dataset.style = id;
800
+ if (term) { term.options.fontFamily = STYLES[id]; scheduleFit(); }
801
+ lsSet(LS_STYLE, id);
802
+ }
803
+
804
+ // ── UI feedback helpers ────────────────────────────────────────────────────
805
+ function showBanner(msg, type = 'error', options = {}) {
806
+ const banner = $('#banner');
807
+ banner.textContent = '';
808
+ const text = document.createElement('span');
809
+ text.className = 'banner-text';
810
+ text.textContent = msg;
811
+ banner.append(text);
812
+ if (options.action) {
813
+ const action = document.createElement('button');
814
+ action.type = 'button';
815
+ action.className = 'banner-action';
816
+ action.textContent = options.action.label;
817
+ action.addEventListener('click', options.action.run);
818
+ banner.append(action);
819
+ }
820
+ if (options.dismissible) {
821
+ const dismiss = document.createElement('button');
822
+ dismiss.type = 'button';
823
+ dismiss.className = 'banner-dismiss';
824
+ dismiss.textContent = 'Dismiss';
825
+ // A notice the person has read must not come back on the next load.
826
+ dismiss.addEventListener('click', () => { ssDel(SS_NOTICE); hideBanner(); });
827
+ banner.append(dismiss);
828
+ }
829
+ banner.className = `banner ${type}`;
830
+ // hideBanner writes an inline display:none that would otherwise outrank
831
+ // every .banner.error/.warn rule and keep later banners invisible.
832
+ banner.style.display = '';
833
+ }
834
+
835
+ function hideBanner() {
836
+ $('#banner').className = 'banner';
837
+ $('#banner').style.display = 'none';
838
+ }
839
+
840
+ function updateStatus(text, state = 'neutral') {
841
+ const status = $('#status');
842
+ status.textContent = text;
843
+ status.className = `terminal-status ${state}`;
844
+ const dot = $('#statusDot');
845
+ if (dot) dot.className = `status-dot ${state === 'connected' ? 'connected' : state === 'error' ? 'error' : state === 'neutral' ? '' : 'connecting'}`;
846
+ }
847
+
848
+ function setFooter(text) { $('#footerMeta').textContent = text; }
849
+ function setSessionInfo(text, sessionId) {
850
+ const el = $('#sessionInfo');
851
+ el.textContent = text;
852
+ if (sessionId) el.dataset.sessionId = sessionId;
853
+ else if (!text) delete el.dataset.sessionId;
854
+ }
855
+
856
+ function scheduleFit(delay = 0) {
857
+ if (fitTimer) clearTimeout(fitTimer);
858
+ fitTimer = window.setTimeout(() => {
859
+ fitTimer = null;
860
+ if (!fitAddon || !term || resumeReplay) return;
861
+ try { fitAddon.fit(); } catch (_) {}
862
+ }, delay);
863
+ }
864
+
865
+ // term.write() parses asynchronously. Fit only after every replay chunk has
866
+ // actually landed, or xterm reflows bytes that were still queued for the old
867
+ // width. Output that arrived after replay-end is buffered until the fit.
868
+ function finishReplayIfReady() {
869
+ if (!resumeReplay || !replayEnded || replayPending > 0) return;
870
+ resumeReplay = null;
871
+ replayEnded = false;
872
+ if (fitAddon && term) {
873
+ try { fitAddon.fit(); } catch (_) {}
874
+ }
875
+ const queued = postReplayOutput;
876
+ postReplayOutput = [];
877
+ for (const chunk of queued) term?.write(chunk);
878
+ }
879
+
880
+ // ── On-screen key bar ─────────────────────────────────────────────────────
881
+ // xterm control sequences for the keys missing on iOS/iPadOS keyboards.
882
+ const SEQ = {
883
+ esc: '\x1b',
884
+ tab: '\t',
885
+ enter: '\r',
886
+ del: '\x7f',
887
+ ctrlB: '\x02',
888
+ up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
889
+ home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~'
890
+ };
891
+
892
+ function emitSeq(seq) {
893
+ if (!sendInputFn) return;
894
+ sendInputFn(seq);
895
+ // Sticky modifiers consume themselves on the next emit.
896
+ modState.ctrl = false;
897
+ modState.alt = false;
898
+ syncModButtons();
899
+ }
900
+
901
+ /** Map a literal character to its Ctrl / Alt combination if a mod is sticky. */
902
+ function emitLiteral(ch) {
903
+ if (!sendInputFn) return;
904
+ let out = ch;
905
+ if (modState.ctrl && ch.length === 1) {
906
+ // Ctrl+X = X & 0x1f (ASCII control code).
907
+ out = String.fromCharCode(ch.charCodeAt(0) & 0x1f);
908
+ }
909
+ if (modState.alt && out.length === 1) {
910
+ // Alt prefix in xterm: ESC then the char.
911
+ out = '\x1b' + out;
912
+ }
913
+ sendInputFn(out);
914
+ modState.ctrl = false;
915
+ modState.alt = false;
916
+ syncModButtons();
917
+ }
918
+
919
+ function syncModButtons() {
920
+ document.querySelectorAll('.kb-key.toggle[data-mod]').forEach((b) => {
921
+ b.classList.toggle('active', !!modState[b.dataset.mod]);
922
+ });
923
+ }
924
+
925
+ /** Build a key element. kind: 'seq' | 'literal' | 'toggle' | 'special'. */
926
+ function makeKey(label, opts = {}) {
927
+ const el = document.createElement('button');
928
+ el.type = 'button';
929
+ el.className = 'kb-key';
930
+ el.textContent = label;
931
+ if (opts.title) el.title = opts.title;
932
+ if (opts.kind === 'toggle') {
933
+ el.classList.add('toggle');
934
+ if (opts.mod) el.dataset.mod = opts.mod;
935
+ el.addEventListener('click', () => {
936
+ const m = opts.mod;
937
+ if (!m) return;
938
+ // Toggling one mod clears the other (single sticky mod at a time).
939
+ modState[m] = !modState[m];
940
+ Object.keys(modState).forEach((k) => { if (k !== m) modState[k] = false; });
941
+ syncModButtons();
942
+ });
943
+ } else if (opts.kind === 'special' && opts.special === 'del') {
944
+ el.addEventListener('click', () => emitSeq(SEQ.del));
945
+ } else if (opts.seq) {
946
+ el.addEventListener('click', () => emitSeq(opts.seq));
947
+ } else if (opts.literal != null) {
948
+ el.addEventListener('click', () => emitLiteral(opts.literal));
949
+ }
950
+ return el;
951
+ }
952
+
953
+ function makeArrowPad() {
954
+ const wrap = document.createElement('div');
955
+ wrap.className = 'kb-arrows';
956
+ const top = document.createElement('div'); top.className = 'kb-row';
957
+ top.appendChild(makeKey('↑', { seq: SEQ.up, title: 'Up' }));
958
+ const mid = document.createElement('div'); mid.className = 'kb-row';
959
+ mid.appendChild(makeKey('←', { seq: SEQ.left, title: 'Left' }));
960
+ mid.appendChild(makeKey('↓', { seq: SEQ.down, title: 'Down' }));
961
+ mid.appendChild(makeKey('→', { seq: SEQ.right, title: 'Right' }));
962
+ wrap.appendChild(top);
963
+ wrap.appendChild(mid);
964
+ return wrap;
965
+ }
966
+
967
+ function makeGroup(children) {
968
+ const g = document.createElement('div');
969
+ g.className = 'kb-group';
970
+ children.forEach((c) => g.appendChild(c));
971
+ return g;
972
+ }
973
+
974
+ function buildKeyBars() {
975
+ const device = detectDevice();
976
+ document.body.dataset.device = device;
977
+ const iphone = $('#keybarIphone');
978
+ const ipad = $('#keybarIpad');
979
+
980
+ // iPhone: compact single row — essentials only.
981
+ iphone.innerHTML = '';
982
+ if (device === 'iphone') {
983
+ const modifiers = makeGroup([
984
+ makeKey('ESC', { seq: SEQ.esc, title: 'Escape' }),
985
+ makeKey('TAB', { seq: SEQ.tab, title: 'Tab' }),
986
+ makeKey('ENTER', { seq: SEQ.enter, title: 'Enter' }),
987
+ makeKey('Ctrl+b', { seq: SEQ.ctrlB, title: 'Send Ctrl+b to herdr' }),
988
+ makeKey('CTRL', { kind: 'toggle', mod: 'ctrl', title: 'Ctrl (sticky)' })
989
+ ]);
990
+ modifiers.dataset.kb = 'mod';
991
+ const arrows = makeGroup([
992
+ makeKey('←', { seq: SEQ.left }),
993
+ makeKey('↓', { seq: SEQ.down }),
994
+ makeKey('↑', { seq: SEQ.up }),
995
+ makeKey('→', { seq: SEQ.right })
996
+ ]);
997
+ arrows.dataset.kb = 'arrows';
998
+ const symbols = makeGroup([
999
+ makeKey('~', { literal: '~' }),
1000
+ makeKey('/', { literal: '/' }),
1001
+ makeKey('|', { literal: '|' }),
1002
+ makeKey('-', { literal: '-' })
1003
+ ]);
1004
+ symbols.dataset.kb = 'symbols';
1005
+ iphone.append(modifiers, arrows, symbols);
1006
+ }
1007
+
1008
+ // iPad: two deliberate rows — modifiers/navigation, then arrows/symbols.
1009
+ ipad.innerHTML = '';
1010
+ if (device === 'ipad') {
1011
+ const row1 = document.createElement('div');
1012
+ row1.className = 'kb-grid-row';
1013
+ const modifiers = makeGroup([
1014
+ makeKey('ESC', { seq: SEQ.esc, title: 'Escape' }),
1015
+ makeKey('TAB', { seq: SEQ.tab, title: 'Tab' }),
1016
+ makeKey('ENTER', { seq: SEQ.enter, title: 'Enter' }),
1017
+ makeKey('Ctrl+b', { seq: SEQ.ctrlB, title: 'Send Ctrl+b to herdr' }),
1018
+ makeKey('CTRL', { kind: 'toggle', mod: 'ctrl', title: 'Ctrl (sticky)' }),
1019
+ makeKey('ALT', { kind: 'toggle', mod: 'alt', title: 'Alt / Meta (sticky)' })
1020
+ ]);
1021
+ modifiers.dataset.kb = 'mod';
1022
+ const navigation = makeGroup([
1023
+ makeKey('HOME', { seq: SEQ.home }),
1024
+ makeKey('END', { seq: SEQ.end }),
1025
+ makeKey('PGUP', { seq: SEQ.pgup }),
1026
+ makeKey('PGDN', { seq: SEQ.pgdn })
1027
+ ]);
1028
+ navigation.dataset.kb = 'nav';
1029
+ row1.append(modifiers, navigation);
1030
+
1031
+ const row2 = document.createElement('div');
1032
+ row2.className = 'kb-grid-row';
1033
+ const arrows = document.createElement('div');
1034
+ arrows.className = 'kb-arrow-cluster';
1035
+ arrows.dataset.kb = 'arrows';
1036
+ const blank = () => {
1037
+ const spacer = document.createElement('span');
1038
+ spacer.className = 'kb-arrow-empty';
1039
+ spacer.setAttribute('aria-hidden', 'true');
1040
+ return spacer;
1041
+ };
1042
+ arrows.append(
1043
+ blank(),
1044
+ makeKey('↑', { seq: SEQ.up, title: 'Up' }),
1045
+ blank(),
1046
+ makeKey('←', { seq: SEQ.left, title: 'Left' }),
1047
+ makeKey('↓', { seq: SEQ.down, title: 'Down' }),
1048
+ makeKey('→', { seq: SEQ.right, title: 'Right' })
1049
+ );
1050
+ const symbols = makeGroup([
1051
+ makeKey('~', { literal: '~' }),
1052
+ makeKey('/', { literal: '/' }),
1053
+ makeKey('|', { literal: '|' }),
1054
+ makeKey('-', { literal: '-' }),
1055
+ makeKey('DEL', { kind: 'special', special: 'del', title: 'Delete' })
1056
+ ]);
1057
+ symbols.dataset.kb = 'symbols';
1058
+ row2.append(arrows, symbols);
1059
+ ipad.append(row1, row2);
1060
+ }
1061
+ }
1062
+
1063
+ // ── Two-finger touch scroll (native iOS feel with momentum) ────────────────
1064
+ // One-finger touches pass through to xterm (text selection etc.). Two fingers
1065
+ // scroll the scrollback with inertial momentum on release, like a native iOS
1066
+ // scroll view.
1067
+ function initTouchScroll() {
1068
+ if (!term) return;
1069
+ const screen = term.element;
1070
+ if (!screen) return;
1071
+ let scrolling = false;
1072
+ let lastY = 0;
1073
+ let velocity = 0;
1074
+ let lastMoveTs = 0;
1075
+ let momentumRaf = 0;
1076
+ let lineHeight = 0;
1077
+
1078
+ function getLineHeight() {
1079
+ if (lineHeight > 0) return lineHeight;
1080
+ const rows = screen.querySelector('.xterm-rows');
1081
+ if (rows) {
1082
+ const lh = parseFloat(getComputedStyle(rows).lineHeight) || 0;
1083
+ if (lh > 0) { lineHeight = lh; return lineHeight; }
1084
+ }
1085
+ // Fallback: derive from terminal font size + line height setting.
1086
+ lineHeight = (term.options.fontSize || 14) * (term.options.lineHeight || 1.2);
1087
+ return lineHeight;
1088
+ }
1089
+
1090
+ function avgY(touches) {
1091
+ let sum = 0;
1092
+ for (let i = 0; i < touches.length; i += 1) sum += touches[i].clientY;
1093
+ return sum / touches.length;
1094
+ }
1095
+
1096
+ function stopMomentum() {
1097
+ if (momentumRaf) { cancelAnimationFrame(momentumRaf); momentumRaf = 0; }
1098
+ }
1099
+
1100
+ function momentumStep() {
1101
+ if (Math.abs(velocity) < 0.5) { momentumRaf = 0; return; }
1102
+ const lh = getLineHeight();
1103
+ const lines = Math.round(velocity / lh);
1104
+ if (lines !== 0 && term) term.scrollLines(lines);
1105
+ velocity *= 0.92; // decay
1106
+ momentumRaf = requestAnimationFrame(momentumStep);
1107
+ }
1108
+
1109
+ const onTouchStart = (e) => {
1110
+ if (e.touches.length !== 2) return;
1111
+ scrolling = true;
1112
+ stopMomentum();
1113
+ lastY = avgY(e.touches);
1114
+ velocity = 0;
1115
+ lastMoveTs = Date.now();
1116
+ };
1117
+
1118
+ const onTouchMove = (e) => {
1119
+ if (!scrolling) return;
1120
+ e.preventDefault();
1121
+ const cur = avgY(e.touches);
1122
+ const dy = lastY - cur; // up-drag (cur smaller) → scroll back (positive)
1123
+ const lh = getLineHeight();
1124
+ const lines = Math.round(dy / lh);
1125
+ if (lines !== 0 && term) term.scrollLines(lines);
1126
+ const now = Date.now();
1127
+ const dt = Math.max(1, now - lastMoveTs);
1128
+ velocity = dy / dt * 16; // px per ~frame
1129
+ lastY = cur;
1130
+ lastMoveTs = now;
1131
+ };
1132
+
1133
+ const endScroll = (e) => {
1134
+ if (!scrolling) return;
1135
+ if (e.touches && e.touches.length >= 2) return; // still two fingers down
1136
+ scrolling = false;
1137
+ if (!window.matchMedia || !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
1138
+ momentumRaf = requestAnimationFrame(momentumStep);
1139
+ }
1140
+ };
1141
+ screen.addEventListener('touchstart', onTouchStart, { passive: true });
1142
+ screen.addEventListener('touchmove', onTouchMove, { passive: false });
1143
+ screen.addEventListener('touchend', endScroll, { passive: true });
1144
+ screen.addEventListener('touchcancel', endScroll, { passive: true });
1145
+ return () => {
1146
+ stopMomentum();
1147
+ screen.removeEventListener('touchstart', onTouchStart);
1148
+ screen.removeEventListener('touchmove', onTouchMove);
1149
+ screen.removeEventListener('touchend', endScroll);
1150
+ screen.removeEventListener('touchcancel', endScroll);
1151
+ };
1152
+ }
1153
+
1154
+ // ── Terminal ────────────────────────────────────────────────────────────────
1155
+ // A phone at 14px gets about 41 columns, which splits ordinary prose inside
1156
+ // words. Use a narrower default on narrow screens unless the user chose a
1157
+ // size with A-/A+, the shortcut, or pinch.
1158
+ function defaultTerminalFontSize() {
1159
+ const stored = lsGet('terminalone.fontSize', null);
1160
+ if (stored) {
1161
+ const parsed = parseInt(stored, 10);
1162
+ if (Number.isFinite(parsed)) return parsed;
1163
+ }
1164
+ const width = window.innerWidth;
1165
+ if (width <= 430) return 11;
1166
+ if (width <= 820) return 12;
1167
+ return 14;
1168
+ }
1169
+
1170
+ function initTerminal() {
1171
+ cleanupTerminalResources();
1172
+ sessionReady = false;
1173
+ showSessionEmpty(false);
1174
+ resumeReplay = null;
1175
+ replayEnded = false;
1176
+ replayPending = 0;
1177
+ postReplayOutput = [];
1178
+ if (term) {
1179
+ try { term.dispose(); } catch (_) {}
1180
+ }
1181
+
1182
+ term = new Terminal({
1183
+ cursorBlink: true,
1184
+ cursorStyle: 'block',
1185
+ fontSize: defaultTerminalFontSize(),
1186
+ lineHeight: 1.2,
1187
+ fontFamily: STYLES[currentStyle],
1188
+ theme: THEMES[currentTheme].xterm,
1189
+ allowTransparency: true,
1190
+ minimumContrastRatio: 4.5,
1191
+ allowProposedApi: true,
1192
+ scrollback: 10000,
1193
+ convertEol: false
1194
+ });
1195
+
1196
+ fitAddon = new FitAddon();
1197
+ term.loadAddon(fitAddon);
1198
+ term.loadAddon(new WebLinksAddon());
1199
+ term.open($('#terminal'));
1200
+ try {
1201
+ term.parser.registerOscHandler(52, (data) => {
1202
+ const payload = String(data).split(';')[1] || '';
1203
+ if (payload && payload !== '?') {
1204
+ try {
1205
+ const text = atob(payload);
1206
+ if (text) navigator.clipboard?.writeText(text).catch(() => {});
1207
+ } catch (_) { /* malformed clipboard payload */ }
1208
+ }
1209
+ return true;
1210
+ });
1211
+ } catch (_) { /* older xterm without OSC handlers */ }
1212
+ // If resume already selected the old replay dimensions, do not fit to the
1213
+ // new viewport here; replay-end owns that transition.
1214
+ // The frame can land after this terminal was disposed (a quick switch, or
1215
+ // the last shell being closed), so check it is still here.
1216
+ requestAnimationFrame(() => { if (!resumeReplay && fitAddon) fitAddon.fit(); });
1217
+ // The grid is measured with whatever font is in place when the terminal is
1218
+ // opened, and measured again only when its font setting is set to a new
1219
+ // value. A web font that arrives after that leaves the grid with the
1220
+ // stand-in font's line spacing for good, and a later fit keeps it, because
1221
+ // a fit reuses the last measurement. So each time a font finishes loading,
1222
+ // set the font again with one more stand-in at the end of the stack (a new
1223
+ // value, never reached), which makes the terminal measure, and then fit.
1224
+ const refitForFont = () => {
1225
+ if (!term) return;
1226
+ term.options.fontFamily = `${STYLES[currentStyle]}, monospace`;
1227
+ scheduleFit();
1228
+ };
1229
+ if (document.fonts) {
1230
+ document.fonts.addEventListener('loadingdone', refitForFont);
1231
+ addTerminalResource(() => document.fonts.removeEventListener('loadingdone', refitForFont));
1232
+ document.fonts.ready.then(refitForFont).catch(() => {});
1233
+ }
1234
+
1235
+
1236
+ addTerminalResource(initTouchScroll());
1237
+
1238
+ // ── iOS dictation / typing guard ────────────────────────────────────────
1239
+ // Replaced buggy inline debounce (which overwrote fast keystrokes) with
1240
+ // InputGuard: single chars send immediately, duplicated onData events are
1241
+ // dropped, and iOS/IME cumulative partials send only the new suffix.
1242
+
1243
+ function sendInput(data) {
1244
+ if (ws && ws.readyState === WebSocket.OPEN) {
1245
+ ws.send(JSON.stringify({ type: 'input', data }));
1246
+ }
1247
+ }
1248
+ const guard = new InputGuard({ send: sendInput, identicalDedupeMs: 500 });
1249
+ // Expose the sender to the on-screen key bar (outside this closure).
1250
+ sendInputFn = (data) => guard.send(data);
1251
+ bindAttachmentDrop();
1252
+
1253
+ // While a resumed shell's earlier output is being replayed, the terminal's
1254
+ // answers to questions in that output must not be typed into the shell.
1255
+ addTerminalResource(bindInputGuard(term, guard, { ignoreGenerated: () => resumeReplay !== null }));
1256
+
1257
+ // Take focus on load where there is no touchscreen, so the very first
1258
+ // keypress reaches the terminal. A tablet would get its on-screen keyboard
1259
+ // opened uninvited, so those devices rely on the key-capture fallback above.
1260
+ // (Headless Chrome reports a coarse pointer, so maxTouchPoints is the
1261
+ // reliable signal here.)
1262
+ // A session an agent asked to show does not pull the keyboard out of
1263
+ // whatever the person was doing.
1264
+ const holdFocus = suppressAutoFocus;
1265
+ suppressAutoFocus = false;
1266
+ if (!navigator.maxTouchPoints && !holdFocus) {
1267
+ requestAnimationFrame(() => { try { term.focus(); } catch (_) {} });
1268
+ }
1269
+
1270
+ // A key typed while <body> has focus never reaches xterm, so the first press
1271
+ // was silently discarded and the user had to press it again. Capture the
1272
+ // first printable key at document level, focus the terminal, and deliver it.
1273
+ // Focusing only happens when the user actually types, so a touch device does
1274
+ // not have its on-screen keyboard opened for it.
1275
+ document.addEventListener('keydown', (event) => {
1276
+ const el = document.activeElement;
1277
+ if (el && el !== document.body) return;
1278
+ if (event.metaKey || event.ctrlKey || event.altKey) return;
1279
+ if (!event.key || event.key.length !== 1) return;
1280
+ try { term.focus(); } catch (_) {}
1281
+ sendInput(event.key);
1282
+ event.preventDefault();
1283
+ }, true);
1284
+
1285
+ addTerminalResource(term.onResize(({ cols, rows }) => {
1286
+ // While replaying, xterm is deliberately at the old PTY width. Sending
1287
+ // that as a resize would yank the live PTY back to the old width. Before
1288
+ // the first ready, a resize would also destroy the old dimensions resume
1289
+ // needs to detect a width change.
1290
+ if (!sessionReady || resumeReplay) return;
1291
+ if (ws && ws.readyState === WebSocket.OPEN) {
1292
+ ws.send(JSON.stringify({ type: 'resize', cols, rows }));
1293
+ }
1294
+ }));
1295
+
1296
+ const ro = new ResizeObserver(() => scheduleFit());
1297
+ ro.observe($('#terminal'));
1298
+ addTerminalResource(() => ro.disconnect());
1299
+ }
1300
+
1301
+ function handleServerMessage(msg) {
1302
+ switch (msg.type) {
1303
+ case 'ready': {
1304
+ sessionReady = true;
1305
+ currentSessionId = msg.sessionId;
1306
+ // A different epoch means the app itself was restarted since this window
1307
+ // last heard from it. That is worth saying; one closed shell is not.
1308
+ const restarted = Boolean(knownEpoch && msg.epoch && knownEpoch !== msg.epoch);
1309
+ if (msg.epoch) rememberEpoch(msg.epoch);
1310
+ if (restarted) { sessionList = []; sessionKnown = false; }
1311
+ currentSession = { id: msg.sessionId, name: msg.name || 'Shell', cwd: msg.cwd || '', command: msg.command || '' };
1312
+ viewerState = 'live';
1313
+ viewerResumed = Boolean(msg.resumed);
1314
+ closingOwn = null;
1315
+ rememberSession(msg.sessionId);
1316
+ if (msg.resumed) {
1317
+ // Replay the buffered output at the dimensions it was produced with,
1318
+ // then fit to this viewport after replay-end. Otherwise old wraps and
1319
+ // cursor-addressed lines are reflowed into fragments. A transcript replay
1320
+ // has no control codes, so fit first and write it at the final width.
1321
+ if (term && msg.transcript) {
1322
+ resumeReplay = { transcript: true };
1323
+ replayEnded = false;
1324
+ replayPending = 0;
1325
+ postReplayOutput = [];
1326
+ try {
1327
+ term.reset();
1328
+ if (fitAddon) fitAddon.fit();
1329
+ } catch (_) {
1330
+ resumeReplay = null;
1331
+ }
1332
+ } else if (term && Number.isFinite(msg.cols) && Number.isFinite(msg.rows)) {
1333
+ resumeReplay = { cols: msg.cols, rows: msg.rows };
1334
+ replayEnded = false;
1335
+ replayPending = 0;
1336
+ postReplayOutput = [];
1337
+ try {
1338
+ term.resize(msg.cols, msg.rows);
1339
+ } catch (_) {
1340
+ resumeReplay = null;
1341
+ }
1342
+ }
1343
+ updateStatus('Resumed', 'connected');
1344
+ setFooter(`Resumed · ${msg.cwd}`);
1345
+ } else {
1346
+ resumeReplay = null;
1347
+ replayEnded = false;
1348
+ replayPending = 0;
1349
+ postReplayOutput = [];
1350
+ updateStatus('Connected', 'connected');
1351
+ setFooter(`${msg.command} · ${msg.cwd}`);
1352
+ }
1353
+ setSessionInfo(`session ${msg.sessionId.slice(0, 8)}`, msg.sessionId);
1354
+ window.dispatchEvent(new CustomEvent('t1:session-ready', {
1355
+ detail: {
1356
+ command: msg.command, cwd: msg.cwd, resumed: !!msg.resumed,
1357
+ sessionId: msg.sessionId, name: currentSession.name, restarted
1358
+ }
1359
+ }));
1360
+ renderSessionChrome();
1361
+ showPendingNotice();
1362
+ break;
1363
+ }
1364
+ case 'sessions': {
1365
+ // The server's account of which shells exist, pushed whenever it changes.
1366
+ applySessionState(msg);
1367
+ break;
1368
+ }
1369
+ case 'session-ended': {
1370
+ onSessionEnded(msg.sessionId, msg.reason || 'closed', msg);
1371
+ break;
1372
+ }
1373
+ case 'result': {
1374
+ const pending = pendingCommands.get(msg.requestId);
1375
+ if (!pending) break;
1376
+ pendingCommands.delete(msg.requestId);
1377
+ pending.resolve(msg);
1378
+ break;
1379
+ }
1380
+ case 'output': {
1381
+ if (resumeReplay) {
1382
+ if (replayEnded) {
1383
+ postReplayOutput.push(msg.data);
1384
+ break;
1385
+ }
1386
+ replayPending += 1;
1387
+ term?.write(msg.data, () => {
1388
+ replayPending = Math.max(0, replayPending - 1);
1389
+ finishReplayIfReady();
1390
+ });
1391
+ break;
1392
+ }
1393
+ term?.write(msg.data);
1394
+ break;
1395
+ }
1396
+ case 'replay-end': {
1397
+ // The old-width buffer has been queued. Wait for xterm to parse it before
1398
+ // fitting; the resulting resize event tells the PTY its new dimensions.
1399
+ replayEnded = true;
1400
+ finishReplayIfReady();
1401
+ break;
1402
+ }
1403
+ case 'exit': {
1404
+ updateStatus(`Exited (code ${msg.code})`, 'error');
1405
+ setFooter(`Process exited · code ${msg.code}`);
1406
+ break;
1407
+ }
1408
+ case 'shell-reset': {
1409
+ // Wiping here erased a failing shell's own error message and made a
1410
+ // respawn storm look like a frozen terminal. Keep what the user saw.
1411
+ term?.write('\r\n\x1b[2m──── shell restarted ────\x1b[0m\r\n');
1412
+ updateStatus('Connected', 'connected');
1413
+ setFooter('Fresh shell — type to continue');
1414
+ break;
1415
+ }
1416
+ case 'resume-failed': {
1417
+ // The shell this window remembered is not on the server. What happens
1418
+ // next is decided from the server's real list and said out loud.
1419
+ resumeReplay = null;
1420
+ replayEnded = false;
1421
+ replayPending = 0;
1422
+ postReplayOutput = [];
1423
+ scheduleFit();
1424
+ onResumeFailed(msg);
1425
+ break;
1426
+ }
1427
+ case 'voice-ready': {
1428
+ window.dispatchEvent(new CustomEvent('t1:voice-ready', { detail: msg }));
1429
+ break;
1430
+ }
1431
+ case 'voice-transcript': {
1432
+ window.dispatchEvent(new CustomEvent('t1:voice-transcript', { detail: msg }));
1433
+ break;
1434
+ }
1435
+ case 'voice-error': {
1436
+ window.dispatchEvent(new CustomEvent('t1:voice-error', { detail: msg }));
1437
+ break;
1438
+ }
1439
+ case 'error': {
1440
+ const errText = `\r\n\x1b[31m[ERROR ${msg.code}]\x1b[0m ${msg.message}\r\n`;
1441
+ term?.write(errText);
1442
+ showBanner(`[${msg.code}] ${msg.message}`, 'error');
1443
+ updateStatus(msg.code, 'error');
1444
+ break;
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ // ── Shell sessions ─────────────────────────────────────────────────────────
1450
+ // The server keeps the list of shells. This window remembers the one it is
1451
+ // viewing and asks the server for it; the row, the title and the Sessions
1452
+ // list are drawn from what the server sends back. When the shell this window
1453
+ // is viewing is gone, the window says so and lands on a shell that exists,
1454
+ // or on one clear action. Nothing here starts a shell on the quiet.
1455
+
1456
+ function rememberEpoch(epoch) {
1457
+ knownEpoch = epoch;
1458
+ ssSet(SS_EPOCH, epoch);
1459
+ lsSet(LS_EPOCH, epoch);
1460
+ }
1461
+
1462
+ // The shell to ask for: this tab's own, else the browser's last, else none.
1463
+ function rememberedSession() {
1464
+ return ssGet(SS_VIEWING) || lsGet(LS_SESSION, null);
1465
+ }
1466
+
1467
+ function rememberSession(id) {
1468
+ if (id) {
1469
+ ssSet(SS_VIEWING, id);
1470
+ lsSet(LS_SESSION, id);
1471
+ ssDel(SS_SHELLLESS);
1472
+ } else {
1473
+ ssDel(SS_VIEWING);
1474
+ lsDel(LS_SESSION);
1475
+ }
1476
+ }
1477
+
1478
+ // What a newly opened socket should ask the server for.
1479
+ function planInitialAttach() {
1480
+ const id = rememberedSession();
1481
+ if (id) return { resume: id };
1482
+ // A window with no shell on purpose stays that way across a reload or a
1483
+ // reconnect. It never grows a shell by itself.
1484
+ if (viewerState === 'ended' || ssGet(SS_SHELLLESS) === '1') return { control: true };
1485
+ return { create: true };
1486
+ }
1487
+
1488
+ function sendOnSocket(payload) {
1489
+ if (ws && ws.readyState === WebSocket.OPEN) {
1490
+ ws.send(JSON.stringify(payload));
1491
+ return true;
1492
+ }
1493
+ return false;
1494
+ }
1495
+
1496
+ // A command the server answers by requestId, so its outcome can be shown
1497
+ // where it was asked instead of in the terminal.
1498
+ function sessionCommand(payload) {
1499
+ return new Promise((resolve, reject) => {
1500
+ if (!(ws && ws.readyState === WebSocket.OPEN)) {
1501
+ reject(new Error('Townmouse is not connected.'));
1502
+ return;
1503
+ }
1504
+ const requestId = `c${++commandSeq}`;
1505
+ pendingCommands.set(requestId, { resolve, reject });
1506
+ ws.send(JSON.stringify({ ...payload, requestId }));
1507
+ });
1508
+ }
1509
+
1510
+ function rejectPendingCommands(error) {
1511
+ for (const pending of pendingCommands.values()) pending.reject(error);
1512
+ pendingCommands.clear();
1513
+ }
1514
+
1515
+ // Stop using the current socket on purpose. The close that follows is this
1516
+ // window's own doing, so nothing may reconnect or start a shell from it.
1517
+ function abandonSocket() {
1518
+ if (reconnectTimer) {
1519
+ clearTimeout(reconnectTimer);
1520
+ reconnectTimer = null;
1521
+ }
1522
+ if (ws) {
1523
+ try { ws.onclose = null; ws.close(); } catch (_) {}
1524
+ }
1525
+ ws = null;
1526
+ rejectPendingCommands(new Error('The connection was closed.'));
1527
+ }
1528
+
1529
+ function disposeTerminal() {
1530
+ try { term?.dispose(); } catch (_) {}
1531
+ cleanupTerminalResources();
1532
+ term = null;
1533
+ fitAddon = null;
1534
+ sendInputFn = null;
1535
+ sessionReady = false;
1536
+ }
1537
+
1538
+ function focusTerminal() {
1539
+ try { term?.focus(); } catch (_) { /* no terminal */ }
1540
+ }
1541
+
1542
+ // The title names the shell this window is viewing, or nothing.
1543
+ function renderSessionChrome() {
1544
+ const label = document.getElementById('titleSession');
1545
+ if (label) label.textContent = viewerState === 'live' && currentSession ? ` / ${currentSession.name}` : '';
1546
+ }
1547
+
1548
+ function announceSessions() {
1549
+ window.dispatchEvent(new CustomEvent('t1:sessions-change', {
1550
+ detail: { sessions: sessionList.map((session) => ({ ...session })), max: sessionMax, state: viewerState }
1551
+ }));
1552
+ }
1553
+
1554
+ // Replaces the terminal while no shell is open. Pass nothing to bring the
1555
+ // terminal back.
1556
+ function showSessionEmpty(options) {
1557
+ const empty = document.getElementById('session-empty');
1558
+ const host = document.getElementById('terminal');
1559
+ if (!empty || !host) return;
1560
+ if (!options) {
1561
+ empty.hidden = true;
1562
+ host.hidden = false;
1563
+ return;
1564
+ }
1565
+ document.getElementById('session-empty-title').textContent = options.heading || 'No shell is open';
1566
+ document.getElementById('session-empty-detail').textContent = options.detail || '';
1567
+ const output = document.getElementById('session-empty-output');
1568
+ output.textContent = options.output || '';
1569
+ output.hidden = !options.output;
1570
+ host.hidden = true;
1571
+ empty.hidden = false;
1572
+ }
1573
+
1574
+ function showPendingNotice() {
1575
+ let text = pendingNotice;
1576
+ pendingNotice = null;
1577
+ let carried = false;
1578
+ if (!text && !noticeShown) {
1579
+ // A notice outlives the reload the page does to refresh its owner
1580
+ // session, once, until the person dismisses it or it gets old.
1581
+ try {
1582
+ const saved = JSON.parse(ssGet(SS_NOTICE) || 'null');
1583
+ if (saved && Date.now() - saved.at < NOTICE_TTL_MS) {
1584
+ text = saved.text;
1585
+ carried = true;
1586
+ }
1587
+ } catch (_) { /* no notice */ }
1588
+ }
1589
+ if (!text) return;
1590
+ if (carried) noticeShown = true;
1591
+ ssSet(SS_NOTICE, JSON.stringify({ text, at: Date.now() }));
1592
+ showBanner(text, 'info', { dismissible: true });
1593
+ }
1594
+
1595
+ // The server's account of which shells exist, in row order.
1596
+ function applySessionState(state) {
1597
+ if (!state || !Array.isArray(state.sessions)) return;
1598
+ if (state.epoch && state.epoch !== knownEpoch) {
1599
+ // A different run of the app: nothing it listed carried over.
1600
+ rememberEpoch(state.epoch);
1601
+ sessionList = [];
1602
+ sessionKnown = false;
1603
+ }
1604
+ const before = sessionList;
1605
+ const known = new Set(before.map((session) => session.id));
1606
+ sessionList = state.sessions;
1607
+ sessionMax = Number(state.max) || 0;
1608
+ const first = !sessionKnown;
1609
+ sessionKnown = true;
1610
+ if (viewerState === 'live' && currentSessionId) {
1611
+ const mine = sessionList.find((session) => session.id === currentSessionId);
1612
+ if (mine) {
1613
+ currentSession = mine;
1614
+ } else {
1615
+ // The server dropped the shell this window is viewing and its notice
1616
+ // did not arrive. It counts exactly like the notice.
1617
+ onSessionEnded(currentSessionId, 'closed', state);
1618
+ return;
1619
+ }
1620
+ }
1621
+ if (!first) {
1622
+ // An agent starting a shell while the person watches should not go unnoticed.
1623
+ for (const session of sessionList) {
1624
+ if (!known.has(session.id) && session.id !== currentSessionId && session.createdBy === 'agent') {
1625
+ T1.toast(`Agent started “${session.name}”`);
1626
+ }
1627
+ }
1628
+ }
1629
+ followActivation(state.activation);
1630
+ renderSessionChrome();
1631
+ announceSessions();
1632
+ }
1633
+
1634
+ function seenActivation() {
1635
+ const [epoch, seq] = String(ssGet(SS_ACTIVATION) || ':0').split(':');
1636
+ return epoch === knownEpoch ? Number(seq) || 0 : 0;
1637
+ }
1638
+
1639
+ // `activate` is the one agent action that moves the person's view. It is
1640
+ // followed once, while it is fresh; the person asked the agent for it.
1641
+ function followActivation(activation) {
1642
+ if (!activation || !Number.isFinite(activation.seq)) return;
1643
+ if (activation.seq <= seenActivation()) return;
1644
+ ssSet(SS_ACTIVATION, `${knownEpoch}:${activation.seq}`);
1645
+ if (Date.now() - activation.at > ACTIVATION_TTL_MS) return;
1646
+ if (viewerState === 'live' && activation.id === currentSessionId) return;
1647
+ const target = sessionList.find((session) => session.id === activation.id);
1648
+ if (!target) return;
1649
+ T1.toast(`Showing “${target.name}”, as the agent asked.`);
1650
+ const held = document.activeElement instanceof Element &&
1651
+ Boolean(document.activeElement.closest('dialog, input, textarea, select, [contenteditable="true"], .workspace-drawer'));
1652
+ attachSession(target.id, held);
1653
+ }
1654
+
1655
+ function attachSession(id, holdFocus = false) {
1656
+ suppressAutoFocus = holdFocus;
1657
+ abandonSocket();
1658
+ attachRequest = { resume: id };
1659
+ connect();
1660
+ }
1661
+
1662
+ function switchSession(id) {
1663
+ if (!id) return false;
1664
+ if (viewerState === 'live' && id === currentSessionId) {
1665
+ focusTerminal();
1666
+ return true;
1667
+ }
1668
+ // Only a shell the server lists can be switched to. Anything else is
1669
+ // refused; it is never turned into a new shell.
1670
+ if (!sessionList.some((session) => session.id === id)) {
1671
+ T1.toast('That session is no longer available.', 'warn');
1672
+ return false;
1673
+ }
1674
+ attachSession(id);
1675
+ return true;
1676
+ }
1677
+
1678
+ function newSession() {
1679
+ abandonSocket();
1680
+ attachRequest = { create: true };
1681
+ connect();
1682
+ }
1683
+
1684
+ // End a session the server lists. The shell stops on the server; a window
1685
+ // that was viewing it is moved on by the notice the server sends.
1686
+ async function closeSession(id) {
1687
+ const wasCurrent = viewerState === 'live' && id === currentSessionId;
1688
+ if (wasCurrent) closingOwn = id;
1689
+ try {
1690
+ const result = await sessionCommand({ type: 'close', sessionId: id });
1691
+ if (!result.ok && wasCurrent) closingOwn = null;
1692
+ return Boolean(result.ok);
1693
+ } catch (error) {
1694
+ if (wasCurrent) closingOwn = null;
1695
+ T1.toast(error.message || 'The session could not be closed.', 'error');
1696
+ return false;
1697
+ }
1698
+ }
1699
+
1700
+ async function renameSession(id, name) {
1701
+ try {
1702
+ const result = await sessionCommand({ type: 'rename', sessionId: id, name });
1703
+ if (result.ok) return { ok: true, name: result.name };
1704
+ return { ok: false, error: result.error || 'That name was not saved.' };
1705
+ } catch (error) {
1706
+ return { ok: false, error: error.message || 'That name was not saved.' };
1707
+ }
1708
+ }
1709
+
1710
+ // The shell to the right of the one that ended, else the one to the left,
1711
+ // else the one looked at most recently. Browser tabs move this way too.
1712
+ function neighbour(id, order, live) {
1713
+ const index = order.findIndex((session) => session.id === id);
1714
+ for (let step = 1; index >= 0 && step <= order.length; step += 1) {
1715
+ for (const candidate of [order[index + step], order[index - step]]) {
1716
+ if (!candidate) continue;
1717
+ const next = live.find((session) => session.id === candidate.id);
1718
+ if (next) return next;
1719
+ }
1720
+ }
1721
+ return live.slice().sort((a, b) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0))[0];
1722
+ }
1723
+
1724
+ // The shell this window was viewing is gone: closed here, closed by an
1725
+ // agent or another window, or unable to keep running. The window lands on
1726
+ // a shell that exists, or on one clear action, and says which unless the
1727
+ // person closed it themselves.
1728
+ function onSessionEnded(id, reason = 'closed', state) {
1729
+ if (viewerState !== 'live' || id !== currentSessionId) return;
1730
+ const bySelf = closingOwn === id;
1731
+ closingOwn = null;
1732
+ const name = currentSession?.name || 'The shell';
1733
+ const order = sessionList;
1734
+ const live = (state && Array.isArray(state.sessions) ? state.sessions : sessionList)
1735
+ .filter((session) => session.id !== id);
1736
+ abandonSocket();
1737
+ sessionList = live;
1738
+ sessionKnown = true;
1739
+ currentSessionId = null;
1740
+ currentSession = null;
1741
+ if (live.length) {
1742
+ const target = neighbour(id, order, live);
1743
+ if (!bySelf) {
1744
+ pendingNotice = reason === 'error'
1745
+ ? `“${name}” stopped unexpectedly. This window is now in “${target.name}”.`
1746
+ : `“${name}” was closed. This window is now in “${target.name}”.`;
1747
+ }
1748
+ attachRequest = { resume: target.id, after: 'ended' };
1749
+ connect();
1750
+ return;
1751
+ }
1752
+ enterEndedState(reason, name, bySelf);
1753
+ }
1754
+
1755
+ // What the window shows while no shell is open: what happened (as far as it
1756
+ // is known) and the one way forward. Shown when the last shell is closed and
1757
+ // again on every load that finds no shell on purpose.
1758
+ function showNoShell(options = {}) {
1759
+ const { reason = 'closed', name = '', bySelf = false, output = '' } = options;
1760
+ updateStatus('No shell', 'neutral');
1761
+ setFooter('No shell is open');
1762
+ setSessionInfo('');
1763
+ hideBanner();
1764
+ showSessionEmpty({
1765
+ heading: reason === 'error'
1766
+ ? `“${name}” could not keep running`
1767
+ : (name ? (bySelf ? `You closed “${name}”` : `“${name}” was closed`) : 'No shell is open'),
1768
+ detail: reason === 'error'
1769
+ ? 'Its shell exited again and again, so it was not restarted. Check $SHELL and your shell profile, then start another shell.'
1770
+ : (name
1771
+ ? 'No shell is open. A shell you close is gone for good; start one when you need it.'
1772
+ : 'A shell you close is gone for good. Start one when you need it.'),
1773
+ output
1774
+ });
1775
+ renderSessionChrome();
1776
+ announceSessions();
1777
+ }
1778
+
1779
+ // No shell, and none started in the background: the person stays in charge.
1780
+ // The window keeps a shell-less connection so the row stays current and can
1781
+ // still be acted on.
1782
+ function enterEndedState(reason, name, bySelf) {
1783
+ let output = '';
1784
+ if (reason === 'error' && term) {
1785
+ // What the shell printed before it gave up is the diagnosis. Keep the
1786
+ // last of it readable.
1787
+ output = String(window.__terminalOne.text?.() || '')
1788
+ .split('\n')
1789
+ .map((line) => line.trimEnd())
1790
+ .filter((line) => line.trim())
1791
+ .slice(-6)
1792
+ .join('\n');
1793
+ }
1794
+ rememberSession(null);
1795
+ ssSet(SS_SHELLLESS, '1');
1796
+ viewerState = 'ended';
1797
+ viewerResumed = false;
1798
+ disposeTerminal();
1799
+ showNoShell({ reason, name, bySelf, output });
1800
+ abandonSocket();
1801
+ attachRequest = { control: true };
1802
+ connect();
1803
+ document.getElementById('session-empty-start')?.focus();
1804
+ }
1805
+
1806
+ // The shell this window remembered is not on the server: the app was
1807
+ // restarted, or that shell was closed while the window was away. Say which
1808
+ // is known, then land on a shell that exists, or start exactly one.
1809
+ function onResumeFailed(msg) {
1810
+ const failed = msg.sessionId || rememberedSession() || '';
1811
+ const restarted = Boolean(knownEpoch && msg.epoch && msg.epoch !== knownEpoch);
1812
+ const before = restarted ? [] : sessionList;
1813
+ if (msg.epoch) rememberEpoch(msg.epoch);
1814
+ rememberSession(null);
1815
+ const live = (Array.isArray(msg.sessions) ? msg.sessions : []).filter((session) => session.id !== failed);
1816
+ const failedName = (before.find((session) => session.id === failed) || currentSession || {}).name;
1817
+ // Was this window opening, or moving off a shell that was closed under it?
1818
+ const movingOff = Boolean(lastAttach && lastAttach.after === 'ended');
1819
+ if (restarted) {
1820
+ sessionList = [];
1821
+ sessionKnown = false;
1822
+ }
1823
+ applySessionState({ ...msg, sessions: live });
1824
+ const said = restarted
1825
+ ? 'Townmouse was restarted, so the shells from before have ended.'
1826
+ : `“${failedName || 'The shell this window was viewing'}” is no longer available.`;
1827
+ const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1828
+ if (live.length) {
1829
+ const target = live.slice().sort((a, b) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0))[0];
1830
+ pendingNotice = `${said} This window is now in “${target.name}”.`;
1831
+ sendOnSocket({ type: 'resume', sessionId: target.id, cols: dims.cols, rows: dims.rows });
1832
+ return;
1833
+ }
1834
+ if (movingOff) {
1835
+ // Every other shell is gone too. That is not a fresh start: the choice
1836
+ // of a new shell is left to the person.
1837
+ enterEndedState('closed', failedName, false);
1838
+ return;
1839
+ }
1840
+ pendingNotice = `${said} This is a new shell.`;
1841
+ sendOnSocket({ type: 'shell', cols: dims.cols, rows: dims.rows });
1842
+ }
1843
+
1844
+ function connect() {
1845
+ if (ws && ws.readyState === WebSocket.OPEN) return;
1846
+
1847
+ if (reconnectTimer) {
1848
+ clearTimeout(reconnectTimer);
1849
+ reconnectTimer = null;
1850
+ }
1851
+
1852
+ userInitiatedClose = false;
1853
+ if (ws) {
1854
+ try { ws.close(); } catch (_) {}
1855
+ }
1856
+
1857
+ const request = attachRequest || planInitialAttach();
1858
+ attachRequest = null;
1859
+ lastAttach = request;
1860
+ if (request.control) {
1861
+ if (viewerState !== 'ended') {
1862
+ // Loaded with no shell on purpose: the person closed the last one. Show
1863
+ // that, rather than a blank space where the terminal was.
1864
+ viewerState = 'ended';
1865
+ showNoShell();
1866
+ }
1867
+ } else {
1868
+ initTerminal();
1869
+ viewerState = 'connecting';
1870
+ updateStatus('Connecting…', 'connecting');
1871
+ hideBanner();
1872
+ }
1873
+
1874
+ const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1875
+ // The handlers hold this socket, not the shared `ws`: an event from a
1876
+ // socket that has been replaced must not act on the new one.
1877
+ const socket = new WebSocket(`${protocol}//${location.host}`);
1878
+ ws = socket;
1879
+
1880
+ socket.onopen = () => {
1881
+ reconnectAttempts = 0;
1882
+ const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1883
+ if (request.resume) {
1884
+ // Ask for a shell the server has. If it is gone the server answers with
1885
+ // its real list, and onResumeFailed decides what happens next.
1886
+ socket.send(JSON.stringify({ type: 'resume', sessionId: request.resume, cols: dims.cols, rows: dims.rows }));
1887
+ } else if (request.create) {
1888
+ // The one way a shell is started: it was asked for, here.
1889
+ socket.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1890
+ } else {
1891
+ // No shell on purpose. The socket only carries the list of sessions.
1892
+ updateStatus('No shell', 'neutral');
1893
+ socket.send(JSON.stringify({ type: 'sessions' }));
1894
+ }
1895
+ scheduleFit();
1896
+ };
1897
+
1898
+ socket.onmessage = (evt) => {
1899
+ try { handleServerMessage(JSON.parse(evt.data)); }
1900
+ catch (e) { showBanner('Malformed server message', 'error'); }
1901
+ };
1902
+
1903
+ socket.onerror = () => {
1904
+ showBanner('WebSocket connection failed', 'error');
1905
+ updateStatus('WS error', 'error');
1906
+ };
1907
+
1908
+ socket.onclose = () => {
1909
+ if (ws !== socket) return;
1910
+ rejectPendingCommands(new Error('The connection closed.'));
1911
+ // A shell this window closed itself ends here, whether or not the
1912
+ // server's notice reached this socket first.
1913
+ if (closingOwn && closingOwn === currentSessionId) {
1914
+ onSessionEnded(currentSessionId, 'closed', null);
1915
+ return;
1916
+ }
1917
+ if (userInitiatedClose) return;
1918
+ updateStatus('Disconnected', 'error');
1919
+ // The remembered shell stays remembered, so the reconnect resumes it.
1920
+ const delay = Math.min(1_000 * Math.pow(2, reconnectAttempts), 60_000);
1921
+ reconnectAttempts++;
1922
+ reconnectTimer = setTimeout(() => {
1923
+ if (!userInitiatedClose) connect();
1924
+ }, delay);
1925
+ };
1926
+ }
1927
+
1928
+ // Ends the shell this window is viewing. The caller has already asked; this
1929
+ // leaves the window with no shell of its own.
1930
+ function closeConnection() {
1931
+ const id = currentSessionId;
1932
+ if (!id || viewerState !== 'live') return;
1933
+ reconnectAttempts = 0;
1934
+ if (reconnectTimer) {
1935
+ clearTimeout(reconnectTimer);
1936
+ reconnectTimer = null;
1937
+ }
1938
+ closingOwn = id;
1939
+ if (sendOnSocket({ type: 'close' })) {
1940
+ try { ws.close(); } catch (_) {}
1941
+ } else {
1942
+ onSessionEnded(id, 'closed', null);
1943
+ }
1944
+ }
1945
+
1946
+ // ── Settings UI ─────────────────────────────────────────────────────────────
1947
+ function buildThemeOptions() {
1948
+ const sel = $('#themeSelect');
1949
+ sel.innerHTML = '';
1950
+ for (const id of THEME_ORDER) {
1951
+ if (!THEMES[id]) continue;
1952
+ const opt = document.createElement('option');
1953
+ opt.value = id;
1954
+ opt.textContent = THEMES[id].name;
1955
+ sel.appendChild(opt);
1956
+ }
1957
+ }
1958
+
1959
+ function setVoiceStatus(text, kind) {
1960
+ const el = $('#voiceStatus');
1961
+ if (!el) return;
1962
+ el.textContent = text || '';
1963
+ el.dataset.kind = kind || '';
1964
+ }
1965
+
1966
+ function fillVoiceFields(data) {
1967
+ $('#voiceCommand').value = data.command || '';
1968
+ $('#voiceModel').value = data.model || '';
1969
+ $('#voiceLanguage').value = data.language || '';
1970
+ $('#voiceArgs').value = data.args || '';
1971
+ }
1972
+
1973
+ async function loadVoiceSettings() {
1974
+ setVoiceStatus('Loading voice settings...');
1975
+ try {
1976
+ const res = await fetch('/api/voice/settings', { cache: 'no-store' });
1977
+ const data = await res.json().catch(() => ({}));
1978
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
1979
+ fillVoiceFields(data);
1980
+ const resolved = data.resolved || {};
1981
+ if (resolved.commandFound) setVoiceStatus(`Command found: ${resolved.commandPath}`, 'ok');
1982
+ else setVoiceStatus(`Command not found: ${data.command || '(empty)'}`, 'error');
1983
+ } catch (err) {
1984
+ setVoiceStatus(`Could not load voice settings: ${err.message || err}`, 'error');
1985
+ }
1986
+ }
1987
+
1988
+ async function saveVoiceSettings() {
1989
+ const button = $('#voiceSave');
1990
+ const body = {
1991
+ command: $('#voiceCommand').value,
1992
+ model: $('#voiceModel').value,
1993
+ language: $('#voiceLanguage').value,
1994
+ args: $('#voiceArgs').value
1995
+ };
1996
+ button.disabled = true;
1997
+ setVoiceStatus('Saving voice settings...');
1998
+ try {
1999
+ const res = await fetch('/api/voice/settings', {
2000
+ method: 'PUT',
2001
+ headers: { 'Content-Type': 'application/json' },
2002
+ body: JSON.stringify(body)
2003
+ });
2004
+ const data = await res.json().catch(() => ({}));
2005
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
2006
+ fillVoiceFields(data);
2007
+ const resolved = data.resolved || {};
2008
+ if (resolved.commandFound) setVoiceStatus(`Saved. Command found: ${resolved.commandPath}`, 'ok');
2009
+ else setVoiceStatus(`Saved, but command not found: ${data.command || '(empty)'}`, 'warn');
2010
+ } catch (err) {
2011
+ setVoiceStatus(`Could not save voice settings: ${err.message || err}`, 'error');
2012
+ } finally {
2013
+ button.disabled = false;
2014
+ }
2015
+ }
2016
+
2017
+ function openSettings() {
2018
+ $('#styleSelect').value = currentStyle;
2019
+ $('#themeSelect').value = currentTheme;
2020
+ loadVoiceSettings();
2021
+ // Settings is a docked peer of the shell, not a modal over it. The terminal
2022
+ // stays visible, live, and operable while settings are adjusted.
2023
+ document.querySelectorAll('dialog.workspace-drawer[open]').forEach((dialog) => dialog.close());
2024
+ $('#settingsModal').classList.add('open');
2025
+ $('#styleSelect').focus();
2026
+ }
2027
+ function closeSettings() {
2028
+ $('#settingsModal').classList.remove('open');
2029
+ document.querySelector('#workspace-tools')?.focus();
2030
+ }
2031
+
2032
+ // ── Wire up ──────────────────────────────────────────────────────────────────
2033
+ buildThemeOptions();
2034
+ buildKeyBars();
2035
+ applyStyle(lsGet(LS_STYLE, DEFAULT_STYLE));
2036
+ applyTheme(lsGet(LS_THEME, DEFAULT_THEME));
2037
+
2038
+ $('#settingsModal').addEventListener('keydown', e => {
2039
+ if (e.key === 'Escape') { e.preventDefault(); closeSettings(); }
2040
+ });
2041
+ $('#settingsBtn').addEventListener('click', openSettings);
2042
+ $('#settingsClose').addEventListener('click', closeSettings);
2043
+ $('#settingsCloseTop').addEventListener('click', closeSettings);
2044
+ $('#settingsModal').addEventListener('click', (e) => { if (e.target === $('#settingsModal')) closeSettings(); });
2045
+ document.addEventListener('keydown', (e) => {
2046
+ if (e.key !== 'Escape' || !$('#settingsModal').classList.contains('open')) return;
2047
+ // Capture-phase: with the terminal live behind the dock, xterm would consume
2048
+ // Escape before a bubble listener could close Settings.
2049
+ e.preventDefault();
2050
+ e.stopPropagation();
2051
+ closeSettings();
2052
+ }, true);
2053
+ $('#styleSelect').addEventListener('change', (e) => applyStyle(e.target.value));
2054
+ $('#themeSelect').addEventListener('change', (e) => applyTheme(e.target.value));
2055
+ $('#voiceSave').addEventListener('click', saveVoiceSettings);
2056
+
2057
+ $('#reconnectBtn').addEventListener('click', () => {
2058
+ // Manual reconnect keeps the saved session id so it resumes.
2059
+ userInitiatedClose = false;
2060
+ connect();
2061
+ });
2062
+ $('#closeBtn').addEventListener('click', closeConnection);
2063
+ $('#session-empty-start').addEventListener('click', newSession);
2064
+
2065
+ // Re-detect on orientation change (iPhone↔iPad-like layout shifts are rare,
2066
+ // but viewport reflow should refresh the key bars).
2067
+ window.addEventListener('orientationchange', () => {
2068
+ setTimeout(() => { buildKeyBars(); scheduleFit(); }, 200);
2069
+ });
2070
+
2071
+ // ── Feature module loader ────────────────────────────────────────────────
2072
+ // public/features/*.mjs each export init(T1). This builds the T1 facade the
2073
+ // feature API contract expects, then dynamically imports every module and
2074
+ // runs its init() inside try/catch so one failure cannot break the app.
2075
+ const termReadyCbs = [];
2076
+ function runTermReadyCallback(cb) {
2077
+ if (!term) return;
2078
+ try { addTerminalResource(cb(term)); } catch (_) {}
2079
+ }
2080
+ function onTermReady(cb) {
2081
+ termReadyCbs.push(cb);
2082
+ runTermReadyCallback(cb);
2083
+ }
2084
+ // Re-fire onTermReady callbacks whenever the terminal is recreated on
2085
+ // reconnect. initTerminal() already ran before this loader exists, so fire
2086
+ // for the current term now.
2087
+ function __fireTermReady() { if (term) termReadyCbs.forEach(runTermReadyCallback); }
2088
+ const __origInitTerminal = initTerminal;
2089
+ initTerminal = function () { __origInitTerminal(); __fireTermReady(); };
2090
+ __fireTermReady();
2091
+
2092
+ // ── Toast notification system ─────────────────────────────────────────────
2093
+ // A real transient toast (auto-dismiss) layered above the app. Features call
2094
+ // T1.toast(msg, type) expecting a notification, NOT a persistent status-bar
2095
+ // change. Multiple toasts stack and fade; the toast-status feature wraps
2096
+ // this to also log them.
2097
+ let __toastSeq = 0;
2098
+ function __toastContainer() {
2099
+ let c = document.getElementById('t1toastHost');
2100
+ if (!c) {
2101
+ c = document.createElement('div');
2102
+ c.id = 't1toastHost';
2103
+ c.className = 't1toast-host';
2104
+ // In flow above the terminal: a toast may never cover live output.
2105
+ const shell = document.querySelector('.app-shell');
2106
+ const terminalContainer = shell?.querySelector('.terminal-container');
2107
+ if (shell && terminalContainer) shell.insertBefore(c, terminalContainer);
2108
+ else document.querySelector('.terminal-container')?.appendChild(c);
2109
+ }
2110
+ return c;
2111
+ }
2112
+ function __showToast(msg, type) {
2113
+ const el = document.createElement('div');
2114
+ el.className = `t1toast t1toast-${type || 'info'}`;
2115
+ el.setAttribute('role', 'status');
2116
+ el.textContent = String(msg).slice(0, 160);
2117
+ __toastContainer().appendChild(el);
2118
+ const id = ++__toastSeq;
2119
+ el.dataset.seq = String(id);
2120
+ // Animate in, hold, then fade out and remove.
2121
+ requestAnimationFrame(() => el.classList.add('show'));
2122
+ const ttl = type === 'error' ? 6000 : type === 'warn' ? 4500 : 3000;
2123
+ setTimeout(() => {
2124
+ el.classList.remove('show');
2125
+ setTimeout(() => el.remove(), 350);
2126
+ }, ttl);
2127
+ return id;
2128
+ }
2129
+
2130
+ // A failed or missing local STT command is usually a settings problem; point
2131
+ // the user at the new section instead of only surfacing the raw error code.
2132
+ window.addEventListener('t1:voice-error', (event) => {
2133
+ const code = event.detail && event.detail.code;
2134
+ if (code === 'STT_UNAVAILABLE' || code === 'STT_FAILED') {
2135
+ __showToast('Voice settings: Settings → Voice', 'warn');
2136
+ }
2137
+ });
2138
+
2139
+ const T1 = {
2140
+ get term() { return term; },
2141
+ get ws() { return ws; },
2142
+ // detectDevice() is defined above; surface the current device so features
2143
+ // can gate per-device (desktop-palette, haptic-keys, split-view, etc.).
2144
+ get device() { return document.body.dataset.device || detectDevice(); },
2145
+ sendData: (data) => { if (sendInputFn) sendInputFn(data); },
2146
+ fit: () => scheduleFit(),
2147
+ // Shell sessions, for the row and the Sessions list.
2148
+ sessions: () => sessionList.map((session) => ({ ...session })),
2149
+ sessionView: () => ({
2150
+ state: viewerState,
2151
+ current: currentSession ? { ...currentSession } : null,
2152
+ max: sessionMax,
2153
+ known: sessionKnown,
2154
+ resumed: viewerResumed
2155
+ }),
2156
+ newSession,
2157
+ switchSession,
2158
+ toast: (msg, type = 'info') => __showToast(msg, type),
2159
+ onTermReady,
2160
+ storage: {
2161
+ get: (k, def) => { const v = lsGet(k, undefined); return v === undefined ? def : v; },
2162
+ set: (k, v) => lsSet(k, String(v)),
2163
+ del: (k) => lsDel(k)
2164
+ },
2165
+ ui: {
2166
+ toolbar: () => document.getElementById('t1toolbar'),
2167
+ appShell: () => document.querySelector('.app-shell'),
2168
+ settingsPanel: () => document.querySelector('#settingsModal .settings-panel'),
2169
+ addStyle: (css) => {
2170
+ const s = document.createElement('style');
2171
+ s.textContent = css;
2172
+ document.head.appendChild(s);
2173
+ },
2174
+ makeButton: (label, title, onClick) => {
2175
+ const b = document.createElement('button');
2176
+ b.type = 'button';
2177
+ b.className = 't1button';
2178
+ b.textContent = label;
2179
+ if (title) b.title = title;
2180
+ if (typeof onClick === 'function') b.addEventListener('click', onClick);
2181
+ return b;
2182
+ }
2183
+ }
2184
+ };
2185
+
2186
+ // Ordered by the ShellFish parity manifest, then the extra verticals.
2187
+ const FEATURE_MODULES = [
2188
+ 'theme-system', 'keyboard-shortcuts', 'history-undo', 'autosave',
2189
+ 'recent-commands', 'search', 'command-palette', 'toast-status',
2190
+ 'osc-bridge', 'links', 'zoom', 'keybar-config', 'voice-input', 'session-manager',
2191
+ 'status-metrics', 'export', 'clipboard', 'snippets', 'fontsize',
2192
+ 'wake-fullscreen', 'desktop-palette', 'floating-palette',
2193
+ 'haptic-keys', 'keepalive', 'multi-window-sync', 'phone-landscape-focus',
2194
+ 'session-lock', 'settings-sync', 'shortcut-help', 'smart-completions',
2195
+ 'smart-suggest', 'split-view', 'stylus-support', 'swipe-history',
2196
+ 'swipe-sessions', 'two-finger-menu', 'app-version', 'window-title'
2197
+ ];
2198
+ (async () => {
2199
+ const loaded = [];
2200
+ for (const name of FEATURE_MODULES) {
2201
+ try {
2202
+ const mod = await import(`./features/${name}.mjs`);
2203
+ if (typeof mod.init === 'function') { mod.init(T1); loaded.push(name); }
2204
+ } catch (err) {
2205
+ console.error(`[features] ${name} failed to load:`, err);
2206
+ }
2207
+ }
2208
+ window.__t1Features = loaded;
2209
+ const workspace = await import('./workspace.mjs');
2210
+ workspace.init(T1);
2211
+ })();
2212
+
2213
+ connect();
2214
+
2215
+ // Best-effort: on touch devices only, shed the browser URL bar by entering
2216
+ // fullscreen on the first user gesture. Gated to iPhone/iPad so a desktop
2217
+ // click is never hijacked into fullscreen. iPhone Safari has no element
2218
+ // Fullscreen API (the requestFullscreen guard no-ops there); the real
2219
+ // chrome-hiding path on iPhone is PWA standalone (Add to Home Screen).
2220
+ (function attemptFullscreenOnce() {
2221
+ const dev = detectDevice();
2222
+ if (dev !== 'iphone' && dev !== 'ipad') return;
2223
+ const standalone =
2224
+ (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) ||
2225
+ window.navigator.standalone === true;
2226
+ if (standalone) return;
2227
+ const target = document.documentElement;
2228
+ if (!target || !target.requestFullscreen) return;
2229
+ function go() {
2230
+ document.removeEventListener('pointerdown', go);
2231
+ document.removeEventListener('keydown', go);
2232
+ if (!document.fullscreenElement) target.requestFullscreen().catch(() => {});
2233
+ }
2234
+ document.addEventListener('pointerdown', go, { passive: true });
2235
+ document.addEventListener('keydown', go);
2236
+ })();
2237
+
2238
+ // Expose for automated tests.
2239
+ window.__terminalOne = {
2240
+ get theme() { return currentTheme; },
2241
+ get style() { return currentStyle; },
2242
+ get device() { return document.body.dataset.device; },
2243
+ themes: () => THEME_ORDER.slice(),
2244
+ setTheme: applyTheme,
2245
+ setStyle: applyStyle,
2246
+ termTheme: () => term && term.options.theme,
2247
+ close: closeConnection,
2248
+ // Shell sessions. The list is the server's; these act on it and never
2249
+ // start a shell that was not asked for.
2250
+ newSession,
2251
+ switchSession,
2252
+ closeSession,
2253
+ renameSession,
2254
+ sessions: () => sessionList.map((session) => ({ ...session })),
2255
+ sessionView: () => ({
2256
+ state: viewerState,
2257
+ current: currentSession ? { ...currentSession } : null,
2258
+ max: sessionMax,
2259
+ known: sessionKnown,
2260
+ resumed: viewerResumed
2261
+ }),
2262
+ // Test hooks for the key bar + resume.
2263
+ detectDevice,
2264
+ visibleKeyBar: () => {
2265
+ const d = document.body.dataset.device;
2266
+ if (d === 'iphone') return $('#keybarIphone');
2267
+ if (d === 'ipad') return $('#keybarIpad');
2268
+ return null;
2269
+ },
2270
+ keyCount: () => {
2271
+ const bar = (document.body.dataset.device === 'iphone' ? $('#keybarIphone') : $('#keybarIpad'));
2272
+ return bar ? bar.querySelectorAll('.kb-key').length : 0;
2273
+ },
2274
+ savedSession: () => rememberedSession(),
2275
+ // Attachment controls insert a shell-quoted path through the same guarded
2276
+ // input path as the keyboard and key bar.
2277
+ sendData: (data) => {
2278
+ if (sendInputFn && typeof data === 'string') sendInputFn(data);
2279
+ },
2280
+ dimensions: () => term ? { cols: term.cols, rows: term.rows } : null,
2281
+ text: () => {
2282
+ if (!term) return '';
2283
+ const buffer = term.buffer.active;
2284
+ const lines = [];
2285
+ for (let i = 0; i < buffer.length; i++) {
2286
+ const line = buffer.getLine(i);
2287
+ lines.push(line ? line.translateToString(true) : '');
2288
+ }
2289
+ return lines.join('\n');
2290
+ }
2291
+ };
2292
+ </script>
2293
+ <script>
2294
+ /* PWA: register the offline shell service worker. Guarded — failure never breaks the app. */
2295
+ if ('serviceWorker' in navigator) {
2296
+ window.addEventListener('load', () => {
2297
+ navigator.serviceWorker.register('/service-worker.js').catch((e) => {
2298
+ console.warn('Townmouse service worker registration failed:', e);
2299
+ });
2300
+ });
2301
+ }
2302
+ </script>
2303
+ </body>
2304
+ </html>