From ff85a9c95cab9e43f62eb2d2656beffd71ae9036 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sat, 21 Nov 2026 06:09:16 +0100 Subject: [PATCH 1/2] feat(archived): list folder archives and restore one without Undo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Archived now lists folder archives with their archive date and disabled schedule count; Unarchive restores one through a new unarchive-folder IPC, and the sidebar recovery notices open the page. --- .ai/contexts/ipc-bridge.md | 26 +++-- .ai/contexts/session-cache.md | 19 +++- CHANGELOG.md | 2 +- docs/session-browser.md | 8 ++ docs/settings.md | 15 ++- main.js | 16 +++ preload.js | 1 + public/archived-manager.js | 63 ++++++++---- public/settings-panel.js | 5 +- public/sidebar.js | 12 ++- test/dom-archived-manager.test.js | 140 +++++++++++++++++++++++++-- test/dom-folder-archive-undo.test.js | 46 +++++++++ test/dom-remote-host-labels.test.js | 2 +- test/unarchive-folder.test.js | 103 ++++++++++++++++++++ 14 files changed, 408 insertions(+), 50 deletions(-) create mode 100644 test/unarchive-folder.test.js diff --git a/.ai/contexts/ipc-bridge.md b/.ai/contexts/ipc-bridge.md index ada4ca590..b97a83e7d 100644 --- a/.ai/contexts/ipc-bridge.md +++ b/.ai/contexts/ipc-bridge.md @@ -1,10 +1,11 @@ # Context: ipc-bridge -## Archived projects manager (#863 slice 2) +## Archived projects manager (#863 slices 2–3, #1167) `settings-panel.js` mounts `renderArchivedProjects` from `archived-manager.js` after the shared renderer helpers, dialogs, notices and sidebar controller. -It passes a copy of hidden entries/kinds, archive timestamps, cached projects and +It reads `archivedProjects` through `getSetting` and passes a copy of folder records, +hidden entries/kinds, archive timestamps, cached projects and the working remote-host list. Host edits update labels without saving. The manager groups Local first, then configured hosts in order, then unknown aliases; it never collapses a worktree entry into its repository. The filter, selections and folds @@ -12,9 +13,11 @@ are local to the mounted list. Filtering clears selections outside the results. Counts exclude deleted entries. Missing timestamps and unknown session counts are omitted, never invented. Names use `shortProjectPath` (last two segments). -Unarchive uses the exact stored entry via `unarchiveProject`, sequentially for a +Unarchive uses the exact stored entry via `unarchiveProject` and/or `unarchiveFolder`, sequentially for a bulk action. Successful entries leave the list, reload projects and get one B8 -ten-second Undo notice. Undo calls `archiveProjectSettings(path, folderKey)` and +ten-second Undo notice for project archives only. Folder restores use an informational +notice; mixed restores explain that Undo only re-archives projects and that folders +must be archived again through Archive folder. Undo calls `archiveProjectSettings(path, folderKey)` and reads the new writer timestamp. After reopening Settings, Undo refreshes the currently mounted manager; a pending action does not consume its Undo notice. The notice stores its entry array and load generation. A later accepted project @@ -54,12 +57,20 @@ leaves fallback focus to that caller; sidebar and project-settings callers retai their existing project-header/sidebar fallback. Unlocking keeps refused actions disabled until the menu reopens. It never calls Unarchive before Delete. The overflow also copies the full path through -`writeClipboard`. No new IPC or launch code is introduced. +`writeClipboard`. The folder restore IPC does not change launch code. Native controls provide Tab navigation; Enter/Space folds host groups and Escape clears the filter. ResizeObserver alone controls the 720px stacked layout and -480px search disclosure. New surfaces use existing dark chrome tokens. Folder -archives and archived sessions are not listed in this slice. +480px search disclosure. New surfaces use existing dark chrome tokens. + +Folder and project archives with the same exact entry share one row with both badges. +Folder dates accept the stored ISO timestamp; metadata includes the number of disabled +schedules. Deleted entries stay excluded. Combined restoration clears the project +archive first. The existing project writer also clears its folder record, so a following +`unarchiveFolder` returning `NOT_ARCHIVED` counts as success only after that project's +successful restore. A genuine folder failure retains a Folder-only row for retry; +a project failure prevents the folder call. Refresh reads both stores and retains the +filter and folded groups. Archived sessions remain outside this slice. **Purpose**: The trust boundary between the Electron main process (Node, full filesystem) and the renderer (Chromium, sandboxed). The renderer can only call what `preload.js` exposes via `contextBridge`; everything else is denied. @@ -463,6 +474,7 @@ consent and avoid recovery during a system exit. See window-frame.md. | `add-project` | `(projectPath)` | Register a project (creates folder index) | | `archive-project-settings` | `(projectPath, folderKey)` | Archive the project reversibly; preserve settings/cache/registration, suspend schedules through hidden-state filtering. Returns `{ ok: true, entry }`, where `entry` is the exact stored bare path or `alias::path` for `unarchiveProject(entry)`. Bridge: `archiveProjectSettings`. | | `unarchive-project` | `(entry)` | Refuse entries marked `delete` before effects with `{ error, code: 'DELETED' }`; missing entries return `{ error, code: 'NOT_ARCHIVED' }`. Remove an archived or legacy hidden entry, refresh its folder and restore legacy local schedule registration. Bridge: `unarchiveProject`. | +| `unarchive-folder` | `(entry)` | Restore an exact folder archive through `writer.clearArchivedEntry`; missing entries return `{ error, code: NOT_ARCHIVED }`. Keep session archive flags and schedule files unchanged; preserve disabled schedules as a re-enable offer and notify once with `archive`. Bridge: `unarchiveFolder`. | | `archive-project` | `(groups, opts)` | Archive folder groups and confirmed schedules; success includes `archivedAt` for the reverse path. Bridge: `archiveProject`. | | `undo-archive-project` | `(groups, archivedAt)` | Refuse invalid groups or a stale timestamp before any effects; remove those folder archives, restore consumed offers and re-enable exactly their `disabledByArchive` files. Bridge: `undoArchiveProject`; folder Archive Undo passes the original groups and returned timestamp before restoring session archive flags. | | `remove-project` | `(projectPath, folderKey)` | Legacy removal: drop settings, cache/search and schedule registration; no disk deletion. Bridge: `removeProjectLegacy`; neither current Delete entry point uses it. | diff --git a/.ai/contexts/session-cache.md b/.ai/contexts/session-cache.md index f45499a40..ba351f397 100644 --- a/.ai/contexts/session-cache.md +++ b/.ai/contexts/session-cache.md @@ -2476,8 +2476,11 @@ Project Settings offers **Archive Project** and **Delete Project** (#568). Archive writes only the existing `global.hiddenProjects` array through `archive-project-settings`. Bare paths keep their historical all-host matching; `alias::path` entries match only that host. There is no key migration. Old Hide -entries remain listed in Global Settings → **Archived projects**; entries marked -as deleted are excluded. +entries remain listed in Global Settings → **Archived**; entries marked +as deleted are excluded. Folder archives share this manager, with separate badges +and restore semantics described below. A combined row clears the project archive +first; that existing writer operation also clears its folder archive and preserves +the disabled schedules as an offer. Archive keeps `project:`, cache metadata, session rows, search rows and `scheduleProjects`. `buildProjectsFromCache` already filters hidden entries; @@ -2603,8 +2606,16 @@ lists never cross the writer transport. See `session-index-writer.md` for orderi local groups in the schedule registry; `archive-project` re-scans and disables only the ones the renderer confirmed — see [schedule-runner.md](schedule-runner.md) ("Disabling a schedule file"). -- **Clearing by hand.** `add-project` and `delete-worktree` call - `clearArchivedEntry`. +- **Clearing by hand.** Settings → Archived lists the keys of `archivedProjects` + alongside non-deleted `hiddenProjects`, merging an exact entry into one row with + Project and Folder badges. `unarchive-folder(entry)` calls the writer's + `clearArchivedEntry` and sends one `projects-changed('archive')` notification on + success; missing entries return `NOT_ARCHIVED`. `add-project` and + `delete-worktree` retain their existing clearing paths. A plain folder restore + keeps session archive flags and schedule file bytes unchanged. The existing + clearing helper moves disabled schedules into a re-enable offer, preserving + unrelated offers. Folder Undo remains the separate timestamp-checked path. + Recovery notices for a failed Undo or partial Archive expose **Open Archived**. - **Re-enable offers.** An entry records `disabledSchedules`, the files the archive actually disabled. When an entry leaves `archivedProjects` (a reappearance in `get-projects`, or `clearArchivedEntry`), a non-empty list diff --git a/CHANGELOG.md b/CHANGELOG.md index c0fba6461..68f94a8a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ### Changed - After a restart, Switchboard re-reads only Claude Code transcripts changed since the previous run. Codex history is still re-read in full. (#1144) -- Settings → Archived groups projects by host, shows their paths and archive dates, and filters by name, path or host. Restore one or several projects with Undo, or delete an archived project through the existing preview without restoring it first. Worktree entries whose repository is gone can be deleted; entries still grouped under a repository explain that you can delete their repository instead. (#863) +- Settings → Archived groups project and folder archives by host, shows their paths and archive dates, and filters by name, path or host. Folder archives show their disabled schedule count and can be restored after Undo expires, keeping schedules off until you choose Turn back on. Restore one or several projects with Undo, or delete an archived project through the existing preview without restoring it first. Worktree entries whose repository is gone can be deleted; entries still grouped under a repository explain that you can delete their repository instead. (#863, #1167) - Codex sessions run non-interactively by a program (`codex exec`: scripted reviews and fixes) are now left out of the sidebar and grid like Claude Agent SDK sessions, under the same **Hide SDK-launched Sessions** setting. They still count in the heatmap and are found by search; the ones you have open stay listed. Codex sessions already indexed are re-checked once at the next start. (#1145) ### Fixed diff --git a/docs/session-browser.md b/docs/session-browser.md index c4db40c3d..fc6055df1 100644 --- a/docs/session-browser.md +++ b/docs/session-browser.md @@ -278,6 +278,14 @@ back on exactly the schedules it disabled; stopped processes stay stopped. An empty folder archived without a dialog also offers Undo. An options dialog with nothing running is configuration and has no Undo notice. +After Undo has expired, open Settings → **Archived**. Folder archives have a +**Folder** badge, their archive date and the number of schedules turned off. +**Unarchive** restores the group while keeping its sessions archived and schedules +off. The offer at the top of the restored group lets you **Turn back on** those +schedules. This restore has no folder Undo; use **Archive folder** to archive it +again. A row with both Project and Folder badges restores both archives. +Recovery notices for partial Archive or failed Undo have an **Open Archived** action. + Accepting the options hides the folder and its nested worktrees from the sidebar, even with both boxes unticked. **Show archived sessions** shows it again, and search still finds its sessions. The folder comes back, with its settings, when it is diff --git a/docs/settings.md b/docs/settings.md index 9db6f3a30..0791e6e4b 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -140,16 +140,21 @@ The **What is sent** explanation expands when selected. ### Archived -Projects are grouped by host, with Local first. Each row shows its name, full path -(also in the tooltip), Project and legacy badges, and an archive date for new -archives. Worktree entries keep their own rows and paths. Filter by name, path, +Project and folder archives are grouped by host, with Local first. Each row shows +its name, full path (also in the tooltip), Project or Folder badges (both when +archived both ways), any legacy badge, and the available archive date. Folder +archives also show how many schedules the archive turned off. Worktree entries keep their own rows and paths. Filter by name, path, host label or alias; Escape clears the filter. Host headers fold with Enter or Space. Select rows or a host group to unarchive several projects together. -**Unarchive** applies immediately and offers a ten-second **Undo**. The row's +**Unarchive** applies immediately. Project restores offer a ten-second **Undo**; +folder restores keep sessions archived and schedules off, with **Turn back on** +offered at the top of the restored group. Re-archive a folder with **Archive folder**; +in a mixed restore, Undo re-archives projects only. A combined row restores its +project archive first, then its folder archive. The row's **More actions** menu offers **Copy path** and **Delete project…**. Delete opens the same preview and confirmation as the sidebar, without unarchiving first. -Folder and session archive management will be added separately. +Archived session management will be added separately. ### Advanced diff --git a/main.js b/main.js index 379dfd1f8..d40281961 100644 --- a/main.js +++ b/main.js @@ -1059,6 +1059,22 @@ ipcMain.handle('archive-project', async (_event, groups, opts) => { return res; }); +ipcMain.handle('unarchive-folder', async (_event, entry) => { + try { + if (typeof entry !== 'string' || !Object.hasOwn(getSetting('archivedProjects') || {}, entry)) { + return { error: 'Folder is not archived', code: 'NOT_ARCHIVED' }; + } + const { alias, folder } = parseFolderKey(entry); + if (!await writer.clearArchivedEntry(alias, alias && folder === '' ? '/' : folder)) { + return { error: 'Folder is not archived', code: 'NOT_ARCHIVED' }; + } + notifyRendererProjectsChanged('archive'); + return { ok: true }; + } catch (error) { + return { error: error.message }; + } +}); + ipcMain.handle('undo-archive-project', async (_event, groups, archivedAt) => await writer.undoArchiveProjectFolders(groups, archivedAt, archiveDeps())); diff --git a/preload.js b/preload.js index bb77cef6e..2d0849bfe 100644 --- a/preload.js +++ b/preload.js @@ -125,6 +125,7 @@ contextBridge.exposeInMainWorld('api', { onProjectDeleteRecovery: callback => ipcRenderer.on('project-delete-recovery', (_event, payload) => callback(payload)), archiveProjectSettings: (projectPath, folderKey) => ipcRenderer.invoke('archive-project-settings', projectPath, folderKey), unarchiveProject: (entry) => ipcRenderer.invoke('unarchive-project', entry), + unarchiveFolder: (entry) => ipcRenderer.invoke('unarchive-folder', entry), remapProject: (oldPath, newPath) => ipcRenderer.invoke('remap-project', oldPath, newPath), checkRemapProject: (oldPath) => ipcRenderer.invoke('check-remap-project', oldPath), deleteWorktree: (worktreePath, shown) => ipcRenderer.invoke('delete-worktree', worktreePath, shown), diff --git a/public/archived-manager.js b/public/archived-manager.js index f8e92bedb..83ee093c8 100644 --- a/public/archived-manager.js +++ b/public/archived-manager.js @@ -1,8 +1,10 @@ // see .ai/contexts/ipc-bridge.md (Archived projects manager) let activeArchivedProjectsManager = null; -function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, hosts = [], projects = [], onCount }) { - let archived = [...new Set(entries)].filter(entry => kinds[entry] !== 'delete'); +function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, folders = {}, hosts = [], projects = [], onCount }) { + let projectEntries = new Set(entries.filter(entry => kinds[entry] !== 'delete')); + folders = { ...folders }; + let archived = [...new Set([...projectEntries, ...Object.keys(folders)])].filter(entry => kinds[entry] !== 'delete'); const selected = new Set(), folded = new Set(); let busy = false; container.innerHTML = `
@@ -55,6 +57,7 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho const result = await window.api.archiveProjectSettings(project.projectPath, project.folder); if (!result?.ok) throw new Error(result?.error || 'No archive result'); if (!archived.includes(entry)) archived.push(entry); + projectEntries.add(entry); kinds[entry] = 'archive'; const latest = await window.api.getSetting('global'); dates = latest?.hiddenProjectArchivedAt || dates; @@ -66,26 +69,43 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho async function restore(targets, button) { if (busy) return; lock(true); - const restored = [], errors = []; + const restored = [], restoredProjects = [], restoredFolders = [], errors = []; for (const entry of targets) { try { - const result = await window.api.unarchiveProject(entry); - if (!result?.ok) throw new Error(result?.error || 'No unarchive result'); + if (projectEntries.has(entry)) { + const result = await window.api.unarchiveProject(entry); + if (!result?.ok) throw new Error(result?.error || 'No unarchive result'); + projectEntries.delete(entry); + restoredProjects.push(entry); + } + if (Object.hasOwn(folders, entry)) { + const result = await window.api.unarchiveFolder(entry); + if (!result?.ok && !(restoredProjects.includes(entry) && result?.code === 'NOT_ARCHIVED')) { + throw new Error(result?.error || 'No unarchive result'); + } + delete folders[entry]; + restoredFolders.push(entry); + } archived = archived.filter(item => item !== entry); selected.delete(entry); restored.push(entry); } catch (error) { errors.push(`${identity(entry).name}: ${error.message}`); } } lock(false); - if (restored.length) { + if (restored.length || restoredProjects.length) { render(); filter.focus(); await reload(); - const noticeId = 'archived-restored:' + restored.join('|'); - const notice = showAppNotice({ id: noticeId, kind: 'undo', dismissOnAction: false, - message: restored.length === 1 ? `Project "${identity(restored[0]).name}" restored.` : `${restored.length} projects restored.`, - actionLabel: 'Undo', onAction: () => { + const completed = [...new Set([...restored, ...restoredProjects])]; + const noticeId = 'archived-restored:' + completed.join('|'); + const message = completed.length === 1 + ? `${restoredProjects.length ? 'Project' : 'Folder'} "${identity(completed[0]).name}" restored.` + : `${completed.length} ${restoredFolders.length ? 'projects and folders' : 'projects'} restored.`; + const notice = showAppNotice({ id: noticeId, kind: restoredProjects.length ? 'undo' : 'info', dismissOnAction: false, + message: message + (restoredFolders.length + ? `${restoredProjects.length ? ' Undo re-archives projects only.' : ''} To archive folders again, use Archive folder.` : ''), + ...(restoredProjects.length ? { actionLabel: 'Undo', onAction: () => { if (busy) return; clearAppNotice(noticeId); - return undo(restored); - } }); - notice.dataset.restoredEntries = JSON.stringify(restored); + return undo(restoredProjects); + } } : {}) }); + notice.dataset.restoredEntries = JSON.stringify(restoredProjects); notice.dataset.loadGeneration = loadProjects.state?.started || 0; } if (errors.length) await fail('Could not unarchive project', errors, button.isConnected ? button : filter); @@ -108,6 +128,7 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho + (retryable ? ' Reopen the menu and click Delete project to try again.' : ''); button.dataset.unavailable = 'true'; button.dataset.retryable = String(retryable); button.disabled = true; } })) { + projectEntries.delete(entry); delete folders[entry]; archived = archived.filter(item => item !== entry); selected.delete(entry); render(); filter.focus(); } } catch (error) { await fail('Could not delete project', [error.message], button); } @@ -126,7 +147,7 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho }); for (const entry of selected) if (!matches.includes(entry)) selected.delete(entry); if (!matches.length) { - list.innerHTML = `
${query ? `No archived item matches "${escapeHtml(filter.value.trim())}". ` : 'No archived project. Archive Project in a project’s settings lists it here.'}
`; + list.innerHTML = `
${query ? `No archived item matches "${escapeHtml(filter.value.trim())}". ` : 'No archived project. Archive Project (a project’s settings) or Archive folder (a project header) lists it here.'}
`; list.querySelector('.archived-clear')?.addEventListener('click', clearFilter); selection(); return; } @@ -140,12 +161,14 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho
${group.map(entry => { const p = identity(entry), reasonId = 'archived-delete-reason-' + encodeURIComponent(entry); - const date = typeof dates[entry] === 'number' && Number.isFinite(dates[entry]) ? new Date(dates[entry]) : null; + const folder = folders[entry], hasFolder = Object.hasOwn(folders, entry), hasProject = projectEntries.has(entry); + const archivedAt = folder?.archivedAt ?? dates[entry]; + const date = typeof archivedAt === 'number' || typeof archivedAt === 'string' ? new Date(archivedAt) : null; return `
-
${escapeHtml(p.name)} Project${kinds[entry] === undefined ? ' legacy' : ''}${alias ? ` ${escapeHtml(alias)}` : ''}
+
${escapeHtml(p.name)} ${hasProject ? 'Project' : ''}${hasFolder ? ' Folder' : ''}${hasProject && kinds[entry] === undefined ? ' legacy' : ''}${alias ? ` ${escapeHtml(alias)}` : ''}
${escapeHtml(p.projectPath)}
-
${date && Number.isFinite(date.getTime()) ? `` : ''}${p.cached ? ` ${p.sessions.length} session${p.sessions.length === 1 ? '' : 's'}` : ''}
+
${date && Number.isFinite(date.getTime()) ? `` : ''}${p.cached ? ` ${p.sessions.length} session${p.sessions.length === 1 ? '' : 's'}` : ''}${Array.isArray(folder?.disabledSchedules) ? ` ${folder.disabledSchedules.length} schedules off` : ''}
⋯
`; @@ -207,10 +230,12 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, ho container, setHosts(next) { hosts = next; render(); }, async refresh() { - const latest = await window.api.getSetting('global'); + const [latest, folderArchives] = await Promise.all([window.api.getSetting('global'), window.api.getSetting('archivedProjects')]); kinds = { ...latest?.hiddenProjectKinds }; dates = latest?.hiddenProjectArchivedAt || {}; - archived = (latest?.hiddenProjects || []).filter(entry => kinds[entry] !== 'delete'); + folders = { ...folderArchives }; + projectEntries = new Set((latest?.hiddenProjects || []).filter(entry => kinds[entry] !== 'delete')); + archived = [...new Set([...projectEntries, ...Object.keys(folders)])].filter(entry => kinds[entry] !== 'delete'); render(); }, }; diff --git a/public/settings-panel.js b/public/settings-panel.js index bc0619ecf..cc74318b6 100644 --- a/public/settings-panel.js +++ b/public/settings-panel.js @@ -516,8 +516,8 @@
` : ''} ${!isProject ? `
-
Archived projects
-
Unarchive restores a project's sidebar row and schedules. Actions apply immediately.
+
Projects and folders
+
Unarchive restores sidebar groups. Folder schedules stay off until you choose Turn back on. Actions apply immediately.
` : ''} @@ -709,6 +709,7 @@ const archivedManager = renderArchivedProjects(list, { entries: current.hiddenProjects || [], kinds: { ...current.hiddenProjectKinds }, dates: current.hiddenProjectArchivedAt || {}, hosts: remoteHosts, + folders: await window.api.getSetting('archivedProjects') || {}, projects: typeof cachedAllProjects === 'undefined' ? [] : cachedAllProjects, onCount: count => { const nav = settingsViewerBody.querySelector('.settings-nav [data-section="archived"]'); diff --git a/public/sidebar.js b/public/sidebar.js index 5728a486d..97cd90362 100644 --- a/public/sidebar.js +++ b/public/sidebar.js @@ -1946,7 +1946,9 @@ function showFolderArchiveUndo(project, groups, archivedAt, rows, didStop, child if (result.failed?.length) throw new Error(result.failed.map(failure => `${failure.name}: ${failure.error}`).join('; ')); await loadProjects(); } catch (error) { - showSessionActionFailure('Undo Archive folder', project, error, 'Check the folder and schedules in Settings before retrying.'); + showAppNotice({ id: sessionActionNoticeId('Undo Archive folder', project), kind: 'error', + message: `Undo Archive folder failed for ${sessionActionDescription(project)}: ${error.message}. Review the folder and schedules before retrying.`, + actionLabel: 'Open Archived', onAction: () => openSettingsViewer('global', null, null, { section: 'archived' }) }); } }, }); @@ -2091,10 +2093,10 @@ async function archiveProjectFolder(project, button) { ? 'Check the schedules in the Schedules tab, then retry Archive folder.' : 'Check schedule-*.md in the Agent Files tab, then retry Archive folder.'); } else if (res.failed?.length) { - showSessionActionFailure('Archive folder', project, 'The folder is archived, but these schedules could not be disabled: ' + res.failed.map(f => f.name + ': ' + f.error).join('; '), - window.schedulesTabEnabled - ? 'Review the schedules in the Schedules tab. Restore the folder from Settings → Archived projects if you need to retry Archive folder.' - : 'Review schedule-*.md in the Agent Files tab. Restore the folder from Settings → Archived projects if you need to retry Archive folder.', undefined, { headline: 'Archive folder partly done' }); + showAppNotice({ id: sessionActionNoticeId('Archive folder', project), kind: 'error', + message: `Archive folder partly done for ${sessionActionDescription(project)}: The folder is archived, but these schedules could not be disabled: ${res.failed.map(f => f.name + ': ' + f.error).join('; ')}. ` + + (window.schedulesTabEnabled ? 'Review the schedules in the Schedules tab.' : 'Review schedule-*.md in the Agent Files tab.'), + actionLabel: 'Open Archived', onAction: () => openSettingsViewer('global', null, null, { section: 'archived' }) }); } else { clearAppNotice(sessionActionNoticeId('Archive folder', project)); } diff --git a/test/dom-archived-manager.test.js b/test/dom-archived-manager.test.js index a4c0aa4f6..7eef2b0f8 100644 --- a/test/dom-archived-manager.test.js +++ b/test/dom-archived-manager.test.js @@ -56,9 +56,11 @@ async function setup(t, empty = false) { } const settings = { hiddenProjects: empty ? [] : [...entries], hiddenProjectKinds: { [entries[0]]: 'archive', '/gone': 'delete' }, hiddenProjectArchivedAt: { [entries[0]]: 1795089600000 }, remoteHosts: [{ alias: 'vps', label: 'Planificator' }] }; - const calls = { restore: [], archive: [], preview: [], execute: [], reload: 0 }; + const folders = {}; + const calls = { restore: [], folderRestore: [], archive: [], preview: [], execute: [], reload: 0 }; w.cachedAllProjects = [{ projectPath: entries[0], sessions: [{ sessionId: 'one' }] }]; - w.api.getSetting = async () => settings; + w.api.getSetting = async key => key === 'archivedProjects' ? folders : settings; + w.api.unarchiveFolder = async entry => { calls.folderRestore.push(entry); delete folders[entry]; return { ok: true }; }; w.api.getHarnesses = w.api.getShellProfiles = async () => []; w.api.getAppVersion = async () => 'test'; w.api.unarchiveProject = async entry => { calls.restore.push(entry); settings.hiddenProjects = settings.hiddenProjects.filter(e => e !== entry); return { ok: true }; }; @@ -80,7 +82,7 @@ async function setup(t, empty = false) { await w.openSettingsViewer('global', null, null, { section: 'archived' }); const q = selector => h.document.querySelector(selector); const rows = () => [...h.document.querySelectorAll('.archived-row')]; - return { ...h, w, settings, calls, q, rows, observers }; + return { ...h, w, settings, folders, calls, q, rows, observers }; } test('host groups preserve separate worktree entries, names, safe paths, badges, dates and counts', async t => { @@ -111,10 +113,11 @@ test('filter matches name, path, host label and alias, clears by Escape and expo assert.equal(filter.value, ''); assert.equal(h.rows().length, 4); }); -test('empty projects state does not promise folder or session archives', async t => { +test('empty projects state explains both project and folder archives', async t => { const h = await setup(t, true); assert.match(h.q('#sv-archived-projects').textContent, /No archived project\./); assert.match(h.q('#sv-archived-projects').textContent, /Archive Project/); + assert.match(h.q('#sv-archived-projects').textContent, /Archive folder/); }); test('Unarchive uses the exact entry, reloads and Undo restores its remote identity and date', async t => { @@ -494,7 +497,7 @@ test('older in-flight reload cannot invalidate a newer restore Undo', async t => const staleSettings = JSON.parse(JSON.stringify(h.settings)); let release; h.w.api.getProjects = async () => ({ defaultProjects: [], allProjects: [] }); - h.w.api.getSetting = async () => staleSettings; + h.w.api.getSetting = async key => key === 'archivedProjects' ? h.folders : staleSettings; h.w.api.getActiveTerminals = () => new Promise(resolve => { release = resolve; }); h.w.loadingStatus = h.document.createElement('div'); h.w.reportActivityFocus = h.w.reportActivityTitles = h.w.refreshSidebar = h.w.renderDefaultStatus = () => {}; @@ -502,7 +505,7 @@ test('older in-flight reload cannot invalidate a newer restore Undo', async t => const pending = realLoad(); await waitFor(() => release); h.w.loadProjects = Object.assign(async () => {}, { state: realLoad.state }); - h.w.api.getSetting = async () => h.settings; + h.w.api.getSetting = async key => key === 'archivedProjects' ? h.folders : h.settings; h.q('.archived-unarchive').click(); await settle(); const undo = h.q('.app-notice-action'); assert.ok(undo, 'restore creates Undo while older reload is pending'); @@ -510,3 +513,128 @@ test('older in-flight reload cannot invalidate a newer restore Undo', async t => release([]); await pending; assert.equal(undo.isConnected, true, 'older reload must preserve newer restore Undo'); }); + +test('folder-only archives show Folder, archive date and disabled schedule count', async t => { + const h = await setup(t, true); + h.folders['vps::/srv/folder'] = { archivedAt: '2026-11-19T10:00:00Z', disabledSchedules: ['one', 'two'] }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.equal(h.rows().length, 1, 'folder archive must be listed'); + const row = h.rows()[0]; + assert.deepEqual([...row.querySelectorAll('.archived-badge')].map(n => n.textContent), ['Folder', 'vps']); + assert.equal(row.querySelector('time').getAttribute('datetime'), '2026-11-19T10:00:00.000Z'); + assert.match(row.textContent, /2 schedules off/); + assert.match(h.q('[data-section="archived"]').textContent, /1/); + row.querySelector('.archived-unarchive').click(); + await waitFor(() => h.rows().length === 0); + assert.deepEqual(h.calls.folderRestore, ['vps::/srv/folder']); + assert.deepEqual(h.calls.restore, []); + assert.equal(h.calls.reload, 1); + assert.equal(h.q('.app-notice-action'), null, 'folder restore has no misleading Undo'); + assert.match(h.q('.app-notice').textContent, /Archive folder/); +}); + +test('combined archive is one row with two badges and restores project before folder', async t => { + const h = await setup(t, true); + const entry = 'vps::/srv/combined'; + h.settings.hiddenProjects = [entry]; + h.settings.hiddenProjectKinds[entry] = 'archive'; + h.folders[entry] = { archivedAt: '2026-11-19T10:00:00Z', disabledSchedules: ['one', 'two'] }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.equal(h.rows().length, 1); + assert.deepEqual([...h.rows()[0].querySelectorAll('.archived-badge')].map(n => n.textContent), ['Project', 'Folder', 'vps']); + const order = []; + const project = h.w.api.unarchiveProject, folder = h.w.api.unarchiveFolder; + h.w.api.unarchiveProject = async e => { order.push('project:' + e); return project(e); }; + h.w.api.unarchiveFolder = async e => { order.push('folder:' + e); return folder(e); }; + h.q('.archived-unarchive').click(); + await waitFor(() => h.rows().length === 0); + assert.deepEqual(order, ['project:' + entry, 'folder:' + entry]); + assert.match(h.q('.app-notice').textContent, /Archive folder/); + h.q('.app-notice-action').click(); + await waitFor(() => h.rows().length === 1); + assert.deepEqual(h.calls.archive, [['/srv/combined', 'vps::-srv-combined']]); + assert.doesNotMatch(h.rows()[0].querySelector('.archived-name').textContent, /Folder/); +}); + +test('combined restore accepts the folder already cleared by the real project writer', async t => { + const h = await setup(t, true), entry = 'vps::/srv/combined'; + h.settings.hiddenProjects = [entry]; + h.settings.hiddenProjectKinds[entry] = 'archive'; + h.folders[entry] = { archivedAt: '2026-11-19T10:00:00Z', disabledSchedules: ['one'] }; + const state = { global: h.settings, archivedProjects: h.folders }; + const writer = require('./fixtures/writer-memory.cjs').memoryWriter({ + getSetting: key => state[key], setSetting: (key, value) => { state[key] = value; }, + }, {}); + h.w.api.unarchiveProject = async e => { await writer.unhideProject(e, 'vps', '/srv/combined'); return { ok: true }; }; + h.w.api.unarchiveFolder = async e => { + h.calls.folderRestore.push(e); + return await writer.clearArchivedEntry('vps', '/srv/combined') ? { ok: true } : { error: 'Folder is not archived', code: 'NOT_ARCHIVED' }; + }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.match(h.rows()[0].textContent, /Folder/); + h.q('.archived-unarchive').click(); + await waitFor(() => h.rows().length === 0); + assert.deepEqual(h.calls.folderRestore, [entry]); + assert.equal(h.q('.choice-dialog'), null); + assert.equal(state.archivedProjects[entry], undefined); + assert.deepEqual(state.scheduleReenableOffers[entry].disabledSchedules, ['one']); +}); + +for (const failure of ['project', 'folder']) test(`combined ${failure} refusal leaves an accurate retryable row`, async t => { + const h = await setup(t, true), entry = entries[0]; + h.settings.hiddenProjects = [entry]; + h.settings.hiddenProjectKinds[entry] = 'archive'; + h.folders[entry] = { disabledSchedules: [] }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.match(h.rows()[0].textContent, /Folder/); + const original = failure === 'project' ? h.w.api.unarchiveProject : h.w.api.unarchiveFolder; + h.w.api[failure === 'project' ? 'unarchiveProject' : 'unarchiveFolder'] = async () => ({ error: 'refused' }); + h.q('.archived-unarchive').click(); + await waitFor(() => h.q('.choice-dialog')); + assert.equal(h.rows().length, 1); + assert.equal(/Project/.test(h.rows()[0].querySelector('.archived-name').textContent), failure === 'project'); + assert.equal(h.calls.folderRestore.length, 0); + h.q('.choice-dialog-confirm').click(); + await waitFor(() => !h.q('.choice-dialog')); + assert.equal(h.q('.archived-unarchive').disabled, false); + h.w.api[failure === 'project' ? 'unarchiveProject' : 'unarchiveFolder'] = original; + h.q('.archived-unarchive').click(); + await waitFor(() => h.rows().length === 0); + assert.equal(h.calls.restore.length, 1, 'retry must not repeat a successful project restore'); +}); + +test('unknown standalone folder keeps its row and reports NOT_ARCHIVED', async t => { + const h = await setup(t, true); + h.folders['/folder'] = {}; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.equal(h.rows().length, 1, 'folder archive must be listed'); + h.w.api.unarchiveFolder = async () => ({ error: 'Folder is not archived', code: 'NOT_ARCHIVED' }); + h.q('.archived-unarchive').click(); + await waitFor(() => h.q('.choice-dialog')); + assert.match(h.q('.choice-dialog').textContent, /Folder is not archived/); + assert.equal(h.rows().length, 1); + assert.equal(h.q('.archived-unarchive').disabled, false); +}); + +test('mixed bulk restore stays sequential and Undo only rearchives project entries', async t => { + const h = await setup(t, true); + h.settings.hiddenProjects = [entries[0]]; + h.settings.hiddenProjectKinds[entries[0]] = 'archive'; + h.folders['/folder'] = { archivedAt: 'invalid', disabledSchedules: [] }; + h.folders['/gone'] = { disabledSchedules: [] }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.equal(h.rows().length, 2, 'deleted entries stay excluded from the merged list'); + assert.equal(h.rows()[1].querySelector('time'), null, 'invalid dates are omitted'); + const order = []; + const project = h.w.api.unarchiveProject, folder = h.w.api.unarchiveFolder; + h.w.api.unarchiveProject = async e => { order.push('project'); await settle(); return project(e); }; + h.w.api.unarchiveFolder = async e => { assert.deepEqual(order, ['project']); order.push('folder'); return folder(e); }; + h.q('.archived-select-all').click(); h.q('.archived-bulk').click(); + await waitFor(() => h.rows().length === 0); + assert.deepEqual(order, ['project', 'folder']); + assert.equal(h.document.querySelectorAll('.app-notice').length, 1); + assert.match(h.q('.app-notice').textContent, /2.*restored.*Undo.*project.*Archive folder/s); + h.q('.app-notice-action').click(); + await waitFor(() => h.rows().length === 1); + assert.deepEqual(h.calls.archive, [[entries[0], h.w.encodeProjectPath(entries[0])]]); +}); diff --git a/test/dom-folder-archive-undo.test.js b/test/dom-folder-archive-undo.test.js index e2080a607..c873a6cc4 100644 --- a/test/dom-folder-archive-undo.test.js +++ b/test/dom-folder-archive-undo.test.js @@ -302,3 +302,49 @@ test('PR5b review one session archive failure keeps the folder and offers no fol assert.equal(undo(ctx), undefined); assert.match(ctx.document.getElementById('app-notices').textContent, /Some sessions could not be archived; the folder was kept/); }); + +test('failed folder Undo offers Open Archived navigation', async t => { + const ctx = setup(t); + const opened = []; + ctx.window.openSettingsViewer = (...args) => opened.push(plain(args)); + ctx.window.api.undoArchiveProject = async () => ({ error: 'writer unavailable' }); + await archive(ctx); + undo(ctx).click(); + await settle(); + const action = ctx.document.querySelector('[role="alert"] .app-notice-action'); + assert.ok(action, 'folder Undo recovery must have an action'); + assert.equal(action.textContent, 'Open Archived'); + action.click(); + assert.deepEqual(opened, [['global', null, null, { section: 'archived' }]]); +}); + +for (const schedulesTab of [false, true]) test(`partial folder archive opens Archived, schedules tab=${schedulesTab}`, async t => { + const ctx = setup(t); + ctx.window.schedulesTabEnabled = schedulesTab; + const opened = []; + ctx.window.openSettingsViewer = (...args) => opened.push(plain(args)); + ctx.window.api.archiveProject = async () => ({ ok: true, archivedAt: 123, failed: [{ name: 'Audit', error: 'read-only' }], disabled: [] }); + await archive(ctx); + const notice = ctx.document.querySelector('[role="alert"]'); + assert.match(notice.textContent, /Archive folder partly done/); + assert.match(notice.textContent, schedulesTab ? /Schedules tab/ : /Agent Files tab/); + const action = notice.querySelector('.app-notice-action'); + assert.ok(action, 'partial folder archive recovery must have an action'); + assert.equal(action.textContent, 'Open Archived'); + action.click(); + assert.deepEqual(opened, [['global', null, null, { section: 'archived' }]]); +}); + +test('restored folder schedule offer appears first in its sidebar group', t => { + const ctx = setup(t); + const { archivedEntry, clearArchivedEntry, applyAndPersistArchived } = require('../archived-projects'); + const entry = archivedEntry(null, '/p'); + const state = { archivedProjects: { [entry]: { disabledSchedules: ['schedule-audit.md'] } } }; + const getSetting = key => state[key], setSetting = (key, value) => { state[key] = value; }; + assert.equal(clearArchivedEntry(getSetting, setSetting, null, '/p'), true); + const projects = applyAndPersistArchived(ctx.window.cachedAllProjects, false, { getSetting, setSetting, scheduleName: () => 'Audit' }); + ctx.sidebar.renderProjects(projects, true); + const notice = ctx.document.querySelector('.schedule-reenable-notice'); + assert.ok(notice, 'restored folder shows its schedule offer'); + assert.equal(notice.parentElement.firstElementChild, notice, 'schedule offer is at the top of its group'); +}); diff --git a/test/dom-remote-host-labels.test.js b/test/dom-remote-host-labels.test.js index 0962bb098..4addf38d4 100644 --- a/test/dom-remote-host-labels.test.js +++ b/test/dom-remote-host-labels.test.js @@ -22,7 +22,7 @@ async function setup(t, hosts = [{ alias, label: 'VPS', enabled: true }]) { window.reportActivityFocus = () => {}; window.reportActivityTitles = () => {}; window.renderDefaultStatus = () => {}; - window.api.getSetting = async () => settings; + window.api.getSetting = async key => key === 'archivedProjects' ? {} : settings; window.api.getProjects = async () => ({ defaultProjects: [project], allProjects: [project] }); window.api.getActiveTerminals = async () => []; window.refreshSidebar = () => ctx.sidebar.renderProjects(window.cachedProjects, true); diff --git a/test/unarchive-folder.test.js b/test/unarchive-folder.test.js new file mode 100644 index 000000000..209b8c0b1 --- /dev/null +++ b/test/unarchive-folder.test.js @@ -0,0 +1,103 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const vm = require('node:vm'); +const { memoryWriter } = require('./fixtures/writer-memory.cjs'); +const { archivedEntry, applyAndPersistArchived } = require('../archived-projects'); +const { parseFolderKey } = require('../src/main/remote/remote-hosts'); + +function setup(t, alias = null, rootPath) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'unarchive-folder-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const projectPath = rootPath || (alias ? '/srv/project' : path.join(root, 'project')); + const entry = archivedEntry(alias, projectPath); + const file = path.join(root, 'schedule-audit.md'); + fs.writeFileSync(file, '---\nname: Audit\ncron: 0 * * * *\nenabled: false\n---\nAudit\n'); + const settingsFile = path.join(root, 'settings.json'); + const originalOffer = { archivedAt: 'old', disabledSchedules: ['other.md'], failed: [{ name: 'other', error: 'offline' }] }; + fs.writeFileSync(settingsFile, JSON.stringify({ + archivedProjects: { [entry]: { archivedAt: '2026-11-19T10:00:00Z', knownSessionIds: ['one'], disabledSchedules: [file] }, untouched: { archivedAt: 'old' } }, + scheduleReenableOffers: { untouched: originalOffer }, + })); + const getSetting = key => JSON.parse(fs.readFileSync(settingsFile, 'utf8'))[key]; + const setSetting = (key, value) => { + const settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); + settings[key] = value; + fs.writeFileSync(settingsFile, JSON.stringify(settings)); + }; + const row = { sessionId: 'one', archived: 1, created: '2026-11-18T10:00:00Z' }; + const writer = memoryWriter({ getSetting, setSetting, getAllCached: () => [row], + setArchived: (_id, value) => { row.archived = value; } }, {}); + const handlers = new Map(), notifications = []; + const filename = path.join(__dirname, '../main.js'); + const source = fs.readFileSync(filename, 'utf8'); + const start = source.indexOf("ipcMain.handle('unarchive-folder',"); + if (start !== -1) vm.runInNewContext(source.slice(start, source.indexOf('\n});', start) + 4), { + writer, getSetting, parseFolderKey, + ipcMain: { handle: (name, handler) => handlers.set(name, handler) }, + notifyRendererProjectsChanged: reason => notifications.push(reason), + }, { filename }); + const invoke = async value => { + assert.ok(handlers.has('unarchive-folder'), 'plain folder restore IPC must be registered'); + return handlers.get('unarchive-folder')(null, value); + }; + return { root, entry, projectPath, alias, file, row, writer, invoke, getSetting, setSetting, notifications, originalOffer }; +} + +for (const alias of [null, 'vps']) test(`plain folder restore preserves sessions and disabled files, seeds the sidebar offer: ${alias || 'local'}`, async t => { + const h = setup(t, alias); + const before = fs.readFileSync(h.file); + assert.equal((await h.invoke(h.entry)).ok, true); + assert.equal(h.getSetting('archivedProjects')[h.entry], undefined); + assert.deepEqual(h.getSetting('archivedProjects').untouched, { archivedAt: 'old' }); + assert.deepEqual(h.getSetting('scheduleReenableOffers').untouched, h.originalOffer); + assert.deepEqual(h.getSetting('scheduleReenableOffers')[h.entry], { archivedAt: '2026-11-19T10:00:00Z', disabledSchedules: [h.file] }); + assert.equal(h.row.archived, 1); + assert.deepEqual(fs.readFileSync(h.file), before); + assert.deepEqual(h.notifications, ['archive']); + const projects = applyAndPersistArchived([{ projectPath: h.projectPath, remoteAlias: alias, folder: '-project', sessions: [h.row] }], false, h); + assert.deepEqual(projects[0].reenableOffer, { names: ['Audit'] }); +}); + +test('remote root folder restore uses its exact stored identity', async t => { + const h = setup(t, 'vps', '/'); + assert.equal(h.entry, 'vps::'); + assert.equal((await h.invoke(h.entry)).ok, true); + assert.equal(h.getSetting('archivedProjects')[h.entry], undefined); +}); + +test('unknown folder restore refuses without writes or notifications', async t => { + const h = setup(t); + const before = h.getSetting('archivedProjects'); + const offers = h.getSetting('scheduleReenableOffers'); + const result = await h.invoke('vps::/unknown'); + assert.equal(result.code, 'NOT_ARCHIVED'); + assert.match(result.error, /not archived/i); + assert.deepEqual(h.getSetting('archivedProjects'), before); + assert.deepEqual(h.getSetting('scheduleReenableOffers'), offers); + assert.deepEqual(h.notifications, []); +}); + +test('folder restore reports a rejected writer without announcing success', async t => { + const h = setup(t); + h.writer.clearArchivedEntry = async () => { throw new Error('writer unavailable'); }; + const result = await h.invoke(h.entry); + assert.equal(result.error, 'writer unavailable'); + assert.ok(h.getSetting('archivedProjects')[h.entry]); + assert.deepEqual(h.notifications, []); +}); + +test('preload forwards the exact folder archive entry on its own channel', async () => { + const filename = path.join(__dirname, '../preload.js'); + const source = fs.readFileSync(filename, 'utf8'); + const property = source.match(/^\s*unarchiveFolder:\s*(.+),\s*$/m); + assert.ok(property, 'preload exposes unarchiveFolder'); + const calls = []; + const context = vm.createContext({ ipcRenderer: { invoke: (...args) => { calls.push(args); return Promise.resolve({ ok: true }); } } }); + const forward = vm.runInContext(property[1], context, { filename }); + assert.equal((await forward('vps::/srv/éxact')).ok, true); + assert.deepEqual(calls, [['unarchive-folder', 'vps::/srv/éxact']]); +}); From 7b3aabee83281bddf78d0b6ed822624558337224 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sat, 21 Nov 2026 07:17:52 +0100 Subject: [PATCH 2/2] fix(archived): keep the retry guidance of a partial folder archive The partial Archive folder notice says again to restore the folder in Archived before retrying, the schedule count is singular for one and hidden at zero, and the own-key guard of unarchive-folder is tested. --- .ai/contexts/session-cache.md | 8 ++- CHANGELOG.md | 1 + public/archived-manager.js | 2 +- public/sidebar.js | 3 +- test/dom-archived-manager.test.js | 9 ++++ test/dom-row-action-errors.test.js | 80 ++++++++++++++++-------------- test/unarchive-folder.test.js | 15 ++++++ 7 files changed, 78 insertions(+), 40 deletions(-) diff --git a/.ai/contexts/session-cache.md b/.ai/contexts/session-cache.md index 77ad202f0..9bd83f303 100644 --- a/.ai/contexts/session-cache.md +++ b/.ai/contexts/session-cache.md @@ -2610,12 +2610,18 @@ lists never cross the writer transport. See `session-index-writer.md` for orderi alongside non-deleted `hiddenProjects`, merging an exact entry into one row with Project and Folder badges. `unarchive-folder(entry)` calls the writer's `clearArchivedEntry` and sends one `projects-changed('archive')` notification on - success; missing entries return `NOT_ARCHIVED`. `add-project` and + success; missing entries return `NOT_ARCHIVED`. The own-key check precedes + writer normalization: `vps::/srv/x/` cannot restore stored `vps::/srv/x`. + `add-project` and `delete-worktree` retain their existing clearing paths. A plain folder restore keeps session archive flags and schedule file bytes unchanged. The existing clearing helper moves disabled schedules into a re-enable offer, preserving unrelated offers. Folder Undo remains the separate timestamp-checked path. Recovery notices for a failed Undo or partial Archive expose **Open Archived**. + Partial Archive notices also explain that retrying Archive folder requires + restoring the folder in Archived first, with either Schedules tab setting. + Folder rows show disabled schedule counts only above zero, using singular + "1 schedule off" for one file. - **Re-enable offers.** An entry records `disabledSchedules`, the files the archive actually disabled. When an entry leaves `archivedProjects` (a reappearance in `get-projects`, or `clearArchivedEntry`), a non-empty list diff --git a/CHANGELOG.md b/CHANGELOG.md index 68f94a8a5..c1fc3aedd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc - Codex sessions run non-interactively by a program (`codex exec`: scripted reviews and fixes) are now left out of the sidebar and grid like Claude Agent SDK sessions, under the same **Hide SDK-launched Sessions** setting. They still count in the heatmap and are found by search; the ones you have open stay listed. Codex sessions already indexed are re-checked once at the next start. (#1145) ### Fixed +- A partially completed Archive folder explains how to restore the folder before retrying, with an Open Archived button. Archived folders omit empty schedule counts and show "1 schedule off" for a single disabled schedule. (#1167) - After restarting the app or Windows, the sidebar shows the projects as they were at exit, even if the last project load finished just before you closed the app or signed out. (#1136) - On Windows, a slow start no longer leaves tabs without process cleanup: tabs already open, restored ones included, are covered once cleanup starts, and programs they launch afterwards end when the tab closes. Programs launched before that can keep running. (#1140, #1156) - Claude and Codex sessions in `.work-files/worktrees/`, and Codex sessions in `.worktrees`, `.claude-worktrees` and `.claude/worktrees`, appear under their existing repository, including nested worktrees and sessions already indexed. Repository settings, archive and hidden state follow the group, and project deletion removes the session metadata it previews for both runtimes. Archiving a repository covers its worktrees' sessions; a new session in a worktree reopens the repository. Resume and fork use the recorded worktree directory and refuse to launch if it no longer exists; Claude sessions in a deleted `.claude/worktrees` directory are refused instead of starting in the repository. (#1137) diff --git a/public/archived-manager.js b/public/archived-manager.js index 83ee093c8..95628ca46 100644 --- a/public/archived-manager.js +++ b/public/archived-manager.js @@ -168,7 +168,7 @@ function renderArchivedProjects(container, { entries, kinds = {}, dates = {}, fo
${escapeHtml(p.name)} ${hasProject ? 'Project' : ''}${hasFolder ? ' Folder' : ''}${hasProject && kinds[entry] === undefined ? ' legacy' : ''}${alias ? ` ${escapeHtml(alias)}` : ''}
${escapeHtml(p.projectPath)}
-
${date && Number.isFinite(date.getTime()) ? `` : ''}${p.cached ? ` ${p.sessions.length} session${p.sessions.length === 1 ? '' : 's'}` : ''}${Array.isArray(folder?.disabledSchedules) ? ` ${folder.disabledSchedules.length} schedules off` : ''}
+
${date && Number.isFinite(date.getTime()) ? `` : ''}${p.cached ? ` ${p.sessions.length} session${p.sessions.length === 1 ? '' : 's'}` : ''}${Array.isArray(folder?.disabledSchedules) && folder.disabledSchedules.length > 0 ? ` ${folder.disabledSchedules.length} schedule${folder.disabledSchedules.length === 1 ? '' : 's'} off` : ''}
⋯
`; diff --git a/public/sidebar.js b/public/sidebar.js index 97cd90362..a85fd716e 100644 --- a/public/sidebar.js +++ b/public/sidebar.js @@ -2095,7 +2095,8 @@ async function archiveProjectFolder(project, button) { } else if (res.failed?.length) { showAppNotice({ id: sessionActionNoticeId('Archive folder', project), kind: 'error', message: `Archive folder partly done for ${sessionActionDescription(project)}: The folder is archived, but these schedules could not be disabled: ${res.failed.map(f => f.name + ': ' + f.error).join('; ')}. ` - + (window.schedulesTabEnabled ? 'Review the schedules in the Schedules tab.' : 'Review schedule-*.md in the Agent Files tab.'), + + (window.schedulesTabEnabled ? 'Review the schedules in the Schedules tab.' : 'Review schedule-*.md in the Agent Files tab.') + + ' To retry Archive folder, restore the folder in Archived first.', actionLabel: 'Open Archived', onAction: () => openSettingsViewer('global', null, null, { section: 'archived' }) }); } else { clearAppNotice(sessionActionNoticeId('Archive folder', project)); diff --git a/test/dom-archived-manager.test.js b/test/dom-archived-manager.test.js index 7eef2b0f8..a50cee711 100644 --- a/test/dom-archived-manager.test.js +++ b/test/dom-archived-manager.test.js @@ -85,6 +85,15 @@ async function setup(t, empty = false) { return { ...h, w, settings, folders, calls, q, rows, observers }; } +for (const count of [0, 1]) test(`folder disabled schedule count is accurate for ${count}`, async t => { + const h = await setup(t, true); + h.folders['vps::/srv/folder'] = { disabledSchedules: Array.from({ length: count }, (_, i) => `schedule-${i}.md`) }; + await h.w.openSettingsViewer('global', null, null, { section: 'archived' }); + assert.equal(h.rows().length, 1); + const meta = h.rows()[0].querySelector('.archived-meta'); + assert.equal(meta.textContent.trim(), count === 1 ? '1 schedule off' : ''); +}); + test('host groups preserve separate worktree entries, names, safe paths, badges, dates and counts', async t => { const h = await setup(t); assert.equal(h.rows().length, 4, 'four archived entries including the worktree must have their own rows'); diff --git a/test/dom-row-action-errors.test.js b/test/dom-row-action-errors.test.js index 4ae53a666..d659d2763 100644 --- a/test/dom-row-action-errors.test.js +++ b/test/dom-row-action-errors.test.js @@ -53,6 +53,49 @@ function setup(t, extra = {}) { return { ...h, session, project, render, click, notice, focus, timers, confirmations }; } +test('folder partial success names Schedules tab and uses a partial headline with one path', async t => { + const h = setup(t); + h.window.api.getProjectArchivePlan = async () => ({ schedules: [] }); + h.window.api.archiveProject = async () => ({ ok: true, failed: [{ name: 'nightly', error: 'EACCES' }] }); + const pending = h.click('.project-archive-btn'); + await answerChoiceDialog(h, { confirm: true }); + await pending; + const el = h.document.querySelector('[role="alert"]'); + assert.match(el.textContent, /^Archive folder partly done/); + assert.match(el.textContent, /Schedules tab/); + assert.match(el.textContent, /To retry Archive folder, restore the folder in Archived first\./); + assert.equal(el.querySelector('.app-notice-action').textContent, 'Open Archived'); + assert.doesNotMatch(el.textContent, /schedules in Settings|Archive folder failed/); + assert.equal(el.textContent.split('/project').length - 1, 1); +}); + +for (const partial of [false, true]) { + test(`off-mode folder archive ${partial ? 'partly done' : 'failure'} points to Agent Files`, async t => { + const h = setup(t); + h.window.schedulesTabEnabled = false; + h.window.api.getProjectArchivePlan = async () => ({ schedules: [] }); + h.window.api.archiveProject = async () => partial + ? { ok: true, failed: [{ name: 'nightly', error: 'EACCES' }] } + : { ok: false, error: 'database locked' }; + const pending = h.click('.project-archive-btn'); + await answerChoiceDialog(h, { confirm: true }); + await pending; + const el = h.document.querySelector('[role="alert"]'); + assert.ok(el, 'archive recovery stays visible'); + assert.match(el.textContent, partial + ? /Review schedule-\*\.md in the Agent Files tab/ + : /Check schedule-\*\.md in the Agent Files tab/); + assert.match(el.textContent, partial ? /^Archive folder partly done/ : /^Archive folder failed/); + assert.match(el.textContent, partial ? /nightly: EACCES/ : /database locked/); + assert.match(el.textContent, /retry Archive folder/); + if (partial) { + assert.match(el.textContent, /To retry Archive folder, restore the folder in Archived first\./); + assert.equal(el.querySelector('.app-notice-action').textContent, 'Open Archived'); + } + assert.doesNotMatch(el.textContent, /Schedules tab/); + }); +} + test('successive not-stopped batches merge by host and refresh a repeated member reason', t => { const h = setup(t, { remoteAlias: 'vps' }); const second = { ...h.session, sessionId: 's2', name: 'Second' }; @@ -392,43 +435,6 @@ test('a failed Unarchive names that action and preserves its archived state', as assert.equal(h.session.archived, 1); }); -test('folder partial success names Schedules tab and uses a partial headline with one path', async t => { - const h = setup(t); - h.window.api.getProjectArchivePlan = async () => ({ schedules: [] }); - h.window.api.archiveProject = async () => ({ ok: true, failed: [{ name: 'nightly', error: 'EACCES' }] }); - const pending = h.click('.project-archive-btn'); - await answerChoiceDialog(h, { confirm: true }); - await pending; - const el = h.document.querySelector('[role="alert"]'); - assert.match(el.textContent, /^Archive folder partly done/); - assert.match(el.textContent, /Schedules tab/); - assert.doesNotMatch(el.textContent, /schedules in Settings|Archive folder failed/); - assert.equal(el.textContent.split('/project').length - 1, 1); -}); - -for (const partial of [false, true]) { - test(`off-mode folder archive ${partial ? 'partly done' : 'failure'} points to Agent Files`, async t => { - const h = setup(t); - h.window.schedulesTabEnabled = false; - h.window.api.getProjectArchivePlan = async () => ({ schedules: [] }); - h.window.api.archiveProject = async () => partial - ? { ok: true, failed: [{ name: 'nightly', error: 'EACCES' }] } - : { ok: false, error: 'database locked' }; - const pending = h.click('.project-archive-btn'); - await answerChoiceDialog(h, { confirm: true }); - await pending; - const el = h.document.querySelector('[role="alert"]'); - assert.ok(el, 'archive recovery stays visible'); - assert.match(el.textContent, partial - ? /Review schedule-\*\.md in the Agent Files tab/ - : /Check schedule-\*\.md in the Agent Files tab/); - assert.match(el.textContent, partial ? /^Archive folder partly done/ : /^Archive folder failed/); - assert.match(el.textContent, partial ? /nightly: EACCES/ : /database locked/); - assert.match(el.textContent, /retry Archive folder/); - assert.doesNotMatch(el.textContent, /Schedules tab/); - }); -} - test('an Archive database failure after Stop says the process stopped and the row is not archived', async t => { const h = setup(t); h.window.activePtyIds.add('s1'); diff --git a/test/unarchive-folder.test.js b/test/unarchive-folder.test.js index 209b8c0b1..706da9ae4 100644 --- a/test/unarchive-folder.test.js +++ b/test/unarchive-folder.test.js @@ -81,6 +81,21 @@ test('unknown folder restore refuses without writes or notifications', async t = assert.deepEqual(h.notifications, []); }); +test('folder restore refuses a normalized alias of an exact stored entry without changes', async t => { + const h = setup(t, 'vps', '/srv/x'); + assert.equal(h.entry, 'vps::/srv/x'); + const archives = h.getSetting('archivedProjects'); + const offers = h.getSetting('scheduleReenableOffers'); + const file = fs.readFileSync(h.file); + const result = await h.invoke('vps::/srv/x/'); + assert.equal(result.code, 'NOT_ARCHIVED'); + assert.deepEqual(h.getSetting('archivedProjects'), archives); + assert.deepEqual(h.getSetting('scheduleReenableOffers'), offers); + assert.deepEqual(fs.readFileSync(h.file), file); + assert.equal(h.row.archived, 1); + assert.deepEqual(h.notifications, []); +}); + test('folder restore reports a rejected writer without announcing success', async t => { const h = setup(t); h.writer.clearArchivedEntry = async () => { throw new Error('writer unavailable'); };