townmouse 0.0.0-stage → 0.2.1

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 (103) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/DESIGN.md +169 -0
  3. package/LICENSE +661 -0
  4. package/README.md +368 -2
  5. package/SECURITY.md +57 -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 +275 -0
  13. package/docs/browser-workspace.md +184 -0
  14. package/docs/panes.md +252 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/package.json +89 -4
  17. package/public/apple-touch-icon.png +0 -0
  18. package/public/brand/floydslabs-credit.png +0 -0
  19. package/public/brand/floydslabs-credit.webp +0 -0
  20. package/public/brand/townmouse-aristocrat.webp +0 -0
  21. package/public/brand/townmouse-monocled.webp +0 -0
  22. package/public/clipboard-text.mjs +5 -0
  23. package/public/favicon-16x16.png +0 -0
  24. package/public/favicon-32x32.png +0 -0
  25. package/public/favicon.ico +0 -0
  26. package/public/favicon.svg +1 -0
  27. package/public/features/autosave.mjs +76 -0
  28. package/public/features/clipboard.mjs +69 -0
  29. package/public/features/command-palette.mjs +181 -0
  30. package/public/features/desktop-palette.mjs +19 -0
  31. package/public/features/export.mjs +37 -0
  32. package/public/features/file-drop.mjs +77 -0
  33. package/public/features/floating-palette.mjs +113 -0
  34. package/public/features/fontsize.mjs +72 -0
  35. package/public/features/haptic-keys.mjs +42 -0
  36. package/public/features/history-undo.mjs +102 -0
  37. package/public/features/keepalive.mjs +36 -0
  38. package/public/features/keybar-config.mjs +70 -0
  39. package/public/features/keyboard-shortcuts.mjs +74 -0
  40. package/public/features/links.mjs +139 -0
  41. package/public/features/multi-window-sync.mjs +74 -0
  42. package/public/features/osc-bridge.mjs +59 -0
  43. package/public/features/phone-landscape-focus.mjs +157 -0
  44. package/public/features/recent-commands.mjs +100 -0
  45. package/public/features/search.mjs +134 -0
  46. package/public/features/session-lock.mjs +96 -0
  47. package/public/features/session-manager.mjs +149 -0
  48. package/public/features/settings-sync.mjs +77 -0
  49. package/public/features/shortcut-help.mjs +85 -0
  50. package/public/features/smart-completions.mjs +101 -0
  51. package/public/features/smart-suggest.mjs +124 -0
  52. package/public/features/snippets.mjs +85 -0
  53. package/public/features/split-view.mjs +102 -0
  54. package/public/features/status-metrics.mjs +114 -0
  55. package/public/features/stylus-support.mjs +124 -0
  56. package/public/features/swipe-history.mjs +141 -0
  57. package/public/features/swipe-sessions.mjs +85 -0
  58. package/public/features/tab-reorder.mjs +62 -0
  59. package/public/features/theme-system.mjs +51 -0
  60. package/public/features/toast-status.mjs +118 -0
  61. package/public/features/two-finger-menu.mjs +87 -0
  62. package/public/features/voice-input.mjs +244 -0
  63. package/public/features/wake-fullscreen.mjs +67 -0
  64. package/public/features/window-title.mjs +40 -0
  65. package/public/features/zoom.mjs +80 -0
  66. package/public/icon-128.png +0 -0
  67. package/public/icon-180.png +0 -0
  68. package/public/icon-192.png +0 -0
  69. package/public/icon-48.png +0 -0
  70. package/public/icon-512-maskable.png +0 -0
  71. package/public/icon-512.png +0 -0
  72. package/public/icon.svg +1 -0
  73. package/public/index.html +1765 -0
  74. package/public/input-chunks.mjs +22 -0
  75. package/public/input-guard.mjs +210 -0
  76. package/public/manifest.json +56 -0
  77. package/public/panes.css +1257 -0
  78. package/public/panes.html +208 -0
  79. package/public/panes.mjs +2625 -0
  80. package/public/service-worker.js +67 -0
  81. package/public/workspace.css +1447 -0
  82. package/public/workspace.mjs +1475 -0
  83. package/scripts/install-service.sh +269 -0
  84. package/scripts/node-runtime.sh +138 -0
  85. package/scripts/panes +439 -0
  86. package/scripts/prepare-native.sh +35 -0
  87. package/scripts/run-hooks +69 -0
  88. package/scripts/t1.sh +113 -0
  89. package/scripts/uninstall-service.sh +49 -0
  90. package/src/agent-guide.js +260 -0
  91. package/src/attachments.js +128 -0
  92. package/src/browser-dom.js +545 -0
  93. package/src/browser-workspace.js +1246 -0
  94. package/src/chrome-resolve.js +80 -0
  95. package/src/pty-permissions.js +99 -0
  96. package/src/regex-worker.js +13 -0
  97. package/src/replay-text.js +189 -0
  98. package/src/request-boundary.js +58 -0
  99. package/src/safe-regex.js +87 -0
  100. package/src/server.js +1122 -0
  101. package/src/shell-resolve.js +42 -0
  102. package/src/static-deps.js +61 -0
  103. package/src/workspace-panes.js +1099 -0
