pinokiod 8.3.7 → 8.3.9

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.
@@ -0,0 +1,1912 @@
1
+ // Agent bar: the sessions it starts or lists, shown in a docked window.
2
+ // On pages with the main sidebar and on app pages (Run).
3
+ //
4
+ // - Send (Ask, Create app, Create plugin) on a main-sidebar page: agent-bar.js
5
+ // offers the started session to PinokioAgentBar.deliver. This file takes it
6
+ // and shows the agent's own page (the page Pinokio opened before) in the
7
+ // window. Download is not an agent session and still leaves the page.
8
+ // - "N running" in that bar: every running agent session, in workspaces and in
9
+ // apps, and shells opened inside an app. An app's own running scripts are not
10
+ // listed. Grouped by where it runs. Each row can be opened or stopped.
11
+ // - App pages: the app's own bar (agent-bar-app.js) opens its sessions through
12
+ // window.PinokioAgentDock, which this file provides there.
13
+ // - Every session you open becomes a tab along the bottom, and each can have its
14
+ // own window on screen. The windows sit side by side in a row above the tabs,
15
+ // the first against the right edge and each new one to its left (their tabs
16
+ // run the same way), sharing the width; when one more would not fit
17
+ // (four at most), the one that has been at the back longest is minimised. A
18
+ // window you move or resize by hand leaves the row until the row is next laid
19
+ // out (an open, a close, a minimise). The tabs and the windows follow you from
20
+ // page to page, each window where and how big you left it.
21
+ // - The window's header is the same for every kind of session:
22
+ // [Open app | Open plugin | Open folder] [Stop] [more] | [minimise] [dock to the side / float] [close]
23
+ // more: Refresh, Open in a new tab, Terminal appearance, Sync terminal size
24
+ // Minimise keeps the tab. Close removes the tab; the session keeps running and
25
+ // stays in the bar's list. Stop ends it (asked twice), the way the session's
26
+ // own page does.
27
+ // - Floating, the window is moved by its header and resized at any edge or
28
+ // corner; it stays on screen and above the tabs. Docked to the side, the page
29
+ // makes room and the panel's edge can be dragged; while it is showing it has
30
+ // no tab, since its own header is always on screen.
31
+ // - Create app: the new app is added to the top of My Apps.
32
+ // - A session is only ever attached to while it is still running, so a page
33
+ // change, a tab or Refresh never starts one. A tab whose session has ended
34
+ // goes away.
35
+ (function (window, document) {
36
+ 'use strict';
37
+ if (window.PinokioAgentBarPanel) return;
38
+ window.PinokioAgentBarPanel = true;
39
+
40
+ const STORE_ASKED = 'pinokio.agentBar.panel.asked';
41
+ const OPEN_CLASS = 'agent-bar-panel-open';
42
+ const STILL_CLASS = 'agent-bar-panel-still';
43
+ // how long a session that was just started may take to show up as running
44
+ const START_GRACE_MS = 20000;
45
+ const REFRESH_MS = 5000;
46
+ // with no tab and no list open, only the count in the bar depends on the list
47
+ const IDLE_REFRESH_MS = 30000;
48
+
49
+ // One list of tabs per window. In the layout shell every pane is a frame the
50
+ // shell names by its pane id, and all panes share this storage: each keeps its
51
+ // own list, or they would overwrite each other's and restore each other's windows.
52
+ const paneId = (() => {
53
+ try {
54
+ return window.parent !== window && window.parent.PinokioLayout ? window.name : '';
55
+ } catch (_) {
56
+ return '';
57
+ }
58
+ })();
59
+ const STORE_TABS = `pinokio.agentBar.dock.tabs${paneId ? `:${paneId}` : ''}`;
60
+
61
+ const read = (key, fallback) => {
62
+ try {
63
+ const raw = window.sessionStorage.getItem(key);
64
+ return raw ? JSON.parse(raw) : fallback;
65
+ } catch (_) {
66
+ return fallback;
67
+ }
68
+ };
69
+ const write = (key, value) => {
70
+ try {
71
+ if (value === null) window.sessionStorage.removeItem(key);
72
+ else window.sessionStorage.setItem(key, JSON.stringify(value));
73
+ } catch (_) {}
74
+ };
75
+
76
+ const root = document.documentElement;
77
+ const release = () => root.classList.remove(OPEN_CLASS, STILL_CLASS);
78
+ // Docked to the side, the width is yours: dragged at the panel's
79
+ // edge and remembered (in localStorage, like the app page panel's width today).
80
+ const STORE_WIDTH = 'pinokio.agentBar.dock.width';
81
+ const MIN_WIDTH = 240; // the app page panel's own minimum
82
+ const PAGE_MIN = 320; // what is always left for the page
83
+ const readWidth = () => {
84
+ try {
85
+ const value = parseInt(window.localStorage.getItem(STORE_WIDTH), 10);
86
+ return Number.isFinite(value) ? value : 0;
87
+ } catch (_) {
88
+ return 0;
89
+ }
90
+ };
91
+ const clampWidth = (width) => Math.max(MIN_WIDTH, Math.min(width, Math.max(MIN_WIDTH, window.innerWidth - PAGE_MIN)));
92
+ function applyWidth() {
93
+ const width = readWidth();
94
+ // phones use the full width; with nothing remembered the panel keeps its own default
95
+ if (!width || window.innerWidth <= 768) root.style.removeProperty('--agent-bar-panel-w');
96
+ else root.style.setProperty('--agent-bar-panel-w', `${clampWidth(width)}px`);
97
+ }
98
+ applyWidth();
99
+ window.addEventListener('resize', applyWidth);
100
+ // Floating, a window is moved by its header and resized at any edge or corner.
101
+ const FLOAT_MIN_W = 320;
102
+ const FLOAT_MIN_H = 240;
103
+ const FLOAT_EDGE = 8; // kept clear of the screen's edges and of the top bar
104
+ const FLOAT_TABS = 46; // kept clear at the bottom, where the tabs are
105
+ // A window's box is { w, h, r, b }: its size, and how far its right and bottom
106
+ // edges are from the screen's (so it keeps its place when the screen changes
107
+ // size). It is set on the window's own element.
108
+ function setFloat(element, value) {
109
+ const box = value || {};
110
+ const set = (name, number) => {
111
+ if (Number.isFinite(number)) element.style.setProperty(name, `${Math.round(number)}px`);
112
+ else element.style.removeProperty(name);
113
+ };
114
+ set('--agent-dock-float-w', box.w);
115
+ set('--agent-dock-float-h', box.h);
116
+ set('--agent-dock-float-r', box.r);
117
+ set('--agent-dock-float-b', box.b);
118
+ }
119
+ // Where a window may be: under the top bar, above the tabs, inside the screen.
120
+ function floatLimits() {
121
+ const top = parseFloat(window.getComputedStyle(root).getPropertyValue('--agent-bar-panel-top')) || 46;
122
+ return { left: FLOAT_EDGE, top: top + FLOAT_EDGE, right: window.innerWidth - FLOAT_EDGE, bottom: window.innerHeight - FLOAT_TABS };
123
+ }
124
+ // A box kept from the page before, brought inside the screen as it is now.
125
+ function fitBox(box) {
126
+ const limits = floatLimits();
127
+ const w = Math.max(FLOAT_MIN_W, Math.min(box.w, limits.right - limits.left));
128
+ const h = Math.max(FLOAT_MIN_H, Math.min(box.h, limits.bottom - limits.top));
129
+ return {
130
+ w,
131
+ h,
132
+ r: Math.max(FLOAT_EDGE, Math.min(box.r, window.innerWidth - limits.left - w)),
133
+ b: Math.max(FLOAT_TABS, Math.min(box.b, window.innerHeight - limits.top - h)),
134
+ };
135
+ }
136
+
137
+ let bar = null;
138
+ let H = null;
139
+ let tools = [];
140
+ let sessions = [];
141
+ let asked = read(STORE_ASKED, {});
142
+ let menuOpen = false;
143
+ // The sessions you have opened, one tab each. Besides the session itself a tab
144
+ // remembers its window: `open` (it has a window on screen), `docked` (that
145
+ // window is docked to the side), `z` (when it was last in front) and `box`
146
+ // (where it was put and how big, once it has been moved or resized by hand).
147
+ let tabs = read(STORE_TABS, []);
148
+ if (!Array.isArray(tabs)) tabs = [];
149
+ const MAX_OPEN = 4;
150
+ const wins = new Map(); // key -> { key, element, part, session, embedTimer, watched, awaiting }
151
+ let frontKey = '';
152
+ let zCounter = tabs.reduce((highest, tab) => Math.max(highest, tab.z || 0), 0);
153
+ const tabOf = (key) => tabs.find((tab) => tab.key === key) || null;
154
+ const isOpen = (key) => {
155
+ const tab = tabOf(key);
156
+ return Boolean(tab && tab.open);
157
+ };
158
+ const openTabs = () => tabs.filter((tab) => tab.open);
159
+ const saveTabs = () => write(STORE_TABS, tabs);
160
+ // A window was docked to the side on the page before this one: keep its room
161
+ // from the first paint, so the page does not jump when it comes back.
162
+ if (tabs.some((tab) => tab.open && tab.docked)) root.classList.add(OPEN_CLASS, STILL_CLASS);
163
+ let dock = null;
164
+ // True on an app page, where the app's own bar opens the sessions
165
+ let APP = false;
166
+ let toolsReady = false;
167
+ let appCwd = '';
168
+ const shellMenus = new Map();
169
+
170
+ const cleanPath = (value) => String(value || '').replace(/\\/g, '/').replace(/\/+$/, '');
171
+ const snippet = (text, max) => {
172
+ const line = String(text || '').trim().split('\n')[0];
173
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
174
+ };
175
+ // a shell is told apart by which shell it is and its session value
176
+ const shellKey = (shellId, session) => (session ? `${shellId}?session=${session}` : shellId);
177
+ function sessionKey(tail, cwd, session) {
178
+ return `${tail}|${cleanPath(cwd)}|${session || ''}`;
179
+ }
180
+
181
+ // Where a folder is: a Pinokio workspace, an app (PINOKIO_HOME/api/<folder>),
182
+ // a plugin, or some other folder (shown like a workspace, by its name).
183
+ function placeOf(rawPath) {
184
+ const path = cleanPath(rawPath);
185
+ const match = path.match(/^(.*?\/(api|workspaces|plugin)\/([^/]+))(?:\/|$)/);
186
+ // the brain: the one folder every Ask from the home bar runs in
187
+ if (!match && /\/brain$/.test(path)) return { placeKind: 'ask', placeName: 'Ask', folder: '', rootPath: path };
188
+ if (!match) return { placeKind: 'workspace', placeName: path.split('/').filter(Boolean).pop() || 'folder', folder: '', rootPath: path };
189
+ if (match[2] === 'workspaces') return { placeKind: 'workspace', placeName: match[3], folder: match[3], rootPath: match[1] };
190
+ if (match[2] === 'plugin') return { placeKind: 'plugin', placeName: match[3], folder: match[3], rootPath: match[1] };
191
+ let name = match[3];
192
+ document.querySelectorAll('.home-app-line[data-path]').forEach((row) => {
193
+ if (row.dataset.path === match[3] && row.dataset.name) name = row.dataset.name;
194
+ });
195
+ return { placeKind: 'app', placeName: name, folder: match[3], rootPath: match[1] };
196
+ }
197
+
198
+ // The pages of one agent session: `url` shows it in the panel (it attaches to
199
+ // the session if it is running), `fullUrl` is its own full page.
200
+ function agentUrls(href, cwd, session) {
201
+ const params = new URLSearchParams();
202
+ params.set('cwd', cwd);
203
+ if (session) params.set('session', session);
204
+ const full = new URLSearchParams(params);
205
+ full.set('chrome', 'full');
206
+ const base = String(href).split('?')[0];
207
+ return { url: `${base}?${params.toString()}`, fullUrl: `${base}?${full.toString()}` };
208
+ }
209
+
210
+ // ---- what is running ------------------------------------------------------
211
+ function readShells(shells) {
212
+ const seen = new Set();
213
+ const found = [];
214
+ (Array.isArray(shells) ? shells : []).forEach((shell) => {
215
+ if (!shell || shell.done) return;
216
+ const group = typeof shell.group === 'string' ? shell.group : '';
217
+ const id = typeof shell.id === 'string' ? shell.id : '';
218
+ const queryIndex = group.indexOf('?');
219
+ if (queryIndex > 0) {
220
+ // an agent: its script, the folder it works in, and (if any) its session
221
+ const { script, cwd, session } = H.readRunId(group);
222
+ const tool = tools.find((item) => item.href && script.endsWith(H.pluginTail(item.href)));
223
+ if (!tool || !cwd) return;
224
+ const key = sessionKey(H.pluginTail(tool.href), cwd, session);
225
+ if (seen.has(key)) return;
226
+ seen.add(key);
227
+ const place = placeOf(cwd);
228
+ const urls = agentUrls(tool.href, cwd, session);
229
+ found.push(Object.assign({
230
+ key,
231
+ ref: group,
232
+ kind: 'agent',
233
+ label: tool.label,
234
+ iconSrc: tool.iconSrc || '',
235
+ start: shell.start_time,
236
+ url: urls.url,
237
+ fullUrl: place.placeKind === 'app' ? '' : urls.fullUrl,
238
+ tabUrl: urls.fullUrl,
239
+ appHref: place.placeKind === 'app' ? `/p/${encodeURIComponent(place.folder)}` : '',
240
+ }, place));
241
+ return;
242
+ }
243
+ // A shell the user opened inside an app. Anything else (an app's own
244
+ // running scripts) was not started from a bar and is not listed.
245
+ if (!id.startsWith('shell/')) return;
246
+ const place = placeOf(shell.path);
247
+ if (place.placeKind !== 'app') return;
248
+ if (seen.has(id)) return;
249
+ seen.add(id);
250
+ const idQuery = id.indexOf('?');
251
+ const shellId = idQuery < 0 ? id : id.slice(0, idQuery);
252
+ const shellSession = idQuery < 0 ? '' : (new URLSearchParams(id.slice(idQuery + 1)).get('session') || '');
253
+ found.push(Object.assign({
254
+ key: shellKey(shellId, shellSession),
255
+ ref: id,
256
+ kind: 'shell',
257
+ label: 'Shell',
258
+ iconClass: 'fa-solid fa-terminal',
259
+ start: shell.start_time,
260
+ shellId,
261
+ shellSession,
262
+ url: '',
263
+ fullUrl: '',
264
+ appHref: `/p/${encodeURIComponent(place.folder)}`,
265
+ }, place));
266
+ });
267
+ found.sort((a, b) => Number(b.start || 0) - Number(a.start || 0));
268
+ return found;
269
+ }
270
+
271
+ // A shell's page is only known to its app's own menu.
272
+ function shellUrl(session) {
273
+ if (!shellMenus.has(session.rootPath)) {
274
+ shellMenus.set(session.rootPath, fetch(`/api/plugin/menu?workspace=${encodeURIComponent(session.rootPath)}`)
275
+ .then((response) => (response.ok ? response.json() : null))
276
+ .then((payload) => (payload && payload.projectShell && Array.isArray(payload.projectShell.items) ? payload.projectShell.items : []))
277
+ .catch(() => []));
278
+ }
279
+ return shellMenus.get(session.rootPath).then((items) => {
280
+ const match = items.find((item) => {
281
+ const href = item && typeof item.href === 'string' ? item.href.trim() : '';
282
+ if (!href.startsWith('/shell/')) return false;
283
+ let shellId = typeof item.shellId === 'string' ? item.shellId.trim() : '';
284
+ if (!shellId) {
285
+ try {
286
+ shellId = `shell/${decodeURIComponent(href.split('?')[0].slice('/shell/'.length))}`;
287
+ } catch (_) {
288
+ shellId = '';
289
+ }
290
+ }
291
+ return shellId.split('?')[0] === session.shellId;
292
+ });
293
+ if (!match) return '';
294
+ const url = new URL(match.href.trim(), window.location.origin);
295
+ if (session.shellSession) url.searchParams.set('session', session.shellSession);
296
+ return `${url.pathname}${url.search}`;
297
+ });
298
+ }
299
+
300
+ function loadTools() {
301
+ return fetch('/api/plugin/menu')
302
+ .then((response) => (response.ok ? response.json() : null))
303
+ .then((payload) => {
304
+ const list = payload && Array.isArray(payload.menu) ? payload.menu : [];
305
+ tools = list.map((plugin) => {
306
+ const tool = H.mapPluginMenuToTools([plugin])[0];
307
+ if (!tool) return null;
308
+ tool.href = String(plugin.href).trim();
309
+ return tool;
310
+ }).filter(Boolean);
311
+ toolsReady = tools.length > 0;
312
+ })
313
+ .catch(() => {});
314
+ }
315
+
316
+ // What the last look at the list of running sessions showed, as text. When the
317
+ // next look shows the same, nothing on screen has to change, so nothing is
318
+ // redrawn or saved: a redraw under the pointer swallows a click and resets a
319
+ // Stop that is waiting for its second click.
320
+ let lastLook = '';
321
+ let lastRead = 0;
322
+ // Resolves true only when the list of running sessions was actually read.
323
+ function refresh() {
324
+ if (document.hidden) return Promise.resolve(false);
325
+ lastRead = Date.now();
326
+ return fetch('/info/shells')
327
+ .then((response) => {
328
+ if (!response.ok) throw new Error('failed');
329
+ return response.json();
330
+ })
331
+ .then((shells) => {
332
+ sessions = readShells(shells);
333
+ const seen = JSON.stringify([
334
+ toolsReady,
335
+ sessions.map((session) => [session.key, session.ref, session.start]),
336
+ tabs.map((tab) => [tab.key, tab.open === true, inGrace(tab)]),
337
+ ]);
338
+ if (seen !== lastLook) {
339
+ lastLook = seen;
340
+ pruneTabs();
341
+ renderChip();
342
+ if (menuOpen) renderMenu();
343
+ }
344
+ return true;
345
+ })
346
+ .catch(() => false);
347
+ }
348
+ // Loading a session's page starts the session if it is not running, and the
349
+ // server's stop reaches further than one session. So before either, the list of
350
+ // running sessions is read again and the session must be on it. It is matched
351
+ // by its exact id when that is known, else by its key.
352
+ function whenRunning(session, then) {
353
+ refresh().then((read) => {
354
+ const known = read && (session.kind === 'shell' || toolsReady);
355
+ const live = known
356
+ ? sessions.find((item) => (session.ref ? item.ref === session.ref : item.key === session.key))
357
+ : null;
358
+ if (live) then(live);
359
+ else if (!known) toast('Could not check that this session is still running.');
360
+ else toast(inGrace(session) ? 'This session is still starting. Try again in a moment.' : 'This session has already ended.');
361
+ });
362
+ }
363
+
364
+ // The session in the panel counts as running from the moment it is started,
365
+ // before Pinokio lists it.
366
+ function listed() {
367
+ const starting = tabs.filter((tab) => inGrace(tab) && !sessions.some((session) => session.key === tab.key));
368
+ return starting.concat(sessions);
369
+ }
370
+
371
+ // ---- "N running" in the bar, and its list ----------------------------------
372
+ let chip = null;
373
+ let menu = null;
374
+
375
+ function ensureChip() {
376
+ if (APP) return false; // The app's own bar has its count and list
377
+ const top = document.querySelector('.agent-bar__top');
378
+ const inner = document.querySelector('.agent-bar__inner');
379
+ if (!top || !inner) return false;
380
+ if (!chip) {
381
+ chip = H.el('button', 'agent-bar__running');
382
+ chip.type = 'button';
383
+ chip.append(H.el('span', 'agent-bar__dot'), H.el('span', 'agent-bar__running-count'), H.el('span', 'agent-bar__running-word', 'running'));
384
+ chip.addEventListener('click', () => setMenu(!menuOpen));
385
+ chip.addEventListener('pointerenter', loadAppIcons);
386
+ }
387
+ if (chip.parentNode !== top) top.insertBefore(chip, top.querySelector('.agent-bar__agent'));
388
+ if (!menu) {
389
+ menu = H.el('div', 'agent-bar__menu agent-bar__menu--running');
390
+ menu.dataset.menu = 'running';
391
+ menu.hidden = true;
392
+ }
393
+ if (menu.parentNode !== inner) inner.appendChild(menu);
394
+ return true;
395
+ }
396
+
397
+ function renderChip() {
398
+ if (!ensureChip()) return;
399
+ const count = listed().length;
400
+ chip.hidden = count === 0;
401
+ chip.querySelector('.agent-bar__running-count').textContent = String(count);
402
+ chip.setAttribute('aria-label', `${count} running`);
403
+ if (count === 0) setMenu(false);
404
+ }
405
+
406
+ function setMenu(open) {
407
+ menuOpen = Boolean(open) && Boolean(menu);
408
+ if (!menu) return;
409
+ menu.hidden = !menuOpen;
410
+ chip.classList.toggle('is-open', menuOpen);
411
+ if (!menuOpen) return;
412
+ bar.closeMenus();
413
+ loadAppIcons();
414
+ renderMenu();
415
+ refresh();
416
+ }
417
+
418
+ // Each app's icon and title, for the app headings in the list. Asked for once per
419
+ // page, when the pointer first reaches "N running" or the list is first opened.
420
+ let appIcons = null;
421
+ let appTitles = null;
422
+ function loadAppIcons() {
423
+ if (appIcons) return;
424
+ appIcons = new Map();
425
+ appTitles = new Map();
426
+ fetch('/info/apps')
427
+ .then((response) => (response.ok ? response.json() : null))
428
+ .then((payload) => {
429
+ (payload && Array.isArray(payload.apps) ? payload.apps : []).forEach((app) => {
430
+ if (app && app.name && app.icon) appIcons.set(app.name, app.icon);
431
+ if (app && app.name && app.title) appTitles.set(app.name, app.title);
432
+ });
433
+ if (menuOpen) renderMenu();
434
+ })
435
+ .catch(() => {});
436
+ }
437
+ // A heading of the list. An app's starts with the app's icon. Its name is the
438
+ // app's title: placeOf() only finds that on the home page, whose rows carry it;
439
+ // on any other page it has the folder's name, and the title comes from the list.
440
+ function placeTitle(place) {
441
+ const title = H.el('div', 'agent-bar__menu-title');
442
+ const name = (place.name === place.folder && appTitles && appTitles.get(place.folder)) || place.name;
443
+ let src = (place.folder && appIcons && appIcons.get(place.folder)) || '';
444
+ // an app without an icon of its own has Pinokio's, which comes in two colours
445
+ if (src === '/pinokio-black.png' && document.body.classList.contains('dark')) src = '/pinokio-white.png';
446
+ if (!src) {
447
+ title.textContent = name;
448
+ return title;
449
+ }
450
+ title.classList.add('agent-bar__menu-title--app');
451
+ const img = H.el('img', 'agent-bar__menu-title-icon');
452
+ img.alt = '';
453
+ img.src = src;
454
+ img.addEventListener('error', () => img.remove());
455
+ title.append(img, H.el('span', 'agent-bar__menu-title-text', name));
456
+ return title;
457
+ }
458
+
459
+ function rowFor(session) {
460
+ const icon = H.toolIcon({ iconSrc: session.iconSrc, iconClass: session.iconClass });
461
+ const said = asked[session.key];
462
+ // Two lines: what was asked (the agent's name when that is not known) with the
463
+ // row's whole width, then the agent, how long ago it started, and whether its
464
+ // window is on screen.
465
+ const notes = [];
466
+ if (said) notes.push(session.label);
467
+ else if (session.placeKind === 'workspace') notes.push(session.placeName);
468
+ notes.push(H.timeAgo(session.start));
469
+ if (isOpen(session.key)) notes.push('on screen');
470
+ const row = H.el('button', 'agent-bar__row');
471
+ row.type = 'button';
472
+ const text = H.el('span', 'agent-dock__listtext');
473
+ text.append(
474
+ H.el('span', 'agent-dock__listline', said ? snippet(said, 200) : session.label),
475
+ H.el('span', 'agent-dock__listsub', notes.filter(Boolean).join(' · ')),
476
+ );
477
+ row.append(icon, text);
478
+ row.addEventListener('click', () => {
479
+ setMenu(false);
480
+ show(session);
481
+ });
482
+ // Stop on the row, shown on hover; a second click confirms
483
+ const wrap = H.el('div', 'agent-dock__listrow');
484
+ const stop = stopButton('agent-dock__liststop', () => stopSession(session));
485
+ wrap.append(row, stop);
486
+ return wrap;
487
+ }
488
+
489
+ function renderMenu() {
490
+ menu.textContent = '';
491
+ const list = listed();
492
+ const workspaces = list.filter((session) => session.placeKind === 'workspace');
493
+ if (workspaces.length) {
494
+ menu.appendChild(H.el('div', 'agent-bar__menu-title', 'Workspaces'));
495
+ workspaces.forEach((session) => menu.appendChild(rowFor(session)));
496
+ }
497
+ const places = [];
498
+ list.filter((session) => session.placeKind !== 'workspace').forEach((session) => {
499
+ const name = session.placeKind === 'plugin' ? `Plugin: ${session.placeName}` : session.placeName;
500
+ let place = places.find((item) => item.name === name);
501
+ if (!place) {
502
+ place = { name, folder: session.placeKind === 'app' ? session.folder : '', sessions: [] };
503
+ places.push(place);
504
+ }
505
+ place.sessions.push(session);
506
+ });
507
+ places.forEach((place) => {
508
+ menu.appendChild(placeTitle(place));
509
+ place.sessions.forEach((session) => menu.appendChild(rowFor(session)));
510
+ });
511
+ }
512
+
513
+ // ---- the windows ------------------------------------------------------------
514
+ function iconButton(label, iconClass, onClick) {
515
+ const button = H.el('button', 'agent-bar-panel__btn');
516
+ button.type = 'button';
517
+ button.title = label;
518
+ button.setAttribute('aria-label', label);
519
+ button.appendChild(H.faIcon(iconClass));
520
+ button.addEventListener('click', onClick);
521
+ return button;
522
+ }
523
+
524
+ // One window, for one session. It is built the first time its session is opened
525
+ // and removed when its tab is closed; minimised, it stays loaded and out of sight.
526
+ function createWindow(key) {
527
+ const element = H.el('aside', 'agent-bar-panel');
528
+ element.setAttribute('aria-label', 'Agent session');
529
+ element.dataset.open = 'false';
530
+ const part = {};
531
+ const win = { key, element, part, session: null, embedTimer: null };
532
+ const header = H.el('div', 'agent-bar-panel__header');
533
+ part.icon = H.el('span', 'agent-bar-panel__icon');
534
+ const text = H.el('div', 'agent-bar-panel__text');
535
+ part.title = H.el('div', 'agent-bar-panel__title');
536
+ part.sub = H.el('div', 'agent-bar-panel__sub');
537
+ text.append(part.title, part.sub);
538
+ // One header for every kind of session.
539
+ // [Open app | Open plugin | Open folder] [Stop] [more] | [minimise] [dock to the side / float] [close]
540
+ // more: Refresh, Open in a new tab, the terminal's two buttons
541
+ const goWhere = () => {
542
+ const place = win.session && where(win.session);
543
+ if (place) place.run();
544
+ };
545
+ part.open = H.el('button', 'agent-bar-panel__open', 'Open app');
546
+ part.open.type = 'button';
547
+ part.open.addEventListener('click', goWhere);
548
+ part.stop = stopButton('agent-dock__stop', () => { if (win.session) stopSession(win.session); });
549
+ part.more = iconButton('More', 'fa-solid fa-ellipsis', () => setMore(win, part.moreMenu.hidden));
550
+ part.moreMenu = H.el('div', 'agent-dock__more');
551
+ part.moreMenu.hidden = true;
552
+ const moreRow = (label, iconClass, onClick) => {
553
+ const row = H.el('button', 'agent-dock__more-row');
554
+ row.type = 'button';
555
+ row.append(H.faIcon(iconClass), H.el('span', '', label));
556
+ row.addEventListener('click', () => {
557
+ setMore(win, false);
558
+ onClick();
559
+ });
560
+ part.moreMenu.appendChild(row);
561
+ return row;
562
+ };
563
+ // a narrow window has no room for the "Open ..." button in its header, so it is a row here
564
+ part.whereRow = moreRow('Open app', 'fa-solid fa-arrow-right', goWhere);
565
+ part.whereRow.dataset.row = 'where';
566
+ moreRow('Refresh', 'fa-solid fa-rotate-right', () => reload(win));
567
+ moreRow('Open in a new tab', 'fa-solid fa-arrow-up-right-from-square', () => {
568
+ const session = win.session;
569
+ const url = session && (session.tabUrl || session.fullUrl || session.url);
570
+ if (url) whenRunning(session, () => window.open(url, '_blank', 'noopener'));
571
+ });
572
+ // the session page's own two terminal buttons, pressed from here (see embed below)
573
+ part.termLook = moreRow('Terminal appearance', 'fa-solid fa-sliders', () => pressInPage(win, '.terminal-config-button'));
574
+ part.termSync = moreRow('Sync terminal size', 'fa-solid fa-ruler-combined', () => pressInPage(win, '.terminal-resize-button'));
575
+ // always in the header, between the window's other two controls, where a window's
576
+ // maximise / restore button usually is
577
+ part.wide = iconButton('Dock to the side', 'fa-solid fa-table-columns', () => toggleDocked(win));
578
+ part.wide.classList.add('agent-dock__wide');
579
+ header.append(part.icon, text, part.open, part.stop, part.more, H.el('span', 'agent-dock__sep'),
580
+ iconButton('Minimise', 'fa-solid fa-minus', () => minimise(key)),
581
+ part.wide,
582
+ iconButton('Close (keeps running)', 'fa-solid fa-xmark', () => close(key)));
583
+ part.frame = document.createElement('iframe');
584
+ part.frame.className = 'agent-bar-panel__frame';
585
+ part.frame.title = 'Agent session';
586
+ part.frame.setAttribute('allow', 'fullscreen *;');
587
+ part.frame.setAttribute('allowfullscreen', '');
588
+ element.append(header, part.moreMenu, part.frame);
589
+ document.body.appendChild(element);
590
+ // the edge to drag when docked to the side
591
+ part.resizer = H.el('div', 'agent-dock__resizer');
592
+ part.resizer.setAttribute('role', 'separator');
593
+ part.resizer.setAttribute('aria-orientation', 'vertical');
594
+ part.resizer.setAttribute('aria-label', 'Resize the panel');
595
+ part.resizer.tabIndex = 0;
596
+ element.appendChild(part.resizer);
597
+ bindResizer(win);
598
+ bindFloatGrips(win);
599
+ part.frame.addEventListener('load', () => embed(win));
600
+ // A narrow window keeps room for the title: under 600px "Open ..." moves into
601
+ // the more menu, and under 440px Stop is its icon (see the styles).
602
+ const fitHeader = () => {
603
+ const width = element.getBoundingClientRect().width;
604
+ element.dataset.narrow = String(width < 600);
605
+ element.dataset.tight = String(width < 440);
606
+ };
607
+ fitHeader();
608
+ if (typeof window.ResizeObserver === 'function') new window.ResizeObserver(fitHeader).observe(element);
609
+ else window.addEventListener('resize', fitHeader);
610
+ // pressed anywhere, it comes to the front (a press inside its page is seen in start)
611
+ element.addEventListener('pointerdown', () => { if (frontKey !== key) focus(key); }, true);
612
+ wins.set(key, win);
613
+ return win;
614
+ }
615
+
616
+ // The windows start under the top bar, wherever that ends on this page.
617
+ function syncTop() {
618
+ // under whatever holds the bar: the top bar, or on a phone's app page the strip
619
+ const barRoot = document.querySelector('.agent-bar');
620
+ const header = (barRoot && barRoot.closest('header.navheader, .mobile-bottom-nav'))
621
+ || document.querySelector('body > header.navheader');
622
+ const bottom = header ? Math.max(0, Math.round(header.getBoundingClientRect().bottom)) : 0;
623
+ root.style.setProperty('--agent-bar-panel-top', `${bottom}px`);
624
+ }
625
+
626
+ function describe(session) {
627
+ const said = asked[session.key];
628
+ const agent = session.label;
629
+ // On its own app's page the app's name says nothing; nor does the folder of a home Ask
630
+ if (session.placeKind === 'ask' || (APP && session.placeKind === 'app' && cleanPath(session.rootPath) === cleanPath(appCwd))) {
631
+ return { title: said ? snippet(said, 70) : agent, sub: said ? `${agent} · started ${H.timeAgo(session.start)}` : `started ${H.timeAgo(session.start)}` };
632
+ }
633
+ if (session.placeKind === 'workspace') {
634
+ return { title: said ? snippet(said, 70) : `Workspace ${session.placeName}`, sub: said ? `${agent} · ${session.placeName}` : `${agent} · started ${H.timeAgo(session.start)}` };
635
+ }
636
+ const name = session.placeKind === 'plugin' ? `Plugin: ${session.placeName}` : session.placeName;
637
+ return { title: name, sub: said ? `${agent} · ${snippet(said, 60)}` : `${agent} · started ${H.timeAgo(session.start)}` };
638
+ }
639
+
640
+ // Floating windows sit side by side in a row along the bottom, above the tabs,
641
+ // against the right edge: the first one opened is rightmost and each new one
642
+ // lands to its left, so the ones already up do not move. Their tabs run the
643
+ // same way (see the styles). They share the width.
644
+ // A window can be dragged or resized out of the row by hand (`free`, with its
645
+ // own box). That lasts until the row is next laid out, or until its header or
646
+ // an edge is double-clicked.
647
+ const ROW_WIDTH = 440; // as wide as a window gets in the row
648
+ const ROW_MIN = 360; // narrower than this and a terminal is cramped: one is minimised instead
649
+ // On a narrow screen (a phone) a window takes the whole screen, so one at a time.
650
+ const narrow = () => window.innerWidth <= 768;
651
+ const ROW_GAP = 12;
652
+ const ROW_SIDE = 16;
653
+ const inRow = (tab) => tab.open === true && !tab.docked;
654
+ // the room the row has: left of a window docked to the side, if there is one
655
+ function rowRoom() {
656
+ const docked = tabs.find((tab) => tab.open && tab.docked);
657
+ const dockedWin = docked ? wins.get(docked.key) : null;
658
+ const taken = dockedWin ? dockedWin.element.getBoundingClientRect().width : 0;
659
+ const right = ROW_SIDE + taken;
660
+ return { right, width: window.innerWidth - right - FLOAT_EDGE };
661
+ }
662
+ const rowCapacity = () => (narrow() ? 1 : Math.max(1, Math.min(MAX_OPEN, Math.floor((rowRoom().width + ROW_GAP) / (ROW_MIN + ROW_GAP)))));
663
+ function tile(keep) {
664
+ // Every floating window is in the row whenever the row is laid out. A window
665
+ // dragged or resized by hand stays where it was put only until then (the next
666
+ // open, minimise, close or dock), so the row can never be laid out under it.
667
+ // `keep` is for a page change: nothing was opened or closed, so every window
668
+ // comes back as it was, the hand-placed ones where they were put.
669
+ if (!keep) tabs.forEach((tab) => { delete tab.box; });
670
+ const row = tabs.filter(inRow);
671
+ if (!row.length) return;
672
+ // one that came back into the row may be one too many: the one longest at the back gives way
673
+ if (row.length > rowCapacity()) {
674
+ const oldest = row.slice().sort((a, b) => (a.z || 0) - (b.z || 0))[0];
675
+ minimise(oldest.key);
676
+ return;
677
+ }
678
+ const room = rowRoom();
679
+ const width = Math.max(FLOAT_MIN_W, Math.min(ROW_WIDTH, Math.floor((room.width - ROW_GAP * (row.length - 1)) / row.length)));
680
+ row.forEach((tab, index) => {
681
+ const win = wins.get(tab.key);
682
+ if (!win) return;
683
+ // counted from the right edge: the first one opened is rightmost, each later one to its left
684
+ setFloat(win.element, tab.box ? fitBox(tab.box) : { w: width, r: room.right + index * (width + ROW_GAP), b: FLOAT_TABS });
685
+ });
686
+ }
687
+ // The row holds only as many as fit: the one that has been at the back longest
688
+ // is minimised (its tab stays) until the rest do. `room` leaves space for one more.
689
+ function fitRow(room) {
690
+ const most = rowCapacity() - (room ? 1 : 0);
691
+ let guard = 0;
692
+ while (tabs.filter(inRow).length > Math.max(0, most) && guard < 8) {
693
+ guard += 1;
694
+ const oldest = tabs.filter(inRow).sort((a, b) => (a.z || 0) - (b.z || 0))[0];
695
+ if (!oldest) break;
696
+ minimise(oldest.key);
697
+ }
698
+ }
699
+ function applyBox(win, tab, keep) {
700
+ if (tab.docked) setFloat(win.element, null);
701
+ tile(keep);
702
+ }
703
+ // Back into the row, from wherever it was dragged or however it was resized.
704
+ function joinRow(win) {
705
+ const tab = tabOf(win.key);
706
+ if (!tab || tab.docked) return;
707
+ // it counts as the newest, so it is not the one minimised to make room for itself
708
+ zCounter += 1;
709
+ tab.z = zCounter;
710
+ fitRow();
711
+ tile();
712
+ saveTabs();
713
+ }
714
+ // The page makes room only for a window that is docked to the side.
715
+ function syncSide(still) {
716
+ const side = tabs.some((tab) => tab.open && tab.docked);
717
+ if (still) root.classList.add(STILL_CLASS);
718
+ root.classList.toggle(OPEN_CLASS, side);
719
+ if (still) window.setTimeout(() => root.classList.remove(STILL_CLASS), 300);
720
+ }
721
+ // In front: on top of the other windows, and its tab is the marked one.
722
+ function focus(key) {
723
+ const tab = tabOf(key);
724
+ if (!tab) return;
725
+ frontKey = key;
726
+ zCounter += 1;
727
+ tab.z = zCounter;
728
+ openTabs().slice().sort((a, b) => (a.z || 0) - (b.z || 0)).forEach((item, index) => {
729
+ const win = wins.get(item.key);
730
+ if (!win) return;
731
+ win.element.style.setProperty('--agent-dock-order', String(index + 1));
732
+ win.element.dataset.front = String(item.key === key);
733
+ });
734
+ saveTabs();
735
+ renderTabs();
736
+ }
737
+
738
+ // Puts a session on screen, in its own window. `launchUrl` is given only for a
739
+ // session the bar has just started (it carries the prompt); otherwise the
740
+ // session's own page is loaded, which attaches to it. A window that already has
741
+ // its session's page keeps it.
742
+ function open(session, options) {
743
+ const settings = options || {};
744
+ syncTop();
745
+ let tab = tabOf(session.key);
746
+ const fresh = !tab || !tab.open;
747
+ if (fresh && openTabs().length >= MAX_OPEN) {
748
+ // the one that has been at the back longest makes room
749
+ const oldest = openTabs().slice().sort((a, b) => (a.z || 0) - (b.z || 0))[0];
750
+ if (oldest) minimise(oldest.key);
751
+ }
752
+ const startedHere = settings.launchUrl ? Date.now() : ((tab && tab.startedHere) || session.startedHere || 0);
753
+ const data = stored(Object.assign({}, session, { startedHere }));
754
+ if (tab) Object.assign(tab, data);
755
+ else {
756
+ tab = data;
757
+ tabs.push(tab);
758
+ }
759
+ // a narrow screen shows one window at a time
760
+ if (narrow()) openTabs().forEach((other) => { if (other.key !== tab.key) minimise(other.key); });
761
+ // if the row is full, one is minimised to make room
762
+ if (fresh && !tab.docked) fitRow(true);
763
+ tab.open = true;
764
+ const win = wins.get(tab.key) || createWindow(tab.key);
765
+ const part = win.part;
766
+ win.session = Object.assign({}, session, { startedHere });
767
+ const info = describe(win.session);
768
+ part.icon.textContent = '';
769
+ part.icon.appendChild(H.toolIcon({ iconSrc: session.iconSrc, iconClass: session.iconClass }));
770
+ part.title.textContent = info.title;
771
+ part.sub.textContent = info.sub;
772
+ // where this session lives
773
+ const place = where(win.session);
774
+ part.open.hidden = !place;
775
+ if (place) part.open.textContent = place.label;
776
+ part.whereRow.dataset.none = String(!place);
777
+ if (place) part.whereRow.lastChild.textContent = place.label;
778
+ disarm(part.stop);
779
+ setMore(win, false);
780
+ const frameUrl = settings.launchUrl || session.url;
781
+ if (frameUrl && (settings.launchUrl || !part.frame.dataset.url)) {
782
+ part.frame.dataset.url = frameUrl;
783
+ part.frame.src = frameUrl;
784
+ embedSoon(win);
785
+ }
786
+ win.element.dataset.docked = String(tab.docked === true);
787
+ applyBox(win, tab, settings.keep);
788
+ syncWide(win);
789
+ if (settings.still) win.element.classList.add('agent-bar-panel--still');
790
+ win.element.getBoundingClientRect();
791
+ win.element.dataset.open = 'true';
792
+ if (settings.still) window.setTimeout(() => win.element.classList.remove('agent-bar-panel--still'), 300);
793
+ syncSide(settings.still === true);
794
+ focus(tab.key);
795
+ tile(settings.keep);
796
+ renderChip();
797
+ if (menuOpen) renderMenu();
798
+ // opened by you (a tab, a row, a send), not brought back by a page change
799
+ if (!settings.still) wantKeyboard(tab.key);
800
+ }
801
+
802
+ // ---- the dock ---------------------------------------------------------------
803
+ // The one button that depends on where a session lives.
804
+ function where(session) {
805
+ if (session.placeKind === 'app') {
806
+ const href = session.appHref || `/p/${encodeURIComponent(session.folder)}`;
807
+ const page = (value) => decodeURIComponent(String(value).split('?')[0]).split('/').slice(0, 3).join('/');
808
+ if (page(window.location.pathname) === page(href)) return null; // already on this app's page
809
+ return { label: 'Open app', run: () => leaveFor(href) };
810
+ }
811
+ if (session.placeKind === 'plugin') {
812
+ return { label: 'Open plugin', run: () => leaveFor(`/plugin?path=${encodeURIComponent(`plugin/${session.folder}`)}`) };
813
+ }
814
+ // a workspace: its folder, in the system's file explorer (as "Open in File Explorer" does)
815
+ return {
816
+ label: 'Open folder',
817
+ run: () => {
818
+ fetch('/openfs', {
819
+ method: 'POST',
820
+ headers: { 'Content-Type': 'application/json' },
821
+ body: JSON.stringify({ path: session.rootPath, mode: 'open' }),
822
+ }).then((response) => {
823
+ if (!response.ok) throw new Error('failed');
824
+ }).catch(() => toast('Could not open the folder.'));
825
+ },
826
+ };
827
+ }
828
+
829
+ // Stop asks once more before it acts: the first click arms it, the second stops.
830
+ function stopButton(className, run) {
831
+ const button = H.el('button', className);
832
+ button.type = 'button';
833
+ button.title = 'Stop this session';
834
+ button.append(H.faIcon('fa-solid fa-stop'), H.el('span', '', 'Stop'));
835
+ button.addEventListener('click', (event) => {
836
+ event.stopPropagation();
837
+ if (button.dataset.armed === 'true') {
838
+ // the second half of a double-click is not a confirmation
839
+ if (Date.now() - button.armedAt < 600) return;
840
+ disarm(button);
841
+ run();
842
+ return;
843
+ }
844
+ button.dataset.armed = 'true';
845
+ button.armedAt = Date.now();
846
+ button.lastChild.textContent = 'Confirm stop';
847
+ button.armTimer = window.setTimeout(() => disarm(button), 4000);
848
+ });
849
+ return button;
850
+ }
851
+ function disarm(button) {
852
+ if (!button) return;
853
+ window.clearTimeout(button.armTimer);
854
+ button.dataset.armed = 'false';
855
+ button.lastChild.textContent = 'Stop';
856
+ }
857
+ // Reload the session's own page. It attaches to the session and carries no
858
+ // prompt; a session that is not running is not reloaded, since that would start it.
859
+ function reload(win) {
860
+ const session = win.session;
861
+ if (!session || !session.url) return;
862
+ whenRunning(session, () => {
863
+ if (!wins.has(win.key)) return;
864
+ win.part.frame.dataset.url = session.url;
865
+ win.part.frame.src = session.url;
866
+ embedSoon(win);
867
+ });
868
+ }
869
+
870
+ // Socket.js declares `class Socket` at the top level. That makes `Socket` a
871
+ // global name, but not a property of window, so both are looked at (as
872
+ // Pinokio's own common.js and layout.js do).
873
+ /* global Socket */
874
+ const socketClass = () => {
875
+ if (typeof window.Socket === 'function') return window.Socket;
876
+ return typeof Socket === 'function' ? Socket : null;
877
+ };
878
+ function ensureSocket() {
879
+ if (socketClass()) return Promise.resolve(socketClass());
880
+ return new Promise((resolve, reject) => {
881
+ const script = document.createElement('script');
882
+ script.src = '/Socket.js';
883
+ script.async = true;
884
+ script.onload = () => (socketClass() ? resolve(socketClass()) : reject(new Error('socket')));
885
+ script.onerror = () => reject(new Error('socket'));
886
+ (document.head || document.documentElement).appendChild(script);
887
+ });
888
+ }
889
+ // Ends a session the way its own page's Stop does: an agent by its running key
890
+ // (kernel.api.stop), a shell by its id (kernel.bin.shell_kill).
891
+ // Only a session that is running right now is stopped (see whenRunning).
892
+ // `sent` (optional) is called once the request is on its way.
893
+ function stopSession(session, sent) {
894
+ whenRunning(session, (live) => {
895
+ const request = live.kind === 'shell'
896
+ ? { method: 'kernel.bin.shell_kill', params: { id: live.ref } }
897
+ : { method: 'kernel.api.stop', params: { id: live.ref } };
898
+ ensureSocket().then((SocketConstructor) => {
899
+ const socket = new SocketConstructor();
900
+ const done = () => {
901
+ try {
902
+ socket.close();
903
+ } catch (_) {}
904
+ };
905
+ Promise.resolve(socket.run(request, () => {})).then(done, done);
906
+ window.setTimeout(done, 4000);
907
+ // it is gone from here at once; the list is read again to confirm
908
+ close(session.key);
909
+ sessions = sessions.filter((item) => item.ref !== live.ref);
910
+ lastLook = ''; // taken off the list here, before the server has: the next look redraws whatever it shows
911
+ renderChip();
912
+ if (menuOpen) renderMenu();
913
+ if (sent) sent();
914
+ window.setTimeout(refresh, 1200);
915
+ // a stop that did not go through is said, not hidden behind the closed window
916
+ window.setTimeout(() => refresh().then((read) => {
917
+ if (read && sessions.some((item) => item.ref === live.ref)) toast(`${live.label} is still running. Stop did not go through.`);
918
+ }), 5000);
919
+ }).catch(() => toast('Could not stop this session.'));
920
+ });
921
+ }
922
+
923
+ let toastNode = null;
924
+ let toastTimer = null;
925
+ function toast(text) {
926
+ if (!toastNode) {
927
+ toastNode = H.el('div', 'agent-dock__toast');
928
+ toastNode.setAttribute('role', 'status');
929
+ document.body.appendChild(toastNode);
930
+ }
931
+ toastNode.textContent = '';
932
+ toastNode.appendChild(H.el('span', '', text));
933
+ toastNode.hidden = false;
934
+ window.clearTimeout(toastTimer);
935
+ toastTimer = window.setTimeout(() => { toastNode.hidden = true; }, 9000);
936
+ }
937
+
938
+ // ---- the session's own page, inside the window ---------------------------------
939
+ // The page (terminal.ejs, shell.ejs) has a row of its own above the terminal:
940
+ // Run/Stop, Save task, a status line and two terminal buttons. Inside the window
941
+ // the header already has Stop, so that row is folded away and the terminal fills
942
+ // the window. The two terminal buttons are pressed from the more menu, and their
943
+ // "Terminal appearance" menu opens at the top right of the page as it always did.
944
+ // The page itself is not changed: this is styling added to its document while
945
+ // it is shown here. Its full page ("Open in a new tab") looks as before.
946
+ const EMBED_STYLE = `
947
+ html.pinokio-dock-embed .navheader2 {
948
+ position: relative !important;
949
+ z-index: 1600;
950
+ height: 0 !important;
951
+ min-height: 0 !important;
952
+ margin: 0 !important;
953
+ padding: 0 !important;
954
+ border: 0 !important;
955
+ overflow: visible !important;
956
+ }
957
+ html.pinokio-dock-embed .navheader2 .runner {
958
+ height: 0 !important;
959
+ min-height: 0 !important;
960
+ margin: 0 !important;
961
+ padding: 0 !important;
962
+ }
963
+ html.pinokio-dock-embed .navheader2 .runner > *:not(.terminal-runner-utilities) {
964
+ display: none !important;
965
+ }
966
+ html.pinokio-dock-embed .terminal-runner-utilities {
967
+ position: absolute !important;
968
+ top: 0;
969
+ right: 8px;
970
+ height: 0;
971
+ margin: 0 !important;
972
+ }
973
+ html.pinokio-dock-embed .terminal-runner-utilities button.terminal-utility-button {
974
+ visibility: hidden !important;
975
+ width: 0 !important;
976
+ min-width: 0 !important;
977
+ height: 0 !important;
978
+ margin: 0 !important;
979
+ padding: 0 !important;
980
+ border: 0 !important;
981
+ overflow: hidden !important;
982
+ }
983
+ html.pinokio-dock-embed .terminal-config-menu {
984
+ top: 8px !important;
985
+ right: 0 !important;
986
+ }
987
+ `;
988
+ function embed(win) {
989
+ let doc = null;
990
+ try {
991
+ doc = win.part.frame ? win.part.frame.contentDocument : null;
992
+ } catch (_) {
993
+ return null;
994
+ }
995
+ if (!doc || !doc.documentElement || !doc.head || !doc.body) return null;
996
+ if (!doc.getElementById('agent-dock-embed')) {
997
+ const style = doc.createElement('style');
998
+ style.id = 'agent-dock-embed';
999
+ style.textContent = EMBED_STYLE;
1000
+ doc.head.appendChild(style);
1001
+ doc.documentElement.classList.add('pinokio-dock-embed');
1002
+ }
1003
+ watchTerminal(win, doc);
1004
+ return doc;
1005
+ }
1006
+
1007
+ // What shows around the terminal's text: its side padding, the scrollbar's
1008
+ // track, and the last partial row and column. All of that has the terminal's own
1009
+ // background, which on a light Pinokio is white. An agent that draws its own
1010
+ // dark screen (most do) fills every cell, so it ends up as a dark screen inside
1011
+ // a white frame. Here that frame takes the colour the agent's screen has: the
1012
+ // background of the cells at the corners of the screen, read from the terminal
1013
+ // itself. A terminal that draws no background of its own is left as it is.
1014
+ const ANSI_16 = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5',
1015
+ '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff'];
1016
+ const ANSI_NAMES = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white',
1017
+ 'brightBlack', 'brightRed', 'brightGreen', 'brightYellow', 'brightBlue', 'brightMagenta', 'brightCyan', 'brightWhite'];
1018
+ const hex = (red, green, blue) => `#${[red, green, blue].map((part) => part.toString(16).padStart(2, '0')).join('')}`;
1019
+ function paletteColour(index, theme) {
1020
+ if (index < 16) return (theme && theme[ANSI_NAMES[index]]) || ANSI_16[index];
1021
+ if (index < 232) {
1022
+ const step = (value) => (value === 0 ? 0 : 55 + value * 40);
1023
+ const cube = index - 16;
1024
+ return hex(step(Math.floor(cube / 36)), step(Math.floor(cube / 6) % 6), step(cube % 6));
1025
+ }
1026
+ const grey = 8 + (index - 232) * 10;
1027
+ return hex(grey, grey, grey);
1028
+ }
1029
+ // The background a cell was drawn with, or '' when it has the terminal's default.
1030
+ function cellColour(term, x, y) {
1031
+ try {
1032
+ const line = term.buffer.active.getLine(y);
1033
+ const cell = line && line.getCell(x);
1034
+ if (!cell || cell.isBgDefault()) return '';
1035
+ if (cell.isBgRGB()) {
1036
+ const value = cell.getBgColor();
1037
+ return hex((value >> 16) & 255, (value >> 8) & 255, value & 255);
1038
+ }
1039
+ if (cell.isBgPalette()) return paletteColour(cell.getBgColor(), term.options && term.options.theme);
1040
+ } catch (_) {}
1041
+ return '';
1042
+ }
1043
+ // The terminal of a session's page (its window object), once the page has made one.
1044
+ function terminalOf(view) {
1045
+ const settings = view && view.PinokioTerminalSettings;
1046
+ return settings && settings.terminals && typeof settings.terminals.values === 'function'
1047
+ ? settings.terminals.values().next().value || null
1048
+ : null;
1049
+ }
1050
+ function paintAround(doc) {
1051
+ const view = doc.defaultView;
1052
+ const viewport = doc.querySelector('.xterm-viewport');
1053
+ if (!view || !viewport) return;
1054
+ const term = terminalOf(view);
1055
+ let colour = '';
1056
+ if (term && term.buffer && term.buffer.active && term.cols > 0 && term.rows > 0) {
1057
+ // the screen as it is now (not the scrollback): its two bottom corners must agree
1058
+ const bottom = term.buffer.active.baseY + term.rows - 1;
1059
+ const left = cellColour(term, 0, bottom);
1060
+ const right = cellColour(term, term.cols - 1, bottom);
1061
+ if (left && left === right) colour = left;
1062
+ }
1063
+ const root = doc.documentElement;
1064
+ if (colour) {
1065
+ // set every time: the terminal puts its own background back whenever its theme is applied
1066
+ root.dataset.dockPaint = colour;
1067
+ viewport.style.backgroundColor = colour;
1068
+ doc.body.style.backgroundColor = colour;
1069
+ // the scrollbar's track follows: dark on a dark screen
1070
+ const [red, green, blue] = [1, 3, 5].map((at) => parseInt(colour.slice(at, at + 2), 16));
1071
+ viewport.style.colorScheme = (red * 299 + green * 587 + blue * 114) / 1000 < 128 ? 'dark' : 'light';
1072
+ } else if (root.dataset.dockPaint) {
1073
+ // the agent's screen is gone (it exited, or cleared to the default): back to the terminal's own
1074
+ delete root.dataset.dockPaint;
1075
+ const theme = term && term.options ? term.options.theme : null;
1076
+ viewport.style.backgroundColor = (theme && theme.background) || '';
1077
+ viewport.style.colorScheme = '';
1078
+ doc.body.style.backgroundColor = '';
1079
+ }
1080
+ }
1081
+ // The frame is looked at when the terminal has drawn something, not on a timer:
1082
+ // a terminal that sits idle costs nothing. A page makes its terminal some time
1083
+ // after it loads (it may ask for permission first), so until there is one the
1084
+ // page is watched for it.
1085
+ function watchTerminal(win, doc) {
1086
+ if (win.watched === doc) return;
1087
+ const term = terminalOf(doc.defaultView);
1088
+ if (!term || typeof term.onRender !== 'function') {
1089
+ if (win.awaiting && win.awaiting.doc === doc) return;
1090
+ if (win.awaiting) win.awaiting.observer.disconnect();
1091
+ const observer = new MutationObserver(() => watchTerminal(win, doc));
1092
+ observer.observe(doc.body, { childList: true, subtree: true });
1093
+ win.awaiting = { doc, observer };
1094
+ return;
1095
+ }
1096
+ if (win.awaiting) win.awaiting.observer.disconnect();
1097
+ win.awaiting = null;
1098
+ win.watched = doc;
1099
+ let due = 0;
1100
+ term.onRender(() => {
1101
+ if (due) return;
1102
+ due = window.setTimeout(() => {
1103
+ due = 0;
1104
+ paintAround(doc);
1105
+ }, 400);
1106
+ });
1107
+ paintAround(doc);
1108
+ giveKeyboard(win);
1109
+ }
1110
+
1111
+ // ---- the keyboard goes where you just went ------------------------------------
1112
+ // Clicking a tab or a row of the running list, or sending, puts the cursor in
1113
+ // that window's terminal, so you can type at once. Its page may still be
1114
+ // loading, so the wish is kept for a few seconds and granted when the terminal
1115
+ // is there (see watchTerminal). Not on a phone, where it would bring the
1116
+ // keyboard up on every tap.
1117
+ const KEYBOARD_WAIT_MS = 10000;
1118
+ let keyboardFor = { key: '', until: 0 };
1119
+ function giveKeyboard(win) {
1120
+ if (keyboardFor.key !== win.key) return;
1121
+ if (Date.now() > keyboardFor.until) {
1122
+ keyboardFor = { key: '', until: 0 };
1123
+ return;
1124
+ }
1125
+ try {
1126
+ const view = win.part.frame.contentWindow;
1127
+ const term = terminalOf(view);
1128
+ if (!term || typeof term.focus !== 'function') return;
1129
+ view.focus();
1130
+ term.focus();
1131
+ keyboardFor = { key: '', until: 0 };
1132
+ } catch (_) {}
1133
+ }
1134
+ function wantKeyboard(key) {
1135
+ if (narrow()) return;
1136
+ keyboardFor = { key, until: Date.now() + KEYBOARD_WAIT_MS };
1137
+ const win = wins.get(key);
1138
+ if (win) giveKeyboard(win);
1139
+ }
1140
+
1141
+ // A page that has just started loading: styled as early as its document is
1142
+ // there, so its own row does not flash before the page has finished loading.
1143
+ function embedSoon(win) {
1144
+ window.clearInterval(win.embedTimer);
1145
+ let tries = 0;
1146
+ win.embedTimer = window.setInterval(() => {
1147
+ tries += 1;
1148
+ embed(win);
1149
+ if (tries > 60 || !wins.has(win.key)) window.clearInterval(win.embedTimer);
1150
+ }, 50);
1151
+ }
1152
+ function pressInPage(win, selector) {
1153
+ const doc = embed(win);
1154
+ const button = doc && doc.querySelector(selector);
1155
+ if (button) button.click();
1156
+ }
1157
+
1158
+ function setMore(win, open) {
1159
+ const part = win.part;
1160
+ if (!part.moreMenu) return;
1161
+ if (open) {
1162
+ const doc = embed(win);
1163
+ part.termLook.hidden = !(doc && doc.querySelector('.terminal-config-button'));
1164
+ part.termSync.hidden = !(doc && doc.querySelector('.terminal-resize-button'));
1165
+ }
1166
+ part.moreMenu.hidden = !open;
1167
+ part.more.classList.toggle('is-open', Boolean(open));
1168
+ }
1169
+
1170
+ // App pages: the app's own bar (agent-bar-app.js) opens its sessions here.
1171
+ // A launch address is built the way the page's own panel builds it
1172
+ // (normalizeLaunchUrl in app.ejs): the app's folder, and the prompt if any.
1173
+ function launchAddress(rawUrl, prompt) {
1174
+ let url;
1175
+ try {
1176
+ url = new URL(rawUrl, window.location.origin);
1177
+ } catch (_) {
1178
+ return null;
1179
+ }
1180
+ if (url.origin !== window.location.origin) return null;
1181
+ const path = url.pathname;
1182
+ if (path.startsWith('/run/plugin/') || path.startsWith('/pinokio/run/plugin/')
1183
+ || (path.startsWith('/run/api/') && /\/pinokio\.js$/i.test(path))) {
1184
+ if (appCwd && !url.searchParams.has('cwd')) url.searchParams.set('cwd', appCwd);
1185
+ url.searchParams.set('ask_ai', '1');
1186
+ url.searchParams.delete('prompt');
1187
+ if (prompt) url.searchParams.set('prompt', prompt);
1188
+ }
1189
+ return url;
1190
+ }
1191
+ // The session an address belongs to: the running one, as the list has it, or
1192
+ // one made up from the address (a session that is only being started now).
1193
+ function sessionAt(url, label) {
1194
+ const sessionId = url.searchParams.get('session') || '';
1195
+ const address = `${url.pathname}${url.search}`;
1196
+ if (url.pathname.startsWith('/shell/')) {
1197
+ let shellId = '';
1198
+ try {
1199
+ shellId = `shell/${decodeURIComponent(url.pathname.slice('/shell/'.length))}`;
1200
+ } catch (_) {
1201
+ return null;
1202
+ }
1203
+ const running = sessions.find((item) => item.kind === 'shell' && item.shellId === shellId && (item.shellSession || '') === sessionId);
1204
+ if (running) return Object.assign({}, running, { url: address, tabUrl: address });
1205
+ const place = placeOf(appCwd);
1206
+ return Object.assign({
1207
+ key: shellKey(shellId, sessionId), kind: 'shell', label: label || 'Shell',
1208
+ iconClass: 'fa-solid fa-terminal', start: Date.now(), shellId, shellSession: sessionId,
1209
+ url: address, fullUrl: '', tabUrl: address, appHref: `/p/${encodeURIComponent(place.folder)}`,
1210
+ }, place);
1211
+ }
1212
+ const tail = H.pluginTail(url.pathname);
1213
+ const cwd = url.searchParams.get('cwd') || appCwd;
1214
+ const key = sessionKey(tail, cwd, sessionId);
1215
+ const running = sessions.find((item) => item.key === key);
1216
+ if (running) return running;
1217
+ const tool = tools.find((item) => H.pluginTail(item.href) === tail) || {};
1218
+ const place = placeOf(cwd);
1219
+ const urls = agentUrls(url.pathname, cwd, sessionId);
1220
+ return Object.assign({
1221
+ key, kind: 'agent', label: tool.label || 'Agent', iconSrc: tool.iconSrc || '', start: Date.now(),
1222
+ url: urls.url, fullUrl: '', tabUrl: urls.fullUrl, appHref: `/p/${encodeURIComponent(place.folder)}`,
1223
+ }, place);
1224
+ }
1225
+ // `launch` is true for a session that is being started now (a send, a new
1226
+ // shell); otherwise the address is one of a running session and attaches to it.
1227
+ function openFromUrl(rawUrl, options) {
1228
+ const settings = options || {};
1229
+ const prompt = typeof settings.prompt === 'string' ? settings.prompt.trim() : '';
1230
+ const url = launchAddress(rawUrl, prompt);
1231
+ const session = url ? sessionAt(url, settings.label) : null;
1232
+ if (!session) return false;
1233
+ const address = `${url.pathname}${url.search}`;
1234
+ if (prompt) {
1235
+ asked[session.key] = prompt;
1236
+ write(STORE_ASKED, asked);
1237
+ }
1238
+ if (settings.launch) {
1239
+ open(Object.assign({}, session, { startedHere: Date.now() }), { launchUrl: address });
1240
+ [1500, 4000].forEach((delay) => window.setTimeout(refresh, delay));
1241
+ } else {
1242
+ // attaching: only while it is still running
1243
+ show(session);
1244
+ }
1245
+ return true;
1246
+ }
1247
+ function offerDock() {
1248
+ const drawer = document.getElementById('ask-ai-drawer');
1249
+ appCwd = drawer ? (drawer.dataset.workspaceCwd || '') : '';
1250
+ window.PinokioAgentDock = {
1251
+ // a running session's own address: attaches to it
1252
+ openWithUrl: (rawUrl) => openFromUrl(rawUrl, {}),
1253
+ // a send: starts the agent with the prompt
1254
+ openWithAgent: (payload) => {
1255
+ if (!payload || typeof payload.agentHref !== 'string' || !payload.agentHref) return false;
1256
+ return openFromUrl(payload.agentHref, { prompt: payload.prompt || '', launch: true });
1257
+ },
1258
+ // a new shell, with a session of its own
1259
+ openShellTool: (shell) => {
1260
+ if (!shell || typeof shell.href !== 'string') return false;
1261
+ let href = shell.href;
1262
+ if (!href.includes('session=')) href += `${href.includes('?') ? '&' : '?'}session=${encodeURIComponent(H.newSession())}`;
1263
+ return openFromUrl(href, { launch: true, label: shell.label });
1264
+ },
1265
+ // a plugin that is not installed yet still goes to its install page, the page's own way
1266
+ redirectToPluginInstallIfNeeded: (href) => {
1267
+ const page = window.PinokioAskAiDrawer;
1268
+ return page && typeof page.redirectToPluginInstallIfNeeded === 'function'
1269
+ ? page.redirectToPluginInstallIfNeeded(href)
1270
+ : Promise.resolve(false);
1271
+ },
1272
+ // A Stop button for the running session at this address, for a row of the
1273
+ // app bar's list: the same button as on the home bar's rows (asks twice).
1274
+ stopButton: (rawUrl, sent) => {
1275
+ const url = launchAddress(rawUrl, '');
1276
+ const session = url ? sessionAt(url) : null;
1277
+ return session ? stopButton('agent-dock__liststop', () => stopSession(session, sent)) : null;
1278
+ },
1279
+ // the addresses of every session that has a window up
1280
+ openUrls: () => openTabs().map((tab) => {
1281
+ const win = wins.get(tab.key);
1282
+ return win && win.session ? (win.session.url || '') : '';
1283
+ }).filter(Boolean),
1284
+ };
1285
+ renderTabs();
1286
+ }
1287
+ const inGrace = (tab) => Boolean(tab.startedHere) && Date.now() - tab.startedHere < START_GRACE_MS;
1288
+ // what a tab keeps of its session (its window's own state is kept beside this)
1289
+ const stored = (session) => ({
1290
+ key: session.key, kind: session.kind, label: session.label, iconSrc: session.iconSrc || '', iconClass: session.iconClass || '',
1291
+ start: session.start, url: session.url, fullUrl: session.fullUrl, appHref: session.appHref,
1292
+ placeKind: session.placeKind, placeName: session.placeName, folder: session.folder, rootPath: session.rootPath,
1293
+ shellId: session.shellId || '', shellSession: session.shellSession || '', startedHere: session.startedHere || 0,
1294
+ ref: session.ref || '', tabUrl: session.tabUrl || '',
1295
+ });
1296
+ // Takes a tab away, and its window with it. The session is not touched.
1297
+ function removeTab(key) {
1298
+ tabs = tabs.filter((tab) => tab.key !== key);
1299
+ const win = wins.get(key);
1300
+ if (win) {
1301
+ wins.delete(key);
1302
+ window.clearInterval(win.embedTimer);
1303
+ if (win.awaiting) win.awaiting.observer.disconnect();
1304
+ win.element.dataset.open = 'false';
1305
+ // let go of the session's page once the window has faded away
1306
+ window.setTimeout(() => win.element.remove(), 220);
1307
+ }
1308
+ if (frontKey === key) {
1309
+ const next = openTabs().slice().sort((a, b) => (b.z || 0) - (a.z || 0))[0];
1310
+ frontKey = next ? next.key : '';
1311
+ }
1312
+ saveTabs();
1313
+ syncSide();
1314
+ tile();
1315
+ renderTabs();
1316
+ }
1317
+ // A tab whose session has ended goes away: opening it again would start the
1318
+ // agent again. One whose window is on screen stays until it is minimised or closed.
1319
+ function pruneTabs() {
1320
+ // not before the list of running sessions can be read properly
1321
+ if (!toolsReady) {
1322
+ renderTabs();
1323
+ return;
1324
+ }
1325
+ tabs.slice().forEach((tab) => {
1326
+ const live = sessions.find((session) => session.key === tab.key);
1327
+ if (live) {
1328
+ Object.assign(tab, stored(Object.assign({}, tab, live)), { ended: false });
1329
+ // once it is listed, Stop knows what to stop
1330
+ const win = wins.get(tab.key);
1331
+ if (win && win.session) win.session = Object.assign({}, win.session, { ref: live.ref, start: live.start });
1332
+ } else if (tab.open || inGrace(tab)) {
1333
+ tab.ended = !inGrace(tab);
1334
+ } else {
1335
+ removeTab(tab.key);
1336
+ }
1337
+ });
1338
+ saveTabs();
1339
+ renderTabs();
1340
+ }
1341
+ function minimise(key) {
1342
+ const tab = tabOf(key);
1343
+ if (!tab || !tab.open) return;
1344
+ tab.open = false;
1345
+ const win = wins.get(key);
1346
+ if (win) {
1347
+ win.element.dataset.open = 'false';
1348
+ setMore(win, false);
1349
+ }
1350
+ if (frontKey === key) {
1351
+ const next = openTabs().slice().sort((a, b) => (b.z || 0) - (a.z || 0))[0];
1352
+ frontKey = next ? next.key : '';
1353
+ }
1354
+ saveTabs();
1355
+ syncSide();
1356
+ tile();
1357
+ renderChip();
1358
+ pruneTabs();
1359
+ }
1360
+ // A tab: opens its window, brings it to the front, or (already in front) minimises it.
1361
+ function pickTab(tab) {
1362
+ if (tab.open) {
1363
+ if (tab.key === frontKey) {
1364
+ minimise(tab.key);
1365
+ } else {
1366
+ focus(tab.key);
1367
+ wantKeyboard(tab.key);
1368
+ }
1369
+ return;
1370
+ }
1371
+ const live = sessions.find((session) => session.key === tab.key) || (inGrace(tab) ? tab : null);
1372
+ if (!live) {
1373
+ removeTab(tab.key);
1374
+ return;
1375
+ }
1376
+ show(Object.assign({}, tab, live));
1377
+ }
1378
+ // Closing a window closes its tab; the session keeps running.
1379
+ function close(key) {
1380
+ removeTab(key);
1381
+ renderChip();
1382
+ if (menuOpen) renderMenu();
1383
+ }
1384
+
1385
+ // Floating: a window is moved by its header and resized at any edge or corner.
1386
+ // Both work on its box in screen coordinates; what is kept is its size and how
1387
+ // far its right and bottom edges are from the screen's.
1388
+ function bindFloatGrips(win) {
1389
+ const panel = win.element;
1390
+ const boxNow = () => {
1391
+ const box = panel.getBoundingClientRect();
1392
+ return { left: box.left, top: box.top, right: box.right, bottom: box.bottom };
1393
+ };
1394
+ const place = (box) => setFloat(panel, {
1395
+ w: box.right - box.left, h: box.bottom - box.top,
1396
+ r: window.innerWidth - box.right, b: window.innerHeight - box.bottom,
1397
+ });
1398
+ // Where it was put and how big, kept on its tab so it is the same on the next page.
1399
+ const remember = () => {
1400
+ const tab = tabOf(win.key);
1401
+ if (!tab) return;
1402
+ const box = panel.getBoundingClientRect();
1403
+ tab.box = {
1404
+ w: Math.round(box.width), h: Math.round(box.height),
1405
+ r: Math.round(window.innerWidth - box.right), b: Math.round(window.innerHeight - box.bottom),
1406
+ };
1407
+ saveTabs();
1408
+ };
1409
+ const floating = () => {
1410
+ const tab = tabOf(win.key);
1411
+ return Boolean(tab) && !tab.docked && window.innerWidth > 768;
1412
+ };
1413
+
1414
+ // `change(box, dx, dy, limits)` gives the box for a pointer that has moved by dx, dy.
1415
+ function dragOn(handle, kind, change) {
1416
+ let start = null;
1417
+ let moving = false;
1418
+ let changed = false;
1419
+ const begin = () => {
1420
+ moving = true;
1421
+ // no sliding while it follows the pointer, and the sessions' pages must not swallow the drag
1422
+ root.classList.add(STILL_CLASS, 'agent-dock-resizing');
1423
+ root.dataset.dockResize = kind;
1424
+ };
1425
+ handle.addEventListener('pointerdown', (event) => {
1426
+ if (!floating() || event.button > 0) return;
1427
+ // the header's buttons stay buttons
1428
+ if (kind === 'move' && event.target.closest('button')) return;
1429
+ start = { x: event.clientX, y: event.clientY, box: boxNow(), pointerId: event.pointerId };
1430
+ moving = false;
1431
+ changed = false;
1432
+ // From here on the pointer belongs to this handle, wherever it goes. Without
1433
+ // this a quick pull leaves the header before the first move is seen.
1434
+ try {
1435
+ handle.setPointerCapture(event.pointerId);
1436
+ } catch (_) {}
1437
+ // a grip acts at once; the header waits for a real drag, so a click stays a click
1438
+ if (kind !== 'move') {
1439
+ event.preventDefault();
1440
+ begin();
1441
+ }
1442
+ });
1443
+ handle.addEventListener('pointermove', (event) => {
1444
+ if (!start) return;
1445
+ const dx = event.clientX - start.x;
1446
+ const dy = event.clientY - start.y;
1447
+ // A hand moves a few pixels while it presses. That is a click, not a drag:
1448
+ // the header must be pulled a clear distance before the window follows,
1449
+ // and an edge a little before it resizes.
1450
+ if (!moving) {
1451
+ if (Math.hypot(dx, dy) < 10) return;
1452
+ begin();
1453
+ }
1454
+ if (!changed && Math.hypot(dx, dy) < 4) return;
1455
+ changed = true;
1456
+ place(change(start.box, dx, dy, floatLimits()));
1457
+ });
1458
+ const end = (event) => {
1459
+ if (!start) return;
1460
+ const was = moving;
1461
+ start = null;
1462
+ moving = false;
1463
+ try {
1464
+ handle.releasePointerCapture(event.pointerId);
1465
+ } catch (_) {}
1466
+ if (!was) return;
1467
+ root.classList.remove(STILL_CLASS, 'agent-dock-resizing');
1468
+ delete root.dataset.dockResize;
1469
+ // The window stays where it was put, and nothing else moves, so the others
1470
+ // cannot slide under it; the next layout of the row takes it back in.
1471
+ // (A press on an edge that moved nothing changes nothing.)
1472
+ if (changed) remember();
1473
+ };
1474
+ handle.addEventListener('pointerup', end);
1475
+ handle.addEventListener('pointercancel', end);
1476
+ }
1477
+
1478
+ // move: by the header, anywhere that is not a button
1479
+ const header = panel.querySelector('.agent-bar-panel__header');
1480
+ // The agent's icon is an image, and the browser picks an image up for its own
1481
+ // drag-and-drop, which cancels this one. Nothing in the header is dragged that way.
1482
+ header.addEventListener('dragstart', (event) => event.preventDefault());
1483
+ dragOn(header, 'move', (box, dx, dy, limits) => {
1484
+ const width = box.right - box.left;
1485
+ const height = box.bottom - box.top;
1486
+ const left = Math.max(limits.left, Math.min(box.left + dx, limits.right - width));
1487
+ const top = Math.max(limits.top, Math.min(box.top + dy, limits.bottom - height));
1488
+ return { left, top, right: left + width, bottom: top + height };
1489
+ });
1490
+ // double-click the header: back into the row
1491
+ header.addEventListener('dblclick', (event) => {
1492
+ if (!floating() || event.target.closest('button')) return;
1493
+ joinRow(win);
1494
+ });
1495
+
1496
+ // resize: four edges and four corners
1497
+ const resize = (sides) => (box, dx, dy, limits) => {
1498
+ let { left, top, right, bottom } = box;
1499
+ if (sides.includes('l')) left = Math.max(limits.left, Math.min(box.left + dx, right - FLOAT_MIN_W));
1500
+ if (sides.includes('r')) right = Math.min(limits.right, Math.max(box.right + dx, left + FLOAT_MIN_W));
1501
+ if (sides.includes('t')) top = Math.max(limits.top, Math.min(box.top + dy, bottom - FLOAT_MIN_H));
1502
+ if (sides.includes('b')) bottom = Math.min(limits.bottom, Math.max(box.bottom + dy, top + FLOAT_MIN_H));
1503
+ return { left, top, right, bottom };
1504
+ };
1505
+ [['left', 'l'], ['right', 'r'], ['top', 't'], ['bottom', 'b'], ['tl', 'tl'], ['tr', 'tr'], ['bl', 'bl'], ['br', 'br']].forEach(([edge, sides]) => {
1506
+ const grip = H.el('div', 'agent-dock__grip');
1507
+ grip.dataset.edge = edge;
1508
+ panel.appendChild(grip);
1509
+ dragOn(grip, edge, resize(sides));
1510
+ // double-click: back into the row, at the row's size
1511
+ grip.addEventListener('dblclick', () => joinRow(win));
1512
+ });
1513
+ }
1514
+ // Docked to the side: its one free edge is dragged. The width is the same for
1515
+ // whichever window is docked, and remembered.
1516
+ function bindResizer(win) {
1517
+ const panel = win.element;
1518
+ const handle = win.part.resizer;
1519
+ let dragging = false;
1520
+ const isDocked = () => {
1521
+ const tab = tabOf(win.key);
1522
+ return Boolean(tab && tab.docked);
1523
+ };
1524
+ const remember = () => {
1525
+ const width = Math.round(panel.getBoundingClientRect().width);
1526
+ try {
1527
+ window.localStorage.setItem(STORE_WIDTH, String(width));
1528
+ } catch (_) {}
1529
+ handle.setAttribute('aria-valuenow', String(width));
1530
+ };
1531
+ const setWidth = (width) => root.style.setProperty('--agent-bar-panel-w', `${clampWidth(width)}px`);
1532
+ handle.addEventListener('pointerdown', (event) => {
1533
+ if (!isDocked() || event.button > 0) return;
1534
+ event.preventDefault();
1535
+ dragging = true;
1536
+ try {
1537
+ handle.setPointerCapture(event.pointerId);
1538
+ } catch (_) {}
1539
+ root.classList.add(STILL_CLASS, 'agent-dock-resizing');
1540
+ });
1541
+ handle.addEventListener('pointermove', (event) => {
1542
+ if (dragging) setWidth(window.innerWidth - event.clientX);
1543
+ });
1544
+ const end = (event) => {
1545
+ if (!dragging) return;
1546
+ dragging = false;
1547
+ try {
1548
+ handle.releasePointerCapture(event.pointerId);
1549
+ } catch (_) {}
1550
+ root.classList.remove(STILL_CLASS, 'agent-dock-resizing');
1551
+ remember();
1552
+ // the row beside it has more or less room now
1553
+ fitRow();
1554
+ tile();
1555
+ };
1556
+ handle.addEventListener('pointerup', end);
1557
+ handle.addEventListener('pointercancel', end);
1558
+ // double-click: back to the default width
1559
+ handle.addEventListener('dblclick', () => {
1560
+ try {
1561
+ window.localStorage.removeItem(STORE_WIDTH);
1562
+ } catch (_) {}
1563
+ applyWidth();
1564
+ fitRow();
1565
+ tile();
1566
+ });
1567
+ handle.addEventListener('keydown', (event) => {
1568
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
1569
+ event.preventDefault();
1570
+ setWidth(panel.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? 16 : -16));
1571
+ remember();
1572
+ });
1573
+ }
1574
+ function syncWide(win) {
1575
+ const tab = tabOf(win.key);
1576
+ const docked = Boolean(tab && tab.docked);
1577
+ const label = docked ? 'Float' : 'Dock to the side';
1578
+ win.part.wide.title = label;
1579
+ win.part.wide.setAttribute('aria-label', label);
1580
+ win.part.wide.firstChild.className = docked ? 'fa-solid fa-window-restore' : 'fa-solid fa-table-columns';
1581
+ }
1582
+ // One window at a time can be docked to the side; docking another floats the first.
1583
+ function toggleDocked(win) {
1584
+ const tab = tabOf(win.key);
1585
+ if (!tab) return;
1586
+ const dockIt = !tab.docked;
1587
+ root.classList.add(STILL_CLASS);
1588
+ if (dockIt) {
1589
+ tabs.forEach((other) => {
1590
+ if (!other.docked || other.key === tab.key) return;
1591
+ other.docked = false;
1592
+ const otherWin = wins.get(other.key);
1593
+ if (!otherWin) return;
1594
+ otherWin.element.dataset.docked = 'false';
1595
+ applyBox(otherWin, other);
1596
+ syncWide(otherWin);
1597
+ });
1598
+ }
1599
+ tab.docked = dockIt;
1600
+ win.element.dataset.docked = String(dockIt);
1601
+ applyBox(win, tab);
1602
+ syncWide(win);
1603
+ syncSide();
1604
+ // the row has less room beside a docked window, and more without one
1605
+ fitRow();
1606
+ tile();
1607
+ saveTabs();
1608
+ renderTabs();
1609
+ window.setTimeout(() => root.classList.remove(STILL_CLASS), 50);
1610
+ }
1611
+ function renderTabs() {
1612
+ if (!H || !document.body) return;
1613
+ if (!dock) {
1614
+ dock = H.el('div', 'agent-dock');
1615
+ dock.setAttribute('aria-label', 'Open sessions');
1616
+ document.body.appendChild(dock);
1617
+ }
1618
+ // a window docked to the side and showing has no tab: its header is always on screen
1619
+ const shown = tabs.filter((tab) => !(tab.open === true && tab.docked));
1620
+ dock.textContent = '';
1621
+ dock.hidden = shown.length === 0;
1622
+ shown.forEach((tab) => {
1623
+ const info = describe(tab);
1624
+ const item = H.el('div', 'agent-dock__tab');
1625
+ // open: it has a window on screen; active: that window is the one in front
1626
+ item.dataset.active = String(tab.open === true && tab.key === frontKey);
1627
+ item.dataset.ended = String(tab.ended === true);
1628
+ const main = H.el('button', 'agent-dock__tab-main');
1629
+ main.type = 'button';
1630
+ main.title = `${info.title} · ${info.sub}`;
1631
+ const icon = H.el('span', 'agent-dock__tab-icon');
1632
+ icon.appendChild(H.toolIcon({ iconSrc: tab.iconSrc, iconClass: tab.iconClass }));
1633
+ main.append(icon, H.el('span', 'agent-dock__dot'), H.el('span', 'agent-dock__tab-title', info.title));
1634
+ main.addEventListener('click', () => pickTab(tab));
1635
+ const x = H.el('button', 'agent-dock__tab-x');
1636
+ x.type = 'button';
1637
+ x.title = 'Close';
1638
+ x.setAttribute('aria-label', `Close ${info.title}`);
1639
+ x.appendChild(H.faIcon('fa-solid fa-xmark'));
1640
+ x.addEventListener('click', () => close(tab.key));
1641
+ item.append(main, x);
1642
+ dock.appendChild(item);
1643
+ });
1644
+ }
1645
+
1646
+ // From the running list or a tab. A shell's page has to be looked up first.
1647
+ function show(session) {
1648
+ const win = wins.get(session.key);
1649
+ // its page is already in its window: nothing is loaded, so nothing can start
1650
+ if (win && win.part.frame.dataset.url) {
1651
+ open(session);
1652
+ return;
1653
+ }
1654
+ whenRunning(session, () => {
1655
+ if (session.kind !== 'shell' || session.url) {
1656
+ open(session);
1657
+ return;
1658
+ }
1659
+ shellUrl(session).then((url) => {
1660
+ if (url) open(Object.assign({}, session, { url }));
1661
+ else leaveFor(session.appHref);
1662
+ });
1663
+ });
1664
+ }
1665
+
1666
+ // Leaving for an app, a plugin or another page. The tabs come along.
1667
+ function leaveFor(url) {
1668
+ if (!url) return;
1669
+ bar.navigate(url);
1670
+ }
1671
+
1672
+ // ---- a send from the bar ---------------------------------------------------
1673
+ // Ask and Create plugin return the agent's own page. Create app returns the
1674
+ // new app's Dev page, which starts the agent itself from its address
1675
+ // (?plugin=...&prompt=...); the same start is made here, the way that page
1676
+ // builds it (see buildPluginLaunchFromQuery in app.ejs).
1677
+ function fromSend(info) {
1678
+ const tool = info.tool || {};
1679
+ let launch = null;
1680
+ try {
1681
+ const sent = new URL(info.url, window.location.origin);
1682
+ if (info.type === 'create_app') {
1683
+ const plugin = sent.searchParams.get('plugin') || '';
1684
+ const isSystem = plugin.startsWith('/pinokio/run/plugin/');
1685
+ const isLocal = plugin.startsWith('/plugin/') || plugin.startsWith('/api/');
1686
+ if (!info.cwd || (!isSystem && !isLocal)) return null;
1687
+ launch = new URL(isSystem ? plugin : `/run${plugin}`, window.location.origin);
1688
+ sent.searchParams.forEach((value, key) => {
1689
+ if (key !== 'plugin' && key !== 'plugin_label') launch.searchParams.set(key, value);
1690
+ });
1691
+ if (!launch.searchParams.has('cwd')) launch.searchParams.set('cwd', info.cwd);
1692
+ launch.searchParams.set('session', H.newSession());
1693
+ } else {
1694
+ // the panel has its own header, so the page's full navbar is not asked for
1695
+ launch = sent;
1696
+ launch.searchParams.delete('chrome');
1697
+ }
1698
+ } catch (_) {
1699
+ return null;
1700
+ }
1701
+ const cwd = launch.searchParams.get('cwd') || info.cwd;
1702
+ if (!cwd) return null;
1703
+ const session = launch.searchParams.get('session') || '';
1704
+ const place = placeOf(cwd);
1705
+ const urls = agentUrls(launch.pathname, cwd, session);
1706
+ return {
1707
+ launchUrl: `${launch.pathname}${launch.search}`,
1708
+ session: Object.assign({
1709
+ key: sessionKey(H.pluginTail(launch.pathname), cwd, session),
1710
+ kind: 'agent',
1711
+ label: tool.label || 'Agent',
1712
+ iconSrc: tool.iconSrc || '',
1713
+ start: Date.now(),
1714
+ url: urls.url,
1715
+ fullUrl: place.placeKind === 'app' ? '' : urls.fullUrl,
1716
+ appHref: info.type === 'create_app' ? `/p/${encodeURIComponent(info.name || place.folder)}/dev`
1717
+ : (place.placeKind === 'app' ? `/p/${encodeURIComponent(place.folder)}` : ''),
1718
+ }, place, info.type === 'create_app' && info.name ? { placeName: info.name } : {}),
1719
+ };
1720
+ }
1721
+
1722
+ function deliver(info) {
1723
+ if (!info || !info.url) return false;
1724
+ if (!document.querySelector('.agent-bar__top')) return false;
1725
+ const started = fromSend(info);
1726
+ if (!started) return false;
1727
+ if (info.prompt) {
1728
+ asked[started.session.key] = info.prompt;
1729
+ write(STORE_ASKED, asked);
1730
+ }
1731
+ open(started.session, { launchUrl: started.launchUrl });
1732
+ if (info.type === 'create_app') showNewApp(info.name);
1733
+ [1500, 4000].forEach((delay) => window.setTimeout(refresh, delay));
1734
+ return true;
1735
+ }
1736
+
1737
+ // ---- Create app: the new app appears in My Apps ----------------------------
1738
+ // The list is drawn by the server, so the page is fetched again and the new
1739
+ // app's row is taken from it and put at the top, until the next page load
1740
+ // orders it like the rest.
1741
+ function showNewApp(name) {
1742
+ if (!name || !document.body.classList.contains('is-home')) return;
1743
+ const first = document.querySelector('.home-app-line');
1744
+ if (!first || !first.parentNode) return;
1745
+ const byPath = (scope) => Array.from(scope.querySelectorAll('.home-app-line')).find((row) => row.dataset.path === name || row.dataset.uri === name);
1746
+ if (byPath(document)) return;
1747
+ fetch(window.location.href, { headers: { Accept: 'text/html' } })
1748
+ .then((response) => (response.ok ? response.text() : ''))
1749
+ .then((html) => {
1750
+ if (!html || byPath(document)) return;
1751
+ const fetched = byPath(new DOMParser().parseFromString(html, 'text/html'));
1752
+ if (!fetched) return;
1753
+ const row = document.importNode(fetched, true);
1754
+ // its numbers are from the fetched page: keep them from clashing here
1755
+ let highest = 0;
1756
+ document.querySelectorAll('.line[data-index]').forEach((line) => {
1757
+ const index = parseInt(line.dataset.index, 10);
1758
+ if (Number.isFinite(index) && index > highest) highest = index;
1759
+ });
1760
+ row.dataset.index = String(highest + 1);
1761
+ row.querySelectorAll('[id]').forEach((node) => {
1762
+ if (!document.getElementById(node.id)) return;
1763
+ const previous = node.id;
1764
+ node.id = `${previous}-new`;
1765
+ row.querySelectorAll(`[aria-controls="${previous}"], [aria-labelledby="${previous}"], [for="${previous}"]`).forEach((ref) => {
1766
+ ['aria-controls', 'aria-labelledby', 'for'].forEach((attribute) => {
1767
+ if (ref.getAttribute(attribute) === previous) ref.setAttribute(attribute, node.id);
1768
+ });
1769
+ });
1770
+ });
1771
+ row.classList.remove('hidden', 'selected');
1772
+ row.classList.add('agent-bar-new-app');
1773
+ first.parentNode.insertBefore(row, first);
1774
+ // the page's search keeps its own list of rows
1775
+ try {
1776
+ // eslint-disable-next-line no-undef
1777
+ if (typeof list !== 'undefined' && Array.isArray(list)) {
1778
+ // eslint-disable-next-line no-undef
1779
+ list.push({ index: highest + 1, name: row.dataset.name, description: row.dataset.description, uri: row.dataset.uri });
1780
+ }
1781
+ } catch (_) {}
1782
+ const scroller = row.closest('.container');
1783
+ if (scroller) scroller.scrollTop = 0;
1784
+ })
1785
+ .catch(() => {});
1786
+ }
1787
+
1788
+ // ---- the windows that were open on the page before this one -----------------
1789
+ // Each comes back only while its session is still running, so a page change
1790
+ // never starts one. In the order they were last in front, so the same one is on top.
1791
+ // Only once it is known what is running: a hidden page reads nothing and a failed
1792
+ // read says nothing, and neither is a reason to take a tab away (see `look`).
1793
+ let restored = false;
1794
+ function restore() {
1795
+ let wanted = tabs.filter((tab) => tab.open).sort((a, b) => (a.z || 0) - (b.z || 0));
1796
+ // a narrow screen shows one window at a time: the one that was in front
1797
+ if (narrow() && wanted.length > 1) {
1798
+ wanted.slice(0, -1).forEach((tab) => { tab.open = false; });
1799
+ wanted = wanted.slice(-1);
1800
+ }
1801
+ let waiting = false;
1802
+ wanted.forEach((tab) => {
1803
+ const running = sessions.find((session) => session.key === tab.key);
1804
+ if (running) {
1805
+ const session = Object.assign({}, tab, running, { startedHere: tab.startedHere || 0 });
1806
+ if (session.kind === 'shell' && !session.url) {
1807
+ shellUrl(session).then((url) => {
1808
+ if (url) open(Object.assign({}, session, { url }), { still: true, keep: true });
1809
+ else removeTab(tab.key);
1810
+ });
1811
+ return;
1812
+ }
1813
+ open(session, { still: true, keep: true });
1814
+ return;
1815
+ }
1816
+ // started a moment ago and not listed yet: wait for it, never start it again
1817
+ if (inGrace(tab)) {
1818
+ waiting = true;
1819
+ return;
1820
+ }
1821
+ removeTab(tab.key);
1822
+ });
1823
+ if (waiting) {
1824
+ window.setTimeout(() => refresh().then((read) => {
1825
+ if (read) restore();
1826
+ else restored = false; // not known right now: `look` takes it from here
1827
+ }), 1500);
1828
+ }
1829
+ syncSide(true);
1830
+ fitRow();
1831
+ tile(true);
1832
+ renderTabs();
1833
+ }
1834
+
1835
+ // ---- start ----------------------------------------------------------------
1836
+ function start() {
1837
+ bar = window.PinokioAgentBar;
1838
+ // App pages too
1839
+ APP = Boolean(document.body) && document.body.classList.contains('app-page');
1840
+ const usable = bar && bar.helpers && document.body
1841
+ && (APP || (document.body.classList.contains('main-sidebar-page') && document.querySelector('.agent-bar__top')));
1842
+ if (!usable) {
1843
+ release();
1844
+ return;
1845
+ }
1846
+ H = bar.helpers;
1847
+ if (APP) offerDock();
1848
+ else bar.deliver = deliver;
1849
+ document.addEventListener('pointerdown', (event) => {
1850
+ wins.forEach((win) => {
1851
+ const part = win.part;
1852
+ if (!part.moreMenu.hidden && !part.moreMenu.contains(event.target) && !part.more.contains(event.target)) setMore(win, false);
1853
+ });
1854
+ });
1855
+ document.addEventListener('pointerdown', (event) => {
1856
+ if (!menuOpen) return;
1857
+ if ((chip && chip.contains(event.target)) || (menu && menu.contains(event.target))) return;
1858
+ setMenu(false);
1859
+ });
1860
+ document.addEventListener('keydown', (event) => {
1861
+ if (event.key === 'Escape') setMenu(false);
1862
+ });
1863
+ window.addEventListener('blur', () => {
1864
+ if (document.activeElement && document.activeElement.tagName === 'IFRAME') setMenu(false);
1865
+ // A press inside a window's page never reaches this document. What does
1866
+ // happen is that this window loses focus and that frame becomes the active
1867
+ // element: its window comes to the front.
1868
+ window.setTimeout(() => {
1869
+ const active = document.activeElement;
1870
+ wins.forEach((win) => {
1871
+ if (active === win.part.frame && isOpen(win.key) && frontKey !== win.key) focus(win.key);
1872
+ });
1873
+ }, 0);
1874
+ });
1875
+ // the screen changed size: the row is laid out again (fewer fit on a narrower screen)
1876
+ window.addEventListener('resize', () => {
1877
+ // narrowed to a phone's width: only the one in front stays up
1878
+ if (narrow()) openTabs().forEach((tab) => { if (tab.key !== frontKey) minimise(tab.key); });
1879
+ fitRow();
1880
+ tile();
1881
+ });
1882
+ // Reads what is running. Until that has worked once (with the agents known),
1883
+ // the tabs are left exactly as they were saved; then the windows come back.
1884
+ const look = () => {
1885
+ if (restored) return refresh();
1886
+ return (toolsReady ? Promise.resolve() : loadTools()).then(refresh).then((read) => {
1887
+ if (!read || !toolsReady || restored) return;
1888
+ restored = true;
1889
+ restore();
1890
+ });
1891
+ };
1892
+ look();
1893
+ // Every 5 seconds while something of yours depends on the list (a tab, the
1894
+ // open list); every 30 otherwise.
1895
+ window.setInterval(() => {
1896
+ const idle = !tabs.length && !menuOpen;
1897
+ if (idle && Date.now() - lastRead < IDLE_REFRESH_MS) return;
1898
+ look();
1899
+ }, REFRESH_MS);
1900
+ document.addEventListener('visibilitychange', () => {
1901
+ if (!document.hidden) look();
1902
+ });
1903
+ }
1904
+
1905
+ const begin = () => {
1906
+ const api = window.PinokioAgentBar;
1907
+ if (api && api.ready && typeof api.ready.then === 'function') api.ready.then(start);
1908
+ else release();
1909
+ };
1910
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', begin);
1911
+ else begin();
1912
+ })(window, document);