townmouse 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +72 -2
  2. package/DESIGN.md +26 -42
  3. package/README.md +286 -54
  4. package/SECURITY.md +3 -0
  5. package/TOWNMOUSE.md +1 -1
  6. package/bin/townmouse +2 -2
  7. package/docs/PACKAGING.md +104 -8
  8. package/docs/browser-workspace.md +62 -9
  9. package/docs/panes.md +199 -9
  10. package/native/TownmouseApp.swift +5 -5
  11. package/npm-shrinkwrap.json +1282 -0
  12. package/package.json +11 -7
  13. package/public/browser-picture.mjs +159 -0
  14. package/public/features/app-version.mjs +35 -0
  15. package/public/features/autosave.mjs +5 -1
  16. package/public/features/multi-window-sync.mjs +3 -1
  17. package/public/features/osc-bridge.mjs +8 -3
  18. package/public/features/session-manager.mjs +202 -100
  19. package/public/features/status-metrics.mjs +23 -0
  20. package/public/features/tab-reorder.mjs +8 -0
  21. package/public/features/window-title.mjs +10 -3
  22. package/public/index.html +617 -78
  23. package/public/input-guard.mjs +10 -2
  24. package/public/panes.css +189 -13
  25. package/public/panes.html +4 -1
  26. package/public/panes.mjs +667 -109
  27. package/public/workspace.css +198 -24
  28. package/public/workspace.mjs +346 -106
  29. package/scripts/install-service.sh +97 -63
  30. package/scripts/panes +134 -5
  31. package/scripts/retire-legacy-service.sh +76 -0
  32. package/scripts/{t1.sh → townmouse.sh} +60 -21
  33. package/scripts/uninstall-service.sh +31 -15
  34. package/src/agent-guide.js +72 -3
  35. package/src/attachments.js +2 -2
  36. package/src/browser-dom.js +5 -2
  37. package/src/browser-workspace.js +549 -62
  38. package/src/owner-page.js +43 -0
  39. package/src/request-boundary.js +1 -1
  40. package/src/server.js +588 -128
  41. package/src/workspace-panes.js +423 -91
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "townmouse",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "A terminal and agent browser workspace built on TerminalOne.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -29,22 +29,25 @@
29
29
  "dev": "scripts/node-runtime.sh exec src/server.js",
30
30
  "doctor": "scripts/node-runtime.sh doctor",
31
31
  "repair": "scripts/node-runtime.sh repair",
32
- "test": "npm run test:security && bash tests/hooks.test.sh && npm run test:unit && scripts/node-runtime.sh exec tests/smoke-test.js && scripts/node-runtime.sh exec tests/feature-test.js && scripts/node-runtime.sh exec tests/feature-behavior-test.js && scripts/node-runtime.sh exec tests/voice-input.test.js && scripts/node-runtime.sh exec tests/responsive-test.js && npm run test:ui && npm run test:panes && npm run test:agent-control && npm run test:voice-routing",
33
- "test:unit": "scripts/node-runtime.sh exec tests/input-guard.test.mjs && node --test tests/input-chunks.test.mjs tests/replay-text.test.mjs tests/attachments-retention.test.mjs tests/service-worker.test.js tests/commercial-polish.test.js tests/autosave-restore.test.mjs tests/shell-resolve.test.js tests/static-deps.test.js tests/pty-permissions.test.js tests/chrome-resolve.test.js tests/safe-regex.test.js && node --test tests/clipboard-text.test.mjs",
32
+ "test": "npm run test:security && bash tests/hooks.test.sh && bash tests/townmouse-docs.test.sh && bash tests/townmouse-launch.test.sh && bash tests/install-service-portability.test.sh && bash tests/townmouse-app-build.test.sh && npm run test:unit && scripts/node-runtime.sh exec tests/smoke-test.js && scripts/node-runtime.sh exec tests/feature-test.js && scripts/node-runtime.sh exec tests/feature-behavior-test.js && scripts/node-runtime.sh exec tests/voice-input.test.js && scripts/node-runtime.sh exec tests/responsive-test.js && npm run test:ui && npm run test:panes && npm run test:agent-control && npm run test:voice-routing",
33
+ "test:unit": "scripts/node-runtime.sh exec tests/input-guard.test.mjs && node --test tests/input-chunks.test.mjs tests/replay-text.test.mjs tests/attachments-retention.test.mjs tests/service-worker.test.js tests/commercial-polish.test.js tests/autosave-restore.test.mjs tests/shell-resolve.test.js tests/static-deps.test.js tests/pty-permissions.test.js tests/chrome-resolve.test.js tests/safe-regex.test.js tests/check-version.test.mjs && node --test tests/clipboard-text.test.mjs",
34
34
  "test:smoke": "scripts/node-runtime.sh exec tests/smoke-test.js",
