diff --git a/src/gui/src/UI/Dashboard/TabFiles.js b/src/gui/src/UI/Dashboard/TabFiles.js index 713d61506..183de9750 100644 --- a/src/gui/src/UI/Dashboard/TabFiles.js +++ b/src/gui/src/UI/Dashboard/TabFiles.js @@ -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(); } } }); diff --git a/src/gui/src/UI/Dashboard/UIDashboard.js b/src/gui/src/UI/Dashboard/UIDashboard.js index 71f2aa8bb..6c7ea1df3 100644 --- a/src/gui/src/UI/Dashboard/UIDashboard.js +++ b/src/gui/src/UI/Dashboard/UIDashboard.js @@ -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}']`); diff --git a/src/gui/src/UI/Dashboard/UIDashboardDialog.js b/src/gui/src/UI/Dashboard/UIDashboardDialog.js index 4d874e4c9..5206419a7 100644 --- a/src/gui/src/UI/Dashboard/UIDashboardDialog.js +++ b/src/gui/src/UI/Dashboard/UIDashboardDialog.js @@ -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} */ -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. diff --git a/src/gui/src/UI/Dashboard/UIDashboardDialog.test.js b/src/gui/src/UI/Dashboard/UIDashboardDialog.test.js index 4f2003583..bbd308614 100644 --- a/src/gui/src/UI/Dashboard/UIDashboardDialog.test.js +++ b/src/gui/src/UI/Dashboard/UIDashboardDialog.test.js @@ -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', diff --git a/src/gui/src/UI/Dashboard/UIPublishDialogs.js b/src/gui/src/UI/Dashboard/UIPublishDialogs.js index fb81f59e0..34e02d623 100644 --- a/src/gui/src/UI/Dashboard/UIPublishDialogs.js +++ b/src/gui/src/UI/Dashboard/UIPublishDialogs.js @@ -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) { diff --git a/src/gui/src/UI/UIDesktop.js b/src/gui/src/UI/UIDesktop.js index a39b3d13c..8f0182c99 100644 --- a/src/gui/src/UI/UIDesktop.js +++ b/src/gui/src/UI/UIDesktop.js @@ -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', diff --git a/src/gui/src/css/dashboard.css b/src/gui/src/css/dashboard.css index ad353151c..0b969c775 100644 --- a/src/gui/src/css/dashboard.css +++ b/src/gui/src/css/dashboard.css @@ -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; } diff --git a/src/gui/src/helpers.js b/src/gui/src/helpers.js index e2b7a29d5..37b22d4bc 100644 --- a/src/gui/src/helpers.js +++ b/src/gui/src/helpers.js @@ -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 // -------------------------------------------------------- diff --git a/src/gui/src/helpers/trashWorkers.js b/src/gui/src/helpers/trashWorkers.js new file mode 100644 index 000000000..2e8cc5693 --- /dev/null +++ b/src/gui/src/helpers/trashWorkers.js @@ -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 . + */ + +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 } | 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} + */ +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} + */ +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} + */ +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 + ? `

${i18n('trash_deletes_worker', [workers[0].name])}

` + : `

${i18n('trash_deletes_workers')}

    ${workers.map(w => `
  • ${html_encode(w.name)}
  • `).join('')}
`; + 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 + ? `

${i18n('trash_worker_delete_failed', [failures[0].worker.name])}

${reasonOf(failures[0])}

` + : `

${i18n('trash_workers_delete_failed')}

    ${failures.map(f => `
  • ${html_encode(f.worker.name)}: ${reasonOf(f)}
  • `).join('')}
`; + 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; +}; diff --git a/src/gui/src/helpers/trashWorkers.test.js b/src/gui/src/helpers/trashWorkers.test.js new file mode 100644 index 000000000..c7a81e40a --- /dev/null +++ b/src/gui/src/helpers/trashWorkers.test.js @@ -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 . + */ +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, '"'); +// 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: 'x', 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 ', 'mail: Could not delete ']); + 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); + }); +}); diff --git a/src/gui/src/i18n/translations/en.js b/src/gui/src/i18n/translations/en.js index 7d5db54de..2ccab970f 100644 --- a/src/gui/src/i18n/translations/en.js +++ b/src/gui/src/i18n/translations/en.js @@ -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.',