mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-25 07:09:11 +00:00
feat(gui): confirm before trashing a worker's source file (#4742)
* feat(gui): confirm before trashing a worker's source file Moving a worker's source file, or a folder that holds one, to the Trash now asks first and deletes those workers when the user agrees. Workers are found by prefix-matching the user's worker list against the trashed paths, so folders aren't walked; the list is cached for a minute and dropped when a worker is published or deleted. * fix(gui): refresh the worker list after a rename or move The cached list keeps each worker's source path, so a folder renamed or moved within the minute went to the Trash without a warning, and a folder a worker's file had just left asked to delete that worker. A move, rename or update heard over the socket now drops the cache; a move into the Trash keeps it. * fix(gui): trash anyway when a listed worker is already gone A worker deleted from another tab or the CLI since the list was cached made the delete fail with not_found, so the user saw "Worker not found" and nothing went to the Trash. That worker is already in the state the user agreed to, so the move goes ahead. * fix(gui): say which worker failed and that nothing was trashed A failed worker delete showed only the raw error, with no title, so the user couldn't tell which worker it was or whether their items had gone to the Trash. The dialog now has a title, names the worker, and says nothing was moved. * fix(gui): show the trash worker dialog over every window The dialog mounted on the body at the dashboard overlay's z-index, but phones and tablets pin every window, the dashboard included, at 9999999, so there the confirm sat hidden and trashing seemed to do nothing. Any window can trash, so the dialog now stacks over all of them, as the auth dialog does. * fix(gui): ask once when Delete is pressed again before the dialog A second Delete press while the worker list was loading opened a second confirm for the same items, so the user had to answer twice and the second answer acted on items already gone. A repeat check for the same paths while one is pending is now dropped; the first one trashes them. * fix(gui): bring back the phone selection bar when a trash is cancelled The Delete button in the phone selection bar hid the bar before trashing. Cancelling the worker dialog, or any other dialog that stops the trash, left the rows selected with no bar to act on them. The bar comes back when a selected row wasn't trashed. * fix(gui): stop waiting on a stalled worker listing after 10s The listing goes through the SDK's 15-minute idle limit, so a backend that stopped answering left Delete doing nothing, and a second press was dropped as a repeat. After 10s the trash goes ahead without the warning, as it does when the listing fails. * fix(gui): name every worker that couldn't be deleted When several worker deletes failed, the dialog named only the first, so the user didn't know the others were still running. It now lists each one with its error. * fix(gui): space lists in dashboard dialogs like paragraphs A list in a dialog's message kept the browser's margins and 40px indent, leaving a gap under it larger than the body's padding. It now takes the paragraphs' spacing and a 20px indent.
This commit is contained in:
1 parent
ed3861f289
commit
38ca3d9a76
11 files changed
+567
-4
No files matched your search
@@ -1895,7 +1895,10 @@ const TabFiles = {
|
||||
const rows = await _this.restructurableRows(selectedRows);
|
||||
if ( rows.length > 0 ) {
|
||||
$actions.removeClass('visible');
|
||||
window.move_items(rows, window.trash_path);
|
||||
await window.move_items(rows, window.trash_path);
|
||||
// A row still here and not fading out wasn't trashed (the
|
||||
// user backed out of a dialog): its bar comes back.
|
||||
if ( rows.some(row => row.isConnected && ! $(row).is(':animated')) ) _this.updateFooterStats();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ import UIWindowSaveAccount from '../UIWindowSaveAccount.js';
|
||||
import UIAuthLogin from '../Auth/UIAuthLogin.js';
|
||||
import apply_item_added_to_containers from '../../helpers/applyItemAddedToContainers.js';
|
||||
import { clear_shared_param } from '../../helpers/parseSharedPath.js';
|
||||
import { forgetWorkers, forgetWorkersAfterMove } from '../../helpers/trashWorkers.js';
|
||||
import UIDashboardNotifications from './UIDashboardNotifications.js';
|
||||
import UIDashboardContactDialog from './UIDashboardContactDialog.js';
|
||||
import {
|
||||
@@ -382,6 +383,8 @@ async function UIDashboard (options) {
|
||||
};
|
||||
|
||||
window.socket.on('item.moved', async (resp) => {
|
||||
// This tab's own moves included: they can change a worker's source path.
|
||||
forgetWorkersAfterMove(resp.path);
|
||||
if ( resp.original_client_socket_id === window.socket.id ) return;
|
||||
|
||||
// Fade out the stale row at the item's OLD location only. A moved item
|
||||
@@ -437,6 +440,8 @@ async function UIDashboard (options) {
|
||||
});
|
||||
|
||||
window.socket.on('item.renamed', async (item) => {
|
||||
// A rename can change a worker's source path.
|
||||
forgetWorkers();
|
||||
if ( item.original_client_socket_id === window.socket.id ) return;
|
||||
|
||||
const $el = $(`.item[data-uid='${item.uid}']`);
|
||||
@@ -458,6 +463,8 @@ async function UIDashboard (options) {
|
||||
});
|
||||
|
||||
window.socket.on('item.updated', async (item) => {
|
||||
// The owner hears of a rename as an update.
|
||||
forgetWorkers();
|
||||
if ( item.original_client_socket_id === window.socket.id ) return;
|
||||
|
||||
const $el = $(`.item[data-uid='${item.uid}']`);
|
||||
|
||||
@@ -48,10 +48,12 @@ const BUTTON_TYPES = new Set(['primary', 'danger', 'quiet']);
|
||||
* Turns the dialog into a prompt: Enter presses the primary button and the
|
||||
* result is the trimmed text rather than the button's value.
|
||||
* @param {jQuery} [opts.$container] Where the overlay mounts; defaults to body.
|
||||
* @param {boolean} [opts.aboveWindows] Stack over every window, the
|
||||
* dashboard's included, for a dialog any window can open.
|
||||
* @param {HTMLElement} [opts.returnFocusTo] Where focus goes on close.
|
||||
* @returns {Promise<unknown>}
|
||||
*/
|
||||
export default function UIDashboardDialog ({ title, message, tone, buttons, input, $container, returnFocusTo }) {
|
||||
export default function UIDashboardDialog ({ title, message, tone, buttons, input, $container, aboveWindows, returnFocusTo }) {
|
||||
const { html_encode } = window;
|
||||
const id = window.uuidv4?.() ?? String(Date.now());
|
||||
const toneClass = TONES.has(tone) ? ` dashboard-dialog-${tone}` : '';
|
||||
@@ -94,6 +96,7 @@ export default function UIDashboardDialog ({ title, message, tone, buttons, inpu
|
||||
returnFocusTo,
|
||||
onDismiss: () => resolve(false),
|
||||
});
|
||||
if ( aboveWindows ) $overlay.addClass('dashboard-dialog-above-windows');
|
||||
|
||||
const $input = $overlay.find('.dashboard-dialog-input');
|
||||
// A prompt wants the text; anything else, the safest button.
|
||||
|
||||
@@ -50,6 +50,12 @@ describe('UIDashboardDialog', () => {
|
||||
expect($('.dashboard-dialog-message').html()).toBe('hello');
|
||||
});
|
||||
|
||||
it('stacks over every window only when asked to', () => {
|
||||
UIDashboardDialog({ message: 'm' });
|
||||
UIDashboardDialog({ message: 'm', aboveWindows: true });
|
||||
expect(overlay().map((_, el) => $(el).hasClass('dashboard-dialog-above-windows')).get()).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it('resolves with the pressed button value', async () => {
|
||||
const p = UIDashboardDialog({
|
||||
message: 'm',
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
import ensure_can_publish from '../../helpers/ensureCanPublish.js';
|
||||
import forget_parent_listing from '../../helpers/forgetParentListing.js';
|
||||
import { forgetWorkers } from '../../helpers/trashWorkers.js';
|
||||
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
|
||||
import { openLinkHtml, publishDomainFields, setupPublishDomain } from './publishDomain.js';
|
||||
import { finalizePublishName, normalizePublishName, PUBLISH_NAME_RULES } from './publishName.js';
|
||||
@@ -95,6 +96,7 @@ const KINDS = {
|
||||
}],
|
||||
async publish (name, path, { sandboxed }) {
|
||||
const result = await puter.workers.create(name, path, { sandbox: sandboxed });
|
||||
forgetWorkers();
|
||||
return result?.url ?? `https://${name}.puter.work`;
|
||||
},
|
||||
markPublished (path, url) {
|
||||
|
||||
@@ -54,6 +54,7 @@ import { httpsIconFor, notificationTarget, senderNameFor } from './Dashboard/not
|
||||
import apply_item_added_to_containers from '../helpers/applyItemAddedToContainers.js';
|
||||
import parse_item_metadata from '../helpers/parseItemMetadata.js';
|
||||
import { resolve_default_app } from '../helpers/defaultApp.js';
|
||||
import { forgetWorkers, forgetWorkersAfterMove } from '../helpers/trashWorkers.js';
|
||||
|
||||
async function UIDesktop () {
|
||||
// start a transaction if we're not in embedded or fullpage mode
|
||||
@@ -338,6 +339,8 @@ async function UIDesktop () {
|
||||
});
|
||||
|
||||
window.socket.on('item.updated', async (item) => {
|
||||
// The owner hears of a rename as an update.
|
||||
forgetWorkers();
|
||||
// Don't update if this is the original client that initiated the action
|
||||
if ( item.original_client_socket_id === window.socket.id )
|
||||
{
|
||||
@@ -395,6 +398,7 @@ async function UIDesktop () {
|
||||
});
|
||||
|
||||
window.socket.on('item.moved', async (resp) => {
|
||||
forgetWorkersAfterMove(resp.path);
|
||||
let fsentry = resp;
|
||||
// Notify all apps that are watching this item
|
||||
window.sendItemChangeEventToWatchingApps(fsentry.uid, {
|
||||
@@ -563,6 +567,8 @@ async function UIDesktop () {
|
||||
});
|
||||
|
||||
window.socket.on('item.renamed', async (item) => {
|
||||
// A rename can change a worker's source path.
|
||||
forgetWorkers();
|
||||
// Notify all apps that are watching this item
|
||||
window.sendItemChangeEventToWatchingApps(item.uid, {
|
||||
event: 'rename',
|
||||
|
||||
@@ -9961,6 +9961,11 @@ body.dashboard-mode .notifications-close-all {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Above every window (phones pin them all at 9999999, the dashboard's
|
||||
included) and under the stay-on-top band, like the auth dialog. */
|
||||
.dashboard-dialog-overlay.dashboard-dialog-above-windows {
|
||||
z-index: 99999998;
|
||||
}
|
||||
.dashboard-dialog-overlay.dashboard-dialog-show {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
@@ -10099,11 +10104,17 @@ body.dashboard-mode .notifications-close-all {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-dialog-message p {
|
||||
.dashboard-dialog-message p,
|
||||
.dashboard-dialog-message ul {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.dashboard-dialog-message p:last-child {
|
||||
.dashboard-dialog-message ul {
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.dashboard-dialog-message p:last-child,
|
||||
.dashboard-dialog-message ul:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import { invalidate_shared_roots } from './helpers/sharedAccess.js';
|
||||
import truncate_filename from './helpers/truncateFilename.js';
|
||||
import update_title_based_on_uploads from './helpers/updateTitleBasedOnUploads.js';
|
||||
import update_username_in_gui from './helpers/updateUsernameInGui.js';
|
||||
import { confirmTrashingWorkers } from './helpers/trashWorkers.js';
|
||||
import { notifyItemWatchers } from './helpers/watchItems.js';
|
||||
import { select_uploaded_items } from './helpers/uploadSelection.js';
|
||||
import { templateMenuItem } from './helpers/templateMenuItem.js';
|
||||
@@ -1795,6 +1796,15 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Trashing a worker's source file, or a folder holding one, deletes the
|
||||
// worker; the user agrees to that first.
|
||||
if ( dest_path === window.trash_path ) {
|
||||
const trashed_paths = Array.from(el_items)
|
||||
.filter(el_item => $(el_item).attr('data-immutable') !== '1')
|
||||
.map(el_item => $(el_item).attr('data-path'));
|
||||
if ( ! await confirmTrashingWorkers(trashed_paths) ) return;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
// good to go, proceed
|
||||
// --------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIDashboardDialog from '../UI/Dashboard/UIDashboardDialog.js';
|
||||
|
||||
/** @typedef {{ name: string, file_path?: string | null }} Worker */
|
||||
|
||||
/** Long enough that trashing several things in a row costs one listing. */
|
||||
const WORKER_LIST_TTL = 60 * 1000;
|
||||
|
||||
/** How long a trash waits for the listing before going ahead without it. */
|
||||
const WORKER_LIST_WAIT = 10 * 1000;
|
||||
|
||||
/** @type {{ at: number, promise: Promise<Worker[]> } | null} */
|
||||
let workerListCache = null;
|
||||
|
||||
/** Path sets whose trashing is waiting on the listing, the user, or a delete. */
|
||||
const pendingTrashes = new Set();
|
||||
|
||||
/**
|
||||
* The user's workers, from a short-lived cache. A listing that failed isn't
|
||||
* cached, so the next call tries again.
|
||||
*
|
||||
* @returns {Promise<Worker[]>}
|
||||
*/
|
||||
export const listWorkers = async () => {
|
||||
if ( workerListCache && Date.now() - workerListCache.at < WORKER_LIST_TTL ) {
|
||||
return workerListCache.promise;
|
||||
}
|
||||
const entry = {
|
||||
at: Date.now(),
|
||||
promise: puter.workers.list().then(list => (Array.isArray(list) ? list : [])),
|
||||
};
|
||||
workerListCache = entry;
|
||||
entry.promise.catch(() => {
|
||||
if ( workerListCache === entry ) workerListCache = null;
|
||||
});
|
||||
return entry.promise;
|
||||
};
|
||||
|
||||
/** Drops the cached listing: a worker was created or deleted, or a path changed. */
|
||||
export const forgetWorkers = () => {
|
||||
workerListCache = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Drops the cached listing after an item moved to `path`. A move into the
|
||||
* Trash keeps it: the workers it would affect are deleted before the move.
|
||||
*
|
||||
* @param {string | undefined} path
|
||||
*/
|
||||
export const forgetWorkersAfterMove = (path) => {
|
||||
if ( path?.startsWith(`${window.trash_path}/`) ) return;
|
||||
forgetWorkers();
|
||||
};
|
||||
|
||||
/**
|
||||
* The workers whose source file is one of `paths` or inside one of them.
|
||||
* Matches by path prefix, so a folder isn't walked. Paths compare ignoring
|
||||
* case, like the rest of the GUI.
|
||||
*
|
||||
* @param {Worker[]} workers
|
||||
* @param {string[]} paths
|
||||
* @returns {Worker[]}
|
||||
*/
|
||||
export const workersUnderPaths = (workers, paths) => {
|
||||
const roots = paths.filter(Boolean).map(p => p.toLowerCase());
|
||||
if ( roots.length === 0 ) return [];
|
||||
return workers.filter((worker) => {
|
||||
const file = worker?.file_path?.toLowerCase();
|
||||
if ( ! file ) return false;
|
||||
return roots.some(root => file === root || file.startsWith(`${root}/`));
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Before `paths` go to the Trash: if any of them is, or holds, a worker's
|
||||
* source file, asks the user and deletes those workers. Resolves `true` when
|
||||
* trashing may go ahead. A listing that fails or stalls doesn't block
|
||||
* trashing. A repeat for the same paths while the first is pending (a second
|
||||
* Delete press) resolves `false`: the first call trashes them.
|
||||
*
|
||||
* @param {string[]} paths
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const confirmTrashingWorkers = async (paths) => {
|
||||
const key = [...paths].sort().join('\n');
|
||||
if ( pendingTrashes.has(key) ) return false;
|
||||
pendingTrashes.add(key);
|
||||
try {
|
||||
return await askAndDeleteWorkers(paths);
|
||||
} finally {
|
||||
pendingTrashes.delete(key);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The check itself, run once per pending path set.
|
||||
*
|
||||
* @param {string[]} paths
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
const askAndDeleteWorkers = async (paths) => {
|
||||
let workers;
|
||||
let timer;
|
||||
try {
|
||||
// A stalled listing would hold the trash with nothing on screen.
|
||||
const deadline = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('worker listing timed out')), WORKER_LIST_WAIT);
|
||||
});
|
||||
workers = workersUnderPaths(await Promise.race([listWorkers(), deadline]), paths);
|
||||
} catch {
|
||||
return true;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if ( workers.length === 0 ) return true;
|
||||
|
||||
const single = workers.length === 1;
|
||||
const message = single
|
||||
? `<p>${i18n('trash_deletes_worker', [workers[0].name])}</p>`
|
||||
: `<p>${i18n('trash_deletes_workers')}</p><ul>${workers.map(w => `<li><strong>${html_encode(w.name)}</strong></li>`).join('')}</ul>`;
|
||||
const confirmed = await UIDashboardDialog({
|
||||
title: i18n(single ? 'delete_worker_title' : 'delete_workers_title', [], false),
|
||||
message,
|
||||
tone: 'danger',
|
||||
// Any window can trash, and phones stack every window over a body overlay.
|
||||
aboveWindows: true,
|
||||
buttons: [
|
||||
{ label: i18n('cancel', [], false), value: false, type: 'quiet' },
|
||||
{ label: i18n('delete', [], false), value: true, type: 'danger' },
|
||||
],
|
||||
});
|
||||
if ( confirmed !== true ) return false;
|
||||
|
||||
const results = await Promise.allSettled(workers.map(w => puter.workers.delete(w.name)));
|
||||
forgetWorkers();
|
||||
// A worker deleted elsewhere since the list was read is already gone.
|
||||
const failures = workers
|
||||
.map((worker, i) => ({ worker, result: results[i] }))
|
||||
.filter(({ result }) => result.status === 'rejected' && result.reason?.code !== 'not_found');
|
||||
if ( failures.length > 0 ) {
|
||||
const reasonOf = ({ result }) => html_encode(result.reason?.message ?? i18n('error_unknown_cause', [], false));
|
||||
const message = failures.length === 1
|
||||
? `<p>${i18n('trash_worker_delete_failed', [failures[0].worker.name])}</p><p>${reasonOf(failures[0])}</p>`
|
||||
: `<p>${i18n('trash_workers_delete_failed')}</p><ul>${failures.map(f => `<li><strong>${html_encode(f.worker.name)}</strong>: ${reasonOf(f)}</li>`).join('')}</ul>`;
|
||||
await UIDashboardDialog({
|
||||
title: i18n(failures.length === 1 ? 'trash_worker_delete_failed_title' : 'trash_workers_delete_failed_title', [], false),
|
||||
message,
|
||||
tone: 'error',
|
||||
aboveWindows: true,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,335 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
globalThis.html_encode = (value) => String(value ?? '')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
// Encodes replacements, as the real i18n() does by default.
|
||||
globalThis.i18n = (key, replacements) => (Array.isArray(replacements) && replacements.length
|
||||
? `${key}:${replacements.map(globalThis.html_encode).join(',')}`
|
||||
: key);
|
||||
window.html_encode = globalThis.html_encode;
|
||||
window.requestAnimationFrame = (fn) => setTimeout(fn, 0);
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
|
||||
const { confirmTrashingWorkers, forgetWorkers, forgetWorkersAfterMove, listWorkers, workersUnderPaths } = await import('./trashWorkers.js');
|
||||
|
||||
const API = { name: 'api', file_path: '/alice/Projects/api/index.js' };
|
||||
const CRON = { name: 'cron', file_path: '/alice/Projects/cron.js' };
|
||||
const GONE = { name: 'gone', file_path: null };
|
||||
|
||||
const settle = async () => {
|
||||
for ( let i = 0; i < 5; i++ ) await new Promise(resolve => setTimeout(resolve, 0));
|
||||
};
|
||||
// A closed dialog stays in the DOM while it fades out, without the show
|
||||
// class; of the open ones, the newest is on top.
|
||||
const dialog = () => $('.dashboard-dialog-overlay.dashboard-dialog-show .dashboard-dialog').last();
|
||||
const press = async (label) => {
|
||||
dialog().find('.dashboard-dialog-btn').filter((_, el) => $(el).text() === label).trigger('click');
|
||||
await settle();
|
||||
};
|
||||
|
||||
const stubWorkers = (list, del = async () => true) => {
|
||||
globalThis.puter = {
|
||||
workers: {
|
||||
list: vi.fn(async () => list),
|
||||
delete: vi.fn(del),
|
||||
},
|
||||
};
|
||||
return globalThis.puter.workers;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
forgetWorkers();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('workersUnderPaths', () => {
|
||||
it('matches a worker by its own source file', () => {
|
||||
expect(workersUnderPaths([API, CRON], ['/alice/Projects/cron.js'])).toEqual([CRON]);
|
||||
});
|
||||
|
||||
it('matches every worker inside a folder without walking it', () => {
|
||||
expect(workersUnderPaths([API, CRON], ['/alice/Projects'])).toEqual([API, CRON]);
|
||||
});
|
||||
|
||||
it('ignores a sibling whose name only starts with the folder name', () => {
|
||||
expect(workersUnderPaths([API], ['/alice/Projects/ap'])).toEqual([]);
|
||||
expect(workersUnderPaths([API], ['/alice/Projects/api/index'])).toEqual([]);
|
||||
});
|
||||
|
||||
it('compares paths ignoring case', () => {
|
||||
expect(workersUnderPaths([API], ['/alice/projects/API'])).toEqual([API]);
|
||||
});
|
||||
|
||||
it('skips workers whose source file no longer exists', () => {
|
||||
expect(workersUnderPaths([GONE], ['/alice'])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listWorkers', () => {
|
||||
it('lists once for calls within the cache window', async () => {
|
||||
const workers = stubWorkers([API]);
|
||||
await listWorkers();
|
||||
await listWorkers();
|
||||
expect(workers.list).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('lists again once the cache expires', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
const workers = stubWorkers([API]);
|
||||
await listWorkers();
|
||||
vi.setSystemTime(Date.now() + 61 * 1000);
|
||||
await listWorkers();
|
||||
expect(workers.list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('lists again after forgetWorkers()', async () => {
|
||||
const workers = stubWorkers([API]);
|
||||
await listWorkers();
|
||||
forgetWorkers();
|
||||
await listWorkers();
|
||||
expect(workers.list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('lists again after an item moves somewhere other than the Trash', async () => {
|
||||
window.trash_path = '/alice/Trash';
|
||||
const workers = stubWorkers([API]);
|
||||
await listWorkers();
|
||||
forgetWorkersAfterMove('/alice/Archive/Projects');
|
||||
await listWorkers();
|
||||
expect(workers.list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keeps the listing when an item moves into the Trash', async () => {
|
||||
window.trash_path = '/alice/Trash';
|
||||
const workers = stubWorkers([API]);
|
||||
await listWorkers();
|
||||
forgetWorkersAfterMove('/alice/Trash/2f1c-notes.txt');
|
||||
await listWorkers();
|
||||
expect(workers.list).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not cache a failed listing', async () => {
|
||||
const workers = stubWorkers([API]);
|
||||
workers.list.mockRejectedValueOnce(new Error('offline'));
|
||||
await expect(listWorkers()).rejects.toThrow('offline');
|
||||
await expect(listWorkers()).resolves.toEqual([API]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('confirmTrashingWorkers', () => {
|
||||
it('goes ahead without asking when nothing trashed holds a worker', async () => {
|
||||
const workers = stubWorkers([API]);
|
||||
await expect(confirmTrashingWorkers(['/alice/Documents'])).resolves.toBe(true);
|
||||
expect(dialog().length).toBe(0);
|
||||
expect(workers.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('goes ahead without asking when the worker list is unavailable', async () => {
|
||||
const workers = stubWorkers([API]);
|
||||
workers.list.mockRejectedValueOnce(new Error('offline'));
|
||||
await expect(confirmTrashingWorkers(['/alice/Projects'])).resolves.toBe(true);
|
||||
expect(dialog().length).toBe(0);
|
||||
});
|
||||
|
||||
it('goes ahead without asking when the worker list stalls', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
const workers = stubWorkers([API]);
|
||||
workers.list.mockReturnValueOnce(new Promise(() => {}));
|
||||
const result = confirmTrashingWorkers(['/alice/Projects']);
|
||||
let settled = false;
|
||||
result.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(9 * 1000);
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(dialog().length).toBe(0);
|
||||
});
|
||||
|
||||
it('names the worker and deletes it once the user confirms', async () => {
|
||||
const workers = stubWorkers([API, CRON]);
|
||||
const result = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await settle();
|
||||
|
||||
expect(dialog().find('.dashboard-dialog-title').text()).toBe('delete_worker_title');
|
||||
// Any window can trash, so the dialog can't sit under one.
|
||||
expect(dialog().closest('.dashboard-dialog-overlay').hasClass('dashboard-dialog-above-windows')).toBe(true);
|
||||
expect(dialog().find('.dashboard-dialog-message').text()).toBe('trash_deletes_worker:cron');
|
||||
await press('delete');
|
||||
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(workers.delete).toHaveBeenCalledTimes(1);
|
||||
expect(workers.delete).toHaveBeenCalledWith('cron');
|
||||
});
|
||||
|
||||
it('lists every worker inside a trashed folder', async () => {
|
||||
const workers = stubWorkers([API, CRON]);
|
||||
const result = confirmTrashingWorkers(['/alice/Projects']);
|
||||
await settle();
|
||||
|
||||
expect(dialog().find('.dashboard-dialog-title').text()).toBe('delete_workers_title');
|
||||
expect(dialog().find('li').map((_, el) => $(el).text()).get()).toEqual(['api', 'cron']);
|
||||
await press('delete');
|
||||
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(workers.delete.mock.calls.map(call => call[0]).sort()).toEqual(['api', 'cron']);
|
||||
});
|
||||
|
||||
it('escapes worker names in the message', async () => {
|
||||
stubWorkers([{ name: '<b>x</b>', file_path: '/alice/x.js' }]);
|
||||
const result = confirmTrashingWorkers(['/alice']);
|
||||
await settle();
|
||||
expect(dialog().find('.dashboard-dialog-message b').length).toBe(0);
|
||||
await press('cancel');
|
||||
await result;
|
||||
});
|
||||
|
||||
it('keeps the items and the worker when the user cancels', async () => {
|
||||
const workers = stubWorkers([CRON]);
|
||||
const result = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await settle();
|
||||
await press('cancel');
|
||||
|
||||
await expect(result).resolves.toBe(false);
|
||||
expect(workers.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops and names the worker that could not be deleted', async () => {
|
||||
const workers = stubWorkers([API, CRON], async (name) => {
|
||||
if ( name === 'cron' ) throw { message: 'Permission denied', code: 'forbidden' };
|
||||
return true;
|
||||
});
|
||||
const result = confirmTrashingWorkers(['/alice/Projects']);
|
||||
await settle();
|
||||
await press('delete');
|
||||
|
||||
expect(dialog().find('.dashboard-dialog-title').text()).toBe('trash_worker_delete_failed_title');
|
||||
expect(dialog().find('.dashboard-dialog-message p').map((_, el) => $(el).text()).get())
|
||||
.toEqual(['trash_worker_delete_failed:cron', 'Permission denied']);
|
||||
await press('ok');
|
||||
await expect(result).resolves.toBe(false);
|
||||
expect(workers.delete).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('names every worker that could not be deleted', async () => {
|
||||
stubWorkers([API, CRON, { name: 'mail', file_path: '/alice/Projects/mail.js' }], async (name) => {
|
||||
if ( name === 'api' ) return true;
|
||||
if ( name === 'mail' ) throw { message: 'Worker not found', code: 'not_found' };
|
||||
throw { message: `Could not delete ${name}`, code: 'internal' };
|
||||
});
|
||||
const result = confirmTrashingWorkers(['/alice/Projects']);
|
||||
await settle();
|
||||
await press('delete');
|
||||
expect(dialog().find('.dashboard-dialog-title').text()).toBe('trash_worker_delete_failed_title');
|
||||
await press('ok');
|
||||
await expect(result).resolves.toBe(false);
|
||||
|
||||
const workers = stubWorkers([API, CRON, { name: 'mail', file_path: '/alice/Projects/mail.js' }], async (name) => {
|
||||
if ( name === 'cron' ) return true;
|
||||
throw { message: `Could not delete <${name}>`, code: 'internal' };
|
||||
});
|
||||
const again = confirmTrashingWorkers(['/alice/Projects']);
|
||||
await settle();
|
||||
await press('delete');
|
||||
|
||||
expect(dialog().find('.dashboard-dialog-title').text()).toBe('trash_workers_delete_failed_title');
|
||||
expect(dialog().find('.dashboard-dialog-message p').text()).toBe('trash_workers_delete_failed');
|
||||
expect(dialog().find('li').map((_, el) => $(el).text()).get())
|
||||
.toEqual(['api: Could not delete <api>', 'mail: Could not delete <mail>']);
|
||||
await press('ok');
|
||||
await expect(again).resolves.toBe(false);
|
||||
expect(workers.delete).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('goes ahead when a worker was already deleted elsewhere', async () => {
|
||||
const workers = stubWorkers([API, CRON], async (name) => {
|
||||
if ( name === 'cron' ) throw { message: 'Worker not found', code: 'not_found' };
|
||||
return true;
|
||||
});
|
||||
const result = confirmTrashingWorkers(['/alice/Projects']);
|
||||
await settle();
|
||||
await press('delete');
|
||||
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(workers.delete).toHaveBeenCalledTimes(2);
|
||||
expect($('.dashboard-dialog-error').length).toBe(0);
|
||||
});
|
||||
|
||||
it('asks once when the same items are trashed again before the first answer', async () => {
|
||||
const workers = stubWorkers([CRON]);
|
||||
const first = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
const repeat = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await expect(repeat).resolves.toBe(false);
|
||||
await settle();
|
||||
expect($('.dashboard-dialog-overlay')).toHaveLength(1);
|
||||
|
||||
await press('delete');
|
||||
await expect(first).resolves.toBe(true);
|
||||
expect(workers.delete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('checks other items trashed meanwhile on their own', async () => {
|
||||
stubWorkers([API, CRON]);
|
||||
const first = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
const other = confirmTrashingWorkers(['/alice/Projects/api']);
|
||||
await settle();
|
||||
expect($('.dashboard-dialog-overlay')).toHaveLength(2);
|
||||
await press('cancel');
|
||||
await press('cancel');
|
||||
await expect(first).resolves.toBe(false);
|
||||
await expect(other).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('checks the same items again once the first check is done', async () => {
|
||||
stubWorkers([CRON]);
|
||||
const first = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await settle();
|
||||
await press('cancel');
|
||||
await expect(first).resolves.toBe(false);
|
||||
|
||||
const again = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await settle();
|
||||
expect(dialog().find('.dashboard-dialog-message').text()).toBe('trash_deletes_worker:cron');
|
||||
await press('cancel');
|
||||
await expect(again).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('lists afresh after deleting, so a deleted worker is not asked about again', async () => {
|
||||
const workers = stubWorkers([CRON]);
|
||||
const result = confirmTrashingWorkers(['/alice/Projects/cron.js']);
|
||||
await settle();
|
||||
await press('delete');
|
||||
await result;
|
||||
|
||||
workers.list.mockResolvedValueOnce([]);
|
||||
await expect(confirmTrashingWorkers(['/alice/Projects/cron.js'])).resolves.toBe(true);
|
||||
expect(workers.list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -755,6 +755,14 @@ const en = {
|
||||
download_as_tar: 'Download as Tar',
|
||||
sequencing: 'Sequencing %strong%',
|
||||
worker: 'Worker',
|
||||
delete_worker_title: 'Delete Worker?',
|
||||
delete_workers_title: 'Delete Workers?',
|
||||
trash_deletes_worker: 'Moving to the Trash also deletes the worker %strong%. Its URL will stop working.',
|
||||
trash_deletes_workers: 'Moving to the Trash also deletes these workers. Their URLs will stop working.',
|
||||
trash_worker_delete_failed: 'The worker %strong% couldn\'t be deleted, so nothing was moved to the Trash.',
|
||||
trash_worker_delete_failed_title: 'Couldn\'t Delete Worker',
|
||||
trash_workers_delete_failed: 'These workers couldn\'t be deleted, so nothing was moved to the Trash.',
|
||||
trash_workers_delete_failed_title: 'Couldn\'t Delete Workers',
|
||||
worker_published: 'Your worker is live',
|
||||
worker_sandboxed: 'Sandboxed',
|
||||
worker_sandboxed_hint: 'Keeps the worker\'s data separate from the rest of your account.',
|
||||
|
||||
Reference in new issue
Block a user