)}
+
}
+
{pluginProps && }
,
diff --git a/components/files/file-views.tsx b/components/files/file-views.tsx
index 7087c3d62..f03d33c64 100644
--- a/components/files/file-views.tsx
+++ b/components/files/file-views.tsx
@@ -10,6 +10,7 @@ import {
FileSize, MiddleCutName, ResourceIcon, ShareBadge, Thumbnail, canShowThumbnail, formatFullDate, formatShortDate,
type IconOptions,
} from "@/components/files/file-item-parts";
+import { FilesSyncBadge } from "@/components/files-sync/files-sync-item";
import type { SortDir, SortKey } from "@/components/files/files-header";
import { TOUCH_HIT_AREA } from "@/components/ui/button";
import { FILE_LIST_COLUMNS } from "./file-list-layout";
@@ -274,6 +275,7 @@ function FileListRow({ resource, isSelected, isFocused, isTabStop, isDropTarget,
{isStarred && }
+
{touch && (
@@ -487,6 +489,7 @@ function FileTile({ resource, isSelected, isFocused, isTabStop, isCut, selecting
{!resource.isSymlink && <> · >}{formatShortDate(resource.lastModified)}
+
(null);
useEffect(() => watchTitlebarArea((next) => {
diff --git a/components/providers/files-sync-host.tsx b/components/providers/files-sync-host.tsx
new file mode 100644
index 000000000..0f941679b
--- /dev/null
+++ b/components/providers/files-sync-host.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { getDesktopBridge } from "@/lib/desktop/bridge";
+import { getDesktopPolicy, onDesktopPolicyChange } from "@/lib/desktop/policy";
+import { canDownload } from "@/lib/device-policy";
+import { claimFilesControls } from "@/lib/files-sync/controls";
+import { FilesSyncHost as Host, type HostAccount } from "@/lib/files-sync/host";
+import { registerFilesSyncLifecycle, setRunningFilesSyncHost } from "@/lib/files-sync/lifecycle";
+import { scopeDecided } from "@/lib/offline/offline-mode";
+import { subscribePushStateChanges } from "@/lib/push-events";
+import { useAccountStore } from "@/stores/account-store";
+import { useAuthStore } from "@/stores/auth-store";
+import { useFilesSyncStore } from "@/stores/files-sync-store";
+
+registerFilesSyncLifecycle();
+
+/** `FilesFolderSyncEnabled` forced off. Main removes the folders itself; this keeps the engine off them meanwhile. */
+function folderSyncForcedOff(): boolean {
+ const entry = getDesktopPolicy().FilesFolderSyncEnabled;
+ return entry.locked && entry.value === false;
+}
+
+/** A definite no from the organisation. An unknown policy isn't one. */
+function downloadsForbidden(account: string): boolean {
+ return scopeDecided(account) && !canDownload(account);
+}
+
+/**
+ * Files on this computer, in the desktop app's main window (it's under MainWindowOnly): starts
+ * the sync engine for the signed-in accounts and keeps it fed with push, the network and the
+ * policies. Renders nothing. In a browser, or a shell without the files bridge, it does nothing.
+ */
+export function FilesSyncHost() {
+ const hostRef = useRef(null);
+ const accounts = useAccountStore((s) => s.accounts);
+ const activeAccountId = useAuthStore((s) => s.activeAccountId);
+ const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
+ const revision = useAuthStore((s) => s.connectedAccountsRevision);
+ const client = useAuthStore((s) => s.client);
+
+ useEffect(() => {
+ const bridge = getDesktopBridge();
+ const controls = bridge?.files ? claimFilesControls() : null;
+ if (!bridge || !controls) return;
+ const store = useFilesSyncStore.getState();
+ const host = new Host({
+ controls,
+ platform: bridge.platform,
+ publish: (patch) => useFilesSyncStore.getState().publish(patch),
+ setController: (controller) => useFilesSyncStore.getState().setController(controller),
+ folderSyncForcedOff,
+ downloadsForbidden,
+ });
+ hostRef.current = host;
+ setRunningFilesSyncHost(host);
+ host.start();
+ const stopPush = subscribePushStateChanges((change, changedClient) => {
+ for (const [account, entry] of useAuthStore.getState().getAllConnectedClients()) {
+ if (entry !== changedClient) continue;
+ if (Object.values(change.changed).some((types) => !!types && "FileNode" in types)) host.remoteChanged(account);
+ }
+ });
+ const stopPolicy = onDesktopPolicyChange(() => host.policyChanged());
+ const online = () => host.online();
+ window.addEventListener("online", online);
+ return () => {
+ stopPush();
+ stopPolicy();
+ window.removeEventListener("online", online);
+ setRunningFilesSyncHost(null);
+ host.stop();
+ hostRef.current = null;
+ store.reset();
+ };
+ }, []);
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ const clients = isAuthenticated ? useAuthStore.getState().getAllConnectedClients() : new Map();
+ const list: HostAccount[] = [];
+ for (const [id, entry] of clients) {
+ const account = accounts.find((a) => a.id === id);
+ if (account && !account.isConnected) continue;
+ list.push({ id, label: account?.email || account?.username || account?.label || id, client: entry });
+ }
+ host.setAccounts(list, isAuthenticated ? activeAccountId : null);
+ }, [accounts, activeAccountId, isAuthenticated, revision, client]);
+
+ return null;
+}
diff --git a/components/settings/__tests__/desktop-files-settings.test.tsx b/components/settings/__tests__/desktop-files-settings.test.tsx
new file mode 100644
index 000000000..4ef21b3e3
--- /dev/null
+++ b/components/settings/__tests__/desktop-files-settings.test.tsx
@@ -0,0 +1,314 @@
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { NextIntlClientProvider } from 'next-intl';
+import en from '@/locales/en/common.json';
+import type { FilesDriveState, FilesRoot } from '@/lib/desktop/types';
+import type { FilesSyncActivity, FilesSyncController, FilesSyncRootStatus } from '@/lib/files-sync/types';
+
+// Files on this computer, the settings page: the drive, synced folders, the
+// activity list and the mass-delete question, against the store and a fake
+// controller (the engine is built elsewhere).
+
+vi.unmock('next-intl');
+vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } }));
+
+const { useFilesSyncStore } = await import('@/stores/files-sync-store');
+const { useAuthStore } = await import('@/stores/auth-store');
+const { DesktopFilesSettings } = await import('../desktop-files-settings');
+
+type Fake = { [K in keyof FilesSyncController]: ReturnType };
+
+function fakeController(): Fake {
+ return {
+ addFolder: vi.fn(async () => ({ ok: true as const, value: folderRoot() })),
+ removeRoot: vi.fn(async () => {}),
+ setPaused: vi.fn(async () => {}),
+ confirmMassDelete: vi.fn(async () => {}),
+ setDriveEnabled: vi.fn(async () => ({ ok: true as const, value: null })),
+ setDriveLetter: vi.fn(async () => ({ ok: true as const, value: { letter: 'Z', chosen: 'Z', locked: false, available: [] } })),
+ coverage: vi.fn(() => null),
+ showInFolder: vi.fn(async () => true),
+ clearActivity: vi.fn(),
+ } as never;
+}
+
+function folderRoot(patch: Partial = {}): FilesRoot {
+ return {
+ id: 'r1', kind: 'folder', account: 'acc', path: 'C:\\Users\\ann\\Documents\\Projects', remoteId: 'n-proj',
+ remoteLabel: 'Projects', paused: false, createdAt: 1, ...patch,
+ };
+}
+
+function drive(patch: Partial = {}): FilesDriveState {
+ return {
+ supported: true, forcedOff: false, wanted: [],
+ letter: { letter: null, chosen: null, locked: false, available: ['X', 'Z'] },
+ ...patch,
+ };
+}
+
+let controller: ReturnType;
+
+function setup(patch: Record = {}) {
+ controller = fakeController();
+ useFilesSyncStore.setState({ available: true, account: 'acc', controller: controller as unknown as FilesSyncController, ...patch });
+}
+
+function renderPage() {
+ return render(
+
+
+ ,
+ );
+}
+
+beforeEach(() => {
+ useFilesSyncStore.getState().reset();
+});
+afterEach(() => {
+ useFilesSyncStore.getState().reset();
+});
+
+describe('Files on this computer settings page', () => {
+ it('draws nothing outside the desktop app or on an older shell', () => {
+ useFilesSyncStore.setState({ available: false, roots: [folderRoot()], drive: drive() });
+ const { container } = renderPage();
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('has no drive section off Windows', () => {
+ setup({ drive: null });
+ renderPage();
+ expect(screen.queryByRole('switch', { name: 'Show Files as a drive' })).toBeNull();
+ expect(screen.getByRole('heading', { name: 'Synced folders' })).toBeInTheDocument();
+ });
+
+ it('turns the drive on for the account from the click itself', () => {
+ setup({ drive: drive() });
+ renderPage();
+ const toggle = screen.getByRole('switch', { name: 'Show Files as a drive' });
+ expect(toggle).toHaveAttribute('aria-checked', 'false');
+ // No drive, no letter.
+ expect(screen.queryByText('Drive letter')).toBeNull();
+ fireEvent.click(toggle);
+ // Synchronously: the shell needs the click it came from.
+ expect(controller.setDriveEnabled).toHaveBeenCalledWith(true);
+ });
+
+ it('shows the drive on, and turns it off', () => {
+ setup({ drive: drive({ wanted: ['acc'] }) });
+ renderPage();
+ const toggle = screen.getByRole('switch', { name: 'Show Files as a drive' });
+ expect(toggle).toHaveAttribute('aria-checked', 'true');
+ fireEvent.click(toggle);
+ expect(controller.setDriveEnabled).toHaveBeenCalledWith(false);
+ });
+
+ it('says the organisation turned the drive off and keeps the switch off', () => {
+ setup({ drive: drive({ forcedOff: true, wanted: ['acc'] }) });
+ renderPage();
+ const toggle = screen.getByRole('switch', { name: 'Show Files as a drive' });
+ expect(toggle).toHaveAttribute('aria-checked', 'false');
+ expect(toggle).toBeDisabled();
+ expect(screen.getByText(en.settings.org_locked)).toBeInTheDocument();
+ });
+
+ it('offers no letter by default and the free letters, and sets the chosen one', () => {
+ setup({ drive: drive({ wanted: ['acc'] }) });
+ renderPage();
+ const select = screen.getByRole('combobox', { name: 'Drive letter' }) as HTMLSelectElement;
+ expect(select.value).toBe('none');
+ expect([...select.options].map((o) => o.textContent)).toEqual(['No letter', 'X:', 'Z:']);
+ fireEvent.change(select, { target: { value: 'Z' } });
+ expect(controller.setDriveLetter).toHaveBeenCalledWith('Z');
+ fireEvent.change(select, { target: { value: 'none' } });
+ expect(controller.setDriveLetter).toHaveBeenLastCalledWith(null);
+ });
+
+ it('shows a letter forced by policy, locked', () => {
+ setup({ drive: drive({ wanted: ['acc'], letter: { letter: 'Q', chosen: 'X', locked: true, available: ['X'] } }) });
+ renderPage();
+ const select = screen.getByRole('combobox', { name: 'Drive letter' }) as HTMLSelectElement;
+ expect(select.value).toBe('Q');
+ expect(select).toBeDisabled();
+ const row = select.closest('[data-search-label]') as HTMLElement;
+ expect(within(row).getByText(en.settings.org_locked)).toBeInTheDocument();
+ });
+
+ it('lists a synced folder with its Files folder and pauses and resumes it', () => {
+ setup({ roots: [folderRoot()], status: { r1: { rootId: 'r1', state: 'idle', pending: 0, done: 0, lastSyncedAt: null } } });
+ const { rerender } = renderPage();
+ expect(screen.getByText('C:\\Users\\ann\\Documents\\Projects')).toBeInTheDocument();
+ expect(screen.getByText('With Projects in Files')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Pause' }));
+ expect(controller.setPaused).toHaveBeenCalledWith('r1', true);
+
+ act(() => useFilesSyncStore.setState({ roots: [folderRoot({ paused: true })], status: { r1: { rootId: 'r1', state: 'paused', pending: 0, done: 0, lastSyncedAt: null } } }));
+ rerender(
+
+
+ ,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Resume' }));
+ expect(controller.setPaused).toHaveBeenLastCalledWith('r1', false);
+ });
+
+ it('asks before removing a folder, saying its files stay', () => {
+ setup({ roots: [folderRoot()] });
+ renderPage();
+ fireEvent.click(screen.getByRole('button', { name: 'Remove…' }));
+ const dialog = screen.getByRole('alertdialog');
+ expect(dialog).toHaveTextContent('The files on this computer stay where they are');
+ expect(controller.removeRoot).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Stop syncing' }));
+ expect(controller.removeRoot).toHaveBeenCalledWith('r1');
+ });
+
+ it('says how each folder is doing', () => {
+ const at = Date.UTC(2026, 10, 4, 14, 5);
+ vi.useFakeTimers({ now: at + 60_000, toFake: ['Date'] });
+ const states: [string, Partial][] = [
+ ['idle', { lastSyncedAt: at }],
+ ['syncing', { done: 3, pending: 7 }],
+ ['paused', {}],
+ ['offline', { pending: 2 }],
+ ['error', { errorKey: 'files_sync.errors.quota' }],
+ ['blocked', {}],
+ ['starting', {}],
+ ];
+ const roots = states.map(([state]) => folderRoot({ id: state, path: `/home/ann/${state}` }));
+ const status = Object.fromEntries(states.map(([state, extra]) => [state, { rootId: state, state, pending: 0, done: 0, lastSyncedAt: null, ...extra }]));
+ setup({ roots, status });
+ renderPage();
+ const line = (id: string) => document.querySelector(`[data-files-sync-root="${id}"] [data-files-sync-state]`)!.textContent;
+ expect(line('idle')).toMatch(/^Up to date\. Last synced .*2:05/);
+ expect(line('syncing')).toBe('Syncing: 3 done, 7 to go');
+ expect(line('paused')).toBe('Paused');
+ expect(line('offline')).toBe('Offline. 2 changes wait for the server');
+ expect(line('error')).toBe('Stopped: Your storage in Files is full');
+ expect(line('blocked')).toBe('Turned off by your organisation');
+ expect(line('starting')).toBe('Starting…');
+ // A blocked folder can't be resumed, only removed.
+ expect(within(document.querySelector('[data-files-sync-root="blocked"]') as HTMLElement).queryByRole('button', { name: 'Resume' })).toBeNull();
+ vi.useRealTimers();
+ });
+
+ it('shows an unknown error key as a plain failure, never the key', () => {
+ setup({ roots: [folderRoot()], status: { r1: { rootId: 'r1', state: 'error', pending: 0, done: 0, lastSyncedAt: null, errorKey: 'something_new' } } });
+ renderPage();
+ expect(screen.getByText('Stopped: Something went wrong')).toBeInTheDocument();
+ });
+
+ it('adds a folder: picks the Files folder, then calls the controller from that click', async () => {
+ const listAllFileNodes = vi.fn(async () => [
+ { id: 'n-proj', name: 'Projects', parentId: null, blobId: null },
+ { id: 'n-2026', name: '2026', parentId: 'n-proj', blobId: null },
+ { id: 'n-file', name: 'a.txt', parentId: 'n-proj', blobId: 'b1' },
+ ]);
+ useAuthStore.setState({ client: { listAllFileNodes } as never });
+ setup({ roots: [] });
+ renderPage();
+ expect(screen.getByText('No folders are synced yet.')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Add folder…' }));
+ const dialog = await screen.findByRole('dialog', { name: 'Which folder in Files?' });
+ // Only folders are offered.
+ expect(within(dialog).queryByText('a.txt')).toBeNull();
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Expand Projects' }));
+ await waitFor(() => expect(within(dialog).getByText('2026')).toBeInTheDocument());
+ fireEvent.click(within(dialog).getByText('2026'));
+ expect(controller.addFolder).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Choose folder on this computer…' }));
+ // In the same task as the click: nothing slow is awaited first.
+ expect(controller.addFolder).toHaveBeenCalledWith('n-2026', 'Projects / 2026');
+ useAuthStore.setState({ client: null });
+ });
+
+ it('says why a folder could not be added, and nothing when the picker was closed', async () => {
+ useAuthStore.setState({ client: { listAllFileNodes: vi.fn(async () => [{ id: 'n-proj', name: 'Projects', parentId: null, blobId: null }]) } as never });
+ setup({ roots: [] });
+ controller.addFolder.mockResolvedValueOnce({ ok: false, error: 'overlap' });
+ renderPage();
+ fireEvent.click(screen.getByRole('button', { name: 'Add folder…' }));
+ let dialog = await screen.findByRole('dialog');
+ fireEvent.click(within(dialog).getByText('Projects'));
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Choose folder on this computer…' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent(en.files_sync.folders.add_failed.overlap);
+
+ controller.addFolder.mockResolvedValueOnce({ ok: false, error: 'cancelled' });
+ fireEvent.click(screen.getByRole('button', { name: 'Add folder…' }));
+ dialog = await screen.findByRole('dialog');
+ fireEvent.click(within(dialog).getByText('Projects'));
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Choose folder on this computer…' }));
+ await waitFor(() => expect(controller.addFolder).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ useAuthStore.setState({ client: null });
+ });
+
+ it('hides adding folders when the organisation turned folder sync off', () => {
+ setup({ folderSyncForcedOff: true, roots: [folderRoot()], status: { r1: { rootId: 'r1', state: 'blocked', pending: 0, done: 0, lastSyncedAt: null } } });
+ renderPage();
+ expect(screen.queryByRole('button', { name: 'Add folder…' })).toBeNull();
+ expect(screen.getByTestId('files-sync-folders-locked')).toHaveTextContent(en.settings.org_locked);
+ // The folder can still be removed; its files stay.
+ expect(screen.getByRole('button', { name: 'Remove…' })).toBeInTheDocument();
+ });
+
+ it('lists recent activity newest first, marks conflicts and errors, and clears it', () => {
+ const activity: FilesSyncActivity[] = [
+ { id: 'a1', at: 1000, rootId: 'r1', kind: 'uploaded', direction: 'up', path: 'notes.txt' },
+ { id: 'a3', at: 3000, rootId: 'r1', kind: 'error', direction: 'up', path: 'big.iso', messageKey: 'files_sync.errors.quota' },
+ { id: 'a2', at: 2000, rootId: 'r1', kind: 'conflict', direction: null, path: 'plan.docx', detail: 'plan (conflict, PC, 2026-11-04).docx' },
+ { id: 'a4', at: 500, rootId: 'r1', kind: 'too-large', direction: null, path: 'video.mp4', detail: '1048576' },
+ ];
+ setup({ roots: [folderRoot()], activity });
+ renderPage();
+ const rows = within(screen.getByTestId('files-sync-activity')).getAllByRole('listitem');
+ expect(rows.map((r) => r.getAttribute('data-activity-kind'))).toEqual(['error', 'conflict', 'uploaded', 'too-large']);
+ expect(rows[0]).toHaveTextContent('big.iso couldn\'t be synced: Your storage in Files is full');
+ expect(within(rows[0]).getByRole('img', { name: 'Error' })).toBeInTheDocument();
+ expect(rows[1]).toHaveTextContent('plan.docx was changed in both places. The other version is kept as plan (conflict, PC, 2026-11-04).docx');
+ expect(within(rows[1]).getByRole('img', { name: 'Conflict' })).toBeInTheDocument();
+ expect(rows[2]).toHaveTextContent('Projects');
+ expect(rows[2]).toHaveTextContent('Uploaded notes.txt');
+ expect(within(rows[2]).getByRole('img', { name: 'To Files' })).toBeInTheDocument();
+ expect(rows[3]).toHaveTextContent('video.mp4 is bigger than Files allows (1 MB)');
+ expect(within(rows[3]).getByRole('img', { name: 'Error' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
+ expect(controller.clearActivity).toHaveBeenCalled();
+ });
+
+ it('has a line for every kind of activity', () => {
+ const kinds = ['uploaded', 'downloaded', 'folder-created', 'renamed', 'moved', 'deleted', 'trashed', 'conflict', 'renamed-for-disk', 'too-large', 'waiting', 'mass-delete', 'error'] as const;
+ setup({ roots: [folderRoot()], activity: kinds.map((kind, i) => ({ id: kind, at: 10_000 - i, rootId: 'r1', kind, direction: null, path: 'x.txt', detail: 'y.txt' })) });
+ renderPage();
+ const rows = within(screen.getByTestId('files-sync-activity')).getAllByRole('listitem');
+ expect(rows).toHaveLength(kinds.length);
+ for (const row of rows) expect(row.textContent).not.toMatch(/files_sync\.|\{/);
+ });
+
+ it('says when nothing happened yet', () => {
+ setup({ roots: [folderRoot()] });
+ renderPage();
+ expect(screen.getByText('Nothing has happened yet.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Clear' })).toBeDisabled();
+ });
+
+ it('asks about a mass delete in the folder row, with both answers', () => {
+ setup({
+ roots: [folderRoot(), folderRoot({ id: 'r2', path: '/home/ann/Photos', remoteLabel: 'Photos' })],
+ status: {
+ r1: { rootId: 'r1', state: 'confirm-delete', pending: 0, done: 0, lastSyncedAt: null, massDelete: { count: 120, side: 'local' } },
+ r2: { rootId: 'r2', state: 'confirm-delete', pending: 0, done: 0, lastSyncedAt: null, massDelete: { count: 64, side: 'remote' } },
+ },
+ });
+ renderPage();
+ const first = document.querySelector('[data-files-sync-root="r1"]') as HTMLElement;
+ expect(first).toHaveTextContent('120 items were deleted from Projects on this computer. Delete them in Files too?');
+ const second = document.querySelector('[data-files-sync-root="r2"]') as HTMLElement;
+ expect(second).toHaveTextContent('64 items were deleted from Photos in Files. Delete them on this computer too?');
+ fireEvent.click(within(first).getByRole('button', { name: 'Delete them' }));
+ expect(controller.confirmMassDelete).toHaveBeenCalledWith('r1', true);
+ fireEvent.click(within(second).getByRole('button', { name: 'Bring them back' }));
+ expect(controller.confirmMassDelete).toHaveBeenLastCalledWith('r2', false);
+ });
+});
diff --git a/components/settings/__tests__/settings-boot-skeleton.test.tsx b/components/settings/__tests__/settings-boot-skeleton.test.tsx
index 5417f9871..d974d4cd0 100644
--- a/components/settings/__tests__/settings-boot-skeleton.test.tsx
+++ b/components/settings/__tests__/settings-boot-skeleton.test.tsx
@@ -35,6 +35,7 @@ const { useSettingsStore } = await import('@/stores/settings-store');
const { SETTINGS_NAV_GROUPS } = await import('../settings-tab-icons');
const { BOOT_HINTS_KEY } = await import('@/lib/boot-skeleton/keys');
const { resetRailHintsMemo } = await import('@/lib/boot-skeleton/hints');
+const { useFilesSyncStore } = await import('@/stores/files-sync-store');
/** A client that supports everything it is asked about. */
const fullClient = new Proxy({}, {
@@ -91,11 +92,25 @@ describe('Settings while the session restores', () => {
expect(skeleton()).toBeNull();
const shown = [...document.querySelectorAll('[data-testid^="settings-tab-"]')]
.map((el) => el.getAttribute('data-testid')!.slice('settings-tab-'.length));
- // Recovery waits for a server probe this test doesn't answer.
- const drawn = SETTINGS_NAV_GROUPS.flatMap((g) => g.tabs).filter((tab) => tab !== 'recovery');
+ // Recovery waits for a server probe this test doesn't answer; Files on
+ // this computer for the desktop app's sync engine.
+ const drawn = SETTINGS_NAV_GROUPS.flatMap((g) => g.tabs).filter((tab) => tab !== 'recovery' && tab !== 'files_sync');
expect(shown).toEqual(drawn);
});
+ it('lists Files on this computer after Files only while the desktop sync engine runs', () => {
+ useAuthStore.setState({ isAuthenticated: true, isLoading: false, client: fullClient as never });
+ useFilesSyncStore.setState({ available: true });
+ try {
+ render();
+ const shown = [...document.querySelectorAll('[data-testid^="settings-tab-"]')]
+ .map((el) => el.getAttribute('data-testid')!.slice('settings-tab-'.length));
+ expect(shown.slice(shown.indexOf('files'), shown.indexOf('files') + 2)).toEqual(['files', 'files_sync']);
+ } finally {
+ useFilesSyncStore.getState().reset();
+ }
+ });
+
it('leaves the next load the pages this account has', () => {
useAuthStore.setState({ isAuthenticated: true, isLoading: false, client: bareClient as never });
render();
diff --git a/components/settings/__tests__/settings-search-anchors.test.tsx b/components/settings/__tests__/settings-search-anchors.test.tsx
index 14bb7ff1c..585aef541 100644
--- a/components/settings/__tests__/settings-search-anchors.test.tsx
+++ b/components/settings/__tests__/settings-search-anchors.test.tsx
@@ -36,6 +36,7 @@ const { useCalendarStore } = await import('@/stores/calendar-store');
const { useContactStore } = await import('@/stores/contact-store');
const { useEmailStore } = await import('@/stores/email-store');
const { useAccountStore } = await import('@/stores/account-store');
+const { useFilesSyncStore } = await import('@/stores/files-sync-store');
const { TourProvider } = await import('@/components/tour/tour-provider');
const { AdvancedSettingsProvider } = await import('../settings-section');
const { tabSearchEntries, getByPath, withAppName, settingsTabLabelKey } = await import('@/lib/settings-search');
@@ -60,6 +61,7 @@ const pages = {
contacts: (await import('../contacts-settings')).ContactsSettings,
contacts2: (await import('../address-book-management-settings')).AddressBookManagementSettings,
files: (await import('../files-settings')).FilesSettingsComponent,
+ files_sync: (await import('../desktop-files-settings')).DesktopFilesSettings,
addons: (await import('../addons-settings')).AddonsSettings,
backup: (await import('../about-data-settings')).AboutDataSettings,
offline: (await import('@/components/offline/offline-settings')).OfflineSettings,
@@ -76,7 +78,7 @@ const OVERRIDES: Record unknown> = {
getPrincipals: async () => [], listArchivedEmails: async () => ({ items: [], nextPosition: null }),
};
/** Pages with rows of the desktop app's own, or browser rows it hides. */
-const DESKTOP_PAGES = new Set(['general', 'notifications', 'privacy', 'backup']);
+const DESKTOP_PAGES = new Set(['general', 'notifications', 'privacy', 'backup', 'files_sync']);
/** The desktop app's bridge, answering as Windows does, with every switch off. */
const DESKTOP_BRIDGE = {
@@ -121,7 +123,7 @@ const TAB_PAGES: Record = {
accessibility: ['accessibility'],
message_list: ['message_list'], reading: ['reading'], composing: ['composing'], vacation: ['vacation'],
filters: ['filters'], organize: ['organize'], security: ['security'], sharing: ['sharing'], recovery: ['recovery'], calendar: ['calendar', 'calendar2'],
- contacts: ['contacts', 'contacts2'], files: ['files'], addons: ['addons'], backup: ['backup'],
+ contacts: ['contacts', 'contacts2'], files: ['files'], files_sync: ['files_sync'], addons: ['addons'], backup: ['backup'],
offline: ['offline'], privacy: ['privacy'], about: ['about'],
};
@@ -141,7 +143,15 @@ describe('settings search index', () => {
const realMatchMedia = window.matchMedia;
const variants: Record void> = {
base: () => {},
- desktop: () => { window.bulwarkDesktop = DESKTOP_BRIDGE as never; },
+ desktop: () => {
+ window.bulwarkDesktop = DESKTOP_BRIDGE as never;
+ // Files on this computer: the engine runs, on Windows, with the drive on offer.
+ useFilesSyncStore.setState({
+ available: true,
+ account: 'acc',
+ drive: { supported: true, forcedOff: false, wanted: [], letter: { letter: null, chosen: null, locked: false, available: ['Z'] } },
+ });
+ },
touch: () => {
window.matchMedia = ((q: string) => ({ ...realMatchMedia(q), matches: q.includes('coarse') })) as typeof window.matchMedia;
},
@@ -160,6 +170,7 @@ describe('settings search index', () => {
useAccountStore.setState(accountsInitial, true);
window.matchMedia = realMatchMedia;
window.bulwarkDesktop = undefined;
+ useFilesSyncStore.getState().reset();
apply();
out[variant] = {};
for (const [tab, Page] of Object.entries(pages)) {
diff --git a/components/settings/desktop-files-settings.tsx b/components/settings/desktop-files-settings.tsx
new file mode 100644
index 000000000..fbeb9357a
--- /dev/null
+++ b/components/settings/desktop-files-settings.tsx
@@ -0,0 +1,346 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useFormatter, useTranslations } from "next-intl";
+import {
+ AlertCircle, AlertTriangle, ArrowDown, ArrowUp, FolderSync, HardDrive, HelpCircle, Loader2, Trash2, type AppIcon,
+} from "@/components/icons";
+import { Button } from "@/components/ui/button";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import { FolderPickerDialog, type PickerFolder } from "@/components/files/folder-picker-dialog";
+import { FilesSyncStatusLine } from "@/components/files-sync/files-sync-status-line";
+import { MassDeleteQuestion, useInlineMassDeleteQuestions } from "@/components/files-sync/files-sync-prompts";
+import { filesSyncErrorKey, rootName, syncTimeOptions } from "@/components/files-sync/files-sync-text";
+import { fileNodeKind } from "@/lib/jmap/filenode-kind";
+import { findTrashFolder, trashSubtreeIds } from "@/lib/files-trash";
+import { cn, formatFileSize } from "@/lib/utils";
+import type { FilesDriveState, FilesError, FilesRoot } from "@/lib/desktop/types";
+import type { FilesSyncActivity, FilesSyncActivityKind } from "@/lib/files-sync/types";
+import { useAuthStore } from "@/stores/auth-store";
+import { useFilesSyncStore } from "@/stores/files-sync-store";
+import { OrgLockedNote } from "./org-locked-note";
+import { SettingItem, SettingsSection, Select, ToggleSwitch } from "./settings-section";
+
+/**
+ * Settings > Files on this computer, in the desktop app only: the Files drive
+ * (Windows), folders kept the same as a Files folder, and what happened lately.
+ * Everything comes from stores/files-sync-store.ts and goes to the engine's
+ * controller; the page never talks to the bridge.
+ */
+export function DesktopFilesSettings() {
+ const available = useFilesSyncStore((s) => s.available);
+ const drive = useFilesSyncStore((s) => s.drive);
+ // The page asks about a mass delete in the folder's row; the app-wide dialog waits.
+ useInlineMassDeleteQuestions();
+ if (!available) return null;
+ return (
+
+ );
+}
+
+/** What went wrong turning something on, in words. */
+function addErrorKey(error: FilesError): string | null {
+ if (error === "cancelled") return null;
+ if (error === "overlap" || error === "denied" || error === "policy") return `folders.add_failed.${error}`;
+ return "folders.add_failed.failed";
+}
+
+function DriveSection({ drive }: { drive: FilesDriveState }) {
+ const t = useTranslations("files_sync");
+ const account = useFilesSyncStore((s) => s.account);
+ const roots = useFilesSyncStore((s) => s.roots);
+ const status = useFilesSyncStore((s) => s.status);
+ const controller = useFilesSyncStore((s) => s.controller);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+
+ const on = !drive.forcedOff && !!account && drive.wanted.includes(account);
+ const driveRoot = roots.find((r) => r.kind === "drive" && r.account === account);
+ const { letter } = drive;
+ const letterValue = (letter.locked ? letter.letter : letter.chosen) ?? "none";
+ const letters = [...new Set([...letter.available, letter.chosen, letter.letter].filter((l): l is string => !!l))].sort();
+
+ const toggle = (next: boolean) => {
+ if (!controller) return;
+ setError(null);
+ setBusy(true);
+ // Straight from the click: turning it on needs the click it came from.
+ void controller.setDriveEnabled(next).then(
+ (result) => { if (!result.ok) setError(addErrorKey(result.error)); },
+ () => setError("folders.add_failed.failed"),
+ ).finally(() => setBusy(false));
+ };
+ const chooseLetter = (value: string) => {
+ if (!controller) return;
+ setError(null);
+ void controller.setDriveLetter(value === "none" ? null : value).then(
+ (result) => { if (!result.ok) setError(addErrorKey(result.error)); },
+ () => setError("folders.add_failed.failed"),
+ );
+ };
+
+ return (
+
+
+
+
+ {on && driveRoot && }
+ {on && driveRoot && status[driveRoot.id]?.state === "confirm-delete" && status[driveRoot.id]?.massDelete && (
+
+ )}
+ {(on || letter.locked) && drive.supported && (
+
+
+ )}
+ {error && {t(error)}
}
+
+ );
+}
+
+/** The folders of the user's own Files, for the picker: no trash, nothing shared. */
+async function loadFolders(): Promise {
+ const client = useAuthStore.getState().client;
+ if (!client) throw new Error("not signed in");
+ const nodes = await client.listAllFileNodes();
+ const inTrash = trashSubtreeIds(nodes, findTrashFolder(nodes)?.id);
+ return nodes
+ .filter((n) => fileNodeKind(n) === "directory" && !n.discoverableOnly && !n.isShared && !inTrash.has(n.id) && !n.id.includes(":"))
+ .map((n) => ({ id: n.id, name: n.name, parentId: n.parentId ?? null }));
+}
+
+/** "Projects / 2026" for a folder, "My files" for the top. */
+function folderLabel(folders: PickerFolder[], id: string | null, top: string): string {
+ if (id === null) return top;
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ const names: string[] = [];
+ const seen = new Set();
+ for (let cur = byId.get(id); cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
+ seen.add(cur.id);
+ names.unshift(cur.name);
+ }
+ return names.join(" / ") || top;
+}
+
+function FoldersSection() {
+ const t = useTranslations("files_sync");
+ const tFiles = useTranslations("files");
+ const account = useFilesSyncStore((s) => s.account);
+ const roots = useFilesSyncStore((s) => s.roots);
+ const controller = useFilesSyncStore((s) => s.controller);
+ const forcedOff = useFilesSyncStore((s) => s.folderSyncForcedOff);
+ const [folders, setFolders] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const [removing, setRemoving] = useState(null);
+
+ const folderRoots = roots.filter((r) => r.kind === "folder" && (!account || r.account === account));
+
+ const openPicker = () => {
+ setError(null);
+ setLoading(true);
+ loadFolders().then(setFolders, () => setError("folders.load_failed")).finally(() => setLoading(false));
+ };
+ // Called from the picker's button: the OS folder picker needs that click, so
+ // nothing is awaited before addFolder.
+ const pick = (remoteId: string | null) => {
+ if (!controller) return;
+ const label = folderLabel(folders ?? [], remoteId, tFiles("my_files"));
+ void controller.addFolder(remoteId, label).then(
+ (result) => { if (!result.ok) setError(addErrorKey(result.error)); },
+ () => setError("folders.add_failed.failed"),
+ );
+ };
+
+ return (
+
+ {forcedOff && (
+
+
+
{t("folders.forced_off")}
+
+ )}
+ {folderRoots.length === 0 ? (
+ !forcedOff && {t("folders.empty")}
+ ) : (
+
+ {folderRoots.map((root) => (
+ setRemoving(root)} />
+ ))}
+
+ )}
+ {!forcedOff && (
+
+
+
+ )}
+ {error && {t(error)}
}
+ {folders && (
+ setFolders(null)}
+ onPick={pick}
+ title={t("folders.pick_title")}
+ confirmText={t("folders.pick_confirm")}
+ folders={folders}
+ // Nothing is "where it is now": every folder, My files too, can be picked.
+ currentId="#none"
+ />
+ )}
+ setRemoving(null)}
+ onConfirm={() => { if (removing && controller) void controller.removeRoot(removing.id).catch(() => {}); }}
+ title={t("folders.remove_title")}
+ message={t("folders.remove_message")}
+ confirmText={t("folders.remove_confirm")}
+ variant="destructive"
+ />
+
+ );
+}
+
+function FolderRow({ root, onRemove }: { root: FilesRoot; onRemove: () => void }) {
+ const t = useTranslations("files_sync");
+ const status = useFilesSyncStore((s) => s.status[root.id]);
+ const controller = useFilesSyncStore((s) => s.controller);
+ const paused = root.paused || status?.state === "paused";
+ const blocked = status?.state === "blocked";
+ return (
+
+
+
+
+
+
{root.path}
+
{t("folders.paired_with", { folder: root.remoteLabel })}
+
+
+
+
+ {!blocked && (
+
+ )}
+
+
+
+ {status?.state === "confirm-delete" && status.massDelete && }
+
+ );
+}
+
+const ERROR_KINDS: ReadonlySet = new Set(["error", "too-large"]);
+
+function ActivityMark({ item }: { item: FilesSyncActivity }) {
+ const t = useTranslations("files_sync");
+ let mark: { icon: AppIcon; label: string; className: string } | null = null;
+ if (ERROR_KINDS.has(item.kind)) mark = { icon: AlertCircle, label: t("activity.mark_error"), className: "text-destructive" };
+ else if (item.kind === "conflict") mark = { icon: AlertTriangle, label: t("activity.mark_conflict"), className: "text-amber-600 dark:text-amber-400" };
+ else if (item.kind === "mass-delete") mark = { icon: HelpCircle, label: t("activity.mark_question"), className: "text-amber-600 dark:text-amber-400" };
+ else if (item.direction === "up") mark = { icon: ArrowUp, label: t("activity.to_files"), className: "text-muted-foreground" };
+ else if (item.direction === "down") mark = { icon: ArrowDown, label: t("activity.to_computer"), className: "text-muted-foreground" };
+ if (!mark) return ;
+ const Icon = mark.icon;
+ return (
+
+
+
+ );
+}
+
+function ActivitySection() {
+ const t = useTranslations("files_sync");
+ const format = useFormatter();
+ const activity = useFilesSyncStore((s) => s.activity);
+ const roots = useFilesSyncStore((s) => s.roots);
+ const controller = useFilesSyncStore((s) => s.controller);
+ const items = useMemo(() => [...activity].sort((a, b) => b.at - a.at), [activity]);
+ const rootById = useMemo(() => new Map(roots.map((r) => [r.id, r])), [roots]);
+
+ const message = (item: FilesSyncActivity) => {
+ const detail = item.kind === "too-large" && item.detail && /^\d+$/.test(item.detail)
+ ? formatFileSize(Number(item.detail))
+ : item.detail ?? "";
+ const text = t(`activity.${item.kind}`, { path: item.path, detail });
+ return (item.kind === "error" || item.kind === "waiting") && item.messageKey
+ ? `${text}: ${t(filesSyncErrorKey(item.messageKey))}`
+ : text;
+ };
+
+ return (
+
+ {items.length === 0 ? (
+ {t("activity.empty")}
+ ) : (
+
+ {items.map((item) => {
+ const root = rootById.get(item.rootId);
+ const marked = ERROR_KINDS.has(item.kind) || item.kind === "conflict" || item.kind === "mass-delete";
+ return (
+ -
+
+
+ {root && (
+
+ {root.kind === "drive" ? : }
+ {rootName(root, t("drive.root_name"))}
+
+ )}
+ {message(item)}
+
+ );
+ })}
+
+ )}
+
+
+
+
+ );
+}
diff --git a/components/settings/settings-app.tsx b/components/settings/settings-app.tsx
index 36379f6f1..faadf3bba 100644
--- a/components/settings/settings-app.tsx
+++ b/components/settings/settings-app.tsx
@@ -42,6 +42,8 @@ import { HelpLinks } from '@/components/layout/help-links';
import { OrganizeSettings } from '@/components/settings/organize-settings';
import { AccountSecuritySettings } from '@/components/settings/account-security-settings';
import { FilesSettingsComponent } from '@/components/settings/files-settings';
+import { DesktopFilesSettings } from '@/components/settings/desktop-files-settings';
+import { useFilesSyncStore } from '@/stores/files-sync-store';
import { ContactsSettings } from '@/components/settings/contacts-settings';
import { AddonsSettings } from '@/components/settings/addons-settings';
import { NotificationSettings } from '@/components/settings/notification-settings';
@@ -686,6 +688,8 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
const supportsCalendar = client?.supportsCalendars() ?? false;
const supportsSieve = client?.supportsSieve() ?? false;
const supportsFiles = client?.supportsFiles() ?? false;
+ // Files on this computer: the desktop app's sync engine runs in this window.
+ const filesSyncAvailable = useFilesSyncStore((s) => s.available);
// Delegates (Settings > Sharing) needs someone to share with and something to share.
const supportsSharing = !delegationHidden && !!client?.getShareTargets && (client?.supportsPrincipals() ?? false)
&& ((client?.supportsMailboxSharing?.() ?? false)
@@ -718,6 +722,7 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
...(supportsCalendar && isFeatureEnabled('calendarEnabled') ? [{ id: 'calendar' as Tab, label: t('tabs.calendar'), icon: tabIcons.calendar, group: 'apps' as TabGroup }] : []),
...(isFeatureEnabled('contactsEnabled') ? [{ id: 'contacts' as Tab, label: t('tabs.contacts'), icon: tabIcons.contacts, group: 'apps' as TabGroup }] : []),
...(supportsFiles && isFeatureEnabled('filesEnabled') ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
+ ...(filesSyncAvailable && supportsFiles && isFeatureEnabled('filesEnabled') ? [{ id: 'files_sync' as Tab, label: tRoot(settingsTabLabelKey('files_sync')), icon: tabIcons.files_sync, group: 'apps' as TabGroup }] : []),
...(isFeatureEnabled('sidebarAppsEnabled') || isFeatureEnabled('pluginsEnabled') ? [{ id: 'addons' as Tab, label: t('tabs.addons'), icon: tabIcons.addons, group: 'apps' as TabGroup }] : []),
// Plugin-contributed pages nest under Add-ons: a page of its own for each
// plugin that offers one, and an entry for each plugin that offers only a
@@ -926,6 +931,7 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
: <>>
)}
{effectiveActiveTab === 'files' && }
+ {effectiveActiveTab === 'files_sync' && }
{effectiveActiveTab === 'addons' && }
{effectiveActiveTab === 'privacy' && }
{effectiveActiveTab === 'offline' && }
diff --git a/components/settings/settings-tab-icons.ts b/components/settings/settings-tab-icons.ts
index 2cee44f68..bb38501cc 100644
--- a/components/settings/settings-tab-icons.ts
+++ b/components/settings/settings-tab-icons.ts
@@ -8,6 +8,7 @@ import {
Calendar,
Filter,
FolderOpen,
+ FolderSync,
HardDrive,
BookUser,
Bell,
@@ -48,6 +49,7 @@ export const SETTINGS_TAB_ICONS: Record = {
calendar: Calendar,
contacts: BookUser,
files: HardDrive,
+ files_sync: FolderSync,
addons: Puzzle,
offline: CloudOff,
privacy: EyeOff,
@@ -66,6 +68,6 @@ export type SettingsTabGroup = 'top' | 'mail' | 'apps' | 'bottom';
export const SETTINGS_NAV_GROUPS: readonly { group: SettingsTabGroup; tabs: readonly SettingsSearchTab[] }[] = [
{ group: 'top', tabs: ['account', 'security', 'privacy', 'sharing', 'notifications', 'general', 'offline', 'appearance', 'accessibility'] },
{ group: 'mail', tabs: ['message_list', 'reading', 'composing', 'organize', 'filters', 'vacation', 'recovery'] },
- { group: 'apps', tabs: ['calendar', 'contacts', 'files', 'addons'] },
+ { group: 'apps', tabs: ['calendar', 'contacts', 'files', 'files_sync', 'addons'] },
{ group: 'bottom', tabs: ['backup', 'about'] },
];
diff --git a/desktop-policies/Bulwark.admx b/desktop-policies/Bulwark.admx
index 1d040ac07..6a2a8211c 100644
--- a/desktop-policies/Bulwark.admx
+++ b/desktop-policies/Bulwark.admx
@@ -230,5 +230,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop-policies/de-DE/Bulwark.adml b/desktop-policies/de-DE/Bulwark.adml
index e32e66dfc..8ae5378f3 100644
--- a/desktop-policies/de-DE/Bulwark.adml
+++ b/desktop-policies/de-DE/Bulwark.adml
@@ -69,6 +69,12 @@
Dieselben Werte wie die gleichnamige Richtlinie von Chrome. 2: Die Entwicklertools sind aus und die Einstellung ist gesperrt. 0 oder 1 oder nicht konfiguriert: Benutzer können sie nach einer Warnung in den Einstellungen einschalten. Mit den Entwicklertools kann jeder an der Tastatur alles lesen, was die App enthält, auch E-Mails und Passwörter im Speicher.
Zuletzt verwendete Dateien im Menü „Anfügen“ anzeigen
Wenn aktiviert oder nicht konfiguriert, listet die Schaltfläche „Anfügen“ in einer neuen Nachricht die Dateien auf, die der Benutzer zuletzt geöffnet hat, so wie das Betriebssystem sie erfasst. Ein Klick fügt eine davon an. Die Liste wird beim Öffnen des Menüs gelesen und bleibt auf dem Gerät. Wenn deaktiviert, fehlt die Liste und die App lehnt es ab, sie zu lesen. Das Anfügen über den Dateidialog ist nicht betroffen.
+ Dateien als Laufwerk zulassen
+ Wenn aktiviert oder nicht konfiguriert, können Benutzer ihre Dateien im Dateimanager als Laufwerk anzeigen. Dateien werden beim Öffnen heruntergeladen. Vorerst nur unter Windows. Wenn deaktiviert, wird das Laufwerk nicht angeboten, und ein vorhandenes Laufwerk wird mit den Kopien der Dateien darin entfernt. Die Dateien auf dem Server sind davon nicht betroffen.
+ Synchronisieren von Ordnern mit Dateien zulassen
+ Wenn aktiviert oder nicht konfiguriert, können Benutzer einen Ordner auf dem Computer und einen Ordner in Dateien in beide Richtungen gleich halten. Wenn deaktiviert, wird dies nicht angeboten, und Ordner, die gerade synchronisiert werden, hören damit auf. Die Dateien in diesen Ordnern bleiben, wo sie sind.
+ Laufwerksbuchstabe für Dateien
+ Nur unter Windows. Ein Buchstabe von D bis Z gibt dem Laufwerk Dateien für jeden Benutzer diesen Buchstaben, und Benutzer können ihn nicht ändern. Geben Sie none ein, damit es nie einen Buchstaben bekommt. Wenn nicht konfiguriert, wählen Benutzer in den Einstellungen, und bis dahin gibt es keinen Buchstaben. Ein Wert, den die App nicht lesen kann, gilt als none.
@@ -88,6 +94,7 @@
Adressen
Wert (0, 1 oder 2)
+
diff --git a/desktop-policies/en-US/Bulwark.adml b/desktop-policies/en-US/Bulwark.adml
index 1d50fd303..5ef2446ee 100644
--- a/desktop-policies/en-US/Bulwark.adml
+++ b/desktop-policies/en-US/Bulwark.adml
@@ -69,6 +69,12 @@
The same values as Chrome's policy of this name. 2: developer tools are off and the setting is locked. 0 or 1, or not configured: people can turn them on under Settings, after a warning. Developer tools let anyone at the keyboard read everything the app holds, mail and passwords in memory included.
Show recent files in the Attach menu
When enabled or not configured, the Attach button in a new message lists the files the user opened recently, as the operating system records them, so one click attaches one. The list is read when the menu opens and stays on the device. When disabled, the list is gone and the app refuses to read it. Attaching through the file dialog is not affected.
+ Allow Files as a drive
+ When enabled or not configured, people can show their Files in the file manager as a drive, with files downloaded when opened. Windows only for now. When disabled, the drive is not offered, and a drive that is already there is removed with the copies of files in it. Files on the server are not affected.
+ Allow syncing folders with Files
+ When enabled or not configured, people can keep a folder on the computer and a folder in Files the same, in both directions. When disabled, this is not offered and folders that sync now stop. The files in those folders stay where they are.
+ Drive letter for Files
+ Windows only. A letter from D to Z gives the Files drive that letter for every user, and they can't change it. Enter none to never give it a letter. When not configured, people choose under Settings, and there is no letter until they do. A value the app can't read counts as none.
@@ -88,6 +94,7 @@
Addresses
Value (0, 1 or 2)
+
diff --git a/desktop-policies/org.bulwarkmail.desktop.mobileconfig b/desktop-policies/org.bulwarkmail.desktop.mobileconfig
index cb9db7430..8487f71b6 100644
--- a/desktop-policies/org.bulwarkmail.desktop.mobileconfig
+++ b/desktop-policies/org.bulwarkmail.desktop.mobileconfig
@@ -71,6 +71,12 @@
2
RecentFilesInAttach
+ FilesDriveEnabled
+
+ FilesFolderSyncEnabled
+
+ FilesDriveLetter
+ none
Recommended
UpdateChannel
diff --git a/desktop-policies/policies.json b/desktop-policies/policies.json
index 27934322f..cf625e1da 100644
--- a/desktop-policies/policies.json
+++ b/desktop-policies/policies.json
@@ -30,6 +30,9 @@
"OpenWithEnabled": true,
"DeveloperToolsAvailability": 2,
"RecentFilesInAttach": true,
+ "FilesDriveEnabled": true,
+ "FilesFolderSyncEnabled": true,
+ "FilesDriveLetter": "none",
"Recommended": {
"UpdateChannel": "stable"
}
diff --git a/lib/desktop/__tests__/policy-schema.test.ts b/lib/desktop/__tests__/policy-schema.test.ts
index 377cddc93..b952bec50 100644
--- a/lib/desktop/__tests__/policy-schema.test.ts
+++ b/lib/desktop/__tests__/policy-schema.test.ts
@@ -15,6 +15,7 @@ import {
jmapServerAllowed,
parseCertificateRule,
parseInstanceUrl,
+ pagePolicySnapshot,
parsePolicyValue,
parseServerPattern,
pluginAllowedByPolicy,
@@ -32,7 +33,7 @@ describe('the schema', () => {
'PluginsMode', 'PluginAllowlist', 'OfflineEnabled', 'AppLockRequired', 'AppLockTimeoutMinutes', 'TelemetryAllowed',
'CrashReportsAllowed', 'QuickComposeShortcut', 'AuthServerAllowlist', 'AuthNegotiateDelegateAllowlist',
'AutoSelectCertificateForUrls', 'KeystoreEnabled', 'KeystoreAllowedOrigins', 'BrowserSignIn', 'WipeOfflineData',
- 'OpenWithEnabled', 'DeveloperToolsAvailability', 'RecentFilesInAttach',
+ 'OpenWithEnabled', 'DeveloperToolsAvailability', 'RecentFilesInAttach', 'FilesDriveEnabled', 'FilesFolderSyncEnabled', 'FilesDriveLetter',
]);
for (const key of POLICY_KEYS) {
const { title, description } = POLICY_SCHEMA[key];
@@ -65,6 +66,37 @@ describe('developer tools and Open with', () => {
});
});
+describe('Files on this computer', () => {
+ it('tells the page the drive and folder sync are forced off, so it can show the lock', () => {
+ const forced = resolvePolicies(layers({ forcedMachine: { FilesDriveEnabled: 0, FilesFolderSyncEnabled: 0, FilesDriveLetter: 'R' } }));
+ const page = pagePolicySnapshot(forced);
+ expect(page.FilesDriveEnabled).toMatchObject({ value: false, locked: true });
+ expect(page.FilesFolderSyncEnabled).toMatchObject({ value: false, locked: true });
+ // The letter comes from main with the drive's state.
+ expect(page.FilesDriveLetter).toMatchObject({ value: null, locked: false });
+ });
+
+ it('turn the drive and folder sync off only by force, and a value nobody can read leaves them off', () => {
+ for (const key of ['FilesDriveEnabled', 'FilesFolderSyncEnabled'] as const) {
+ expect(resolvePolicies(layers({}))[key]).toMatchObject({ value: true, locked: false });
+ expect(resolvePolicies(layers({ recommendedUser: { [key]: 0 } }))[key]).toMatchObject({ value: true, locked: false });
+ expect(resolvePolicies(layers({ forcedUser: { [key]: 0 } }))[key]).toMatchObject({ value: false, locked: true });
+ expect(resolvePolicies(layers({ forcedMachine: { [key]: 'perhaps' } }))[key]).toMatchObject({ value: false, locked: true });
+ }
+ });
+
+ it('takes a drive letter from D to Z or none, forced only, and a value nobody can read means no letter', () => {
+ expect(parsePolicyValue('FilesDriveLetter', 'x')).toEqual({ ok: true, value: 'X' });
+ expect(parsePolicyValue('FilesDriveLetter', ' Q: ')).toEqual({ ok: true, value: 'Q' });
+ expect(parsePolicyValue('FilesDriveLetter', 'NONE')).toEqual({ ok: true, value: 'none' });
+ for (const bad of ['C', 'A:', 'B', 'QQ', 'Q:\\', '', 4, null]) expect(parsePolicyValue('FilesDriveLetter', bad).ok, String(bad)).toBe(false);
+ expect(resolvePolicies(layers({})).FilesDriveLetter).toMatchObject({ value: null, locked: false });
+ expect(resolvePolicies(layers({ recommendedMachine: { FilesDriveLetter: 'R' } })).FilesDriveLetter).toMatchObject({ value: null, locked: false });
+ expect(resolvePolicies(layers({ forcedMachine: { FilesDriveLetter: 'r' } })).FilesDriveLetter).toMatchObject({ value: 'R', locked: true });
+ expect(resolvePolicies(layers({ forcedUser: { FilesDriveLetter: 'C' } })).FilesDriveLetter).toMatchObject({ value: 'none', locked: true });
+ });
+});
+
describe('precedence', () => {
it('forced machine > forced user > recommended machine > recommended user > default', () => {
const all = {
diff --git a/lib/desktop/policy-schema.ts b/lib/desktop/policy-schema.ts
index 54fca1a4c..fe2dbb390 100644
--- a/lib/desktop/policy-schema.ts
+++ b/lib/desktop/policy-schema.ts
@@ -83,6 +83,9 @@ export interface PolicyValues {
OpenWithEnabled: boolean;
DeveloperToolsAvailability: number | null;
RecentFilesInAttach: boolean;
+ FilesDriveEnabled: boolean;
+ FilesFolderSyncEnabled: boolean;
+ FilesDriveLetter: string | null;
}
export type PolicyKey = keyof PolicyValues;
@@ -129,7 +132,7 @@ export type PolicyDefinition = PolicyBase &
}
| {
type: 'string';
- format: 'instanceUrl' | 'shortcut' | 'hostList' | 'nonce';
+ format: 'instanceUrl' | 'shortcut' | 'hostList' | 'nonce' | 'driveLetter';
default: null;
maxLength: number;
label: PolicyText;
@@ -480,6 +483,47 @@ export const POLICY_SCHEMA: Record = {
de: 'Wenn aktiviert oder nicht konfiguriert, listet die Schaltfläche „Anfügen“ in einer neuen Nachricht die Dateien auf, die der Benutzer zuletzt geöffnet hat, so wie das Betriebssystem sie erfasst. Ein Klick fügt eine davon an. Die Liste wird beim Öffnen des Menüs gelesen und bleibt auf dem Gerät. Wenn deaktiviert, fehlt die Liste und die App lehnt es ab, sie zu lesen. Das Anfügen über den Dateidialog ist nicht betroffen.',
},
},
+ FilesDriveEnabled: {
+ category: 'system',
+ type: 'boolean',
+ default: true,
+ onInvalid: false,
+ forcedOnly: true,
+ sample: true,
+ title: { en: 'Allow Files as a drive', de: 'Dateien als Laufwerk zulassen' },
+ description: {
+ en: 'When enabled or not configured, people can show their Files in the file manager as a drive, with files downloaded when opened. Windows only for now. When disabled, the drive is not offered, and a drive that is already there is removed with the copies of files in it. Files on the server are not affected.',
+ de: 'Wenn aktiviert oder nicht konfiguriert, können Benutzer ihre Dateien im Dateimanager als Laufwerk anzeigen. Dateien werden beim Öffnen heruntergeladen. Vorerst nur unter Windows. Wenn deaktiviert, wird das Laufwerk nicht angeboten, und ein vorhandenes Laufwerk wird mit den Kopien der Dateien darin entfernt. Die Dateien auf dem Server sind davon nicht betroffen.',
+ },
+ },
+ FilesFolderSyncEnabled: {
+ category: 'system',
+ type: 'boolean',
+ default: true,
+ onInvalid: false,
+ forcedOnly: true,
+ sample: true,
+ title: { en: 'Allow syncing folders with Files', de: 'Synchronisieren von Ordnern mit Dateien zulassen' },
+ description: {
+ en: 'When enabled or not configured, people can keep a folder on the computer and a folder in Files the same, in both directions. When disabled, this is not offered and folders that sync now stop. The files in those folders stay where they are.',
+ de: 'Wenn aktiviert oder nicht konfiguriert, können Benutzer einen Ordner auf dem Computer und einen Ordner in Dateien in beide Richtungen gleich halten. Wenn deaktiviert, wird dies nicht angeboten, und Ordner, die gerade synchronisiert werden, hören damit auf. Die Dateien in diesen Ordnern bleiben, wo sie sind.',
+ },
+ },
+ FilesDriveLetter: {
+ category: 'system',
+ forcedOnly: true,
+ type: 'string',
+ format: 'driveLetter',
+ default: null,
+ maxLength: 8,
+ sample: 'none',
+ label: { en: 'Drive letter', de: 'Laufwerksbuchstabe' },
+ title: { en: 'Drive letter for Files', de: 'Laufwerksbuchstabe für Dateien' },
+ description: {
+ en: 'Windows only. A letter from D to Z gives the Files drive that letter for every user, and they can\'t change it. Enter none to never give it a letter. When not configured, people choose under Settings, and there is no letter until they do. A value the app can\'t read counts as none.',
+ de: 'Nur unter Windows. Ein Buchstabe von D bis Z gibt dem Laufwerk Dateien für jeden Benutzer diesen Buchstaben, und Benutzer können ihn nicht ändern. Geben Sie none ein, damit es nie einen Buchstaben bekommt. Wenn nicht konfiguriert, wählen Benutzer in den Einstellungen, und bis dahin gibt es keinen Buchstaben. Ein Wert, den die App nicht lesen kann, gilt als none.',
+ },
+ },
};
export const POLICY_KEYS = Object.keys(POLICY_SCHEMA) as PolicyKey[];
@@ -631,6 +675,16 @@ export function pluginAllowedByPolicy(mode: PluginsMode, allowlist: readonly str
const SHORTCUT = /^(?:(?:Command|Cmd|Control|Ctrl|CommandOrControl|CmdOrCtrl|Alt|Option|AltGr|Shift|Super|Meta)\+){1,4}(?:[A-Z0-9]|F[1-9]|F1[0-9]|F2[0-4]|Space|Tab|Enter|Backspace|Delete|Insert|Home|End|PageUp|PageDown|Up|Down|Left|Right|Plus|[-=,./;'`[\]\\])$/i;
+/** A drive letter from D to Z, upper case, or `none`. */
+function parseDriveLetter(raw: unknown): Parsed {
+ if (typeof raw !== 'string') return fail('not_text');
+ const text = raw.trim();
+ if (text.toLowerCase() === 'none') return { ok: true, value: 'none' };
+ const match = /^([D-Za-z]):?$/.exec(text);
+ if (!match || !/^[D-Z]$/i.test(match[1])) return fail('invalid_drive_letter');
+ return { ok: true, value: match[1].toUpperCase() };
+}
+
function parseShortcut(raw: unknown): Parsed {
if (typeof raw !== 'string') return fail('not_text');
const text = raw.trim();
@@ -810,6 +864,8 @@ export function parsePolicyValue(key: PolicyKey, raw: unknown, allowInsecure = f
return parseHostList(raw);
case 'nonce':
return parseNonce(raw);
+ case 'driveLetter':
+ return parseDriveLetter(raw);
}
break;
case 'list':
@@ -835,6 +891,8 @@ function failClosedValue(key: PolicyKey): PolicyValues[PolicyKey] {
if (definition.type === 'list') return [] as PolicyValues[PolicyKey];
// A shortcut nobody can read doesn't get the built-in one instead.
if (definition.type === 'string' && definition.format === 'shortcut') return 'off' as PolicyValues[PolicyKey];
+ // A drive letter nobody can read means no letter, not the user's own.
+ if (definition.type === 'string' && definition.format === 'driveLetter') return 'none' as PolicyValues[PolicyKey];
// A limit nobody can read is the tightest one, not the user's own.
if (definition.type === 'integer') return (definition.onInvalid !== undefined ? definition.onInvalid : definition.min) as PolicyValues[PolicyKey];
return definition.default as PolicyValues[PolicyKey];
@@ -931,6 +989,8 @@ const PAGE_POLICY_KEYS: readonly PolicyKey[] = [
'AppLockTimeoutMinutes',
'CrashReportsAllowed',
'RecentFilesInAttach',
+ 'FilesDriveEnabled',
+ 'FilesFolderSyncEnabled',
];
/**
@@ -981,6 +1041,9 @@ export const POLICY_CONSUMERS: Record = {
OpenWithEnabled: { repo: 'shell', file: 'src/main/features/os-default-app.ts' },
DeveloperToolsAvailability: { repo: 'shell', file: 'src/main/features/dev-tools.ts' },
RecentFilesInAttach: { repo: 'shell', file: 'src/main/features/os-recent.ts' },
+ FilesDriveEnabled: { repo: 'shell', file: 'src/main/features/files-drive.ts' },
+ FilesFolderSyncEnabled: { repo: 'shell', file: 'src/main/features/files-folders.ts' },
+ FilesDriveLetter: { repo: 'shell', file: 'src/main/features/files-drive.ts' },
};
/** The part the embedded server enforces. Sent to it by message. */
diff --git a/lib/desktop/types.ts b/lib/desktop/types.ts
index 3b14d714d..356f4d82c 100644
--- a/lib/desktop/types.ts
+++ b/lib/desktop/types.ts
@@ -936,6 +936,223 @@ export interface DesktopEditBridge {
onChange: (listener: (sessions: DesktopEditSession[]) => void) => () => void;
}
+/*
+ * Files on this computer: folders kept the same as a Files folder, and on Windows the
+ * Files drive (Cloud Files API placeholders). The sync engine is the page's
+ * (lib/files-sync in the webmail): it holds the JMAP session and decides. Main only does
+ * what the page can't: the disk, the folder picker, the OS's sync root, and the
+ * callbacks Windows makes when someone opens a file that isn't on the disk yet.
+ *
+ * Paths here are always relative to a root, with `/` between parts, never `..`, never
+ * absolute. Main resolves them inside the root and refuses anything that leaves it,
+ * through a link or otherwise.
+ */
+
+/** A place on this computer kept the same as Files: a folder the user picked, or the drive. */
+export interface FilesRoot {
+ /** Main's id for it. Random, never a path. */
+ id: string;
+ kind: 'folder' | 'drive';
+ /** The page's local account id it belongs to. */
+ account: string;
+ /** Where it is on disk, to show and nothing else. */
+ path: string;
+ /** A folder: the Files folder it pairs with (null: the top of Files). The drive: null. */
+ remoteId: string | null;
+ /** What the page called the Files side when it was added, to show. */
+ remoteLabel: string;
+ paused: boolean;
+ createdAt: number;
+}
+
+/** One file or folder under a root, as it is on disk now. */
+export interface FilesLocalEntry {
+ /** Relative to the root, `/` between parts. */
+ path: string;
+ kind: 'file' | 'directory';
+ size: number;
+ mtimeMs: number;
+ /** The same across a rename on the same volume (file id, inode), to tell a move from a delete and a create. */
+ fileId: string;
+ /** The drive only: what the placeholder says. */
+ placeholder?: FilesPlaceholderState;
+}
+
+export interface FilesPlaceholderState {
+ /** The FileNode id written into it. Null for something made in Explorer that isn't a placeholder yet. */
+ identity: string | null;
+ /** Main or the page marked it in sync and nobody changed it since. */
+ inSync: boolean;
+ /** The content is on this disk. */
+ hydrated: boolean;
+ pin: 'pinned' | 'unpinned' | 'unspecified';
+}
+
+/** What the page expects a path to be, so main refuses to act on something that changed meanwhile. */
+export interface FilesExpect {
+ fileId: string;
+ size: number;
+ mtimeMs: number;
+}
+
+export type FilesError =
+ /** Not there. */
+ | 'missing'
+ /** Something is already at the target. */
+ | 'exists'
+ /** It changed since the page looked (`expect` didn't match). */
+ | 'changed'
+ /** Another program has it open. */
+ | 'busy'
+ | 'denied'
+ /** The path leaves the root, or goes through a link. */
+ | 'outside'
+ /** A name this file system can't hold. */
+ | 'name'
+ /** The disk is full. */
+ | 'full'
+ /** The organisation's policy says no. */
+ | 'policy'
+ /** No real click came with a call that needs one. */
+ | 'gesture'
+ /** The user closed the picker. */
+ | 'cancelled'
+ /** The folder is inside another root, holds one, or is a system folder. */
+ | 'overlap'
+ /** The root is paused, gone, or the app is locked. */
+ | 'inactive'
+ | 'unsupported'
+ | 'failed';
+
+export type FilesResult = { ok: true; value: T } | { ok: false; error: FilesError };
+
+/** Something on disk under a root changed. `paths: null`: too much at once, scan it all. */
+export interface FilesChangeEvent {
+ rootId: string;
+ paths: string[] | null;
+}
+
+/** Windows wants bytes of a file that isn't on the disk yet: someone opened it. */
+export interface FilesFetchRequest {
+ fetchId: string;
+ rootId: string;
+ /** The FileNode id in the placeholder. */
+ identity: string;
+ path: string;
+ /** What Windows asked for. Supplying from 0 to the end is always fine. */
+ offset: number;
+ length: number;
+ /** The size in the placeholder. */
+ total: number;
+}
+
+/** A remote file or folder the drive should show, before any content is fetched. */
+export interface FilesPlaceholder {
+ path: string;
+ kind: 'file' | 'directory';
+ size: number;
+ mtimeMs: number;
+ identity: string;
+}
+
+export interface FilesDriveLetterState {
+ /** In use now. */
+ letter: string | null;
+ /** The user's own choice, kept even while a policy overrides it. */
+ chosen: string | null;
+ /** `FilesDriveLetter` forces it (a letter, or `none`). */
+ locked: boolean;
+ /** Letters free now, D to Z. */
+ available: string[];
+}
+
+export interface FilesDriveState {
+ /** Windows 10 1809 or later with the helper loaded. */
+ supported: boolean;
+ /** `FilesDriveEnabled` is off. */
+ forcedOff: boolean;
+ /** Accounts the user turned the drive on for, whether or not it's registered right now. */
+ wanted: string[];
+ letter: FilesDriveLetterState;
+}
+
+/**
+ * What the main page takes once, in its first render (`files.claim()`), like `auth.claim`:
+ * a same-origin frame reaches the bridge through `parent`, and main can't tell its calls
+ * apart. Main also takes these calls only from the main window.
+ */
+export interface FilesControls {
+ roots: () => Promise;
+ /** Shows the OS folder picker. Needs a real click. */
+ addFolder: (request: { account: string; remoteId: string | null; remoteLabel: string }) => Promise>;
+ /** A folder: forgotten, its files stay. The drive: as `drive.disable(account, 'user')`. */
+ removeRoot: (rootId: string) => Promise;
+ setPaused: (rootId: string, paused: boolean) => Promise;
+ /** Everything under `under` (default: the whole root). Skips links and main's own temporary files. */
+ scan: (rootId: string, under?: string) => Promise>;
+ stat: (rootId: string, path: string) => Promise>;
+ /** A URL the page fetches once for the file's bytes (Range works). Refused for a drive file that isn't on the disk. */
+ openRead: (rootId: string, path: string) => Promise>;
+ /**
+ * Writing a file: chunks go to a temporary file next to it, `commitWrite` puts it in place
+ * if what's there is still `expect` (null: nothing may be there), and sets `mtimeMs`.
+ */
+ beginWrite: (rootId: string, path: string, options: { expect: FilesExpect | null; mtimeMs: number; size: number }) => Promise>;
+ writeChunk: (writeId: string, data: Uint8Array) => Promise>;
+ commitWrite: (writeId: string) => Promise>;
+ abortWrite: (writeId: string) => Promise;
+ mkdir: (rootId: string, path: string) => Promise>;
+ /** Never overwrites. A case-only rename works on a case-insensitive disk. */
+ move: (rootId: string, from: string, to: string, expect: FilesExpect | null) => Promise>;
+ /** A folder: to the OS's trash where it has one. Refused when it changed since `expect`. */
+ remove: (rootId: string, path: string, expect: FilesExpect | null) => Promise>;
+ onChange: (listener: (event: FilesChangeEvent) => void) => () => void;
+ /** The engine's own record of a root (what both sides looked like at the last sync). */
+ loadState: (rootId: string) => Promise;
+ saveState: (rootId: string, state: string) => Promise;
+ /** Opens Explorer, Finder or the file manager on it. */
+ showInFolder: (rootId: string, path: string) => Promise;
+ /** Windows only. Absent elsewhere. */
+ drive?: FilesDriveControls;
+}
+
+export interface FilesDriveControls {
+ state: () => Promise;
+ onStateChange: (listener: (state: FilesDriveState) => void) => () => void;
+ /**
+ * Registers and connects the account's sync root. Needs a real click unless the user
+ * turned it on before (a sign-in brings it back). `label` is the address, shown when
+ * there are several accounts.
+ */
+ enable: (account: string, label: string) => Promise>;
+ /**
+ * `user`: turned off. `signed-out`: the account signed out, and comes back at the next
+ * sign-in. `wipe` and `refused`: a wipe or a refused login. Each unregisters the sync root
+ * and deletes it with everything in it; only `signed-out` keeps the wish.
+ */
+ disable: (account: string, reason: 'user' | 'signed-out' | 'wipe' | 'refused') => Promise;
+ /** New placeholders, parents first. One answer per entry. */
+ place: (rootId: string, entries: FilesPlaceholder[]) => Promise>;
+ /**
+ * New metadata from the server for a placeholder that is in sync. `dehydrate`: the
+ * content changed, drop the copy on disk (a pinned one is fetched again). Refused
+ * with `changed` when someone edited it here meanwhile.
+ */
+ update: (rootId: string, path: string, meta: { size: number; mtimeMs: number; identity: string; dehydrate: boolean }, expect: FilesExpect | null) => Promise>;
+ /** After an upload: makes it a placeholder with this identity if it isn't one, and marks it in sync. */
+ markInSync: (rootId: string, path: string, identity: string, expect: FilesExpect) => Promise>;
+ onFetch: (listener: (request: FilesFetchRequest) => void) => () => void;
+ onFetchCancel: (listener: (fetchId: string) => void) => () => void;
+ /** Bytes for a fetch, in order from `offset`. False when Windows no longer wants them. */
+ supply: (fetchId: string, offset: number, data: Uint8Array) => Promise;
+ fail: (fetchId: string, error: 'offline' | 'missing' | 'failed') => void;
+ setLetter: (letter: string | null) => Promise>;
+}
+
+export interface FilesBridge {
+ claim: () => FilesControls | null;
+}
+
export interface BulwarkDesktopBridge {
version: number;
platform: 'win32' | 'darwin' | 'linux';
@@ -965,6 +1182,8 @@ export interface BulwarkDesktopBridge {
edit?: DesktopEditBridge;
/** Absent on older shells. */
devTools?: DesktopDevToolsBridge;
+ /** Files on this computer. Absent on older shells. */
+ files?: FilesBridge;
/** Absent on older shells. */
recentFiles?: DesktopRecentFilesBridge;
}
diff --git a/lib/files-sync/__tests__/engine.test.ts b/lib/files-sync/__tests__/engine.test.ts
new file mode 100644
index 000000000..381f435a2
--- /dev/null
+++ b/lib/files-sync/__tests__/engine.test.ts
@@ -0,0 +1,627 @@
+// @vitest-environment node
+/**
+ * The sync engine against an in-memory disk (main's answers) and a fake FileNode server
+ * (Stalwart's). Each test changes one side or both and checks both sides afterwards.
+ */
+import { describe, expect, it } from 'vitest';
+import type { FilesRoot } from '@/lib/desktop/types';
+import { FilesSyncEngine, type EngineTiming } from '../engine';
+import { namingFor } from '../names';
+import { parseRecord } from '../state';
+import { FakeDisk, str, text } from './helpers/fake-disk';
+import { FakeServer, type FakeServerOptions } from './helpers/fake-server';
+
+const FAST: Partial = { localDelayMs: 0, remoteDelayMs: 0, pollMs: 1e9, rescanMs: 1e9, retryMs: [1e9], soonMs: 5, fetchWaitMs: 2000 };
+
+interface Setup {
+ server: FakeServer;
+ disk: FakeDisk;
+ engine: FilesSyncEngine;
+ root: FilesRoot;
+ sync: () => Promise;
+ kinds: () => string[];
+}
+
+async function setup(options: { server?: FakeServerOptions; drive?: boolean; remoteFolder?: string | null; platform?: string; seed?: (server: FakeServer, disk: FakeDisk, rootId: string) => void } = {}): Promise {
+ const server = new FakeServer(options.server);
+ const platform = options.platform ?? 'win32';
+ const disk = new FakeDisk({ caseInsensitive: platform !== 'linux', drive: options.drive });
+ let remoteId: string | null = null;
+ if (options.remoteFolder !== null && !options.drive) remoteId = server.folder(options.remoteFolder ?? 'Sync').id;
+ const root = disk.addRoot({ id: 'r1', account: 'a1', kind: options.drive ? 'drive' : 'folder', remoteId });
+ options.seed?.(server, disk, root.id);
+ const engine = new FilesSyncEngine({ controls: disk, naming: namingFor(platform), device: 'Laptop', readUrl: disk.readUrl, timing: FAST, now: () => disk.clock });
+ engine.start();
+ engine.setAccount('a1', server.remote());
+ const sync = async () => {
+ await engine.refreshRoots();
+ engine.syncNow();
+ await engine.settled();
+ };
+ await sync();
+ return { server, disk, engine, root, sync, kinds: () => engine.activity.map((entry) => `${entry.kind} ${entry.path}${entry.detail ? ` (${entry.detail})` : ''}`).reverse() };
+}
+
+/** What's under the root's Files folder, as paths relative to it. */
+function remoteUnder(server: FakeServer, folder = 'Sync'): string[] {
+ return server.listing().filter((path) => path.startsWith(`${folder}/`)).map((path) => path.slice(folder.length + 1)).filter(Boolean);
+}
+
+describe('first sync', () => {
+ it('puts both sides together without deleting anything', async () => {
+ const { server, disk } = await setup({
+ seed: (s, d, rootId) => {
+ const sync = s.find('Sync')!;
+ const docs = s.folder('Docs', sync.id);
+ s.file('a.txt', docs.id, 'remote a');
+ s.file('top.txt', sync.id, 'top');
+ d.write(rootId, 'notes.txt', 'local notes');
+ d.write(rootId, 'Pics/p.png', 'png');
+ },
+ });
+ expect(disk.listing('r1')).toEqual(['Docs/', 'Docs/a.txt', 'Pics/', 'Pics/p.png', 'notes.txt', 'top.txt']);
+ expect(remoteUnder(server)).toEqual(['Docs/', 'Docs/a.txt', 'Pics/', 'Pics/p.png', 'notes.txt', 'top.txt']);
+ expect(disk.read('r1', 'Docs/a.txt')).toBe('remote a');
+ expect(server.content(server.find('Sync/notes.txt')!.id)).toBe('local notes');
+ expect(disk.trashed).toEqual([]);
+ const record = parseRecord(disk.states.get('r1') ?? null, server.find('Sync')!.id);
+ expect(record.items.map((item) => item.path).sort()).toEqual(['Docs', 'Docs/a.txt', 'Pics', 'Pics/p.png', 'notes.txt', 'top.txt']);
+ });
+
+ it('takes the same file on both sides as one, and keeps both when they differ', async () => {
+ const { server, disk, kinds } = await setup({
+ seed: (s, d, rootId) => {
+ const sync = s.find('Sync')!;
+ s.file('same.txt', sync.id, 'identical');
+ s.file('differ.txt', sync.id, 'from files');
+ d.write(rootId, 'same.txt', 'identical');
+ d.write(rootId, 'differ.txt', 'from here');
+ },
+ });
+ expect(server.uploads).toEqual([9]);
+ expect(disk.read('r1', 'differ.txt')).toBe('from files');
+ const copy = disk.listing('r1').find((path) => path.startsWith('differ (conflict, Laptop, '));
+ expect(copy).toBeDefined();
+ expect(disk.read('r1', copy!)).toBe('from here');
+ expect(server.content(server.find(`Sync/${copy}`)!.id)).toBe('from here');
+ expect(kinds()).toContain(`conflict differ.txt (${copy})`);
+ });
+
+ it('syncs the top of Files, without the trash, when the pair names no folder', async () => {
+ const s = await setup({
+ remoteFolder: null,
+ seed: (server) => {
+ server.file('root.txt', null, 'at the top');
+ server.file('old.txt', server.folder('.Trash').id, 'deleted');
+ },
+ });
+ expect(s.disk.listing('r1')).toEqual(['root.txt']);
+ s.disk.write('r1', 'up.txt', 'new');
+ await s.sync();
+ expect(s.server.listing()).toEqual(['root.txt', 'up.txt']);
+ });
+});
+
+describe('files the computer makes for itself', () => {
+ it('never uploads them', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { disk.write(rootId, 'desktop.ini', 'x'); disk.write(rootId, 'Docs/~$report.docx', 'lock'); disk.write(rootId, 'Docs/report.docx', 'r'); } });
+ expect(remoteUnder(s.server)).toEqual(['Docs/', 'Docs/report.docx']);
+ });
+});
+
+describe('renames and moves', () => {
+ it('sends a rename and a move made here, without uploading again', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { disk.write(rootId, 'a.txt', 'aaa'); disk.mkdirUser(rootId, 'Folder'); } });
+ const id = s.server.find('Sync/a.txt')!.id;
+ const uploads = s.server.uploads.length;
+ s.disk.moveUser('r1', 'a.txt', 'Folder/b.txt');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['Folder/', 'Folder/b.txt']);
+ expect(s.server.find('Sync/Folder/b.txt')!.id).toBe(id);
+ expect(s.server.uploads.length).toBe(uploads);
+ expect(s.kinds()).toContain('moved Folder/b.txt (a.txt)');
+ });
+
+ it('moves a file here when it moved in Files, keeping the same file', async () => {
+ const s = await setup({ seed: (server) => { const sync = server.find('Sync')!; server.folder('Other', sync.id); server.file('x.txt', sync.id, 'xx'); } });
+ const fileId = s.disk.node('r1', 'x.txt').fileId;
+ const downloads = s.server.downloads.length;
+ s.server.rename(s.server.find('Sync/x.txt')!.id, 'y.txt', s.server.find('Sync/Other')!.id);
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['Other/', 'Other/y.txt']);
+ expect(s.disk.node('r1', 'Other/y.txt').fileId).toBe(fileId);
+ expect(s.server.downloads.length).toBe(downloads);
+ });
+
+ it('moves a whole folder either way with what is in it', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { disk.write(rootId, 'A/one.txt', '1'); disk.write(rootId, 'A/B/two.txt', '2'); } });
+ s.disk.moveUser('r1', 'A', 'Renamed');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['Renamed/', 'Renamed/B/', 'Renamed/B/two.txt', 'Renamed/one.txt']);
+ s.server.rename(s.server.find('Sync/Renamed')!.id, 'Back');
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['Back/', 'Back/B/', 'Back/B/two.txt', 'Back/one.txt']);
+ expect(s.disk.trashed).toEqual([]);
+ });
+
+ it('lets the place in Files win when both sides renamed the same file', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'doc.txt', 'd') });
+ s.disk.moveUser('r1', 'doc.txt', 'mine.txt');
+ s.server.rename(s.server.find('Sync/doc.txt')!.id, 'theirs.txt');
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['theirs.txt']);
+ expect(remoteUnder(s.server)).toEqual(['theirs.txt']);
+ });
+
+ it('does case-only renames both ways', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'readme.txt', 'r') });
+ s.disk.moveUser('r1', 'readme.txt', 'README.txt');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['README.txt']);
+ s.server.rename(s.server.find('Sync/README.txt')!.id, 'ReadMe.txt');
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['ReadMe.txt']);
+ expect(s.server.uploads.length).toBe(1);
+ });
+});
+
+describe('conflicts', () => {
+ it('keeps both versions when both sides changed a file', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'report.txt', 'v1') });
+ const id = s.server.find('Sync/report.txt')!.id;
+ s.disk.write('r1', 'report.txt', 'mine, longer');
+ s.server.edit(id, 'theirs');
+ await s.sync();
+ expect(s.disk.read('r1', 'report.txt')).toBe('theirs');
+ expect(s.server.content(id)).toBe('theirs');
+ const copy = s.disk.listing('r1').find((path) => path.startsWith('report (conflict, Laptop, '))!;
+ expect(copy).toMatch(/^report \(conflict, Laptop, \d{4}-\d\d-\d\d \d\d\.\d\d\)\.txt$/);
+ expect(s.disk.read('r1', copy)).toBe('mine, longer');
+ expect(s.server.content(s.server.find(`Sync/${copy}`)!.id)).toBe('mine, longer');
+ expect(s.engine.activity.some((entry) => entry.kind === 'conflict' && entry.detail === copy)).toBe(true);
+ });
+
+ it('brings back a file deleted here that was changed in Files', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'keep.txt', 'v1') });
+ const id = s.server.find('Sync/keep.txt')!.id;
+ s.disk.deleteUser('r1', 'keep.txt');
+ s.server.edit(id, 'edited elsewhere');
+ await s.sync();
+ expect(s.disk.read('r1', 'keep.txt')).toBe('edited elsewhere');
+ expect(s.server.find('Sync/keep.txt')!.id).toBe(id);
+ });
+
+ it('uploads again a file changed here that was deleted in Files', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'mine.txt', 'v1') });
+ s.server.destroyTree(s.server.find('Sync/mine.txt')!.id);
+ s.disk.write('r1', 'mine.txt', 'v2 here');
+ await s.sync();
+ expect(s.server.content(s.server.find('Sync/mine.txt')!.id)).toBe('v2 here');
+ expect(s.disk.read('r1', 'mine.txt')).toBe('v2 here');
+ });
+
+ it('keeps a folder deleted in Files when something new was put in it here', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'F/old.txt', 'old') });
+ s.server.destroyTree(s.server.find('Sync/F')!.id);
+ s.disk.write('r1', 'F/new.txt', 'new');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['F/', 'F/new.txt', 'F/old.txt']);
+ expect(s.disk.trashed).toEqual([]);
+ });
+});
+
+describe('deletes', () => {
+ it('puts a file deleted here into the Files trash', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { disk.write(rootId, 'gone.txt', 'g'); disk.write(rootId, 'stay.txt', 's'); } });
+ const id = s.server.find('Sync/gone.txt')!.id;
+ s.disk.deleteUser('r1', 'gone.txt');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['stay.txt']);
+ const trashed = s.server.listing(true).find((path) => path.endsWith('/gone.txt'))!;
+ expect(trashed).toMatch(new RegExp(`^\\.Trash/\\d+~${s.server.find('Sync')!.id}/gone\\.txt$`));
+ expect(s.server.nodes.has(id)).toBe(true);
+ expect(s.kinds()).toContain('trashed gone.txt');
+ });
+
+ it('puts a file deleted in Files into the computer trash', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { disk.write(rootId, 'x.txt', 'x'); disk.write(rootId, 'y.txt', 'y'); } });
+ s.server.destroyTree(s.server.find('Sync/x.txt')!.id);
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['y.txt']);
+ expect(s.disk.trashed).toEqual(['x.txt']);
+ });
+
+ function many(server: FakeServer, disk: FakeDisk, rootId: string): void {
+ void server;
+ for (let i = 0; i < 60; i += 1) disk.write(rootId, `bulk/f${i}.txt`, `file ${i}`);
+ disk.write(rootId, 'other.txt', 'o');
+ }
+
+ it('asks before many deletes made here, and brings them back on no', async () => {
+ const s = await setup({ seed: many });
+ s.disk.deleteUser('r1', 'bulk');
+ await s.sync();
+ expect(s.engine.status().r1).toMatchObject({ state: 'confirm-delete', massDelete: { count: 61, side: 'remote' } });
+ expect(remoteUnder(s.server)).toContain('bulk/f0.txt');
+ expect(s.kinds()).toContain('mass-delete (61)');
+ s.engine.confirmMassDelete('r1', false);
+ await s.engine.settled();
+ expect(s.disk.listing('r1').filter((path) => path.startsWith('bulk/')).length).toBe(61);
+ expect(s.engine.status().r1.state).toBe('idle');
+ });
+
+ it('deletes them on yes', async () => {
+ const s = await setup({ seed: many });
+ s.disk.deleteUser('r1', 'bulk');
+ await s.sync();
+ s.engine.confirmMassDelete('r1', true);
+ await s.engine.settled();
+ expect(remoteUnder(s.server)).toEqual(['other.txt']);
+ expect(s.server.listing(true).filter((path) => path.startsWith('.Trash/')).length).toBe(63);
+ });
+
+ it('asks before many deletes from Files, and uploads them again on no', async () => {
+ const s = await setup({ seed: many });
+ s.server.destroyTree(s.server.find('Sync/bulk')!.id);
+ await s.sync();
+ expect(s.engine.status().r1).toMatchObject({ state: 'confirm-delete', massDelete: { count: 61, side: 'local' } });
+ expect(s.disk.trashed).toEqual([]);
+ s.engine.confirmMassDelete('r1', false);
+ await s.engine.settled();
+ expect(remoteUnder(s.server).filter((path) => path.startsWith('bulk/')).length).toBe(61);
+ });
+
+ it('removes them here on yes', async () => {
+ const s = await setup({ seed: many });
+ s.server.destroyTree(s.server.find('Sync/bulk')!.id);
+ await s.sync();
+ s.engine.confirmMassDelete('r1', true);
+ await s.engine.settled();
+ expect(s.disk.listing('r1')).toEqual(['other.txt']);
+ expect(s.disk.trashed).toEqual(['bulk']);
+ });
+
+ it('asks when more than half of a root goes at once', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => { for (let i = 0; i < 12; i += 1) disk.write(rootId, `f${i}.txt`, `${i}`); } });
+ for (let i = 0; i < 7; i += 1) s.disk.deleteUser('r1', `f${i}.txt`);
+ await s.sync();
+ expect(s.engine.status().r1.state).toBe('confirm-delete');
+ });
+});
+
+describe('names the disk cannot hold', () => {
+ it('shows them under another name here and never renames them in Files', async () => {
+ const s = await setup({
+ seed: (server) => {
+ const sync = server.find('Sync')!;
+ server.file('a:b?.txt', sync.id, 'colon');
+ server.file('CON.txt', sync.id, 'device');
+ server.file('trail.', sync.id, 'dot');
+ server.file('Report.txt', sync.id, 'upper');
+ server.file('report.txt', sync.id, 'lower');
+ },
+ });
+ expect(s.disk.listing('r1')).toEqual(['CON_.txt', 'Report.txt', 'a:b?.txt', 'report (2).txt', 'trail._']);
+ expect(s.kinds()).toEqual(expect.arrayContaining(['renamed-for-disk a:b?.txt (a:b?.txt)', 'renamed-for-disk report (2).txt (report (2).txt)']));
+ const id = s.server.find('Sync/a:b?.txt')!.id;
+ // An edit here goes to the same node, under the name it has in Files.
+ s.disk.write('r1', 'a:b?.txt', 'edited');
+ s.disk.write('r1', 'report (2).txt', 'lower edited');
+ await s.sync();
+ expect(s.server.content(id)).toBe('edited');
+ expect(s.server.content(s.server.find('Sync/report.txt')!.id)).toBe('lower edited');
+ expect(remoteUnder(s.server)).toEqual(['CON.txt', 'Report.txt', 'a:b?.txt', 'report.txt', 'trail.']);
+ // Another pass changes nothing on either side.
+ const sets = s.server.sets.length;
+ await s.sync();
+ expect(s.server.sets.length).toBe(sets);
+ });
+
+ it('keeps the name in Files when the disk name is renamed back and forth', async () => {
+ const s = await setup({ seed: (server) => server.file('q?.txt', server.find('Sync')!.id, 'q') });
+ s.server.rename(s.server.find('Sync/q?.txt')!.id, 'r?.txt');
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['r?.txt']);
+ expect(remoteUnder(s.server)).toEqual(['r?.txt']);
+ });
+
+ it('leaves names alone on a disk that takes them', async () => {
+ const s = await setup({ platform: 'linux', seed: (server) => { server.file('a:b.txt', server.find('Sync')!.id, '1'); server.file('A:b.txt', server.find('Sync')!.id, '2'); } });
+ expect(s.disk.listing('r1')).toEqual(['A:b.txt', 'a:b.txt']);
+ });
+});
+
+describe('reading and uploading', () => {
+ it('carries on when a file is renamed while it uploads', async () => {
+ const s = await setup();
+ s.disk.write('r1', 'big.txt', 'content');
+ s.server.beforeRequest = () => {
+ if (s.server.uploads.length === 1 && s.disk.has('r1', 'big.txt')) s.disk.moveUser('r1', 'big.txt', 'renamed.txt');
+ };
+ await s.sync();
+ s.server.beforeRequest = null;
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['renamed.txt']);
+ expect(s.server.uploads.length).toBe(1);
+ expect(s.disk.listing('r1')).toEqual(['renamed.txt']);
+ });
+
+ it('does not upload a file that changed while it was read, and uploads it once it holds still', async () => {
+ const s = await setup();
+ s.disk.write('r1', 'live.log', 'first');
+ let writes = 0;
+ s.disk.onRead = (rootId, path) => {
+ if (writes < 1) {
+ writes += 1;
+ s.disk.write(rootId, path, 'first and more');
+ }
+ };
+ await s.sync();
+ expect(s.server.uploads).toEqual([14]);
+ expect(s.server.content(s.server.find('Sync/live.log')!.id)).toBe('first and more');
+ });
+
+ it('keeps a file over the upload limit here, says so once, and uploads it once it fits', async () => {
+ const s = await setup({ server: { maxSizeUpload: 10 } });
+ s.disk.write('r1', 'huge.bin', 'x'.repeat(20));
+ await s.sync();
+ await s.sync();
+ expect(s.server.uploads).toEqual([]);
+ expect(s.engine.activity.filter((entry) => entry.kind === 'too-large')).toEqual([expect.objectContaining({ path: 'huge.bin', detail: '10', messageKey: 'errors.too_large' })]);
+ s.disk.write('r1', 'huge.bin', 'small');
+ await s.sync();
+ expect(s.server.content(s.server.find('Sync/huge.bin')!.id)).toBe('small');
+ });
+
+ it('writes a downloaded file in pieces and leaves nothing half written', async () => {
+ const big = new Uint8Array(2_600_000).map((_, i) => i % 251);
+ const s = await setup({ seed: (server) => server.file('big.bin', server.find('Sync')!.id, big) });
+ const node = s.disk.node('r1', 'big.bin');
+ expect(node.data?.length).toBe(big.length);
+ expect(node.data?.[2_599_999]).toBe(2_599_999 % 251);
+ expect(s.disk.openWrites).toBe(0);
+ });
+});
+
+describe('offline', () => {
+ it('keeps the changes while the server is away and sends them when it is back', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'a.txt', 'v1') });
+ s.server.offline = true;
+ s.disk.write('r1', 'a.txt', 'v2');
+ s.disk.write('r1', 'b.txt', 'new');
+ await s.sync();
+ expect(s.engine.status().r1.state).toBe('offline');
+ expect(s.engine.activity[0]).toMatchObject({ kind: 'waiting', messageKey: 'errors.offline' });
+ await s.sync();
+ expect(s.engine.activity.filter((entry) => entry.kind === 'waiting')).toHaveLength(1);
+ s.server.offline = false;
+ s.engine.retryNow();
+ await s.engine.settled();
+ expect(s.engine.status().r1.state).toBe('idle');
+ expect(s.server.content(s.server.find('Sync/a.txt')!.id)).toBe('v2');
+ expect(s.server.content(s.server.find('Sync/b.txt')!.id)).toBe('new');
+ });
+
+ it('keeps the record when an upload breaks off, and finishes it later', async () => {
+ const s = await setup();
+ s.disk.write('r1', 'u.txt', 'up');
+ s.server.failUploads = 1;
+ await s.sync();
+ expect(s.engine.status().r1.state).toBe('offline');
+ s.engine.retryNow();
+ await s.engine.settled();
+ expect(remoteUnder(s.server)).toEqual(['u.txt']);
+ });
+});
+
+describe('changes in Files', () => {
+ it('reads FileNode/changes, and lists everything again only when the server cannot say', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'a.txt', 'a') });
+ const fullListings = () => s.server.calls.filter(([name, args]) => name === 'FileNode/get' && (args as { ids: unknown }).ids === null).length;
+ const before = fullListings();
+ s.server.file('b.txt', s.server.find('Sync')!.id, 'b');
+ s.engine.remoteChanged('a1');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await s.engine.settled();
+ expect(s.disk.read('r1', 'b.txt')).toBe('b');
+ expect(fullListings()).toBe(before);
+ s.server.file('c.txt', s.server.find('Sync')!.id, 'c');
+ s.server.account().coll.truncatedBelow = s.server.account().coll.log.length;
+ s.engine.remoteChanged('a1');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await s.engine.settled();
+ expect(s.disk.read('r1', 'c.txt')).toBe('c');
+ expect(fullListings()).toBe(before + 1);
+ });
+
+ it('ignores changes outside the pair', async () => {
+ const s = await setup();
+ const passes = s.server.calls.length;
+ s.server.file('elsewhere.txt', null, 'x');
+ s.engine.remoteChanged('a1');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await s.engine.settled();
+ // One /changes and one get of the new node, and no pass of the root.
+ expect(s.server.calls.length - passes).toBe(2);
+ });
+
+ it('says so when the paired folder is gone from Files, and deletes nothing', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'a.txt', 'a') });
+ s.server.destroyTree(s.server.find('Sync')!.id);
+ await s.sync();
+ expect(s.engine.status().r1).toMatchObject({ state: 'error', errorKey: 'errors.not_found' });
+ expect(s.disk.listing('r1')).toEqual(['a.txt']);
+ });
+});
+
+describe('pause', () => {
+ it('does nothing while paused and catches up on resume', async () => {
+ const s = await setup();
+ await s.engine.setPaused('r1', true);
+ s.disk.write('r1', 'while-paused.txt', 'p');
+ await s.sync();
+ expect(s.engine.status().r1.state).toBe('paused');
+ expect(remoteUnder(s.server)).toEqual([]);
+ await s.engine.setPaused('r1', false);
+ await s.engine.settled();
+ expect(remoteUnder(s.server)).toEqual(['while-paused.txt']);
+ });
+
+ it('runs nothing while the app is locked, and loses no record', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'a.txt', 'a') });
+ const record = s.disk.states.get('r1');
+ s.disk.locked = true;
+ await s.sync();
+ expect(s.disk.states.get('r1')).toBe(record);
+ s.disk.locked = false;
+ s.disk.emit('r1', null);
+ await s.engine.settled();
+ s.disk.write('r1', 'b.txt', 'b');
+ await s.sync();
+ expect(remoteUnder(s.server)).toEqual(['a.txt', 'b.txt']);
+ });
+});
+
+describe('the drive', () => {
+ async function drive(seed?: (server: FakeServer) => void) {
+ return setup({ drive: true, seed: (server) => seed?.(server) });
+ }
+
+ it('places every node of the account but the trash, and downloads nothing', async () => {
+ const s = await drive((server) => {
+ const docs = server.folder('Docs');
+ server.file('a.txt', docs.id, 'aaa');
+ server.file('top.txt', null, 'top');
+ const trash = server.folder('.Trash');
+ server.file('old.txt', trash.id, 'old');
+ });
+ expect(s.disk.listing('r1')).toEqual(['Docs/', 'Docs/a.txt', 'top.txt']);
+ expect(s.disk.node('r1', 'Docs/a.txt').placeholder).toMatchObject({ identity: s.server.find('Docs/a.txt')!.id, hydrated: false, inSync: true });
+ expect(s.server.downloads).toEqual([]);
+ expect(s.engine.items('a1')[s.server.find('Docs/a.txt')!.id]).toBe('online-only');
+ });
+
+ it('streams a file opened in Explorer from where Windows asked, to the end', async () => {
+ const content = new Uint8Array(3 * 1024 * 1024).map((_, i) => i % 199);
+ const s = await drive((server) => server.file('big.bin', null, content));
+ const request = s.disk.requestFetch('r1', 'big.bin', 10_000);
+ expect(request.offset).toBe(8192);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ const got = s.disk.suppliedBytes(request.fetchId);
+ expect(got.length).toBe(content.length - 8192);
+ expect(got[0]).toBe(content[8192]);
+ expect(got.at(-1)).toBe(content.at(-1));
+ expect(s.disk.fetchFailed.size).toBe(0);
+ });
+
+ it('stops streaming when the fetch is cancelled, and fails one it cannot answer', async () => {
+ const content = new Uint8Array(4 * 1024 * 1024);
+ const s = await drive((server) => { server.file('big.bin', null, content); server.file('gone.txt', null, 'g'); });
+ s.server.partBytes = 64 * 1024;
+ s.disk.refuseSupplyAfter = 1024 * 1024;
+ const request = s.disk.requestFetch('r1', 'big.bin');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(s.disk.suppliedBytes(request.fetchId).length).toBe(1024 * 1024);
+ // Cancelled while the download runs: the rest isn't fetched, and nothing is failed.
+ s.disk.refuseSupplyAfter = null;
+ let second = '';
+ let parts = 0;
+ s.server.onPart = () => {
+ parts += 1;
+ if (parts === 2) s.disk.cancelFetch(second);
+ };
+ second = s.disk.requestFetch('r1', 'big.bin').fetchId;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ s.server.onPart = null;
+ expect(parts).toBeLessThan(5);
+ expect(s.disk.suppliedBytes(second).length).toBeLessThan(content.length);
+ expect(s.disk.fetchFailed.has(second)).toBe(false);
+ // Deleted in Files meanwhile.
+ s.server.destroyTree(s.server.find('gone.txt')!.id);
+ const third = s.disk.requestFetch('r1', 'gone.txt');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(s.disk.fetchFailed.get(third.fetchId)).toBe('missing');
+ s.server.offline = true;
+ s.disk.supplied.clear();
+ });
+
+ it('updates a placeholder when the file changed in Files', async () => {
+ const s = await drive((server) => server.file('a.txt', null, 'v1'));
+ s.server.edit(s.server.find('a.txt')!.id, 'version two');
+ await s.sync();
+ expect(s.disk.driveCalls.filter((call) => call.call === 'update')).toEqual([{ call: 'update', args: ['r1', 'a.txt', true] }]);
+ expect(s.disk.node('r1', 'a.txt')).toMatchObject({ size: 11, placeholder: { hydrated: false, inSync: true } });
+ });
+
+ it('uploads a file made in Explorer and marks it in sync', async () => {
+ const s = await drive();
+ s.disk.write('r1', 'new.txt', 'from explorer');
+ await s.sync();
+ const node = s.server.find('new.txt')!;
+ expect(s.server.content(node.id)).toBe('from explorer');
+ expect(s.disk.node('r1', 'new.txt').placeholder).toMatchObject({ identity: node.id, inSync: true });
+ });
+
+ it('uploads a file made in Explorer inside a placed folder, next to a file opened there', async () => {
+ const s = await drive((server) => { const docs = server.folder('Docs'); server.file('seen.txt', docs.id, 'seen'); });
+ const request = s.disk.requestFetch('r1', 'Docs/seen.txt');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(s.disk.fetchFailed.has(request.fetchId)).toBe(false);
+ s.disk.write('r1', 'Docs/new.txt', 'from explorer');
+ await s.sync();
+ const node = s.server.find('Docs/new.txt');
+ expect(node && s.server.content(node.id)).toBe('from explorer');
+ });
+
+ it('takes a save over a placeholder as an edit here', async () => {
+ const s = await drive((server) => server.file('doc.txt', null, 'v1'));
+ const id = s.server.find('doc.txt')!.id;
+ s.disk.write('r1', 'doc.txt', 'saved over');
+ await s.sync();
+ expect(s.server.content(id)).toBe('saved over');
+ expect(s.disk.node('r1', 'doc.txt').placeholder).toMatchObject({ identity: id, inSync: true });
+ });
+
+ it('keeps both when a file edited here also changed in Files', async () => {
+ const s = await drive((server) => server.file('doc.txt', null, 'v1'));
+ const id = s.server.find('doc.txt')!.id;
+ s.disk.write('r1', 'doc.txt', 'here');
+ s.server.edit(id, 'there');
+ await s.sync();
+ const copy = s.disk.listing('r1').find((path) => path.includes('(conflict, Laptop,'))!;
+ expect(s.server.content(id)).toBe('there');
+ expect(s.disk.node('r1', 'doc.txt').placeholder).toMatchObject({ identity: id, hydrated: false });
+ expect(s.server.content(s.server.find(copy)!.id)).toBe('here');
+ });
+
+ it('finds a placeholder moved in Explorer by its identity', async () => {
+ const s = await drive((server) => { server.folder('A'); server.file('f.txt', null, 'f'); });
+ const id = s.server.find('f.txt')!.id;
+ s.disk.moveUser('r1', 'f.txt', 'A/g.txt');
+ await s.sync();
+ expect(s.server.find('A/g.txt')!.id).toBe(id);
+ expect(s.server.uploads).toEqual([]);
+ });
+
+ it('starts afresh when its folder came back empty', async () => {
+ const s = await drive((server) => server.file('a.txt', null, 'a'));
+ s.disk.trees.set('r1', new Map());
+ await s.sync();
+ expect(s.disk.listing('r1')).toEqual(['a.txt']);
+ expect(s.server.listing()).toEqual(['a.txt']);
+ });
+});
+
+describe('coverage', () => {
+ it('maps a node to its root and path', async () => {
+ const s = await setup({ seed: (server, disk, rootId) => disk.write(rootId, 'Docs/a.txt', 'a') });
+ const id = s.server.find('Sync/Docs/a.txt')!.id;
+ expect(s.engine.coverage('a1', id)).toEqual({ rootId: 'r1', kind: 'folder', path: 'Docs/a.txt' });
+ expect(s.engine.coverage('a1', s.server.find('Sync')!.id)).toEqual({ rootId: 'r1', kind: 'folder', path: '' });
+ expect(s.engine.coverage('a2', id)).toBeNull();
+ expect(s.engine.items('a1')[id]).toBe('synced');
+ });
+});
+
+void str;
+void text;
diff --git a/lib/files-sync/__tests__/helpers/fake-disk.ts b/lib/files-sync/__tests__/helpers/fake-disk.ts
new file mode 100644
index 000000000..23422e8ee
--- /dev/null
+++ b/lib/files-sync/__tests__/helpers/fake-disk.ts
@@ -0,0 +1,532 @@
+/**
+ * The desktop app's disk side of Files on this computer, in memory, answering as main does
+ * (desktop src/main/files/disk.ts, drive-controller.ts, features/files-folders.ts):
+ * - `expect` is checked on write, move and remove; null on a write means nothing may be there;
+ * - a move never overwrites, and a case-only rename works on a case-insensitive disk;
+ * - a folder root's remove goes to the trash, the drive's deletes;
+ * - `openRead` refuses folders and drive files whose content isn't here;
+ * - while locked, `roots()` is empty, everything else `inactive`, and the state calls reject;
+ * - the drive: placeholders with an identity, `update` refused with `changed` once someone wrote
+ * over one, `markInSync` making a file a placeholder again, fetches answered by `supply`.
+ */
+
+import type {
+ FilesChangeEvent,
+ FilesControls,
+ FilesDriveControls,
+ FilesDriveState,
+ FilesExpect,
+ FilesFetchRequest,
+ FilesLocalEntry,
+ FilesPlaceholder,
+ FilesPlaceholderState,
+ FilesResult,
+ FilesRoot,
+} from '@/lib/desktop/types';
+
+interface DiskNode {
+ kind: 'file' | 'directory';
+ data: Uint8Array | null;
+ /** For a dehydrated placeholder, its size. */
+ size: number;
+ fileId: string;
+ mtimeMs: number;
+ placeholder?: FilesPlaceholderState;
+}
+
+const ok = (value: T): FilesResult => ({ ok: true, value });
+const fail = (error: Parameters[0]): FilesResult => failOf(error) as FilesResult;
+function failOf(error: Exclude, { ok: true }>['error']) {
+ return { ok: false as const, error };
+}
+
+export const text = (value: string) => new TextEncoder().encode(value);
+export const str = (value: Uint8Array | null | undefined) => (value ? new TextDecoder().decode(value) : '');
+
+let fileIds = 1;
+
+export interface FakeDiskOptions {
+ caseInsensitive?: boolean;
+ drive?: boolean;
+}
+
+export class FakeDisk implements FilesControls {
+ readonly rootsList: FilesRoot[] = [];
+ readonly trees = new Map>();
+ readonly states = new Map();
+ readonly trashed: string[] = [];
+ readonly shown: { rootId: string; path: string }[] = [];
+ readonly calls: string[] = [];
+ locked = false;
+ clock = Date.UTC(2026, 10, 1);
+ private readonly listeners = new Set<(event: FilesChangeEvent) => void>();
+ private readonly fetchListeners = new Set<(request: FilesFetchRequest) => void>();
+ private readonly cancelListeners = new Set<(fetchId: string) => void>();
+ private readonly reads = new Map();
+ private readonly writes = new Map();
+ /** Called when a read URL is fetched, before the bytes go: to change the file meanwhile. */
+ onRead: ((rootId: string, path: string) => void) | null = null;
+ /** Bytes supplied per fetch. */
+ readonly supplied = new Map();
+ readonly fetchFailed = new Map();
+ /** Supply answers false from this many bytes on (Windows no longer wants them). */
+ refuseSupplyAfter: number | null = null;
+ readonly driveCalls: { call: string; args: unknown[] }[] = [];
+ driveWanted: string[] = [];
+ readonly drive?: FilesDriveControls;
+ private nextWrite = 1;
+
+ constructor(private readonly options: FakeDiskOptions = {}) {
+ if (options.drive) this.drive = this.makeDrive();
+ }
+
+ // ─── Test setup and what a user does ────────────────────────
+
+ addRoot(root: Partial & { id: string; account: string }): FilesRoot {
+ const full: FilesRoot = { kind: 'folder', path: `C:\\sync\\${root.id}`, remoteId: null, remoteLabel: '', paused: false, createdAt: 1, ...root };
+ this.rootsList.push(full);
+ this.trees.set(full.id, new Map());
+ return full;
+ }
+
+ private tree(rootId: string): Map {
+ const tree = this.trees.get(rootId);
+ if (!tree) throw new Error(`no root ${rootId}`);
+ return tree;
+ }
+
+ private key(path: string): string {
+ return this.options.caseInsensitive ? path.toLowerCase() : path;
+ }
+
+ /** The stored path for `path`, as cased on disk. */
+ private find(rootId: string, path: string): string | null {
+ const tree = this.tree(rootId);
+ if (tree.has(path)) return path;
+ if (!this.options.caseInsensitive) return null;
+ const wanted = this.key(path);
+ for (const stored of tree.keys()) if (this.key(stored) === wanted) return stored;
+ return null;
+ }
+
+ private tick(): number {
+ this.clock += 1000;
+ return this.clock;
+ }
+
+ private parentOk(rootId: string, path: string): boolean {
+ const slash = path.lastIndexOf('/');
+ if (slash < 0) return true;
+ const parent = this.find(rootId, path.slice(0, slash));
+ return !!parent && this.tree(rootId).get(parent)?.kind === 'directory';
+ }
+
+ /** A user writes a file: a new one, or over the old one in place (same file id). */
+ write(rootId: string, path: string, content: string | Uint8Array): void {
+ const data = typeof content === 'string' ? text(content) : content;
+ this.ensureParents(rootId, path);
+ const tree = this.tree(rootId);
+ const stored = this.find(rootId, path);
+ const old = stored ? tree.get(stored) : undefined;
+ const node: DiskNode = { kind: 'file', data, size: data.length, fileId: old?.fileId ?? `f${fileIds++}`, mtimeMs: this.tick() };
+ if (old?.placeholder) {
+ // Saved over with a plain write: no longer a placeholder.
+ node.placeholder = { identity: null, inSync: false, hydrated: true, pin: 'unspecified' };
+ } else if (this.isDrive(rootId)) {
+ node.placeholder = { identity: null, inSync: false, hydrated: true, pin: 'unspecified' };
+ }
+ tree.set(stored ?? path, node);
+ }
+
+ /** An app that keeps the placeholder edits a hydrated drive file: no longer in sync. */
+ editInPlace(rootId: string, path: string, content: string): void {
+ const node = this.node(rootId, path);
+ node.data = text(content);
+ node.size = node.data.length;
+ node.mtimeMs = this.tick();
+ if (node.placeholder) node.placeholder = { ...node.placeholder, inSync: false, hydrated: true };
+ }
+
+ mkdirUser(rootId: string, path: string): void {
+ this.ensureParents(rootId, `${path}/x`);
+ }
+
+ private ensureParents(rootId: string, path: string): void {
+ const parts = path.split('/');
+ const tree = this.tree(rootId);
+ for (let i = 1; i < parts.length; i += 1) {
+ const dir = parts.slice(0, i).join('/');
+ if (!this.find(rootId, dir)) {
+ tree.set(dir, {
+ kind: 'directory', data: null, size: 0, fileId: `f${fileIds++}`, mtimeMs: this.tick(),
+ ...(this.isDrive(rootId) ? { placeholder: { identity: null, inSync: false, hydrated: true, pin: 'unspecified' as const } } : {}),
+ });
+ }
+ }
+ }
+
+ moveUser(rootId: string, from: string, to: string): void {
+ const result = this.moveTree(rootId, from, to);
+ if (!result) throw new Error(`move ${from} -> ${to} failed`);
+ }
+
+ deleteUser(rootId: string, path: string): void {
+ const tree = this.tree(rootId);
+ const stored = this.find(rootId, path) ?? path;
+ for (const key of [...tree.keys()]) if (key === stored || key.startsWith(`${stored}/`)) tree.delete(key);
+ }
+
+ node(rootId: string, path: string): DiskNode {
+ const stored = this.find(rootId, path);
+ const node = stored ? this.tree(rootId).get(stored) : undefined;
+ if (!node) throw new Error(`nothing at ${path}`);
+ return node;
+ }
+
+ has(rootId: string, path: string): boolean {
+ return this.find(rootId, path) === path;
+ }
+
+ read(rootId: string, path: string): string {
+ return str(this.node(rootId, path).data);
+ }
+
+ /** Every path in a root, sorted, folders with a trailing slash. */
+ listing(rootId: string): string[] {
+ return [...this.tree(rootId)].map(([path, node]) => (node.kind === 'directory' ? `${path}/` : path)).sort();
+ }
+
+ emit(rootId: string, paths: string[] | null = null): void {
+ for (const listener of [...this.listeners]) listener({ rootId, paths });
+ }
+
+ private isDrive(rootId: string): boolean {
+ return this.rootsList.find((root) => root.id === rootId)?.kind === 'drive';
+ }
+
+ private active(rootId: string): boolean {
+ const root = this.rootsList.find((entry) => entry.id === rootId);
+ return !this.locked && !!root && !root.paused;
+ }
+
+ private entry(path: string, node: DiskNode): FilesLocalEntry {
+ return {
+ path,
+ kind: node.kind,
+ size: node.kind === 'directory' ? 0 : node.size,
+ mtimeMs: node.mtimeMs,
+ fileId: node.fileId,
+ ...(node.placeholder ? { placeholder: { ...node.placeholder } } : {}),
+ };
+ }
+
+ private matches(node: DiskNode | undefined, expect: FilesExpect | null): boolean {
+ if (expect === null) return !node;
+ if (!node) return false;
+ return node.fileId === expect.fileId && (node.kind === 'directory' ? 0 : node.size) === expect.size && node.mtimeMs === expect.mtimeMs;
+ }
+
+ private moveTree(rootId: string, from: string, to: string): DiskNode | null {
+ const tree = this.tree(rootId);
+ const source = this.find(rootId, from);
+ if (!source) return null;
+ const target = this.find(rootId, to);
+ if (target && this.key(target) !== this.key(source)) return null;
+ if (!this.parentOk(rootId, to)) return null;
+ const moving = [...tree].filter(([key]) => key === source || key.startsWith(`${source}/`));
+ for (const [key] of moving) tree.delete(key);
+ for (const [key, node] of moving) tree.set(to + key.slice(source.length), node);
+ return tree.get(to) ?? null;
+ }
+
+ // ─── FilesControls ──────────────────────────────────────────
+
+ async roots(): Promise {
+ return this.locked ? [] : this.rootsList.map((root) => ({ ...root }));
+ }
+
+ async addFolder(request: { account: string; remoteId: string | null; remoteLabel: string }): Promise> {
+ this.calls.push(`addFolder ${request.account} ${request.remoteId}`);
+ const root = this.addRoot({ id: `r${this.rootsList.length + 1}`, account: request.account, remoteId: request.remoteId, remoteLabel: request.remoteLabel });
+ return ok(root);
+ }
+
+ async removeRoot(rootId: string): Promise {
+ this.calls.push(`removeRoot ${rootId}`);
+ const at = this.rootsList.findIndex((root) => root.id === rootId);
+ if (at >= 0) this.rootsList.splice(at, 1);
+ }
+
+ async setPaused(rootId: string, paused: boolean): Promise {
+ const root = this.rootsList.find((entry) => entry.id === rootId);
+ if (root) root.paused = paused;
+ if (!paused) this.emit(rootId, null);
+ }
+
+ async scan(rootId: string): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ return ok([...this.tree(rootId)].map(([path, node]) => this.entry(path, node)));
+ }
+
+ async stat(rootId: string, path: string): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ const stored = this.find(rootId, path);
+ return ok(stored ? this.entry(stored, this.tree(rootId).get(stored) as DiskNode) : null);
+ }
+
+ async openRead(rootId: string, path: string): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ const stored = this.find(rootId, path);
+ const node = stored ? this.tree(rootId).get(stored) : undefined;
+ if (!node) return fail('missing');
+ if (node.kind !== 'file' || !node.data || (node.placeholder && !node.placeholder.hydrated)) return fail('unsupported');
+ const token = `mem://${this.reads.size + 1}-${Math.random().toString(36).slice(2)}`;
+ this.reads.set(token, { rootId, path: stored as string });
+ return ok({ url: token, entry: this.entry(stored as string, node) });
+ }
+
+ /** What the page's fetch of a read URL gets. */
+ readUrl = async (url: string): Promise => {
+ const grant = this.reads.get(url);
+ this.reads.delete(url);
+ if (!grant) throw new Error('404');
+ const node = this.node(grant.rootId, grant.path);
+ const data = node.data as Uint8Array;
+ this.onRead?.(grant.rootId, grant.path);
+ return data;
+ };
+
+ async beginWrite(rootId: string, path: string, options: { expect: FilesExpect | null; mtimeMs: number; size: number }): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ if (!this.parentOk(rootId, path)) return fail('missing');
+ const stored = this.find(rootId, path);
+ const node = stored ? this.tree(rootId).get(stored) : undefined;
+ if (node?.kind === 'directory') return fail('exists');
+ if (!this.matches(node, options.expect)) return fail(options.expect ? 'changed' : 'exists');
+ const id = `w${this.nextWrite++}`;
+ this.writes.set(id, { rootId, path, expect: options.expect, mtimeMs: options.mtimeMs, size: options.size, parts: [] });
+ return ok(id);
+ }
+
+ async writeChunk(writeId: string, data: Uint8Array): Promise> {
+ const write = this.writes.get(writeId);
+ if (!write) return fail('missing');
+ write.parts.push(new Uint8Array(data));
+ return ok(null);
+ }
+
+ async commitWrite(writeId: string): Promise> {
+ const write = this.writes.get(writeId);
+ this.writes.delete(writeId);
+ if (!write) return fail('missing');
+ if (!this.active(write.rootId)) return fail('inactive');
+ const size = write.parts.reduce((sum, part) => sum + part.length, 0);
+ if (size !== write.size) return fail('failed');
+ const stored = this.find(write.rootId, write.path);
+ const tree = this.tree(write.rootId);
+ const old = stored ? tree.get(stored) : undefined;
+ if (!this.matches(old, write.expect)) return fail(write.expect ? 'changed' : 'exists');
+ const data = new Uint8Array(size);
+ let at = 0;
+ for (const part of write.parts) {
+ data.set(part, at);
+ at += part.length;
+ }
+ const node: DiskNode = { kind: 'file', data, size, fileId: `f${fileIds++}`, mtimeMs: write.mtimeMs };
+ tree.set(stored ?? write.path, node);
+ return ok(this.entry(stored ?? write.path, node));
+ }
+
+ async abortWrite(writeId: string): Promise {
+ this.writes.delete(writeId);
+ }
+
+ get openWrites(): number {
+ return this.writes.size;
+ }
+
+ async mkdir(rootId: string, path: string): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ if (!this.parentOk(rootId, path)) return fail('missing');
+ const stored = this.find(rootId, path);
+ const tree = this.tree(rootId);
+ if (stored) {
+ const node = tree.get(stored) as DiskNode;
+ return node.kind === 'directory' ? ok(this.entry(stored, node)) : fail('exists');
+ }
+ const node: DiskNode = { kind: 'directory', data: null, size: 0, fileId: `f${fileIds++}`, mtimeMs: this.tick() };
+ tree.set(path, node);
+ return ok(this.entry(path, node));
+ }
+
+ async move(rootId: string, from: string, to: string, expect: FilesExpect | null): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ const source = this.find(rootId, from);
+ if (!source) return fail('missing');
+ const node = this.tree(rootId).get(source) as DiskNode;
+ if (expect && !this.matches(node, expect)) return fail('changed');
+ const target = this.find(rootId, to);
+ if (target && this.key(target) !== this.key(source)) return fail('exists');
+ if (!this.parentOk(rootId, to)) return fail('missing');
+ const moved = this.moveTree(rootId, source, to);
+ return moved ? ok(this.entry(to, moved)) : fail('failed');
+ }
+
+ async remove(rootId: string, path: string, expect: FilesExpect | null): Promise> {
+ if (!this.active(rootId)) return fail('inactive');
+ const stored = this.find(rootId, path);
+ if (!stored) return fail('missing');
+ const node = this.tree(rootId).get(stored) as DiskNode;
+ if (expect && !this.matches(node, expect)) return fail('changed');
+ this.deleteUser(rootId, stored);
+ this.trashed.push(stored);
+ return ok(this.isDrive(rootId) ? 'deleted' : 'trash');
+ }
+
+ onChange(listener: (event: FilesChangeEvent) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ async loadState(rootId: string): Promise {
+ if (this.locked) throw new Error('Locked');
+ return this.states.get(rootId) ?? null;
+ }
+
+ async saveState(rootId: string, state: string): Promise {
+ if (this.locked) throw new Error('Locked');
+ if (!this.rootsList.some((root) => root.id === rootId)) throw new Error('No such root');
+ this.states.set(rootId, state);
+ }
+
+ async showInFolder(rootId: string, path: string): Promise {
+ this.shown.push({ rootId, path });
+ return true;
+ }
+
+ // ─── The drive ──────────────────────────────────────────────
+
+ /** Windows asks for a file someone opened. */
+ requestFetch(rootId: string, path: string, offset = 0): FilesFetchRequest {
+ const node = this.node(rootId, path);
+ const fetchId = `fetch${this.supplied.size + this.fetchFailed.size + 1}-${Math.random().toString(36).slice(2, 6)}`;
+ const start = Math.floor(offset / 4096) * 4096;
+ const request: FilesFetchRequest = { fetchId, rootId, identity: node.placeholder?.identity ?? '', path, offset: start, length: node.size - start, total: node.size };
+ this.supplied.set(fetchId, { offset: start, length: 0, parts: [] });
+ for (const listener of [...this.fetchListeners]) listener(request);
+ return request;
+ }
+
+ /** Everything supplied for a fetch, in one piece. */
+ suppliedBytes(fetchId: string): Uint8Array {
+ const got = this.supplied.get(fetchId);
+ const out = new Uint8Array(got?.length ?? 0);
+ let at = 0;
+ for (const part of got?.parts ?? []) {
+ out.set(part, at);
+ at += part.length;
+ }
+ return out;
+ }
+
+ cancelFetch(fetchId: string): void {
+ for (const listener of [...this.cancelListeners]) listener(fetchId);
+ }
+
+ private makeDrive(): FilesDriveControls {
+ // The bridge hands these out as plain functions, as the preload does.
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ const disk = this;
+ const record = (call: string, ...args: unknown[]) => disk.driveCalls.push({ call, args });
+ const state = (): FilesDriveState => ({ supported: true, forcedOff: false, wanted: [...disk.driveWanted], letter: { letter: null, chosen: null, locked: false, available: ['E'] } });
+ return {
+ state: async () => state(),
+ onStateChange: () => () => {},
+ enable: async (account, label) => {
+ record('enable', account, label);
+ if (!disk.driveWanted.includes(account)) disk.driveWanted.push(account);
+ const existing = disk.rootsList.find((root) => root.kind === 'drive' && root.account === account);
+ return ok(existing ?? disk.addRoot({ id: `drive-${account}`, account, kind: 'drive', remoteId: null, remoteLabel: label }));
+ },
+ disable: async (account, reason) => {
+ record('disable', account, reason);
+ if (reason !== 'signed-out') disk.driveWanted = disk.driveWanted.filter((entry) => entry !== account);
+ const at = disk.rootsList.findIndex((root) => root.kind === 'drive' && root.account === account);
+ if (at >= 0) {
+ const [root] = disk.rootsList.splice(at, 1);
+ disk.trees.set(root.id, new Map());
+ }
+ },
+ place: async (rootId, entries: FilesPlaceholder[]) => {
+ record('place', rootId, entries.length);
+ if (!disk.active(rootId)) return fail('inactive');
+ const tree = disk.tree(rootId);
+ const answers = entries.map((entry) => {
+ if (!disk.parentOk(rootId, entry.path)) return { path: entry.path, error: 'missing' as const };
+ if (disk.find(rootId, entry.path)) return { path: entry.path, error: 'exists' as const };
+ tree.set(entry.path, {
+ kind: entry.kind,
+ data: null,
+ size: entry.kind === 'file' ? entry.size : 0,
+ fileId: `f${fileIds++}`,
+ mtimeMs: entry.mtimeMs,
+ placeholder: { identity: entry.identity, inSync: true, hydrated: entry.kind === 'directory', pin: 'unspecified' },
+ });
+ return { path: entry.path };
+ });
+ return ok(answers);
+ },
+ update: async (rootId, path, meta, expect) => {
+ record('update', rootId, path, meta.dehydrate);
+ if (!disk.active(rootId)) return fail('inactive');
+ const stored = disk.find(rootId, path);
+ const node = stored ? disk.tree(rootId).get(stored) : undefined;
+ if (!node) return fail('missing');
+ if (expect && !disk.matches(node, expect)) return fail('changed');
+ if (!node.placeholder?.identity || !node.placeholder.inSync) return fail('changed');
+ node.size = meta.size;
+ node.mtimeMs = meta.mtimeMs;
+ node.placeholder = { ...node.placeholder, identity: meta.identity, inSync: true };
+ if (meta.dehydrate) {
+ node.data = null;
+ node.placeholder.hydrated = false;
+ }
+ return ok(disk.entry(stored as string, node));
+ },
+ markInSync: async (rootId, path, identity, expect) => {
+ record('markInSync', rootId, path, identity);
+ if (!disk.active(rootId)) return fail('inactive');
+ const stored = disk.find(rootId, path);
+ const node = stored ? disk.tree(rootId).get(stored) : undefined;
+ if (!node) return fail('missing');
+ if (!disk.matches(node, expect)) return fail('changed');
+ node.placeholder = { identity, inSync: true, hydrated: true, pin: node.placeholder?.pin ?? 'unspecified' };
+ return ok(disk.entry(stored as string, node));
+ },
+ onFetch: (listener) => {
+ disk.fetchListeners.add(listener);
+ return () => disk.fetchListeners.delete(listener);
+ },
+ onFetchCancel: (listener) => {
+ disk.cancelListeners.add(listener);
+ return () => disk.cancelListeners.delete(listener);
+ },
+ supply: async (fetchId, offset, data) => {
+ const got = disk.supplied.get(fetchId);
+ if (!got) return false;
+ if (offset !== got.offset + got.length) return false;
+ if (disk.refuseSupplyAfter !== null && got.length >= disk.refuseSupplyAfter) return false;
+ got.parts.push(new Uint8Array(data));
+ got.length += data.length;
+ return true;
+ },
+ fail: (fetchId, error) => {
+ disk.fetchFailed.set(fetchId, error);
+ },
+ setLetter: async (letter) => {
+ record('setLetter', letter);
+ return ok({ letter, chosen: letter, locked: false, available: ['E'] });
+ },
+ };
+ }
+}
diff --git a/lib/files-sync/__tests__/helpers/fake-server.ts b/lib/files-sync/__tests__/helpers/fake-server.ts
new file mode 100644
index 000000000..e03340285
--- /dev/null
+++ b/lib/files-sync/__tests__/helpers/fake-server.ts
@@ -0,0 +1,247 @@
+/**
+ * Files on a fake server for the engine: lib/store's FakeFiles (FileNode/get, query and changes
+ * as both Stalwarts answer them) with FileNode/set and uploads added, as Stalwart does them:
+ * - a folder is a node without blobId; a node can only go under a folder;
+ * - two siblings with the same name are refused (`alreadyExists`);
+ * - a destroy with onDestroyRemoveChildren takes the subtree;
+ * - an upload over maxSizeUpload is an HTTP 413;
+ * - the session's filenode capability names forbidden characters (0.16.6+ style).
+ */
+
+import { TransportError, type StoreSession } from '@/lib/store/engine/transport';
+import { FakeFiles, FILES, FILES_SESSION, type FakeFilesOptions, type FakeNode } from '@/lib/store/__tests__/helpers/fake-files';
+import { JMAP_ACCOUNT } from '@/lib/store/__tests__/helpers/fake-jmap';
+import { FilesRemote } from '../../remote';
+
+export { JMAP_ACCOUNT };
+
+export interface FakeServerOptions extends FakeFilesOptions {
+ maxSizeUpload?: number;
+ forbiddenNameChars?: string;
+}
+
+export class FakeServer extends FakeFiles {
+ readonly session: StoreSession;
+ readonly sets: Record[] = [];
+ readonly uploads: number[] = [];
+ /** Fails the next N uploads like a network drop. */
+ failUploads = 0;
+ private serverClock = Date.UTC(2026, 9, 1);
+ private nextNodeId = 1000;
+ private nextBlob = 1;
+
+ constructor(options: FakeServerOptions = {}) {
+ super(options);
+ this.session = {
+ ...FILES_SESSION,
+ capabilities: {
+ ...FILES_SESSION.capabilities,
+ 'urn:ietf:params:jmap:core': { maxSizeUpload: options.maxSizeUpload ?? 50_000_000, maxObjectsInGet: 500, maxObjectsInSet: 500, maxCallsInRequest: 16 },
+ },
+ accounts: {
+ ...FILES_SESSION.accounts,
+ [JMAP_ACCOUNT]: {
+ ...FILES_SESSION.accounts[JMAP_ACCOUNT],
+ accountCapabilities: { [FILES]: { forbiddenNameChars: options.forbiddenNameChars ?? '/', forbiddenNodeNames: ['.', '..'], maxSizeFileNodeName: 255 } },
+ },
+ },
+ };
+ }
+
+ remote(): FilesRemote {
+ return new FilesRemote(this, () => this.session);
+ }
+
+ private stamp(): string {
+ this.serverClock += 1000;
+ return new Date(this.serverClock).toISOString();
+ }
+
+ get nodes(): Map {
+ return this.account().nodes;
+ }
+
+ /** What another device does in Files. */
+ folder(name: string, parentId: string | null = null): FakeNode {
+ const node = this.addFolder(name, parentId, `n${this.nextNodeId++}`);
+ node.modified = this.stamp();
+ return node;
+ }
+
+ file(name: string, parentId: string | null, content: string | Uint8Array): FakeNode {
+ const data = typeof content === 'string' ? new TextEncoder().encode(content) : content;
+ const node = this.addFile(name, parentId, data, { id: `n${this.nextNodeId++}`, blobId: `b${this.nextBlob++}`, modified: this.stamp() });
+ return node;
+ }
+
+ edit(id: string, content: string): void {
+ const data = new TextEncoder().encode(content);
+ const blobId = `b${this.nextBlob++}`;
+ this.blobs.set(blobId, data);
+ const node = this.nodes.get(id) as FakeNode;
+ node.blobId = blobId;
+ node.size = data.length;
+ node.modified = this.stamp();
+ this.account().coll.push('updated', id);
+ }
+
+ rename(id: string, name: string, parentId?: string | null): void {
+ const node = this.nodes.get(id) as FakeNode;
+ node.name = name;
+ if (parentId !== undefined) node.parentId = parentId;
+ this.account().coll.push('updated', id);
+ }
+
+ destroyTree(id: string): void {
+ for (const child of [...this.nodes.values()].filter((node) => node.parentId === id)) this.destroyTree(child.id);
+ this.removeNode(id);
+ }
+
+ /** The content of a node, as text. */
+ content(id: string): string {
+ const node = this.nodes.get(id);
+ return node?.blobId ? new TextDecoder().decode(this.blobs.get(node.blobId)) : '';
+ }
+
+ /** Path from the top to each node, sorted, folders with a slash. Without the trash unless asked. */
+ listing(withTrash = false): string[] {
+ const out: string[] = [];
+ const pathOf = (node: FakeNode): string | null => {
+ const parts = [node.name];
+ let parent = node.parentId;
+ while (parent) {
+ const up = this.nodes.get(parent);
+ if (!up) return null;
+ parts.unshift(up.name);
+ parent = up.parentId;
+ }
+ return parts.join('/');
+ };
+ for (const node of this.nodes.values()) {
+ const path = pathOf(node);
+ if (path === null) continue;
+ if (!withTrash && (path === '.Trash' || path.startsWith('.Trash/'))) continue;
+ out.push(node.blobId === null ? `${path}/` : path);
+ }
+ return out.sort();
+ }
+
+ find(path: string): FakeNode | undefined {
+ const parts = path.split('/');
+ let parent: string | null = null;
+ let found: FakeNode | undefined;
+ for (const part of parts) {
+ found = [...this.nodes.values()].find((node) => node.parentId === parent && node.name === part);
+ if (!found) return undefined;
+ parent = found.id;
+ }
+ return found;
+ }
+
+ override async upload(_jmap?: string, data?: Uint8Array, type?: string): Promise<{ blobId: string; type: string; size: number }> {
+ if (this.offline) throw new TransportError('network', 'Failed to fetch');
+ if (this.failUploads > 0) {
+ this.failUploads -= 1;
+ throw new TransportError('network', 'Connection reset');
+ }
+ const bytes = data ?? new Uint8Array();
+ const max = (this.session.capabilities['urn:ietf:params:jmap:core'] as { maxSizeUpload: number }).maxSizeUpload;
+ if (bytes.length > max) throw new TransportError('http', 'Upload failed: 413', 413);
+ const blobId = `up${this.nextBlob++}`;
+ this.blobs.set(blobId, new Uint8Array(bytes));
+ this.uploads.push(bytes.length);
+ return { blobId, type: type ?? 'application/octet-stream', size: bytes.length };
+ }
+
+ protected override handle(name: string, args: Record): Record {
+ if (name !== 'FileNode/set') return super.handle(name, args);
+ this.sets.push(args);
+ const account = this.account(String(args.accountId));
+ const nodes = account.nodes;
+ const forbidden = String(((this.session.accounts[JMAP_ACCOUNT].accountCapabilities as Record>)[FILES]).forbiddenNameChars ?? '');
+ const clash = (parentId: string | null, nodeName: string, except?: string) =>
+ [...nodes.values()].some((node) => node.parentId === parentId && node.name === nodeName && node.id !== except);
+ const isFolder = (id: string | null) => id === null || nodes.get(id)?.blobId === null;
+ const created: Record = {};
+ const notCreated: Record = {};
+ for (const [key, raw] of Object.entries((args.create ?? {}) as Record>)) {
+ const parentId = (raw.parentId as string | undefined) ?? null;
+ const nodeName = String(raw.name ?? '');
+ if (!nodeName || [...nodeName].some((ch) => forbidden.includes(ch))) {
+ notCreated[key] = { type: 'invalidProperties', description: 'Name contains a forbidden character.' };
+ continue;
+ }
+ if (parentId !== null && !nodes.has(parentId)) {
+ notCreated[key] = { type: 'invalidProperties', description: 'Parent ID does not exist or is not a folder.' };
+ continue;
+ }
+ if (!isFolder(parentId)) {
+ notCreated[key] = { type: 'invalidProperties', description: 'Parent ID does not exist or is not a folder.' };
+ continue;
+ }
+ if (clash(parentId, nodeName)) {
+ notCreated[key] = { type: 'alreadyExists', description: 'A node with the same name already exists.' };
+ continue;
+ }
+ const id = `n${this.nextNodeId++}`;
+ const blobId = (raw.blobId as string | undefined) ?? null;
+ const type = (raw.type as string | undefined) ?? (raw.mediaType as string | undefined) ?? null;
+ const node: FakeNode = { id, parentId, name: nodeName, blobId, type: blobId ? type : null, size: blobId ? (this.blobs.get(blobId)?.length ?? 0) : null, modified: this.stamp() };
+ nodes.set(id, node);
+ account.coll.push('created', id);
+ created[key] = { id };
+ }
+ const updated: Record = {};
+ const notUpdated: Record = {};
+ for (const [id, patch] of Object.entries((args.update ?? {}) as Record>)) {
+ const node = nodes.get(id);
+ if (!node) {
+ notUpdated[id] = { type: 'notFound' };
+ continue;
+ }
+ const parentId = 'parentId' in patch ? ((patch.parentId as string | null) ?? null) : node.parentId;
+ const nodeName = 'name' in patch ? String(patch.name) : node.name;
+ if ('parentId' in patch && !isFolder(parentId)) {
+ notUpdated[id] = { type: 'invalidProperties', description: 'Parent ID does not exist or is not a folder.' };
+ continue;
+ }
+ if (clash(parentId, nodeName, id)) {
+ notUpdated[id] = { type: 'alreadyExists' };
+ continue;
+ }
+ node.parentId = parentId;
+ node.name = nodeName;
+ if ('blobId' in patch) {
+ node.blobId = patch.blobId as string;
+ node.size = this.blobs.get(node.blobId)?.length ?? 0;
+ }
+ node.modified = this.stamp();
+ account.coll.push('updated', id);
+ updated[id] = null;
+ }
+ const destroyed: string[] = [];
+ const notDestroyed: Record = {};
+ for (const id of (args.destroy ?? []) as string[]) {
+ if (!nodes.has(id)) {
+ notDestroyed[id] = { type: 'notFound' };
+ continue;
+ }
+ if (!args.onDestroyRemoveChildren && [...nodes.values()].some((node) => node.parentId === id)) {
+ notDestroyed[id] = { type: 'nodeHasChildren' };
+ continue;
+ }
+ this.destroyTree(id);
+ destroyed.push(id);
+ }
+ return {
+ accountId: args.accountId,
+ newState: account.coll.state(),
+ created,
+ notCreated,
+ updated,
+ notUpdated,
+ destroyed,
+ notDestroyed,
+ };
+ }
+}
diff --git a/lib/files-sync/__tests__/host.test.ts b/lib/files-sync/__tests__/host.test.ts
new file mode 100644
index 000000000..d37b77657
--- /dev/null
+++ b/lib/files-sync/__tests__/host.test.ts
@@ -0,0 +1,225 @@
+/**
+ * The host of Files on this computer: claiming the bridge once, the accounts it runs for, what
+ * it publishes, the controller, and what sign-out, a wipe and a refused login do.
+ */
+import { render } from '@testing-library/react';
+import { createElement } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { FilesControls } from '@/lib/desktop/types';
+import { WindowControlsHost } from '@/components/layout/window-controls-host';
+import { noteCredentialsRejected } from '@/lib/offline/credentials-rejected';
+import { runWipeCleaners } from '@/lib/offline/wipe-registry';
+import { runBeforeSignOut } from '@/lib/sign-out-cleanup';
+import type { FilesSyncController, FilesSyncSnapshot } from '../types';
+import { claimFilesControls, resetFilesControlsForTests } from '../controls';
+import { FilesSyncHost, type HostAccount } from '../host';
+import { registerFilesSyncLifecycle, resetFilesSyncLifecycleForTests, setRunningFilesSyncHost } from '../lifecycle';
+import { FakeDisk } from './helpers/fake-disk';
+import { FakeServer } from './helpers/fake-server';
+
+const FAST = { localDelayMs: 0, remoteDelayMs: 0, pollMs: 1e9, rescanMs: 1e9, retryMs: [1e9], soonMs: 5, fetchWaitMs: 1000 };
+
+function fakeBridge(controls: FilesControls) {
+ const claim = vi.fn<() => FilesControls | null>();
+ let taken = false;
+ claim.mockImplementation(() => {
+ if (taken) return null;
+ taken = true;
+ return controls;
+ });
+ return { version: 1, platform: 'win32' as const, files: { claim } };
+}
+
+describe('claiming the bridge', () => {
+ afterEach(() => {
+ delete (window as { bulwarkDesktop?: unknown }).bulwarkDesktop;
+ resetFilesControlsForTests();
+ });
+
+ it('takes the controls in the first render, once, so a frame coming later gets nothing', () => {
+ const controls = new FakeDisk();
+ const bridge = fakeBridge(controls);
+ (window as { bulwarkDesktop?: unknown }).bulwarkDesktop = bridge;
+ const { rerender } = render(createElement(WindowControlsHost));
+ rerender(createElement(WindowControlsHost));
+ expect(bridge.files.claim).toHaveBeenCalledTimes(1);
+ expect(claimFilesControls()).toBe(controls);
+ // A same-origin frame reaching the bridge through parent.
+ expect(bridge.files.claim()).toBeNull();
+ });
+
+ it('takes nothing in a browser', () => {
+ render(createElement(WindowControlsHost));
+ expect(claimFilesControls()).toBeNull();
+ });
+});
+
+interface Rig {
+ host: FilesSyncHost;
+ disk: FakeDisk;
+ server: FakeServer;
+ snapshot: () => Partial;
+ controller: () => FilesSyncController | null;
+ folderOff: { value: boolean };
+ account: HostAccount;
+}
+
+function rig(options: { drive?: boolean; wanted?: string[] } = {}): Rig {
+ const disk = new FakeDisk({ caseInsensitive: true, drive: options.drive });
+ disk.driveWanted = options.wanted ?? [];
+ const server = new FakeServer();
+ let published: Partial = {};
+ let controller: FilesSyncController | null = null;
+ const folderOff = { value: false };
+ const host = new FilesSyncHost({
+ controls: disk,
+ platform: 'win32',
+ publish: (patch) => {
+ published = { ...published, ...patch };
+ },
+ setController: (next) => {
+ controller = next;
+ },
+ folderSyncForcedOff: () => folderOff.value,
+ downloadsForbidden: () => false,
+ remoteFor: () => server.remote(),
+ readUrl: disk.readUrl,
+ timing: FAST,
+ });
+ const account: HostAccount = { id: 'a1', label: 'a@example.org', client: { getSessionSnapshot: () => server.session, getAuthHeader: () => 'Basic x' } };
+ return { host, disk, server, snapshot: () => published, controller: () => controller, folderOff, account };
+}
+
+async function settle(host: FilesSyncHost): Promise {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ await host.engine.settled();
+ await new Promise((resolve) => setTimeout(resolve, 60));
+}
+
+describe('the host', () => {
+ it('runs the roots of signed-in accounts, publishes the current one, and registers the controller', async () => {
+ const r = rig();
+ r.disk.addRoot({ id: 'r1', account: 'a1', remoteId: null });
+ r.disk.addRoot({ id: 'r2', account: 'other', remoteId: null });
+ r.disk.write('r1', 'a.txt', 'a');
+ r.host.start();
+ r.host.setAccounts([r.account], 'a1');
+ await settle(r.host);
+ expect(r.server.listing()).toEqual(['a.txt']);
+ expect(r.snapshot()).toMatchObject({ available: true, account: 'a1', folderSyncForcedOff: false });
+ expect(r.snapshot().roots?.map((root) => root.id)).toEqual(['r1']);
+ expect(r.snapshot().status?.r1).toMatchObject({ state: 'idle' });
+ expect(r.snapshot().activity?.[0]).toMatchObject({ kind: 'uploaded', path: 'a.txt' });
+ expect(Object.values(r.snapshot().items ?? {})).toEqual(['synced']);
+ expect(r.controller()).not.toBeNull();
+ r.host.stop();
+ expect(r.controller()).toBeNull();
+ });
+
+ it('keeps folders out of sync while the policy forbids them', async () => {
+ const r = rig();
+ r.folderOff.value = true;
+ r.disk.addRoot({ id: 'r1', account: 'a1', remoteId: null });
+ r.disk.write('r1', 'a.txt', 'a');
+ r.host.start();
+ r.host.setAccounts([r.account], 'a1');
+ await settle(r.host);
+ expect(r.server.listing()).toEqual([]);
+ expect(r.snapshot().status?.r1).toMatchObject({ state: 'blocked', errorKey: 'errors.policy' });
+ expect(r.snapshot().folderSyncForcedOff).toBe(true);
+ r.host.stop();
+ });
+
+ it('turns the drive back on at sign-in without a click, and off at sign-out keeping the wish', async () => {
+ const r = rig({ drive: true, wanted: ['a1'] });
+ r.server.file('a.txt', null, 'a');
+ r.host.start();
+ r.host.setAccounts([r.account], 'a1');
+ await settle(r.host);
+ await settle(r.host);
+ expect(r.disk.driveCalls[0]).toEqual({ call: 'enable', args: ['a1', 'a@example.org'] });
+ expect(r.disk.listing('drive-a1')).toEqual(['a.txt']);
+ expect(r.disk.states.get('drive-a1')).toContain('a.txt');
+ await r.host.signedOut('a1');
+ expect(r.disk.driveCalls.at(-1)).toEqual({ call: 'disable', args: ['a1', 'signed-out'] });
+ expect(r.disk.driveWanted).toEqual(['a1']);
+ // The record went before the folder did: the next sign-in starts from an empty one.
+ expect(r.disk.states.get('drive-a1')).not.toContain('a.txt');
+ r.host.stop();
+ });
+
+ it('removes the drive and forgets the folders of a wiped account, and keeps their files', async () => {
+ const r = rig({ drive: true, wanted: ['a1', 'a2'] });
+ r.disk.addRoot({ id: 'r1', account: 'a1', remoteId: null });
+ r.disk.addRoot({ id: 'r2', account: 'a2', remoteId: null });
+ r.disk.write('r1', 'mine.txt', 'mine');
+ r.host.start();
+ await r.host.removeAccountData('a1', 'wipe');
+ expect(r.disk.driveCalls).toContainEqual({ call: 'disable', args: ['a1', 'wipe'] });
+ expect(r.disk.driveCalls.some((call) => call.args[0] === 'a2')).toBe(false);
+ expect(r.disk.calls).toEqual(['removeRoot r1']);
+ expect(r.disk.read('r1', 'mine.txt')).toBe('mine');
+ r.host.stop();
+ });
+
+ it('answers the controller: shared folders refused, the drive switch, show in folder', async () => {
+ const r = rig({ drive: true });
+ r.disk.addRoot({ id: 'r1', account: 'a1', remoteId: null });
+ r.disk.write('r1', 'Docs/a.txt', 'a');
+ r.host.start();
+ r.host.setAccounts([r.account], 'a1');
+ await settle(r.host);
+ const controller = r.controller()!;
+ expect(await controller.addFolder('shared1:n5', 'Team')).toEqual({ ok: false, error: 'unsupported' });
+ expect(r.disk.calls).toEqual([]);
+ const id = r.server.find('Docs/a.txt')!.id;
+ expect(controller.coverage(id)).toEqual({ rootId: 'r1', kind: 'folder', path: 'Docs/a.txt' });
+ expect(await controller.showInFolder(id)).toBe(true);
+ expect(r.disk.shown).toEqual([{ rootId: 'r1', path: 'Docs/a.txt' }]);
+ expect(await controller.showInFolder('unknown')).toBe(false);
+ expect((await controller.setDriveEnabled(true)).ok).toBe(true);
+ expect(r.disk.driveCalls.at(-1)).toEqual({ call: 'enable', args: ['a1', 'a@example.org'] });
+ expect(await controller.setDriveEnabled(false)).toEqual({ ok: true, value: null });
+ expect(r.disk.driveCalls.at(-1)).toEqual({ call: 'disable', args: ['a1', 'user'] });
+ r.host.stop();
+ });
+});
+
+describe('sign-out, wipe and refused logins', () => {
+ let r: Rig;
+ beforeEach(async () => {
+ resetFilesSyncLifecycleForTests();
+ registerFilesSyncLifecycle();
+ r = rig({ drive: true, wanted: ['a1'] });
+ r.disk.addRoot({ id: 'r1', account: 'a1', remoteId: null });
+ r.host.start();
+ setRunningFilesSyncHost(r.host);
+ });
+ afterEach(() => {
+ r.host.stop();
+ resetFilesSyncLifecycleForTests();
+ });
+
+ it('a wipe removes the drive and forgets the folders', async () => {
+ await runWipeCleaners('a1');
+ expect(r.disk.driveCalls).toContainEqual({ call: 'disable', args: ['a1', 'wipe'] });
+ expect(r.disk.calls).toContain('removeRoot r1');
+ });
+
+ it('a refused login the server is sure of does the same, an unsure one nothing', async () => {
+ noteCredentialsRejected('a1', false, 'refused');
+ noteCredentialsRejected('a1', true, 'session');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(r.disk.driveCalls.filter((call) => call.call === 'disable')).toEqual([]);
+ noteCredentialsRejected('a1', true, 'refused');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(r.disk.driveCalls).toContainEqual({ call: 'disable', args: ['a1', 'refused'] });
+ expect(r.disk.calls).toContain('removeRoot r1');
+ });
+
+ it('a sign-out takes the drive down and keeps the folders', async () => {
+ await runBeforeSignOut('a1');
+ expect(r.disk.driveCalls).toContainEqual({ call: 'disable', args: ['a1', 'signed-out'] });
+ expect(r.disk.calls).toEqual([]);
+ });
+});
diff --git a/lib/files-sync/__tests__/real-server.test.ts b/lib/files-sync/__tests__/real-server.test.ts
new file mode 100644
index 000000000..245301733
--- /dev/null
+++ b/lib/files-sync/__tests__/real-server.test.ts
@@ -0,0 +1,225 @@
+// @vitest-environment node
+/**
+ * The engine against a real Stalwart, with the in-memory disk. Skipped unless asked for:
+ *
+ * FILES_SYNC_REAL_URL=https://stalwart.internal.bulwarkmail.org FILES_SYNC_REAL_LABEL=0.16 \
+ * vw exec --env FILES_SYNC_REAL_PASSWORD="vault:///password" -- npx vitest run lib/files-sync/__tests__/real-server.test.ts
+ *
+ * Uses the throwaway accounts dso-fs and dso-fs-b (VM 106 ~/desktop-offline/dso_fs_provision.py,
+ * which also seeds dso-fs's "Seed" folder; dso_fs_dav_seed.py adds names Windows can't hold over
+ * WebDAV). It signs in once per account and stops there if that's refused: nothing polls as a
+ * missing user.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { FetchTransport, type StoreSession } from '@/lib/store/engine/transport';
+import { FilesSyncEngine, type EngineTiming } from '../engine';
+import { namingFor } from '../names';
+import { FilesRemote, type RemoteNode } from '../remote';
+import { FakeDisk, str, text } from './helpers/fake-disk';
+
+const URL_BASE = process.env.FILES_SYNC_REAL_URL ?? '';
+const LABEL = process.env.FILES_SYNC_REAL_LABEL ?? '';
+const PASSWORD = process.env.FILES_SYNC_REAL_PASSWORD ?? '';
+const run = !!URL_BASE && !!PASSWORD;
+const FAST: Partial = { localDelayMs: 0, remoteDelayMs: 0, pollMs: 1e9, rescanMs: 1e9, retryMs: [1e9], soonMs: 50, fetchWaitMs: 30_000 };
+
+function basic(user: string): string {
+ return `Basic ${Buffer.from(`${user}@example.org:${PASSWORD}`).toString('base64')}`;
+}
+
+async function signIn(user: string): Promise {
+ const response = await fetch(`${URL_BASE}/jmap/session`, { headers: { Authorization: basic(user) } });
+ if (response.status !== 200) throw new Error(`${user} on ${LABEL}: session ${response.status}; run dso_fs_provision.py first`);
+ const session = (await response.json()) as StoreSession;
+ const transport = new FetchTransport({ session: () => session, auth: () => basic(user), refreshAuth: async () => basic(user) });
+ return new FilesRemote(transport, () => session);
+}
+
+async function tree(remote: FilesRemote): Promise