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,85 @@
1
+ /**
2
+ * Swipe-left/right session switcher.
3
+ *
4
+ * Two-finger horizontal swipe or edge swipe switches to next/previous
5
+ * session tab. Wraps around at the ends. Works on phones and tablets.
6
+ */
7
+ export function init(T1) {
8
+ if (T1.device === 'desktop') return;
9
+
10
+ let startX = 0;
11
+ let startY = 0;
12
+ let isTwoFinger = false;
13
+ const EDGE_PX = 28;
14
+
15
+ function getTabs() {
16
+ return Array.from(document.querySelectorAll('.t1session-tab')).filter((t) => !t.classList.contains('t1session-new'));
17
+ }
18
+
19
+ function getActiveIndex(tabs) {
20
+ return tabs.findIndex((t) => t.classList.contains('active'));
21
+ }
22
+
23
+ function switchTo(tabs, idx) {
24
+ if (!tabs.length || idx < 0 || idx >= tabs.length) return;
25
+ tabs[idx].dispatchEvent(new MouseEvent('click', { bubbles: true }));
26
+ T1.toast(`Switched to ${tabs[idx].textContent.trim()}`);
27
+ }
28
+
29
+ function next() {
30
+ const tabs = getTabs();
31
+ let i = getActiveIndex(tabs);
32
+ if (i < 0) i = 0;
33
+ switchTo(tabs, (i + 1) % tabs.length);
34
+ }
35
+
36
+ function prev() {
37
+ const tabs = getTabs();
38
+ let i = getActiveIndex(tabs);
39
+ if (i < 0) i = 0;
40
+ switchTo(tabs, (i - 1 + tabs.length) % tabs.length);
41
+ }
42
+
43
+ const target = T1.term?.element || document.querySelector('.terminal-container') || document.body;
44
+
45
+ target.addEventListener('touchstart', (e) => {
46
+ if (e.touches.length >= 2) {
47
+ isTwoFinger = true;
48
+ startX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
49
+ startY = (e.touches[0].clientY + e.touches[1].clientY) / 2;
50
+ return;
51
+ }
52
+ isTwoFinger = false;
53
+ const t = e.touches[0];
54
+ startX = t.clientX;
55
+ startY = t.clientY;
56
+ }, { passive: true });
57
+
58
+ target.addEventListener('touchend', (e) => {
59
+ if (!startX && !startY) return;
60
+ const t = e.changedTouches[0];
61
+ const dx = t.clientX - startX;
62
+ const dy = Math.abs(t.clientY - startY);
63
+ const minDX = 70;
64
+ const maxDY = 80;
65
+
66
+ if (dy > maxDY) { startX = 0; startY = 0; return; }
67
+
68
+ if (isTwoFinger) {
69
+ if (dx > minDX) { e.preventDefault(); prev(); }
70
+ else if (dx < -minDX) { e.preventDefault(); next(); }
71
+ isTwoFinger = false;
72
+ } else {
73
+ const isEdge = startX <= EDGE_PX || startX >= window.innerWidth - EDGE_PX;
74
+ if (isEdge && Math.abs(dx) > minDX) {
75
+ e.preventDefault();
76
+ if (dx > 0) prev(); else next();
77
+ }
78
+ }
79
+ startX = 0;
80
+ startY = 0;
81
+ }, { passive: false });
82
+
83
+ // Expose for tests.
84
+ window.__terminalOneSwipeSessions = { next, prev, getTabs };
85
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Drag-to-reorder session tabs.
3
+ *
4
+ * Session tabs in the header can be dragged to reorder; the new order is
5
+ * persisted to localStorage.
6
+ */
7
+ const LS_ORDER = 'terminalone.sessionOrder';
8
+
9
+ export function init(T1) {
10
+ const tabsEl = document.querySelector('.t1session-tabs');
11
+ if (!tabsEl) return;
12
+
13
+ T1.ui.addStyle(`
14
+ .t1session-tab[draggable="true"] { cursor: grab; }
15
+ .t1session-tab.dragging { opacity: 0.6; }
16
+ .t1session-tab.drop-target { border-left: 2px solid var(--ui-accent); }
17
+ `);
18
+
19
+ function readOrder() {
20
+ try { return JSON.parse(T1.storage.get(LS_ORDER, '[]')); }
21
+ catch (_) { return []; }
22
+ }
23
+ function writeOrder(order) { T1.storage.set(LS_ORDER, JSON.stringify(order)); }
24
+
25
+ function getIds() {
26
+ return Array.from(tabsEl.querySelectorAll('.t1session-tab')).map((t) => t.dataset.sessionId).filter(Boolean);
27
+ }
28
+
29
+ function wire() {
30
+ const tabs = tabsEl.querySelectorAll('.t1session-tab');
31
+ for (const tab of tabs) {
32
+ if (tab.dataset.reorderWired) continue;
33
+ tab.dataset.reorderWired = '1';
34
+ tab.draggable = true;
35
+ tab.addEventListener('dragstart', (e) => {
36
+ tab.classList.add('dragging');
37
+ e.dataTransfer.setData('text/plain', tab.dataset.sessionId);
38
+ e.dataTransfer.effectAllowed = 'move';
39
+ });
40
+ tab.addEventListener('dragend', () => {
41
+ tab.classList.remove('dragging');
42
+ tabsEl.querySelectorAll('.drop-target').forEach((t) => t.classList.remove('drop-target'));
43
+ writeOrder(getIds());
44
+ });
45
+ tab.addEventListener('dragover', (e) => {
46
+ e.preventDefault();
47
+ const dragging = tabsEl.querySelector('.dragging');
48
+ if (!dragging || dragging === tab) return;
49
+ const after = tab.compareDocumentPosition(dragging) & Node.DOCUMENT_POSITION_FOLLOWING;
50
+ if (after) tabsEl.insertBefore(dragging, tab.nextSibling);
51
+ else tabsEl.insertBefore(dragging, tab);
52
+ });
53
+ }
54
+ }
55
+
56
+ const mo = new MutationObserver(wire);
57
+ mo.observe(tabsEl, { childList: true });
58
+ wire();
59
+
60
+ // Expose for tests.
61
+ window.__terminalOneTabReorder = { wire, readOrder, writeOrder, getIds };
62
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Theme system preference detection — on the first visit with no manually
3
+ * stored theme, follow the OS `prefers-color-scheme` setting. Once the user
4
+ * explicitly picks a theme in Settings we stop syncing so their choice sticks.
5
+ */
6
+ const LS_THEME = 'terminalone.theme';
7
+ const LS_THEME_USER_SET = 'terminalone.themeUserSet';
8
+
9
+ export function init(T1) {
10
+ const darkMq = window.matchMedia('(prefers-color-scheme: dark)');
11
+
12
+ function hasStoredTheme() {
13
+ try { return localStorage.getItem(LS_THEME) !== null; } catch (_) { return false; }
14
+ }
15
+ function userHasSetTheme() {
16
+ try { return localStorage.getItem(LS_THEME_USER_SET) === '1'; } catch (_) { return false; }
17
+ }
18
+ function setUserSetTheme() {
19
+ try { localStorage.setItem(LS_THEME_USER_SET, '1'); } catch (_) {}
20
+ }
21
+
22
+ // If the user has never picked a theme, seed from system preference.
23
+ if (!hasStoredTheme() && !userHasSetTheme()) {
24
+ const systemDark = darkMq.matches;
25
+ const initialTheme = systemDark ? 'tokyo-night' : 'solarized-light';
26
+ if (window.__terminalOne && typeof window.__terminalOne.setTheme === 'function') {
27
+ window.__terminalOne.setTheme(initialTheme);
28
+ } else if (T1.ui && T1.ui.settingsPanel) {
29
+ const sel = document.getElementById('themeSelect');
30
+ if (sel) { sel.value = initialTheme; sel.dispatchEvent(new Event('change')); }
31
+ }
32
+ }
33
+
34
+ // Listen to OS changes and sync only while the user has not manually chosen.
35
+ const onSchemeChange = () => {
36
+ if (userHasSetTheme()) return;
37
+ const theme = darkMq.matches ? 'tokyo-night' : 'solarized-light';
38
+ if (window.__terminalOne && typeof window.__terminalOne.setTheme === 'function') {
39
+ window.__terminalOne.setTheme(theme);
40
+ }
41
+ };
42
+ try { darkMq.addEventListener('change', onSchemeChange); } catch (_) {
43
+ try { darkMq.addListener(onSchemeChange); } catch (_) {}
44
+ }
45
+
46
+ // Mark a manual theme pick so system changes stop overriding it.
47
+ const themeSelect = document.getElementById('themeSelect');
48
+ if (themeSelect) {
49
+ themeSelect.addEventListener('change', () => setUserSetTheme(), { once: true });
50
+ }
51
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Toast notifications and status bar — extends the built-in banner/toast with
3
+ * a persistent log. Clicking the status text opens a small panel showing the
4
+ * last 20 system messages so users can review warnings they missed.
5
+ */
6
+ const KEY = 'terminalone.statusLog';
7
+ const MAX = 20;
8
+
9
+ export function init(T1) {
10
+ const originalToast = T1.toast;
11
+ let log = [];
12
+
13
+ function load() {
14
+ try {
15
+ const v = JSON.parse(T1.storage.get(KEY, '[]'));
16
+ log = Array.isArray(v) ? v.slice(-MAX) : [];
17
+ } catch (_) { log = []; }
18
+ }
19
+ function save() {
20
+ T1.storage.set(KEY, JSON.stringify(log.slice(-MAX)));
21
+ }
22
+ function add(type, msg) {
23
+ log.push({ t: Date.now(), type, msg });
24
+ if (log.length > MAX) log.shift();
25
+ save();
26
+ updatePanel();
27
+ }
28
+
29
+ // Wrap the global toast so every toast is logged.
30
+ T1.toast = function(msg, type = 'info') {
31
+ add(type, msg);
32
+ return originalToast.call(this, msg, type);
33
+ };
34
+
35
+ // Also log connection status changes.
36
+ const statusEl = document.getElementById('status');
37
+ if (statusEl) {
38
+ const obs = new MutationObserver(() => {
39
+ const text = statusEl.textContent;
40
+ if (text && (text.includes('Disconnected') || text.includes('error') || text.includes('Exited'))) {
41
+ add(text.includes('Disconnected') || text.includes('error') ? 'error' : 'warn', text);
42
+ }
43
+ });
44
+ obs.observe(statusEl, { childList: true, subtree: true });
45
+ }
46
+
47
+ // Status panel attached to the footer.
48
+ const footer = document.querySelector('.terminal-footer');
49
+ if (!footer) return;
50
+
51
+ T1.ui.addStyle(`
52
+ .t1status-panel {
53
+ position: absolute;
54
+ bottom: 100%;
55
+ right: 8px;
56
+ z-index: 300;
57
+ min-width: 240px;
58
+ max-width: 80vw;
59
+ max-height: 40vh;
60
+ overflow-y: auto;
61
+ background: var(--ui-elevated);
62
+ border: 1px solid var(--ui-border);
63
+ border-radius: 8px 8px 0 0;
64
+ box-shadow: 0 -8px 32px rgba(0,0,0,0.35);
65
+ display: none;
66
+ flex-direction: column;
67
+ padding: 8px;
68
+ }
69
+ .t1status-panel.open { display: flex; }
70
+ .t1status-entry {
71
+ font-size: 11px;
72
+ padding: 4px 0;
73
+ border-bottom: 1px solid var(--ui-border);
74
+ color: var(--ui-fg);
75
+ }
76
+ .t1status-entry:last-child { border-bottom: none; }
77
+ .t1status-entry.info { color: var(--ui-accent); }
78
+ .t1status-entry.warn { color: var(--ui-warning, #dcc38b); }
79
+ .t1status-entry.error { color: var(--ui-danger, #e2a69e); }
80
+ .t1status-time { color: var(--ui-muted); margin-right: 6px; }
81
+ .t1status-footer { color: var(--ui-muted); font-size: 11px; cursor: pointer; }
82
+ `);
83
+
84
+ const panel = document.createElement('div');
85
+ panel.className = 't1status-panel';
86
+ footer.appendChild(panel);
87
+
88
+ const statusWrap = document.querySelector('.statuswrap');
89
+ const clickTarget = statusWrap || footer;
90
+ clickTarget.style.cursor = 'pointer';
91
+ clickTarget.title = 'Click to view status log';
92
+ clickTarget.addEventListener('click', () => panel.classList.toggle('open'));
93
+
94
+ function updatePanel() {
95
+ panel.innerHTML = '';
96
+ if (!log.length) {
97
+ const empty = document.createElement('div');
98
+ empty.className = 't1status-entry';
99
+ empty.textContent = 'No status messages yet';
100
+ panel.appendChild(empty);
101
+ return;
102
+ }
103
+ for (const entry of log.slice().reverse()) {
104
+ const row = document.createElement('div');
105
+ row.className = `t1status-entry ${entry.type || 'info'}`;
106
+ const time = new Date(entry.t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
107
+ row.innerHTML = `<span class="t1status-time">${time}</span>${entry.msg}`;
108
+ panel.appendChild(row);
109
+ }
110
+ }
111
+
112
+ load();
113
+ updatePanel();
114
+
115
+ document.addEventListener('click', (e) => {
116
+ if (!panel.contains(e.target) && !clickTarget.contains(e.target)) panel.classList.remove('open');
117
+ });
118
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Two-finger tap context menu (tablet).
3
+ *
4
+ * A two-finger tap on the terminal opens a context menu with Copy, Paste,
5
+ * Select All, Clear, and Search.
6
+ */
7
+ export function init(T1) {
8
+ if (T1.device !== 'ipad') return;
9
+
10
+ T1.ui.addStyle(`
11
+ .t1-twofinger-menu {
12
+ position: fixed;
13
+ background: var(--ui-elevated);
14
+ border: 1px solid var(--ui-border);
15
+ border-radius: 8px;
16
+ padding: 4px 0;
17
+ z-index: 210;
18
+ display: none;
19
+ min-width: 140px;
20
+ box-shadow: 0 4px 14px rgba(0,0,0,0.3);
21
+ }
22
+ .t1-twofinger-menu button {
23
+ display: block; width: 100%;
24
+ padding: 8px 14px; background: transparent; border: none;
25
+ color: var(--ui-fg); text-align: left; font-size: 13px; cursor: pointer;
26
+ }
27
+ .t1-twofinger-menu button:active { background: var(--ui-accent); color: var(--ui-on-accent, #14171b); }
28
+ `);
29
+
30
+ const menu = document.createElement('div');
31
+ menu.className = 't1-twofinger-menu';
32
+ menu.setAttribute('role', 'menu');
33
+ menu.innerHTML = `
34
+ <button type="button" role="menuitem" data-action="copy">Copy</button>
35
+ <button type="button" role="menuitem" data-action="paste">Paste</button>
36
+ <button type="button" role="menuitem" data-action="select-all">Select All</button>
37
+ <button type="button" role="menuitem" data-action="clear">Clear</button>
38
+ <button type="button" role="menuitem" data-action="search">Search</button>
39
+ `;
40
+ document.body.appendChild(menu);
41
+
42
+ let firstTouch = null;
43
+ const target = T1.term?.element || document.querySelector('.terminal-container') || document.body;
44
+
45
+ function hide() { menu.style.display = 'none'; }
46
+
47
+ target.addEventListener('touchstart', (e) => {
48
+ if (e.touches.length === 2) {
49
+ firstTouch = { x: (e.touches[0].clientX + e.touches[1].clientX) / 2, y: (e.touches[0].clientY + e.touches[1].clientY) / 2 };
50
+ } else { firstTouch = null; }
51
+ }, { passive: true });
52
+
53
+ target.addEventListener('touchend', (e) => {
54
+ if (!firstTouch || e.touches.length > 0) return;
55
+ e.preventDefault();
56
+ menu.style.left = `${firstTouch.x}px`;
57
+ menu.style.top = `${firstTouch.y}px`;
58
+ menu.style.display = 'block';
59
+ firstTouch = null;
60
+ }, { passive: false });
61
+
62
+ menu.addEventListener('click', async (e) => {
63
+ const action = e.target.dataset.action;
64
+ if (!action) return;
65
+ hide();
66
+ const term = T1.term;
67
+ try {
68
+ if (action === 'copy') {
69
+ const selection = term?.getSelection?.() || '';
70
+ if (!selection) { T1.toast('Select terminal text first', 'warn'); return; }
71
+ await navigator.clipboard.writeText(selection);
72
+ T1.toast('Selection copied');
73
+ }
74
+ if (action === 'paste') {
75
+ const text = await navigator.clipboard.readText();
76
+ if (text) T1.sendData(text);
77
+ }
78
+ if (action === 'select-all' && term) term.selectAll();
79
+ if (action === 'clear' && term) term.clear();
80
+ if (action === 'search') window.dispatchEvent(new CustomEvent('t1:action', { detail: { action: 'toggle-search' } }));
81
+ } catch (_) {
82
+ T1.toast('Clipboard is unavailable in this browser', 'warn');
83
+ }
84
+ });
85
+
86
+ window.__terminalOneTwoFingerMenu = { menu, hide };
87
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Voice input — push-to-talk speech capture into the terminal input line.
3
+ *
4
+ * Captures a short utterance with getUserMedia + MediaRecorder, sends it over
5
+ * the existing JSON WebSocket as bounded base64 chunks, then injects the final
6
+ * server transcript exactly once through T1.sendData(). It never sends Enter.
7
+ */
8
+ const MAX_RECORDING_MS = 20_000;
9
+ const DANGEROUS_COMMAND_RE = /\b(rm\s+-rf|mkfs|dd\s+if=|:\(\)\s*\{|diskutil\s+erase|shutdown|reboot)\b/i;
10
+
11
+ export function init(T1) {
12
+ T1.ui.addStyle(`
13
+ .t1voice-button.listening,
14
+ .t1voice-key.listening {
15
+ background: #e2a69e;
16
+ color: #14171b;
17
+ border-color: #e2a69e;
18
+ }
19
+ .t1voice-button.transcribing,
20
+ .t1voice-key.transcribing {
21
+ background: #dcc38b;
22
+ color: #14171b;
23
+ border-color: #dcc38b;
24
+ }
25
+ .t1voice-key {
26
+ min-width: 64px;
27
+ }
28
+ `);
29
+
30
+ let recorder = null;
31
+ let stream = null;
32
+ let state = 'idle';
33
+ let stopTimer = 0;
34
+ let pendingChunks = Promise.resolve();
35
+ const buttons = new Set();
36
+
37
+ function supported() {
38
+ return !!(navigator.mediaDevices?.getUserMedia && window.MediaRecorder && window.isSecureContext);
39
+ }
40
+
41
+ function wsOpen() {
42
+ const sock = T1.ws;
43
+ return sock && sock.readyState === WebSocket.OPEN ? sock : null;
44
+ }
45
+
46
+ function setState(next) {
47
+ state = next;
48
+ for (const button of buttons) {
49
+ button.classList.toggle('listening', state === 'recording');
50
+ button.classList.toggle('transcribing', state === 'transcribing');
51
+ button.disabled = state === 'transcribing' || !supported();
52
+ button.setAttribute('aria-pressed', state === 'recording' ? 'true' : 'false');
53
+ button.textContent = state === 'recording' ? 'Stop' : state === 'transcribing' ? 'Wait' : 'Voice';
54
+ button.title = supported() ? 'Voice input' : 'Voice input needs a secure connection and a supported browser';
55
+ }
56
+ }
57
+
58
+ function pickMimeType() {
59
+ const candidates = [
60
+ 'audio/webm;codecs=opus',
61
+ 'audio/webm',
62
+ 'audio/mp4',
63
+ 'audio/ogg;codecs=opus'
64
+ ];
65
+ for (const type of candidates) {
66
+ try {
67
+ if (MediaRecorder.isTypeSupported?.(type)) return type;
68
+ } catch (_) {}
69
+ }
70
+ return '';
71
+ }
72
+
73
+ function arrayBufferToBase64(buffer) {
74
+ const bytes = new Uint8Array(buffer);
75
+ let binary = '';
76
+ const stride = 0x8000;
77
+ for (let i = 0; i < bytes.length; i += stride) {
78
+ binary += String.fromCharCode(...bytes.subarray(i, i + stride));
79
+ }
80
+ return btoa(binary);
81
+ }
82
+
83
+ function normalizeTranscript(text) {
84
+ return String(text || '')
85
+ .trim()
86
+ .replace(/\s+/g, ' ')
87
+ .replace(/\s+([|/.-])/g, '$1')
88
+ .replace(/\bpipe\b/gi, '|')
89
+ .replace(/\bslash\b/gi, '/')
90
+ .replace(/\bdash dash\b/gi, '--')
91
+ .replace(/\bdot\b/gi, '.')
92
+ .replace(/[.!?]+$/g, '');
93
+ }
94
+
95
+ function sendJson(payload) {
96
+ const sock = wsOpen();
97
+ if (!sock) {
98
+ T1.toast('Voice input needs an active terminal connection', 'warn');
99
+ return false;
100
+ }
101
+ sock.send(JSON.stringify(payload));
102
+ return true;
103
+ }
104
+
105
+ async function sendBlob(blob) {
106
+ if (!blob || blob.size === 0) return;
107
+ const b64 = arrayBufferToBase64(await blob.arrayBuffer());
108
+ sendJson({ type: 'voice-chunk', b64 });
109
+ }
110
+
111
+ function cleanupRecording() {
112
+ if (stopTimer) {
113
+ clearTimeout(stopTimer);
114
+ stopTimer = 0;
115
+ }
116
+ if (stream) {
117
+ for (const track of stream.getTracks()) track.stop();
118
+ }
119
+ stream = null;
120
+ recorder = null;
121
+ }
122
+
123
+ async function start() {
124
+ if (state !== 'idle') return;
125
+ if (!supported()) {
126
+ T1.toast('Voice input needs a secure connection and a supported browser', 'warn');
127
+ setState('idle');
128
+ return;
129
+ }
130
+ let serverVoiceStarted = false;
131
+ try {
132
+ stream = await navigator.mediaDevices.getUserMedia({
133
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }
134
+ });
135
+ const mimeType = pickMimeType();
136
+ recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
137
+ if (!sendJson({ type: 'voice-start', mimeType: recorder.mimeType || mimeType })) {
138
+ cleanupRecording();
139
+ return;
140
+ }
141
+ serverVoiceStarted = true;
142
+ pendingChunks = Promise.resolve();
143
+ recorder.addEventListener('dataavailable', (event) => {
144
+ pendingChunks = pendingChunks.then(() => sendBlob(event.data)).catch((err) => {
145
+ T1.toast(`Voice chunk failed: ${err.message || err}`, 'error');
146
+ });
147
+ });
148
+ recorder.addEventListener('stop', async () => {
149
+ setState('transcribing');
150
+ await pendingChunks;
151
+ sendJson({ type: 'voice-end' });
152
+ cleanupRecording();
153
+ }, { once: true });
154
+ recorder.start(500);
155
+ setState('recording');
156
+ stopTimer = setTimeout(() => stop(), MAX_RECORDING_MS);
157
+ } catch (err) {
158
+ if (serverVoiceStarted) sendJson({ type: 'voice-end' });
159
+ cleanupRecording();
160
+ setState('idle');
161
+ T1.toast(`Microphone unavailable: ${err.message || err}`, 'error');
162
+ }
163
+ }
164
+
165
+ function stop() {
166
+ if (state !== 'recording' || !recorder) return;
167
+ if (stopTimer) {
168
+ clearTimeout(stopTimer);
169
+ stopTimer = 0;
170
+ }
171
+ try { recorder.stop(); }
172
+ catch (err) {
173
+ cleanupRecording();
174
+ setState('idle');
175
+ T1.toast(`Voice stop failed: ${err.message || err}`, 'error');
176
+ }
177
+ }
178
+
179
+ function toggle() {
180
+ if (state === 'recording') stop();
181
+ else if (state === 'idle') start();
182
+ }
183
+
184
+ function registerButton(button) {
185
+ if (!button || buttons.has(button)) return button;
186
+ buttons.add(button);
187
+ button.addEventListener('click', toggle);
188
+ setState(state);
189
+ return button;
190
+ }
191
+
192
+ const toolbar = T1.ui.toolbar();
193
+ if (toolbar) {
194
+ const button = T1.ui.makeButton('Voice', 'Voice input');
195
+ button.classList.add('t1voice-button');
196
+ button.setAttribute('aria-pressed', 'false');
197
+ toolbar.appendChild(registerButton(button));
198
+ }
199
+
200
+ function ensureKeybarButtons() {
201
+ for (const button of Array.from(buttons)) {
202
+ if (!button.isConnected) buttons.delete(button);
203
+ }
204
+ const device = T1.device;
205
+ const ids = device === 'iphone' ? ['keybarIphone'] : device === 'ipad' ? ['keybarIpad'] : [];
206
+ for (const id of ids) {
207
+ const bar = document.getElementById(id);
208
+ if (!bar || bar.querySelector('.t1voice-key')) continue;
209
+ const group = document.createElement('div');
210
+ group.className = 'kb-group t1voice-group';
211
+ const button = document.createElement('button');
212
+ button.type = 'button';
213
+ button.className = 'kb-key t1voice-key';
214
+ group.appendChild(registerButton(button));
215
+ bar.appendChild(group);
216
+ }
217
+ }
218
+ ensureKeybarButtons();
219
+ window.addEventListener('orientationchange', () => setTimeout(ensureKeybarButtons, 250));
220
+
221
+ window.addEventListener('t1:voice-transcript', (event) => {
222
+ const text = normalizeTranscript(event.detail?.text);
223
+ setState('idle');
224
+ if (!text) {
225
+ T1.toast('No speech detected', 'warn');
226
+ return;
227
+ }
228
+ if (DANGEROUS_COMMAND_RE.test(text) && !confirm(`Insert potentially dangerous command?\n\n${text}`)) {
229
+ T1.toast('Voice command discarded', 'warn');
230
+ return;
231
+ }
232
+ T1.sendData(text);
233
+ T1.toast('Voice transcript inserted');
234
+ });
235
+
236
+ window.addEventListener('t1:voice-error', (event) => {
237
+ setState('idle');
238
+ const code = event.detail?.code || 'VOICE_ERROR';
239
+ const message = event.detail?.message || 'Voice input failed';
240
+ T1.toast(`${code}: ${message}`, 'error');
241
+ });
242
+
243
+ window.__terminalOneVoiceInput = { start, stop, toggle, supported, normalizeTranscript };
244
+ }