pinokiod 8.3.28 → 8.3.30

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.
package/kernel/shell.js CHANGED
@@ -24,6 +24,7 @@ const ShellRunTemplate = require('./api/shell_run_template')
24
24
  const { PYTHON_INSTALL_SPEC, PIP_WHEEL, PIP_SEED_SCRIPT } = require('./bin/conda-pins')
25
25
  const CondaRuntimeGuard = require('./shell_conda_runtime_guard')
26
26
  const WindowsConsole = require('./windows_console')
27
+ const ShellSize = require('./shell_size')
27
28
  const { managedCertPaths, applyManagedCertEnv, repairPipVendoredBundle, explorerHref } = require('./cert_env')
28
29
  const escapeHtml = require('escape-html')
29
30
  const home = os.homedir()
@@ -524,6 +525,7 @@ class Shell {
524
525
 
525
526
  // 1. id
526
527
  this.id = (params.id ? params.id : uuidv4())
528
+ ShellSize.track(this, params)
527
529
  const explicitTerminalId = typeof params.terminal_id === "string" ? params.terminal_id.trim() : ""
528
530
  const resolvedTerminalId = explicitTerminalId || extractTerminalIdFromShellId(this.id)
529
531
  this.terminal_id = resolvedTerminalId || null
@@ -1535,6 +1537,7 @@ class Shell {
1535
1537
  this.kernel.shell.rm(this.id)
1536
1538
  return ""
1537
1539
  }
1540
+ if (!this.ptyProcess) ShellSize.beforeSpawn(this)
1538
1541
  let res = await new Promise((resolve, reject) => {
1539
1542
  this.resolve = resolve
1540
1543
  this.reject = reject
@@ -0,0 +1,99 @@
1
+ // The size a new shell starts at.
2
+ //
3
+ // A script run carries one record of the page's terminal size, taken when the
4
+ // run was launched. Every step of the run starts a new shell from that record.
5
+ // A resize from the page reaches the shell that is running at that moment, but
6
+ // the record stayed as it was, so the next step's shell started at the size
7
+ // the page had at launch, however often it had changed since. The shell and
8
+ // the page then disagree about the width for that whole step. On Windows the
9
+ // console layer redraws the screen with its own width, so the output of a
10
+ // progress display comes out shifted or stair-stepped.
11
+ //
12
+ // So the record is kept current here: a resize is written into it, whether or
13
+ // not a shell is running to receive it (one that lands between two steps has
14
+ // none), and a shell takes its size from the record right before its console
15
+ // is created, which is after the setup work a resize can arrive during.
16
+
17
+ const crypto = require('crypto')
18
+
19
+ // shell id -> run record, for a resize that arrives while no shell with that
20
+ // id is running. An entry stays after its shell ends; that is the point.
21
+ const idle = new Map()
22
+ // Ids are not reused across runs, so the oldest are dropped past this many.
23
+ const MAX_IDLE = 500
24
+
25
+ const valid = (n) => Number.isInteger(n) && n > 0
26
+ const validSize = (size) => !!size && valid(size.cols) && valid(size.rows)
27
+
28
+ // The run record a shell was started under. A shell started outside a script
29
+ // run (a plain terminal) has none and is left alone throughout.
30
+ const recordOf = (params) => {
31
+ const record = params && params.$parent && params.$parent.client
32
+ return record && typeof record === "object" ? record : null
33
+ }
34
+
35
+ // Called once a starting shell has its id.
36
+ const track = (shell, params) => {
37
+ const record = recordOf(params)
38
+ if (!record) return
39
+ idle.delete(shell.id)
40
+ idle.set(shell.id, record)
41
+ if (idle.size > MAX_IDLE) {
42
+ idle.delete(idle.keys().next().value)
43
+ }
44
+ }
45
+
46
+ // Called right before a shell's console is created: brings the shell to the
47
+ // run's current size if that changed since the step began.
48
+ const beforeSpawn = (shell) => {
49
+ const record = recordOf(shell.params)
50
+ if (!record) return
51
+ // A step that sets its own size keeps it; it still belongs to the run.
52
+ const own = shell.params.client
53
+ const follows = !(own && (own.cols || own.rows))
54
+ log.start(shell, record, follows)
55
+ if (follows && validSize(record) && (record.cols !== shell.cols || record.rows !== shell.rows)) {
56
+ shell.resize({ cols: record.cols, rows: record.rows })
57
+ }
58
+ }
59
+
60
+ // A resize arrived for a shell id. `shell` is the running shell with that id,
61
+ // if there is one: its own run takes the new size. With no shell running, the
62
+ // run that last used the id does.
63
+ const resized = (id, size, shell) => {
64
+ const record = shell ? recordOf(shell.params) : idle.get(id)
65
+ const recorded = !!record && validSize(size)
66
+ if (recorded) {
67
+ record.cols = size.cols
68
+ record.rows = size.rows
69
+ }
70
+ log.resize(id, size, !!shell, recorded)
71
+ }
72
+
73
+ // TEMPORARY DIAGNOSTIC — remove once the Windows 10 width reports are settled.
74
+ // One line when a script run's shell starts and one per resize, in the server
75
+ // output (logs/stdout.txt), to show where a shell's width and the page's part ways.
76
+ const TAG = "[term-size]"
77
+ // An id can hold a command line or a URL, so only a fingerprint of it is
78
+ // written: enough to tell which lines belong to the same shell.
79
+ const tag = (id) => crypto.createHash('sha1').update(String(id)).digest('hex').slice(0, 8)
80
+ const fmt = (size) => (size && (size.cols || size.rows)) ? `${size.cols}x${size.rows}` : "none"
81
+ const launched = new WeakSet()
82
+ const log = {
83
+ start(shell, record, follows) {
84
+ try {
85
+ if (!launched.has(record)) {
86
+ launched.add(record)
87
+ console.log(`${TAG} launch id=${tag(shell.id)} page=${fmt(record)}`)
88
+ }
89
+ console.log(`${TAG} shell start id=${tag(shell.id)} step=${fmt(shell)} run=${fmt(record)} follows=${follows ? "yes" : "no"}`)
90
+ } catch (_) {}
91
+ },
92
+ resize(id, size, running, recorded) {
93
+ try {
94
+ console.log(`${TAG} resize id=${tag(id)} size=${fmt(size)} shell=${running ? "yes" : "no"} run=${recorded ? "updated" : "none"}`)
95
+ } catch (_) {}
96
+ }
97
+ }
98
+
99
+ module.exports = { track, beforeSpawn, resized }
package/kernel/shells.js CHANGED
@@ -9,6 +9,7 @@ const {
9
9
 
10
10
  const path = require('path')
11
11
  const Shell = require("./shell")
12
+ const ShellSize = require("./shell_size")
12
13
  const { detect: detectBracketedPasteSupport } = require('./bracketed_paste_detector')
13
14
  class Shells {
14
15
  constructor(kernel) {
@@ -762,6 +763,7 @@ class Shells {
762
763
  }
763
764
  */
764
765
  let session = this.get(params.id)
766
+ ShellSize.resized(params.id, params.resize, session)
765
767
  if (session) {
766
768
  session.resize(params.resize)
767
769
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.28",
3
+ "version": "8.3.30",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/server/index.js CHANGED
@@ -6616,6 +6616,8 @@ class Server {
6616
6616
  res.locals.vaultAutomaticSupported = !!(
6617
6617
  this.kernel.vault && this.kernel.vault.automaticScans &&
6618
6618
  this.kernel.vault.automaticScans.supported)
6619
+ // Pinokio's own folder, for the pages that tell it apart from an app's
6620
+ res.locals.pinokioHome = this.kernel.homedir || ""
6619
6621
  next()
6620
6622
  })
6621
6623
  this.app.use(cors({
@@ -0,0 +1,67 @@
1
+ /* An Ask pointed at one app, from home (see agent-bar-about.js).
2
+ At rest the mode chip names the app ("Ask · <app>"); a long name is cut. */
3
+ .agent-bar[data-about]:not([data-about=""]) .agent-bar__scope-label {
4
+ max-width: 200px;
5
+ overflow: hidden;
6
+ text-overflow: ellipsis;
7
+ white-space: nowrap;
8
+ }
9
+
10
+ /* The chip in the open view's bottom row, at the left: the app's icon and name,
11
+ and an x that makes it an ordinary Ask again. It looks like an attached
12
+ file's chip. */
13
+ .agent-bar .agent-bar__about {
14
+ display: inline-flex;
15
+ align-items: center;
16
+ gap: 6px;
17
+ min-width: 0;
18
+ max-width: 240px;
19
+ height: 28px;
20
+ box-sizing: border-box;
21
+ padding: 0 4px 0 6px;
22
+ border-radius: 14px;
23
+ background: var(--agent-bar-chip);
24
+ font: 500 13px system-ui, -apple-system, "Segoe UI", sans-serif;
25
+ color: var(--agent-bar-text);
26
+ }
27
+ .agent-bar .agent-bar__about[hidden],
28
+ .agent-bar .agent-bar__about-icon[hidden] {
29
+ display: none;
30
+ }
31
+ .agent-bar .agent-bar__about-icon {
32
+ flex: none;
33
+ width: 18px;
34
+ height: 18px;
35
+ border-radius: 5px;
36
+ object-fit: cover;
37
+ }
38
+ .agent-bar .agent-bar__about-name {
39
+ min-width: 0;
40
+ overflow: hidden;
41
+ text-overflow: ellipsis;
42
+ white-space: nowrap;
43
+ }
44
+ .agent-bar .agent-bar__about-x {
45
+ flex: none;
46
+ width: 20px;
47
+ height: 20px;
48
+ display: inline-flex;
49
+ align-items: center;
50
+ justify-content: center;
51
+ padding: 0;
52
+ border: 0;
53
+ border-radius: 10px;
54
+ background: transparent;
55
+ font-size: 10px;
56
+ cursor: pointer;
57
+ }
58
+ .agent-bar button.agent-bar__about-x {
59
+ color: var(--agent-bar-muted);
60
+ }
61
+ .agent-bar button.agent-bar__about-x:hover {
62
+ background: var(--agent-bar-chip-hover);
63
+ color: var(--agent-bar-text);
64
+ }
65
+ .agent-bar button.agent-bar__about-x:disabled {
66
+ opacity: 0.4;
67
+ }
@@ -0,0 +1,205 @@
1
+ // Agent bar: an Ask pointed at one app, from home.
2
+ //
3
+ // Every row of My Apps has an "Ask about this app" button (drawn by the page,
4
+ // partials/home_ask_button.ejs). A click does not open the app's page and does
5
+ // not start the app: it points the bar at the top of the page at that app.
6
+ //
7
+ // click on a row's button -> the bar is on Ask, with the cursor in the text,
8
+ // and says which app it is about: the mode chip at rest
9
+ // ("Ask · <app>"), the empty text ("Ask Pinokio about <app>…"),
10
+ // what the face says in the open view, and a chip with the
11
+ // app's icon and name at the left of the open view's bottom row.
12
+ // the chip's x, or another mode -> an ordinary Ask again.
13
+ // send -> the same request the app's own page sends for "Ask Pinokio
14
+ // about <app>" (POST /brain/ask with `app`), so the agent starts
15
+ // in the app's folder. The session opens in the docked window,
16
+ // under the app's name, like any other. After a send the bar is
17
+ // an ordinary Ask again.
18
+ // With nothing typed and nothing attached there is no request:
19
+ // the agent just starts in the app's folder, as on the app's page.
20
+ //
21
+ // The bar draws itself (agent-bar.js); this file only holds which app it is
22
+ // pointed at and readies the send. On PinokioAgentBar it replaces `about`.
23
+ (function (window, document) {
24
+ 'use strict';
25
+
26
+ if (window.PinokioAgentBarAbout) return;
27
+ const bar = window.PinokioAgentBar;
28
+ if (!bar || !bar.ready || !bar.about || !bar.helpers) return;
29
+ window.PinokioAgentBarAbout = true;
30
+
31
+ const BUTTON = '.home-ask-button';
32
+ const H = bar.helpers;
33
+ let root = null;
34
+ let chip = null;
35
+ let chipIcon = null;
36
+ let chipName = null;
37
+ let chipX = null;
38
+ // { id, name, folder, icon }: the app's folder name, what it is called, the
39
+ // folder's full path and its icon's address
40
+ let app = null;
41
+
42
+ const isBusy = () => Boolean(root) && root.dataset.busy === 'true';
43
+ const onAsk = () => Boolean(root) && root.dataset.item === 'ask';
44
+
45
+ // The chip sits in the open view's bottom row (made by agent-bar-compose.js,
46
+ // possibly after this file runs), at the left, after the mode chip.
47
+ function placeChip() {
48
+ const controls = root.querySelector('.agent-compose__controls');
49
+ const grow = controls && controls.querySelector('.agent-compose__grow');
50
+ if (!grow) return false;
51
+ if (!chip) {
52
+ chip = H.el('span', 'agent-bar__about');
53
+ chipIcon = H.el('img', 'agent-bar__about-icon');
54
+ chipIcon.alt = '';
55
+ chipIcon.addEventListener('error', () => setHidden(chipIcon, true));
56
+ chipName = H.el('span', 'agent-bar__about-name');
57
+ chipX = H.el('button', 'agent-bar__about-x');
58
+ chipX.type = 'button';
59
+ chipX.appendChild(H.faIcon('fa-solid fa-xmark'));
60
+ chipX.addEventListener('click', (event) => {
61
+ event.preventDefault();
62
+ event.stopPropagation();
63
+ unpoint();
64
+ });
65
+ chip.append(chipIcon, chipName, chipX);
66
+ }
67
+ if (chip.parentNode !== controls || chip.nextSibling !== grow) controls.insertBefore(chip, grow);
68
+ return true;
69
+ }
70
+
71
+ // The compose view lays the box out again whenever something in it is shown
72
+ // or hidden, and this file looks again whenever the bar changes, so `hidden`
73
+ // is only written when it changes: writing the same value would make each
74
+ // call the other without end.
75
+ function setHidden(node, hidden) {
76
+ if (node.hidden !== hidden) node.hidden = hidden;
77
+ }
78
+
79
+ function sync() {
80
+ if (!root) return;
81
+ // another mode: an Ask pointed at an app is no longer what the bar shows
82
+ if (app && !onAsk()) app = null;
83
+ if (!placeChip()) return;
84
+ setHidden(chip, !app);
85
+ if (!app) return;
86
+ chipName.textContent = app.name;
87
+ chip.title = `This Ask is about ${app.name}. The agent starts in the app's folder.`;
88
+ setHidden(chipIcon, !app.icon);
89
+ if (app.icon && chipIcon.getAttribute('src') !== app.icon) chipIcon.src = app.icon;
90
+ chipX.title = `Ask without ${app.name}`;
91
+ chipX.setAttribute('aria-label', chipX.title);
92
+ chipX.disabled = isBusy();
93
+ }
94
+
95
+ // Point the bar at an app: Ask, the cursor in the text.
96
+ function point(next) {
97
+ if (!root || isBusy() || !next || !next.id || !next.folder) return false;
98
+ app = next;
99
+ bar.choose('ask');
100
+ sync();
101
+ return true;
102
+ }
103
+
104
+ // The user took the app off: an ordinary Ask, the cursor still in the text.
105
+ function unpoint() {
106
+ if (!app || isBusy()) return;
107
+ app = null;
108
+ bar.refresh();
109
+ sync();
110
+ const input = root.querySelector('.agent-bar__input');
111
+ if (input) input.focus();
112
+ }
113
+
114
+ // The plugin's address, for an agent that is started with no request.
115
+ let menuRead = null;
116
+ function hrefOf(tool) {
117
+ if (!menuRead) {
118
+ menuRead = fetch('/api/plugin/menu')
119
+ .then((response) => (response.ok ? response.json() : null))
120
+ .then((payload) => (payload && Array.isArray(payload.menu) ? payload.menu : []));
121
+ menuRead.catch(() => { menuRead = null; });
122
+ }
123
+ return menuRead.then((menu) => {
124
+ const plugin = menu.find((entry) => {
125
+ const mapped = H.mapPluginMenuToTools([entry])[0];
126
+ return mapped && mapped.value === tool.value;
127
+ });
128
+ return plugin && typeof plugin.href === 'string' ? plugin.href.trim().split('?')[0] : '';
129
+ }).catch(() => '');
130
+ }
131
+
132
+ // What the bar's own request resolves to: { response, payload }, the payload
133
+ // carrying the address the agent starts at.
134
+ async function prepare(about, prompt, tool) {
135
+ // attached files go into the app's own temp folder first (agent-bar-attach.js)
136
+ const files = await bar.attachments.paths(about.id);
137
+ if (!prompt && files.length === 0) {
138
+ const href = await hrefOf(tool);
139
+ if (!href) return { response: { ok: false }, payload: { ok: false, error: 'Could not find this agent.' } };
140
+ const params = new URLSearchParams();
141
+ params.set('cwd', about.folder);
142
+ params.set('session', H.newSession());
143
+ return { response: { ok: true }, payload: { ok: true, cwd: about.folder, url: `${href}?${params.toString()}` } };
144
+ }
145
+ const response = await fetch('/brain/ask', {
146
+ method: 'POST',
147
+ headers: { 'Content-Type': 'application/json' },
148
+ body: JSON.stringify({ app: about.id, prompt, tool: tool.value, files }),
149
+ });
150
+ const payload = await response.json().catch(() => null);
151
+ return { response, payload };
152
+ }
153
+
154
+ function install() {
155
+ // the home bar only; an app's page has its own bar, which is about that app already
156
+ if (!document.body || document.body.classList.contains('app-page')) return;
157
+ root = document.querySelector('.agent-bar');
158
+ if (!root || typeof bar.choose !== 'function' || typeof bar.refresh !== 'function') {
159
+ root = null;
160
+ return;
161
+ }
162
+ bar.about = {
163
+ app: () => app,
164
+ prepare,
165
+ // a send was handed over; the bar draws itself right after
166
+ clear: () => {
167
+ app = null;
168
+ window.setTimeout(sync, 0);
169
+ },
170
+ };
171
+ new MutationObserver(sync).observe(root, {
172
+ attributes: true,
173
+ attributeFilter: ['data-item', 'data-busy', 'data-compose', 'data-about'],
174
+ });
175
+ sync();
176
+ }
177
+
178
+ function fromButton(button) {
179
+ const id = (button.dataset.askApp || '').trim();
180
+ return {
181
+ id,
182
+ name: (button.dataset.askName || '').trim() || id,
183
+ folder: (button.dataset.askFolder || '').trim(),
184
+ icon: (button.dataset.askIcon || '').trim(),
185
+ };
186
+ }
187
+
188
+ // The rows of My Apps are links: a click anywhere on one opens the app. The
189
+ // button's click is taken here, before the page's own handlers see it.
190
+ document.addEventListener('click', (event) => {
191
+ const button = event.target && event.target.closest ? event.target.closest(BUTTON) : null;
192
+ if (!button) return;
193
+ event.preventDefault();
194
+ event.stopPropagation();
195
+ point(fromButton(button));
196
+ }, true);
197
+ // (and Enter or Space on the button is the button's, not the row's)
198
+ document.addEventListener('keydown', (event) => {
199
+ if ((event.key === 'Enter' || event.key === ' ') && event.target && event.target.closest && event.target.closest(BUTTON)) {
200
+ event.stopPropagation();
201
+ }
202
+ }, true);
203
+
204
+ bar.ready.then(install);
205
+ })(window, document);
@@ -317,7 +317,10 @@
317
317
  // or as the placeholder when the face is small. A link is an example of what
318
318
  // to paste, so Download keeps its own placeholder.
319
319
  // On an app's page the greeting is the bar's own line, which names the app.
320
- const greetingNow = () => (isApp ? restPlaceholder.replace(/…$/, '') : (GREETINGS[item()] || ''));
320
+ // The home bar pointed at one app says so too (its greeting()).
321
+ const greetingNow = () => (isApp
322
+ ? restPlaceholder.replace(/…$/, '')
323
+ : ((typeof host.greeting === 'function' && host.greeting()) || GREETINGS[item()] || ''));
321
324
  // Under the large face the blinking cursor is all that marks the empty text
322
325
  // as a place to type. Where there is none, the text says so itself, in the
323
326
  // bar's own line at rest. A phone only shows the cursor with its keyboard:
@@ -0,0 +1,78 @@
1
+ /* The agent bar's modes, all named at once (agent-bar-modes.js).
2
+
3
+ In the open view on a desktop (data-compose "place" or "centre") the row is
4
+ the first row of the box, above the face and the text, and the mode chip is
5
+ not shown. data-modes="menu" on .agent-bar says the box is too narrow for the
6
+ four names: the row is then out of sight, still laid out so it can be
7
+ measured, and the chip is back. */
8
+ .agent-bar-modes {
9
+ display: none;
10
+ }
11
+ html .agent-bar.agent-bar--modes[data-compose="place"] .agent-bar-modes,
12
+ html .agent-bar.agent-bar--modes[data-compose="centre"] .agent-bar-modes {
13
+ /* before the face and the text (see the rows' order in agent-bar-compose.css) */
14
+ order: 0;
15
+ flex: none;
16
+ display: flex;
17
+ align-items: center;
18
+ justify-content: flex-start;
19
+ gap: 2px;
20
+ box-sizing: border-box;
21
+ min-height: 44px;
22
+ /* from the box's top edge, and as far left as the face */
23
+ margin: -12px -12px 0;
24
+ padding: 0 12px;
25
+ animation: agent-bar-modes-in 220ms linear;
26
+ }
27
+ html .agent-bar.agent-bar--modes[data-compose="centre"] .agent-bar-modes {
28
+ margin: -14px -16px 0;
29
+ padding: 0 16px;
30
+ }
31
+ html .agent-bar.agent-bar--modes[data-compose="place"]:not([data-modes="menu"]) .agent-bar__scope,
32
+ html .agent-bar.agent-bar--modes[data-compose="centre"]:not([data-modes="menu"]) .agent-bar__scope {
33
+ display: none;
34
+ }
35
+ html .agent-bar.agent-bar--modes[data-modes="menu"] .agent-bar-modes {
36
+ position: absolute;
37
+ visibility: hidden;
38
+ pointer-events: none;
39
+ animation: none;
40
+ }
41
+
42
+ /* every name is the chip's size; only the one in use has its pill */
43
+ .agent-bar-modes__item {
44
+ flex: none;
45
+ height: 28px;
46
+ padding: 0 11px;
47
+ border: 0;
48
+ border-radius: 14px;
49
+ background: transparent;
50
+ color: var(--agent-bar-muted);
51
+ font: inherit;
52
+ font-size: 13px;
53
+ font-weight: 600;
54
+ white-space: nowrap;
55
+ cursor: pointer;
56
+ }
57
+ .agent-bar-modes__item:hover {
58
+ color: var(--agent-bar-text);
59
+ }
60
+ .agent-bar-modes__item[aria-checked="true"] {
61
+ background: var(--agent-bar-chip);
62
+ color: var(--agent-bar-text);
63
+ }
64
+ .agent-bar-modes__item:disabled {
65
+ cursor: default;
66
+ opacity: 0.6;
67
+ }
68
+
69
+ @keyframes agent-bar-modes-in {
70
+ from { opacity: 0; }
71
+ 45% { opacity: 0; }
72
+ to { opacity: 1; }
73
+ }
74
+ @media (prefers-reduced-motion: reduce) {
75
+ html .agent-bar.agent-bar--modes .agent-bar-modes {
76
+ animation: none;
77
+ }
78
+ }
@@ -0,0 +1,97 @@
1
+ // The agent bar's modes, all named at once.
2
+ //
3
+ // In the open view on a desktop the mode chip (one name and a menu) gives way to
4
+ // a row along the top of the box that names every mode: Ask, Create app, Create
5
+ // plugin, Download. The one in use has the chip's pill; a click on another
6
+ // switches to it. Nothing has to be opened to learn what the bar can do.
7
+ //
8
+ // The row has a line of its own, so it does not depend on what else the box
9
+ // holds: the agent's name, however long, or what send says.
10
+ //
11
+ // The chip and its menu stay where there is no row: the bar at rest, a phone,
12
+ // and a box too narrow for the four names.
13
+ //
14
+ // This file only adds the row. The modes and what choosing one does are the
15
+ // bar's own (agent-bar.js: `modes`, `choose`); the box is the compose view's
16
+ // (agent-bar-compose.js).
17
+ (function (window, document) {
18
+ 'use strict';
19
+
20
+ const bar = window.PinokioAgentBar;
21
+ if (!bar) return;
22
+
23
+ function install() {
24
+ const root = document.querySelector('.agent-bar');
25
+ if (!root) return false;
26
+ // the app page's bar only asks
27
+ if (root.dataset.item === 'ask_app') return true;
28
+ if (root.classList.contains('agent-bar--modes')) return true;
29
+ const field = root.querySelector('.agent-bar__field');
30
+ // (made by the compose view, whose box this row is part of)
31
+ const controls = root.querySelector('.agent-compose__controls');
32
+ const scope = root.querySelector('.agent-bar__scope');
33
+ if (!field || !controls || !scope || typeof bar.modes !== 'function' || typeof bar.choose !== 'function') return false;
34
+
35
+ const row = document.createElement('div');
36
+ row.className = 'agent-bar-modes';
37
+ row.setAttribute('role', 'radiogroup');
38
+ row.setAttribute('aria-label', 'What to do');
39
+ const buttons = bar.modes().map((mode) => {
40
+ const button = document.createElement('button');
41
+ button.type = 'button';
42
+ button.className = 'agent-bar-modes__item';
43
+ button.setAttribute('role', 'radio');
44
+ button.dataset.mode = mode.key;
45
+ button.textContent = mode.label;
46
+ button.addEventListener('click', () => bar.choose(mode.key));
47
+ row.appendChild(button);
48
+ return button;
49
+ });
50
+ // the first row of the box (the stylesheet orders the rows)
51
+ field.insertBefore(row, field.querySelector('.agent-compose__toprow') || field.firstChild);
52
+ root.classList.add('agent-bar--modes');
53
+ // like the view's other buttons, the names do not take the cursor out of the text
54
+ row.addEventListener('pointerdown', (event) => {
55
+ if (event.target.closest && event.target.closest('button')) event.preventDefault();
56
+ });
57
+
58
+ // Is the box wide enough for the four names? (While it is not, the row is
59
+ // out of sight but still laid out, so it can be measured. Widths are read in
60
+ // whole pixels, so a little is kept in hand.)
61
+ function fits() {
62
+ const style = window.getComputedStyle(row);
63
+ const between = parseFloat(style.columnGap) || 0;
64
+ const sides = (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0);
65
+ const names = buttons.reduce((sum, button) => sum + button.offsetWidth, 0) + between * (buttons.length - 1);
66
+ return names + sides + 2 <= field.clientWidth;
67
+ }
68
+
69
+ function sync() {
70
+ const busy = root.dataset.busy === 'true';
71
+ buttons.forEach((button) => {
72
+ button.setAttribute('aria-checked', String(button.dataset.mode === root.dataset.item));
73
+ button.disabled = busy;
74
+ });
75
+ const shape = root.dataset.compose;
76
+ const next = (shape === 'place' || shape === 'centre') && !fits() ? 'menu' : 'row';
77
+ if (root.dataset.modes !== next) root.dataset.modes = next;
78
+ }
79
+
80
+ new MutationObserver(sync).observe(root, {
81
+ attributes: true,
82
+ attributeFilter: ['data-item', 'data-busy', 'data-compose'],
83
+ });
84
+ window.addEventListener('resize', sync);
85
+ sync();
86
+ return true;
87
+ }
88
+
89
+ // after the compose view, which makes the box
90
+ let installed = false;
91
+ const tryInstall = () => {
92
+ if (!installed) installed = install() === true;
93
+ };
94
+ bar.ready.then(tryInstall);
95
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', tryInstall);
96
+ window.addEventListener('load', tryInstall);
97
+ })(window, document);