845 lines
48 KiB
JavaScript
845 lines
48 KiB
JavaScript
// The Docker window (desktop IDE): the Docker of this computer, beside the code.
|
||
// - Containers: grouped by Compose project, state, image, published ports (a click opens http://localhost:<port>), CPU / memory
|
||
// (docker stats, only while the window is shown), start / stop / restart, logs (followed), a shell in the IDE's terminal,
|
||
// inspect, remove; a Compose project as a whole: up / stop / down.
|
||
// - Images: size, tags, created; run, inspect, remove; prune the dangling ones.
|
||
// - Docker Hub: search, a repository's page (description, tags with size and date), pull a tag (progress), run it.
|
||
// - Volumes & networks: listed, inspected, removed.
|
||
// - Compose: the project's compose files by folder (a JumPHP site's generated stack + its compose.override.yaml, symfony-docker's,
|
||
// any other), opened in the editor, a service added from a template, checked (docker compose config: its errors in Problems),
|
||
// applied (web:up / docker compose up -d); Docker Hub's tags insert "image: name:tag" into the YAML being edited.
|
||
// A web site also gets its PHP version (bin/jumphp web:php) and its Docker setup (web:docker: the JumPHP stack,
|
||
// symfony-docker, or its own compose service that runs PHP), changed in the Run window.
|
||
// - Engine: this computer, a server of the SSH window (the IDE's ssh tunnel to its docker socket: key, jump host) or a docker context;
|
||
// remembered per project. Everything above then works with that engine.
|
||
// Destructive actions always ask first. The PHP side: ide/src/Docker/DockerCommands.php (+ DockerEngine.php). Claude: docker_* tools at the end.
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t, confirm, dialog, progressBar, copyText, fileIcon } from './ui.js';
|
||
import { renderMarkdown } from './markdown.js';
|
||
import { monaco } from './editor.js';
|
||
import { withImage } from './yaml-lang.js';
|
||
|
||
const STATS_EVERY = 4000;
|
||
const OUTPUT_MAX = 400000;
|
||
const num = (n) => (n >= 1e9 ? (n / 1e9).toFixed(1) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'k' : String(n));
|
||
const bytes = (n) => (!n ? '–' : n >= 1073741824 ? (n / 1073741824).toFixed(2) + ' GB' : n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : (n / 1024).toFixed(0) + ' KB');
|
||
const day = (iso) => { const d = new Date(iso); return isNaN(d) ? '' : d.toLocaleDateString(); };
|
||
const lines = (text) => String(text || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
||
|
||
export class DockerPanel {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.node = el('div.docker-view');
|
||
this.tab = prefs.get('dockerTab', 'containers');
|
||
this.ps = null; // {available, error, containers, groups}
|
||
this.stats = {}; // short id -> {cpu, mem, memPerc}
|
||
this.statCells = new Map(); // short id -> node
|
||
this.folded = new Set(prefs.get('dockerFolded', []));
|
||
this.filter = '';
|
||
this.images = null;
|
||
this.volumes = null;
|
||
this.networks = null;
|
||
this.hub = { query: prefs.get('dockerHubQuery', ''), results: null, busy: false, repo: null, error: null };
|
||
this.output = null; // {stream, title, text, done, code, follow, pull: {layers: Map}}
|
||
this.waiters = new Map(); // stream -> resolve(text) (Claude's docker_pull)
|
||
this.engine = 'local'; // the engine in use (local, ssh:<server>, context:<name>)
|
||
this.engines = [];
|
||
this.engineState = null; // {state: ready | connecting | error | disconnected, step, reason, message, detail, version, webHost}
|
||
this.engineReady = null;
|
||
backend.on('docker.engine', (s) => this.engineStatus(s));
|
||
backend.on('docker.output', (p) => this.streamOutput(p));
|
||
backend.on('docker.exit', (p) => this.streamExit(p));
|
||
this.render();
|
||
setInterval(() => this.pollStats(), STATS_EVERY);
|
||
}
|
||
|
||
title() { return 'Docker'; }
|
||
|
||
actions() {
|
||
return [el('button', { title: t('Refresh'), onclick: () => this.refresh() }, icon('refresh'))];
|
||
}
|
||
|
||
visible() { return this.app.open?.[this.app.tools?.docker?.side] === 'docker' && document.visibilityState === 'visible'; }
|
||
|
||
shown() { this.initEngine().then(() => this.refresh()); }
|
||
|
||
setTab(tab) { this.tab = tab; prefs.set('dockerTab', tab); this.render(); this.refresh(); }
|
||
|
||
refresh() {
|
||
if (this.tab === 'containers') return this.loadContainers();
|
||
if (this.tab === 'images') return this.loadImages();
|
||
if (this.tab === 'other') return this.loadOther();
|
||
if (this.tab === 'compose') return this.loadCompose();
|
||
return null;
|
||
}
|
||
|
||
// the window ------------------------------------------------------------------------------------------------
|
||
|
||
render() {
|
||
clear(this.node);
|
||
this.engineBar = el('div.docker-engine');
|
||
this.node.append(this.engineBar);
|
||
this.renderEngineBar();
|
||
const tabs = [['containers', 'Containers'], ['compose', 'Compose'], ['images', 'Images'], ['hub', 'Docker Hub'], ['other', 'Volumes & networks']];
|
||
this.node.append(el('div.cryo-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label)))));
|
||
this.body = el('div.docker-body');
|
||
this.node.append(this.body);
|
||
if (this.tab === 'containers') this.renderContainers();
|
||
else if (this.tab === 'images') this.renderImages();
|
||
else if (this.tab === 'hub') this.renderHub();
|
||
else if (this.tab === 'compose') this.renderCompose();
|
||
else this.renderOther();
|
||
this.outputNode = el('div.docker-output');
|
||
this.node.append(this.outputNode);
|
||
this.renderOutput();
|
||
}
|
||
|
||
unavailable(error) {
|
||
return el('div.prof-empty', {},
|
||
el('div.prof-empty-title', {}, t('Docker does not answer')),
|
||
el('p', {}, this.engine === 'local' ? t('Start Docker (Docker Desktop, or the Docker service), then refresh.')
|
||
: this.engineState?.state === 'error' ? this.engineAdvice(this.engineState) : t('The engine chosen above does not answer.')),
|
||
error ? el('pre.docker-error', {}, String(error).slice(0, 600)) : null,
|
||
el('button.btn', { onclick: () => this.refresh() }, icon('refresh'), t('Refresh')));
|
||
}
|
||
|
||
async run(what, fn, refresh = true) {
|
||
try {
|
||
const r = await fn();
|
||
if (refresh) this.refresh();
|
||
return r;
|
||
} catch (e) {
|
||
notify(e.message || String(e), 'error', { title: what });
|
||
if (refresh) this.refresh();
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// the engine: this computer, a server of the SSH window (a tunnel), a docker context --------------------------------
|
||
|
||
engineKey() { return 'dockerEngine:' + (this.app.projectKey || ''); }
|
||
|
||
initEngine() {
|
||
this.engineReady ||= (async () => {
|
||
const saved = prefs.get(this.engineKey(), 'local');
|
||
await this.loadEngines();
|
||
if (saved !== 'local' && saved !== this.engine && this.engines.some((e) => e.id === saved)) await this.selectEngine(saved, false);
|
||
})();
|
||
return this.engineReady;
|
||
}
|
||
|
||
async loadEngines() {
|
||
const r = await backend.invoke('docker.engines', {}).catch(() => null);
|
||
if (r) { this.engines = r.engines; this.engine = r.current; this.engineState = r.status; }
|
||
this.renderEngineBar();
|
||
}
|
||
|
||
async selectEngine(id, refresh = true) {
|
||
this.engine = id;
|
||
prefs.set(this.engineKey(), id);
|
||
this.ps = null; this.images = null; this.volumes = null; this.networks = null; this.stats = {};
|
||
this.engineState = { id, state: 'connecting', step: id.startsWith('ssh:') ? 'probe' : 'docker' };
|
||
this.render();
|
||
this.engineState = await backend.invoke('docker.engine.select', { id }).catch((e) => ({ id, state: 'error', reason: 'docker', message: e.message }));
|
||
this.renderEngineBar();
|
||
if (refresh) this.refresh();
|
||
}
|
||
|
||
engineStatus(s) {
|
||
if (s.id && s.id !== this.engine) return;
|
||
this.engineState = s;
|
||
this.renderEngineBar();
|
||
}
|
||
|
||
engineLabel(e) {
|
||
if (e.kind === 'ssh') return t('{name} (remote)', { name: e.name });
|
||
if (e.kind === 'context') return t('{name} (docker context)', { name: e.name });
|
||
return t('This computer');
|
||
}
|
||
|
||
// where a published port answers: the server's host for a remote engine
|
||
portHost(p) {
|
||
const web = this.engineState?.webHost || 'localhost';
|
||
if (this.engine === 'local' || web === 'localhost') return 'localhost';
|
||
return p.ip && p.ip !== '0.0.0.0' && p.ip !== '127.0.0.1' ? p.ip : web;
|
||
}
|
||
|
||
engineStep(step) {
|
||
if (step === 'probe') return t('Looking for Docker on the server…');
|
||
if (step === 'tunnel') return t('Opening the tunnel…');
|
||
return t('Asking Docker…');
|
||
}
|
||
|
||
engineAdvice(s) {
|
||
switch (s.reason) {
|
||
case 'host-key': return t('The server\'s host key is not known yet: open an SSH session on it once to accept it.');
|
||
case 'auth': return t('The server refused the login: the Docker window needs a key file or the ssh agent (no password can be typed here).');
|
||
case 'network': return t('The server cannot be reached.');
|
||
case 'no-docker': return t('No Docker on the server (no Docker socket found): install or start Docker there.');
|
||
case 'socket-denied': return t('{user} may not use Docker on the server: add it to the docker group (sudo usermod -aG docker {user}), then log in again.', { user: s.detail || '…' });
|
||
case 'forwarding': return t('The server refuses to forward Docker\'s socket (AllowStreamLocalForwarding in its sshd_config).');
|
||
case 'no-ssh': return t('No ssh program on this computer.');
|
||
case 'no-docker-cli': return t('The docker command is not installed on this computer (its client is enough for a remote engine).');
|
||
default: return s.message || t('The engine chosen above does not answer.');
|
||
}
|
||
}
|
||
|
||
renderEngineBar() {
|
||
if (!this.engineBar) return;
|
||
clear(this.engineBar);
|
||
const list = this.engines.length ? this.engines : [{ id: 'local', kind: 'local', name: '', detail: '' }];
|
||
const select = el('select.input.docker-engine-select', { title: t('Docker engine'), onchange: (e) => this.selectEngine(e.target.value) },
|
||
...list.map((e) => el('option', { value: e.id, selected: e.id === this.engine, title: e.detail || '' }, this.engineLabel(e))));
|
||
const s = this.engineState || { state: 'ready' };
|
||
const text = s.state === 'connecting' ? this.engineStep(s.step)
|
||
: s.state === 'ready' ? (s.version ? 'Docker ' + s.version : '')
|
||
: s.state === 'disconnected' ? t('Disconnected: opened again at the next refresh')
|
||
: s.state === 'error' ? this.engineAdvice(s) : '';
|
||
const server = String(s.id || '').startsWith('ssh:') ? s.id.slice(4) : null;
|
||
this.engineBar.append(...[el('span.docker-muted', {}, t('Engine')), select,
|
||
el('span.docker-dot.' + (s.state === 'ready' ? 'on' : s.state === 'connecting' ? 'paused' : 'off')),
|
||
el('span.docker-engine-state' + (s.state === 'error' ? '.error' : ''), { title: s.message || '' }, text),
|
||
s.state === 'error' && server && ['host-key', 'auth'].includes(s.reason) && this.app.terminal
|
||
? el('button.btn.small', { onclick: () => this.sshSession(server) }, icon('terminal'), t('Open an SSH session')) : null,
|
||
s.state === 'error' || s.state === 'disconnected' ? el('button.btn.small', { onclick: () => this.selectEngine(this.engine) }, icon('refresh'), t('Retry')) : null].filter(Boolean));
|
||
}
|
||
|
||
async sshSession(id) {
|
||
try {
|
||
const r = await backend.invoke('ssh.session', { id });
|
||
this.app.showTool?.('terminal', true);
|
||
await this.app.terminal.run(r.line, 'SSH ' + r.label);
|
||
} catch (e) { notify(e.message, 'error', { title: 'SSH' }); }
|
||
}
|
||
|
||
// containers --------------------------------------------------------------------------------------------------
|
||
|
||
async loadContainers() {
|
||
this.ps = await backend.invoke('docker.ps', {}).catch((e) => ({ available: false, error: e.message, containers: [], groups: [] }));
|
||
if (this.tab === 'containers') { this.renderContainers(); this.pollStats(true); }
|
||
}
|
||
|
||
renderContainers() {
|
||
clear(this.body);
|
||
if (!this.ps) { this.body.append(el('div.docker-hint', {}, t('Loading…'))); return; }
|
||
if (!this.ps.available) { this.body.append(this.unavailable(this.ps.error)); return; }
|
||
const search = el('input.input.docker-filter', { placeholder: t('Filter by name, image or project'), value: this.filter,
|
||
oninput: (e) => { this.filter = e.target.value; this.renderContainerList(list); } });
|
||
const list = el('div.docker-list');
|
||
this.body.append(el('div.docker-toolbar', {}, search), list);
|
||
this.renderContainerList(list);
|
||
}
|
||
|
||
renderContainerList(list) {
|
||
clear(list);
|
||
this.statCells.clear();
|
||
const f = this.filter.trim().toLowerCase();
|
||
const match = (c) => !f || [c.name, c.image, c.project, c.service].some((s) => String(s).toLowerCase().includes(f));
|
||
if (!this.ps.containers.length) { list.append(el('div.docker-hint', {}, this.engine === 'local' ? t('No containers on this computer.') : t('No containers on this engine.'))); return; }
|
||
for (const g of this.ps.groups) {
|
||
const shown = g.containers.filter(match);
|
||
if (!shown.length) continue;
|
||
if (g.project) {
|
||
const folded = this.folded.has(g.project);
|
||
list.append(el('div.docker-group', {},
|
||
el('button.docker-fold', { onclick: () => this.fold(g.project, list) }, icon(folded ? 'expand' : 'collapse')),
|
||
el('span.docker-group-name', { title: g.dir || '' }, g.project),
|
||
el('span.docker-muted', {}, t('{running}/{total} running', { running: g.running, total: g.containers.length })),
|
||
el('span.docker-spacer'),
|
||
this.btn('Up (docker compose up -d)', 'play', () => this.compose(g, 'up'), !g.files.length),
|
||
this.btn('Stop the project', 'stop', () => this.compose(g, 'stop')),
|
||
this.btn('Down: remove the project\'s containers and networks', 'trash', () => this.compose(g, 'down'))));
|
||
if (folded) continue;
|
||
} else if (this.ps.groups.length > 1) {
|
||
list.append(el('div.docker-group', {}, el('span.docker-group-name', {}, t('Other containers'))));
|
||
}
|
||
for (const c of shown) list.append(this.containerRow(c, !!g.project));
|
||
}
|
||
}
|
||
|
||
fold(project, list) {
|
||
if (this.folded.has(project)) this.folded.delete(project); else this.folded.add(project);
|
||
prefs.set('dockerFolded', [...this.folded]);
|
||
this.renderContainerList(list);
|
||
}
|
||
|
||
btn(title, ico, fn, disabled = false) {
|
||
return el('button.icon-btn', { title: t(title), disabled, onclick: (e) => { e.stopPropagation(); fn(); } }, icon(ico));
|
||
}
|
||
|
||
containerRow(c, inGroup) {
|
||
const running = c.state === 'running';
|
||
const stat = el('span.docker-stat');
|
||
this.statCells.set(c.id.slice(0, 12), stat);
|
||
this.fillStat(stat, this.stats[c.id.slice(0, 12)], running);
|
||
const ports = c.ports.map((p) => el('a.docker-port', { href: '#', title: `${p.ip}:${p.host} → ${p.container}`,
|
||
onclick: (e) => { e.preventDefault(); this.app.openUrl(`http://${this.portHost(p)}:${p.host}`); } }, String(p.host)));
|
||
return el('div.docker-row' + (inGroup ? '.indent' : ''), {},
|
||
el('span.docker-dot.' + (running ? 'on' : c.state === 'paused' ? 'paused' : c.state === 'restarting' ? 'paused' : 'off'), { title: c.status }),
|
||
el('div.docker-main', {},
|
||
el('div.docker-name', { title: c.id }, c.service && inGroup ? c.service : c.name, el('span.docker-muted', {}, ' ' + c.image)),
|
||
el('div.docker-sub', {}, el('span.docker-muted', {}, c.status), ports.length ? el('span.docker-ports', {}, ...ports) : null)),
|
||
stat,
|
||
el('div.docker-actions', {},
|
||
running ? this.btn('Stop', 'stop', () => this.containerAction(c, 'stop')) : this.btn('Start', 'play', () => this.containerAction(c, 'start')),
|
||
this.btn('Restart', 'undo', () => this.containerAction(c, 'restart')),
|
||
this.btn('Logs', 'logfile', () => this.followLogs(c)),
|
||
this.btn('Open a shell in the terminal', 'terminal', () => this.shell(c), !running || !this.app.terminal),
|
||
this.btn('Inspect', 'eye', () => this.inspect('container', c.id, c.name)),
|
||
this.btn('Remove', 'trash', () => this.removeContainer(c))));
|
||
}
|
||
|
||
fillStat(node, s, running) {
|
||
clear(node);
|
||
if (!running) return;
|
||
if (!s) { node.append(el('span.docker-muted', {}, '…')); return; }
|
||
node.append(el('span', { title: t('CPU') }, s.cpu.toFixed(1) + '%'), el('span.docker-muted', { title: s.mem }, String(s.mem).split('/')[0].trim()));
|
||
}
|
||
|
||
async pollStats(now = false) {
|
||
if (this.statsBusy || this.tab !== 'containers' || !this.ps?.available || !(now || (this.visible() && !document.hidden && document.hasFocus()))) return;
|
||
if (!this.ps.containers.some((c) => c.state === 'running')) return;
|
||
this.statsBusy = true;
|
||
try {
|
||
this.stats = await backend.invoke('docker.stats', {});
|
||
for (const c of this.ps.containers) {
|
||
const id = c.id.slice(0, 12);
|
||
const cell = this.statCells.get(id);
|
||
if (cell) this.fillStat(cell, this.stats[id], c.state === 'running');
|
||
}
|
||
} catch { /* Docker stopped meanwhile: the next refresh says so */ } finally { this.statsBusy = false; }
|
||
}
|
||
|
||
containerAction(c, action) {
|
||
return this.run(t('Docker'), () => backend.invoke('docker.container', { id: c.id, action }));
|
||
}
|
||
|
||
async removeContainer(c) {
|
||
const running = c.state === 'running';
|
||
if (!await confirm(t('Remove the container {name}?', { name: c.name }),
|
||
t(running ? 'It is running: it will be stopped and removed. Its data outside volumes is lost.' : 'Its data outside volumes is lost.'), { ok: t('Remove'), danger: true })) return;
|
||
await this.run(t('Docker'), () => backend.invoke('docker.container', { id: c.id, action: 'rm', force: running }));
|
||
}
|
||
|
||
async compose(g, action) {
|
||
if (action === 'down' && !await confirm(t('Down the project {name}?', { name: g.project }),
|
||
t('Its containers and networks are removed (its named volumes are kept).'), { ok: t('Down'), danger: true })) return;
|
||
const label = { up: 'Up', stop: 'Stop', down: 'Down' }[action];
|
||
await this.startStream(`${t(label)} ${g.project}`, () => backend.invoke('docker.compose', { project: g.project, action, files: g.files, dir: g.dir, remote: this.engine !== 'local' }));
|
||
}
|
||
|
||
followLogs(c) {
|
||
return this.startStream(t('Logs: {name}', { name: c.name }), () => backend.invoke('docker.logs.follow', { id: c.id, tail: 500 }), { logs: true });
|
||
}
|
||
|
||
async shell(c) {
|
||
const r = await this.run(t('Docker'), () => backend.invoke('docker.shell', { id: c.id }), false);
|
||
if (!r) return;
|
||
this.app.showTool?.('terminal', true);
|
||
this.app.terminal.run(r.command, c.name);
|
||
}
|
||
|
||
// inspect: a JSON tree ----------------------------------------------------------------------------------------
|
||
|
||
async inspect(kind, id, name) {
|
||
const data = await this.run(t('Inspect'), () => backend.invoke('docker.inspect', { kind, id }), false);
|
||
if (data == null) return;
|
||
const tree = el('div.docker-json');
|
||
tree.append(jsonNode(null, data, 0));
|
||
dialog({ title: `${t('Inspect')} ${name || id}`, wide: true, body: tree,
|
||
buttons: [{ label: 'Copy', action: () => { navigator.clipboard?.writeText(JSON.stringify(data, null, 2)); return false; } }, { label: 'Close', primary: true }] });
|
||
}
|
||
|
||
// images ------------------------------------------------------------------------------------------------------
|
||
|
||
async loadImages() {
|
||
this.images = await backend.invoke('docker.images', {}).catch((e) => ({ error: e.message }));
|
||
if (this.tab === 'images') this.renderImages();
|
||
}
|
||
|
||
renderImages() {
|
||
clear(this.body);
|
||
if (!this.images) { this.body.append(el('div.docker-hint', {}, t('Loading…'))); return; }
|
||
if (this.images.error) { this.body.append(this.unavailable(this.images.error)); return; }
|
||
const dangling = this.images.filter((i) => i.dangling).length;
|
||
this.body.append(el('div.docker-toolbar', {},
|
||
el('span.docker-muted', {}, t('{count} images', { count: this.images.length })), el('span.docker-spacer'),
|
||
el('button.btn.small', { disabled: !dangling, onclick: () => this.prune(dangling) }, icon('trash'), t('Prune dangling images ({count})', { count: dangling }))));
|
||
const list = el('div.docker-list');
|
||
for (const i of this.images) {
|
||
list.append(el('div.docker-row', {},
|
||
el('span.docker-dot.' + (i.dangling ? 'off' : 'image')),
|
||
el('div.docker-main', {},
|
||
el('div.docker-name', { title: i.id }, i.dangling ? el('span.docker-muted', {}, t('<none> (dangling)')) : i.ref),
|
||
el('div.docker-sub', {}, el('span.docker-muted', {}, `${i.id} · ${i.createdSince || i.created}`))),
|
||
el('span.docker-stat', {}, i.size),
|
||
el('div.docker-actions', {},
|
||
this.btn('Run…', 'play', () => this.runForm(i.ref), i.dangling),
|
||
this.btn('Inspect', 'eye', () => this.inspect('image', i.id, i.ref)),
|
||
this.btn('Remove', 'trash', () => this.removeImage(i)))));
|
||
}
|
||
this.body.append(list);
|
||
}
|
||
|
||
async removeImage(i) {
|
||
if (!await confirm(t('Remove the image {name}?', { name: i.dangling ? i.id : i.ref }), t('It can be pulled again later.'), { ok: t('Remove'), danger: true })) return;
|
||
await this.run(t('Docker'), () => backend.invoke('docker.image.rm', { id: i.dangling ? i.id : i.ref }));
|
||
}
|
||
|
||
async prune(count) {
|
||
if (!await confirm(t('Prune dangling images?'), t('{count} images without a tag are removed.', { count }), { ok: t('Prune'), danger: true })) return;
|
||
const r = await this.run(t('Docker'), () => backend.invoke('docker.image.prune', {}));
|
||
if (r) notify(lines(r.output).pop() || t('Done'), 'success', { title: 'Docker' });
|
||
}
|
||
|
||
// run an image: a small form ----------------------------------------------------------------------------------
|
||
|
||
runForm(image) {
|
||
const field = (label, input) => el('label.docker-field', {}, el('span', {}, t(label)), input);
|
||
const f = {
|
||
image: el('input.input', { value: image }),
|
||
name: el('input.input', { placeholder: t('optional') }),
|
||
ports: el('textarea.input', { rows: 2, placeholder: '8080:80' }),
|
||
env: el('textarea.input', { rows: 2, placeholder: 'KEY=value' }),
|
||
volumes: el('textarea.input', { rows: 2, placeholder: 'data:/var/lib/data' }),
|
||
restart: el('select.input', {}, ...['no', 'unless-stopped', 'always', 'on-failure'].map((v) => el('option', { value: v }, v))),
|
||
};
|
||
dialog({ title: t('Run a container'), body: el('div.docker-form', {},
|
||
field('Image', f.image), field('Name', f.name), field('Ports (host:container, one per line)', f.ports),
|
||
field('Environment (NAME=value, one per line)', f.env), field('Volumes (source:/path/in/container, one per line)', f.volumes), field('Restart', f.restart)),
|
||
buttons: [{ label: 'Cancel' }, { label: 'Run', primary: true, action: async () => {
|
||
const r = await backend.invoke('docker.run', { image: f.image.value, name: f.name.value, ports: lines(f.ports.value), env: lines(f.env.value),
|
||
volumes: lines(f.volumes.value), restart: f.restart.value });
|
||
notify(t('Container {id} started.', { id: r.id }), 'success', { title: 'Docker' });
|
||
this.setTab('containers');
|
||
} }] });
|
||
}
|
||
|
||
// Docker Hub --------------------------------------------------------------------------------------------------
|
||
|
||
renderHub() {
|
||
clear(this.body);
|
||
if (this.hub.repo) { this.renderRepo(); return; }
|
||
const input = el('input.input', { placeholder: t('Search Docker Hub (nginx, postgres, redis…)'), value: this.hub.query,
|
||
onkeydown: (e) => { if (e.key === 'Enter') this.search(input.value); } });
|
||
this.body.append(el('div.docker-toolbar', {}, input, el('button.btn.small', { onclick: () => this.search(input.value) }, icon('search'), t('Search'))));
|
||
if (this.hub.busy) this.body.append(el('div.docker-hint', {}, t('Searching…')));
|
||
else if (this.hub.error) this.body.append(el('pre.docker-error', {}, this.hub.error));
|
||
else if (this.hub.results && !this.hub.results.results.length) this.body.append(el('div.docker-hint', {}, t('Nothing found.')));
|
||
const list = el('div.docker-list');
|
||
for (const r of this.hub.results?.results || []) {
|
||
list.append(el('div.docker-row.click', { onclick: () => this.openRepo(r.name) },
|
||
el('span.docker-dot.image'),
|
||
el('div.docker-main', {},
|
||
el('div.docker-name', {}, r.name, r.official ? el('span.docker-badge', {}, t('Official')) : null),
|
||
el('div.docker-sub', {}, el('span.docker-muted', {}, r.description))),
|
||
el('span.docker-stat', {}, el('span', { title: t('Stars') }, '★ ' + num(r.stars)), el('span.docker-muted', { title: t('Pulls') }, '↓ ' + num(r.pulls)))));
|
||
}
|
||
this.body.append(list);
|
||
if (!this.hub.results) setTimeout(() => input.focus(), 0);
|
||
}
|
||
|
||
async search(query) {
|
||
this.hub.query = query.trim();
|
||
prefs.set('dockerHubQuery', this.hub.query);
|
||
if (!this.hub.query) return;
|
||
this.hub.busy = true; this.hub.error = null; this.renderHub();
|
||
try { this.hub.results = await backend.invoke('docker.hub.search', { query: this.hub.query }); } catch (e) { this.hub.error = e.message; }
|
||
this.hub.busy = false;
|
||
if (this.tab === 'hub') this.renderHub();
|
||
}
|
||
|
||
async openRepo(name) {
|
||
this.hub.repo = { name, loading: true };
|
||
this.renderHub();
|
||
try { this.hub.repo = await backend.invoke('docker.hub.repo', { name }); } catch (e) { this.hub.repo = { name, error: e.message }; }
|
||
if (this.tab === 'hub') this.renderHub();
|
||
}
|
||
|
||
renderRepo() {
|
||
const r = this.hub.repo;
|
||
const back = el('button.btn.small', { onclick: () => { this.hub.repo = null; this.renderHub(); } }, '← ' + t('Back'));
|
||
this.body.append(el('div.docker-toolbar', {}, back, el('b', {}, r.name), r.official ? el('span.docker-badge', {}, t('Official')) : null, el('span.docker-spacer'),
|
||
r.url ? el('button.btn.small', { onclick: () => this.app.openUrl(r.url) }, icon('globe'), t('Open on Docker Hub')) : null));
|
||
if (r.loading) { this.body.append(el('div.docker-hint', {}, t('Loading…'))); return; }
|
||
if (r.error) { this.body.append(el('pre.docker-error', {}, r.error)); return; }
|
||
this.body.append(el('div.docker-repo-head', {},
|
||
el('span', {}, '★ ' + num(r.stars)), el('span', {}, '↓ ' + num(r.pulls)), r.updated ? el('span.docker-muted', {}, t('Updated {date}', { date: day(r.updated) })) : null),
|
||
r.description ? el('p.docker-desc', {}, r.description) : null);
|
||
const tags = el('div.docker-list');
|
||
for (const tag of r.tags) {
|
||
const ref = `${r.name}:${tag.name}`;
|
||
tags.append(el('div.docker-row', {},
|
||
el('div.docker-main', {}, el('div.docker-name', {}, tag.name),
|
||
el('div.docker-sub', {}, el('span.docker-muted', {}, [day(tag.updated), tag.architectures.slice(0, 6).join(', ')].filter(Boolean).join(' · ')))),
|
||
el('span.docker-stat', {}, bytes(tag.size)),
|
||
el('div.docker-actions', {},
|
||
this.yamlOpen() ? el('button.btn.small', { title: `image: ${ref}`, onclick: () => this.insertImage(ref) }, icon('edit'), t('Insert into the editor')) : null,
|
||
el('button.btn.small', { onclick: () => this.pull(ref) }, icon('download'), t('Pull')),
|
||
this.btn('Run…', 'play', () => this.runForm(ref)))));
|
||
}
|
||
this.body.append(el('div.docker-section', {}, t('Tags')), tags);
|
||
if (r.fullDescription) {
|
||
const more = el('details.docker-readme', {}, el('summary', {}, t('Description')),
|
||
el('div.md-body', {}, ...renderMarkdown(r.fullDescription, (url) => this.app.openUrl(url))));
|
||
this.body.append(more);
|
||
}
|
||
}
|
||
|
||
pull(image) {
|
||
return this.startStream(t('Pull {image}', { image }), () => backend.invoke('docker.pull', { image }), { pull: true });
|
||
}
|
||
|
||
/** the YAML file being edited (the place a Docker Hub tag is inserted) */
|
||
yamlOpen() { return /\.ya?ml$/i.test(this.app.editors?.activePath() || ''); }
|
||
|
||
/** "image: name:tag" on the editor's line (its image replaced, or a new line below) */
|
||
insertImage(ref) {
|
||
const ed = this.app.editors.editor();
|
||
const model = ed?.getModel();
|
||
if (!model || !this.yamlOpen()) { copyText(`image: ${ref}`); notify(t('Copied: {text}', { text: `image: ${ref}` }), 'info'); return; }
|
||
const n = ed.getPosition()?.lineNumber || 1;
|
||
const text = model.getLineContent(n);
|
||
const end = model.getLineMaxColumn(n);
|
||
const next = withImage(text, ref);
|
||
if (next !== null) ed.executeEdits('docker-hub', [{ range: new monaco.Range(n, 1, n, end), text: next }]);
|
||
else ed.executeEdits('docker-hub', [{ range: new monaco.Range(n, end, n, end), text: `\n${/^\s*(?:-\s+)?/.exec(text)[0].replace('-', ' ')}${/:\s*$/.test(text) ? ' ' : ''}image: ${ref}` }]);
|
||
ed.focus();
|
||
notify(t('Inserted: {text}', { text: `image: ${ref}` }), 'success', { title: 'Docker Hub' });
|
||
}
|
||
|
||
// compose -----------------------------------------------------------------------------------------------------
|
||
|
||
async loadCompose() {
|
||
const [stacks, ps, web] = await Promise.all([backend.invoke('compose.stacks', {}).catch((e) => ({ error: e.message })),
|
||
backend.invoke('docker.ps', {}).catch(() => null), backend.invoke('web.settings', {}).catch(() => null)]);
|
||
this.web = web;
|
||
for (const s of Array.isArray(stacks) ? stacks : []) s.check = this.stacks?.find?.((o) => o.dir === s.dir)?.check || null;
|
||
this.stacks = stacks;
|
||
if (ps) this.ps = ps;
|
||
if (this.tab === 'compose') this.renderCompose();
|
||
}
|
||
|
||
/** the running Compose project of a stack (from docker ps: the folder its files are in) */
|
||
runningGroup(s) {
|
||
const root = String(this.app.project?.root || '').replace(/\\/g, '/').replace(/\/$/, '');
|
||
const dir = s.dir ? `${root}/${s.dir}` : root;
|
||
return (this.ps?.groups || []).find((g) => g.project && (String(g.dir).replace(/\\/g, '/') === dir
|
||
|| (g.files || []).some((f) => s.files.some((mine) => String(f).replace(/\\/g, '/').endsWith('/' + mine))))) || null;
|
||
}
|
||
|
||
renderCompose() {
|
||
clear(this.body);
|
||
this.body.append(el('div.docker-toolbar', {}, el('span.docker-muted', {}, t('The Docker Compose files of this project, by folder.')), el('span.docker-spacer'),
|
||
el('button.btn.small', { onclick: () => this.setTab('hub') }, icon('search'), t('Search Docker Hub'))));
|
||
if (!this.stacks) { this.body.append(el('div.docker-hint', {}, t('Loading…'))); return; }
|
||
if (this.stacks.error) { this.body.append(el('pre.docker-error', {}, this.stacks.error)); return; }
|
||
if (this.web) this.body.append(this.renderWebSetup(this.web));
|
||
if (!this.stacks.length) { this.body.append(el('div.docker-hint', {}, t('No compose file in this project.'))); return; }
|
||
const list = el('div.docker-list');
|
||
this.body.append(list);
|
||
const kinds = { jumphp: t('JumPHP site'), dunglas: 'symfony-docker', compose: 'Docker Compose' };
|
||
for (const s of this.stacks) {
|
||
const g = this.runningGroup(s);
|
||
list.append(el('div.docker-group', {},
|
||
el('span.docker-group-name', {}, s.dir || t('(project root)')), el('span.docker-badge', {}, kinds[s.kind] || s.kind),
|
||
g ? el('span.docker-muted', {}, t('{running}/{total} running', { running: g.running, total: g.containers.length })) : null,
|
||
el('span.docker-spacer'),
|
||
this.btn('Add a service…', 'plus', () => this.addServiceDialog(s)),
|
||
this.btn('Check (docker compose config)', 'check', () => this.checkStack(s)),
|
||
this.btn('Apply (restart the changed containers)', 'play', () => this.applyStack(s, g))));
|
||
if (s.kind === 'jumphp') list.append(el('div.docker-hint', {}, t('Its stack is written into .jumphp/compose.yaml at each start; your changes go into compose.override.yaml, merged over it.')));
|
||
s.files.forEach((f, i) => list.append(this.fileRow(f, i > 0 ? t('merged over the file above') : s.files.length > 1 ? t('base') : '', f === s.generated)));
|
||
if (!s.overrideExists) {
|
||
list.append(el('div.docker-row', {}, el('div.docker-main', {}, el('div.docker-name.docker-muted', {}, s.override)),
|
||
el('div.docker-actions', {}, el('button.btn.small', { onclick: () => this.createOverride(s) }, icon('plus'), t('Create')))));
|
||
}
|
||
for (const f of s.others) list.append(this.fileRow(f, t('not read by default (docker compose -f)')));
|
||
if (s.check) {
|
||
list.append(s.check.ok ? el('div.docker-hint', {}, '✔ ' + t('docker compose config: no problem.'))
|
||
: el('pre.docker-error', {}, s.check.output || t('failed')));
|
||
}
|
||
}
|
||
}
|
||
|
||
/** a web site: its PHP version and its Docker setup, each changed by bin/jumphp (web:php / web:docker) in the Run window */
|
||
renderWebSetup(w) {
|
||
const SETUPS = {
|
||
jumphp: [t('JumPHP stack'), t('bin/jumphp web:serve writes .jumphp/compose.yaml: FrankenPHP on the project\'s PHP, its database, live reload; compose.override.yaml merged over it. symfony-docker\'s files, if any, stay in the folder unused (its compose.override.yaml is kept aside).')],
|
||
dunglas: ['symfony-docker', t('symfony-docker (dunglas): its Dockerfile, compose.yaml and frankenphp/ are added (your compose files kept as *.before-symfony-docker), its Dockerfile set to the project\'s PHP; the database is the one of its compose.yaml.')],
|
||
compose: [t('My own compose service'), t('Your compose file is the stack: web:serve runs docker compose up, the Console and Composer run in the service you choose. Its image decides the PHP (a version chosen here changes its tag).')],
|
||
};
|
||
const php = el('select.input', {},
|
||
el('option', { value: 'auto', selected: !w.setting }, t('Auto: what Composer needs (PHP {version})', { version: w.auto })),
|
||
...(w.available || []).map((v) => el('option', { value: v, selected: w.setting === v }, `PHP ${v}`)));
|
||
const setup = el('select.input', {}, ...Object.entries(SETUPS).filter(([k]) => k !== 'dunglas' || w.symfony)
|
||
.map(([k, [label]]) => el('option', { value: k, selected: w.setup === k }, label)));
|
||
const service = el('select.input', {}, ...(w.services || []).map((n) => el('option', { value: n, selected: (w.service || 'php') === n }, n)));
|
||
const explain = el('div.docker-muted');
|
||
const serviceRow = el('label.docker-setup-row', {}, t('PHP service'), service, el('span.docker-muted', {}, w.composeFile || ''));
|
||
const update = () => {
|
||
explain.textContent = SETUPS[setup.value][1];
|
||
serviceRow.style.display = setup.value === 'compose' ? '' : 'none';
|
||
};
|
||
setup.addEventListener('change', update);
|
||
update();
|
||
const source = w.source === 'web.json' ? t('chosen for this project') : w.source === 'Dockerfile' ? t('from its Dockerfile')
|
||
: w.source === 'compose' ? t('from the image of its service') : w.source === 'composer' ? t('what Composer needs: {detail}', { detail: w.detail }) : t('the default');
|
||
const apply = async (call, payload) => {
|
||
const r = await this.run(t('Docker'), () => backend.invoke(call, payload), false);
|
||
if (!r) return;
|
||
this.app.showTool?.('run');
|
||
const off = backend.on('run.exit', (p) => { if (p.id === r.id) { off?.(); this.loadCompose(); } });
|
||
};
|
||
return el('div.docker-setup', {},
|
||
el('div.docker-setup-row', {}, el('b', {}, 'PHP'), php,
|
||
el('button.btn.small', { onclick: () => apply('web.setPhp', { version: php.value }) }, t('Apply')),
|
||
el('span.docker-muted', {}, w.php ? `PHP ${w.php} · ${source}` : source)),
|
||
el('div.docker-setup-row', {}, el('b', {}, t('Docker setup')), setup,
|
||
el('button.btn.small', { onclick: () => {
|
||
if (setup.value === 'compose' && !service.value) { notify(t('This compose file has no service.'), 'error', { title: 'Docker Compose' }); return; }
|
||
apply('web.setDocker', { setup: setup.value, service: setup.value === 'compose' ? service.value : '' });
|
||
} }, t('Apply'))),
|
||
serviceRow, explain,
|
||
el('div.docker-muted', {}, t('The same PHP runs the site, Composer and the Console: changing it rebuilds the image (the Run window shows it).')));
|
||
}
|
||
|
||
fileRow(path, note, generated = false) {
|
||
return el('div.docker-row', { style: { cursor: 'pointer' }, onclick: () => this.app.editors.open(path) },
|
||
el('div.docker-main', {}, el('div.docker-name', {}, fileIcon(path), ' ', path, generated ? el('span.docker-badge', {}, t('generated')) : null),
|
||
note ? el('div.docker-sub', {}, el('span.docker-muted', {}, note)) : null),
|
||
el('div.docker-actions', {}, this.btn('Open', 'file', () => this.app.editors.open(path))));
|
||
}
|
||
|
||
async createOverride(s) {
|
||
const r = await this.run(t('Docker'), () => backend.invoke('compose.override', { dir: s.dir }), false);
|
||
if (r) { await this.app.editors.open(r.path); this.app.tree?.refresh?.(); this.loadCompose(); }
|
||
}
|
||
|
||
async addServiceDialog(s) {
|
||
const templates = await this.run(t('Docker'), () => backend.invoke('compose.templates', {}), false);
|
||
if (!templates) return;
|
||
// a JumPHP site: only its override is the project's; elsewhere the override when there is one, else the main file
|
||
const targets = s.kind === 'jumphp' ? [s.override] : [...new Set([...(s.overrideExists ? [s.override] : []), ...s.files, ...(s.overrideExists ? [] : [s.override])])];
|
||
let chosen = templates[0].name;
|
||
const rows = el('div.docker-list');
|
||
const draw = () => {
|
||
clear(rows);
|
||
for (const tpl of templates) {
|
||
rows.append(el('div.docker-row' + (tpl.name === chosen ? '.on' : ''), { style: { cursor: 'pointer', background: tpl.name === chosen ? 'var(--selection, rgba(80,120,200,.25))' : '' },
|
||
onclick: () => { chosen = tpl.name; name.value = tpl.name; draw(); } },
|
||
el('div.docker-main', {}, el('div.docker-name', {}, tpl.label), el('div.docker-sub', {}, el('span.docker-muted', {}, `image: ${tpl.image}`)))));
|
||
}
|
||
};
|
||
const name = el('input.input', { value: chosen, spellcheck: false });
|
||
const file = el('select.input', {}, ...targets.map((f) => el('option', { value: f }, f)));
|
||
draw();
|
||
dialog({ title: t('Add a service'), wide: true, body: el('div.docker-form', {}, rows,
|
||
el('label', {}, t('Name'), name), el('label', {}, t('File'), file)),
|
||
buttons: [{ label: t('Cancel') }, { label: t('Add'), primary: true, action: async () => {
|
||
const r = await this.run(t('Docker'), () => backend.invoke('compose.addService', { path: file.value, template: chosen, name: name.value.trim() || null }), false);
|
||
if (!r) return;
|
||
await this.app.editors.reloadFromDisk?.([r.path]);
|
||
await this.app.editors.open(r.path, { line: r.line });
|
||
this.app.tree?.refresh?.();
|
||
notify(t('The service {name} was added to {path}.', { name: r.name, path: r.path }), 'success', { title: 'Docker Compose' });
|
||
this.loadCompose();
|
||
} }] });
|
||
}
|
||
|
||
async checkStack(s) {
|
||
await this.app.editors.saveAll?.(true);
|
||
s.check = { ok: false, output: t('Checking…') };
|
||
this.renderCompose();
|
||
const r = await backend.invoke('compose.validate', { dir: s.dir }).catch((e) => ({ ok: false, output: e.message, problems: {} }));
|
||
s.check = r;
|
||
// its problems at their line (Problems window, editor markers): cleared for the stack's files first
|
||
for (const f of [...s.files, ...s.others]) this.app.setProblems?.(f, (r.problems || {})[f] || [], 'compose');
|
||
for (const [f, list] of Object.entries(r.problems || {})) if (!s.files.includes(f)) this.app.setProblems?.(f, list, 'compose');
|
||
if (!r.ok && Object.keys(r.problems || {}).length) this.app.showTool?.('problems');
|
||
if (this.tab === 'compose') this.renderCompose();
|
||
}
|
||
|
||
async applyStack(s, g) {
|
||
await this.app.editors.saveAll?.(true);
|
||
if (s.kind !== 'compose') {
|
||
const config = this.app.runner?.configs.find((c) => c.id === 'web:up');
|
||
if (config) { this.app.runner.start(config); this.app.showTool?.('run'); return; }
|
||
}
|
||
const base = (s.dir || String(this.app.project?.name || 'app')).split('/').pop().toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'app';
|
||
await this.startStream(`${t('Apply')} ${g?.project || base}`, () => backend.invoke('docker.compose', { project: g?.project || base, action: 'up', files: s.files, dir: s.dir || '.' }));
|
||
}
|
||
|
||
// volumes and networks ----------------------------------------------------------------------------------------
|
||
|
||
async loadOther() {
|
||
const [v, n] = await Promise.all([backend.invoke('docker.volumes', {}).catch((e) => ({ error: e.message })),
|
||
backend.invoke('docker.networks', {}).catch((e) => ({ error: e.message }))]);
|
||
this.volumes = v; this.networks = n;
|
||
if (this.tab === 'other') this.renderOther();
|
||
}
|
||
|
||
renderOther() {
|
||
clear(this.body);
|
||
if (!this.volumes) { this.body.append(el('div.docker-hint', {}, t('Loading…'))); return; }
|
||
if (this.volumes.error) { this.body.append(this.unavailable(this.volumes.error)); return; }
|
||
const section = (title, items, row) => {
|
||
this.body.append(el('div.docker-section', {}, t(title), el('span.docker-muted', {}, ` (${items.length})`)));
|
||
const list = el('div.docker-list');
|
||
for (const it of items) list.append(row(it));
|
||
this.body.append(list);
|
||
};
|
||
section('Volumes', this.volumes, (v) => el('div.docker-row', {},
|
||
el('div.docker-main', {}, el('div.docker-name', { title: v.name }, v.name), el('div.docker-sub', {}, el('span.docker-muted', {}, `${v.driver} · ${v.mountpoint}`))),
|
||
el('div.docker-actions', {},
|
||
this.btn('Inspect', 'eye', () => this.inspect('volume', v.name, v.name)),
|
||
this.btn('Remove', 'trash', () => this.removeOther('volume', v.name)))));
|
||
if (this.networks?.error) return;
|
||
section('Networks', this.networks || [], (n) => el('div.docker-row', {},
|
||
el('div.docker-main', {}, el('div.docker-name', {}, n.name), el('div.docker-sub', {}, el('span.docker-muted', {}, `${n.driver} · ${n.scope} · ${n.id}`))),
|
||
el('div.docker-actions', {},
|
||
this.btn('Inspect', 'eye', () => this.inspect('network', n.id, n.name)),
|
||
this.btn('Remove', 'trash', () => this.removeOther('network', n.name), n.builtin))));
|
||
}
|
||
|
||
async removeOther(kind, name) {
|
||
const text = kind === 'volume' ? 'Its data is lost for good.' : 'Containers still attached to it make Docker refuse.';
|
||
if (!await confirm(t(kind === 'volume' ? 'Remove the volume {name}?' : 'Remove the network {name}?', { name }), t(text), { ok: t('Remove'), danger: true })) return;
|
||
await this.run(t('Docker'), () => backend.invoke(kind === 'volume' ? 'docker.volume.rm' : 'docker.network.rm', { id: name }));
|
||
}
|
||
|
||
// the output pane: logs followed, pulls, compose ---------------------------------------------------------------
|
||
|
||
async startStream(title, start, { logs = false, pull = false } = {}) {
|
||
if (this.output && !this.output.done) backend.invoke('docker.stream.stop', { stream: this.output.stream }).catch(() => null);
|
||
this.output = { stream: null, title, text: '', done: false, code: null, follow: true, logs, pull: pull ? { layers: new Map() } : null };
|
||
this.renderOutput();
|
||
try {
|
||
const r = await start();
|
||
this.output.stream = r.stream;
|
||
return r.stream;
|
||
} catch (e) {
|
||
this.output.text = e.message + '\n';
|
||
this.output.done = true;
|
||
this.renderOutput();
|
||
return null;
|
||
}
|
||
}
|
||
|
||
streamOutput(p) {
|
||
const o = this.output;
|
||
if (o && o.stream === p.stream) {
|
||
o.text = (o.text + p.chunk).slice(-OUTPUT_MAX);
|
||
if (o.pull) {
|
||
for (const m of p.chunk.matchAll(/^([0-9a-f]{12}): (.+)$/gm)) o.pull.layers.set(m[1], m[2].trim());
|
||
}
|
||
this.appendOutput(p.chunk);
|
||
}
|
||
this.waiters.get(p.stream)?.chunks.push(p.chunk);
|
||
}
|
||
|
||
streamExit(p) {
|
||
const o = this.output;
|
||
if (o && o.stream === p.stream) {
|
||
o.done = true; o.code = p.code;
|
||
this.renderOutput();
|
||
if (!o.logs) {
|
||
notify(t(p.code === 0 ? '{title}: done.' : '{title}: failed.', { title: o.title }), p.code === 0 ? 'success' : 'error', { title: 'Docker' });
|
||
this.refresh();
|
||
}
|
||
}
|
||
const w = this.waiters.get(p.stream);
|
||
if (w) { this.waiters.delete(p.stream); w.resolve({ code: p.code, output: w.chunks.join('').slice(-4000) }); }
|
||
}
|
||
|
||
pullProgress() {
|
||
const layers = [...this.output.pull.layers.values()];
|
||
if (!layers.length) return null;
|
||
const done = layers.filter((s) => /complete|already exists/i.test(s)).length;
|
||
return el('span.docker-progress', { title: t('{done} of {total} layers', { done, total: layers.length }) }, progressBar(done / layers.length), `${done}/${layers.length}`);
|
||
}
|
||
|
||
renderOutput() {
|
||
const n = this.outputNode;
|
||
if (!n) return;
|
||
clear(n);
|
||
const o = this.output;
|
||
n.hidden = !o;
|
||
if (!o) return;
|
||
const follow = el('label.docker-follow', {}, el('input', { type: 'checkbox', checked: o.follow, onchange: (e) => { o.follow = e.target.checked; if (o.follow) this.pre.scrollTop = this.pre.scrollHeight; } }), t('Follow'));
|
||
n.append(el('div.docker-output-head', {},
|
||
el('b', {}, o.title),
|
||
o.done ? el('span.docker-muted', {}, o.code === 0 || o.logs ? t('ended') : t('failed (code {code})', { code: o.code })) : el('span.docker-muted', {}, t('running…')),
|
||
o.pull && !o.done ? this.pullProgress() : null,
|
||
el('span.docker-spacer'), follow,
|
||
!o.done ? this.btn('Stop', 'stop', () => backend.invoke('docker.stream.stop', { stream: o.stream }).catch(() => null)) : null,
|
||
this.btn('Clear', 'minus', () => { o.text = ''; this.pre.textContent = ''; }),
|
||
this.btn('Close', 'close', () => {
|
||
if (!o.done) backend.invoke('docker.stream.stop', { stream: o.stream }).catch(() => null);
|
||
this.output = null; this.renderOutput();
|
||
})));
|
||
this.pre = el('pre.docker-pre', {}, o.text);
|
||
n.append(this.pre);
|
||
if (o.follow) setTimeout(() => { this.pre.scrollTop = this.pre.scrollHeight; }, 0);
|
||
}
|
||
|
||
appendOutput(chunk) {
|
||
if (!this.pre) return;
|
||
if (this.output.pull) { this.renderOutput(); return; } // the progress bar moves with each line
|
||
this.pre.append(chunk);
|
||
if (this.pre.textContent.length > OUTPUT_MAX) this.pre.textContent = this.output.text;
|
||
if (this.output.follow) this.pre.scrollTop = this.pre.scrollHeight;
|
||
}
|
||
|
||
/** Claude's docker_pull: shown in the window, resolved at the end. */
|
||
async pullAndWait(image) {
|
||
this.app.showTool?.('docker');
|
||
const stream = await this.pull(image);
|
||
if (stream == null) throw new Error(this.output?.text || 'docker pull did not start');
|
||
return new Promise((resolve) => this.waiters.set(stream, { resolve, chunks: [this.output?.text || ''] }));
|
||
}
|
||
}
|
||
|
||
/** One value of an inspect: objects and arrays fold (the first two levels open). */
|
||
function jsonNode(key, value, depth) {
|
||
const label = key === null ? null : el('span.docker-json-key', {}, key + ': ');
|
||
if (value && typeof value === 'object') {
|
||
const entries = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value);
|
||
const summary = el('summary', {}, label, el('span.docker-muted', {}, Array.isArray(value) ? `[${entries.length}]` : `{${entries.length}}`));
|
||
const d = el('details', { open: depth < 2 }, summary);
|
||
for (const [k, v] of entries) d.append(el('div.docker-json-child', {}, jsonNode(k, v, depth + 1)));
|
||
return d;
|
||
}
|
||
const cls = typeof value === 'string' ? 'str' : value === null ? 'null' : 'num';
|
||
return el('div', {}, label, el('span.docker-json-' + cls, {}, JSON.stringify(value)));
|
||
}
|
||
|
||
// Claude's tools (agent.js)
|
||
export const dockerAgentTools = {
|
||
dockerPanel() {
|
||
if (!this.app.dockerPanel) throw new Error('no Docker window here: it needs the desktop IDE with a JumPHP project');
|
||
return this.app.dockerPanel;
|
||
},
|
||
async tool_docker_ps(args) {
|
||
this.dockerPanel();
|
||
const ps = await backend.invoke('docker.ps', {});
|
||
if (!ps.available) throw new Error('Docker does not answer: ' + (ps.error || ''));
|
||
const stats = args.stats ? await backend.invoke('docker.stats', {}).catch(() => ({})) : {};
|
||
return ps.containers.map((c) => ({ id: c.id, name: c.name, image: c.image, state: c.state, status: c.status,
|
||
ports: c.ports.map((p) => `${p.host}->${p.container}`), project: c.project || undefined, service: c.service || undefined, ...(stats[c.id.slice(0, 12)] ? { stats: stats[c.id.slice(0, 12)] } : {}) }));
|
||
},
|
||
async tool_docker_logs(args) {
|
||
this.dockerPanel();
|
||
return (await backend.invoke('docker.logs', { id: args.id, tail: args.tail || 200 })).text;
|
||
},
|
||
async tool_docker_hub_search(args) {
|
||
this.dockerPanel();
|
||
if (args.name) return backend.invoke('docker.hub.repo', { name: args.name }).then((r) => ({ ...r, fullDescription: (r.fullDescription || '').slice(0, 3000) }));
|
||
return backend.invoke('docker.hub.search', { query: args.query || '' });
|
||
},
|
||
async tool_docker_pull(args) {
|
||
const r = await this.dockerPanel().pullAndWait(String(args.image || ''));
|
||
if (r.code !== 0) throw new Error(`docker pull failed (code ${r.code}):\n${r.output}`);
|
||
return r;
|
||
},
|
||
};
|