Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+232
View File
@@ -0,0 +1,232 @@
(function (root, factory) {
const client = factory();
if (typeof module === 'object' && module.exports) module.exports = client;
else root.adpanelAgentLive = client;
})(typeof globalThis === 'object' ? globalThis : this, function () {
'use strict';
const scopeTimeoutMs = 12_000;
const pollDeadlineMs = 10 * 60 * 1000;
const maxUnacknowledged = 8;
const unacknowledged = new Map();
const discoveryQueue = [];
let activeDiscoveries = 0;
const defaultAccessMode = 'file_plan';
const accessModes = new Set([defaultAccessMode, 'read_only']);
function bindAccessMode(select, account, server, storage) {
const key = `adpanel:agent-access:${encodeURIComponent(account || '')}:${encodeURIComponent(server || '')}`;
select.value = defaultAccessMode;
try {
const saved = storage?.getItem(key);
if (accessModes.has(saved)) select.value = saved;
} catch { }
select.addEventListener('change', () => {
if (!accessModes.has(select.value)) select.value = defaultAccessMode;
try { storage?.setItem(key, select.value); } catch { }
});
return () => accessModes.has(select.value) ? select.value : defaultAccessMode;
}
const accessPicker = globalThis.document?.getElementById('aiAgentAccessMode');
const manualModelField = globalThis.document?.getElementById('aiManualModelField');
const manualModelInput = globalThis.document?.getElementById('aiManualModelInput');
let getAccessMode;
if (accessPicker) {
let storage;
try { storage = globalThis.localStorage; } catch { }
getAccessMode = bindAccessMode(accessPicker, globalThis.__ADPANEL_BOOTSTRAP__?.currentUser?.email,
globalThis.document.documentElement.dataset.bot, storage);
}
function showProviderModelInput(available, modelIds) {
if (manualModelField) manualModelField.hidden = !available;
if (manualModelInput) manualModelInput.value = available ? (Array.isArray(modelIds) ? modelIds.join('\n') : modelIds || '') : '';
}
function readProviderModelIds() {
if (manualModelField && !manualModelField.hidden) return manualModelInput?.value.split(/\r?\n/).map((id) => id.trim()).filter(Boolean);
}
const states = {
agent_interrupted: 'The Agent worker stopped before this reply was saved. Send again to start a new run.',
agent_authority_revoked: 'Access changed while the Agent was working.',
agent_disabled: 'ADPanel Agent is disabled.',
agent_provider_busy: 'The AI provider or Agent reached its request limit. Try again shortly.',
agent_provider_auth: 'The AI provider refused access. Ask an administrator to check its API key and model permissions.',
agent_provider_account: 'The AI provider requires account or billing attention. Ask an administrator to check the provider account.',
agent_provider_blocked: 'The AI provider blocked this reply. No new action was prepared.',
agent_provider_configuration: 'This AI provider is no longer configured for the selected model. Check Agent settings or select another model.',
agent_provider_incomplete: 'The AI provider did not return a complete reply. No new action was prepared. Try a smaller request.',
agent_provider_model_unavailable: 'The AI provider could not find the selected model or endpoint. Select another model or check Agent settings.',
agent_provider_rejected: 'The AI provider rejected this request. Try a shorter message or select another model that supports Agent tools.',
agent_provider_unavailable: 'The AI provider returned a service error. Try again shortly or select another provider.',
agent_provider_unreachable: 'The Agent could not reach the AI provider. Check the provider connection in Agent settings.',
agent_provider_timeout: 'The AI provider did not respond in time. Try again or select another model.',
agent_provider_tool_call_invalid: 'The AI provider did not return a valid tool call. No new action was prepared. Try again or select another model.',
agent_provider_response_too_large: 'The AI provider response exceeded the size limit. Ask for a smaller change or shorter reply.',
agent_panel_unavailable: 'The Agent could not reach the panel to complete this request. Try again shortly.',
agent_unavailable: 'The Agent service did not respond. Try again shortly.',
agent_diagnostic_not_allowed: 'The Agent could not use a requested diagnostic tool. Check your server permissions and try again.',
agent_console_owner_unavailable: 'The Agent could not load the local console. Check the server console directly.',
agent_console_owner_ambiguous: 'The Agent could not identify the current local console. Check the server console directly.',
agent_transcript_changed: 'The chat changed before the Agent could read the request. Reopen the chat and send it again.',
agent_run_stopped: 'Generation exceeded its time limit.',
agent_automatic_edit_interrupted: 'The Agent stopped before saving the edit result. Check the affected files before trying again.',
agent_automatic_edits_incomplete: 'The Agent did not complete all automatic edits. Review the result and check the affected files before retrying.',
agent_automatic_edit_upgrade: 'This queued edit was stopped by an Agent upgrade. Review the request before sending it again.',
agent_claim_inactive: 'This Agent run is no longer active.',
};
function jobOutcomeMessage(job) {
if (job?.status === 'failed') {
if (Object.hasOwn(states, job.error)) return states[job.error];
const reference = /^\d{1,20}$/.test(String(job.id)) ? ` (job ${job.id})` : '';
return `The Agent could not finish this reply${reference}. Try again shortly.`;
}
if (job?.status === 'cancelled') return job.error === 'agent_automatic_edit_interrupted' ? states[job.error]
: job.error === 'agent_disabled' ? 'This run was cancelled when ADPanel Agent was disabled.' : 'Generation stopped.';
return '';
}
function queueModelDiscovery(request) {
return new Promise((resolve, reject) => {
const start = () => {
activeDiscoveries += 1;
Promise.resolve().then(request).then(resolve, reject).finally(() => {
activeDiscoveries -= 1;
discoveryQueue.shift()?.();
});
};
if (activeDiscoveries < 2) start();
else discoveryQueue.push(start);
});
}
async function requestJson(fetcher, path, options, signal) {
const timeout = AbortSignal.timeout(scopeTimeoutMs);
const response = await fetcher(path, { ...options, cache: 'no-store', signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
const payload = await response.json().catch((error) => {
if (response.ok) throw error;
return {};
});
if (!response.ok) throw Object.assign(new Error(payload.error || `Agent request failed (${response.status}).`), {
status: response.status, code: payload.code, retry: Number(response.headers.get('Retry-After')) || 0,
});
return payload;
}
function wait(delay, signal) {
return new Promise((resolve, reject) => {
signal?.throwIfAborted();
const dispose = () => signal?.removeEventListener('abort', abort);
const abort = () => { clearTimeout(timer); dispose(); reject(signal.reason); };
const timer = setTimeout(() => { dispose(); resolve(); }, delay);
signal?.addEventListener('abort', abort, { once: true });
});
}
function makeRequestKey(cryptoApi = globalThis.crypto) {
if (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID();
const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 15) | 64;
bytes[8] = (bytes[8] & 63) | 128;
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
function retryableSubmissionError(error) {
return error.code !== 'agent_disabled' && (!error.status || error.status === 429 || error.status >= 500);
}
function createRun(submission, { fetcher = globalThis.fetch, requestKey } = {}) {
if (getAccessMode) submission = { ...submission, accessMode: getAccessMode() };
const payload = JSON.stringify(submission);
if (!requestKey) {
const now = Date.now();
for (const [pending, entry] of unacknowledged) {
if (entry.expiresAt <= now) unacknowledged.delete(pending);
}
requestKey = unacknowledged.get(payload)?.key || makeRequestKey();
unacknowledged.delete(payload);
}
const body = JSON.stringify({ ...submission, requestKey });
const send = async () => {
const response = await requestJson(fetcher, '/api/ai/chat', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body,
});
if (!/^\d+$/.test(String(response?.jobId)) || !/^\d+$/.test(String(response?.chatId))) {
throw new Error('The Agent returned an invalid job acknowledgement.');
}
return response;
};
const accepted = (async () => {
try { return await send(); } catch (error) {
if (!retryableSubmissionError(error)) throw error;
await wait(Math.min(3000, Math.max(300, (error.retry || 0) * 1000)));
try { return await send(); } catch (retryError) {
if (retryableSubmissionError(retryError)) {
if (unacknowledged.size >= maxUnacknowledged) unacknowledged.delete(unacknowledged.keys().next().value);
unacknowledged.set(payload, { key: requestKey, expiresAt: Date.now() + pollDeadlineMs });
}
throw retryError;
}
}
})();
return followRun(accepted, fetcher);
}
function followRun(accepted, fetcher) {
const controller = new AbortController();
let stopping = false;
let cancellation;
async function cancel() {
stopping = true;
cancellation ||= accepted.then(({ jobId }) => requestJson(fetcher, `/api/ai/jobs/${encodeURIComponent(jobId)}/cancel`, {
method: 'POST',
})).then((result) => {
if (result.cancelled) controller.abort();
return result;
}).catch((error) => {
stopping = false;
cancellation = null;
throw error;
});
return cancellation;
}
async function result() {
const { jobId } = await accepted;
const deadline = Date.now() + pollDeadlineMs;
let delay = 800;
while (Date.now() < deadline) {
if (stopping && cancellation) await cancellation.catch(() => {});
await wait(delay, controller.signal);
let payload;
try {
payload = await requestJson(fetcher, `/api/ai/jobs/${encodeURIComponent(jobId)}`, {}, controller.signal);
} catch (error) {
if (controller.signal.aborted || error.code === 'agent_disabled' || (error.status && error.status < 500 && error.status !== 429)) throw error;
delay = Math.min(15_000, Math.max(delay * 1.6, (error.retry || 0) * 1000));
continue;
}
const { job } = payload;
if (job?.status === 'completed') return job;
if (job?.status === 'cancelled') throw new DOMException(jobOutcomeMessage(job), 'AbortError');
if (job?.status === 'failed') throw Object.assign(new Error(jobOutcomeMessage(job)), { code: job.error });
delay = Math.min(10_000, Math.ceil(delay * 1.4));
}
throw new Error('The Agent run is still pending. Reopen this chat to check for the reply.');
}
return { accepted, result, cancel, detach: () => controller.abort() };
}
function resumeRun(jobId, chatId, { fetcher = globalThis.fetch } = {}) {
return followRun(Promise.resolve({ jobId, chatId }), fetcher);
}
return { createRun, resumeRun, queueModelDiscovery, jobOutcomeMessage, bindAccessMode, showProviderModelInput, readProviderModelIds };
});
+6909 -2581
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1177 -1888
View File
File diff suppressed because it is too large. Load diff
+22 -12
View File
@@ -64,7 +64,12 @@
}
function onResourceData(data) {
if (!data || data.server !== bot) return;
// Unsubscribe on hide is asynchronous server-side, so an in-flight
// room event can still land afterwards; ignore everything while the
// tab is hidden (the show path re-subscribes and the server
// immediately replays the watcher's last snapshot).
if (document.visibilityState === 'hidden') return;
if (!data || String(data.server || '').trim().toLowerCase() !== String(bot || '').trim().toLowerCase()) return;
const isRunning = data.status === 'running' || data.status === 'online';
if (data.memory && isRunning) {
@@ -125,17 +130,19 @@
const network = data.network || null;
const inboundBytes = readNetworkBytes(network, ['inboundBytes', 'rxBytes', 'receivedBytes']);
const outboundBytes = readNetworkBytes(network, ['outboundBytes', 'txBytes', 'transmittedBytes']);
if (inboundBytes !== null) {
lastNetworkInboundBytes = Math.max(lastNetworkInboundBytes, inboundBytes);
if (inboundBytes !== null && isRunning) {
lastNetworkInboundBytes = inboundBytes;
if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = formatBytes(lastNetworkInboundBytes);
} else if (resNetworkInboundLabel) {
resNetworkInboundLabel.textContent = '—';
lastNetworkInboundBytes = 0;
resNetworkInboundLabel.textContent = isRunning ? '0 B' : '—';
}
if (outboundBytes !== null) {
lastNetworkOutboundBytes = Math.max(lastNetworkOutboundBytes, outboundBytes);
if (outboundBytes !== null && isRunning) {
lastNetworkOutboundBytes = outboundBytes;
if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = formatBytes(lastNetworkOutboundBytes);
} else if (resNetworkOutboundLabel) {
resNetworkOutboundLabel.textContent = '—';
lastNetworkOutboundBytes = 0;
resNetworkOutboundLabel.textContent = isRunning ? '0 B' : '—';
}
if (data.uptime && data.uptime > 0 && isRunning) {
@@ -172,29 +179,32 @@
}
}
// The resources:data handler is registered exactly once. The old path
// re-registered it on every reconnect (subscribed survived disconnects
// while the listener was added again), so each event was processed N+1
// times in long-lived tabs; subscribed now only gates the server-side
// room join.
socket.on('resources:data', onResourceData);
let subscribed = false;
function subscribe() {
if (subscribed) return;
subscribed = true;
socket.on('resources:data', onResourceData);
socket.emit('resources:subscribe', { server: bot });
}
function unsubscribe() {
if (!subscribed) return;
subscribed = false;
socket.off('resources:data', onResourceData);
socket.emit('resources:unsubscribe', { server: bot });
stopUptimeCounter();
}
socket.on('connect', () => {
if (subscribed) {
if (subscribed || document.visibilityState !== 'hidden') {
subscribed = false;
subscribe();
} else if (document.visibilityState !== 'hidden') {
subscribe();
}
});
+102
View File
@@ -0,0 +1,102 @@
'use strict';
const serverAgentHistory = (() => {
const pages = new WeakMap();
const reviewOutcomes = Object.freeze({
applying: 'The panel received the approval but has not recorded a result yet. Reopen this chat to check the outcome.',
dismissed: 'Action declined. Nothing was sent.', refused: 'The panel refused the action.',
unknown: 'The outcome is unknown. Check the server before trying again.', expired: 'The review expired.',
stale: 'The file changed after review. Nothing was applied.',
});
function reviewOutcomeMessage(state) {
const key = state === 'file_changed_on_disk' ? 'stale' : state;
return Object.hasOwn(reviewOutcomes, key) ? reviewOutcomes[key] : '';
}
function isProposalMessage(content) {
return content === 'Action prepared.' || content === 'Action prepared. Review it before applying.';
}
function fromPage(data, chatId) {
const entries = Array.isArray(data?.messages) ? data.messages : [];
const messages = entries.map((entry) => ({
role: entry.role === 'assistant' ? 'ai' : entry.role,
content: entry.content,
thinking_time_ms: entry.thinking_time_ms,
thinking_content: entry.thinking_content,
model: entry.model,
agentActions: entry.role === 'assistant' ? readActions(entry.agent_actions) : [],
timestamp: new Date(entry.created_at).getTime(),
attachment: entry.image_data ? { isImage: true, data: entry.image_data, name: 'Image' } : null,
}));
const status = data?.chat?.latest_job_status;
const last = messages.at(-1);
if ((last?.role === 'user' || (last?.role === 'ai' && Number(data?.chat?.active_job_is_review) === 1)) &&
String(entries.at(-1).id) === data.chat?.latest_message_id &&
(status === 'failed' || status === 'cancelled')) {
last.agentOutcome = { status, error: data.chat.latest_job_error };
}
if (data?.chat?.review_state) {
const reply = entries.findIndex((entry) => entry.role === 'assistant' && String(entry.id) === data.chat.review_message_id);
if (reply !== -1 && isProposalMessage(messages[reply].content)) messages[reply].agentReviewState = data.chat.review_state;
}
pages.set(messages, { chatId, before: data?.nextBeforeId || null });
if (data?.chat?.review_job_id && last?.role === 'ai' && String(entries.at(-1).id) === data.chat.review_message_id) {
last.agentReview = { chatId, jobId: data.chat.review_job_id, server: data.chat.review_server };
}
return messages;
}
function clone(messages) {
const copy = messages.map((message) => ({ ...message }));
if (pages.has(messages)) pages.set(copy, pages.get(messages));
return copy;
}
function reviewJobId(messages, chatId, server) {
const review = messages.at(-1)?.agentReview;
return review && review.chatId === chatId && review.server === server ? review.jobId : null;
}
function readActions(stored) {
try {
const actions = typeof stored === 'string' ? JSON.parse(stored) : stored;
return Array.isArray(actions) ? actions.filter((entry) => typeof entry?.action === 'string' &&
typeof entry.status === 'string' && typeof entry.target === 'string') : [];
} catch { return []; }
}
function bindOlderButton(button, { messages, chatId, scrollPane, loadPage, isCurrent, applyPage, showError }) {
if (!button) return;
const page = pages.get(messages);
button.hidden = !page?.before || page.chatId !== chatId;
button.disabled = false;
button.onclick = button.hidden ? null : loadEarlier;
async function loadEarlier() {
if (button.disabled || !isCurrent()) return;
button.disabled = true;
try {
const data = await loadPage(chatId, page.before);
if (!isCurrent()) return;
if (!Array.isArray(data?.messages)) {
showError();
return;
}
const older = fromPage(data, chatId);
const combined = older.concat(messages);
pages.set(combined, pages.get(older));
const { scrollHeight, scrollTop } = scrollPane;
applyPage(combined);
scrollPane.scrollTop = Math.max(0, scrollTop + scrollPane.scrollHeight - scrollHeight);
} finally {
if (button.onclick === loadEarlier) button.disabled = false;
}
}
}
return { fromPage, clone, bindOlderButton, reviewJobId, reviewOutcomeMessage, isProposalMessage, readActions };
})();
if (typeof module === 'object' && module.exports) module.exports = serverAgentHistory;
+309
View File
@@ -0,0 +1,309 @@
'use strict';
(() => {
const card = document.getElementById('aiReviewCard');
if (!card) return;
const heading = document.getElementById('aiReviewHeading');
const summary = document.getElementById('aiReviewSummary');
const plan = document.getElementById('aiReviewPlan');
const before = document.getElementById('aiReviewBefore');
const after = document.getElementById('aiReviewAfter');
const diff = document.getElementById('aiReviewDiff');
const status = document.getElementById('aiReviewStatus');
const apply = document.getElementById('aiReviewApply');
const applyLabel = document.getElementById('aiReviewApplyLabel');
const dismiss = document.getElementById('aiReviewDismiss');
const dismissLabel = document.getElementById('aiReviewDismissLabel');
const retry = document.getElementById('aiReviewRetry');
const server = document.documentElement.dataset.bot;
const labels = {
start: 'Start server', stop: 'Stop server', restart: 'Restart server', kill: 'Force stop server',
console_command: 'Run console command', write_file: 'Edit file', replace_file: 'Replace entire file', create_file: 'Create file',
revert_file: 'Revert file edit',
create_folder: 'Create folder', delete_file: 'Delete file', create_backup: 'Create backup',
restore_backup: 'Restore backup', delete_backup: 'Delete backup',
};
const actionStatuses = { applied: 'Confirmed', dismissed: 'Declined', refused: 'Refused', unknown: 'Unconfirmed' };
const acknowledgementActions = new Set(['start', 'stop', 'restart', 'kill', 'console_command']);
let selected = null;
let preview = null;
let loading = false;
let version = 0;
const resolved = new Set();
const pending = new Set();
function bind(jobId, thread, messages) {
if (messages) bindActivity(thread, messages);
const last = thread?.lastElementChild;
const host = last?.classList.contains('ai') && last.querySelector(':scope > .ai-message-body');
const next = host && /^\d{1,20}$/.test(String(jobId)) && !resolved.has(String(jobId)) ? String(jobId) : null;
if (next && card.parentElement !== host) host.append(card);
card.hidden = !next;
if (next === selected) return;
selected = next;
version += 1;
loading = false;
preview = null;
if (selected) return loadPreview();
}
function visibleText(value) {
return value.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/gu,
(character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
}
function renderActivity(host, actions, append = false) {
if (!host || !actions?.length) return;
let activity = host.querySelector(':scope > .agent-action-log');
if (!activity) {
activity = document.createElement('section');
activity.className = 'agent-action-log';
activity.setAttribute('aria-label', 'Agent actions');
const title = document.createElement('h3');
title.textContent = 'Actions';
activity.append(title);
activity.append(document.createElement('ol'));
host.prepend(activity);
}
const list = activity.lastElementChild;
if (!append) list.textContent = '';
for (const entry of actions) {
if (!Object.hasOwn(labels, entry.action) || !Object.hasOwn(actionStatuses, entry.status)) continue;
const item = document.createElement('li');
const headline = document.createElement('strong');
headline.textContent = `${labels[entry.action]}: ${visibleText(entry.target)}`;
const outcome = document.createElement('span');
outcome.className = 'agent-action-status';
outcome.textContent = entry.status === 'applied' && acknowledgementActions.has(entry.action) ? 'Sent' : actionStatuses[entry.status];
item.append(headline, outcome);
if (typeof entry.command === 'string') {
const command = document.createElement('code');
command.textContent = visibleText(entry.command);
item.append(command);
}
const detail = document.createElement('span');
const counts = Number.isInteger(entry.addedLines) && Number.isInteger(entry.removedLines)
? ` +${entry.addedLines} / -${entry.removedLines} lines.` : '';
detail.className = 'agent-action-detail';
detail.textContent = `${typeof entry.detail === 'string' ? visibleText(entry.detail) : ''}${counts}`;
item.append(detail);
list.append(item);
}
}
function bindActivity(thread, messages) {
if (!thread?.children) return;
for (const [index, message] of messages.entries()) {
if (message.role === 'ai' && message.agentActions?.length) {
renderActivity(thread.children[index]?.querySelector(':scope > .ai-message-body'), message.agentActions);
}
}
}
function setBlock(block, value) {
block.parentElement.hidden = typeof value !== 'string';
block.textContent = typeof value === 'string' ? visibleText(value) || '(empty)' : '';
}
function setDiff(block, value) {
block.textContent = '';
block.parentElement.hidden = typeof value !== 'string';
if (typeof value !== 'string') return;
const lines = value.split('\n');
let inHunk = false;
for (const line of lines.slice(0, 600)) {
const row = document.createElement('span');
const hunk = line.startsWith('@@');
inHunk ||= hunk;
const kind = hunk ? 'hunk' : inHunk && line.startsWith('+') ? 'add' : inHunk && line.startsWith('-') ? 'remove' : '';
row.className = `agent-review-line${kind ? ` agent-review-line-${kind}` : ''}`;
row.textContent = visibleText(line);
block.append(row);
}
if (lines.length > 600) block.append('\nOpen the full file previews to see the remaining lines.');
}
function describe(proposal, showServer = true) {
const lines = showServer ? [`Server: ${server}`] : [];
if (proposal.path) lines.push(`Path: ${proposal.path}`);
if (proposal.command) lines.push(`Command: ${proposal.command}`);
if (proposal.name) lines.push(`Name: ${proposal.name}`);
if (proposal.description) lines.push(`Description: ${proposal.description}`);
if (proposal.backup) lines.push(`Backup ID: ${proposal.backup}`);
if (proposal.action === 'restore_backup') lines.push(proposal.deleteOldFiles ? 'Replace existing server files.' : 'Merge backup into existing files.');
return lines.join('\n');
}
function appendFileDetails(item, label, value, render, open = false) {
if (typeof value !== 'string') return;
const details = document.createElement('details');
details.open = open;
const title = document.createElement('summary');
title.textContent = label;
const block = document.createElement('pre');
details.append(title);
details.append(block);
item.append(details);
render(block, value);
}
function showPlan(steps) {
for (const step of steps) {
const item = document.createElement('li');
const title = document.createElement('strong');
title.textContent = labels[step.proposal.action];
const target = document.createElement('pre');
target.className = 'agent-review-target';
target.textContent = describe(step.proposal, false);
item.append(title);
item.append(target);
appendFileDetails(item, 'Changes', step.diff, setDiff, true);
appendFileDetails(item, 'Current file', step.before, setBlock);
appendFileDetails(item, 'Proposed file', step.proposedText ?? step.proposal.content, setBlock, !step.diff);
plan.append(item);
}
plan.hidden = false;
}
function route(jobId) { return `/api/ai/jobs/${jobId}/review`; }
async function readResponse(response) {
const body = await response.json();
if (!response.ok) throw Object.assign(new Error(body.error || 'Action review is unavailable.'), { status: response.status });
return body;
}
function refreshChat(result) {
if (/^\d{1,20}$/.test(String(result.chatId))) {
document.dispatchEvent(new CustomEvent('adpanel:agent-review-settled', { detail: {
chatId: result.chatId, conclusionJobId: result.conclusionJobId,
} }));
}
}
function showResult(jobId, result, recovered = false) {
resolved.add(jobId);
if (resolved.size > 64) resolved.delete(resolved.values().next().value);
if (selected === jobId) {
renderActivity(card.parentElement, serverAgentHistory.readActions(result.activity), !recovered);
if ((result.state === 'applied' || result.state === 'dismissed') && result.receiptSaved !== false) bind(null);
else {
status.textContent = result.receipt || serverAgentHistory.reviewOutcomeMessage(result.code || result.state) || serverAgentHistory.reviewOutcomeMessage('unknown');
if (result.receiptSaved === false) status.textContent += ' The panel could not save this result to the chat.';
}
}
refreshChat(result);
}
async function recoverResult(jobId) {
const deadline = AbortSignal.timeout(30_000);
for (let delay = 500; !deadline.aborted; delay = Math.min(delay * 2, 4_000)) {
const { job } = await readResponse(await fetch(`/api/ai/jobs/${jobId}`, {
cache: 'no-store', signal: AbortSignal.any([deadline, AbortSignal.timeout(10_000)]),
}));
if (String(job?.id) !== jobId || job.review_server !== server || !job.review_state) return false;
if (job.review_state !== 'applying') {
const receipt = job.review_state === 'expired' || serverAgentHistory.isProposalMessage(job.content) ? undefined : job.content;
showResult(jobId, { state: job.review_state, chatId: job.chat_id, conclusionJobId: job.review_conclusion_job_id,
receipt, activity: job.agent_actions }, true);
return true;
}
if (selected !== jobId) return true;
status.textContent = 'Waiting for the action result...';
await new Promise((resolve) => setTimeout(resolve, delay));
}
return false;
}
async function loadPreview() {
if (!selected || loading) return;
const jobId = selected;
const view = version;
loading = true;
preview = null;
apply.disabled = true;
dismiss.disabled = true;
applyLabel.textContent = 'Accept';
dismissLabel.textContent = 'Decline';
retry.hidden = true;
heading.textContent = 'Proposed action';
summary.textContent = '';
plan.hidden = true;
plan.textContent = '';
setBlock(before, null);
setBlock(after, null);
setDiff(diff, null);
status.textContent = pending.has(jobId) ? 'Waiting for the action result...' : 'Loading preview...';
if (pending.has(jobId)) { loading = false; return; }
try {
const data = await readResponse(await fetch(`${route(jobId)}?${new URLSearchParams({ server })}`, {
cache: 'no-store', signal: AbortSignal.timeout(15000),
}));
if (view !== version) return;
const grouped = Array.isArray(data.plan);
const steps = grouped ? data.plan : [data];
const versions = grouped ? data.expectedSha256 : [data.expectedSha256];
if (data.server !== server || !data.token || (grouped && (steps.length < 2 || steps.length > 5)) ||
steps.some((step) => !Object.hasOwn(labels, step?.proposal?.action)) || (data.expectedSha256 !== null &&
(!Array.isArray(versions) || versions.length !== steps.length || versions.some((value) => typeof value !== 'string')))) {
throw new Error('Invalid action review.');
}
if (grouped) {
heading.textContent = `File plan (${steps.length} steps)`;
summary.textContent = `Server: ${server}`;
applyLabel.textContent = 'Accept plan';
dismissLabel.textContent = 'Decline plan';
showPlan(steps);
} else {
heading.textContent = labels[data.proposal.action] + (Number.isInteger(data.remaining) && data.remaining > 0 ? ` (${data.remaining} more after this)` : '');
summary.textContent = describe(data.proposal);
setBlock(before, data.before);
setBlock(after, data.proposedText ?? data.proposal.content);
setDiff(diff, data.diff);
}
const notices = [];
if (steps.some(({ proposal }) => proposal.action === 'replace_file')) notices.push('Replacement removes settings not present in the proposed file.');
if (grouped) notices.push('A failure stops the plan. Changes already applied are kept.');
status.textContent = data.previewError || notices.join(' ');
preview = { jobId, view, token: data.token, expectedSha256: data.expectedSha256, grouped };
apply.disabled = data.expectedSha256 === null;
dismiss.disabled = false;
} catch (error) {
if (view === version) {
status.textContent = error.message || 'Could not load the preview.';
retry.hidden = false;
}
} finally {
if (view === version) loading = false;
}
}
async function decide(event, decision) {
if (!event.isTrusted || !preview || preview.view !== version || pending.has(preview.jobId)) return;
if (decision === 'apply' && preview.expectedSha256 === null) return;
const { jobId, token, expectedSha256, grouped } = preview;
preview = null;
pending.add(jobId);
apply.disabled = dismiss.disabled = true;
status.textContent = decision === 'apply' ? (grouped ? 'Applying plan...' : 'Applying...') : 'Declining...';
try {
const result = await readResponse(await fetch(route(jobId), {
method: 'POST', cache: 'no-store', signal: AbortSignal.timeout(31 * 60_000),
headers: { 'Content-Type': 'application/json', 'x-action-token': token },
body: JSON.stringify({ server, decision, expectedSha256 }),
}));
showResult(jobId, result);
} catch (error) {
if ((!error.status || error.status >= 500 || error.status === 409) && await recoverResult(jobId).catch(() => false)) return;
if (selected === jobId) {
status.textContent = !error.status || error.status >= 500 ? serverAgentHistory.reviewOutcomeMessage('unknown') : error.message;
if (error.status === 403 || error.status === 429) retry.hidden = false;
}
} finally { pending.delete(jobId); }
}
apply.addEventListener('click', (event) => decide(event, 'apply'));
dismiss.addEventListener('click', (event) => decide(event, 'dismiss'));
retry.addEventListener('click', (event) => { if (event.isTrusted) void loadPreview(); });
window.adpanelAgentReview = Object.freeze({ bind });
})();
+220
View File
@@ -0,0 +1,220 @@
(function (root) {
'use strict';
function createReinstallController({ document, serverName, hasPerm, fetchWithServerActionToken, showModalElement, animateClose, logger = console }) {
const reinstallModal = document.getElementById('reinstallModal');
const reinstallModalClose = document.getElementById('reinstallModalClose');
const reinstallCancelBtn = document.getElementById('reinstallCancelBtn');
const reinstallConfirmBtn = document.getElementById('reinstallConfirmBtn');
const reinstallConfirmNo = document.getElementById('reinstallConfirmNo');
const reinstallConfirmYes = document.getElementById('reinstallConfirmYes');
const reinstallDoneBtn = document.getElementById('reinstallDoneBtn');
const reinstallErrorClose = document.getElementById('reinstallErrorClose');
const reinstallDefaultView = document.getElementById('reinstallDefaultView');
const reinstallConfirmView = document.getElementById('reinstallConfirmView');
const reinstallProgressView = document.getElementById('reinstallProgressView');
const reinstallSuccessView = document.getElementById('reinstallSuccessView');
const reinstallSuccessDesc = document.getElementById('reinstallSuccessDesc');
const reinstallSuccessText = reinstallSuccessDesc?.textContent;
const reinstallErrorView = document.getElementById('reinstallErrorView');
const reinstallErrorTitle = document.getElementById('reinstallErrorTitle');
const reinstallErrorDesc = document.getElementById('reinstallErrorDesc');
const reinstallCredentialBlock = document.getElementById('reinstallCredentialBlock');
const reinstallCredentialLabel = document.getElementById('reinstallCredentialLabel');
const reinstallCredentialInput = document.getElementById('reinstallCredentialInput');
const reinstallCredentialError = document.getElementById('reinstallCredentialError');
const REINSTALL_STEPUP_CODES = ['password-required', '2fa-required', 'invalid-password', 'invalid-2fa'];
let reinstallCredentialMode = '';
let reinstallInFlight = false;
let reinstallResultView = '';
function reinstallShowView(viewId) {
[reinstallDefaultView, reinstallConfirmView, reinstallProgressView, reinstallSuccessView, reinstallErrorView].forEach(view => {
if (view) view.style.display = 'none';
});
const target = document.getElementById(viewId);
if (target) target.style.display = '';
}
function reinstallShowCredentialStep(message, revokeSecurity) {
if (revokeSecurity && typeof revokeSecurity === 'object') {
reinstallCredentialMode = (revokeSecurity.requiresTwoFactor || revokeSecurity.authMethod === '2fa') ? '2fa' : 'password';
} else if (!reinstallCredentialMode) {
reinstallCredentialMode = 'password';
}
if (reinstallCredentialLabel) {
reinstallCredentialLabel.textContent = reinstallCredentialMode === '2fa'
? 'Enter a 6-digit code from your authenticator app to confirm'
: 'Enter your current password to confirm';
}
if (reinstallCredentialInput) {
reinstallCredentialInput.type = reinstallCredentialMode === '2fa' ? 'text' : 'password';
reinstallCredentialInput.autocomplete = reinstallCredentialMode === '2fa' ? 'one-time-code' : 'current-password';
reinstallCredentialInput.placeholder = reinstallCredentialMode === '2fa' ? '123456' : 'Current password';
reinstallCredentialInput.maxLength = reinstallCredentialMode === '2fa' ? 6 : 128;
}
if (reinstallCredentialError) {
reinstallCredentialError.textContent = message || '';
reinstallCredentialError.style.display = message ? 'block' : 'none';
}
if (reinstallCredentialBlock) reinstallCredentialBlock.style.display = 'flex';
reinstallShowView('reinstallConfirmView');
if (reinstallCredentialInput) reinstallCredentialInput.focus();
}
function reinstallResetCredentialStep() {
if (reinstallCredentialBlock) reinstallCredentialBlock.style.display = 'none';
if (reinstallCredentialInput) reinstallCredentialInput.value = '';
if (reinstallCredentialError) {
reinstallCredentialError.textContent = '';
reinstallCredentialError.style.display = 'none';
}
reinstallCredentialMode = '';
}
function showReinstallResult(viewId) {
reinstallResetCredentialStep();
reinstallResultView = viewId;
reinstallShowView(viewId);
}
function showReinstallError(message, unconfirmed = false) {
if (reinstallErrorTitle) reinstallErrorTitle.textContent = unconfirmed ? 'Reinstall result unconfirmed' : 'Reinstall failed';
if (reinstallErrorDesc) reinstallErrorDesc.textContent = message;
showReinstallResult('reinstallErrorView');
}
async function attemptReinstall() {
if (reinstallInFlight) return;
reinstallInFlight = true;
if (reinstallConfirmYes) reinstallConfirmYes.disabled = true;
reinstallShowView('reinstallProgressView');
try {
const body = {};
if (reinstallCredentialMode === '2fa') {
body.twoFactorCode = (reinstallCredentialInput?.value || '').replace(/\D/g, '');
} else if (reinstallCredentialMode === 'password') {
body.currentPassword = reinstallCredentialInput?.value || '';
}
if (reinstallCredentialInput) reinstallCredentialInput.value = '';
const response = await fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/reinstall`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}, 'reinstallServer', { refreshBefore: true });
const data = await response.json().catch(() => null);
if (response.status === 403 && REINSTALL_STEPUP_CODES.includes(data?.code)) {
if (!reinstallModal?.classList.contains('show') || reinstallModal.classList.contains('closing')) return;
const failed = data.code === 'invalid-password' || data.code === 'invalid-2fa';
const revokeSecurity = data.revokeSecurity || { authMethod: data.code.endsWith('2fa') || data.code === '2fa-required' ? '2fa' : 'password' };
reinstallShowCredentialStep(failed ? (data.error || 'Verification failed.') : '', revokeSecurity);
return;
}
if (!response.ok || data?.ok !== true) {
const unconfirmed = response.ok || data?.code === 'reinstall-result-unconfirmed' || response.status === 504 ||
(response.status >= 500 && (data?.ok !== false || !data?.error));
showReinstallError(unconfirmed
? 'The reinstall result could not be confirmed. It may still be running or may have completed. Check the server state before retrying.'
: (data?.error || 'Reinstall failed. Check the server state before retrying.'), unconfirmed);
return;
}
if (reinstallSuccessDesc) {
let message = reinstallSuccessText;
if (data.eulaRequired === true) {
message = 'Your server files were replaced. Accept the Minecraft EULA in the console before starting the server.';
} else if (data.powerState === 'stopped') {
message = 'Your server files were replaced, but the server is stopped.';
}
reinstallSuccessDesc.textContent = message;
}
showReinstallResult('reinstallSuccessView');
} catch (error) {
logger.error('[reinstall] Network error:', error);
showReinstallError('Connection lost. The reinstall may still be running or may have completed. Check the server state before retrying.', true);
} finally {
reinstallInFlight = false;
if (reinstallConfirmYes) reinstallConfirmYes.disabled = false;
}
}
function openReinstallModal() {
if (!reinstallModal || !hasPerm('server_reinstall')) return;
// adpanel:reinstall-admission - navigation must not release a pending
// destructive request; only its completion can admit another attempt.
if (reinstallInFlight) {
reinstallShowView('reinstallProgressView');
} else {
reinstallResetCredentialStep();
reinstallShowView(reinstallResultView || 'reinstallDefaultView');
}
showModalElement(reinstallModal);
}
function dismissReinstallView() {
reinstallResultView = '';
reinstallResetCredentialStep();
}
function closeReinstallModal() {
if (!reinstallModal) return;
dismissReinstallView();
animateClose(reinstallModal);
}
[reinstallModalClose, reinstallCancelBtn, reinstallErrorClose, reinstallDoneBtn].forEach(button => {
if (button) button.addEventListener('click', closeReinstallModal);
});
if (reinstallConfirmBtn) {
reinstallConfirmBtn.addEventListener('click', () => {
reinstallShowView('reinstallConfirmView');
});
}
if (reinstallConfirmNo) {
reinstallConfirmNo.addEventListener('click', () => {
reinstallResetCredentialStep();
reinstallShowView('reinstallDefaultView');
});
}
if (reinstallConfirmYes) {
reinstallConfirmYes.addEventListener('click', () => {
if (!hasPerm('server_reinstall')) {
closeReinstallModal();
return;
}
return attemptReinstall();
});
}
if (reinstallCredentialInput) {
reinstallCredentialInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
if (hasPerm('server_reinstall')) return attemptReinstall();
}
});
}
if (reinstallModal) {
reinstallModal.addEventListener('adpanel:reinstall-dismiss', dismissReinstallView);
reinstallModal.addEventListener('click', (event) => {
if (event.target === reinstallModal) closeReinstallModal();
});
if (root.MutationObserver) {
const observer = new root.MutationObserver(() => {
if (!reinstallModal.classList.contains('show')) reinstallResetCredentialStep();
});
observer.observe(reinstallModal, { attributes: true, attributeFilter: ['class'] });
}
}
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && reinstallModal && reinstallModal.classList.contains('show')) {
closeReinstallModal();
}
});
return { open: openReinstallModal, close: closeReinstallModal };
}
const api = { createReinstallController };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.ADPanelReinstall = api;
})(typeof window !== 'undefined' ? window : globalThis);
+25
View File
@@ -0,0 +1,25 @@
(function (root) {
'use strict';
const ids = new Map();
const key = (email) => String(email || '').trim().toLowerCase();
const changed = () => new Error('Account state changed. Close this dialog, reload accounts, and select the account again.');
// adpanel:account-retry-identity - a refreshed token cannot retarget a
// pending action to a replacement row that reuses its email.
root.ADPanelAccountTargets = {
update(accounts) {
ids.clear();
for (const account of accounts || []) {
if (Number.isSafeInteger(account.id) && account.id > 0) ids.set(key(account.email), account.id);
}
},
select(email) {
const id = ids.get(key(email));
return Object.freeze({ email: key(email), id: id || 0 });
},
payload(target, body) {
if (!target || !target.id || ids.get(target.email) !== target.id) throw changed();
return { ...body, expectedTargetId: target.id };
}
};
})(window);
+8636 -3132
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
/*!
* Socket.IO v4.8.3
* (c) 2014-2025 Guillermo Rauch
* Released under the MIT License.
*/
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t="undefined"!=typeof globalThis?globalThis:t||self).io=n()}(this,(function(){"use strict";function t(t,n){(null==n||n>t.length)&&(n=t.length);for(var i=0,r=Array(n);i<n;i++)r[i]=t[i];return r}function n(t,n){for(var i=0;i<n.length;i++){var r=n[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,f(r.key),r)}}function i(t,i,r){return i&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function r(n,i){var r="undefined"!=typeof Symbol&&n[Symbol.iterator]||n["@@iterator"];if(!r){if(Array.isArray(n)||(r=function(n,i){if(n){if("string"==typeof n)return t(n,i);var r={}.toString.call(n).slice(8,-1);return"Object"===r&&n.constructor&&(r=n.constructor.name),"Map"===r||"Set"===r?Array.from(n):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(n,i):void 0}}(n))||i&&n&&"number"==typeof n.length){r&&(n=r);var e=0,o=function(){};return{s:o,n:function(){return e>=n.length?{done:!0}:{done:!1,value:n[e++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,u=!0,h=!1;return{s:function(){r=r.call(n)},n:function(){var t=r.next();return u=t.done,t},e:function(t){h=!0,s=t},f:function(){try{u||null==r.return||r.return()}finally{if(h)throw s}}}}function e(){return e=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var i=arguments[n];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},e.apply(null,arguments)}function o(t){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},o(t)}function s(t,n){t.prototype=Object.create(n.prototype),t.prototype.constructor=t,h(t,n)}function u(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(u=function(){return!!t})()}function h(t,n){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},h(t,n)}function f(t){var n=function(t,n){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,n||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(t)}(t,"string");return"symbol"==typeof n?n:n+""}function c(t){return c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},c(t)}function a(t){var n="function"==typeof Map?new Map:void 0;return a=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(n){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(t))return n.get(t);n.set(t,i)}function i(){return function(t,n,i){if(u())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,n);var e=new(t.bind.apply(t,r));return i&&h(e,i.prototype),e}(t,arguments,o(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),h(i,t)},a(t)}var v=Object.create(null);v.open="0",v.close="1",v.ping="2",v.pong="3",v.message="4",v.upgrade="5",v.noop="6";var l=Object.create(null);Object.keys(v).forEach((function(t){l[v[t]]=t}));var p,d={type:"error",data:"parser error"},y="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),b="function"==typeof ArrayBuffer,w=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer},g=function(t,n,i){var r=t.type,e=t.data;return y&&e instanceof Blob?n?i(e):m(e,i):b&&(e instanceof ArrayBuffer||w(e))?n?i(e):m(new Blob([e]),i):i(v[r]+(e||""))},m=function(t,n){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];n("b"+(t||""))},i.readAsDataURL(t)};function k(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}for(var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j="undefined"==typeof Uint8Array?[]:new Uint8Array(256),E=0;E<64;E++)j[A.charCodeAt(E)]=E;var O,B="function"==typeof ArrayBuffer,S=function(t,n){if("string"!=typeof t)return{type:"message",data:C(t,n)};var i=t.charAt(0);return"b"===i?{type:"message",data:N(t.substring(1),n)}:l[i]?t.length>1?{type:l[i],data:t.substring(1)}:{type:l[i]}:d},N=function(t,n){if(B){var i=function(t){var n,i,r,e,o,s=.75*t.length,u=t.length,h=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);var f=new ArrayBuffer(s),c=new ULine truncated
//# sourceMappingURL=socket.io.min.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"socket.io.min.js","sources":["../../engine.io-parser/build/esm/commons.js","../../engine.io-parser/build/esm/encodePacket.browser.js","../../engine.io-parser/build/esm/contrib/base64-arraybuffer.js","../../engine.io-parser/build/esm/index.js","../../engine.io-parser/build/esm/decodePacket.browser.js","../../socket.io-component-emitter/lib/esm/index.js","../../engine.io-client/build/esm/globals.js","../../engine.io-client/build/esm/util.js","../../engine.io-client/build/esm/transport.js","../../engine.io-client/build/esm/contrib/parseqs.js","../../engine.io-client/build/esm/transports/polling.js","../../engine.io-client/build/esm/contrib/has-cors.js","../../engine.io-client/build/esm/transports/polling-xhr.js","../../engine.io-client/build/esm/transports/websocket.js","../../engine.io-client/build/esm/transports/webtransport.js","../../engine.io-client/build/esm/transports/index.js","../../engine.io-client/build/esm/contrib/parseuri.js","../../engine.io-client/build/esm/socket.js","../../engine.io-client/build/esm/index.js","../../socket.io-parser/build/esm/is-binary.js","../../socket.io-parser/build/esm/binary.js","../../socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach((key) => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n if (data instanceof Uint8Array) {\n return data;\n }\n else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n else {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n}\nlet TEXT_ENCODER;\nexport function encodePacketToBinary(packet, callback) {\n if (withNativeBlob && packet.data instanceof Blob) {\n return packet.data.arrayBuffer().then(toArray).then(callback);\n }\n else if (withNativeArrayBuffer &&\n (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n return callback(toArray(packet.data));\n }\n encodePacket(packet, false, (encoded) => {\n if (!TEXT_ENCODER) {\n TEXT_ENCODER = new TextEncoder();\n }\n callback(TEXT_ENCODER.encode(encoded));\n });\n}\nexport { encodePacket };\n","// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + Line truncated
+194 -11
View File
@@ -1,7 +1,20 @@
(function () {
"use strict";
// Shared (localStorage, all tabs): window geometry plus a "last live
// session" hint (sessionId/live) so a tab that has never opened a terminal
// here can attach to another tab's still-live SSH session — the server
// explicitly supports several viewers sharing one session.
const STORAGE_KEY = "adpanel:ssh-terminal-window:v1";
// Per-tab (sessionStorage, dies with the tab): whether THIS tab's window is
// open, its minimized state, and the session id THIS tab's frame is
// attached to. A close in one tab must not flip another tab's restore
// state — the shared record used to carry `open`/`sessionId` globally, so
// closing here silently killed every other tab's auto-restore.
const TAB_STORAGE_KEY = "adpanel:ssh-terminal-window:tab:v1";
// Fields routed to the per-tab store by writeState(); everything else
// (geometry) stays shared.
const TAB_STATE_FIELDS = new Set(["open", "minimized", "sessionId", "live"]);
const DEFAULT_WIDTH = 960;
const DEFAULT_HEIGHT = 640;
const MIN_WIDTH = 360;
@@ -36,9 +49,13 @@
let launcherVisibilityRaf = 0;
let geometry = { x: 24, y: 24, w: DEFAULT_WIDTH, h: DEFAULT_HEIGHT };
function readState() {
// Storage access is resolved inside the try: sessionStorage/localStorage
// themselves can throw (blocked storage, privacy modes), and a throwing
// store must degrade to "no state" exactly like a parse failure does.
function readStore(store, key) {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!store) return {};
const raw = store.getItem(key);
if (!raw) return {};
const data = JSON.parse(raw);
return data && typeof data === "object" ? data : {};
@@ -47,13 +64,103 @@
}
}
function writeState(patch) {
function writeStore(store, key, patch) {
try {
const next = Object.assign({}, readState(), patch, { updatedAt: Date.now() });
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
if (!store) return;
const next = Object.assign({}, readStore(store, key), patch, { updatedAt: Date.now() });
store.setItem(key, JSON.stringify(next));
} catch { }
}
function sessionStore() {
try { return window.sessionStorage; } catch { return null; }
}
function localStore() {
try { return window.localStorage; } catch { return null; }
}
function readTabState() {
return readStore(sessionStore(), TAB_STORAGE_KEY);
}
function writeTabState(patch) {
writeStore(sessionStore(), TAB_STORAGE_KEY, patch);
}
function readSharedState() {
return readStore(localStore(), STORAGE_KEY);
}
function writeSharedState(patch) {
writeStore(localStore(), STORAGE_KEY, patch);
}
function deleteSharedKeys(keys) {
try {
const store = localStore();
if (!store) return;
const raw = store.getItem(STORAGE_KEY);
if (!raw) return;
const data = JSON.parse(raw);
if (!data || typeof data !== "object") return;
let changed = false;
for (const key of keys) {
if (key in data) {
delete data[key];
changed = true;
}
}
if (changed) store.setItem(STORAGE_KEY, JSON.stringify(data));
} catch { }
}
// One-time migration from the pre-per-tab layout, which stored
// open/minimized/sessionId/live in the shared key. Adopt the legacy record
// into this tab's own storage (so an in-flight terminal survives the
// upgrade) and strip the ownership fields from the shared record — from
// then on the shared sessionId/live pair is only the last-live-session
// hint. Every not-yet-migrated open tab adopts once (each into its own
// sessionStorage); the server's multi-viewer attach makes that harmless.
function migrateLegacySharedState() {
const shared = readSharedState();
if (!("open" in shared) && !("minimized" in shared)) return;
const tab = readTabState();
if (shared.open && Object.keys(tab).length === 0) {
writeTabState({
open: true,
minimized: !!shared.minimized,
sessionId: typeof shared.sessionId === "string" ? shared.sessionId : "",
live: shared.live !== false,
});
}
deleteSharedKeys(["open", "minimized"]);
}
// Merged view for geometry consumers and existing call sites: per-tab
// ownership fields win over the shared record (whose sessionId/live are
// then just the hint).
function readState() {
return Object.assign({}, readSharedState(), readTabState());
}
// Routes each field to the store that owns it: ownership fields to the
// per-tab record, geometry to the shared one.
function writeState(patch) {
const tabPatch = {};
const sharedPatch = {};
for (const [key, value] of Object.entries(patch)) {
(TAB_STATE_FIELDS.has(key) ? tabPatch : sharedPatch)[key] = value;
}
if (Object.keys(tabPatch).length) writeTabState(tabPatch);
if (Object.keys(sharedPatch).length) writeSharedState(sharedPatch);
}
// Valid terminal session id, same shape the server normalizes to.
function isValidSessionId(value) {
return typeof value === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(value);
}
function viewport() {
return {
w: Math.max(320, window.innerWidth || document.documentElement.clientWidth || 1280),
@@ -291,7 +398,12 @@
// check is handled by the panel's upgrade proxy (it rewrites the Origin
// header upstream). The page receives its session id via the URL
// fragment and uses no storage at all; the sandbox must keep excluding
// allow-same-origin.
// allow-same-origin. allow-modals is required for the terminal page's
// multi-line paste confirmation: in a sandboxed frame without it,
// window.confirm() is a silent no-op returning false, which would block
// every multi-line paste. The frame hosts only first-party, token-gated,
// nonce-CSP content, so modals carry no additional exposure.
// allow-same-origin stays excluded.
win.innerHTML = `
<div class="adp-ssh-terminal-titlebar" data-adp-ssh-drag>
<div class="adp-ssh-terminal-title">
@@ -309,7 +421,7 @@
</div>
</div>
<div class="adp-ssh-terminal-frame-wrap">
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts"></iframe>
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts allow-modals"></iframe>
</div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-n" data-adp-ssh-resize="n"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-e" data-adp-ssh-resize="e"></div>
@@ -382,8 +494,24 @@
// sees. A minted id is flagged fresh so the page skips a pointless
// attach attempt; a reused id lets the page re-attach to the
// still-live SSH session.
let sessionId = (typeof state.sessionId === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(state.sessionId)) ? state.sessionId : "";
// Resolution order: (1) this tab's own session id (its window was open
// here — navigation restore or re-open); (2) the shared last-live hint
// for a tab that has NEVER had a terminal here, so opening in a second
// tab attaches to the other tab's live session; (3) mint fresh. A tab
// that closed its own window keeps an empty sessionId in its record,
// so it deliberately starts clean instead of re-attaching. Both stores
// are read explicitly — the merged readState() would leak the shared
// hint into state.sessionId for a record-less tab and bypass the
// live !== false guard below.
const tab = readTabState();
let sessionId = isValidSessionId(tab.sessionId) ? tab.sessionId : "";
let minted = false;
if (!sessionId && !("sessionId" in tab)) {
const shared = readSharedState();
if (shared.live !== false && isValidSessionId(shared.sessionId)) {
sessionId = shared.sessionId;
}
}
if (!sessionId) {
sessionId = (window.crypto && typeof window.crypto.randomUUID === "function")
? window.crypto.randomUUID()
@@ -482,6 +610,21 @@
// Invalidate any in-flight open: after a close, a pending openTerminal
// promise is stale and must neither be reused nor write state/frame.src.
openEpoch += 1;
// A close can land mid-interaction: on touch/pen devices a second
// pointer taps the close button while the first is still dragging the
// titlebar (or a resize handle). The pending pointerup would otherwise
// hit endInteraction's !win guard and strand the page-wide grabbing
// cursor and the interaction state until some later drag completes, so
// unwind them here, before the window node goes away.
if (interaction) {
if (raf) {
cancelAnimationFrame(raf);
raf = 0;
}
if (win) win.classList.remove("is-interacting", "is-dragging", "is-resizing");
clearInteractionCursor();
interaction = null;
}
if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
if (frame && frame.contentWindow) {
try {
@@ -498,9 +641,19 @@
}
// The child receives the close signal and replies with a 'disconnect'
// message, destroying the server-side session; clearing the id here
// means the next open is a genuinely new terminal session.
// message; the server tears the shared session down when the closing
// tab was the last attached viewer, and otherwise only detaches this
// tab (other tabs keep the session live). Clearing the id here means
// the next open in this window is a genuinely new terminal session
// either way.
// All four fields are per-tab (routed to sessionStorage): closing here
// must leave every other tab's open flag and stored session id intact so
// their auto-restore keeps working. The shared hint is only marked
// not-live: this tab's frame is disconnecting, and if it was the last
// viewer the session really is gone — a still-attached tab refreshes the
// hint via its own frame's next live report.
writeState({ open: false, minimized: false, live: false, sessionId: "" });
writeSharedState({ live: false });
const old = win;
const from = old ? old.getBoundingClientRect() : null;
@@ -607,7 +760,18 @@
}
function endInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
if (!interaction) return;
if (!win) {
// Defense in depth for a window torn down mid-interaction by a path
// that did not unwind first: the geometry has nothing left to apply
// to, but the page-wide interaction cursor must still unwind or the
// page stays stuck in "grabbing"/resize cursor until a later drag
// completes.
clearInteractionCursor();
interaction = null;
return;
}
if (event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.next || clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
@@ -629,9 +793,17 @@
});
});
// Adopt/strip the pre-per-tab shared record before the restore read
// below, so an in-flight terminal survives this deploy exactly once.
migrateLegacySharedState();
// Invariant: `open: true` is only persisted after a successful launch
// (see openTerminal), so a true state here means the last open fully
// succeeded — restoring it can never resurrect a failed/ghost window.
// The flag is per-tab (sessionStorage): a close in another tab no longer
// suppresses this tab's restore, and this tab's close no longer
// suppresses theirs. The merged read still falls back to the shared
// record for geometry.
const state = readState();
if (state.open) {
// The frame reports liveness via postMessage (live on ws connect, false
@@ -708,6 +880,17 @@
const data = event.data;
if (!data || data.type !== "adpanel-ssh-terminal-live" || typeof data.live !== "boolean") return;
writeState({ live: data.live });
// Mirror liveness into the shared hint so a tab that never opened a
// terminal here can discover and attach to this tab's live session.
// live:false clears only the flag (the id stays for diagnostics); the
// frame-null guard above keeps a stale report from a dying frame out —
// closeTerminal nulls the frame before any late report can land.
if (data.live) {
const sid = readTabState().sessionId;
if (isValidSessionId(sid)) writeSharedState({ sessionId: sid, live: true });
} else {
writeSharedState({ live: false });
}
});
window.addEventListener("resize", () => {
if (!win) return;
+194 -11
View File
@@ -2,7 +2,20 @@
(function () {
"use strict";
// Shared (localStorage, all tabs): window geometry plus a "last live
// session" hint (sessionId/live) so a tab that has never opened a terminal
// here can attach to another tab's still-live SSH session — the server
// explicitly supports several viewers sharing one session.
const STORAGE_KEY = "adpanel:ssh-terminal-window:v1";
// Per-tab (sessionStorage, dies with the tab): whether THIS tab's window is
// open, its minimized state, and the session id THIS tab's frame is
// attached to. A close in one tab must not flip another tab's restore
// state — the shared record used to carry `open`/`sessionId` globally, so
// closing here silently killed every other tab's auto-restore.
const TAB_STORAGE_KEY = "adpanel:ssh-terminal-window:tab:v1";
// Fields routed to the per-tab store by writeState(); everything else
// (geometry) stays shared.
const TAB_STATE_FIELDS = new Set(["open", "minimized", "sessionId", "live"]);
const DEFAULT_WIDTH = 960;
const DEFAULT_HEIGHT = 640;
const MIN_WIDTH = 360;
@@ -37,9 +50,13 @@
let launcherVisibilityRaf = 0;
let geometry = { x: 24, y: 24, w: DEFAULT_WIDTH, h: DEFAULT_HEIGHT };
function readState() {
// Storage access is resolved inside the try: sessionStorage/localStorage
// themselves can throw (blocked storage, privacy modes), and a throwing
// store must degrade to "no state" exactly like a parse failure does.
function readStore(store, key) {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!store) return {};
const raw = store.getItem(key);
if (!raw) return {};
const data = JSON.parse(raw);
return data && typeof data === "object" ? data : {};
@@ -48,13 +65,103 @@
}
}
function writeState(patch) {
function writeStore(store, key, patch) {
try {
const next = Object.assign({}, readState(), patch, { updatedAt: Date.now() });
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
if (!store) return;
const next = Object.assign({}, readStore(store, key), patch, { updatedAt: Date.now() });
store.setItem(key, JSON.stringify(next));
} catch { }
}
function sessionStore() {
try { return window.sessionStorage; } catch { return null; }
}
function localStore() {
try { return window.localStorage; } catch { return null; }
}
function readTabState() {
return readStore(sessionStore(), TAB_STORAGE_KEY);
}
function writeTabState(patch) {
writeStore(sessionStore(), TAB_STORAGE_KEY, patch);
}
function readSharedState() {
return readStore(localStore(), STORAGE_KEY);
}
function writeSharedState(patch) {
writeStore(localStore(), STORAGE_KEY, patch);
}
function deleteSharedKeys(keys) {
try {
const store = localStore();
if (!store) return;
const raw = store.getItem(STORAGE_KEY);
if (!raw) return;
const data = JSON.parse(raw);
if (!data || typeof data !== "object") return;
let changed = false;
for (const key of keys) {
if (key in data) {
delete data[key];
changed = true;
}
}
if (changed) store.setItem(STORAGE_KEY, JSON.stringify(data));
} catch { }
}
// One-time migration from the pre-per-tab layout, which stored
// open/minimized/sessionId/live in the shared key. Adopt the legacy record
// into this tab's own storage (so an in-flight terminal survives the
// upgrade) and strip the ownership fields from the shared record — from
// then on the shared sessionId/live pair is only the last-live-session
// hint. Every not-yet-migrated open tab adopts once (each into its own
// sessionStorage); the server's multi-viewer attach makes that harmless.
function migrateLegacySharedState() {
const shared = readSharedState();
if (!("open" in shared) && !("minimized" in shared)) return;
const tab = readTabState();
if (shared.open && Object.keys(tab).length === 0) {
writeTabState({
open: true,
minimized: !!shared.minimized,
sessionId: typeof shared.sessionId === "string" ? shared.sessionId : "",
live: shared.live !== false,
});
}
deleteSharedKeys(["open", "minimized"]);
}
// Merged view for geometry consumers and existing call sites: per-tab
// ownership fields win over the shared record (whose sessionId/live are
// then just the hint).
function readState() {
return Object.assign({}, readSharedState(), readTabState());
}
// Routes each field to the store that owns it: ownership fields to the
// per-tab record, geometry to the shared one.
function writeState(patch) {
const tabPatch = {};
const sharedPatch = {};
for (const [key, value] of Object.entries(patch)) {
(TAB_STATE_FIELDS.has(key) ? tabPatch : sharedPatch)[key] = value;
}
if (Object.keys(tabPatch).length) writeTabState(tabPatch);
if (Object.keys(sharedPatch).length) writeSharedState(sharedPatch);
}
// Valid terminal session id, same shape the server normalizes to.
function isValidSessionId(value) {
return typeof value === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(value);
}
function viewport() {
return {
w: Math.max(320, window.innerWidth || document.documentElement.clientWidth || 1280),
@@ -292,7 +399,12 @@
// check is handled by the panel's upgrade proxy (it rewrites the Origin
// header upstream). The page receives its session id via the URL
// fragment and uses no storage at all; the sandbox must keep excluding
// allow-same-origin.
// allow-same-origin. allow-modals is required for the terminal page's
// multi-line paste confirmation: in a sandboxed frame without it,
// window.confirm() is a silent no-op returning false, which would block
// every multi-line paste. The frame hosts only first-party, token-gated,
// nonce-CSP content, so modals carry no additional exposure.
// allow-same-origin stays excluded.
win.innerHTML = `
<div class="adp-ssh-terminal-titlebar" data-adp-ssh-drag>
<div class="adp-ssh-terminal-title">
@@ -310,7 +422,7 @@
</div>
</div>
<div class="adp-ssh-terminal-frame-wrap">
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts"></iframe>
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts allow-modals"></iframe>
</div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-n" data-adp-ssh-resize="n"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-e" data-adp-ssh-resize="e"></div>
@@ -383,8 +495,24 @@
// sees. A minted id is flagged fresh so the page skips a pointless
// attach attempt; a reused id lets the page re-attach to the
// still-live SSH session.
let sessionId = (typeof state.sessionId === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(state.sessionId)) ? state.sessionId : "";
// Resolution order: (1) this tab's own session id (its window was open
// here — navigation restore or re-open); (2) the shared last-live hint
// for a tab that has NEVER had a terminal here, so opening in a second
// tab attaches to the other tab's live session; (3) mint fresh. A tab
// that closed its own window keeps an empty sessionId in its record,
// so it deliberately starts clean instead of re-attaching. Both stores
// are read explicitly — the merged readState() would leak the shared
// hint into state.sessionId for a record-less tab and bypass the
// live !== false guard below.
const tab = readTabState();
let sessionId = isValidSessionId(tab.sessionId) ? tab.sessionId : "";
let minted = false;
if (!sessionId && !("sessionId" in tab)) {
const shared = readSharedState();
if (shared.live !== false && isValidSessionId(shared.sessionId)) {
sessionId = shared.sessionId;
}
}
if (!sessionId) {
sessionId = (window.crypto && typeof window.crypto.randomUUID === "function")
? window.crypto.randomUUID()
@@ -483,6 +611,21 @@
// Invalidate any in-flight open: after a close, a pending openTerminal
// promise is stale and must neither be reused nor write state/frame.src.
openEpoch += 1;
// A close can land mid-interaction: on touch/pen devices a second
// pointer taps the close button while the first is still dragging the
// titlebar (or a resize handle). The pending pointerup would otherwise
// hit endInteraction's !win guard and strand the page-wide grabbing
// cursor and the interaction state until some later drag completes, so
// unwind them here, before the window node goes away.
if (interaction) {
if (raf) {
cancelAnimationFrame(raf);
raf = 0;
}
if (win) win.classList.remove("is-interacting", "is-dragging", "is-resizing");
clearInteractionCursor();
interaction = null;
}
if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
if (frame && frame.contentWindow) {
try {
@@ -499,9 +642,19 @@
}
// The child receives the close signal and replies with a 'disconnect'
// message, destroying the server-side session; clearing the id here
// means the next open is a genuinely new terminal session.
// message; the server tears the shared session down when the closing
// tab was the last attached viewer, and otherwise only detaches this
// tab (other tabs keep the session live). Clearing the id here means
// the next open in this window is a genuinely new terminal session
// either way.
// All four fields are per-tab (routed to sessionStorage): closing here
// must leave every other tab's open flag and stored session id intact so
// their auto-restore keeps working. The shared hint is only marked
// not-live: this tab's frame is disconnecting, and if it was the last
// viewer the session really is gone — a still-attached tab refreshes the
// hint via its own frame's next live report.
writeState({ open: false, minimized: false, live: false, sessionId: "" });
writeSharedState({ live: false });
const old = win;
const from = old ? old.getBoundingClientRect() : null;
@@ -608,7 +761,18 @@
}
function endInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
if (!interaction) return;
if (!win) {
// Defense in depth for a window torn down mid-interaction by a path
// that did not unwind first: the geometry has nothing left to apply
// to, but the page-wide interaction cursor must still unwind or the
// page stays stuck in "grabbing"/resize cursor until a later drag
// completes.
clearInteractionCursor();
interaction = null;
return;
}
if (event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.next || clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
@@ -630,9 +794,17 @@
});
});
// Adopt/strip the pre-per-tab shared record before the restore read
// below, so an in-flight terminal survives this deploy exactly once.
migrateLegacySharedState();
// Invariant: `open: true` is only persisted after a successful launch
// (see openTerminal), so a true state here means the last open fully
// succeeded — restoring it can never resurrect a failed/ghost window.
// The flag is per-tab (sessionStorage): a close in another tab no longer
// suppresses this tab's restore, and this tab's close no longer
// suppresses theirs. The merged read still falls back to the shared
// record for geometry.
const state = readState();
if (state.open) {
// The frame reports liveness via postMessage (live on ws connect, false
@@ -709,6 +881,17 @@
const data = event.data;
if (!data || data.type !== "adpanel-ssh-terminal-live" || typeof data.live !== "boolean") return;
writeState({ live: data.live });
// Mirror liveness into the shared hint so a tab that never opened a
// terminal here can discover and attach to this tab's live session.
// live:false clears only the flag (the id stays for diagnostics); the
// frame-null guard above keeps a stale report from a dying frame out —
// closeTerminal nulls the frame before any late report can land.
if (data.live) {
const sid = readTabState().sessionId;
if (isValidSessionId(sid)) writeSharedState({ sessionId: sid, live: true });
} else {
writeSharedState({ live: false });
}
});
window.addEventListener("resize", () => {
if (!win) return;
+87 -13
View File
@@ -64,12 +64,20 @@
}
// Network bars are scaled relative to a rolling observed peak so the bar is
// meaningful even without a hard cap.
var netPeak = { rx: 1024 * 256, tx: 1024 * 256 };
// meaningful even without a hard cap. The peak decays toward the floor on
// every sample (~1min half-life at the 1s sample cadence) so a single burst
// doesn't flatten the ring for the rest of the session; sustained traffic
// keeps the peak pinned at its own level.
var NET_PEAK_FLOOR = 1024 * 256; // bytes/s lower bound for the scale
var NET_PEAK_DECAY = 0.99; // per-sample peak multiplier
var netPeak = { rx: NET_PEAK_FLOOR, tx: NET_PEAK_FLOOR };
function netPercent(dir, bps) {
bps = Number(bps) || 0;
if (bps > netPeak[dir]) netPeak[dir] = bps;
return (bps / netPeak[dir]) * 100;
var peak = netPeak[dir] * NET_PEAK_DECAY;
if (peak < NET_PEAK_FLOOR) peak = NET_PEAK_FLOOR;
if (bps > peak) peak = bps;
netPeak[dir] = peak;
return (bps / peak) * 100;
}
function applySample(s) {
@@ -112,9 +120,20 @@
}
setSvcText("svcNodes", sv.nodes ? (sv.nodes.online + "/" + sv.nodes.total + " online") : "n/a",
sv.nodes && sv.nodes.total > 0 && sv.nodes.online === sv.nodes.total);
setSvcText("svcContainers", sv.containers ? (sv.containers.running + " running, " + sv.containers.stopped + " stopped") : "n/a", true);
setSvcText("svcSsh", (sv.sshSessions || 0) + " active", true);
setSvcText("svcSockets", (sv.activeSockets || 0) + " connected", true);
// Real state, not a hardcoded "ok": stopped containers flag the row the
// same way offline nodes do, and a missing payload (probe failure or an
// older panel build) must not render green. "0 connected" is also flagged:
// anyone viewing this page live is a socket themselves, so a zero count
// means the realtime layer is down and the page is on REST fallback.
setSvcText("svcContainers",
sv.containers ? (sv.containers.running + " running, " + sv.containers.stopped + " stopped") : "n/a",
!!sv.containers && sv.containers.stopped === 0);
setSvcText("svcSsh",
sv.sshSessions != null ? sv.sshSessions + " active" : "n/a",
sv.sshSessions != null);
setSvcText("svcSockets",
sv.activeSockets != null ? sv.activeSockets + " connected" : "n/a",
Number(sv.activeSockets) > 0);
var ver = $("svcVersion");
if (ver && sv.panelVersion) ver.textContent = sv.panelVersion;
}
@@ -135,7 +154,13 @@
// ---- history graph -----------------------------------------------------
var graphMode = "today"; // or a YYYY-MM-DD string
// Last drawn day, kept so a resize can re-render at the new canvas size
// without refetching /api/status/metrics/day.
var lastGraphPoints = null;
var lastGraphLabel = "";
function drawGraph(points, label) {
lastGraphPoints = points || null;
lastGraphLabel = label || "";
var canvas = $("metricsGraph");
if (!canvas) return;
var ctx = canvas.getContext("2d");
@@ -260,6 +285,19 @@
}
}
function loadSnapshot() {
fetch("/api/status/snapshot", { credentials: "include" })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (data) {
if (data && data.ok && data.snapshot) {
applySample(data.snapshot);
}
})
.catch(function (err) {
console.warn("[monitor] snapshot fetch error:", err);
});
}
function loadSummaryAndCalendar() {
fetch("/api/status/metrics/summary", { credentials: "include" })
.then(function (r) { return r.ok ? r.json() : null; })
@@ -271,23 +309,43 @@
if (todayCell) todayCell.classList.add("cal-cell--active");
loadDay(todayKey);
})
.catch(function () { buildCalendar([]); });
.catch(function () {
buildCalendar([]);
// The resize redraw reuses the last drawn day; populate it here too,
// otherwise a summary fetch failure leaves nothing for the resize
// handler to re-render.
loadDay(new Date().toISOString().slice(0, 10));
});
}
// ---- socket wiring -----------------------------------------------------
function connectSocket() {
if (typeof io !== "function") return;
SOCKET = window._monitorSocket || io({ withCredentials: true });
if (window._monitorSocket) {
SOCKET = window._monitorSocket;
if (SOCKET.connected) {
watching = false;
subscribe();
}
return;
}
SOCKET = io({ withCredentials: true, transports: ['websocket', 'polling'] });
window._monitorSocket = SOCKET;
SOCKET.on("connect", subscribe);
SOCKET.on("connect", function () {
watching = false;
subscribe();
});
SOCKET.on("monitor:snapshot", function (snap) { applySample(snap); });
SOCKET.on("monitor:sample", function (s) { applySample(s); });
SOCKET.on("monitor:error", function (e) {
console.warn("[monitor]", e && e.error);
});
if (SOCKET.connected) subscribe();
if (SOCKET.connected) {
watching = false;
subscribe();
}
}
function subscribe() {
@@ -309,11 +367,27 @@
window.addEventListener("beforeunload", unsubscribe);
function init() {
loadSnapshot();
connectSocket();
loadSummaryAndCalendar();
// Fallback REST polling every 3 seconds to guarantee metrics stay live
setInterval(function () {
if (!document.hidden) {
loadSnapshot();
}
}, 3000);
// Redraw the already-fetched graph at the new canvas size (debounced).
// The old handler fired a /api/status/metrics/day fetch per resize
// event, so a window drag turned into a request storm.
var resizeTimer = null;
window.addEventListener("resize", function () {
if (graphMode === "today") loadDay(new Date().toISOString().slice(0, 10));
else loadDay(graphMode);
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
resizeTimer = null;
if (lastGraphPoints) drawGraph(lastGraphPoints, lastGraphLabel);
}, 150);
});
}
+64
View File
@@ -0,0 +1,64 @@
(function (root) {
'use strict';
const MAX_MOUNTS = 32;
const MAX_SPEC_LENGTH = 512;
function destination(spec) {
const segments = [];
for (const segment of spec.split(':', 2)[1].split('/')) {
if (segment === '..') segments.pop();
else if (segment && segment !== '.') segments.push(segment);
}
return '/' + segments.join('/');
}
// adpanel:template-bind-scope - mounts must stay in the server's managed
// storage so both backup and reinstall cover the configured files.
function sanitizeVolumeSpec(entry) {
const spec = String(entry ?? '').trim();
if (!spec || spec.length > MAX_SPEC_LENGTH || /[\0\r\n]/.test(spec)) return '';
const parts = spec.split(':');
if (parts.length < 2 || parts.length > 3) return '';
const [source, target, mode] = parts;
if (!/^\{(?:BOT_DIR|SERVER_DIR|DATA_DIR)\}(?:\/|$)/.test(source) || /\s/.test(source) || source.includes('\\')) return '';
if (source.split('/').some(segment => segment === '.' || segment === '..')) return '';
if (!target.startsWith('/') || /\s/.test(target) || destination(spec) === '/') return '';
if (mode !== undefined && !/^[A-Za-z0-9,]+$/.test(mode)) return '';
return spec;
}
function sanitizeTemplateVolumeList(entries) {
if (!Array.isArray(entries)) return [];
return entries.map(sanitizeVolumeSpec).filter(Boolean).slice(0, MAX_MOUNTS);
}
function validateTemplateVolumeListPayload(value) {
if (value == null) return { volumes: [] };
if (typeof value === 'string') value = value.trim() ? [value] : [];
if (!Array.isArray(value)) {
const kind = typeof value === 'object' ? 'an object' : `a ${typeof value}`;
return { error: `expected an array of "host:container" mount strings, not ${kind}` };
}
if (value.length > MAX_MOUNTS) return { error: `too many volume mounts (max ${MAX_MOUNTS})` };
const volumes = [];
const targets = new Set();
for (const entry of value) {
const spec = String(entry ?? '').trim();
if (!spec) continue;
if (!sanitizeVolumeSpec(spec)) {
const shown = spec.length > 120 ? spec.slice(0, 120) + '...' : spec;
return { error: `invalid volume mount "${shown}"; use a {BOT_DIR}, {SERVER_DIR}, or {DATA_DIR} source and an absolute container directory other than /` };
}
const target = destination(spec);
if (targets.has(target)) return { error: `duplicate volume mount destination "${target}"` };
targets.add(target);
volumes.push(spec);
}
return { volumes };
}
const api = { sanitizeVolumeSpec, sanitizeTemplateVolumeList, validateTemplateVolumeListPayload };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.ADPanelTemplateVolumes = api;
})(typeof window !== 'undefined' ? window : globalThis);