35
35
  "test:features": "scripts/node-runtime.sh exec tests/feature-test.js",
36
36
  "test:behavior": "scripts/node-runtime.sh exec tests/feature-behavior-test.js",
37
37
  "test:voice": "scripts/node-runtime.sh exec tests/voice-input.test.js",
38
38
  "test:responsive": "scripts/node-runtime.sh exec tests/responsive-test.js",
39
39
  "test:workspace": "scripts/node-runtime.sh exec tests/workspace-journeys.cjs",
40
- "test:ui": "scripts/node-runtime.sh exec tests/ui-surfaces.test.cjs && scripts/node-runtime.sh exec tests/owner-recovery.test.cjs",
40
+ "test:ui": "scripts/node-runtime.sh exec tests/ui-surfaces.test.cjs && scripts/node-runtime.sh exec tests/owner-recovery.test.cjs && scripts/node-runtime.sh exec tests/pane-stability.test.cjs && scripts/node-runtime.sh exec tests/browser-picture-rate.test.cjs && scripts/node-runtime.sh exec tests/resume-replay.test.cjs && scripts/node-runtime.sh exec tests/terminal-fit.test.cjs && npm run test:sessions",
41
+ "test:sessions": "scripts/node-runtime.sh exec tests/session-row.test.cjs",
41
42
  "postinstall": "sh scripts/prepare-native.sh",
42
43
  "test:security": "node --test tests/request-boundary.test.js tests/request-boundary-integration.test.js",
43
- "test:panes": "node tests/panes-api.test.cjs && node tests/panes-persistence.test.cjs && node tests/resume-width.test.cjs && node tests/attachments-ui.test.cjs && node tests/idle-wake.test.cjs && node tests/multi-window.test.cjs",
44
+ "test:panes": "node tests/panes-api.test.cjs && node tests/panes-persistence.test.cjs && node tests/pane-access.test.cjs && node tests/pane-access-ui.test.cjs && node tests/password-results.test.cjs && node tests/owner-key.test.cjs && node tests/resume-width.test.cjs && node tests/attachments-ui.test.cjs && node tests/idle-wake.test.cjs && node tests/multi-window.test.cjs",
44
45
  "test:agent-control": "scripts/node-runtime.sh exec tests/agent-control.test.cjs",
45
46
  "test:voice-routing": "node tests/voice-routing.test.cjs",
46
47
  "test:maximize": "node tests/panes-maximize.test.cjs",
47
- "test:package": "scripts/node-runtime.sh exec tests/package-install.test.cjs"
48
+ "test:package": "scripts/node-runtime.sh exec tests/package-install.test.cjs",
49
+ "version:check": "node scripts/check-version.mjs",
50
+ "version:bump": "node scripts/check-version.mjs --bump"
48
51
  },
