diff --git a/docs/architecture.md b/docs/architecture.md index 4f57188..0469b99 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -762,6 +762,13 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **UI (`ui/src/components/deploy/`):** `deploy.ts` store, `DeployStatusItem.vue` (progress, Cancel, the `deployment.*` UI commands), `DeploymentDialog.vue` (exclusive modal `deployment`; write-only secret field; host-key question), `DeploymentLogToolWindow.vue` (bottom panel). The project tree's context menu gains Upload/Download for files and folders. - **Tests:** `crates/deploy/tests/transfer.rs` (7: host key first use and mismatch, password and key sign-in, upload, download, cancel, FTP, unreachable), `crates/engine/tests/deploy.rs` (4, including a grep of every event, value, error and the config and data directories for the test password), `ui/tests/deploy/Deploy.test.ts` (12). +### Remote browser, compare and sync (C9 D2) + +- **Crate:** `Remote` gains `remove_file`, `remove_dir`, `rename` (SFTP, FTP, folder; the test servers too: SFTP `rename`, FTP `RMD`, `DELE`, `RNFR`/`RNTO`). `browse`: browser paths relative to the root (absolute and `..` refused); `list` (folders first), `read` (`Target::Mapped` project path or `Target::Browser` path; at most 4 MiB, NUL or invalid UTF-8 → binary, missing → `text: None`), `write` (creates the folder), `rename`, `mkdir`, `delete` (recursive, never the root). `job::compare` walks the local tree and the remote listings (sizes from the server; `walk_remote_tree` also serves downloads now) and reports `localOnly`, `remoteOnly`, `different` (size, then contents up to 8 MiB); `job::sync` uploads files and deletes listed files in one connection; `Summary.deleted`. +- **Engine (`cmd/deploy_remote.rs`):** `deploy.browse {path?, id?}`, `deploy.readRemote {path | remotePath, id?}` (answers like `git.show`: `{text, binary, tooLarge}`), `deploy.writeRemote {remotePath, text, id?}`, `deploy.renameRemote {from, to, id?}`, `deploy.mkdirRemote {path, id?}`, `deploy.deleteRemote {path, confirm: true, id?}`, `deploy.compare {paths, id?}`, `deploy.sync {upload?, delete?, confirmDelete, id?}`. Same job slot and events as D1. Missing confirmations are `invalid_params` before any connection. `deploy.upload {saveFirst?}` (default true) saves the dirty buffers under its paths through `file::save_buffer` while `DeployState.saving` keeps those saves from queueing uploads on save. +- **UI:** `remoteBrowser.ts` store; `RemoteBrowserToolWindow.vue` (bottom panel tab `remote`: server select, tree, inline rename / new folder / delete question, read-only viewer with Edit and Upload); `SyncDialog.vue` (exclusive modal `deploySync`); the diff store's server tabs (`DiffTab.remote`, `openRemote`, left side from `deploy.readRemote`). UI commands `deployment.browse`, `deployment.compare {path?, kind?}`, `deployment.sync`; the tree menu adds Compare with Server. +- **Tests:** `crates/deploy/tests/remote.rs` (2: the whole browser, compare and sync scenario over SFTP and over FTP), `crates/engine/tests/deploy.rs` (+1: commands, refused unconfirmed deletes, sync, save before upload), `ui/tests/deploy/RemoteBrowser.test.ts` (6). + ## Decisions (M0) | Question | Decision | Why | @@ -782,6 +789,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | C9 D2: remote browser, compare and sync; save before upload | | 2026-11-06 | minor | C9 D1: `crates/deploy` (L3), `deploy.*` commands, deployment events and UI | | 2026-11-02 | minor | C9 F1: `Kind::Path` and `check_path` (one validator for `settings.set` and the dialog, `path` in `settings.list`), `lutra_proc::spawn_detached` for the CLI's desktop start | | 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` | diff --git a/docs/deployment.md b/docs/deployment.md index d67b93b..5d9c5b6 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1,6 +1,6 @@ # Deployment -> **Status:** Deployment v1 (C9 D1, owner decision D27): servers per project, upload, download, upload on save, test connection, host keys, Deployment log. Remote browser, compare and sync follow in D2 · **Last updated:** 2026-11-06 +> **Status:** Deployment v1 (C9 D1, owner decision D27): servers per project, upload, download, upload on save, test connection, host keys, Deployment log. v2 (C9 D2): Remote Host browser, compare with the server, sync with a preview, save before upload · **Last updated:** 2026-11-06 Lutra uploads a PHP project to a server and downloads files back, the way people deploy shared hosting and small servers every day. @@ -41,14 +41,29 @@ Uploads and downloads never ask about a key; they fail with a message pointing t - **Project tree:** right-click a file or folder › **Upload to Server** / **Download from Server** (default server). - **Tools › Deployment:** Upload Current File, Download Current File, Upload Project, Test Connection, Deployment Log. - The same actions are in the command palette. Lutra assigns no default shortcuts; bind them in the keymap. -- Uploads send what is on disk; save first. Downloads replace the local files. +- An upload first saves the open, unsaved files it covers, so the server gets what the editor shows. Downloads replace the local files. - While a job runs, the status bar shows it with a Cancel button. One job runs at a time; uploads on save wait for the running one. - Every file, skip and error goes to the **Deployment** log in the bottom panel (newest 1,000 lines). A failing file is logged and the job goes on; a lost connection or a refused sign-in stops it. Each error says what to do. +## Remote Host + +**Tools › Deployment › Remote Host** opens the server's folders in the bottom panel (the default server; choose another in the toolbar). Paths are relative to the server's root folder; the browser never leaves it. + +- Click a folder to expand it, a file to open it. Files open **read-only**; **Edit** makes the text editable and **Upload** writes it back. Files that are not text, or larger than 4 MiB, are not shown. +- **Rename** and **Delete on Server** are on each row; **New Folder** goes into the selected folder. Delete always asks first, names what goes (a folder with everything inside it), and only the red button deletes. The root folder cannot be deleted. + +## Compare and sync + +- **Compare with Server** on a file (project tree, or Tools › Deployment › Compare Current File with Server) opens the diff viewer: the server's copy on the left (read-only), your working copy on the right (editable as usual). +- On a folder, or **Sync Project with Server…**, Lutra lists every file that differs: only in the project, only on the server, or changed (sizes first, then contents up to 8 MiB per file; larger files of equal size count as equal). Excluded and unmapped files are left out. +- The preview selects the uploads (new and changed files). Files only on the server would be **deleted on the server**; they are never selected for you, and once you select one, Sync stays disabled until you tick "I understand that … files will be deleted on the server". Sync goes from the project to the server only; to take a server change into the project, use Download. + ## For agents and scripts -The `deploy.*` engine commands (`deploy.servers`, `deploy.saveServer`, `deploy.setSecret`, `deploy.testConnection`, `deploy.trustHostKey`, `deploy.upload`, `deploy.download`, `deploy.cancel`, `deploy.log`, …) work over the control channel and MCP like every command; see `docs/architecture.md` › Deployment. Their results never contain a secret. +The `deploy.*` engine commands (`deploy.servers`, `deploy.saveServer`, `deploy.setSecret`, `deploy.testConnection`, `deploy.trustHostKey`, `deploy.upload`, `deploy.download`, `deploy.browse`, `deploy.readRemote`, `deploy.writeRemote`, `deploy.renameRemote`, `deploy.mkdirRemote`, `deploy.deleteRemote`, `deploy.compare`, `deploy.sync`, `deploy.cancel`, `deploy.log`, …) work over the control channel and MCP like every command; see `docs/architecture.md` › Deployment. Their results never contain a secret. `deploy.deleteRemote` refuses without `confirm: true`, and `deploy.sync` refuses deletions without `confirmDelete: true`: an agent must have asked the user. -## Not yet (D2) +## Not yet -A remote file browser, opening and editing remote files, compare with the server, and sync with a preview. +- Remote files open in the Remote Host viewer, not as editor tabs with highlighting. +- FTPS accepts only certificates the system trusts; servers with a self-signed certificate cannot be pinned yet. +- Linux has no keychain store yet. diff --git a/docs/gaps.md b/docs/gaps.md index 36e5fd8..136563b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -22,7 +22,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G14 | Localization: English and German interface: ~~English message catalog for UI strings~~ (M1.11), engine messages (`EngineError.message`) as message keys, language switch, plurals, German catalog | later | ~38 h | | G15 | Database tools, HTTP client, Docker and remote | later | ~430 h | | G16 | Plug-ins and ecosystem | later | ~120 h | -| G17 | Deployment: **v1 done (C9 D1)**: SFTP, FTP, FTPS and folder servers per project, path mappings, excluded paths, upload/download of files and folders, upload on save (off by default), test connection, host-key check, keychain secrets, Deployment log. Open (D2): remote browser, edit remote files, compare with server, sync with preview | M7 | ~40 h | +| G17 | Deployment: **v1 + v2 done (C9 D1, D2)**: SFTP, FTP, FTPS and folder servers per project, path mappings, excluded paths, upload/download, upload on save, save before upload, host-key check, keychain secrets, Deployment log, Remote Host browser (view, edit and upload, rename, delete after a question, new folder), compare (file diff, folder list), sync with preview and confirmed deletions. Open: remote files as highlighted editor tabs, FTPS certificate pinning, Linux keychain | M7 | ~12 h | | G18 | Editor productivity: Local History, live and file templates, postfix completion, code generation, intention actions, auto import, scratch files, macros, compare files/folders, TODO view, language injections, code style/formatter | M6–M7 | ~400 h | | G19 | Remote development and Dev Containers | M9 | ~200 h | | G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h | @@ -55,6 +55,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync | | 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 | | 2026-11-06 | minor | G3: more themes, theme import, editor font settings (C9 T1) | | 2026-11-01 | patch | G8: chunk staging, unstaging and revert from the gutter and the diff viewer (C8 C3) | diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index 15cc04b..1198abc 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -21,7 +21,7 @@ * are exclusive modals too. So is the branches popup (M4.5), and so are * "Clone Repository…" and "Manage Remotes…" (M4.10), the merge * dialog (M4.8) and the stash dialog (M4.9), the deployment servers - * dialog (G17) and the theme picker (C9 T1). + * dialog (G17), the sync preview (C9 D2) and the theme picker (C9 T1). */ import { defineStore } from "pinia"; import { ref, watch } from "vue"; @@ -40,6 +40,7 @@ export type ModalId = | "clone" | "remotes" | "deployment" + | "deploySync" | "merge" | "stash" | "themes"; diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index c73847f..758c172 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -21,6 +21,9 @@ export interface UiCommandSpec { /** The frontend's UI commands. */ export const UI_COMMANDS: readonly UiCommandSpec[] = [ + { id: "deployment.browse", labelKey: "command.deployment.browse", menuPath: "Tools/Deployment/Remote Host" }, + { id: "deployment.compare", labelKey: "command.deployment.compare", menuPath: "Tools/Deployment/Compare Current File with Server" }, + { id: "deployment.sync", labelKey: "command.deployment.sync", menuPath: "Tools/Deployment/Sync Project with Server…" }, { id: "deployment.download", labelKey: "command.deployment.download", menuPath: "Tools/Deployment/Download Current File" }, { id: "deployment.servers", labelKey: "command.deployment.servers", menuPath: "Tools/Deployment/Servers…" }, { id: "deployment.showLog", labelKey: "command.deployment.showLog", menuPath: "Tools/Deployment/Deployment Log" }, diff --git a/ui/src/components/deploy/DeployStatusItem.vue b/ui/src/components/deploy/DeployStatusItem.vue index d672b92..5550d7b 100644 --- a/ui/src/components/deploy/DeployStatusItem.vue +++ b/ui/src/components/deploy/DeployStatusItem.vue @@ -14,25 +14,43 @@ * - `deployment.uploadProject`: the whole project; * - `deployment.testConnection`: opens the servers dialog and tests the * default server, so a host key can be checked there; - * - `deployment.servers`: opens the servers dialog. + * - `deployment.servers`: opens the servers dialog; + * - `deployment.compare {path?, kind?}` (C9 D2): a file (the active one by + * default) opens a server tab in the diff viewer; `kind: "dir"` compares + * the folder and opens the sync preview; + * - `deployment.sync`: compares the whole project and opens the sync + * preview. * All are enabled with a project and while no job runs. It also mounts - * the dialog. + * the dialog and the sync preview, and resets the remote browser when the + * project closes. */ import { LoaderCircle, X } from "@lucide/vue"; -import { computed, onBeforeUnmount, onMounted } from "vue"; +import { computed, onBeforeUnmount, onMounted, watch } from "vue"; import { useCommandsStore } from "../../commands/store"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; import { useNotificationsStore } from "../../stores/notifications"; import { useProjectStore } from "../../stores/project"; import DeploymentDialog from "./DeploymentDialog.vue"; +import SyncDialog from "./SyncDialog.vue"; import { useDeployStore } from "./deploy"; +import { useRemoteBrowserStore } from "./remoteBrowser"; const deploy = useDeployStore(); const commands = useCommandsStore(); const editor = useEditorStore(); const project = useProjectStore(); const notifications = useNotificationsStore(); +const remoteBrowser = useRemoteBrowserStore(); + +watch( + () => project.root, + (root) => { + if (root === null) { + remoteBrowser.reset(); + } + }, +); /** The running job's text, or null while none runs. */ const progressText = computed(() => { @@ -130,6 +148,23 @@ onMounted(() => { }, enabled: idle, }), + commands.provide("deployment.compare", { + run: async (params) => { + const path = pathOf(params); + const kind = (params as { kind?: unknown } | null)?.kind; + if (path === null) { + return; + } + await withTarget(() => + kind === "dir" ? remoteBrowser.compareFolders([path]) : remoteBrowser.compareFile(path), + ); + }, + enabled: idle, + }), + commands.provide("deployment.sync", { + run: () => withTarget(() => remoteBrowser.compareFolders([""])), + enabled: idle, + }), commands.provide("deployment.servers", { run: () => deploy.showDialog(), enabled: () => project.root !== null, @@ -175,6 +210,7 @@ onBeforeUnmount(() => { + diff --git a/ui/src/components/deploy/SyncDialog.vue b/ui/src/components/deploy/SyncDialog.vue new file mode 100644 index 0000000..0621957 --- /dev/null +++ b/ui/src/components/deploy/SyncDialog.vue @@ -0,0 +1,295 @@ + + + + + diff --git a/ui/src/components/deploy/remoteBrowser.ts b/ui/src/components/deploy/remoteBrowser.ts new file mode 100644 index 0000000..11cd39f --- /dev/null +++ b/ui/src/components/deploy/remoteBrowser.ts @@ -0,0 +1,549 @@ +/** + * The remote browser, compare and sync (C9 D2), through the engine's + * `deploy.browse`, `readRemote`, `writeRemote`, `renameRemote`, + * `mkdirRemote`, `deleteRemote`, `compare` and `sync` commands. + * + * - **Tree:** folders load when expanded; paths are relative to the + * server's root (`""` is the root). The server is the default one unless + * one is chosen. + * - **Files** open in the tool window's viewer, read-only first; Edit + * makes the text editable and Upload writes it back to the server. + * - **Delete** happens only after the row's own question was answered; + * only then is `confirm: true` sent. + * - **Compare:** a file opens a server tab in the diff viewer; a folder (or + * the project) opens the sync preview with every differing file. + * Uploads are preselected; deletions on the server never are, and Sync + * with deletions needs the extra confirmation checkbox, which is what + * sends `confirmDelete: true`. + */ +import { defineStore } from "pinia"; +import { computed, ref, shallowRef } from "vue"; +import { runWaiting, type JsonValue } from "../../ipc"; +import { useNotificationsStore } from "../../stores/notifications"; +import { useDiffStore } from "../vcs/diff/diff"; +import { filesText, useDeployStore } from "./deploy"; + +/** Most entries kept from one listing. */ +export const MAX_ENTRIES = 5000; + +/** One entry of a server folder. */ +export interface RemoteEntry { + /** The name. */ + name: string; + /** Whether it is a folder. */ + isDir: boolean; + /** Its size, when known. */ + size: number | null; +} + +/** A loaded (or loading) server folder. */ +export interface DirState { + /** Its entries, folders first. */ + entries: RemoteEntry[]; + /** Whether the listing runs. */ + loading: boolean; + /** Why it failed, or null. */ + error: string | null; +} + +/** The file shown in the viewer. */ +export interface RemoteFile { + /** Its browser path. */ + path: string; + /** The text being shown or edited. */ + text: string; + /** The text as read from the server. */ + original: string; + /** Whether the text can be edited. */ + editing: boolean; + /** Why it cannot be shown, or null. */ + notice: string | null; +} + +/** One differing file of the sync preview. */ +export interface SyncItem { + /** Project-relative path. */ + path: string; + /** How it differs. */ + status: "localOnly" | "remoteOnly" | "different"; + /** Its local size. */ + localSize: number | null; + /** Its size on the server. */ + remoteSize: number | null; + /** Whether Sync acts on it (upload, or delete for `remoteOnly`). */ + selected: boolean; +} + +/** + * Joins a browser folder and a name. + * + * @param dir - the folder, "" for the root. + * @param name - the entry's name. + */ +export function childPath(dir: string, name: string): string { + return dir === "" ? name : `${dir}/${name}`; +} + +/** + * The folder part of a browser path. + * + * @param path - the path. + */ +export function parentPath(path: string): string { + const slash = path.lastIndexOf("/"); + return slash < 0 ? "" : path.slice(0, slash); +} + +/** + * Whether a name typed for a new entry is usable. + * + * @param name - the typed name. + */ +export function validName(name: string): boolean { + const n = name.trim(); + if (n === "" || n === "." || n === ".." || n.includes("/") || n.includes("\\")) { + return false; + } + for (let i = 0; i < n.length; i += 1) { + if (n.charCodeAt(i) < 0x20) { + return false; + } + } + return true; +} + +/** + * Reads a `deploy.browse` answer; malformed entries are dropped. + * + * @param raw - untrusted. + */ +export function toEntries(raw: unknown): RemoteEntry[] { + const list = typeof raw === "object" && raw !== null ? (raw as Record).entries : null; + if (!Array.isArray(list)) { + return []; + } + const out: RemoteEntry[] = []; + for (const item of (list as unknown[]).slice(0, MAX_ENTRIES)) { + const e = typeof item === "object" && item !== null ? (item as Record) : {}; + if (typeof e.name !== "string" || !validName(e.name)) { + continue; + } + out.push({ + name: e.name, + isDir: e.isDir === true, + size: typeof e.size === "number" && Number.isFinite(e.size) ? e.size : null, + }); + } + return out; +} + +/** + * Reads a `deploy.compare` answer into preview items: uploads selected, + * deletions not. + * + * @param raw - untrusted. + */ +export function toSyncItems(raw: unknown): SyncItem[] { + const list = typeof raw === "object" && raw !== null ? (raw as Record).differences : null; + if (!Array.isArray(list)) { + return []; + } + const out: SyncItem[] = []; + for (const item of (list as unknown[]).slice(0, MAX_ENTRIES)) { + const d = typeof item === "object" && item !== null ? (item as Record) : {}; + const status = d.status; + if (typeof d.path !== "string" || (status !== "localOnly" && status !== "remoteOnly" && status !== "different")) { + continue; + } + out.push({ + path: d.path, + status, + localSize: typeof d.localSize === "number" ? d.localSize : null, + remoteSize: typeof d.remoteSize === "number" ? d.remoteSize : null, + selected: status !== "remoteOnly", + }); + } + return out; +} + +/** The remote browser store. */ +export const useRemoteBrowserStore = defineStore("remoteBrowser", () => { + const notifications = useNotificationsStore(); + const deploy = useDeployStore(); + + /** Whether the tool window is shown. */ + const visible = ref(false); + /** Whether the bottom panel is expanded while it is shown. */ + const expanded = ref(true); + /** The chosen server, or null for the default one. */ + const serverId = ref(null); + /** Loaded folders by browser path. */ + const dirs = ref>({}); + /** Expanded folders. */ + const open = ref([]); + /** The selected path, or null. */ + const selected = ref(null); + /** The file in the viewer, or null. */ + const file = shallowRef(null); + /** The sync preview's items; null while the preview is closed. */ + const syncItems = ref(null); + /** The paths the preview compared. */ + const syncPaths = ref([]); + /** Whether the user confirmed the deletions of the preview. */ + const confirmDelete = ref(false); + /** Whether compare or sync runs. */ + const syncing = ref(false); + /** Why the last browser or preview action failed, or null. */ + const error = ref(null); + + /** The server's name as shown. */ + const serverName = computed(() => { + const id = serverId.value ?? deploy.defaultServer; + return deploy.servers.find((s) => s.id === id)?.name ?? ""; + }); + /** Deletions the preview would make. */ + const deletions = computed(() => (syncItems.value ?? []).filter((i) => i.selected && i.status === "remoteOnly")); + /** Whether Sync may run now. */ + const canSync = computed( + () => + (syncItems.value ?? []).some((i) => i.selected) && + (deletions.value.length === 0 || confirmDelete.value) && + !syncing.value, + ); + + /** The params every command gets: the chosen server. */ + function base(): Record { + return serverId.value === null ? {} : { id: serverId.value }; + } + + /** + * Runs one browser command; a failure lands in {@link error}. + * + * @param command - the command. + * @param params - its params (the server is added). + * @returns its value, or null when it failed. + */ + async function call(command: string, params: Record): Promise { + const result = await runWaiting(command, { ...base(), ...params }); + if (!result.ok) { + error.value = result.error.message; + return null; + } + error.value = null; + return result.value; + } + + /** + * Loads (or reloads) a folder. + * + * @param path - the browser folder. + */ + async function loadDir(path: string): Promise { + dirs.value = { ...dirs.value, [path]: { entries: dirs.value[path]?.entries ?? [], loading: true, error: null } }; + const result = await runWaiting("deploy.browse", { ...base(), path }); + dirs.value = { + ...dirs.value, + [path]: result.ok + ? { entries: toEntries(result.value), loading: false, error: null } + : { entries: [], loading: false, error: result.error.message }, + }; + } + + /** Shows the tool window and reads the root. */ + async function show(): Promise { + visible.value = true; + expanded.value = true; + if (deploy.servers.length === 0) { + await deploy.load(); + } + if (dirs.value[""] === undefined) { + await loadDir(""); + } + } + + /** Hides the tool window. */ + function hide(): void { + visible.value = false; + } + + /** + * Chooses the server and reads its root. + * + * @param id - the server, or null for the default one. + */ + async function setServer(id: string | null): Promise { + serverId.value = id; + dirs.value = {}; + open.value = []; + file.value = null; + selected.value = null; + await loadDir(""); + } + + /** Reads every loaded folder again. */ + async function refresh(): Promise { + const loaded = ["", ...open.value]; + dirs.value = {}; + for (const path of loaded) { + await loadDir(path); + } + } + + /** + * Expands or collapses a folder. + * + * @param path - the browser folder. + */ + async function toggle(path: string): Promise { + selected.value = path; + if (open.value.includes(path)) { + open.value = open.value.filter((p) => p !== path && !p.startsWith(`${path}/`)); + return; + } + open.value = [...open.value, path]; + if (dirs.value[path] === undefined) { + await loadDir(path); + } + } + + /** + * Opens a server file in the viewer, read-only. + * + * @param path - the browser path. + */ + async function openFile(path: string): Promise { + selected.value = path; + const value = await call("deploy.readRemote", { remotePath: path }); + if (value === null) { + return; + } + const v = typeof value === "object" && !Array.isArray(value) ? value : {}; + const text = typeof v.text === "string" ? v.text : null; + const notice = v.tooLarge === true ? "tooLarge" : v.binary === true ? "binary" : text === null ? "missing" : null; + file.value = { path, text: text ?? "", original: text ?? "", editing: false, notice }; + } + + /** Makes the viewer's text editable. */ + function edit(): void { + if (file.value && file.value.notice === null) { + file.value = { ...file.value, editing: true }; + } + } + + /** + * Changes the viewer's text while editing. + * + * @param text - the new text. + */ + function setText(text: string): void { + if (file.value?.editing) { + file.value = { ...file.value, text }; + } + } + + /** + * Writes the edited text to the server. + * + * @returns whether it was uploaded. + */ + async function upload(): Promise { + const f = file.value; + if (!f?.editing) { + return false; + } + const value = await call("deploy.writeRemote", { remotePath: f.path, text: f.text }); + if (value === null) { + return false; + } + file.value = { ...f, original: f.text, editing: false }; + notifications.notify({ level: "info", messageKey: "notification.deploy.remoteSaved", params: { path: f.path } }); + return true; + } + + /** Closes the viewer (an unsaved edit is dropped). */ + function closeFile(): void { + file.value = null; + } + + /** + * Renames an entry within its folder. + * + * @param path - the browser path. + * @param name - the new name. + */ + async function rename(path: string, name: string): Promise { + if (!validName(name)) { + return false; + } + const to = childPath(parentPath(path), name.trim()); + const value = await call("deploy.renameRemote", { from: path, to }); + if (value === null) { + return false; + } + await loadDir(parentPath(path)); + return true; + } + + /** + * Creates a folder. + * + * @param parent - the browser folder it goes in. + * @param name - its name. + */ + async function newFolder(parent: string, name: string): Promise { + if (!validName(name)) { + return false; + } + const value = await call("deploy.mkdirRemote", { path: childPath(parent, name.trim()) }); + if (value === null) { + return false; + } + await loadDir(parent); + return true; + } + + /** + * Deletes an entry on the server; callers ask first. + * + * @param path - the browser path. + */ + async function remove(path: string): Promise { + const value = await call("deploy.deleteRemote", { path, confirm: true }); + if (value === null) { + return false; + } + if (file.value?.path === path || file.value?.path.startsWith(`${path}/`)) { + file.value = null; + } + open.value = open.value.filter((p) => p !== path && !p.startsWith(`${path}/`)); + await loadDir(parentPath(path)); + return true; + } + + /** + * Compares one project file with the server in the diff viewer. + * + * @param path - project-relative path. + */ + async function compareFile(path: string): Promise { + await useDiffStore().openRemote(path, { serverId: serverId.value, server: serverName.value }); + } + + /** + * Compares project folders with the server and opens the sync preview. + * + * @param paths - project-relative folders, "" for the whole project. + */ + async function compareFolders(paths: string[]): Promise { + if (deploy.servers.length === 0) { + await deploy.load(); + } + syncPaths.value = paths; + confirmDelete.value = false; + syncItems.value = []; + syncing.value = true; + try { + const value = await call("deploy.compare", { paths }); + syncItems.value = value === null ? [] : toSyncItems(value); + } finally { + syncing.value = false; + } + } + + /** Closes the sync preview. */ + function closeSync(): void { + syncItems.value = null; + error.value = null; + } + + /** + * Runs the previewed sync: uploads the selected local and differing + * files and, only with {@link confirmDelete}, deletes the selected + * server-only files. + * + * @returns whether it ran without failures. + */ + async function runSync(): Promise { + const items = syncItems.value ?? []; + const upload = items.filter((i) => i.selected && i.status !== "remoteOnly").map((i) => i.path); + const del = deletions.value.map((i) => i.path); + if (!canSync.value) { + return false; + } + syncing.value = true; + try { + const params: Record = { upload, delete: del }; + if (del.length > 0) { + params.confirmDelete = true; + } + const value = await call("deploy.sync", params); + if (value === null) { + return false; + } + const v = typeof value === "object" && !Array.isArray(value) ? value : {}; + const count = (key: string): number => { + const n = v[key]; + return typeof n === "number" ? n : 0; + }; + notifications.notify({ + level: count("failed") > 0 ? "warning" : "info", + messageKey: "notification.deploy.synced", + params: { files: filesText(count("files")), deleted: filesText(count("deleted")), server: serverName.value }, + }); + syncItems.value = null; + if (visible.value) { + await refresh(); + } + return count("failed") === 0; + } finally { + syncing.value = false; + } + } + + /** Forgets everything when the project closes. */ + function reset(): void { + dirs.value = {}; + open.value = []; + file.value = null; + selected.value = null; + syncItems.value = null; + serverId.value = null; + } + + return { + visible, + expanded, + serverId, + dirs, + open, + selected, + file, + syncItems, + syncPaths, + confirmDelete, + syncing, + error, + serverName, + deletions, + canSync, + loadDir, + show, + hide, + setServer, + refresh, + toggle, + openFile, + edit, + setText, + upload, + closeFile, + rename, + newFolder, + remove, + compareFile, + compareFolders, + closeSync, + runSync, + reset, + }; +}); diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index 0d6ae1b..73bbdcc 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -17,7 +17,8 @@ * * The bottom panel ({@link BottomPanel}) holds the Find, Terminal and * Problems tool windows (and the Deployment log, G17, which appears with - * `deployment.showLog`), as tabs in its header while more than one is + * `deployment.showLog`, and the Remote Host browser, C9 D2, with + * `deployment.browse`), as tabs in its header while more than one is * shown. Find appears with the UI command `find.open` (`Mod+Alt+F`), * Terminal with `terminal.open` (`Mod+Shift+T`, M3.6), Problems with * `problems.open` (`Mod+Alt+P`, M3.3); all are supplied here so they work @@ -62,6 +63,8 @@ import LogToolWindow from "../vcs/log/LogToolWindow.vue"; import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log"; import StashDialog from "../vcs/stash/StashDialog.vue"; import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue"; +import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue"; +import { useRemoteBrowserStore } from "../deploy/remoteBrowser"; import { useDeployStore } from "../deploy/deploy"; import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame"; import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup"; @@ -117,11 +120,12 @@ const nav = useNavStore(); const changes = useChangesStore(); const vcsLog = useLogStore(); const deploy = useDeployStore(); +const remoteBrowser = useRemoteBrowserStore(); const editor = useEditorStore(); const project = useProjectStore(); /** Tool windows of the bottom panel. */ -type BottomTool = "find" | "terminal" | "problems" | "references" | "changes" | "log" | "deployment"; +type BottomTool = "find" | "terminal" | "problems" | "references" | "changes" | "log" | "deployment" | "remote"; /** The bottom tool window last chosen. */ const bottomTool = ref("find"); /** Bottom tool windows that are shown, in tab order. */ @@ -134,6 +138,7 @@ const bottomTools = computed(() => { if (changes.visible) tools.push({ id: "changes", title: t("vcs.changes.toolWindow.title") }); if (vcsLog.visible) tools.push({ id: "log", title: t("vcs.log.toolWindow.title") }); if (deploy.visible) tools.push({ id: "deployment", title: t("deploy.log.title") }); + if (remoteBrowser.visible) tools.push({ id: "remote", title: t("deploy.remote.title") }); return tools; }); /** The active bottom tool window: the chosen one if shown, else the first. */ @@ -155,7 +160,9 @@ const bottomStore = computed(() => ? vcsLog : bottomActive.value === "deployment" ? deploy - : find, + : bottomActive.value === "remote" + ? remoteBrowser + : find, ); /** Expansion of the panel, kept per tool window by its store. */ const bottomOpen = computed({ @@ -178,7 +185,8 @@ function chooseBottom(id: string): void { id === "references" || id === "changes" || id === "log" || - id === "deployment" + id === "deployment" || + id === "remote" ) { bottomTool.value = id; } @@ -288,6 +296,13 @@ onMounted(() => { }, enabled: () => project.root !== null && activeView() !== null, }), + commands.provide("deployment.browse", { + run: () => { + bottomTool.value = "remote"; + return remoteBrowser.show(); + }, + enabled: () => project.root !== null, + }), commands.provide("deployment.showLog", { run: () => { bottomTool.value = "deployment"; @@ -395,6 +410,10 @@ onBeforeUnmount(() => { v-if="deploy.visible" v-show="bottomActive === 'deployment'" /> + diff --git a/ui/src/components/project/TreeContextMenu.vue b/ui/src/components/project/TreeContextMenu.vue index 6f2c4fe..4b0a093 100644 --- a/ui/src/components/project/TreeContextMenu.vue +++ b/ui/src/components/project/TreeContextMenu.vue @@ -3,8 +3,10 @@ * The project tree's context menu (M4.3). For a file: Open, Show Diff * (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`, * M4.6), the Git items dimmed while their command is disabled. For a file - * and a folder: Upload to Server and Download from Server - * (`deployment.upload` / `deployment.download {path}`, G17), dimmed while + * and a folder: Upload to Server, Compare with Server (a diff for a file, + * the sync preview for a folder, C9 D2) and Download from Server + * (`deployment.upload` / `deployment.compare` / `deployment.download + * {path}`, G17), dimmed while * no project is open or a deployment job runs. * * Follows the WAI-ARIA menu pattern: it takes the focus when it opens, @@ -65,6 +67,12 @@ const deployItems = computed(() => [ enabled: commands.isEnabled("deployment.upload"), run: () => commands.execute("deployment.upload", { path: props.path }), }, + { + id: "compareServer", + label: t("project.tree.menu.compareServer"), + enabled: commands.isEnabled("deployment.compare"), + run: () => commands.execute("deployment.compare", { path: props.path, kind: props.kind ?? "file" }), + }, { id: "download", label: t("project.tree.menu.download"), diff --git a/ui/src/components/vcs/diff/DiffView.vue b/ui/src/components/vcs/diff/DiffView.vue index 2f76775..148fe20 100644 --- a/ui/src/components/vcs/diff/DiffView.vue +++ b/ui/src/components/vcs/diff/DiffView.vue @@ -99,6 +99,9 @@ const caption = computed(() => { if (tab.commit) { return t("vcs.diff.captionCommit", { path: tab.path, hash: tab.commit.hash.slice(0, SHORT_HASH) }); } + if (tab.remote) { + return t("vcs.diff.captionRemote", { path: tab.path, server: tab.remote.server }); + } return refFor(tab.staged) === "HEAD" ? t("vcs.diff.captionHead", { path: tab.path }) : t("vcs.diff.captionIndex", { path: tab.path }); @@ -275,7 +278,7 @@ onBeforeUnmount(() => { {{ caption }}
diff --git a/ui/src/components/vcs/diff/diff.ts b/ui/src/components/vcs/diff/diff.ts index e756617..ab5f814 100644 --- a/ui/src/components/vcs/diff/diff.ts +++ b/ui/src/components/vcs/diff/diff.ts @@ -31,6 +31,11 @@ * (right, `git.showAt {path, rev: hash}`) with its first parent (left, the * old path of a rename). Both sides are read-only texts; nothing is * re-read on `gitChanged` (commits do not change). + * - **Server tabs (C9 D2):** {@link openRemote} compares a file on a + * deployment server (left, read-only, `deploy.readRemote {path, id?}`, + * which answers like `git.show`) with the working copy (right, the + * ordinary buffer). Nothing is re-read on `gitChanged`; reopening the + * tab reads the server again. * - **Untrusted input:** `git.show` results are checked field by field. */ import { defineStore } from "pinia"; @@ -83,6 +88,26 @@ export interface DiffTab { name: string; /** For a commit tab: what it compares; absent for working-copy diffs. */ commit?: DiffCommit; + /** For a server tab: the deployment server compared with. */ + remote?: DiffRemote; +} + +/** The server a server tab compares the working copy with. */ +export interface DiffRemote { + /** The server's id, or null for the default server. */ + serverId: string | null; + /** Its name, for the caption. */ + server: string; +} + +/** + * The key of a server tab. + * + * @param path - project-relative path. + * @param serverId - the server, or null for the default one. + */ +export function remoteDiffKey(path: string, serverId: string | null): string { + return `remote:${serverId ?? ""}:${path}`; } /** What a diff tab shows. */ @@ -282,6 +307,17 @@ export const useDiffStore = defineStore("diff", () => { * @returns the checked result, or the error text. */ async function readLeft(tab: DiffTab): Promise { + if (tab.remote) { + const params: Record = { path: tab.path }; + if (tab.remote.serverId !== null) { + params.id = tab.remote.serverId; + } + const remote = await runWaiting("deploy.readRemote", params); + if (!remote.ok) { + return remote.error.message; + } + return toShowResult(remote.value) ?? t("common.error.unexpectedResult", { command: "deploy.readRemote" }); + } const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) }); if (!result.ok) { return result.error.message; @@ -448,6 +484,24 @@ export const useDiffStore = defineStore("diff", () => { } } + /** + * Opens (or activates and reloads) the comparison of a file with its + * copy on a deployment server. + * + * @param path - project-relative path. + * @param remote - the server. + */ + async function openRemote(path: string, remote: DiffRemote): Promise { + const key = remoteDiffKey(path, remote.serverId); + let tab = tabs.value.find((t) => t.key === key); + if (!tab) { + tab = { key, path, staged: false, name: baseName(path), remote }; + tabs.value.push(tab); + } + activate(key); + await load(tab); + } + /** * Re-reads the left side of every loaded text tab; a changed text * replaces the left document (`gitChanged`). @@ -456,7 +510,7 @@ export const useDiffStore = defineStore("diff", () => { await Promise.all( tabs.value.map(async (tab) => { const before = contents.value[tab.key]; - if (before?.phase !== "ready" || tab.commit) { + if (before?.phase !== "ready" || tab.commit || tab.remote) { return; } const generation = generations.get(tab.key); @@ -569,6 +623,7 @@ export const useDiffStore = defineStore("diff", () => { deactivate, open, openAtCommit, + openRemote, showDiff, refreshLeft, close, diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index d4f3e09..370ab5e 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -1,8 +1,11 @@ { "app.statusBar.version": "{name} {version}", + "command.deployment.browse": "Remote Host", + "command.deployment.compare": "Compare Current File with Server", "command.deployment.download": "Download Current File from Server", "command.deployment.servers": "Deployment Servers…", "command.deployment.showLog": "Deployment Log", + "command.deployment.sync": "Sync Project with Server…", "command.deployment.testConnection": "Test Deployment Connection", "command.deployment.upload": "Upload Current File to Server", "command.deployment.uploadProject": "Upload Project to Server", @@ -135,6 +138,36 @@ "deploy.operation.upload": "Uploading", "deploy.progress.files": "{operation} {done}/{total} · {server}", "deploy.progress.short": "{operation} · {server}", + "deploy.remote.binary": "This file is not text, so it is not shown.", + "deploy.remote.cancel": "Cancel", + "deploy.remote.close": "Close", + "deploy.remote.compareProject": "Compare Project…", + "deploy.remote.defaultServer": "Default server ({name})", + "deploy.remote.delete": "Delete on Server", + "deploy.remote.deleteQuestion": "Delete {path} on the server, with everything inside it? This cannot be undone.", + "deploy.remote.edit": "Edit", + "deploy.remote.loading": "Loading…", + "deploy.remote.missing": "This file no longer exists on the server.", + "deploy.remote.newFolder": "New Folder", + "deploy.remote.newFolderIn": "New folder in {path}:", + "deploy.remote.ok": "OK", + "deploy.remote.readOnly": "read-only", + "deploy.remote.refresh": "Refresh", + "deploy.remote.rename": "Rename", + "deploy.remote.renameTo": "New name:", + "deploy.remote.server": "Server", + "deploy.remote.title": "Remote Host", + "deploy.remote.tooLarge": "This file is larger than 4 MiB, so it is not shown.", + "deploy.remote.upload": "Upload", + "deploy.sync.comparing": "Comparing with the server…", + "deploy.sync.confirmDelete": "I understand that {count} files will be deleted on the server.", + "deploy.sync.deleteOnServer": "delete on the server", + "deploy.sync.equal": "The project and the server are the same.", + "deploy.sync.run": "Sync", + "deploy.sync.showDiff": "Show Diff", + "deploy.sync.title": "Sync with {server}", + "deploy.sync.uploadChanged": "upload (changed)", + "deploy.sync.uploadNew": "upload (new)", "editor.assist.kind.class": "Class", "editor.assist.kind.color": "Colour", "editor.assist.kind.constant": "Constant", @@ -258,6 +291,8 @@ "notification.deploy.downloaded": "Downloaded {files} from {server}.", "notification.deploy.noServer": "No default deployment server yet. Add one, or choose the default.", "notification.deploy.partly": "Transferred {files}, but {failed} failed ({server}); see the Deployment log.", + "notification.deploy.remoteSaved": "Uploaded {path}.", + "notification.deploy.synced": "Synced with {server}: uploaded {files}, deleted {deleted}.", "notification.deploy.uploadFailed": "Upload failed: {reason}", "notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}", "notification.deploy.uploaded": "Uploaded {files} to {server}.", @@ -344,6 +379,7 @@ "project.openFolder": "Open Folder…", "project.toolWindow.title": "Project", "project.tree.loading": "Loading…", + "project.tree.menu.compareServer": "Compare with Server", "project.tree.menu.download": "Download from Server", "project.tree.menu.label": "Actions for {name}", "project.tree.menu.open": "Open", @@ -521,6 +557,7 @@ "vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}", "vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)", "vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)", + "vcs.diff.captionRemote": "{path}: on {server} (left) and working copy (right)", "vcs.diff.chunkHint": "Click a change marker in the gutter to stage, unstage or revert that chunk.", "vcs.diff.closeTab": "Close the diff of {name}", "vcs.diff.failed": "The diff cannot be shown: {reason}", diff --git a/ui/tests/deploy/RemoteBrowser.test.ts b/ui/tests/deploy/RemoteBrowser.test.ts new file mode 100644 index 0000000..57ba5f6 --- /dev/null +++ b/ui/tests/deploy/RemoteBrowser.test.ts @@ -0,0 +1,203 @@ +/** + * Tests of the remote browser, compare and sync (C9 D2): reading untrusted + * listings and comparisons, names; the Remote Host tool window (root, + * expanding a folder, a file read-only then edited and uploaded, rename, + * new folder, and delete only after its question); the sync preview + * (uploads preselected, deletions never, Sync blocked until the deletion + * is confirmed, `confirmDelete` sent only then); and the server diff tab. + * The engine is a fake behind the mocked Tauri `invoke` and `listen`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +const listen = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("@tauri-apps/api/event", () => ({ listen })); + +import RemoteBrowserToolWindow from "../../src/components/deploy/RemoteBrowserToolWindow.vue"; +import SyncDialog from "../../src/components/deploy/SyncDialog.vue"; +import { + childPath, + parentPath, + toEntries, + toSyncItems, + useRemoteBrowserStore, + validName, +} from "../../src/components/deploy/remoteBrowser"; +import { useDiffStore } from "../../src/components/vcs/diff/diff"; + +interface Call { + command: string; + params: Record; +} + +let calls: Call[]; +let pinia: Pinia; +let mounted: VueWrapper[]; + +function callsOf(command: string): Call[] { + return calls.filter((c) => c.command === command); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + mounted = []; + invoke.mockReset(); + listen.mockReset(); + listen.mockResolvedValue(() => undefined); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { + return Promise.resolve(null); + } + calls.push({ command: args.command, params: args.params }); + switch (args.command) { + case "deploy.servers": + return Promise.resolve({ servers: [{ id: "s1", name: "Staging", kind: "sftp" }], defaultServer: "s1" }); + case "deploy.browse": + return Promise.resolve( + args.params.path === "" + ? { entries: [{ name: "public", isDir: true }, { name: "index.php", isDir: false, size: 5 }, { name: "../x", isDir: false }] } + : { entries: [{ name: "app.php", isDir: false, size: 3 }] }, + ); + case "deploy.readRemote": + return Promise.resolve({ text: " { + for (const wrapper of mounted) { + wrapper.unmount(); + } + document.body.innerHTML = ""; +}); + +async function mountBrowser(): Promise { + const wrapper = mount(RemoteBrowserToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useRemoteBrowserStore(pinia).show(); + await flushPromises(); + return wrapper; +} + +describe("reading the engine's answers", () => { + it("drops unsafe names and malformed differences", () => { + expect(toEntries({ entries: [{ name: "a", isDir: true }, { name: ".." }, { name: "x/y" }, null] })).toEqual([ + { name: "a", isDir: true, size: null }, + ]); + const items = toSyncItems({ + differences: [{ path: "a", status: "remoteOnly" }, { path: "b", status: "localOnly" }, { path: "c", status: "gone" }], + }); + expect(items.map((i) => [i.path, i.selected])).toEqual([ + ["a", false], + ["b", true], + ]); + expect(validName("ok.php")).toBe(true); + expect(validName("a\nb")).toBe(false); + expect(validName("..")).toBe(false); + expect(childPath("", "a")).toBe("a"); + expect(parentPath("a/b/c")).toBe("a/b"); + }); +}); + +describe("Remote Host tool window", () => { + it("lists the root, expands a folder and edits a file", async () => { + const wrapper = await mountBrowser(); + expect(wrapper.findAll("[data-test='remote-row']").map((r) => r.attributes("data-path"))).toEqual(["public", "index.php"]); + await wrapper.find("[data-path='public'] .remote__name").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.browse").at(-1)?.params).toEqual({ path: "public" }); + expect(wrapper.find("[data-path='public/app.php']").exists()).toBe(true); + await wrapper.find("[data-path='index.php'] .remote__name").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.readRemote")[0]?.params).toEqual({ remotePath: "index.php" }); + const text = wrapper.find("[data-test='remote-text']"); + expect(text.element.readOnly).toBe(true); + await wrapper.find("[data-test='remote-edit']").trigger("click"); + await text.setValue(" { + const wrapper = await mountBrowser(); + await wrapper.find("[data-path='index.php'] [data-test='remote-rename']").trigger("click"); + await wrapper.find("[data-test='remote-form-name']").setValue("home.php"); + await wrapper.find("[data-test='remote-form']").trigger("submit"); + await flushPromises(); + expect(callsOf("deploy.renameRemote")[0]?.params).toEqual({ from: "index.php", to: "home.php" }); + await wrapper.find("[data-test='remote-new-folder']").trigger("click"); + await wrapper.find("[data-test='remote-form-name']").setValue("cache"); + await wrapper.find("[data-test='remote-form']").trigger("submit"); + await flushPromises(); + expect(callsOf("deploy.mkdirRemote")[0]?.params).toEqual({ path: "cache" }); + await wrapper.find("[data-path='public'] [data-test='remote-delete']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.deleteRemote")).toHaveLength(0); + expect(wrapper.find("[data-test='remote-form']").text()).toContain("public"); + await wrapper.find("[data-test='remote-delete-confirm']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.deleteRemote")[0]?.params).toEqual({ path: "public", confirm: true }); + }); +}); + +describe("sync preview", () => { + it("needs the extra confirmation before deleting on the server", async () => { + const wrapper = mount(SyncDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + const browser = useRemoteBrowserStore(pinia); + await browser.compareFolders([""]); + await flushPromises(); + expect(callsOf("deploy.compare")[0]?.params).toEqual({ paths: [""] }); + expect(wrapper.findAll("[data-test='sync-item']")).toHaveLength(3); + expect(wrapper.find("[data-test='sync-confirm']").exists()).toBe(false); + await wrapper.find("input[data-path='old.php']").setValue(true); + expect(wrapper.find("[data-test='sync-confirm']").exists()).toBe(true); + expect(wrapper.find("[data-test='sync-run']").attributes("disabled")).toBeDefined(); + await wrapper.find("[data-test='sync-confirm'] input").setValue(true); + await wrapper.find("[data-test='sync-run']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.sync")[0]?.params).toEqual({ + upload: ["a.php", "new.php"], + delete: ["old.php"], + confirmDelete: true, + }); + }); + + it("syncs uploads without confirmDelete when nothing is deleted", async () => { + const wrapper = mount(SyncDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useRemoteBrowserStore(pinia).compareFolders(["src"]); + await flushPromises(); + await wrapper.find("[data-test='sync-run']").trigger("click"); + await flushPromises(); + expect(callsOf("deploy.sync")[0]?.params).toEqual({ upload: ["a.php", "new.php"], delete: [] }); + }); +}); + +describe("server diff tab", () => { + it("reads the server's side through deploy.readRemote", async () => { + const diff = useDiffStore(pinia); + void diff.openRemote("a.php", { serverId: "s1", server: "Staging" }); + await flushPromises(); + expect(callsOf("deploy.readRemote")[0]?.params).toEqual({ path: "a.php", id: "s1" }); + expect(diff.activeTab?.remote?.server).toBe("Staging"); + }); +}); diff --git a/ui/tests/vcs/DiffView.test.ts b/ui/tests/vcs/DiffView.test.ts index 02fa0b0..777f0e1 100644 --- a/ui/tests/vcs/DiffView.test.ts +++ b/ui/tests/vcs/DiffView.test.ts @@ -475,7 +475,7 @@ describe("project tree context menu", () => { await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 }); const menu = document.querySelector("[data-test=tree-menu]"); expect(menu).not.toBeNull(); - expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Download from Server"]); + expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Compare with Server", "Download from Server"]); (document.querySelector("[data-item=showDiff]") as HTMLElement).click(); await flushPromises(); await flushPromises();