pinokiod 8.3.6 → 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.
- package/kernel/agent_instructions.js +56 -0
- package/kernel/app_log_sessions.js +1 -1
- package/kernel/bin/git.js +1 -1
- package/kernel/bin/node.js +2 -2
- package/kernel/environment.js +6 -98
- package/kernel/managed_skills.js +2 -1
- package/package.json +1 -1
- package/prototype/system/SKILL_PINOKIO.md +5 -2
- package/server/index.js +7 -0
- package/server/lib/brain.js +279 -0
- package/server/public/agent-bar-app.css +359 -0
- package/server/public/agent-bar-app.js +821 -0
- package/server/public/agent-bar-attach.css +142 -0
- package/server/public/agent-bar-attach.js +299 -0
- package/server/public/agent-bar-panel.css +788 -0
- package/server/public/agent-bar-panel.js +1912 -0
- package/server/public/agent-bar-shell.css +128 -0
- package/server/public/agent-bar-shell.js +251 -0
- package/server/public/agent-bar.css +972 -0
- package/server/public/agent-bar.js +1513 -0
- package/server/public/common.js +65 -0
- package/server/public/layout.js +13 -1
- package/server/routes/apps.js +6 -0
- package/server/socket.js +6 -2
- package/server/views/app.ejs +13 -0
- package/server/views/partials/main_sidebar.ejs +7 -0
- package/system/plugin/opencode/pinokio.js +8 -2
- package/system/plugin/opencode-auto/pinokio.js +4 -1
- package/test/agent-instructions.test.js +69 -0
- package/test/app-log-sessions.test.js +29 -0
- package/test/brain.test.js +257 -0
- package/test/managed-skills.test.js +6 -1
- package/test/node-bin.test.js +4 -4
|
@@ -0,0 +1,1513 @@
|
|
|
1
|
+
// Agent bar: the prompt input in the top navbar.
|
|
2
|
+
//
|
|
3
|
+
// On every page that has the top navbar except app pages. Four items:
|
|
4
|
+
// Ask, Create app, Create plugin, Download.
|
|
5
|
+
// It is an additional entry point. The universal launcher dialog and everything
|
|
6
|
+
// that opens it are untouched, and apart from Ask the bar sends exactly what the
|
|
7
|
+
// dialog sends:
|
|
8
|
+
// Ask POST /brain/ask { prompt, tool, uploadToken }
|
|
9
|
+
// Create plugin POST /launcher/prepare { type: 'create_plugin', name, prompt, tool, uploadToken }
|
|
10
|
+
// Create app POST /launcher/create-app { name, prompt, tool, uploadToken }
|
|
11
|
+
// Download POST /launcher/download/prepare { intent, ref, name }
|
|
12
|
+
// -> shell.run clone over the socket
|
|
13
|
+
// -> POST /launcher/download/finalize { intent, ref, name, id }
|
|
14
|
+
// then goes to the returned url.
|
|
15
|
+
//
|
|
16
|
+
// Buttons that open the dialog ([data-universal-launcher-open]) and pre-filled
|
|
17
|
+
// links (?universal&type&prompt&name&tool) are offered to the bar first, through
|
|
18
|
+
// window.PinokioAgentBar.open(defaults) called from common.js. The bar takes them
|
|
19
|
+
// when it is on screen; otherwise the dialog opens as before (phones, pages
|
|
20
|
+
// without the bar). While the bar is on screen the sidebar's "Create" and "Ask"
|
|
21
|
+
// entries are hidden by agent-bar.css.
|
|
22
|
+
// Folder names follow the dialog's rules and use the same availability request
|
|
23
|
+
// (POST /pinokio/install/exists).
|
|
24
|
+
(function (window, document) {
|
|
25
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
// A Pinokio page is either the top window or a pane of the layout shell (the
|
|
28
|
+
// page at "/", which shows every Pinokio page inside an iframe). Pages embedded
|
|
29
|
+
// anywhere else (inside an app page, for instance) do not get the bar.
|
|
30
|
+
function isHostPage() {
|
|
31
|
+
if (window.top === window) return true;
|
|
32
|
+
try {
|
|
33
|
+
return Boolean(window.parent && window.parent !== window && window.parent.PinokioLayout);
|
|
34
|
+
} catch (_) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (!isHostPage()) return;
|
|
39
|
+
// The page may load this file twice (early from the sidebar's markup, and from
|
|
40
|
+
// common.js). The first one wins.
|
|
41
|
+
if (window.PinokioAgentBar) return;
|
|
42
|
+
|
|
43
|
+
// Timing: pages with the main sidebar load this file at the top of the sidebar's
|
|
44
|
+
// markup and call PinokioAgentBar.mount() at its end, so the bar is in place and
|
|
45
|
+
// the sidebar's Create and Ask are already hidden the first time the page is
|
|
46
|
+
// drawn. Until then, on desktop widths, those two entries are kept from being
|
|
47
|
+
// drawn at all (PENDING_CLASS, see agent-bar.css). On any other page the bar
|
|
48
|
+
// mounts when the page has loaded.
|
|
49
|
+
const PENDING_CLASS = 'agent-bar-pending';
|
|
50
|
+
const isDesktopWidth = () => !(window.matchMedia && window.matchMedia('(max-width: 768px)').matches);
|
|
51
|
+
if (isDesktopWidth()) document.documentElement.classList.add(PENDING_CLASS);
|
|
52
|
+
|
|
53
|
+
// Same key the dialog uses, so the remembered agent is shared.
|
|
54
|
+
const TOOL_PREFERENCE_KEY = 'pinokio.universalLauncher.tool';
|
|
55
|
+
const NAME_VALIDATION_DEBOUNCE_MS = 260;
|
|
56
|
+
const LINE_HEIGHT = 20;
|
|
57
|
+
const MAX_LINES = 8;
|
|
58
|
+
const PLUGIN_PROMPT_SEED = 'A Pinokio plugin for: ';
|
|
59
|
+
const DOWNLOAD_SHELL_CLIENT = { cols: 120, rows: 32 };
|
|
60
|
+
const NON_INTERACTIVE_GIT_ENV = {
|
|
61
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
62
|
+
GIT_ASKPASS: '',
|
|
63
|
+
SSH_ASKPASS: '',
|
|
64
|
+
GCM_INTERACTIVE: 'never',
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const ITEMS = {
|
|
68
|
+
ask: {
|
|
69
|
+
label: 'Ask',
|
|
70
|
+
placeholder: 'Ask Pinokio anything…',
|
|
71
|
+
send: 'Ask',
|
|
72
|
+
},
|
|
73
|
+
create_app: {
|
|
74
|
+
label: 'Create app',
|
|
75
|
+
placeholder: 'What should this app do?',
|
|
76
|
+
send: 'Create',
|
|
77
|
+
dir: 'api',
|
|
78
|
+
},
|
|
79
|
+
create_plugin: {
|
|
80
|
+
label: 'Create plugin',
|
|
81
|
+
placeholder: 'What should this plugin do?',
|
|
82
|
+
send: 'Create',
|
|
83
|
+
dir: 'plugin',
|
|
84
|
+
},
|
|
85
|
+
download: {
|
|
86
|
+
label: 'Download',
|
|
87
|
+
placeholder: 'https://github.com/owner/repo',
|
|
88
|
+
send: 'Import',
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
// Download destinations, keyed by the intent the server expects.
|
|
92
|
+
const DOWNLOAD_TARGETS = {
|
|
93
|
+
create_app: {
|
|
94
|
+
label: 'App',
|
|
95
|
+
dir: 'api',
|
|
96
|
+
noun: 'app',
|
|
97
|
+
},
|
|
98
|
+
create_plugin: {
|
|
99
|
+
label: 'Plugin',
|
|
100
|
+
dir: 'plugin',
|
|
101
|
+
noun: 'plugin',
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// What common.js talks to. `ready` resolves once the bar has mounted (or
|
|
106
|
+
// decided not to); `open` returns true when the bar took the request.
|
|
107
|
+
let resolveReady = () => {};
|
|
108
|
+
const api = {
|
|
109
|
+
ready: new Promise((resolve) => { resolveReady = resolve; }),
|
|
110
|
+
open: () => false,
|
|
111
|
+
// one place that leaves the page, so it can be observed
|
|
112
|
+
navigate: (url) => { window.location.href = url; },
|
|
113
|
+
// A send that started an agent (Ask, Create app, Create plugin) is offered
|
|
114
|
+
// here first. Whatever shows sessions in place (the panel, see
|
|
115
|
+
// agent-bar-panel.js) replaces this and returns true when it took the
|
|
116
|
+
// session; otherwise the bar leaves the page for it, as the dialog does.
|
|
117
|
+
deliver: () => false,
|
|
118
|
+
// closes the bar's own menus (set once the bar is in the page)
|
|
119
|
+
closeMenus: () => {},
|
|
120
|
+
// Files attached to the next send (see agent-bar-attach.js, which replaces
|
|
121
|
+
// these): `token` uploads them and resolves to the upload token ('' when
|
|
122
|
+
// there are none); `paths` (app pages) uploads them into the app's folder
|
|
123
|
+
// and resolves to where each one is; `clear` drops them once a send has
|
|
124
|
+
// been handed over.
|
|
125
|
+
attachments: { token: async () => '', paths: async () => [], clear: () => {} },
|
|
126
|
+
// shared with agent-bar-app.js (function declarations below are hoisted)
|
|
127
|
+
helpers: {
|
|
128
|
+
el, faIcon, menuRow, toolIcon, mapPluginMenuToTools, getStoredTool, setStoredTool,
|
|
129
|
+
newSession, pluginTail, timeAgo, readRunId,
|
|
130
|
+
agentPicker, agentMenuRows, fitTextarea, raiseTopBar, bindBar,
|
|
131
|
+
},
|
|
132
|
+
// put the bar in the page now, if the top bar is already there
|
|
133
|
+
mount: () => mount(),
|
|
134
|
+
};
|
|
135
|
+
window.PinokioAgentBar = api;
|
|
136
|
+
|
|
137
|
+
function el(tag, className, text) {
|
|
138
|
+
const node = document.createElement(tag);
|
|
139
|
+
if (className) node.className = className;
|
|
140
|
+
if (text != null) node.textContent = text;
|
|
141
|
+
return node;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ---- the helpers below are the same rules as universal-launcher.js ----
|
|
145
|
+
|
|
146
|
+
function mapPluginMenuToTools(menu) {
|
|
147
|
+
if (!Array.isArray(menu)) return [];
|
|
148
|
+
return menu.map((plugin) => {
|
|
149
|
+
if (!plugin || typeof plugin !== 'object') return null;
|
|
150
|
+
const href = typeof plugin.href === 'string' ? plugin.href.trim() : '';
|
|
151
|
+
if (!href) return null;
|
|
152
|
+
|
|
153
|
+
const normalized = href.replace(/^\/run/, '').replace(/^\/+/, '');
|
|
154
|
+
const parts = normalized.split('/').filter(Boolean);
|
|
155
|
+
let value = '';
|
|
156
|
+
if (parts[0] === 'plugin' && parts.length >= 3) {
|
|
157
|
+
value = parts.slice(1, -1).join('/');
|
|
158
|
+
} else {
|
|
159
|
+
value = normalized;
|
|
160
|
+
}
|
|
161
|
+
if (value.endsWith('/pinokio.js')) {
|
|
162
|
+
value = value.replace(/\/pinokio\.js$/i, '');
|
|
163
|
+
}
|
|
164
|
+
if (!value) return null;
|
|
165
|
+
|
|
166
|
+
const explicitCategory = typeof plugin.category === 'string' ? plugin.category.trim().toLowerCase() : '';
|
|
167
|
+
const launchType = typeof plugin.launch_type === 'string' ? plugin.launch_type.trim().toLowerCase() : '';
|
|
168
|
+
const runs = Array.isArray(plugin.run) ? plugin.run : [];
|
|
169
|
+
const hasExec = runs.some((step) => step && step.method === 'exec');
|
|
170
|
+
let category = 'CLI';
|
|
171
|
+
if (explicitCategory === 'ide' || launchType === 'desktop' || hasExec) {
|
|
172
|
+
category = 'IDE';
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
value,
|
|
176
|
+
label: plugin.title || plugin.text || plugin.name || value,
|
|
177
|
+
iconSrc: plugin.image || null,
|
|
178
|
+
category,
|
|
179
|
+
isDefault: plugin.default === true,
|
|
180
|
+
};
|
|
181
|
+
}).filter(Boolean);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function faIcon(className) {
|
|
185
|
+
const node = el('i', className);
|
|
186
|
+
node.setAttribute('aria-hidden', 'true');
|
|
187
|
+
return node;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// One row of a menu: icon, label, optional note at the right, optional check.
|
|
191
|
+
function menuRow(iconNode, label, note, checked, onClick) {
|
|
192
|
+
const row = el('button', 'agent-bar__row');
|
|
193
|
+
row.type = 'button';
|
|
194
|
+
row.append(iconNode, el('span', 'agent-bar__row-label', label));
|
|
195
|
+
if (note) row.appendChild(el('span', 'agent-bar__row-note', note));
|
|
196
|
+
if (checked) row.appendChild(faIcon('fa-solid fa-check agent-bar__row-check'));
|
|
197
|
+
row.addEventListener('click', onClick);
|
|
198
|
+
return row;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function toolIcon(tool) {
|
|
202
|
+
if (!tool || !tool.iconSrc) return faIcon(`${(tool && tool.iconClass) || 'fa-solid fa-robot'} agent-bar__row-icon`);
|
|
203
|
+
const img = el('img', 'agent-bar__row-img');
|
|
204
|
+
img.alt = '';
|
|
205
|
+
img.src = tool.iconSrc;
|
|
206
|
+
img.addEventListener('error', () => { img.style.visibility = 'hidden'; });
|
|
207
|
+
return img;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ---- parts both bars are built from: the home bar below and the app-page bar
|
|
211
|
+
// (agent-bar-app.js). Each bar keeps its own state and its own flow. ----
|
|
212
|
+
|
|
213
|
+
// The small agent button in the field: the chosen agent's icon, or a robot when
|
|
214
|
+
// none is chosen. `show(tool, busy, open)` brings it up to date.
|
|
215
|
+
function agentPicker() {
|
|
216
|
+
const button = el('button', 'agent-bar__agent');
|
|
217
|
+
button.type = 'button';
|
|
218
|
+
button.setAttribute('aria-haspopup', 'menu');
|
|
219
|
+
const img = el('img', 'agent-bar__agent-img');
|
|
220
|
+
img.alt = '';
|
|
221
|
+
img.hidden = true;
|
|
222
|
+
const none = faIcon('fa-solid fa-robot agent-bar__agent-none');
|
|
223
|
+
img.addEventListener('error', () => { img.hidden = true; none.hidden = false; });
|
|
224
|
+
button.append(img, none, faIcon('fa-solid fa-chevron-down agent-bar__caret'));
|
|
225
|
+
const show = (tool, busy, open) => {
|
|
226
|
+
button.disabled = busy;
|
|
227
|
+
button.classList.toggle('is-open', open);
|
|
228
|
+
button.setAttribute('aria-expanded', String(open));
|
|
229
|
+
button.title = tool ? `Runs with ${tool.label}` : 'Choose an agent';
|
|
230
|
+
button.setAttribute('aria-label', button.title);
|
|
231
|
+
const hasIcon = Boolean(tool && tool.iconSrc);
|
|
232
|
+
if (hasIcon && img.getAttribute('src') !== tool.iconSrc) img.src = tool.iconSrc;
|
|
233
|
+
img.hidden = !hasIcon;
|
|
234
|
+
none.hidden = hasIcon;
|
|
235
|
+
};
|
|
236
|
+
return { button, show };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// The agent menu's rows: agents by name, then desktop apps. `pick(tool)` is
|
|
240
|
+
// called with the one that was chosen.
|
|
241
|
+
function agentMenuRows(menu, tools, loaded, current, pick) {
|
|
242
|
+
const byLabel = (a, b) => String(a.label).toLowerCase().localeCompare(String(b.label).toLowerCase());
|
|
243
|
+
const addTool = (tool) => menu.appendChild(menuRow(toolIcon(tool), tool.label, '', tool.value === current, () => pick(tool)));
|
|
244
|
+
menu.appendChild(el('div', 'agent-bar__menu-title', 'Runs with'));
|
|
245
|
+
if (!loaded) menu.appendChild(el('div', 'agent-bar__menu-empty', 'Loading…'));
|
|
246
|
+
else if (!tools.length) menu.appendChild(el('div', 'agent-bar__menu-empty', 'No agents available'));
|
|
247
|
+
tools.filter((tool) => tool.category !== 'IDE').sort(byLabel).forEach(addTool);
|
|
248
|
+
const desktop = tools.filter((tool) => tool.category === 'IDE').sort(byLabel);
|
|
249
|
+
if (desktop.length) menu.appendChild(el('div', 'agent-bar__menu-title', 'Desktop apps'));
|
|
250
|
+
desktop.forEach(addTool);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The input is one line by default; it grows with the text up to MAX_LINES,
|
|
254
|
+
// then scrolls. The box's height is passed on to the stylesheet.
|
|
255
|
+
function fitTextarea(root, field, top, input) {
|
|
256
|
+
const max = LINE_HEIGHT * MAX_LINES + 2;
|
|
257
|
+
// Whether the text needs more than one line (data-multi; the stylesheet then
|
|
258
|
+
// gives the text the box's full width and moves the controls to its bottom
|
|
259
|
+
// row). It is measured in the one-line layout, so the answer does not depend
|
|
260
|
+
// on the layout it selects.
|
|
261
|
+
root.dataset.multi = 'false';
|
|
262
|
+
input.style.height = 'auto';
|
|
263
|
+
root.dataset.multi = String(Boolean(input.value) && input.scrollHeight > LINE_HEIGHT + 4);
|
|
264
|
+
input.style.height = 'auto';
|
|
265
|
+
const wanted = input.value ? input.scrollHeight : 22;
|
|
266
|
+
input.style.height = `${Math.max(22, Math.min(wanted, max))}px`;
|
|
267
|
+
input.style.overflowY = wanted > max ? 'auto' : 'hidden';
|
|
268
|
+
root.style.setProperty('--agent-bar-field-h', `${field.offsetHeight}px`);
|
|
269
|
+
root.style.setProperty('--agent-bar-top-h', `${top.offsetHeight + 2}px`);
|
|
270
|
+
root.dataset.tall = String(field.offsetHeight > 32);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// The menus, the folder row and messages hang below the top bar, over the
|
|
274
|
+
// page. Some pages stack their content above the top bar (the terminal page
|
|
275
|
+
// gives its terminal a z-index of 10000), which would cover them. So while
|
|
276
|
+
// anything of the bar's reaches below the top bar, the top bar is raised.
|
|
277
|
+
function raiseTopBar(h1, reaches) {
|
|
278
|
+
const header = h1.closest('header');
|
|
279
|
+
if (header) header.classList.toggle('agent-bar-raised', reaches);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// The keyboard and click-away behaviour of a bar. `bar` is the bar's own
|
|
283
|
+
// { isBusy, hasMenu, closeMenu, leave, fit }.
|
|
284
|
+
function bindBar(root, inner, bar) {
|
|
285
|
+
// Keys typed in the bar must not reach page shortcuts.
|
|
286
|
+
['keydown', 'keypress', 'keyup'].forEach((type) => {
|
|
287
|
+
root.addEventListener(type, (event) => { event.stopPropagation(); });
|
|
288
|
+
});
|
|
289
|
+
// Escape closes the open menu first, then leaves the bar.
|
|
290
|
+
root.addEventListener('keydown', (event) => {
|
|
291
|
+
if (event.key !== 'Escape' || bar.isBusy()) return;
|
|
292
|
+
if (bar.hasMenu()) {
|
|
293
|
+
bar.closeMenu();
|
|
294
|
+
} else {
|
|
295
|
+
bar.leave();
|
|
296
|
+
if (document.activeElement && root.contains(document.activeElement)) document.activeElement.blur();
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
// "Outside" means outside the box and its menus. The bar's own box is wider
|
|
300
|
+
// than that (it fills the top bar's flexible middle and centers the field in
|
|
301
|
+
// it), so the empty space left and right of the field is outside too.
|
|
302
|
+
document.addEventListener('pointerdown', (event) => {
|
|
303
|
+
if (!inner.contains(event.target)) bar.leave();
|
|
304
|
+
}, true);
|
|
305
|
+
// A click inside a frame on this page (an app's own page, a side panel) never
|
|
306
|
+
// reaches this document, so the check above does not see it. What does happen
|
|
307
|
+
// is that this window loses focus and the frame becomes the active element.
|
|
308
|
+
// Any other loss of focus (another application, another pane of the layout)
|
|
309
|
+
// leaves the bar as it is.
|
|
310
|
+
window.addEventListener('blur', () => {
|
|
311
|
+
window.setTimeout(() => {
|
|
312
|
+
const active = document.activeElement;
|
|
313
|
+
if (active && active.tagName === 'IFRAME') bar.leave();
|
|
314
|
+
}, 0);
|
|
315
|
+
});
|
|
316
|
+
window.addEventListener('resize', bar.fit);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ---- used by the app-page bar and by the dock ----
|
|
320
|
+
function newSession() {
|
|
321
|
+
if (window.crypto && typeof window.crypto.randomUUID === 'function') return window.crypto.randomUUID();
|
|
322
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
323
|
+
}
|
|
324
|
+
// '/pinokio/run/plugin/claude/pinokio.js' and '/run/plugin/x/pinokio.js' both
|
|
325
|
+
// end the same way as the script's path on disk: '/plugin/<name>/pinokio.js'.
|
|
326
|
+
function pluginTail(href) {
|
|
327
|
+
return String(href || '').split('?')[0].replace(/^\/pinokio\/run/, '').replace(/^\/run/, '');
|
|
328
|
+
}
|
|
329
|
+
function timeAgo(start) {
|
|
330
|
+
const started = Number(start);
|
|
331
|
+
if (!Number.isFinite(started) || started <= 0) return '';
|
|
332
|
+
const minutes = Math.max(0, Math.round((Date.now() - started) / 60000));
|
|
333
|
+
if (minutes < 1) return 'just now';
|
|
334
|
+
if (minutes < 60) return `${minutes}m ago`;
|
|
335
|
+
const hours = Math.round(minutes / 60);
|
|
336
|
+
return hours < 24 ? `${hours}h ago` : `${Math.round(hours / 24)}d ago`;
|
|
337
|
+
}
|
|
338
|
+
// A running agent as the server lists it: `<script>?cwd=<folder>[&session=<id>]`.
|
|
339
|
+
// The server builds that id from the folder's path as it is, not encoded, so it
|
|
340
|
+
// is read as plain text: a "+", "&" or "%" in a folder's name is part of the name.
|
|
341
|
+
function readRunId(group) {
|
|
342
|
+
const at = group.indexOf('?');
|
|
343
|
+
const query = group.slice(at + 1);
|
|
344
|
+
const cut = query.lastIndexOf('&session=');
|
|
345
|
+
return {
|
|
346
|
+
script: group.slice(0, at).replace(/\\/g, '/'),
|
|
347
|
+
cwd: query.startsWith('cwd=') ? query.slice(4, cut < 0 ? undefined : cut) : '',
|
|
348
|
+
session: cut < 0 ? '' : query.slice(cut + '&session='.length),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function getStoredTool() {
|
|
353
|
+
try {
|
|
354
|
+
const value = window.localStorage.getItem(TOOL_PREFERENCE_KEY);
|
|
355
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
356
|
+
} catch (_) {
|
|
357
|
+
return '';
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function setStoredTool(value) {
|
|
362
|
+
try {
|
|
363
|
+
if (value) window.localStorage.setItem(TOOL_PREFERENCE_KEY, value);
|
|
364
|
+
else window.localStorage.removeItem(TOOL_PREFERENCE_KEY);
|
|
365
|
+
} catch (_) {}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function generateNameSuggestion(prompt) {
|
|
369
|
+
if (!prompt) return '';
|
|
370
|
+
return prompt
|
|
371
|
+
.toLowerCase()
|
|
372
|
+
.replace(/[^a-z0-9\-\s_]/g, '')
|
|
373
|
+
.replace(/[\s_]+/g, '-')
|
|
374
|
+
.replace(/^-+|-+$/g, '')
|
|
375
|
+
.slice(0, 50);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function isValidWorkspaceName(value) {
|
|
379
|
+
if (typeof value !== 'string') return false;
|
|
380
|
+
const trimmed = value.trim();
|
|
381
|
+
if (!trimmed || trimmed.length > 80) return false;
|
|
382
|
+
if (trimmed === '.' || trimmed === '..') return false;
|
|
383
|
+
if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('\0')) return false;
|
|
384
|
+
return /^[A-Za-z0-9._-]+$/.test(trimmed);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function extractUrlLikeNameSuggestion(value) {
|
|
388
|
+
const rawValue = typeof value === 'string' ? value.trim() : '';
|
|
389
|
+
if (!rawValue) return '';
|
|
390
|
+
|
|
391
|
+
const scpMatch = rawValue.match(/^(?:[^@\s]+@)?[^:\s/]+:(.+)$/);
|
|
392
|
+
if (scpMatch && scpMatch[1]) {
|
|
393
|
+
const scpSegments = scpMatch[1].split('/').filter(Boolean);
|
|
394
|
+
const scpCandidate = scpSegments.length > 0 ? scpSegments[scpSegments.length - 1] : '';
|
|
395
|
+
return generateNameSuggestion(String(scpCandidate).replace(/\.git$/i, ''));
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
let normalizedUrl = rawValue;
|
|
399
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(normalizedUrl)) {
|
|
400
|
+
if (/^[\w.-]+\.[A-Za-z]{2,}(?:[/:?#]|$)/.test(normalizedUrl)) {
|
|
401
|
+
normalizedUrl = `https://${normalizedUrl}`;
|
|
402
|
+
} else {
|
|
403
|
+
return '';
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
try {
|
|
408
|
+
const url = new URL(normalizedUrl);
|
|
409
|
+
const segments = url.pathname.split('/').filter(Boolean);
|
|
410
|
+
const genericTrailingSegments = new Set(['index', 'docs', 'documentation', 'readme']);
|
|
411
|
+
let candidate = '';
|
|
412
|
+
if (segments.length > 0) {
|
|
413
|
+
candidate = segments[segments.length - 1];
|
|
414
|
+
const normalizedCandidate = String(candidate).toLowerCase().replace(/\.(html?|md|txt)$/i, '');
|
|
415
|
+
if (segments.length > 1 && genericTrailingSegments.has(normalizedCandidate)) {
|
|
416
|
+
candidate = segments[segments.length - 2];
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (!candidate) {
|
|
420
|
+
candidate = url.hostname.split('.').filter(Boolean)[0] || '';
|
|
421
|
+
}
|
|
422
|
+
candidate = decodeURIComponent(String(candidate || ''))
|
|
423
|
+
.replace(/\.git$/i, '')
|
|
424
|
+
.replace(/\.(html?|md|txt)$/i, '');
|
|
425
|
+
return generateNameSuggestion(candidate);
|
|
426
|
+
} catch (_) {
|
|
427
|
+
return '';
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function validateDownloadUrl(value) {
|
|
432
|
+
const rawValue = typeof value === 'string' ? value.trim() : '';
|
|
433
|
+
if (!rawValue) return 'Git URL is required.';
|
|
434
|
+
try {
|
|
435
|
+
const normalized = /^[a-z][a-z0-9+.-]*:\/\//i.test(rawValue) ? rawValue : `https://${rawValue}`;
|
|
436
|
+
const parsed = new URL(normalized);
|
|
437
|
+
if (!parsed.hostname) return 'Enter a valid Git URL.';
|
|
438
|
+
return '';
|
|
439
|
+
} catch (_) {
|
|
440
|
+
return 'Enter a valid Git URL.';
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function folderExists(relativePath, folderName) {
|
|
445
|
+
const response = await fetch('/pinokio/install/exists', {
|
|
446
|
+
method: 'POST',
|
|
447
|
+
headers: { 'Content-Type': 'application/json' },
|
|
448
|
+
body: JSON.stringify({ relativePath, folderName }),
|
|
449
|
+
});
|
|
450
|
+
const payload = await response.json().catch(() => null);
|
|
451
|
+
if (!response.ok || !payload || typeof payload.exists !== 'boolean') {
|
|
452
|
+
throw new Error(payload && payload.error ? payload.error : 'Failed to check name availability.');
|
|
453
|
+
}
|
|
454
|
+
return payload.exists;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function suggestAvailableFolderName(relativePath, baseName) {
|
|
458
|
+
const normalizedBase = generateNameSuggestion(baseName);
|
|
459
|
+
if (!normalizedBase) return '';
|
|
460
|
+
let attempt = 0;
|
|
461
|
+
while (attempt < 100) {
|
|
462
|
+
const suffix = attempt === 0 ? '' : `-${attempt + 1}`;
|
|
463
|
+
const maxBaseLength = Math.max(1, 80 - suffix.length);
|
|
464
|
+
const candidate = `${normalizedBase.slice(0, maxBaseLength)}${suffix}`;
|
|
465
|
+
// eslint-disable-next-line no-await-in-loop
|
|
466
|
+
const exists = await folderExists(relativePath, candidate);
|
|
467
|
+
if (!exists) return candidate;
|
|
468
|
+
attempt += 1;
|
|
469
|
+
}
|
|
470
|
+
return normalizedBase;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Socket.js declares `class Socket` at the top level. That makes `Socket` a
|
|
474
|
+
// global name, but not a property of window, so both are looked at (as the
|
|
475
|
+
// dialog and Pinokio's own common.js do).
|
|
476
|
+
/* global Socket */
|
|
477
|
+
function socketClass() {
|
|
478
|
+
if (typeof window.Socket === 'function') return window.Socket;
|
|
479
|
+
return typeof Socket === 'function' ? Socket : null;
|
|
480
|
+
}
|
|
481
|
+
function ensureSocketReady() {
|
|
482
|
+
if (socketClass()) {
|
|
483
|
+
return Promise.resolve(socketClass());
|
|
484
|
+
}
|
|
485
|
+
return new Promise((resolve, reject) => {
|
|
486
|
+
const script = document.createElement('script');
|
|
487
|
+
script.src = '/Socket.js';
|
|
488
|
+
script.async = true;
|
|
489
|
+
script.onload = () => {
|
|
490
|
+
if (socketClass()) resolve(socketClass());
|
|
491
|
+
else reject(new Error('Socket runtime failed to load.'));
|
|
492
|
+
};
|
|
493
|
+
script.onerror = () => reject(new Error('Socket runtime failed to load.'));
|
|
494
|
+
(document.head || document.documentElement).appendChild(script);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async function postJson(url, body) {
|
|
499
|
+
const response = await fetch(url, {
|
|
500
|
+
method: 'POST',
|
|
501
|
+
headers: { 'Content-Type': 'application/json' },
|
|
502
|
+
body: JSON.stringify(body),
|
|
503
|
+
});
|
|
504
|
+
const payload = await response.json().catch(() => null);
|
|
505
|
+
return { response, payload };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// A folder-name field: required, checked as you type. `getDir` returns the
|
|
509
|
+
// PINOKIO_HOME subfolder it will be created in ('api' or 'plugin').
|
|
510
|
+
function createNameField(options) {
|
|
511
|
+
const state = { status: 'idle', message: '', seq: 0, timer: null, checkedName: '', checkedDir: '', edited: false };
|
|
512
|
+
const root = el('div', 'agent-bar__name');
|
|
513
|
+
const label = el('label', 'agent-bar__name-label', options.label);
|
|
514
|
+
const input = el('input', 'agent-bar__name-input');
|
|
515
|
+
input.type = 'text';
|
|
516
|
+
input.id = options.id;
|
|
517
|
+
input.autocomplete = 'off';
|
|
518
|
+
input.spellcheck = false;
|
|
519
|
+
input.placeholder = options.placeholder;
|
|
520
|
+
label.htmlFor = input.id;
|
|
521
|
+
const status = el('div', 'agent-bar__name-status');
|
|
522
|
+
root.append(label, input, status);
|
|
523
|
+
|
|
524
|
+
function setStatus(next, message) {
|
|
525
|
+
state.status = next || 'idle';
|
|
526
|
+
state.message = typeof message === 'string' ? message : '';
|
|
527
|
+
status.textContent = state.message;
|
|
528
|
+
status.dataset.state = state.status;
|
|
529
|
+
options.onChange();
|
|
530
|
+
}
|
|
531
|
+
function clearTimer() {
|
|
532
|
+
if (!state.timer) return;
|
|
533
|
+
window.clearTimeout(state.timer);
|
|
534
|
+
state.timer = null;
|
|
535
|
+
}
|
|
536
|
+
// Same steps and messages as runNameValidation() in the dialog.
|
|
537
|
+
async function run(runOptions) {
|
|
538
|
+
clearTimer();
|
|
539
|
+
const dir = options.getDir();
|
|
540
|
+
const name = input.value.trim();
|
|
541
|
+
const showEmpty = !runOptions || runOptions.showEmpty !== false;
|
|
542
|
+
if (!name) {
|
|
543
|
+
state.checkedName = '';
|
|
544
|
+
state.checkedDir = '';
|
|
545
|
+
setStatus(showEmpty ? 'error' : 'idle', 'Required');
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
if (!isValidWorkspaceName(name)) {
|
|
549
|
+
state.checkedName = '';
|
|
550
|
+
state.checkedDir = '';
|
|
551
|
+
setStatus('error', 'Letters, numbers, . - _ only');
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
if (state.status === 'success' && state.checkedName === name && state.checkedDir === dir) {
|
|
555
|
+
return true;
|
|
556
|
+
}
|
|
557
|
+
state.checkedName = '';
|
|
558
|
+
state.checkedDir = '';
|
|
559
|
+
const requestId = state.seq + 1;
|
|
560
|
+
state.seq = requestId;
|
|
561
|
+
setStatus('checking', 'Checking…');
|
|
562
|
+
try {
|
|
563
|
+
const exists = await folderExists(dir, name);
|
|
564
|
+
if (state.seq !== requestId) return false;
|
|
565
|
+
if (exists) {
|
|
566
|
+
setStatus('error', 'Already exists');
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
state.checkedName = name;
|
|
570
|
+
state.checkedDir = dir;
|
|
571
|
+
setStatus('success', `Creates ${dir}/${name}`);
|
|
572
|
+
return true;
|
|
573
|
+
} catch (error) {
|
|
574
|
+
if (state.seq !== requestId) return false;
|
|
575
|
+
setStatus('error', error && error.message ? error.message : 'Failed to check name availability.');
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
// Same steps as scheduleNameValidation() in the dialog.
|
|
580
|
+
function schedule() {
|
|
581
|
+
clearTimer();
|
|
582
|
+
const dir = options.getDir();
|
|
583
|
+
const name = input.value.trim();
|
|
584
|
+
if (!name) {
|
|
585
|
+
state.seq += 1;
|
|
586
|
+
state.checkedName = '';
|
|
587
|
+
state.checkedDir = '';
|
|
588
|
+
setStatus('idle', 'Required');
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
if (!isValidWorkspaceName(name)) {
|
|
592
|
+
state.seq += 1;
|
|
593
|
+
state.checkedName = '';
|
|
594
|
+
state.checkedDir = '';
|
|
595
|
+
setStatus('error', 'Letters, numbers, . - _ only');
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (state.status === 'success' && state.checkedName === name && state.checkedDir === dir) {
|
|
599
|
+
options.onChange();
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
state.seq += 1;
|
|
603
|
+
state.checkedName = '';
|
|
604
|
+
state.checkedDir = '';
|
|
605
|
+
state.timer = window.setTimeout(() => {
|
|
606
|
+
state.timer = null;
|
|
607
|
+
run({ showEmpty: false });
|
|
608
|
+
}, NAME_VALIDATION_DEBOUNCE_MS);
|
|
609
|
+
options.onChange();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
input.addEventListener('input', () => {
|
|
613
|
+
state.edited = true;
|
|
614
|
+
schedule();
|
|
615
|
+
if (options.onEdit) options.onEdit();
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
return {
|
|
619
|
+
root,
|
|
620
|
+
input,
|
|
621
|
+
state,
|
|
622
|
+
run,
|
|
623
|
+
schedule,
|
|
624
|
+
isReady() {
|
|
625
|
+
return Boolean(input.value.trim()) && state.status === 'success' && !state.timer;
|
|
626
|
+
},
|
|
627
|
+
setValue(value) {
|
|
628
|
+
input.value = value || '';
|
|
629
|
+
schedule();
|
|
630
|
+
},
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function isAppPage() {
|
|
635
|
+
return Boolean(document.querySelector('header.navheader h1 > .app-header-identity'))
|
|
636
|
+
|| document.body.classList.contains('app-page');
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Done deciding: stop holding the sidebar's entries back and answer anyone
|
|
640
|
+
// waiting to know whether the bar can take a request.
|
|
641
|
+
function settle() {
|
|
642
|
+
document.documentElement.classList.remove(PENDING_CLASS);
|
|
643
|
+
resolveReady();
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// Returns true once the bar is in the page (or the app-page version took over).
|
|
647
|
+
function mount() {
|
|
648
|
+
if (!document.body) return false;
|
|
649
|
+
// App pages have their own version of the bar, which the page loads itself
|
|
650
|
+
// (agent-bar-app.js).
|
|
651
|
+
if (isAppPage()) {
|
|
652
|
+
settle();
|
|
653
|
+
return true;
|
|
654
|
+
}
|
|
655
|
+
const mountedNow = mountBar();
|
|
656
|
+
// The top bar is there and has no place for the bar: Explore, whose address
|
|
657
|
+
// box sits where the bar would. The sidebar's Create and Ask stay hidden
|
|
658
|
+
// there too, so the sidebar is the same on every page (see agent-bar.css).
|
|
659
|
+
const noPlace = !mountedNow && Boolean(document.querySelector('header.navheader h1'));
|
|
660
|
+
document.documentElement.classList.toggle('agent-bar-absent', noPlace);
|
|
661
|
+
// Mounted, or no place for it: either way the answer is final.
|
|
662
|
+
if (mountedNow || noPlace) settle();
|
|
663
|
+
return mountedNow;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// The bar: an input, a small agent icon and a send arrow. Nothing opens when you
|
|
667
|
+
// click into it. The mode chip and the agent icon each open a small menu; the
|
|
668
|
+
// folder name (Create app, Create plugin, Download) is the footer of the same box.
|
|
669
|
+
function mountBar() {
|
|
670
|
+
const h1 = document.querySelector('header.navheader h1');
|
|
671
|
+
if (!h1 || isAppPage()) return false;
|
|
672
|
+
if (h1.querySelector('.agent-bar')) return true;
|
|
673
|
+
// The bar takes the header's flexible middle: the (permanently hidden) url
|
|
674
|
+
// form on home, the spacer everywhere else.
|
|
675
|
+
const slot = h1.querySelector(':scope > form.urlbar') || h1.querySelector(':scope > .flexible');
|
|
676
|
+
if (!slot) return false;
|
|
677
|
+
|
|
678
|
+
const ITEM_ICONS = {
|
|
679
|
+
ask: 'fa-regular fa-comment',
|
|
680
|
+
create_app: 'fa-solid fa-plus',
|
|
681
|
+
create_plugin: 'fa-solid fa-puzzle-piece',
|
|
682
|
+
download: 'fa-solid fa-download',
|
|
683
|
+
};
|
|
684
|
+
const state = {
|
|
685
|
+
item: 'ask',
|
|
686
|
+
menu: null, // null | 'mode' | 'agent'
|
|
687
|
+
engaged: false, // the user is in the bar
|
|
688
|
+
busy: false,
|
|
689
|
+
tools: [],
|
|
690
|
+
tool: '',
|
|
691
|
+
toolsLoaded: false,
|
|
692
|
+
prompt: '', // shared by Ask, Create app and Create plugin
|
|
693
|
+
downloadUrl: '', // Download keeps its own text
|
|
694
|
+
downloadTarget: 'create_app',
|
|
695
|
+
suggestionToken: 0,
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
const root = el('div', 'agent-bar');
|
|
699
|
+
const inner = el('div', 'agent-bar__inner');
|
|
700
|
+
const field = el('div', 'agent-bar__field');
|
|
701
|
+
const top = el('div', 'agent-bar__top');
|
|
702
|
+
|
|
703
|
+
const scope = el('button', 'agent-bar__scope');
|
|
704
|
+
scope.type = 'button';
|
|
705
|
+
scope.setAttribute('aria-haspopup', 'menu');
|
|
706
|
+
const mark = el('span', 'agent-bar__mark');
|
|
707
|
+
mark.setAttribute('aria-hidden', 'true');
|
|
708
|
+
const scopeLabel = el('span', 'agent-bar__scope-label');
|
|
709
|
+
scope.append(mark, scopeLabel, faIcon('fa-solid fa-chevron-down agent-bar__caret'));
|
|
710
|
+
|
|
711
|
+
const input = el('textarea', 'agent-bar__input');
|
|
712
|
+
input.rows = 1;
|
|
713
|
+
input.autocomplete = 'off';
|
|
714
|
+
|
|
715
|
+
const agent = agentPicker();
|
|
716
|
+
const agentButton = agent.button;
|
|
717
|
+
|
|
718
|
+
const go = el('button', 'agent-bar__go');
|
|
719
|
+
go.type = 'button';
|
|
720
|
+
top.append(scope, input, agentButton, go);
|
|
721
|
+
|
|
722
|
+
// footer of the same box: the folder name, only for Create app / Create plugin / Download
|
|
723
|
+
const footer = el('div', 'agent-bar__footer');
|
|
724
|
+
footer.hidden = true;
|
|
725
|
+
const targetGroup = el('div', 'agent-bar__seg');
|
|
726
|
+
targetGroup.setAttribute('role', 'radiogroup');
|
|
727
|
+
targetGroup.setAttribute('aria-label', 'Download as');
|
|
728
|
+
Object.keys(DOWNLOAD_TARGETS).forEach((key) => {
|
|
729
|
+
const button = el('button', 'agent-bar__seg-item', DOWNLOAD_TARGETS[key].label);
|
|
730
|
+
button.type = 'button';
|
|
731
|
+
button.setAttribute('role', 'radio');
|
|
732
|
+
button.dataset.target = key;
|
|
733
|
+
targetGroup.appendChild(button);
|
|
734
|
+
});
|
|
735
|
+
const createName = createNameField({
|
|
736
|
+
id: 'agent-bar-create-name',
|
|
737
|
+
label: 'Folder name',
|
|
738
|
+
placeholder: 'e.g. my-app',
|
|
739
|
+
getDir: () => (ITEMS[state.item].dir || 'api'),
|
|
740
|
+
onChange: () => syncReady(),
|
|
741
|
+
onEdit: () => { setMsg(''); render(); },
|
|
742
|
+
});
|
|
743
|
+
const downloadName = createNameField({
|
|
744
|
+
id: 'agent-bar-download-name',
|
|
745
|
+
label: 'Folder name',
|
|
746
|
+
placeholder: 'e.g. repo-name',
|
|
747
|
+
getDir: () => DOWNLOAD_TARGETS[state.downloadTarget].dir,
|
|
748
|
+
onChange: () => syncReady(),
|
|
749
|
+
onEdit: () => {
|
|
750
|
+
state.suggestionToken += 1; // a hand-typed name stops the suggestion from the URL
|
|
751
|
+
setMsg('');
|
|
752
|
+
render();
|
|
753
|
+
},
|
|
754
|
+
});
|
|
755
|
+
footer.append(targetGroup, createName.root, downloadName.root);
|
|
756
|
+
field.append(top, footer);
|
|
757
|
+
|
|
758
|
+
// a message or progress, only when there is one
|
|
759
|
+
const note = el('div', 'agent-bar__note');
|
|
760
|
+
note.setAttribute('role', 'status');
|
|
761
|
+
note.hidden = true;
|
|
762
|
+
const noteSpinner = faIcon('fa-solid fa-circle-notch fa-spin agent-bar__note-spinner');
|
|
763
|
+
const noteCopy = el('div', 'agent-bar__note-copy');
|
|
764
|
+
const noteLabel = el('span', 'agent-bar__note-label');
|
|
765
|
+
const noteDetail = el('span', 'agent-bar__note-detail');
|
|
766
|
+
noteCopy.append(noteLabel, noteDetail);
|
|
767
|
+
const output = el('pre', 'agent-bar__output');
|
|
768
|
+
output.hidden = true;
|
|
769
|
+
note.append(noteSpinner, noteCopy, output);
|
|
770
|
+
|
|
771
|
+
const menu = el('div', 'agent-bar__menu');
|
|
772
|
+
menu.setAttribute('role', 'menu');
|
|
773
|
+
menu.hidden = true;
|
|
774
|
+
|
|
775
|
+
inner.append(field, note, menu);
|
|
776
|
+
root.appendChild(inner);
|
|
777
|
+
slot.parentNode.insertBefore(root, slot);
|
|
778
|
+
// The slot is hidden by agent-bar.css, and only where the bar itself is shown.
|
|
779
|
+
slot.dataset.agentBarReplaced = 'true';
|
|
780
|
+
|
|
781
|
+
const isCreate = () => Boolean(ITEMS[state.item].dir);
|
|
782
|
+
const isDownload = () => state.item === 'download';
|
|
783
|
+
const activeName = () => (isDownload() ? downloadName : (isCreate() ? createName : null));
|
|
784
|
+
const selectedTool = () => state.tools.find((tool) => tool.value === state.tool) || null;
|
|
785
|
+
const promptText = () => (state.item === 'create_plugin' && input.value.startsWith(PLUGIN_PROMPT_SEED)
|
|
786
|
+
? input.value.slice(PLUGIN_PROMPT_SEED.length)
|
|
787
|
+
: input.value);
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
function syncRaise() {
|
|
791
|
+
raiseTopBar(h1, Boolean(state.menu) || !note.hidden || field.offsetHeight > 32);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function showNote(label, detail, kind, spinning) {
|
|
795
|
+
const active = Boolean(label) || !output.hidden;
|
|
796
|
+
note.hidden = !active;
|
|
797
|
+
syncRaise();
|
|
798
|
+
noteLabel.textContent = label || '';
|
|
799
|
+
noteDetail.textContent = detail || '';
|
|
800
|
+
noteSpinner.hidden = !spinning;
|
|
801
|
+
if (kind) note.dataset.kind = kind;
|
|
802
|
+
else delete note.dataset.kind;
|
|
803
|
+
}
|
|
804
|
+
const setMsg = (text, kind) => showNote(text, '', kind, false);
|
|
805
|
+
// progress while something is being created
|
|
806
|
+
const setStatus = (label, detail) => showNote(label, detail, '', Boolean(label));
|
|
807
|
+
|
|
808
|
+
function appendOutput(text) {
|
|
809
|
+
const next = String(text == null ? '' : text);
|
|
810
|
+
if (!next) return;
|
|
811
|
+
output.hidden = false;
|
|
812
|
+
note.hidden = false;
|
|
813
|
+
syncRaise();
|
|
814
|
+
output.textContent += next;
|
|
815
|
+
output.scrollTop = output.scrollHeight;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function resetOutput() {
|
|
819
|
+
output.textContent = '';
|
|
820
|
+
output.hidden = true;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function fitInput() {
|
|
824
|
+
// how wide the send button is, for the controls placed beside it
|
|
825
|
+
if (go.offsetWidth) root.style.setProperty('--agent-bar-go-w', `${go.offsetWidth}px`);
|
|
826
|
+
fitTextarea(root, field, top, input);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
function setInputValue(value) {
|
|
830
|
+
input.value = value;
|
|
831
|
+
fitInput();
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function focusInputAtEnd() {
|
|
835
|
+
if (input.disabled) return;
|
|
836
|
+
input.focus();
|
|
837
|
+
try {
|
|
838
|
+
input.setSelectionRange(input.value.length, input.value.length);
|
|
839
|
+
} catch (_) {}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const isReady = () => {
|
|
843
|
+
if (isDownload()) return !validateDownloadUrl(input.value) && downloadName.isReady();
|
|
844
|
+
if (isCreate()) return createName.isReady();
|
|
845
|
+
return true;
|
|
846
|
+
};
|
|
847
|
+
// The arrow is dimmed until the folder name (and, for Download, the URL) is
|
|
848
|
+
// usable. It still responds, so a click tells you what is missing.
|
|
849
|
+
function syncReady() {
|
|
850
|
+
go.classList.toggle('is-waiting', !state.busy && !isReady());
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
function renderMenu() {
|
|
854
|
+
menu.textContent = '';
|
|
855
|
+
menu.hidden = !state.menu;
|
|
856
|
+
menu.dataset.menu = state.menu || '';
|
|
857
|
+
if (state.menu === 'mode') {
|
|
858
|
+
Object.keys(ITEMS).forEach((key) => {
|
|
859
|
+
menu.appendChild(menuRow(
|
|
860
|
+
faIcon(`${ITEM_ICONS[key]} agent-bar__row-icon`),
|
|
861
|
+
ITEMS[key].label,
|
|
862
|
+
'',
|
|
863
|
+
key === state.item,
|
|
864
|
+
() => { setItem(key); focusInputAtEnd(); }
|
|
865
|
+
));
|
|
866
|
+
});
|
|
867
|
+
} else if (state.menu === 'agent') {
|
|
868
|
+
agentMenuRows(menu, state.tools, state.toolsLoaded, state.tool, (tool) => {
|
|
869
|
+
state.tool = tool.value;
|
|
870
|
+
state.menu = null;
|
|
871
|
+
setStoredTool(tool.value);
|
|
872
|
+
setMsg('');
|
|
873
|
+
render();
|
|
874
|
+
focusInputAtEnd();
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
let toolsPromise = null;
|
|
880
|
+
function loadTools() {
|
|
881
|
+
if (toolsPromise) return toolsPromise;
|
|
882
|
+
toolsPromise = fetch('/api/plugin/menu')
|
|
883
|
+
.then((res) => {
|
|
884
|
+
if (!res.ok) throw new Error('Failed to load plugins.');
|
|
885
|
+
return res.json();
|
|
886
|
+
})
|
|
887
|
+
.then((payload) => {
|
|
888
|
+
state.tools = mapPluginMenuToTools(payload && Array.isArray(payload.menu) ? payload.menu : []);
|
|
889
|
+
state.toolsLoaded = true;
|
|
890
|
+
// The agent: the last one used; otherwise the one the plugin list marks
|
|
891
|
+
// as default; otherwise none yet (the first send asks once).
|
|
892
|
+
const stored = getStoredTool();
|
|
893
|
+
const fallback = state.tools.find((tool) => tool.isDefault);
|
|
894
|
+
if (stored && state.tools.some((tool) => tool.value === stored)) {
|
|
895
|
+
state.tool = stored;
|
|
896
|
+
} else {
|
|
897
|
+
if (stored) setStoredTool('');
|
|
898
|
+
if (!state.tools.some((tool) => tool.value === state.tool)) state.tool = fallback ? fallback.value : '';
|
|
899
|
+
}
|
|
900
|
+
render();
|
|
901
|
+
})
|
|
902
|
+
.catch(() => {
|
|
903
|
+
toolsPromise = null;
|
|
904
|
+
state.toolsLoaded = true;
|
|
905
|
+
render();
|
|
906
|
+
});
|
|
907
|
+
return toolsPromise;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function render() {
|
|
911
|
+
const item = ITEMS[state.item];
|
|
912
|
+
const download = isDownload();
|
|
913
|
+
const tool = selectedTool();
|
|
914
|
+
root.dataset.item = state.item;
|
|
915
|
+
root.dataset.busy = String(state.busy);
|
|
916
|
+
root.dataset.engaged = String(state.engaged);
|
|
917
|
+
scopeLabel.textContent = item.label;
|
|
918
|
+
scope.disabled = state.busy;
|
|
919
|
+
scope.classList.toggle('is-open', state.menu === 'mode');
|
|
920
|
+
scope.setAttribute('aria-expanded', String(state.menu === 'mode'));
|
|
921
|
+
input.placeholder = item.placeholder;
|
|
922
|
+
input.disabled = state.busy;
|
|
923
|
+
input.setAttribute('aria-label', download ? 'Git URL' : 'Message for the agent');
|
|
924
|
+
// the agent: one small icon in the field. Download does not use one.
|
|
925
|
+
agentButton.hidden = download;
|
|
926
|
+
agent.show(tool, state.busy, state.menu === 'agent');
|
|
927
|
+
// The folder row shows while you are in the bar, and stays once anything is
|
|
928
|
+
// typed, so a half-filled Create never looks like a plain Ask bar.
|
|
929
|
+
const nameField = activeName();
|
|
930
|
+
const showFooter = Boolean(nameField) && (state.engaged || state.busy
|
|
931
|
+
|| Boolean(nameField.input.value.trim()) || Boolean(promptText().trim()));
|
|
932
|
+
footer.hidden = !showFooter;
|
|
933
|
+
root.dataset.footer = String(showFooter);
|
|
934
|
+
targetGroup.hidden = !download;
|
|
935
|
+
targetGroup.querySelectorAll('.agent-bar__seg-item').forEach((button) => {
|
|
936
|
+
button.setAttribute('aria-checked', String(button.dataset.target === state.downloadTarget));
|
|
937
|
+
button.disabled = state.busy;
|
|
938
|
+
});
|
|
939
|
+
createName.root.hidden = !isCreate();
|
|
940
|
+
downloadName.root.hidden = !download;
|
|
941
|
+
createName.input.disabled = state.busy;
|
|
942
|
+
downloadName.input.disabled = state.busy;
|
|
943
|
+
createName.input.placeholder = state.item === 'create_plugin' ? 'e.g. my-plugin' : 'e.g. my-app';
|
|
944
|
+
go.disabled = state.busy;
|
|
945
|
+
go.textContent = '';
|
|
946
|
+
// Its label is shown where the button sits in the folder row (see the
|
|
947
|
+
// stylesheet): making a folder is named, a plain Ask is the arrow alone.
|
|
948
|
+
go.append(
|
|
949
|
+
el('span', 'agent-bar__go-label', item.label),
|
|
950
|
+
faIcon(state.busy ? 'fa-solid fa-circle-notch fa-spin' : 'fa-solid fa-arrow-up'),
|
|
951
|
+
);
|
|
952
|
+
go.setAttribute('aria-label', state.busy ? 'Working' : item.send);
|
|
953
|
+
go.title = state.busy ? '' : item.send;
|
|
954
|
+
syncReady();
|
|
955
|
+
renderMenu();
|
|
956
|
+
fitInput();
|
|
957
|
+
syncRaise();
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function engage() {
|
|
961
|
+
if (!state.engaged) {
|
|
962
|
+
state.engaged = true;
|
|
963
|
+
loadTools();
|
|
964
|
+
render();
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
function leave() {
|
|
969
|
+
if (state.busy || (!state.engaged && !state.menu)) return;
|
|
970
|
+
state.engaged = false;
|
|
971
|
+
state.menu = null;
|
|
972
|
+
render();
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
api.closeMenus = () => {
|
|
976
|
+
if (!state.menu) return;
|
|
977
|
+
state.menu = null;
|
|
978
|
+
render();
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
function toggleMenu(which) {
|
|
982
|
+
if (state.busy) return;
|
|
983
|
+
state.menu = state.menu === which ? null : which;
|
|
984
|
+
state.engaged = true;
|
|
985
|
+
setMsg('');
|
|
986
|
+
loadTools();
|
|
987
|
+
render();
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// The folder name for Download is suggested from the repo name and moved to
|
|
991
|
+
// a free name, until it is edited by hand (same as the dialog).
|
|
992
|
+
let suggestTimer = null;
|
|
993
|
+
function suggestDownloadName() {
|
|
994
|
+
if (downloadName.state.edited) return;
|
|
995
|
+
window.clearTimeout(suggestTimer);
|
|
996
|
+
const base = extractUrlLikeNameSuggestion(input.value);
|
|
997
|
+
const token = state.suggestionToken + 1;
|
|
998
|
+
state.suggestionToken = token;
|
|
999
|
+
if (!base) {
|
|
1000
|
+
downloadName.setValue('');
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
const dir = DOWNLOAD_TARGETS[state.downloadTarget].dir;
|
|
1004
|
+
suggestTimer = window.setTimeout(async () => {
|
|
1005
|
+
let name = base;
|
|
1006
|
+
try {
|
|
1007
|
+
name = await suggestAvailableFolderName(dir, base);
|
|
1008
|
+
} catch (_) {}
|
|
1009
|
+
if (state.suggestionToken !== token || downloadName.state.edited || !isDownload()) return;
|
|
1010
|
+
downloadName.setValue(name);
|
|
1011
|
+
render();
|
|
1012
|
+
}, 200);
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function setItem(next) {
|
|
1016
|
+
if (!ITEMS[next] || state.busy) return;
|
|
1017
|
+
const previous = state.item;
|
|
1018
|
+
// keep what was typed: one prompt for Ask / Create app / Create plugin, one URL for Download
|
|
1019
|
+
if (previous === 'download') state.downloadUrl = input.value;
|
|
1020
|
+
else state.prompt = promptText();
|
|
1021
|
+
state.item = next;
|
|
1022
|
+
state.menu = null;
|
|
1023
|
+
state.engaged = true;
|
|
1024
|
+
setMsg('');
|
|
1025
|
+
resetOutput();
|
|
1026
|
+
if (next === 'download') {
|
|
1027
|
+
setInputValue(state.downloadUrl);
|
|
1028
|
+
downloadName.schedule();
|
|
1029
|
+
suggestDownloadName();
|
|
1030
|
+
} else if (next === 'create_plugin') {
|
|
1031
|
+
// starter text, with the cursor after it
|
|
1032
|
+
setInputValue(`${PLUGIN_PROMPT_SEED}${state.prompt}`);
|
|
1033
|
+
} else {
|
|
1034
|
+
setInputValue(state.prompt);
|
|
1035
|
+
}
|
|
1036
|
+
if (ITEMS[next].dir) createName.schedule();
|
|
1037
|
+
render();
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
function setDownloadTarget(next) {
|
|
1041
|
+
if (!DOWNLOAD_TARGETS[next] || state.busy || state.downloadTarget === next) return;
|
|
1042
|
+
state.downloadTarget = next;
|
|
1043
|
+
setMsg('');
|
|
1044
|
+
render();
|
|
1045
|
+
if (downloadName.state.edited) downloadName.schedule();
|
|
1046
|
+
else suggestDownloadName();
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function setBusy(busy) {
|
|
1050
|
+
state.busy = busy;
|
|
1051
|
+
if (busy) state.menu = null;
|
|
1052
|
+
render();
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function fail(error, fallback) {
|
|
1056
|
+
setBusy(false);
|
|
1057
|
+
setMsg(error && error.message ? error.message : fallback, 'error');
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
async function requireTool() {
|
|
1061
|
+
await loadTools();
|
|
1062
|
+
const tool = selectedTool();
|
|
1063
|
+
if (!tool) {
|
|
1064
|
+
state.menu = 'agent';
|
|
1065
|
+
render();
|
|
1066
|
+
setMsg('Choose an agent once. It is remembered after that.', 'error');
|
|
1067
|
+
}
|
|
1068
|
+
return tool;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
async function requireName(nameField) {
|
|
1072
|
+
if (!nameField.input.value.trim()) {
|
|
1073
|
+
await nameField.run({ showEmpty: true });
|
|
1074
|
+
state.engaged = true;
|
|
1075
|
+
render();
|
|
1076
|
+
nameField.input.focus();
|
|
1077
|
+
return false;
|
|
1078
|
+
}
|
|
1079
|
+
const ready = await nameField.run({ showEmpty: true });
|
|
1080
|
+
if (!ready) {
|
|
1081
|
+
setMsg(nameField.state.message || 'Please choose a different name.', 'error');
|
|
1082
|
+
nameField.input.focus();
|
|
1083
|
+
}
|
|
1084
|
+
return ready;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// Offers a session that was just started to api.deliver. If it is taken, the
|
|
1088
|
+
// bar goes back to how a fresh page shows it: closed, empty, on Ask.
|
|
1089
|
+
function handOver(type, payload, tool) {
|
|
1090
|
+
let taken = false;
|
|
1091
|
+
try {
|
|
1092
|
+
taken = api.deliver({
|
|
1093
|
+
type,
|
|
1094
|
+
url: payload.url,
|
|
1095
|
+
cwd: typeof payload.cwd === 'string' ? payload.cwd : '',
|
|
1096
|
+
name: typeof payload.name === 'string' ? payload.name : '',
|
|
1097
|
+
prompt: input.value.trim(),
|
|
1098
|
+
tool: { value: tool.value, label: tool.label, iconSrc: tool.iconSrc || '' },
|
|
1099
|
+
}) === true;
|
|
1100
|
+
} catch (_) {
|
|
1101
|
+
taken = false;
|
|
1102
|
+
}
|
|
1103
|
+
if (!taken) return false;
|
|
1104
|
+
state.busy = false;
|
|
1105
|
+
state.menu = null;
|
|
1106
|
+
state.engaged = false;
|
|
1107
|
+
state.item = 'ask';
|
|
1108
|
+
state.prompt = '';
|
|
1109
|
+
setInputValue('');
|
|
1110
|
+
createName.setValue('');
|
|
1111
|
+
api.attachments.clear();
|
|
1112
|
+
setMsg('');
|
|
1113
|
+
if (document.activeElement && root.contains(document.activeElement)) document.activeElement.blur();
|
|
1114
|
+
render();
|
|
1115
|
+
return true;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
async function submitAsk() {
|
|
1119
|
+
const tool = await requireTool();
|
|
1120
|
+
if (!tool) return;
|
|
1121
|
+
setBusy(true);
|
|
1122
|
+
try {
|
|
1123
|
+
// an Ask from this bar runs in the one shared brain folder (server/lib/brain.js)
|
|
1124
|
+
const { response, payload } = await postJson('/brain/ask', {
|
|
1125
|
+
prompt: input.value.trim(),
|
|
1126
|
+
tool: tool.value,
|
|
1127
|
+
uploadToken: await api.attachments.token(),
|
|
1128
|
+
});
|
|
1129
|
+
if (!response.ok || !payload || !payload.ok || !payload.url) {
|
|
1130
|
+
throw new Error(payload && payload.error ? payload.error : 'Failed to prepare launcher.');
|
|
1131
|
+
}
|
|
1132
|
+
if (!handOver('ask', payload, tool)) api.navigate(payload.url);
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
fail(error, 'Failed to continue.');
|
|
1135
|
+
focusInputAtEnd();
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async function submitCreatePlugin() {
|
|
1140
|
+
const tool = await requireTool();
|
|
1141
|
+
if (!tool) return;
|
|
1142
|
+
if (!(await requireName(createName))) return;
|
|
1143
|
+
setBusy(true);
|
|
1144
|
+
try {
|
|
1145
|
+
const { response, payload } = await postJson('/launcher/prepare', {
|
|
1146
|
+
type: 'create_plugin',
|
|
1147
|
+
name: createName.input.value.trim(),
|
|
1148
|
+
prompt: input.value.trim(),
|
|
1149
|
+
tool: tool.value,
|
|
1150
|
+
uploadToken: await api.attachments.token(),
|
|
1151
|
+
});
|
|
1152
|
+
if (!response.ok || !payload || !payload.ok || !payload.url) {
|
|
1153
|
+
throw new Error(payload && payload.error ? payload.error : 'Failed to prepare launcher.');
|
|
1154
|
+
}
|
|
1155
|
+
if (!handOver('create_plugin', payload, tool)) api.navigate(payload.url);
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
fail(error, 'Failed to continue.');
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
async function submitCreateApp() {
|
|
1162
|
+
const tool = await requireTool();
|
|
1163
|
+
if (!tool) return;
|
|
1164
|
+
if (!(await requireName(createName))) return;
|
|
1165
|
+
setBusy(true);
|
|
1166
|
+
// same progress text as the dialog
|
|
1167
|
+
setStatus('Preparing app workspace', 'Creating the app folder, starter files, and first git commit. This usually takes a few seconds.');
|
|
1168
|
+
try {
|
|
1169
|
+
const { response, payload } = await postJson('/launcher/create-app', {
|
|
1170
|
+
name: createName.input.value.trim(),
|
|
1171
|
+
prompt: input.value.trim(),
|
|
1172
|
+
tool: tool.value,
|
|
1173
|
+
uploadToken: await api.attachments.token(),
|
|
1174
|
+
});
|
|
1175
|
+
if (!response.ok || !payload || !payload.ok || !payload.url) {
|
|
1176
|
+
throw new Error(payload && payload.error ? payload.error : 'Failed to create app.');
|
|
1177
|
+
}
|
|
1178
|
+
if (handOver('create_app', payload, tool)) return;
|
|
1179
|
+
setStatus('Opening dev page', 'Redirecting to the new app.');
|
|
1180
|
+
api.navigate(payload.url);
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
fail(error, 'Failed to continue.');
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
function runDownloadClone(clone) {
|
|
1187
|
+
if (!clone || typeof clone !== 'object') {
|
|
1188
|
+
return Promise.reject(new Error('Download is unavailable right now.'));
|
|
1189
|
+
}
|
|
1190
|
+
appendOutput(`$ ${clone.message}\n\n`);
|
|
1191
|
+
return ensureSocketReady().then((SocketConstructor) => new Promise((resolve, reject) => {
|
|
1192
|
+
const socket = new SocketConstructor();
|
|
1193
|
+
let settled = false;
|
|
1194
|
+
const settle = (fn, value) => {
|
|
1195
|
+
if (settled) return;
|
|
1196
|
+
settled = true;
|
|
1197
|
+
try {
|
|
1198
|
+
socket.close();
|
|
1199
|
+
} catch (_) {}
|
|
1200
|
+
fn(value);
|
|
1201
|
+
};
|
|
1202
|
+
socket.run({
|
|
1203
|
+
method: 'shell.run',
|
|
1204
|
+
client: DOWNLOAD_SHELL_CLIENT,
|
|
1205
|
+
params: {
|
|
1206
|
+
message: clone.message,
|
|
1207
|
+
path: clone.path,
|
|
1208
|
+
env: clone.env || { ...NON_INTERACTIVE_GIT_ENV },
|
|
1209
|
+
},
|
|
1210
|
+
}, (packet) => {
|
|
1211
|
+
if (!packet || typeof packet !== 'object') return;
|
|
1212
|
+
if (packet.type === 'stream') {
|
|
1213
|
+
const data = packet.data || {};
|
|
1214
|
+
if (typeof data.raw === 'string' && data.raw) appendOutput(data.raw);
|
|
1215
|
+
else if (data.json) appendOutput(`${JSON.stringify(data.json)}\n`);
|
|
1216
|
+
else if (data.json2) appendOutput(`${JSON.stringify(data.json2)}\n`);
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
if (packet.type === 'result') {
|
|
1220
|
+
const errors = packet.data && Array.isArray(packet.data.error) ? packet.data.error : [];
|
|
1221
|
+
if (errors.length > 0) {
|
|
1222
|
+
const failureMessage = errors.join('\n').trim() || 'Download failed.';
|
|
1223
|
+
appendOutput(`${failureMessage}\n`);
|
|
1224
|
+
settle(reject, new Error(failureMessage));
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
settle(resolve);
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
if (packet.type === 'error') {
|
|
1231
|
+
const failureMessage = typeof packet.data === 'string' && packet.data.trim()
|
|
1232
|
+
? packet.data.trim()
|
|
1233
|
+
: 'Download failed.';
|
|
1234
|
+
appendOutput(`${failureMessage}\n`);
|
|
1235
|
+
settle(reject, new Error(failureMessage));
|
|
1236
|
+
}
|
|
1237
|
+
}).catch((error) => {
|
|
1238
|
+
settle(reject, error instanceof Error ? error : new Error(String(error || 'Download failed.')));
|
|
1239
|
+
});
|
|
1240
|
+
}));
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
async function submitDownload() {
|
|
1244
|
+
const ref = input.value.trim();
|
|
1245
|
+
const urlError = validateDownloadUrl(ref);
|
|
1246
|
+
if (urlError) {
|
|
1247
|
+
setMsg(urlError, 'error');
|
|
1248
|
+
focusInputAtEnd();
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
if (!(await requireName(downloadName))) return;
|
|
1252
|
+
const intent = state.downloadTarget;
|
|
1253
|
+
const targetInfo = DOWNLOAD_TARGETS[intent];
|
|
1254
|
+
const name = downloadName.input.value.trim();
|
|
1255
|
+
setBusy(true);
|
|
1256
|
+
resetOutput();
|
|
1257
|
+
// same progress text as the dialog
|
|
1258
|
+
setStatus(`Importing ${targetInfo.noun}`, `Cloning into PINOKIO_HOME/${targetInfo.dir} and preparing the destination folder.`);
|
|
1259
|
+
try {
|
|
1260
|
+
const prepared = await postJson('/launcher/download/prepare', { intent, ref, name });
|
|
1261
|
+
if (!prepared.response.ok || !prepared.payload || !prepared.payload.ok) {
|
|
1262
|
+
throw new Error(prepared.payload && prepared.payload.error ? prepared.payload.error : 'Failed to prepare download.');
|
|
1263
|
+
}
|
|
1264
|
+
const plan = prepared.payload;
|
|
1265
|
+
if (plan.existing && plan.url) {
|
|
1266
|
+
api.navigate(plan.url);
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
await runDownloadClone(plan.clone);
|
|
1270
|
+
const finalized = await postJson('/launcher/download/finalize', {
|
|
1271
|
+
intent,
|
|
1272
|
+
ref: plan.finalize && plan.finalize.ref ? plan.finalize.ref : ref,
|
|
1273
|
+
name: plan.finalize && plan.finalize.name ? plan.finalize.name : name,
|
|
1274
|
+
id: plan.finalize && plan.finalize.id ? plan.finalize.id : '',
|
|
1275
|
+
});
|
|
1276
|
+
if (!finalized.response.ok || !finalized.payload || !finalized.payload.ok || !finalized.payload.url) {
|
|
1277
|
+
throw new Error(finalized.payload && finalized.payload.error ? finalized.payload.error : 'Failed to finalize download.');
|
|
1278
|
+
}
|
|
1279
|
+
api.navigate(finalized.payload.url);
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
fail(error, 'Failed to continue.');
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
// One send at a time. `state.busy` is only set once a send's checks have
|
|
1286
|
+
// passed, so a second Enter during those checks is held off here.
|
|
1287
|
+
let sending = false;
|
|
1288
|
+
function submit() {
|
|
1289
|
+
if (state.busy || sending) return;
|
|
1290
|
+
sending = true;
|
|
1291
|
+
state.menu = null;
|
|
1292
|
+
state.engaged = true;
|
|
1293
|
+
setMsg('');
|
|
1294
|
+
render();
|
|
1295
|
+
let sent;
|
|
1296
|
+
if (state.item === 'ask') sent = submitAsk();
|
|
1297
|
+
else if (state.item === 'create_app') sent = submitCreateApp();
|
|
1298
|
+
else if (state.item === 'create_plugin') sent = submitCreatePlugin();
|
|
1299
|
+
else sent = submitDownload();
|
|
1300
|
+
sent.finally(() => { sending = false; });
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
scope.addEventListener('click', () => toggleMenu('mode'));
|
|
1304
|
+
agentButton.addEventListener('click', () => toggleMenu('agent'));
|
|
1305
|
+
targetGroup.addEventListener('click', (event) => {
|
|
1306
|
+
const button = event.target.closest('[data-target]');
|
|
1307
|
+
if (button) setDownloadTarget(button.dataset.target);
|
|
1308
|
+
});
|
|
1309
|
+
input.addEventListener('focus', engage);
|
|
1310
|
+
input.addEventListener('pointerdown', engage);
|
|
1311
|
+
input.addEventListener('input', () => {
|
|
1312
|
+
setMsg('');
|
|
1313
|
+
if (isDownload()) suggestDownloadName();
|
|
1314
|
+
render();
|
|
1315
|
+
});
|
|
1316
|
+
input.addEventListener('keydown', (event) => {
|
|
1317
|
+
if (event.key !== 'Enter' || event.isComposing) return;
|
|
1318
|
+
// Enter sends (so does Cmd/Ctrl+Enter, as in the dialog); Shift+Enter adds a line.
|
|
1319
|
+
// A URL has no lines, so in Download every Enter sends.
|
|
1320
|
+
const newline = event.shiftKey && !event.metaKey && !event.ctrlKey && !isDownload();
|
|
1321
|
+
if (newline) return;
|
|
1322
|
+
event.preventDefault();
|
|
1323
|
+
const nameField = activeName();
|
|
1324
|
+
if (nameField && !nameField.input.value.trim()) {
|
|
1325
|
+
// the name is still empty: go to it instead of showing an error
|
|
1326
|
+
state.engaged = true;
|
|
1327
|
+
render();
|
|
1328
|
+
nameField.input.focus();
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
submit();
|
|
1332
|
+
});
|
|
1333
|
+
[createName, downloadName].forEach((nameField) => {
|
|
1334
|
+
nameField.input.addEventListener('focus', engage);
|
|
1335
|
+
nameField.input.addEventListener('keydown', (event) => {
|
|
1336
|
+
if (event.key === 'Enter' && !event.isComposing) {
|
|
1337
|
+
event.preventDefault();
|
|
1338
|
+
submit();
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
});
|
|
1342
|
+
go.addEventListener('click', submit);
|
|
1343
|
+
bindBar(root, inner, {
|
|
1344
|
+
isBusy: () => state.busy,
|
|
1345
|
+
hasMenu: () => Boolean(state.menu),
|
|
1346
|
+
closeMenu: () => { state.menu = null; render(); },
|
|
1347
|
+
leave,
|
|
1348
|
+
fit: fitInput,
|
|
1349
|
+
});
|
|
1350
|
+
|
|
1351
|
+
// The bar can take requests only while it is actually on screen: in
|
|
1352
|
+
// fullscreen mode the top navbar is hidden, and on phones only pages with the
|
|
1353
|
+
// main sidebar show the bar (see agent-bar.css).
|
|
1354
|
+
function isUsable() {
|
|
1355
|
+
const rect = field.getBoundingClientRect();
|
|
1356
|
+
if (rect.width < 160 || rect.height === 0) return false;
|
|
1357
|
+
if (rect.bottom <= 0 || rect.right <= 0) return false;
|
|
1358
|
+
if (rect.top >= window.innerHeight || rect.left >= window.innerWidth) return false;
|
|
1359
|
+
return window.getComputedStyle(field).visibility !== 'hidden';
|
|
1360
|
+
}
|
|
1361
|
+
function syncActive() {
|
|
1362
|
+
document.documentElement.classList.toggle('agent-bar-active', isUsable());
|
|
1363
|
+
}
|
|
1364
|
+
window.addEventListener('resize', syncActive);
|
|
1365
|
+
const header = h1.closest('header');
|
|
1366
|
+
if (header) {
|
|
1367
|
+
new MutationObserver(syncActive).observe(header, { attributes: true, attributeFilter: ['class', 'style'] });
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
function applyPrompt(text) {
|
|
1371
|
+
let prompt = typeof text === 'string' ? text : '';
|
|
1372
|
+
if (prompt.startsWith(PLUGIN_PROMPT_SEED)) prompt = prompt.slice(PLUGIN_PROMPT_SEED.length);
|
|
1373
|
+
state.prompt = prompt;
|
|
1374
|
+
if (isDownload()) return;
|
|
1375
|
+
setInputValue(state.item === 'create_plugin' ? `${PLUGIN_PROMPT_SEED}${prompt}` : prompt);
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// A Create / Ask / Download button or a pre-filled link. Same fields the
|
|
1379
|
+
// dialog reads: type, mode, prompt, name, tool. No type means Create app.
|
|
1380
|
+
api.open = (defaults) => {
|
|
1381
|
+
if (!isUsable()) return false;
|
|
1382
|
+
if (state.busy) return true;
|
|
1383
|
+
const options = defaults && typeof defaults === 'object' ? defaults : {};
|
|
1384
|
+
const rawType = String(options.type || options.intent || '').trim();
|
|
1385
|
+
const type = rawType === 'ask' || rawType === 'create_plugin' ? rawType : 'create_app';
|
|
1386
|
+
const download = options.mode === 'download';
|
|
1387
|
+
// Importing a task package is not in the bar; the dialog still does it.
|
|
1388
|
+
if (download && !DOWNLOAD_TARGETS[type]) return false;
|
|
1389
|
+
|
|
1390
|
+
loadTools();
|
|
1391
|
+
if (download) {
|
|
1392
|
+
setItem('download');
|
|
1393
|
+
setDownloadTarget(type);
|
|
1394
|
+
} else {
|
|
1395
|
+
setItem(type);
|
|
1396
|
+
const prompt = typeof options.prompt === 'string' ? options.prompt.trim() : '';
|
|
1397
|
+
if (prompt) applyPrompt(prompt);
|
|
1398
|
+
const name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
1399
|
+
if (name && ITEMS[type].dir) {
|
|
1400
|
+
createName.setValue(name);
|
|
1401
|
+
}
|
|
1402
|
+
const tool = typeof options.tool === 'string' ? options.tool.trim().replace(/^\/+|\/+$/g, '') : '';
|
|
1403
|
+
if (tool) {
|
|
1404
|
+
// chosen for this request only, not remembered (same as the dialog)
|
|
1405
|
+
loadTools().then(() => {
|
|
1406
|
+
if (state.tools.some((entry) => entry.value === tool)) {
|
|
1407
|
+
state.tool = tool;
|
|
1408
|
+
render();
|
|
1409
|
+
}
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
render();
|
|
1414
|
+
focusInputAtEnd();
|
|
1415
|
+
return true;
|
|
1416
|
+
};
|
|
1417
|
+
|
|
1418
|
+
render();
|
|
1419
|
+
syncActive();
|
|
1420
|
+
return true;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// Phones, pages with the main sidebar: the top bar keeps only the logo and the
|
|
1424
|
+
// agent bar (see agent-bar.css), so what else was in it is offered in the
|
|
1425
|
+
// sidebar. Explore, Home Server and Remote are sidebar rows already. This adds
|
|
1426
|
+
// the rest, shown at phone widths only: back / forward / reload as one row of
|
|
1427
|
+
// three buttons at the top, and a "Window" section (split into 2 columns, split
|
|
1428
|
+
// into 2 rows, new window). Each row is added only if the header has that
|
|
1429
|
+
// button, and presses it, so it does exactly what the button does.
|
|
1430
|
+
function addPhoneSidebarRows() {
|
|
1431
|
+
const header = 'body.main-sidebar-page > header.navheader h1 > ';
|
|
1432
|
+
const nav = document.querySelector('.main-sidebar .main-sidebar-nav');
|
|
1433
|
+
if (!nav || !document.querySelector(header + '*')) return;
|
|
1434
|
+
if (nav.querySelector('.agent-bar-phone-only')) return;
|
|
1435
|
+
const closeSidebar = () => {
|
|
1436
|
+
const backdrop = document.querySelector('[data-main-sidebar-backdrop]');
|
|
1437
|
+
if (backdrop && !backdrop.hidden) backdrop.click();
|
|
1438
|
+
};
|
|
1439
|
+
const press = (selector) => () => {
|
|
1440
|
+
const target = document.querySelector(header + selector);
|
|
1441
|
+
closeSidebar();
|
|
1442
|
+
if (target) target.click();
|
|
1443
|
+
};
|
|
1444
|
+
const has = (selector) => Boolean(document.querySelector(header + selector));
|
|
1445
|
+
|
|
1446
|
+
const history = [
|
|
1447
|
+
['#back', 'fa-chevron-left', 'Back'],
|
|
1448
|
+
['#forward', 'fa-chevron-right', 'Forward'],
|
|
1449
|
+
['#refresh-page', 'fa-rotate-right', 'Reload'],
|
|
1450
|
+
].filter((item) => has(item[0]));
|
|
1451
|
+
if (history.length) {
|
|
1452
|
+
const row = document.createElement('div');
|
|
1453
|
+
row.className = 'agent-bar-phone-only agent-bar-phone-navrow';
|
|
1454
|
+
history.forEach(([selector, icon, label]) => {
|
|
1455
|
+
const button = document.createElement('button');
|
|
1456
|
+
button.type = 'button';
|
|
1457
|
+
button.title = label;
|
|
1458
|
+
button.setAttribute('aria-label', label);
|
|
1459
|
+
const glyph = document.createElement('i');
|
|
1460
|
+
glyph.className = `fa-solid ${icon}`;
|
|
1461
|
+
glyph.setAttribute('aria-hidden', 'true');
|
|
1462
|
+
button.appendChild(glyph);
|
|
1463
|
+
button.addEventListener('click', press(selector));
|
|
1464
|
+
row.appendChild(button);
|
|
1465
|
+
});
|
|
1466
|
+
nav.insertBefore(row, nav.firstChild);
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
const windowRows = [
|
|
1470
|
+
['a[href="/columns"]', 'fa-solid fa-table-columns', 'Split into 2 columns'],
|
|
1471
|
+
['a[href="/rows"]', 'fa-solid fa-table-columns fa-rotate-270', 'Split into 2 rows'],
|
|
1472
|
+
['#new-window', 'fa-solid fa-plus', 'New window'],
|
|
1473
|
+
].filter((item) => has(item[0]));
|
|
1474
|
+
if (windowRows.length) {
|
|
1475
|
+
const section = document.createElement('div');
|
|
1476
|
+
section.className = 'main-sidebar-section agent-bar-phone-only';
|
|
1477
|
+
section.setAttribute('aria-label', 'Window');
|
|
1478
|
+
const title = document.createElement('div');
|
|
1479
|
+
title.className = 'main-sidebar-section-title';
|
|
1480
|
+
title.textContent = 'Window';
|
|
1481
|
+
section.appendChild(title);
|
|
1482
|
+
windowRows.forEach(([selector, icon, label]) => {
|
|
1483
|
+
const button = document.createElement('button');
|
|
1484
|
+
button.type = 'button';
|
|
1485
|
+
button.className = 'tab agent-bar-phone-row';
|
|
1486
|
+
const glyph = document.createElement('i');
|
|
1487
|
+
glyph.className = icon;
|
|
1488
|
+
glyph.setAttribute('aria-hidden', 'true');
|
|
1489
|
+
const caption = document.createElement('div');
|
|
1490
|
+
caption.className = 'caption';
|
|
1491
|
+
caption.textContent = label;
|
|
1492
|
+
button.appendChild(glyph);
|
|
1493
|
+
button.appendChild(caption);
|
|
1494
|
+
button.addEventListener('click', press(selector));
|
|
1495
|
+
section.appendChild(button);
|
|
1496
|
+
});
|
|
1497
|
+
nav.insertBefore(section, nav.querySelector('.main-sidebar-section-connect'));
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// Whatever happened earlier, by the time the page has loaded the bar is either
|
|
1502
|
+
// in or it is not coming, and nothing stays held back.
|
|
1503
|
+
const finish = () => {
|
|
1504
|
+
mount();
|
|
1505
|
+
settle();
|
|
1506
|
+
addPhoneSidebarRows();
|
|
1507
|
+
};
|
|
1508
|
+
if (document.readyState === 'loading') {
|
|
1509
|
+
document.addEventListener('DOMContentLoaded', finish);
|
|
1510
|
+
} else {
|
|
1511
|
+
finish();
|
|
1512
|
+
}
|
|
1513
|
+
})(window, document);
|