49
52
  "dependencies": {
50
53
  "@xterm/addon-fit": "^0.11.0",
@@ -68,7 +71,8 @@
68
71
  "scripts/prepare-native.sh",
69
72
  "scripts/install-service.sh",
70
73
  "scripts/uninstall-service.sh",
71
- "scripts/t1.sh",
74
+ "scripts/retire-legacy-service.sh",
75
+ "scripts/townmouse.sh",
72
76
  "scripts/run-hooks",
73
77
  "README.md",
74
78
  "TOWNMOUSE.md",
@@ -0,0 +1,159 @@
1
+ /*
2
+ * Pictures of a browser page for a person who is looking at it. Both screens
3
+ * use this (a pane's picture on the pane surface, the Browser view on the
4
+ * terminal surface), so the rules live in one place.
5
+ *
6
+ * - A view is "viewed" when a person can see it: the browser tab is showing
7
+ * (not hidden, not minimized) and the view has some area inside the window.
8
+ * - While a view is viewed, one request waits on the server for the next
9
+ * picture, up to `waitMs`. A change is shown as it happens; a still page
10
+ * costs one small request per wait and sends no picture at all.
11
+ * - While a view is not viewed, nothing is asked for, unless `idleMs` is set:
12
+ * then one request per interval keeps its title, address and page prompt
13
+ * current, and the server takes no picture for it.
14
+ * - At most one request is in flight for a view. Becoming viewed asks at once.
15
+ * - A request the server could not hold (all of its waiting slots were taken)
16
+ * is asked again after `retryMs`; a failed one after `failMs`.
17
+ * - `ready`, when given, says whether there is a page to ask about at all.
18
+ */
19
+
20
+ export function createViewedWatch(element, onChange) {
21
+ let intersecting = false;
22
+ let notified = false;
23
+ const viewed = () => Boolean(element) && !document.hidden && intersecting;
24
+ const notify = () => {
25
+ const now = viewed();
26
+ if (now === notified) return;
27
+ notified = now;
28
+ onChange(now);
29
+ };
30
+ let observer = null;
31
+ if (element && typeof IntersectionObserver === 'function') {
32
+ observer = new IntersectionObserver((entries) => {
33
+ for (const entry of entries) {
34
+ // Edge to edge with the window is not "some area inside it".
35
+ const box = entry.intersectionRect;
36
+ intersecting = entry.isIntersecting && box.width > 0 && box.height > 0;
37
+ }
38
+ notify();
39
+ });
40
+ observer.observe(element);
41
+ } else {
42
+ // Without the observer nothing better is known: assume the person can see it.
43
+ intersecting = Boolean(element);
44
+ }
45
+ document.addEventListener('visibilitychange', notify);
46
+ notify();
47
+ return {
48
+ viewed,
49
+ stop() {
50
+ if (observer) observer.disconnect();
51
+ document.removeEventListener('visibilitychange', notify);
52
+ }
53
+ };
54
+ }
55
+
56
+ export function createPictureLoop({ request, apply, failure, viewed, ready = null, waitMs = 500, retryMs = 60, failMs = 1000, idleMs = null }) {
57
+ let busy = false;
58
+ let wanted = false;
59
+ let held = false;
60
+ let failed = false;
61
+ let nextWait = waitMs;
62
+ let timer = 0;
63
+ let controller = null;
64
+ let seq = 0;
65
+ let source = '';
66
+ let stopped = false;
67
+ let started = 0;
68
+ let ended = 0;
69
+ const finished = [];
70
+
71
+ function ask(delay = 0, wait = waitMs) {
72
+ if (stopped) return;
73
+ // Nothing to ask about (no page is open in the view, say): wait until asked again.
74
+ if (ready && !ready()) return;
75
+ nextWait = wait;
76
+ if (busy) {
77
+ wanted = true;
78
+ return;
79
+ }
80
+ // A viewed view is never made to wait to be asked: the request itself
81
+ // waits for the picture. Only the two back-offs are kept as they are.
82
+ const until = viewed() && !failed ? Math.min(delay, retryMs) : delay;
83
+ failed = false;
84
+ clearTimeout(timer);
85
+ timer = setTimeout(() => { timer = 0; void poll(); }, Math.max(0, until));
86
+ }
87
+
88
+ async function poll() {
89
+ if (stopped || busy) return;
90
+ if (ready && !ready()) return;
91
+ started += 1;
92
+ busy = true;
93
+ wanted = false;
94
+ controller = new AbortController();
95
+ const watching = viewed();
96
+ let next = idleMs;
97
+ try {
98
+ const snapshot = await request({ watching, since: seq, waitMs: nextWait, signal: controller.signal });
99
+ if (!snapshot) throw new Error('No answer from the browser.');
100
+ if (stopped) return;
101
+ const fresh = Boolean(snapshot.image) && (snapshot.id !== source || snapshot.seq !== seq);
102
+ if (fresh) {
103
+ source = snapshot.id || source;
104
+ seq = Number(snapshot.seq) || 0;
105
+ }
106
+ held = snapshot.held !== false;
107
+ apply(snapshot, fresh);
108
+ // A server from before this change answers without `seq` and takes a
109
+ // picture for every ask: with one, keep to the old pace of about a second.
110
+ next = watching ? ('seq' in snapshot ? (held ? 0 : retryMs) : failMs) : idleMs;
111
+ } catch (error) {
112
+ if (stopped || controller.signal.aborted) return;
113
+ failed = true;
114
+ failure(error);
115
+ next = watching ? failMs : idleMs;
116
+ } finally {
117
+ controller = null;
118
+ busy = false;
119
+ ended += 1;
120
+ // `null`: not viewed means nothing is asked until the view is viewed again.
121
+ if (next !== null) ask(wanted ? 0 : next, waitMs);
122
+ else if (wanted && viewed()) ask(0, waitMs);
123
+ for (const done of finished.splice(0)) done();
124
+ }
125
+ }
126
+
127
+ const settle = () => new Promise((resolve) => {
128
+ if (!busy && !timer) resolve();
129
+ else finished.push(resolve);
130
+ });
131
+
132
+ return {
133
+ ask,
134
+ // Ask now and do not return before that request has been answered. Used
135
+ // when the person has just acted on the page, or the view was just shown.
136
+ async refresh(wait = waitMs) {
137
+ if (stopped) return;
138
+ if (busy) controller.abort(); // A request already waiting is superseded.
139
+ await settle();
140
+ ask(0, wait);
141
+ await settle();
142
+ },
143
+ // The view can no longer be seen. A request that is waiting is let go at
144
+ // once, so it does not hold one of the browser's few connections.
145
+ unseen() {
146
+ clearTimeout(timer);
147
+ timer = 0;
148
+ if (busy) controller.abort();
149
+ else if (idleMs !== null) ask(idleMs);
150
+ },
151
+ stop() {
152
+ stopped = true;
153
+ clearTimeout(timer);
154
+ timer = 0;
155
+ if (controller) controller.abort();
156
+ },
157
+ since: () => seq
158
+ };
159
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Says which Townmouse version is running.
3
+ *
4
+ * The version comes from the server's health check, so it is the version of
5
+ * the copy that is serving this page and not of a file on a disk somewhere. It
6
+ * is written into every element marked data-app-version-label and kept on the
7
+ * root element for the window title. When it arrives, a "townmouse:version"
8
+ * event is dispatched on the document.
9
+ */
10
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9a-z.-]+)?$/i;
11
+
12
+ export function currentVersion() {
13
+ return document.documentElement.dataset.appVersion || '';
14
+ }
15
+
16
+ export async function loadAppVersion() {
17
+ try {
18
+ const response = await fetch('/health', { cache: 'no-store' });
19
+ if (!response.ok) return '';
20
+ const version = String((await response.json()).version || '');
21
+ if (!VERSION_PATTERN.test(version)) return '';
22
+ document.documentElement.dataset.appVersion = version;
23
+ for (const label of document.querySelectorAll('[data-app-version-label]')) {
24
+ label.textContent = `Townmouse ${version}`;
25
+ }
26
+ document.dispatchEvent(new CustomEvent('townmouse:version', { detail: { version } }));
27
+ return version;
28
+ } catch (_) {
29
+ return '';
30
+ }
31
+ }
32
+
33
+ export function init() {
34
+ void loadAppVersion();
35
+ }
@@ -63,8 +63,12 @@ export function init(T1) {
63
63
  restored = true;
64
64
  // Wait a moment to see if the server sends a resumed session.
65
65
  setTimeout(() => {
66
+ // A resumed shell already has its scrollback back from the server. The
67
+ // saved copy would only paste the last screen on top of it again. Ask
68
+ // the page, not the footer: the footer has usually been rewritten by now.
69
+ const resumed = window.__terminalOne?.sessionView?.()?.resumed === true;
66
70
  const footer = document.getElementById('footerMeta')?.textContent || '';
67
- if (!footer.includes('Resumed')) restore();
71
+ if (!resumed && !footer.includes('Resumed')) restore();
68
72
  }, 400);
69
73
  };
