)}
+
}
+
{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)}
+
Date: Wed, 4 Nov 2026 16:40:40 +0100
Subject: [PATCH 5/8] refactor: keep the Files screen's sync import apart from
the lines the usability fixes change
---
components/files/file-browser.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/components/files/file-browser.tsx b/components/files/file-browser.tsx
index 74070c6f6..ff719cdae 100644
--- a/components/files/file-browser.tsx
+++ b/components/files/file-browser.tsx
@@ -28,7 +28,6 @@ import { FilesSidebar, type CreateKind } from "@/components/files/files-sidebar"
import { FilesHeader, type Crumb, type SortDir, type SortKey, type ViewMode } from "@/components/files/files-header";
import { FileGridView, FileListView, type FileItemHandlers } from "@/components/files/file-views";
import { FileDetailsPanel } from "@/components/files/file-details-panel";
-import { ShowInFolderMenuItem } from "@/components/files-sync/files-sync-item";
import { INTERNAL_DRAG_TYPE, anchorEvent, isInternalDrag, readDraggedNames } from "@/components/files/file-item-parts";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { AppMain } from "@/components/layout/app-landmarks";
@@ -36,6 +35,7 @@ import { useIsEmbedded } from "@/hooks/use-is-embedded";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
import { useAppSidePanel } from "@/components/plugins/app-side-panel";
import { MAX_SIDE_PANEL_FILES } from "@/lib/plugin-sandbox/assistant/f.types";
+import { ShowInFolderMenuItem } from "@/components/files-sync/files-sync-item";
import { resourceToView, useFileStore, isSharedFilesPage, sharedFilePages, type FileResource } from "@/stores/file-store";
import { TRASH_LOCATION, TRASH_PATH, isTrashLocation } from "@/lib/files-trash";
import { PluginActions, usePluginActions } from "@/components/plugins/plugin-actions";
From b177aa47465425ed2778a91c5f5a168127e96d08 Mon Sep 17 00:00:00 2001
From: Linus Rath <139418639+rathlinus@users.noreply.github.com>
Date: Wed, 4 Nov 2026 16:57:30 +0100
Subject: [PATCH 6/8] feat: keep folders and the Files drive the same as Files,
both ways
---
lib/files-sync/__tests__/engine.test.ts | 616 ++++++++
lib/files-sync/__tests__/helpers/fake-disk.ts | 532 +++++++
.../__tests__/helpers/fake-server.ts | 247 +++
lib/files-sync/__tests__/real-server.test.ts | 225 +++
lib/files-sync/__tests__/remote.test.ts | 111 ++
lib/files-sync/engine.ts | 688 +++++++++
lib/files-sync/errors.ts | 92 ++
lib/files-sync/names.ts | 148 ++
lib/files-sync/remote.ts | 450 ++++++
lib/files-sync/root-sync.ts | 1327 +++++++++++++++++
lib/files-sync/state.ts | 83 ++
11 files changed, 4519 insertions(+)
create mode 100644 lib/files-sync/__tests__/engine.test.ts
create mode 100644 lib/files-sync/__tests__/helpers/fake-disk.ts
create mode 100644 lib/files-sync/__tests__/helpers/fake-server.ts
create mode 100644 lib/files-sync/__tests__/real-server.test.ts
create mode 100644 lib/files-sync/__tests__/remote.test.ts
create mode 100644 lib/files-sync/engine.ts
create mode 100644 lib/files-sync/errors.ts
create mode 100644 lib/files-sync/names.ts
create mode 100644 lib/files-sync/remote.ts
create mode 100644 lib/files-sync/root-sync.ts
create mode 100644 lib/files-sync/state.ts
diff --git a/lib/files-sync/__tests__/engine.test.ts b/lib/files-sync/__tests__/engine.test.ts
new file mode 100644
index 000000000..f425acf29
--- /dev/null
+++ b/lib/files-sync/__tests__/engine.test.ts
@@ -0,0 +1,616 @@
+// @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('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__/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