@@ -0,0 +1,1765 @@
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
+ .t1session-tabs { flex-wrap: wrap; overflow: visible !important; margin-left: 0 !important; }
392
+ body[data-style="floyd"] button { font-size: 12px; }
393
+ body[data-style="floyd"] .terminal-status, body[data-style="floyd"] .terminal-footer { font-size: 11px; }
394
+ .keybar .kb-key:active, .keybar .kb-key.toggle.active, .t1button.active,
395
+ body[data-style="floyd"] button:hover { color: var(--ui-on-accent, #14171b); }
396
+ @media (max-width: 600px) {
397
+ .terminal-header { padding: 8px; gap: 8px; }
398
+ .terminal-title { font-size: 13px; }
399
+ .terminal-actions { order: 4; width: 100%; gap: 6px; }
400
+ .terminal-actions button { flex: 1; }
401
+ .statuswrap { margin-left: auto; }
402
+ .terminal-footer { padding: 6px 8px; }
403
+ #sessionInfo { overflow-wrap: anywhere; }
404
+ }
405
+ @media (prefers-reduced-motion: reduce) {
406
+ *, *::before, *::after { animation: none !important; transition: none !important; }
407
+ }
408
+ </style>
409
+ <link rel="stylesheet" href="/workspace.css">
410
+ </head>
411
+ <body class="workspace" data-style="default" data-theme="tokyo-night" data-device="desktop">
412
+ <canvas id="fxCanvas" aria-hidden="true"></canvas>
413
+
414
+ <div class="app-shell">
415
+ <div class="banner" id="banner"></div>
416
+ <header class="terminal-header">
417
+ <div class="terminal-title">Townmouse</div>
418
+ <div class="terminal-actions">
419
+ <button id="settingsBtn" type="button" title="Settings">Settings</button>
420
+ <button id="reconnectBtn" type="button">Reconnect</button>
421
+ <button id="closeBtn" type="button">Close</button>
422
+ </div>
423
+ <div class="statuswrap">
424
+ <span class="status-dot" id="statusDot"></span>
425
+ <span class="terminal-status" id="status">Ready</span>
426
+ </div>
427
+ </header>
428
+
429
+ <!-- Feature toolbar — buttons appended by public/features/*.mjs modules. -->
430
+ <div class="t1toolbar" id="t1toolbar" role="toolbar" aria-label="Features"></div>
431
+ <main class="terminal-container">
432
+ <div id="terminal"></div>
433
+ </main>
434
+
435
+ <!-- iPhone key bar: compact single row of essentials. -->
436
+ <div class="keybar iphone" id="keybarIphone" role="toolbar" aria-label="Control keys"></div>
437
+ <!-- iPad key bar: wide — modifiers, navigation, arrows, symbols. -->
438
+ <div class="keybar ipad" id="keybarIpad" role="toolbar" aria-label="Control keys"></div>
439
+
440
+ <footer class="terminal-footer">
441
+ <span id="footerMeta">Your shell, in focus</span>
442
+ <span id="sessionInfo"></span>
443
+ </footer>
444
+ </div>
445
+
446
+ <!-- Settings modal -->
447
+ <div id="settingsModal" role="dialog" aria-label="Settings">
448
+ <div class="settings-panel">
449
+ <div class="settings-dock-bar">
450
+ <h2>Settings</h2>
451
+ <button id="settingsCloseTop" type="button">Done</button>
452
+ </div>
453
+ <div class="settings-row">
454
+ <label for="styleSelect">Terminal style</label>
455
+ <select id="styleSelect">
456
+ <option value="default">Townmouse (default)</option>
457
+ <option value="floyd">Floyd TTY Bridge</option>
458
+ </select>
459
+ </div>
460
+ <div class="settings-row">
461
+ <label for="themeSelect">Color theme</label>
462
+ <select id="themeSelect"></select>
463
+ </div>
464
+ <div class="settings-section" role="group" aria-labelledby="voiceHeading">
465
+ <h3 id="voiceHeading">Voice / speech-to-text</h3>
466
+ <div class="settings-row">
467
+ <label for="voiceCommand">STT command</label>
468
+ <input id="voiceCommand" type="text" placeholder="whisper or /path/to/whisper" autocomplete="off" spellcheck="false">
469
+ </div>
470
+ <div class="settings-row">
471
+ <label for="voiceModel">Voice model</label>
472
+ <input id="voiceModel" type="text" placeholder="tiny.en, medium, or model path" autocomplete="off" spellcheck="false">
473
+ </div>
474
+ <div class="settings-row">
475
+ <label for="voiceLanguage">Language</label>
476
+ <input id="voiceLanguage" type="text" placeholder="en or auto" autocomplete="off" spellcheck="false">
477
+ </div>
478
+ <details class="settings-advanced">
479
+ <summary>Advanced argument template</summary>
480
+ <div class="settings-row">
481
+ <label for="voiceArgs">Arguments</label>
482
+ <textarea id="voiceArgs" rows="4" spellcheck="false"></textarea>
483
+ </div>
484
+ </details>
485
+ <div class="settings-actions settings-voice-actions">
486
+ <span id="voiceStatus" role="status" aria-live="polite"></span>
487
+ <button id="voiceSave" type="button">Save voice settings</button>
488
+ </div>
489
+ </div>
490
+ <div class="settings-actions">
491
+ <button id="settingsClose" type="button">Done</button>
492
+ </div>
493
+ </div>
494
+ </div>
495
+
496
+ <script type="module">
497
+ import { Terminal } from '/node_modules/@xterm/xterm/lib/xterm.mjs';
498
+ import { FitAddon } from '/node_modules/@xterm/addon-fit/lib/addon-fit.mjs';
499
+ import { WebLinksAddon } from '/node_modules/@xterm/addon-web-links/lib/addon-web-links.mjs';
500
+ import { InputGuard, bindInputGuard } from './input-guard.mjs';
501
+
502
+ // ── Theme catalog ─────────────────────────────────────────────────────────
503
+ // Stable preference keys map to calm studio palettes. Existing saved choices
504
+ // remain valid without exposing their historical palette names in the UI.
505
+ function studioTheme(name, bg, accent, light = false, canvas = false) {
506
+ const ui = {
507
+ bg, accent, fg: light ? '#252b31' : '#eceeea',
508
+ elevated: light ? '#efeee9' : '#242a30',
509
+ border: light ? '#737b82' : '#7d8992', muted: light ? '#515b64' : '#b5bdc4'
510
+ };
511
+ const ansi = light
512
+ ? { black:'#252b31', red:'#9c342c', green:'#356343', yellow:'#79561b', blue:'#345e8a', magenta:'#73536e', cyan:'#35696a', white:'#515b64' }
513
+ : { black:'#a8b0b7', red:'#e2a69e', green:'#b3c8b4', yellow:'#dcc38b', blue:'#a8bed4', magenta:'#cbb5c8', cyan:'#a4c5c4', white:'#d9deda' };
514
+ const bright = Object.fromEntries(Object.entries(ansi).map(([key, value]) => ['bright' + key[0].toUpperCase() + key.slice(1), value]));
515
+ return { name, ui, xterm: {
516
+ background: canvas ? 'rgba(20,27,24,1)' : bg, foreground: ui.fg,
517
+ cursor: accent, cursorAccent: bg, selectionBackground: light ? '#d9dde1' : '#424c54',
518
+ ...ansi, ...bright
519
+ } };
520
+ }
521
+ const THEMES = {
522
+ 'tokyo-night': studioTheme('Graphite Studio', '#14171b', '#d6ad68'),
523
+ 'absolute-void': studioTheme('Obsidian', '#090b0e', '#d2b887'),
524
+ 'matrix': studioTheme('Evergreen', '#141b18', '#a8c4b1', false, true),
525
+ 'dracula': studioTheme('Slate', '#171c24', '#b4becf'),
526
+ 'gruvbox': studioTheme('Warm Graphite', '#1b1916', '#d8b47e'),
527
+ 'nord': studioTheme('Steel', '#1a2027', '#adc0d0'),
528
+ 'catppuccin': studioTheme('Charcoal', '#202024', '#c3b6b0'),
529
+ 'solarized-dark': studioTheme('Deep Ink', '#111b23', '#9ebfcb'),
530
+ 'solarized-light': studioTheme('Paper', '#faf9f5', '#6d491a', true),
531
+ 'monokai': studioTheme('Sepia', '#201d18', '#d3bd97'),
532
+ 'one-dark': studioTheme('Carbon', '#15191c', '#b3c4bc'),
533
+ 'github-dark': studioTheme('Midnight', '#10161c', '#adbfce')
534
+ };
535
+
536
+ const THEME_ORDER = ['tokyo-night','absolute-void','matrix','dracula','gruvbox','nord','catppuccin','solarized-dark','solarized-light','monokai','one-dark','github-dark'];
537
+ const STYLES = { 'default': "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', monospace", 'floyd': "ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace" };
538
+
539
+ const DEFAULT_THEME = 'tokyo-night';
540
+ const DEFAULT_STYLE = 'default';
541
+ const LS_THEME = 'terminalone.theme';
542
+ const LS_STYLE = 'terminalone.style';
543
+ const LS_SESSION = 'terminalone.sessionId';
544
+
545
+ // ── State ───────────────────────────────────────────────────────────────
546
+ let ws = null;
547
+ let term = null;
548
+ let fitAddon = null;
549
+ let reconnectAttempts = 0;
550
+ let reconnectTimer = null;
551
+ // No resize may reach the server before the first ready/shell handshake. A
552
+ // fit on the fresh page would otherwise overwrite the old PTY dimensions and
553
+ // hide the fact that resume is crossing widths.
554
+ let sessionReady = false;
555
+ let userInitiatedClose = false;
556
+ let currentSessionId = null;
557
+ let currentTheme = DEFAULT_THEME;
558
+ let currentStyle = DEFAULT_STYLE;
559
+ let rain = null; // lazily created digital-rain controller
560
+ let fitTimer = null;
561
+ // Non-null while replaying a resumed session's old-width buffer. The xterm
562
+ // stays at the PTY's old dimensions so wrapped lines and cursor addressing
563
+ // survive; fitting waits until the replay-end marker arrives.
564
+ let resumeReplay = null;
565
+ let replayEnded = false;
566
+ let replayPending = 0;
567
+ let postReplayOutput = [];
568
+ let terminalResourceDisposers = [];
569
+
570
+ // Module-level input sender. initTerminal() (which owns the dictation guard
571
+ // and the real sendInput closure) sets this so key-bar buttons outside the
572
+ // closure can emit control sequences.
573
+ let sendInputFn = null;
574
+ // Modifier toggle state for the on-screen key bar (Ctrl / Alt as sticky).
575
+ let modState = { ctrl: false, alt: false };
576
+
577
+ // File/image drops become a server-side attachment plus a shell-quoted path
578
+ // in the terminal. Never paste a data: URI or base64 stream into the PTY.
579
+ let attachmentDropBound = false;
580
+ function shellQuotePath(value) {
581
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
582
+ }
583
+ async function uploadTerminalAttachment(file) {
584
+ const response = await fetch('/api/attachments', {
585
+ method: 'POST',
586
+ headers: {
587
+ 'Content-Type': file.type || 'application/octet-stream',
588
+ 'X-Filename': encodeURIComponent(file.name || 'attachment')
589
+ },
590
+ body: file
591
+ });
592
+ let payload = null;
593
+ try { payload = await response.json(); } catch (_) { payload = null; }
594
+ if (!response.ok) throw new Error((payload && payload.error) || `Upload failed (${response.status}).`);
595
+ return payload;
596
+ }
597
+ function bindAttachmentDrop() {
598
+ if (attachmentDropBound) return;
599
+ const host = document.getElementById('terminal');
600
+ if (!host) return;
601
+ attachmentDropBound = true;
602
+ const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes('Files');
603
+ host.addEventListener('dragover', (event) => {
604
+ if (!hasFiles(event)) return;
605
+ event.preventDefault();
606
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
607
+ });
608
+ document.addEventListener('dragover', (event) => {
609
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
610
+ }, true);
611
+ document.addEventListener('drop', (event) => {
612
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
613
+ }, true);
614
+ host.addEventListener('drop', async (event) => {
615
+ if (!event.dataTransfer?.files?.length) return;
616
+ event.preventDefault();
617
+ event.stopPropagation();
618
+ for (const file of Array.from(event.dataTransfer.files)) {
619
+ try {
620
+ const attachment = await uploadTerminalAttachment(file);
621
+ if (sendInputFn) sendInputFn(`${shellQuotePath(attachment.path)} `);
622
+ showBanner(`Attached ${file.name}`, 'info');
623
+ } catch (error) {
624
+ showBanner(error.message || `Could not attach ${file.name}.`, 'error');
625
+ }
626
+ }
627
+ });
628
+ // xterm's helper-textarea paste handler stops propagation, so capture at
629
+ // document level, before it sees the event, and handle clipboard files.
630
+ document.addEventListener('paste', async (event) => {
631
+ const target = event.target;
632
+ if (!target || !target.closest || !target.closest('#terminal')) return;
633
+ const files = Array.from(event.clipboardData?.items || [])
634
+ .filter((item) => item.kind === 'file')
635
+ .map((item) => item.getAsFile())
636
+ .filter(Boolean);
637
+ if (!files.length) return;
638
+ event.preventDefault();
639
+ event.stopImmediatePropagation();
640
+ for (const file of files) {
641
+ try {
642
+ const attachment = await uploadTerminalAttachment(file);
643
+ if (sendInputFn) sendInputFn(`${shellQuotePath(attachment.path)} `);
644
+ showBanner(`Attached ${file.name}`, 'info');
645
+ } catch (error) {
646
+ showBanner(error.message || `Could not attach ${file.name}.`, 'error');
647
+ }
648
+ }
649
+ }, true);
650
+ }
651
+
652
+ const $ = (sel) => document.querySelector(sel);
653
+
654
+ function addTerminalResource(disposer) {
655
+ if (!disposer) return;
656
+ if (typeof disposer === 'function') {
657
+ terminalResourceDisposers.push(disposer);
658
+ } else if (typeof disposer.dispose === 'function') {
659
+ terminalResourceDisposers.push(() => disposer.dispose());
660
+ }
661
+ }
662
+
663
+ function cleanupTerminalResources() {
664
+ if (fitTimer) {
665
+ clearTimeout(fitTimer);
666
+ fitTimer = null;
667
+ }
668
+ const disposers = terminalResourceDisposers.splice(0).reverse();
669
+ for (const dispose of disposers) {
670
+ try { dispose(); } catch (_) {}
671
+ }
672
+ }
673
+
674
+ // ── Settings persistence ──────────────────────────────────────────────────
675
+ function lsGet(key, fallback) {
676
+ try { const v = localStorage.getItem(key); return v == null ? fallback : v; } catch (_) { return fallback; }
677
+ }
678
+ function lsSet(key, value) {
679
+ try { localStorage.setItem(key, value); } catch (_) {}
680
+ }
681
+ function lsDel(key) {
682
+ try { localStorage.removeItem(key); } catch (_) {}
683
+ }
684
+
685
+ // ── Device detection (iPhone vs iPad vs desktop) ──────────────────────────
686
+ // iPadOS 13+ requests desktop sites and reports platform 'MacIntel' with a
687
+ // touch screen, so the MacIntel+maxTouchPoints heuristic is required in
688
+ // addition to the legacy /iPad/ UA string.
689
+ function detectDevice() {
690
+ const ua = navigator.userAgent || '';
691
+ const isIPad = /iPad/.test(ua) || (navigator.platform === 'MacIntel' && (navigator.maxTouchPoints || 0) > 1);
692
+ const isIPhone = /iPhone|iPod/.test(ua);
693
+ if (isIPad) return 'ipad';
694
+ if (isIPhone) return 'iphone';
695
+ // Viewport/input fallback for touch browsers whose UA is not Apple.
696
+ if (window.matchMedia && window.matchMedia('(pointer: coarse)').matches) {
697
+ const short = Math.min(window.innerWidth, window.innerHeight);
698
+ if (short < 700) return 'iphone';
699
+ if (short < 1100) return 'ipad';
700
+ }
701
+ return 'desktop';
702
+ }
703
+
704
+ // ── Digital rain (ported from VOID MatrixRain.tsx) ─────────────────────────
705
+ function createRain(canvas) {
706
+ return { start() { canvas.getContext('2d')?.clearRect(0, 0, canvas.width, canvas.height); }, stop() {} };
707
+ }
708
+
709
+ function setRainActive(active) {
710
+ const canvas = $('#fxCanvas');
711
+ if (active) {
712
+ if (!rain) rain = createRain(canvas);
713
+ rain.start();
714
+ } else if (rain) {
715
+ rain.stop();
716
+ }
717
+ }
718
+
719
+ // ── Apply theme / style ────────────────────────────────────────────────────
720
+ function applyTheme(id) {
721
+ if (!THEMES[id]) id = DEFAULT_THEME;
722
+ currentTheme = id;
723
+ const t = THEMES[id];
724
+ const root = document.documentElement.style;
725
+ root.setProperty('--ui-bg', t.ui.bg);
726
+ root.setProperty('--ui-fg', t.ui.fg);
727
+ root.setProperty('--ui-elevated', t.ui.elevated);
728
+ root.setProperty('--ui-border', t.ui.border);
729
+ root.setProperty('--ui-accent', t.ui.accent);
730
+ root.setProperty('--ui-muted', t.ui.muted);
731
+ root.setProperty('--ui-on-accent', t.ui.bg);
732
+ root.setProperty('--ui-danger', id === 'solarized-light' ? '#9c342c' : '#e2a69e');
733
+ root.setProperty('--ui-warning', id === 'solarized-light' ? '#79561b' : '#dcc38b');
734
+ document.querySelector('meta[name="theme-color"]')?.setAttribute('content', t.ui.bg);
735
+ document.body.dataset.theme = id;
736
+ if (term) term.options.theme = t.xterm;
737
+ setRainActive(id === 'matrix');
738
+ lsSet(LS_THEME, id);
739
+ }
740
+
741
+ function applyStyle(id) {
742
+ if (!STYLES[id]) id = DEFAULT_STYLE;
743
+ currentStyle = id;
744
+ document.body.dataset.style = id;
745
+ if (term) { term.options.fontFamily = STYLES[id]; scheduleFit(); }
746
+ lsSet(LS_STYLE, id);
747
+ }
748
+
749
+ // ── UI feedback helpers ────────────────────────────────────────────────────
750
+ function showBanner(msg, type = 'error') {
751
+ const banner = $('#banner');
752
+ banner.textContent = msg;
753
+ banner.className = `banner ${type}`;
754
+ // hideBanner writes an inline display:none that would otherwise outrank
755
+ // every .banner.error/.warn rule and keep later banners invisible.
756
+ banner.style.display = '';
757
+ }
758
+
759
+ function hideBanner() {
760
+ $('#banner').className = 'banner';
761
+ $('#banner').style.display = 'none';
762
+ }
763
+
764
+ function updateStatus(text, state = 'neutral') {
765
+ const status = $('#status');
766
+ status.textContent = text;
767
+ status.className = `terminal-status ${state}`;
768
+ const dot = $('#statusDot');
769
+ if (dot) dot.className = `status-dot ${state === 'connected' ? 'connected' : state === 'error' ? 'error' : state === 'neutral' ? '' : 'connecting'}`;
770
+ }
771
+
772
+ function setFooter(text) { $('#footerMeta').textContent = text; }
773
+ function setSessionInfo(text, sessionId) {
774
+ const el = $('#sessionInfo');
775
+ el.textContent = text;
776
+ if (sessionId) el.dataset.sessionId = sessionId;
777
+ else if (!text) delete el.dataset.sessionId;
778
+ }
779
+
780
+ function scheduleFit(delay = 0) {
781
+ if (fitTimer) clearTimeout(fitTimer);
782
+ fitTimer = window.setTimeout(() => {
783
+ fitTimer = null;
784
+ if (!fitAddon || !term || resumeReplay) return;
785
+ try { fitAddon.fit(); } catch (_) {}
786
+ }, delay);
787
+ }
788
+
789
+ // term.write() parses asynchronously. Fit only after every replay chunk has
790
+ // actually landed, or xterm reflows bytes that were still queued for the old
791
+ // width. Output that arrived after replay-end is buffered until the fit.
792
+ function finishReplayIfReady() {
793
+ if (!resumeReplay || !replayEnded || replayPending > 0) return;
794
+ resumeReplay = null;
795
+ replayEnded = false;
796
+ if (fitAddon && term) {
797
+ try { fitAddon.fit(); } catch (_) {}
798
+ }
799
+ const queued = postReplayOutput;
800
+ postReplayOutput = [];
801
+ for (const chunk of queued) term?.write(chunk);
802
+ }
803
+
804
+ // ── On-screen key bar ─────────────────────────────────────────────────────
805
+ // xterm control sequences for the keys missing on iOS/iPadOS keyboards.
806
+ const SEQ = {
807
+ esc: '\x1b',
808
+ tab: '\t',
809
+ enter: '\r',
810
+ del: '\x7f',
811
+ ctrlB: '\x02',
812
+ up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
813
+ home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~'
814
+ };
815
+
816
+ function emitSeq(seq) {
817
+ if (!sendInputFn) return;
818
+ sendInputFn(seq);
819
+ // Sticky modifiers consume themselves on the next emit.
820
+ modState.ctrl = false;
821
+ modState.alt = false;
822
+ syncModButtons();
823
+ }
824
+
825
+ /** Map a literal character to its Ctrl / Alt combination if a mod is sticky. */
826
+ function emitLiteral(ch) {
827
+ if (!sendInputFn) return;
828
+ let out = ch;
829
+ if (modState.ctrl && ch.length === 1) {
830
+ // Ctrl+X = X & 0x1f (ASCII control code).
831
+ out = String.fromCharCode(ch.charCodeAt(0) & 0x1f);
832
+ }
833
+ if (modState.alt && out.length === 1) {
834
+ // Alt prefix in xterm: ESC then the char.
835
+ out = '\x1b' + out;
836
+ }
837
+ sendInputFn(out);
838
+ modState.ctrl = false;
839
+ modState.alt = false;
840
+ syncModButtons();
841
+ }
842
+
843
+ function syncModButtons() {
844
+ document.querySelectorAll('.kb-key.toggle[data-mod]').forEach((b) => {
845
+ b.classList.toggle('active', !!modState[b.dataset.mod]);
846
+ });
847
+ }
848
+
849
+ /** Build a key element. kind: 'seq' | 'literal' | 'toggle' | 'special'. */
850
+ function makeKey(label, opts = {}) {
851
+ const el = document.createElement('button');
852
+ el.type = 'button';
853
+ el.className = 'kb-key';
854
+ el.textContent = label;
855
+ if (opts.title) el.title = opts.title;
856
+ if (opts.kind === 'toggle') {
857
+ el.classList.add('toggle');
858
+ if (opts.mod) el.dataset.mod = opts.mod;
859
+ el.addEventListener('click', () => {
860
+ const m = opts.mod;
861
+ if (!m) return;
862
+ // Toggling one mod clears the other (single sticky mod at a time).
863
+ modState[m] = !modState[m];
864
+ Object.keys(modState).forEach((k) => { if (k !== m) modState[k] = false; });
865
+ syncModButtons();
866
+ });
867
+ } else if (opts.kind === 'special' && opts.special === 'del') {
868
+ el.addEventListener('click', () => emitSeq(SEQ.del));
869
+ } else if (opts.seq) {
870
+ el.addEventListener('click', () => emitSeq(opts.seq));
871
+ } else if (opts.literal != null) {
872
+ el.addEventListener('click', () => emitLiteral(opts.literal));
873
+ }
874
+ return el;
875
+ }
876
+
877
+ function makeArrowPad() {
878
+ const wrap = document.createElement('div');
879
+ wrap.className = 'kb-arrows';
880
+ const top = document.createElement('div'); top.className = 'kb-row';
881
+ top.appendChild(makeKey('↑', { seq: SEQ.up, title: 'Up' }));
882
+ const mid = document.createElement('div'); mid.className = 'kb-row';
883
+ mid.appendChild(makeKey('←', { seq: SEQ.left, title: 'Left' }));
884
+ mid.appendChild(makeKey('↓', { seq: SEQ.down, title: 'Down' }));
885
+ mid.appendChild(makeKey('→', { seq: SEQ.right, title: 'Right' }));
886
+ wrap.appendChild(top);
887
+ wrap.appendChild(mid);
888
+ return wrap;
889
+ }
890
+
891
+ function makeGroup(children) {
892
+ const g = document.createElement('div');
893
+ g.className = 'kb-group';
894
+ children.forEach((c) => g.appendChild(c));
895
+ return g;
896
+ }
897
+
898
+ function buildKeyBars() {
899
+ const device = detectDevice();
900
+ document.body.dataset.device = device;
901
+ const iphone = $('#keybarIphone');
902
+ const ipad = $('#keybarIpad');
903
+
904
+ // iPhone: compact single row — essentials only.
905
+ iphone.innerHTML = '';
906
+ if (device === 'iphone') {
907
+ const modifiers = makeGroup([
908
+ makeKey('ESC', { seq: SEQ.esc, title: 'Escape' }),
909
+ makeKey('TAB', { seq: SEQ.tab, title: 'Tab' }),
910
+ makeKey('ENTER', { seq: SEQ.enter, title: 'Enter' }),
911
+ makeKey('Ctrl+b', { seq: SEQ.ctrlB, title: 'Send Ctrl+b to herdr' }),
912
+ makeKey('CTRL', { kind: 'toggle', mod: 'ctrl', title: 'Ctrl (sticky)' })
913
+ ]);
914
+ modifiers.dataset.kb = 'mod';
915
+ const arrows = makeGroup([
916
+ makeKey('←', { seq: SEQ.left }),
917
+ makeKey('↓', { seq: SEQ.down }),
918
+ makeKey('↑', { seq: SEQ.up }),
919
+ makeKey('→', { seq: SEQ.right })
920
+ ]);
921
+ arrows.dataset.kb = 'arrows';
922
+ const symbols = makeGroup([
923
+ makeKey('~', { literal: '~' }),
924
+ makeKey('/', { literal: '/' }),
925
+ makeKey('|', { literal: '|' }),
926
+ makeKey('-', { literal: '-' })
927
+ ]);
928
+ symbols.dataset.kb = 'symbols';
929
+ iphone.append(modifiers, arrows, symbols);
930
+ }
931
+
932
+ // iPad: two deliberate rows — modifiers/navigation, then arrows/symbols.
933
+ ipad.innerHTML = '';
934
+ if (device === 'ipad') {
935
+ const row1 = document.createElement('div');
936
+ row1.className = 'kb-grid-row';
937
+ const modifiers = makeGroup([
938
+ makeKey('ESC', { seq: SEQ.esc, title: 'Escape' }),
939
+ makeKey('TAB', { seq: SEQ.tab, title: 'Tab' }),
940
+ makeKey('ENTER', { seq: SEQ.enter, title: 'Enter' }),
941
+ makeKey('Ctrl+b', { seq: SEQ.ctrlB, title: 'Send Ctrl+b to herdr' }),
942
+ makeKey('CTRL', { kind: 'toggle', mod: 'ctrl', title: 'Ctrl (sticky)' }),
943
+ makeKey('ALT', { kind: 'toggle', mod: 'alt', title: 'Alt / Meta (sticky)' })
944
+ ]);
945
+ modifiers.dataset.kb = 'mod';
946
+ const navigation = makeGroup([
947
+ makeKey('HOME', { seq: SEQ.home }),
948
+ makeKey('END', { seq: SEQ.end }),
949
+ makeKey('PGUP', { seq: SEQ.pgup }),
950
+ makeKey('PGDN', { seq: SEQ.pgdn })
951
+ ]);
952
+ navigation.dataset.kb = 'nav';
953
+ row1.append(modifiers, navigation);
954
+
955
+ const row2 = document.createElement('div');
956
+ row2.className = 'kb-grid-row';
957
+ const arrows = document.createElement('div');
958
+ arrows.className = 'kb-arrow-cluster';
959
+ arrows.dataset.kb = 'arrows';
960
+ const blank = () => {
961
+ const spacer = document.createElement('span');
962
+ spacer.className = 'kb-arrow-empty';
963
+ spacer.setAttribute('aria-hidden', 'true');
964
+ return spacer;
965
+ };
966
+ arrows.append(
967
+ blank(),
968
+ makeKey('↑', { seq: SEQ.up, title: 'Up' }),
969
+ blank(),
970
+ makeKey('←', { seq: SEQ.left, title: 'Left' }),
971
+ makeKey('↓', { seq: SEQ.down, title: 'Down' }),
972
+ makeKey('→', { seq: SEQ.right, title: 'Right' })
973
+ );
974
+ const symbols = makeGroup([
975
+ makeKey('~', { literal: '~' }),
976
+ makeKey('/', { literal: '/' }),
977
+ makeKey('|', { literal: '|' }),
978
+ makeKey('-', { literal: '-' }),
979
+ makeKey('DEL', { kind: 'special', special: 'del', title: 'Delete' })
980
+ ]);
981
+ symbols.dataset.kb = 'symbols';
982
+ row2.append(arrows, symbols);
983
+ ipad.append(row1, row2);
984
+ }
985
+ }
986
+
987
+ // ── Two-finger touch scroll (native iOS feel with momentum) ────────────────
988
+ // One-finger touches pass through to xterm (text selection etc.). Two fingers
989
+ // scroll the scrollback with inertial momentum on release, like a native iOS
990
+ // scroll view.
991
+ function initTouchScroll() {
992
+ if (!term) return;
993
+ const screen = term.element;
994
+ if (!screen) return;
995
+ let scrolling = false;
996
+ let lastY = 0;
997
+ let velocity = 0;
998
+ let lastMoveTs = 0;
999
+ let momentumRaf = 0;
1000
+ let lineHeight = 0;
1001
+
1002
+ function getLineHeight() {
1003
+ if (lineHeight > 0) return lineHeight;
1004
+ const rows = screen.querySelector('.xterm-rows');
1005
+ if (rows) {
1006
+ const lh = parseFloat(getComputedStyle(rows).lineHeight) || 0;
1007
+ if (lh > 0) { lineHeight = lh; return lineHeight; }
1008
+ }
1009
+ // Fallback: derive from terminal font size + line height setting.
1010
+ lineHeight = (term.options.fontSize || 14) * (term.options.lineHeight || 1.2);
1011
+ return lineHeight;
1012
+ }
1013
+
1014
+ function avgY(touches) {
1015
+ let sum = 0;
1016
+ for (let i = 0; i < touches.length; i += 1) sum += touches[i].clientY;
1017
+ return sum / touches.length;
1018
+ }
1019
+
1020
+ function stopMomentum() {
1021
+ if (momentumRaf) { cancelAnimationFrame(momentumRaf); momentumRaf = 0; }
1022
+ }
1023
+
1024
+ function momentumStep() {
1025
+ if (Math.abs(velocity) < 0.5) { momentumRaf = 0; return; }
1026
+ const lh = getLineHeight();
1027
+ const lines = Math.round(velocity / lh);
1028
+ if (lines !== 0 && term) term.scrollLines(lines);
1029
+ velocity *= 0.92; // decay
1030
+ momentumRaf = requestAnimationFrame(momentumStep);
1031
+ }
1032
+
1033
+ const onTouchStart = (e) => {
1034
+ if (e.touches.length !== 2) return;
1035
+ scrolling = true;
1036
+ stopMomentum();
1037
+ lastY = avgY(e.touches);
1038
+ velocity = 0;
1039
+ lastMoveTs = Date.now();
1040
+ };
1041
+
1042
+ const onTouchMove = (e) => {
1043
+ if (!scrolling) return;
1044
+ e.preventDefault();
1045
+ const cur = avgY(e.touches);
1046
+ const dy = lastY - cur; // up-drag (cur smaller) → scroll back (positive)
1047
+ const lh = getLineHeight();
1048
+ const lines = Math.round(dy / lh);
1049
+ if (lines !== 0 && term) term.scrollLines(lines);
1050
+ const now = Date.now();
1051
+ const dt = Math.max(1, now - lastMoveTs);
1052
+ velocity = dy / dt * 16; // px per ~frame
1053
+ lastY = cur;
1054
+ lastMoveTs = now;
1055
+ };
1056
+
1057
+ const endScroll = (e) => {
1058
+ if (!scrolling) return;
1059
+ if (e.touches && e.touches.length >= 2) return; // still two fingers down
1060
+ scrolling = false;
1061
+ if (!window.matchMedia || !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
1062
+ momentumRaf = requestAnimationFrame(momentumStep);
1063
+ }
1064
+ };
1065
+ screen.addEventListener('touchstart', onTouchStart, { passive: true });
1066
+ screen.addEventListener('touchmove', onTouchMove, { passive: false });
1067
+ screen.addEventListener('touchend', endScroll, { passive: true });
1068
+ screen.addEventListener('touchcancel', endScroll, { passive: true });
1069
+ return () => {
1070
+ stopMomentum();
1071
+ screen.removeEventListener('touchstart', onTouchStart);
1072
+ screen.removeEventListener('touchmove', onTouchMove);
1073
+ screen.removeEventListener('touchend', endScroll);
1074
+ screen.removeEventListener('touchcancel', endScroll);
1075
+ };
1076
+ }
1077
+
1078
+ // ── Terminal ────────────────────────────────────────────────────────────────
1079
+ // A phone at 14px gets about 41 columns, which splits ordinary prose inside
1080
+ // words. Use a narrower default on narrow screens unless the user chose a
1081
+ // size with A-/A+, the shortcut, or pinch.
1082
+ function defaultTerminalFontSize() {
1083
+ const stored = lsGet('terminalone.fontSize', null);
1084
+ if (stored) {
1085
+ const parsed = parseInt(stored, 10);
1086
+ if (Number.isFinite(parsed)) return parsed;
1087
+ }
1088
+ const width = window.innerWidth;
1089
+ if (width <= 430) return 11;
1090
+ if (width <= 820) return 12;
1091
+ return 14;
1092
+ }
1093
+
1094
+ function initTerminal() {
1095
+ cleanupTerminalResources();
1096
+ sessionReady = false;
1097
+ resumeReplay = null;
1098
+ replayEnded = false;
1099
+ replayPending = 0;
1100
+ postReplayOutput = [];
1101
+ if (term) {
1102
+ try { term.dispose(); } catch (_) {}
1103
+ }
1104
+
1105
+ term = new Terminal({
1106
+ cursorBlink: true,
1107
+ cursorStyle: 'block',
1108
+ fontSize: defaultTerminalFontSize(),
1109
+ lineHeight: 1.2,
1110
+ fontFamily: STYLES[currentStyle],
1111
+ theme: THEMES[currentTheme].xterm,
1112
+ allowTransparency: true,
1113
+ minimumContrastRatio: 4.5,
1114
+ allowProposedApi: true,
1115
+ scrollback: 10000,
1116
+ convertEol: false
1117
+ });
1118
+
1119
+ fitAddon = new FitAddon();
1120
+ term.loadAddon(fitAddon);
1121
+ term.loadAddon(new WebLinksAddon());
1122
+ term.open($('#terminal'));
1123
+ try {
1124
+ term.parser.registerOscHandler(52, (data) => {
1125
+ const payload = String(data).split(';')[1] || '';
1126
+ if (payload && payload !== '?') {
1127
+ try {
1128
+ const text = atob(payload);
1129
+ if (text) navigator.clipboard?.writeText(text).catch(() => {});
1130
+ } catch (_) { /* malformed clipboard payload */ }
1131
+ }
1132
+ return true;
1133
+ });
1134
+ } catch (_) { /* older xterm without OSC handlers */ }
1135
+ // If resume already selected the old replay dimensions, do not fit to the
1136
+ // new viewport here; replay-end owns that transition.
1137
+ requestAnimationFrame(() => { if (!resumeReplay) fitAddon.fit(); });
1138
+ // Web-font metrics can land after the first paint; refit once they settle.
1139
+ if (document.fonts && document.fonts.ready) {
1140
+ document.fonts.ready.then(() => scheduleFit()).catch(() => {});
1141
+ }
1142
+
1143
+
1144
+ addTerminalResource(initTouchScroll());
1145
+
1146
+ // ── iOS dictation / typing guard ────────────────────────────────────────
1147
+ // Replaced buggy inline debounce (which overwrote fast keystrokes) with
1148
+ // InputGuard: single chars send immediately, duplicated onData events are
1149
+ // dropped, and iOS/IME cumulative partials send only the new suffix.
1150
+
1151
+ function sendInput(data) {
1152
+ if (ws && ws.readyState === WebSocket.OPEN) {
1153
+ ws.send(JSON.stringify({ type: 'input', data }));
1154
+ }
1155
+ }
1156
+ const guard = new InputGuard({ send: sendInput, identicalDedupeMs: 500 });
1157
+ // Expose the sender to the on-screen key bar (outside this closure).
1158
+ sendInputFn = (data) => guard.send(data);
1159
+ bindAttachmentDrop();
1160
+
1161
+ addTerminalResource(bindInputGuard(term, guard));
1162
+
1163
+ // Take focus on load where there is no touchscreen, so the very first
1164
+ // keypress reaches the terminal. A tablet would get its on-screen keyboard
1165
+ // opened uninvited, so those devices rely on the key-capture fallback above.
1166
+ // (Headless Chrome reports a coarse pointer, so maxTouchPoints is the
1167
+ // reliable signal here.)
1168
+ if (!navigator.maxTouchPoints) {
1169
+ requestAnimationFrame(() => { try { term.focus(); } catch (_) {} });
1170
+ }
1171
+
1172
+ // A key typed while <body> has focus never reaches xterm, so the first press
1173
+ // was silently discarded and the user had to press it again. Capture the
1174
+ // first printable key at document level, focus the terminal, and deliver it.
1175
+ // Focusing only happens when the user actually types, so a touch device does
1176
+ // not have its on-screen keyboard opened for it.
1177
+ document.addEventListener('keydown', (event) => {
1178
+ const el = document.activeElement;
1179
+ if (el && el !== document.body) return;
1180
+ if (event.metaKey || event.ctrlKey || event.altKey) return;
1181
+ if (!event.key || event.key.length !== 1) return;
1182
+ try { term.focus(); } catch (_) {}
1183
+ sendInput(event.key);
1184
+ event.preventDefault();
1185
+ }, true);
1186
+
1187
+ addTerminalResource(term.onResize(({ cols, rows }) => {
1188
+ // While replaying, xterm is deliberately at the old PTY width. Sending
1189
+ // that as a resize would yank the live PTY back to the old width. Before
1190
+ // the first ready, a resize would also destroy the old dimensions resume
1191
+ // needs to detect a width change.
1192
+ if (!sessionReady || resumeReplay) return;
1193
+ if (ws && ws.readyState === WebSocket.OPEN) {
1194
+ ws.send(JSON.stringify({ type: 'resize', cols, rows }));
1195
+ }
1196
+ }));
1197
+
1198
+ const ro = new ResizeObserver(() => scheduleFit());
1199
+ ro.observe($('#terminal'));
1200
+ addTerminalResource(() => ro.disconnect());
1201
+ }
1202
+
1203
+ function handleServerMessage(msg) {
1204
+ switch (msg.type) {
1205
+ case 'ready': {
1206
+ sessionReady = true;
1207
+ currentSessionId = msg.sessionId;
1208
+ lsSet(LS_SESSION, msg.sessionId);
1209
+ if (msg.resumed) {
1210
+ // Replay the buffered output at the dimensions it was produced with,
1211
+ // then fit to this viewport after replay-end. Otherwise old wraps and
1212
+ // cursor-addressed lines are reflowed into fragments. A transcript replay
1213
+ // has no control codes, so fit first and write it at the final width.
1214
+ if (term && msg.transcript) {
1215
+ resumeReplay = { transcript: true };
1216
+ replayEnded = false;
1217
+ replayPending = 0;
1218
+ postReplayOutput = [];
1219
+ try {
1220
+ term.reset();
1221
+ if (fitAddon) fitAddon.fit();
1222
+ } catch (_) {
1223
+ resumeReplay = null;
1224
+ }
1225
+ } else if (term && Number.isFinite(msg.cols) && Number.isFinite(msg.rows)) {
1226
+ resumeReplay = { cols: msg.cols, rows: msg.rows };
1227
+ replayEnded = false;
1228
+ replayPending = 0;
1229
+ postReplayOutput = [];
1230
+ try {
1231
+ term.resize(msg.cols, msg.rows);
1232
+ } catch (_) {
1233
+ resumeReplay = null;
1234
+ }
1235
+ }
1236
+ updateStatus('Resumed', 'connected');
1237
+ setFooter(`Resumed · ${msg.cwd}`);
1238
+ } else {
1239
+ resumeReplay = null;
1240
+ replayEnded = false;
1241
+ replayPending = 0;
1242
+ postReplayOutput = [];
1243
+ updateStatus('Connected', 'connected');
1244
+ setFooter(`${msg.command} · ${msg.cwd}`);
1245
+ }
1246
+ setSessionInfo(`session ${msg.sessionId.slice(0, 8)}`, msg.sessionId);
1247
+ window.dispatchEvent(new CustomEvent('t1:session-ready', {
1248
+ detail: { command: msg.command, cwd: msg.cwd, resumed: !!msg.resumed }
1249
+ }));
1250
+ break;
1251
+ }
1252
+ case 'output': {
1253
+ if (resumeReplay) {
1254
+ if (replayEnded) {
1255
+ postReplayOutput.push(msg.data);
1256
+ break;
1257
+ }
1258
+ replayPending += 1;
1259
+ term?.write(msg.data, () => {
1260
+ replayPending = Math.max(0, replayPending - 1);
1261
+ finishReplayIfReady();
1262
+ });
1263
+ break;
1264
+ }
1265
+ term?.write(msg.data);
1266
+ break;
1267
+ }
1268
+ case 'replay-end': {
1269
+ // The old-width buffer has been queued. Wait for xterm to parse it before
1270
+ // fitting; the resulting resize event tells the PTY its new dimensions.
1271
+ replayEnded = true;
1272
+ finishReplayIfReady();
1273
+ break;
1274
+ }
1275
+ case 'exit': {
1276
+ updateStatus(`Exited (code ${msg.code})`, 'error');
1277
+ setFooter(`Process exited · code ${msg.code}`);
1278
+ break;
1279
+ }
1280
+ case 'shell-reset': {
1281
+ // Wiping here erased a failing shell's own error message and made a
1282
+ // respawn storm look like a frozen terminal. Keep what the user saw.
1283
+ term?.write('\r\n\x1b[2m──── shell restarted ────\x1b[0m\r\n');
1284
+ updateStatus('Connected', 'connected');
1285
+ setFooter('Fresh shell — type to continue');
1286
+ break;
1287
+ }
1288
+ case 'resume-failed': {
1289
+ // Target session gone/expired — fall back to a fresh shell on this open ws.
1290
+ resumeReplay = null;
1291
+ replayEnded = false;
1292
+ replayPending = 0;
1293
+ postReplayOutput = [];
1294
+ scheduleFit();
1295
+ infoResumeFail(msg);
1296
+ lsDel(LS_SESSION);
1297
+ currentSessionId = null;
1298
+ if (ws && ws.readyState === WebSocket.OPEN) {
1299
+ const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1300
+ ws.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1301
+ }
1302
+ break;
1303
+ }
1304
+ case 'voice-ready': {
1305
+ window.dispatchEvent(new CustomEvent('t1:voice-ready', { detail: msg }));
1306
+ break;
1307
+ }
1308
+ case 'voice-transcript': {
1309
+ window.dispatchEvent(new CustomEvent('t1:voice-transcript', { detail: msg }));
1310
+ break;
1311
+ }
1312
+ case 'voice-error': {
1313
+ window.dispatchEvent(new CustomEvent('t1:voice-error', { detail: msg }));
1314
+ break;
1315
+ }
1316
+ case 'error': {
1317
+ const errText = `\r\n\x1b[31m[ERROR ${msg.code}]\x1b[0m ${msg.message}\r\n`;
1318
+ term?.write(errText);
1319
+ showBanner(`[${msg.code}] ${msg.message}`, 'error');
1320
+ updateStatus(msg.code, 'error');
1321
+ break;
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ function infoResumeFail(msg) {
1327
+ term?.write(`\r\n\x1b[33m[resume unavailable — starting fresh shell]\x1b[0m\r\n`);
1328
+ }
1329
+
1330
+ function connect() {
1331
+ if (ws && ws.readyState === WebSocket.OPEN) return;
1332
+
1333
+ if (reconnectTimer) {
1334
+ clearTimeout(reconnectTimer);
1335
+ reconnectTimer = null;
1336
+ }
1337
+
1338
+ userInitiatedClose = false;
1339
+
1340
+ if (ws) {
1341
+ try { ws.close(); } catch (_) {}
1342
+ }
1343
+
1344
+ initTerminal();
1345
+ updateStatus('Connecting…', 'connecting');
1346
+ hideBanner();
1347
+
1348
+ const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1349
+ ws = new WebSocket(`${protocol}//${location.host}`);
1350
+
1351
+ ws.onopen = () => {
1352
+ reconnectAttempts = 0;
1353
+ const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1354
+ // If we have a saved session id, try to resume it; otherwise spawn fresh.
1355
+ const savedId = lsGet(LS_SESSION, null);
1356
+ if (savedId) {
1357
+ ws.send(JSON.stringify({ type: 'resume', sessionId: savedId, cols: dims.cols, rows: dims.rows }));
1358
+ } else {
1359
+ ws.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1360
+ }
1361
+ scheduleFit();
1362
+ };
1363
+
1364
+ ws.onmessage = (evt) => {
1365
+ try { handleServerMessage(JSON.parse(evt.data)); }
1366
+ catch (e) { showBanner('Malformed server message', 'error'); }
1367
+ };
1368
+
1369
+ ws.onerror = () => {
1370
+ showBanner('WebSocket connection failed', 'error');
1371
+ updateStatus('WS error', 'error');
1372
+ };
1373
+
1374
+ ws.onclose = () => {
1375
+ if (userInitiatedClose) return;
1376
+ updateStatus('Disconnected', 'error');
1377
+ // Leave the saved session id in place so the reconnect attempts a resume.
1378
+ const delay = Math.min(1_000 * Math.pow(2, reconnectAttempts), 60_000);
1379
+ reconnectAttempts++;
1380
+ reconnectTimer = setTimeout(() => {
1381
+ if (!userInitiatedClose) connect();
1382
+ }, delay);
1383
+ };
1384
+ }
1385
+
1386
+ function closeConnection() {
1387
+ userInitiatedClose = true;
1388
+ reconnectAttempts = 0;
1389
+
1390
+ // Explicit close must never resume: clear the saved session id first.
1391
+ lsDel(LS_SESSION);
1392
+ currentSessionId = null;
1393
+
1394
+ if (reconnectTimer) {
1395
+ clearTimeout(reconnectTimer);
1396
+ reconnectTimer = null;
1397
+ }
1398
+
1399
+ if (ws) {
1400
+ try { ws.send(JSON.stringify({ type: 'close' })); } catch (_) {}
1401
+ ws.close();
1402
+ ws = null;
1403
+ }
1404
+
1405
+ try { term?.dispose(); } catch (_) {}
1406
+ cleanupTerminalResources();
1407
+ term = null;
1408
+ fitAddon = null;
1409
+ sendInputFn = null;
1410
+
1411
+ updateStatus('Closed', 'neutral');
1412
+ setFooter('Connection closed');
1413
+ setSessionInfo('');
1414
+ }
1415
+
1416
+ function restartConnection(sessionId) {
1417
+ userInitiatedClose = true;
1418
+ reconnectAttempts = 0;
1419
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
1420
+ if (ws) {
1421
+ try { ws.onclose = null; ws.close(); } catch (_) {}
1422
+ ws = null;
1423
+ }
1424
+ currentSessionId = null;
1425
+ if (sessionId) lsSet(LS_SESSION, sessionId);
1426
+ else lsDel(LS_SESSION);
1427
+ userInitiatedClose = false;
1428
+ connect();
1429
+ }
1430
+
1431
+ // ── Settings UI ─────────────────────────────────────────────────────────────
1432
+ function buildThemeOptions() {
1433
+ const sel = $('#themeSelect');
1434
+ sel.innerHTML = '';
1435
+ for (const id of THEME_ORDER) {
1436
+ if (!THEMES[id]) continue;
1437
+ const opt = document.createElement('option');
1438
+ opt.value = id;
1439
+ opt.textContent = THEMES[id].name;
1440
+ sel.appendChild(opt);
1441
+ }
1442
+ }
1443
+
1444
+ function setVoiceStatus(text, kind) {
1445
+ const el = $('#voiceStatus');
1446
+ if (!el) return;
1447
+ el.textContent = text || '';
1448
+ el.dataset.kind = kind || '';
1449
+ }
1450
+
1451
+ function fillVoiceFields(data) {
1452
+ $('#voiceCommand').value = data.command || '';
1453
+ $('#voiceModel').value = data.model || '';
1454
+ $('#voiceLanguage').value = data.language || '';
1455
+ $('#voiceArgs').value = data.args || '';
1456
+ }
1457
+
1458
+ async function loadVoiceSettings() {
1459
+ setVoiceStatus('Loading voice settings...');
1460
+ try {
1461
+ const res = await fetch('/api/voice/settings', { cache: 'no-store' });
1462
+ const data = await res.json().catch(() => ({}));
1463
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
1464
+ fillVoiceFields(data);
1465
+ const resolved = data.resolved || {};
1466
+ if (resolved.commandFound) setVoiceStatus(`Command found: ${resolved.commandPath}`, 'ok');
1467
+ else setVoiceStatus(`Command not found: ${data.command || '(empty)'}`, 'error');
1468
+ } catch (err) {
1469
+ setVoiceStatus(`Could not load voice settings: ${err.message || err}`, 'error');
1470
+ }
1471
+ }
1472
+
1473
+ async function saveVoiceSettings() {
1474
+ const button = $('#voiceSave');
1475
+ const body = {
1476
+ command: $('#voiceCommand').value,
1477
+ model: $('#voiceModel').value,
1478
+ language: $('#voiceLanguage').value,
1479
+ args: $('#voiceArgs').value
1480
+ };
1481
+ button.disabled = true;
1482
+ setVoiceStatus('Saving voice settings...');
1483
+ try {
1484
+ const res = await fetch('/api/voice/settings', {
1485
+ method: 'PUT',
1486
+ headers: { 'Content-Type': 'application/json' },
1487
+ body: JSON.stringify(body)
1488
+ });
1489
+ const data = await res.json().catch(() => ({}));
1490
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
1491
+ fillVoiceFields(data);
1492
+ const resolved = data.resolved || {};
1493
+ if (resolved.commandFound) setVoiceStatus(`Saved. Command found: ${resolved.commandPath}`, 'ok');
1494
+ else setVoiceStatus(`Saved, but command not found: ${data.command || '(empty)'}`, 'warn');
1495
+ } catch (err) {
1496
+ setVoiceStatus(`Could not save voice settings: ${err.message || err}`, 'error');
1497
+ } finally {
1498
+ button.disabled = false;
1499
+ }
1500
+ }
1501
+
1502
+ function openSettings() {
1503
+ $('#styleSelect').value = currentStyle;
1504
+ $('#themeSelect').value = currentTheme;
1505
+ loadVoiceSettings();
1506
+ // Settings is a docked peer of the shell, not a modal over it. The terminal
1507
+ // stays visible, live, and operable while settings are adjusted.
1508
+ document.querySelectorAll('dialog.workspace-drawer[open]').forEach((dialog) => dialog.close());
1509
+ $('#settingsModal').classList.add('open');
1510
+ $('#styleSelect').focus();
1511
+ }
1512
+ function closeSettings() {
1513
+ $('#settingsModal').classList.remove('open');
1514
+ document.querySelector('#workspace-tools')?.focus();
1515
+ }
1516
+
1517
+ // ── Wire up ──────────────────────────────────────────────────────────────────
1518
+ buildThemeOptions();
1519
+ buildKeyBars();
1520
+ applyStyle(lsGet(LS_STYLE, DEFAULT_STYLE));
1521
+ applyTheme(lsGet(LS_THEME, DEFAULT_THEME));
1522
+
1523
+ $('#settingsModal').addEventListener('keydown', e => {
1524
+ if (e.key === 'Escape') { e.preventDefault(); closeSettings(); }
1525
+ });
1526
+ $('#settingsBtn').addEventListener('click', openSettings);
1527
+ $('#settingsClose').addEventListener('click', closeSettings);
1528
+ $('#settingsCloseTop').addEventListener('click', closeSettings);
1529
+ $('#settingsModal').addEventListener('click', (e) => { if (e.target === $('#settingsModal')) closeSettings(); });
1530
+ document.addEventListener('keydown', (e) => {
1531
+ if (e.key !== 'Escape' || !$('#settingsModal').classList.contains('open')) return;
1532
+ // Capture-phase: with the terminal live behind the dock, xterm would consume
1533
+ // Escape before a bubble listener could close Settings.
1534
+ e.preventDefault();
1535
+ e.stopPropagation();
1536
+ closeSettings();
1537
+ }, true);
1538
+ $('#styleSelect').addEventListener('change', (e) => applyStyle(e.target.value));
1539
+ $('#themeSelect').addEventListener('change', (e) => applyTheme(e.target.value));
1540
+ $('#voiceSave').addEventListener('click', saveVoiceSettings);
1541
+
1542
+ $('#reconnectBtn').addEventListener('click', () => {
1543
+ // Manual reconnect keeps the saved session id so it resumes.
1544
+ userInitiatedClose = false;
1545
+ connect();
1546
+ });
1547
+ $('#closeBtn').addEventListener('click', closeConnection);
1548
+
1549
+ // Re-detect on orientation change (iPhone↔iPad-like layout shifts are rare,
1550
+ // but viewport reflow should refresh the key bars).
1551
+ window.addEventListener('orientationchange', () => {
1552
+ setTimeout(() => { buildKeyBars(); scheduleFit(); }, 200);
1553
+ });
1554
+
1555
+ // ── Feature module loader ────────────────────────────────────────────────
1556
+ // public/features/*.mjs each export init(T1). This builds the T1 facade the
1557
+ // feature API contract expects, then dynamically imports every module and
1558
+ // runs its init() inside try/catch so one failure cannot break the app.
1559
+ const termReadyCbs = [];
1560
+ function runTermReadyCallback(cb) {
1561
+ if (!term) return;
1562
+ try { addTerminalResource(cb(term)); } catch (_) {}
1563
+ }
1564
+ function onTermReady(cb) {
1565
+ termReadyCbs.push(cb);
1566
+ runTermReadyCallback(cb);
1567
+ }
1568
+ // Re-fire onTermReady callbacks whenever the terminal is recreated on
1569
+ // reconnect. initTerminal() already ran before this loader exists, so fire
1570
+ // for the current term now.
1571
+ function __fireTermReady() { if (term) termReadyCbs.forEach(runTermReadyCallback); }
1572
+ const __origInitTerminal = initTerminal;
1573
+ initTerminal = function () { __origInitTerminal(); __fireTermReady(); };
1574
+ __fireTermReady();
1575
+
1576
+ // ── Toast notification system ─────────────────────────────────────────────
1577
+ // A real transient toast (auto-dismiss) layered above the app. Features call
1578
+ // T1.toast(msg, type) expecting a notification, NOT a persistent status-bar
1579
+ // change. Multiple toasts stack and fade; the toast-status feature wraps
1580
+ // this to also log them.
1581
+ let __toastSeq = 0;
1582
+ function __toastContainer() {
1583
+ let c = document.getElementById('t1toastHost');
1584
+ if (!c) {
1585
+ c = document.createElement('div');
1586
+ c.id = 't1toastHost';
1587
+ c.className = 't1toast-host';
1588
+ // In flow above the terminal: a toast may never cover live output.
1589
+ const shell = document.querySelector('.app-shell');
1590
+ const terminalContainer = shell?.querySelector('.terminal-container');
1591
+ if (shell && terminalContainer) shell.insertBefore(c, terminalContainer);
1592
+ else document.querySelector('.terminal-container')?.appendChild(c);
1593
+ }
1594
+ return c;
1595
+ }
1596
+ function __showToast(msg, type) {
1597
+ const el = document.createElement('div');
1598
+ el.className = `t1toast t1toast-${type || 'info'}`;
1599
+ el.setAttribute('role', 'status');
1600
+ el.textContent = String(msg).slice(0, 160);
1601
+ __toastContainer().appendChild(el);
1602
+ const id = ++__toastSeq;
1603
+ el.dataset.seq = String(id);
1604
+ // Animate in, hold, then fade out and remove.
1605
+ requestAnimationFrame(() => el.classList.add('show'));
1606
+ const ttl = type === 'error' ? 6000 : type === 'warn' ? 4500 : 3000;
1607
+ setTimeout(() => {
1608
+ el.classList.remove('show');
1609
+ setTimeout(() => el.remove(), 350);
1610
+ }, ttl);
1611
+ return id;
1612
+ }
1613
+
1614
+ // A failed or missing local STT command is usually a settings problem; point
1615
+ // the user at the new section instead of only surfacing the raw error code.
1616
+ window.addEventListener('t1:voice-error', (event) => {
1617
+ const code = event.detail && event.detail.code;
1618
+ if (code === 'STT_UNAVAILABLE' || code === 'STT_FAILED') {
1619
+ __showToast('Voice settings: Settings → Voice', 'warn');
1620
+ }
1621
+ });
1622
+
1623
+ const T1 = {
1624
+ get term() { return term; },
1625
+ get ws() { return ws; },
1626
+ // detectDevice() is defined above; surface the current device so features
1627
+ // can gate per-device (desktop-palette, haptic-keys, split-view, etc.).
1628
+ get device() { return document.body.dataset.device || detectDevice(); },
1629
+ sendData: (data) => { if (sendInputFn) sendInputFn(data); },
1630
+ fit: () => scheduleFit(),
1631
+ toast: (msg, type = 'info') => __showToast(msg, type),
1632
+ onTermReady,
1633
+ storage: {
1634
+ get: (k, def) => { const v = lsGet(k, undefined); return v === undefined ? def : v; },
1635
+ set: (k, v) => lsSet(k, String(v)),
1636
+ del: (k) => lsDel(k)
1637
+ },
1638
+ ui: {
1639
+ toolbar: () => document.getElementById('t1toolbar'),
1640
+ appShell: () => document.querySelector('.app-shell'),
1641
+ settingsPanel: () => document.querySelector('#settingsModal .settings-panel'),
1642
+ addStyle: (css) => {
1643
+ const s = document.createElement('style');
1644
+ s.textContent = css;
1645
+ document.head.appendChild(s);
1646
+ },
1647
+ makeButton: (label, title, onClick) => {
1648
+ const b = document.createElement('button');
1649
+ b.type = 'button';
1650
+ b.className = 't1button';
1651
+ b.textContent = label;
1652
+ if (title) b.title = title;
1653
+ if (typeof onClick === 'function') b.addEventListener('click', onClick);
1654
+ return b;
1655
+ }
1656
+ }
1657
+ };
1658
+
1659
+ // Ordered by the ShellFish parity manifest, then the extra verticals.
1660
+ const FEATURE_MODULES = [
1661
+ 'theme-system', 'keyboard-shortcuts', 'history-undo', 'autosave',
1662
+ 'recent-commands', 'search', 'command-palette', 'toast-status',
1663
+ 'osc-bridge', 'links', 'zoom', 'keybar-config', 'voice-input', 'session-manager',
1664
+ 'status-metrics', 'export', 'clipboard', 'snippets', 'fontsize',
1665
+ 'wake-fullscreen', 'desktop-palette', 'floating-palette',
1666
+ 'haptic-keys', 'keepalive', 'multi-window-sync', 'phone-landscape-focus',
1667
+ 'session-lock', 'settings-sync', 'shortcut-help', 'smart-completions',
1668
+ 'smart-suggest', 'split-view', 'stylus-support', 'swipe-history',
1669
+ 'swipe-sessions', 'tab-reorder', 'two-finger-menu', 'window-title'
1670
+ ];
1671
+ (async () => {
1672
+ const loaded = [];
1673
+ for (const name of FEATURE_MODULES) {
1674
+ try {
1675
+ const mod = await import(`./features/${name}.mjs`);
1676
+ if (typeof mod.init === 'function') { mod.init(T1); loaded.push(name); }
1677
+ } catch (err) {
1678
+ console.error(`[features] ${name} failed to load:`, err);
1679
+ }
1680
+ }
1681
+ window.__t1Features = loaded;
1682
+ const workspace = await import('./workspace.mjs');
1683
+ workspace.init(T1);
1684
+ })();
1685
+
1686
+ connect();
1687
+
1688
+ // Best-effort: on touch devices only, shed the browser URL bar by entering
1689
+ // fullscreen on the first user gesture. Gated to iPhone/iPad so a desktop
1690
+ // click is never hijacked into fullscreen. iPhone Safari has no element
1691
+ // Fullscreen API (the requestFullscreen guard no-ops there); the real
1692
+ // chrome-hiding path on iPhone is PWA standalone (Add to Home Screen).
1693
+ (function attemptFullscreenOnce() {
1694
+ const dev = detectDevice();
1695
+ if (dev !== 'iphone' && dev !== 'ipad') return;
1696
+ const standalone =
1697
+ (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) ||
1698
+ window.navigator.standalone === true;
1699
+ if (standalone) return;
1700
+ const target = document.documentElement;
1701
+ if (!target || !target.requestFullscreen) return;
1702
+ function go() {
1703
+ document.removeEventListener('pointerdown', go);
1704
+ document.removeEventListener('keydown', go);
1705
+ if (!document.fullscreenElement) target.requestFullscreen().catch(() => {});
1706
+ }
1707
+ document.addEventListener('pointerdown', go, { passive: true });
1708
+ document.addEventListener('keydown', go);
1709
+ })();
1710
+
1711
+ // Expose for automated tests.
1712
+ window.__terminalOne = {
1713
+ get theme() { return currentTheme; },
1714
+ get style() { return currentStyle; },
1715
+ get device() { return document.body.dataset.device; },
1716
+ themes: () => THEME_ORDER.slice(),
1717
+ setTheme: applyTheme,
1718
+ setStyle: applyStyle,
1719
+ termTheme: () => term && term.options.theme,
1720
+ close: closeConnection,
1721
+ newSession: () => restartConnection(null),
1722
+ switchSession: (id) => restartConnection(id),
1723
+ // Test hooks for the key bar + resume.
1724
+ detectDevice,
1725
+ visibleKeyBar: () => {
1726
+ const d = document.body.dataset.device;
1727
+ if (d === 'iphone') return $('#keybarIphone');
1728
+ if (d === 'ipad') return $('#keybarIpad');
1729
+ return null;
1730
+ },
1731
+ keyCount: () => {
1732
+ const bar = (document.body.dataset.device === 'iphone' ? $('#keybarIphone') : $('#keybarIpad'));
1733
+ return bar ? bar.querySelectorAll('.kb-key').length : 0;
1734
+ },
1735
+ savedSession: () => lsGet(LS_SESSION, null),
1736
+ // Attachment controls insert a shell-quoted path through the same guarded
1737
+ // input path as the keyboard and key bar.
1738
+ sendData: (data) => {
1739
+ if (sendInputFn && typeof data === 'string') sendInputFn(data);
1740
+ },
1741
+ dimensions: () => term ? { cols: term.cols, rows: term.rows } : null,
1742
+ text: () => {
1743
+ if (!term) return '';
1744
+ const buffer = term.buffer.active;
1745
+ const lines = [];
1746
+ for (let i = 0; i < buffer.length; i++) {
1747
+ const line = buffer.getLine(i);
1748
+ lines.push(line ? line.translateToString(true) : '');
1749
+ }
1750
+ return lines.join('\n');
1751
+ }
1752
+ };
1753
+ </script>
1754
+ <script>
1755
+ /* PWA: register the offline shell service worker. Guarded — failure never breaks the app. */
1756
+ if ('serviceWorker' in navigator) {
1757
+ window.addEventListener('load', () => {
1758
+ navigator.serviceWorker.register('/service-worker.js').catch((e) => {
1759
+ console.warn('Townmouse service worker registration failed:', e);
1760
+ });
1761
+ });
1762
+ }
1763
+ </script>
1764
+ </body>
1765
+ </html>