70
74
  T1.onTermReady(() => checkRestore());
@@ -28,7 +28,9 @@ export function init(T1) {
28
28
  let data;
29
29
  try { data = JSON.parse(raw); } catch (_) { return; }
30
30
  if (!data || !data.type) return;
31
- if (data.type === 'session-active' || data.type === 'session-created' || data.type === 'session-deleted') {
31
+ if (data.type === 'session-created' || data.type === 'session-deleted') {
32
+ // A window switching shells is not news in the other windows: each one
33
+ // keeps the shell it is on, and the row already shows every shell.
32
34
  const detail = data.payload || {};
33
35
  if (detail.sessionId) T1.toast(`Synced: ${data.type.replace('session-', '')} ${detail.sessionId.slice(0, 8)}`);
34
36
  }
@@ -17,8 +17,13 @@ export function init(T1) {
17
17
  const osc52Re = /\x1b\]52;[cCsS];([A-Za-z0-9+\/=]*)\x07/g;
18
18
  const osc777Re = /\x1b\]777;([^\x07]*)\x07/g;
19
19
 
20
- term.write = function (data) {
21
- if (typeof data !== 'string') return original(data);
20
+ // xterm's write(data, callback) calls `callback` once the data is on
21
+ // screen. The page waits on that to fit the terminal after a resumed
22
+ // shell's replay. It must be passed on: dropped here (as it was until
23
+ // 2026-11-29), that wait never ended, so nothing the shell printed after
24
+ // such a rejoin was shown and the terminal no longer resized.
25
+ term.write = function (data, callback) {
26
+ if (typeof data !== 'string') return original(data, callback);
22
27
 
23
28
  // OSC 52 — set clipboard. Data is base64.
24
29
  let m;
@@ -53,7 +58,7 @@ export function init(T1) {
53
58
 
54
59
  // Strip the sequences from the visible stream.
55
60
  const cleaned = data.replace(osc52Re, '').replace(osc777Re, '');
56
- return original(cleaned);
61
+ return original(cleaned, callback);
57
62
  };
58
63
  });
59
64
  }
