Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na
- The e2e server reads its registry from `<workspace>/.registry` (`REGISTRY_DIR`, written by `prepare-workspace.mjs`). A test that publishes a version there, installs a user plugin (`.data/plugins`) or a package (`nanoforge.packages*.json`, `tsconfig.json` paths) puts everything back (see `e2e/marketplace.spec.ts`).
- `nanoforge.manifest.json` is a build input of turbo (it was not until 2026-10-01: a manifest-only change kept the old bundle).
- After changing a plugin manifest, rebuild it: `tooling/example-plugin` is not rebuilt by the editor build filter (`pnpm --filter @nanoforge-dev/editor-example-plugin build`).
- **Server streams and the idle sweep:** when a subscription answers `error`, `RpcClient` deletes it for good (no retry, silent without `onError`). A stream keyed by a project (`fs.changes`, `projects.model`) errors with `NOT_FOUND` once the server's idle sweep closed the project, so give it an `onError` that, on `NOT_FOUND`, reopens the project (`ClientProject._reopen`: `recent` then `open`) and subscribes again (`ProjectFs.reattach`). It gives up and fires `ClientProject.onDidLose` on a definite answer: no recent entry, another id or trust, `NOT_FOUND`/`FORBIDDEN`/`UNAUTHORIZED` from a request of the reopen, or the project lost again while catching up or within 30 s of the last reopen. Any other failure (offline, timeout) leaves it to try again on the next loss. Nothing listens to `onDidLose` yet, so the tab stays as it was (the project page should show its "not open anymore" screen). A copy the server opened for a reopen given up stays open until the session's tabs are gone and the sweep runs: the projects contract has no close.
- **Installing folders and the file watcher:** a folder that appears through a rename is missed by the server's watcher (its content never reaches the client's file list, so the catalog does not see a new package). `installItem` writes files in place, the manifest last.
- **API features:** nothing of the NanoForge API beyond sign-in and projects is called unless listed in `API_FEATURES` (`settings`, `registry`). The real API (`../api`, read-only for us) has a registry (`../api/docs/registry.md`, the source of truth: align `docs/api/registry.md` with it, and `libs/registry` in the CLI repository) and no settings yet.
- **Account plugin list:** `plugins.account` is an account setting, and a local editor's account document lives on its own machine (no sign-in): the list does not travel between machines yet. Don't describe it as cross-machine.
Expand Down
155 changes: 122 additions & 33 deletions packages/project/src/fs/project-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import {
DisposableStore,
Emitter,
type Event,
MutableDisposable,
type Observable,
ObservableValue,
errorCodeOf,
} from '@nanoforge-dev/editor-kernel';
import {
type FileChange,
Expand All @@ -18,6 +20,10 @@ import type { ContentCache, TreeCache } from '../cache/cache.type';
import { sha1Hex } from '../cache/sha1';

const decoder = new TextDecoder();
/** Stats of a remote change batch on their way at once (a checkout touches thousands). */
const CONCURRENT_STATS = 16;
/** Cache lookups on their way at once: each one is a read of the browser's storage and a hash. */
const CONCURRENT_LOOKUPS = 32;

/** Hides files from the whole editor (see the server's file system). */
export const NFIGNORE_FILE = '.nfignore';
Expand All @@ -34,6 +40,41 @@ const sameContent = (a: FileEntry, b: FileEntry): boolean =>
const sameEntry = (a: FileEntry, b: FileEntry): boolean =>
a.kind === b.kind && a.size === b.size && a.mtime === b.mtime && a.hash === b.hash;

const parentOf = (path: string): string => path.slice(0, Math.max(0, path.lastIndexOf('/')));

/** Entries by path, and the paths in each folder: listing a folder reads only its own. */
class FileTree extends Map<string, FileEntry> {
private readonly _children = new Map<string, Set<string>>();

override set(path: string, entry: FileEntry): this {
if (!this.has(path)) {
const parent = parentOf(path);
const siblings = this._children.get(parent) ?? new Set();
this._children.set(parent, siblings.add(path));
}
return super.set(path, entry);
}

override delete(path: string): boolean {
if (!super.delete(path)) return false;
const parent = parentOf(path);
const siblings = this._children.get(parent);
siblings?.delete(path);
if (!siblings?.size) this._children.delete(parent);
return true;
}

override clear(): void {
super.clear();
this._children.clear();
}

/** Paths whose parent folder is `path` (in the order they joined the tree). */
childPaths(path: string): Iterable<string> {
return this._children.get(path) ?? [];
}
}

/**
* Files of the open project. The tree is loaded once (cached for fast startup), then kept in
* sync by the server change stream. Contents come from the local cache, keyed by the hash the
Expand All @@ -42,10 +83,14 @@ const sameEntry = (a: FileEntry, b: FileEntry): boolean =>
*/
export class ProjectFs implements Disposable {
private readonly _fs: RpcApi<typeof FsContract>;
private readonly _tree = new Map<string, FileEntry>();
private readonly _tree = new FileTree();
private readonly _ready = new ObservableValue(false);
private readonly _onDidChange = new Emitter<readonly FileChange[]>();
private readonly _store = new DisposableStore();
private readonly _changes = this._store.add(new MutableDisposable());
private readonly _onDidLose = new Emitter<void>();
/** Bumped by `reattach`: a refusal of a request sent before it is old news. */
private _attached = 0;
private _treeSave: ReturnType<typeof setTimeout> | undefined;
/**
* Ticks at each change of the tree. A reply only updates the paths nothing changed since its
Expand All @@ -61,6 +106,12 @@ export class ProjectFs implements Disposable {

/** Batched changes (from the server watcher and this client's own writes). */
readonly onDidChange: Event<readonly FileChange[]> = this._onDidChange.event;
/**
* The server does not have the project open anymore (the idle sweep closed it while this tab
* was away): the change stream is gone, and calls fail until it is opened again (`reattach`).
* @internal for `ClientProject`, which opens it again.
*/
readonly onDidLose: Event<void> = this._onDidLose.event;

constructor(
readonly projectId: string,
Expand All @@ -80,15 +131,25 @@ export class ProjectFs implements Disposable {
async initialize(): Promise<void> {
const cached = await this._treeCache.load();
for (const entry of cached ?? []) this._tree.set(entry.path, entry);
this._subscribe();
this._store.add(
this._rpc.subscribe(
FsContract,
'changes',
{ project: this.projectId },
({ changes }) => void this._applyRemote(changes),
),
this._rpc.onDidReconnect(() => {
const attached = this._attached;
this.refresh().catch((error: unknown) => {
if (attached === this._attached) this._lost(error);
});
}),
);
this._store.add(this._rpc.onDidReconnect(() => void this.refresh().catch(() => undefined)));
await this.refresh();
}

/**
* Once the server has the project open again: follows its changes again and catches up.
* @internal for `ClientProject`, which opens it again.
*/
async reattach(): Promise<void> {
this._attached++;
this._subscribe();
await this.refresh();
}

Expand Down Expand Up @@ -139,14 +200,8 @@ export class ProjectFs implements Disposable {

/** Direct children of a directory, from the tree. */
children(path: string): FileEntry[] {
const prefix = path ? `${path}/` : '';
return [...this._tree.values()]
.filter(
(entry) =>
entry.path.startsWith(prefix) &&
!entry.path.slice(prefix.length).includes('/') &&
entry.path !== path,
)
return [...this._tree.childPaths(path)]
.map((child) => this._tree.get(child)!)
.sort((a, b) =>
a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1,
);
Expand Down Expand Up @@ -275,8 +330,24 @@ export class ProjectFs implements Disposable {
}
this._store.dispose();
this._onDidChange.dispose();
this._onDidLose.dispose();
}

/** The client drops a stream the server refused: a new one replaces it. */
private _subscribe(): void {
this._changes.value = this._rpc.subscribe(
FsContract,
'changes',
{ project: this.projectId },
({ changes }) => void this._applyRemote(changes),
{ onError: this._lost },
);
}

private readonly _lost = (error: unknown): void => {
if (errorCodeOf(error) === 'NOT_FOUND') this._onDidLose.fire();
};

private async _applyRemote(changes: readonly FileChange[]): Promise<void> {
const relevant: FileChange[] = [];
/**
Expand All @@ -295,24 +366,35 @@ export class ProjectFs implements Disposable {
/**
* Every change is checked with a stat, deletions included: events come late and out of order
* (the echo of a deletion after the file was made again), the stat tells what is there now.
* A few stats are on their way at once; their answers are applied in the batch's order.
*/
for (const change of changes) {
const stats: Promise<{ sent: number; entry: FileEntry | null }>[] = [];
const stat = (path: string) => {
const sent = this._clock;
const entry = await this._fs
.stat({ project: this.projectId, path: change.path })
.catch(() => null);
return this._fs
.stat({ project: this.projectId, path })
.catch(() => null)
.then((entry) => ({ sent, entry }));
};
/** Removals of this batch: the stats sent with them are not older than them. */
const own = new Set<number>();
for (const [index, change] of changes.entries()) {
while (stats.length < Math.min(changes.length, index + CONCURRENT_STATS))
stats.push(stat(changes[stats.length]!.path));
const { sent, entry } = await stats[index]!;
if (!entry) {
if (change.type !== 'deleted' || this._changedSince(change.path, sent)) continue;
if (change.type !== 'deleted' || this._changedSince(change.path, sent, own)) continue;
const prefix = `${change.path}/`;
if (![...this._tree.keys()].some((key) => key === change.path || key.startsWith(prefix)))
continue;
this._removeFromTree(change.path);
own.add(this._clock);
relevant.push(change);
continue;
}
const previous = before.get(change.path) ?? this._tree.get(change.path);
/** A newer update already has the path: a read's is still told, a save told itself. */
if (!this._changedSince(change.path, sent)) this._setEntry(change.path, entry);
if (!this._changedSince(change.path, sent, own)) this._setEntry(change.path, entry);
const now = this._tree.get(change.path);
/** A save's own echo is absorbed once; any other content lands and forgets the save. */
const saved = this._saved.get(change.path);
Expand All @@ -337,14 +419,17 @@ export class ProjectFs implements Disposable {
const found = new Map<string, FileContent>();
const cached = new Map<string, Uint8Array>();
const ask: { path: string; knownHash?: string }[] = [];
/** Cache lookups run together: each one is a read of the browser's storage. */
const lookups = await Promise.all(
paths.map(async (path) => {
const lookups: { path: string; known?: FileEntry; bytes?: Uint8Array }[] = [];
let next = 0;
const lookup = async () => {
for (let index = next++; index < paths.length; index = next++) {
const path = paths[index]!;
const known = this._tree.get(path);
const bytes = known?.hash ? await this._contents.get(known.hash) : undefined;
return { path, known, bytes };
}),
);
lookups[index] = { path, known, bytes };
}
};
await Promise.all(Array.from({ length: Math.min(CONCURRENT_LOOKUPS, paths.length) }, lookup));
for (const { path, known, bytes } of lookups) {
if (known?.hash && bytes) {
if (!fresh) {
Expand Down Expand Up @@ -422,15 +507,19 @@ export class ProjectFs implements Disposable {
this._changedAt.set(path, ++this._clock);
}

/** Whether the tree changed at `path` (or removed a folder holding it) after tick `sent`. */
private _changedSince(path: string, sent: number): boolean {
return (this._changedAt.get(path) ?? 0) > sent || this._removedSince(path, sent);
/**
* Whether the tree changed at `path` (or removed a folder holding it) after tick `sent`,
* removals at the `ignored` ticks aside.
*/
private _changedSince(path: string, sent: number, ignored?: ReadonlySet<number>): boolean {
return (this._changedAt.get(path) ?? 0) > sent || this._removedSince(path, sent, ignored);
}

/** Whether `path`, or a folder holding it, left the tree after tick `sent`. */
private _removedSince(path: string, sent: number): boolean {
private _removedSince(path: string, sent: number, ignored?: ReadonlySet<number>): boolean {
for (let at = path; ; at = at.slice(0, at.lastIndexOf('/'))) {
if ((this._removedAt.get(at) ?? 0) > sent) return true;
const removed = this._removedAt.get(at) ?? 0;
if (removed > sent && !ignored?.has(removed)) return true;
if (!at.includes('/')) return false;
}
}
Expand Down
Loading
Loading