@@ -1,149 +1,251 @@
1
1
  /**
2
- * Session manager — multi-session tabs and session rename for TerminalOne.
2
+ * Session row: one chip per shell in the terminal header.
3
3
  *
4
- * ShellFish parity: switch between named sessions, rename a session.
4
+ * The list of shells belongs to the server. public/index.html keeps a copy of
5
+ * it and announces changes as `t1:sessions-change`; this module only draws it.
5
6
  *
6
- * Note: TerminalOne currently has one live WebSocket per page. This module
7
- * keeps a small client-side registry of sessions and lets the user switch by
8
- * opening the named session id. The server supports resume, so switching to
9
- * an existing session re-attaches the PTY.
7
+ * One button per live session, named as the server names it, with the current
8
+ * one marked; a close control on each; and the + that starts another.
9
+ * Activating a chip switches to that shell and can never start a new one.
10
+ * Closing asks first, in the app's own confirmation (workspace.mjs). The
11
+ * chips are plain buttons with a pressed state, so they are reachable by
12
+ * keyboard; Left and Right move between them.
13
+ *
14
+ * It keeps no list of its own. An earlier version remembered session names in
15
+ * localStorage, under two different keys per session, so the row showed chips
16
+ * for shells that had ended and lost the rest after five.
10
17
  */
11
- const LS_NAMES = 'terminalone.sessionNames';
12
- const MAX_SESSIONS = 5;
18
+
19
+ const ICONS = {
20
+ close: 'M6 6l12 12M18 6L6 18',
21
+ plus: 'M12 5v14M5 12h14'
22
+ };
23
+ const icon = (name) => '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="' + ICONS[name] + '"/></svg>';
13
24
 
14
25
  export function init(T1) {
15
26
  const header = document.querySelector('.terminal-header');
16
27
  if (!header) return;
17
28
 
18
- const names = readNames();
19
- let activeId = null;
20
- let switchCallback = null;
21
-
22
29
  T1.ui.addStyle(`
23
30
  .t1session-tabs {
31
+ display: flex;
32
+ align-items: center;
33
+ gap: 6px;
34
+ margin-left: 4px;
35
+ flex: 0 1 auto;
36
+ min-width: 0;
37
+ }
38
+ .t1session-strip {
24
39
  display: flex;
25
40
  align-items: center;
26
41
  gap: 4px;
27
- margin-left: 12px;
28
42
  flex: 0 1 auto;
29
43
  min-width: 0;
30
- overflow: hidden;
44
+ overflow-x: auto;
45
+ overflow-y: hidden;
46
+ scrollbar-width: none;
47
+ scroll-behavior: smooth;
48
+ /* Keep the current chip clear of the fade when it is scrolled into view. */
49
+ scroll-padding-inline: 20px;
31
50
  }
32
- .t1session-tab {
51
+ .t1session-strip::-webkit-scrollbar { display: none; }
52
+ .t1session-chip {
33
53
  display: inline-flex;
34
54
  align-items: center;
35
- gap: 4px;
36
- padding: 3px 8px;
37
- font-size: 11px;
38
- background: var(--ui-bg);
39
- border: 1px solid var(--ui-border);
55
+ flex: 0 0 auto;
56
+ min-height: 44px;
57
+ border: 1px solid transparent;
40
58
  border-radius: 4px;
41
59
  color: var(--ui-muted);
42
- cursor: pointer;
43
- white-space: nowrap;
44
- user-select: none;
60
+ transition: background-color 200ms, border-color 200ms, color 200ms;
45
61
  }
46
- .t1session-tab.active {
47
- color: var(--ui-fg);
48
- border-color: var(--ui-accent);
49
- }
50
- .t1session-tab input {
51
- width: 80px;
62
+ .t1session-chip.active { color: var(--ui-fg); border-color: var(--ui-accent); }
63
+ .t1session-tab {
64
+ display: inline-flex;
65
+ align-items: center;
66
+ min-width: 0;
67
+ max-width: 180px;
68
+ padding: 3px 8px;
69
+ border: 0;
52
70
  background: transparent;
53
- border: none;
54
71
  color: inherit;
55
72
  font: inherit;
73
+ font-size: 11px;
74
+ white-space: nowrap;
75
+ overflow: hidden;
76
+ text-overflow: ellipsis;
77
+ cursor: pointer;
78
+ }
79
+ .t1session-close {
80
+ display: inline-flex;
81
+ align-items: center;
82
+ justify-content: center;
83
+ flex: 0 0 auto;
84
+ width: 28px;
85
+ min-height: 44px;
56
86
  padding: 0;
57
- outline: none;
87
+ border: 0;
88
+ background: transparent;
89
+ color: var(--ui-muted);
90
+ cursor: pointer;
58
91
  }
92
+ .t1session-close svg { width: 14px; height: 14px; }
93
+ .t1session-close:hover { color: var(--ui-fg); }
59
94
  .t1session-new {
60
- font-size: 14px;
95
+ display: inline-flex;
96
+ align-items: center;
97
+ justify-content: center;
98
+ flex: 0 0 auto;
99
+ min-width: 44px;
100
+ min-height: 44px;
101
+ padding: 0;
61
102
  line-height: 1;
62
- padding: 3px 6px;
103
+ }
104
+ .t1session-new svg { width: 18px; height: 18px; }
105
+ @media (pointer: coarse) {
106
+ .t1session-close { width: 44px; }
107
+ }
108
+ /* Where the row holds more chips than it can show, that edge fades, so a
109
+ chip cut at the edge reads as "more this way" rather than as a fault. */
110
+ .t1session-strip.more-left {
111
+ -webkit-mask-image: linear-gradient(to right, transparent, #000 20px);
112
+ mask-image: linear-gradient(to right, transparent, #000 20px);
113
+ }
114
+ .t1session-strip.more-right {
115
+ -webkit-mask-image: linear-gradient(to left, transparent, #000 20px);
116
+ mask-image: linear-gradient(to left, transparent, #000 20px);
117
+ }
118
+ .t1session-strip.more-left.more-right {
119
+ -webkit-mask-image: linear-gradient(to right, transparent, #000 20px), linear-gradient(to left, transparent, #000 20px);
120
+ mask-image: linear-gradient(to right, transparent, #000 20px), linear-gradient(to left, transparent, #000 20px);
121
+ -webkit-mask-composite: source-in;
122
+ mask-composite: intersect;
123
+ }
124
+ @media (prefers-reduced-motion: reduce) {
125
+ .t1session-strip { scroll-behavior: auto; }
126
+ .t1session-chip { transition: none; }
63
127
  }
64
128
  `);
65
129
 
66
130
  const tabsEl = document.createElement('div');
67
131
  tabsEl.className = 't1session-tabs';
68
- // Insert after the title.
132
+ tabsEl.id = 't1session-tabs';
133
+ const strip = document.createElement('div');
134
+ strip.className = 't1session-strip';
135
+ strip.setAttribute('role', 'group');
136
+ strip.setAttribute('aria-label', 'Shell sessions');
137
+ const plus = document.createElement('button');
138
+ plus.type = 'button';
139
+ plus.className = 't1session-new';
140
+ plus.id = 't1session-new';
141
+ plus.setAttribute('aria-label', 'New terminal session');
142
+ plus.title = 'New terminal session';
143
+ plus.innerHTML = icon('plus');
144
+ // At the session limit this opens the Sessions list instead of starting one.
145
+ plus.addEventListener('click', () => window.__terminalOne?.requestNewSession?.());
146
+ tabsEl.append(strip, plus);
147
+ // The row sits between the title and the session pill.
69
148
  const title = header.querySelector('.terminal-title');
70
149
  title?.parentNode?.insertBefore(tabsEl, title.nextSibling);
71
150
 
72
- function readNames() {
73
- try { return JSON.parse(T1.storage.get(LS_NAMES, '{}')); } catch (_) { return {}; }
74
- }
75
- function writeNames(n) {
76
- try { T1.storage.set(LS_NAMES, JSON.stringify(n)); } catch (_) {}
151
+ function makeChip(session) {
152
+ const chip = document.createElement('div');
153
+ chip.className = 't1session-chip';
154
+ chip.dataset.sessionId = session.id;
155
+ chip.setAttribute('role', 'presentation');
156
+ const tab = document.createElement('button');
157
+ tab.type = 'button';
158
+ tab.className = 't1session-tab';
159
+ tab.setAttribute('aria-pressed', 'false');
160
+ tab.addEventListener('click', () => window.__terminalOne?.switchSession?.(session.id));
161
+ const close = document.createElement('button');
162
+ close.type = 'button';
163
+ close.className = 't1session-close';
164
+ close.innerHTML = icon('close');
165
+ close.addEventListener('click', () => window.__terminalOne?.requestClose?.(session.id));
166
+ chip.append(tab, close);
167
+ return chip;
77
168
  }
78
169
 
79
- function setName(id, newName) {
80
- if (!id) return;
81
- names[id] = newName || id.slice(0, 8);
82
- writeNames(names);
83
- render();
170
+ let signature = '';
171
+ function render() {
172
+ const api = window.__terminalOne;
173
+ if (!api) return;
174
+ const sessions = api.sessions?.() || [];
175
+ const currentId = api.sessionView?.().current?.id || '';
176
+ const next = sessions
177
+ .map((session) => `${session.id}\u0000${session.name}\u0000${session.id === currentId ? 1 : 0}`)
178
+ .join('\u0001');
179
+ if (next === signature) return;
180
+ signature = next;
181
+ const kept = new Map([...strip.querySelectorAll('.t1session-chip')].map((chip) => [chip.dataset.sessionId, chip]));
182
+ const hasCurrent = sessions.some((session) => session.id === currentId);
183
+ sessions.forEach((session, index) => {
184
+ let chip = kept.get(session.id);
185
+ if (!chip) {
186
+ chip = makeChip(session);
187
+ } else {
188
+ kept.delete(session.id);
189
+ }
190
+ const tab = chip.firstElementChild;
191
+ const close = chip.lastElementChild;
192
+ const current = session.id === currentId;
193
+ chip.classList.toggle('active', current);
194
+ tab.classList.toggle('active', current);
195
+ tab.setAttribute('aria-pressed', String(current));
196
+ // One stop in the Tab order: the current chip, else the first.
197
+ tab.tabIndex = current || (!hasCurrent && index === 0) ? 0 : -1;
198
+ tab.textContent = session.name;
199
+ // The tooltip says what a click does: nothing about a chip is left to
200
+ // the shape of the pointer alone.
201
+ const where = session.cwd ? ` · ${session.cwd}` : '';
202
+ tab.title = current ? `${session.name}${where} · current shell` : `Switch to ${session.name}${where}`;
203
+ close.setAttribute('aria-label', `Close ${session.name}`);
204
+ close.title = `Close ${session.name}`;
205
+ strip.append(chip);
206
+ });
207
+ for (const stale of kept.values()) stale.remove();
208
+ keepCurrentVisible();
209
+ showEdges();
84
210
  }
85
211
 
86
- function render() {
87
- tabsEl.innerHTML = '';
88
- // Always show a tab for the active session.
89
- const ids = Object.keys(names);
90
- if (activeId && !names[activeId]) {
91
- names[activeId] = activeId.slice(0, 8);
92
- writeNames(names);
93
- }
94
- for (const id of ids.slice(-MAX_SESSIONS)) {
95
- const tab = document.createElement('div');
96
- tab.className = `t1session-tab ${id === activeId ? 'active' : ''}`;
97
- const span = document.createElement('span');
98
- span.textContent = names[id] || id.slice(0, 8);
99
- tab.appendChild(span);
100
- tab.addEventListener('click', (e) => {
101
- if (e.target === span) {
102
- if (id !== activeId && typeof switchCallback === 'function') switchCallback(id);
103
- }
104
- });
105
- tab.addEventListener('dblclick', () => {
106
- const input = document.createElement('input');
107
- input.value = span.textContent;
108
- tab.replaceChild(input, span);
109
- input.focus();
110
- input.select();
111
- const finish = () => { setName(id, input.value); };
112
- input.addEventListener('keydown', (e) => { if (e.key === 'Enter') finish(); if (e.key === 'Escape') render(); });
113
- input.addEventListener('blur', finish);
114
- });
115
- tabsEl.appendChild(tab);
212
+ // The person must always see which shell is current, including when the row
213
+ // gets narrower (a dock or a browser pane opens) without the list changing.
214
+ function keepCurrentVisible() {
215
+ const current = strip.querySelector('.t1session-chip.active');
216
+ if (current && strip.scrollWidth > strip.clientWidth + 1) {
217
+ current.scrollIntoView({ block: 'nearest', inline: 'nearest' });
116
218
  }
117
- const plus = document.createElement('button');
118
- plus.className = 't1session-tab t1session-new';
119
- plus.title = 'New session';
120
- plus.textContent = '+';
121
- plus.addEventListener('click', () => {
122
- if (typeof switchCallback === 'function') switchCallback('__new__');
123
- });
124
- tabsEl.appendChild(plus);
125
219
  }
126
220
 
127
- // Listen for active session changes.
128
- const infoEl = document.getElementById('sessionInfo');
129
- if (infoEl) {
130
- const observer = new MutationObserver(() => {
131
- const text = infoEl.textContent || '';
132
- const m = text.match(/session\s+([a-f0-9\-]+)/);
133
- if (m) {
134
- activeId = m[1];
135
- if (!names[activeId]) setName(activeId, activeId.slice(0, 8));
136
- else render();
137
- }
138
- });
139
- observer.observe(infoEl, { childList: true });
221
+ // Fade the edges that hide chips (see the style above).
222
+ function showEdges() {
223
+ strip.classList.toggle('more-left', strip.scrollLeft > 1);
224
+ strip.classList.toggle('more-right', strip.scrollLeft + strip.clientWidth < strip.scrollWidth - 1);
140
225
  }
226
+ const rowSettled = () => requestAnimationFrame(() => { keepCurrentVisible(); showEdges(); });
227
+ strip.addEventListener('scroll', showEdges, { passive: true });
228
+ if (typeof ResizeObserver === 'function') new ResizeObserver(rowSettled).observe(strip);
229
+ window.addEventListener('resize', rowSettled);
230
+ // A dock closing or opening can leave the row wide for a single layout and
231
+ // narrow again in the same frame, which resets its scroll place without any
232
+ // change of size for a resize observer to report. Watch the docks instead.
233
+ new MutationObserver(rowSettled)
234
+ .observe(document.body, { attributes: true, attributeFilter: ['open'], subtree: true });
141
235
 
142
- // Allow other modules to register the switch handler.
143
- window.__terminalOne = window.__terminalOne || {};
144
- window.__terminalOne.setSessionSwitchCallback = (cb) => { switchCallback = cb; };
145
- window.__terminalOne.renameSession = (id, name) => setName(id, name);
146
- window.__terminalOne.sessionNames = () => ({ ...names });
236
+ strip.addEventListener('keydown', (event) => {
237
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
238
+ const tabs = [...strip.querySelectorAll('.t1session-tab')];
239
+ const at = tabs.indexOf(document.activeElement);
240
+ if (at < 0 || !tabs.length) return;
241
+ event.preventDefault();
242
+ const next = event.key === 'Home' ? 0
243
+ : event.key === 'End' ? tabs.length - 1
244
+ : (at + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
245
+ tabs[next].focus();
246
+ });
147
247
 
248
+ window.addEventListener('t1:sessions-change', render);
249
+ window.addEventListener('t1:session-ready', render);
148
250
  render();
149
251
  }