From e1de3e2e4e429b620e6393d37cd20740446d25aa Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:09:07 +0100 Subject: [PATCH 01/12] fix(project): open a project the idle sweep closed again after a reconnect --- packages/project/src/fs/project-fs.ts | 42 +++++++++++---- .../project/src/service/client-project.ts | 54 ++++++++++++++++--- packages/project/test/fs/project-fs.spec.ts | 43 ++++++++++++++- 3 files changed, 122 insertions(+), 17 deletions(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index b992a210..4de3dcc0 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -3,8 +3,10 @@ import { DisposableStore, Emitter, type Event, + MutableDisposable, type Observable, ObservableValue, + errorCodeOf, } from '@nanoforge-dev/editor-kernel'; import { type FileChange, @@ -46,6 +48,8 @@ export class ProjectFs implements Disposable { private readonly _ready = new ObservableValue(false); private readonly _onDidChange = new Emitter(); private readonly _store = new DisposableStore(); + private readonly _changes = this._store.add(new MutableDisposable()); + private readonly _onDidLose = new Emitter(); private _treeSave: ReturnType | undefined; /** * Ticks at each change of the tree. A reply only updates the paths nothing changed since its @@ -61,6 +65,11 @@ export class ProjectFs implements Disposable { /** Batched changes (from the server watcher and this client's own writes). */ readonly onDidChange: Event = 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`). + */ + readonly onDidLose: Event = this._onDidLose.event; constructor( readonly projectId: string, @@ -80,15 +89,14 @@ export class ProjectFs implements Disposable { async initialize(): Promise { const cached = await this._treeCache.load(); for (const entry of cached ?? []) this._tree.set(entry.path, entry); - this._store.add( - this._rpc.subscribe( - FsContract, - 'changes', - { project: this.projectId }, - ({ changes }) => void this._applyRemote(changes), - ), - ); - this._store.add(this._rpc.onDidReconnect(() => void this.refresh().catch(() => undefined))); + this._subscribe(); + this._store.add(this._rpc.onDidReconnect(() => void this.refresh().catch(this._lost))); + await this.refresh(); + } + + /** Once the server has the project open again: follows its changes again and catches up. */ + async reattach(): Promise { + this._subscribe(); await this.refresh(); } @@ -275,8 +283,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 { const relevant: FileChange[] = []; /** diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index 00f9a34a..bc34e32a 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -3,9 +3,11 @@ import { type Disposable, DisposableStore, type EngineLibProvider, + MutableDisposable, type Observable, ObservableValue, derived, + errorCodeOf, } from '@nanoforge-dev/editor-kernel'; import { type ProjectModel, ProjectsContract } from '@nanoforge-dev/editor-protocol'; import type { RpcClient } from '@nanoforge-dev/editor-rpc'; @@ -33,6 +35,8 @@ export const memoryCacheFactory = (): CacheFactory => { export class ClientProject implements Disposable, EngineLibProvider { private readonly _store = new DisposableStore(); private readonly _model: ObservableValue; + private readonly _modelStream = this._store.add(new MutableDisposable()); + private _reopening: Promise | undefined; readonly fs: ProjectFs; /** Apps as the kernel sees them (engine lib gating). */ @@ -40,7 +44,7 @@ export class ClientProject implements Disposable, EngineLibProvider { constructor( initial: ProjectModel, - rpc: RpcClient, + private readonly _rpc: RpcClient, caches: CacheFactory, /** * Whether its code may run here. An untrusted local folder is open in restricted mode: its @@ -50,15 +54,12 @@ export class ClientProject implements Disposable, EngineLibProvider { ) { this._model = new ObservableValue(initial); this.fs = this._store.add( - new ProjectFs(initial.id, rpc, caches.contents(initial.id), caches.tree(initial.id)), + new ProjectFs(initial.id, _rpc, caches.contents(initial.id), caches.tree(initial.id)), ); const lease = caches.opened?.(initial.id); if (lease) this._store.add(lease); - this._store.add( - rpc.subscribe(ProjectsContract, 'model', { id: initial.id }, (model) => - this._model.set(model), - ), - ); + this._subscribeModel(); + this._store.add(this.fs.onDidLose(() => void this._reopen())); this.apps = derived([this._model], (model) => model.apps.map((app) => ({ id: app.id, @@ -80,4 +81,43 @@ export class ClientProject implements Disposable, EngineLibProvider { dispose(): void { this._store.dispose(); } + + private _subscribeModel(): void { + this._modelStream.value = this._rpc.subscribe( + ProjectsContract, + 'model', + { id: this.id }, + (model) => this._model.set(model), + { + onError: (error) => { + if (errorCodeOf(error) === 'NOT_FOUND') void this._reopen(); + }, + }, + ); + } + + /** + * The server closed the project (idle sweep) while this tab was away: opens it again from its + * recent entry, the same folder with the same trust, and follows it again. Ids are stable, so + * the tab goes on as it was. Once at a time: the stream errors and the reconnect's refresh all + * report it. + */ + private _reopen(): Promise { + this._reopening ??= (async () => { + const api = this._rpc.api(ProjectsContract); + /** + * shortcut: a folder that moved or changed trust (or a failed open) leaves the tab as it was, + * until the project page shows its "not open anymore" screen for it. + */ + const known = (await api.recent(null)).find((project) => project.id === this.id); + if (!known) return; + const opened = await api.open(known.ref); + if (opened.id !== this.id || opened.trusted !== this.trusted) return; + this._subscribeModel(); + await this.fs.reattach(); + })() + .catch(() => undefined) + .finally(() => (this._reopening = undefined)); + return this._reopening; + } } diff --git a/packages/project/test/fs/project-fs.spec.ts b/packages/project/test/fs/project-fs.spec.ts index 4b32e8aa..b7ba726d 100644 --- a/packages/project/test/fs/project-fs.spec.ts +++ b/packages/project/test/fs/project-fs.spec.ts @@ -1,4 +1,12 @@ -import { cpSync, mkdtempSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'; +import { + cpSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; @@ -155,4 +163,37 @@ describe('ProjectFs', () => { writeFileSync(file, text); await project.fs.refresh(); }); + + it('opens the project again after the idle sweep closed it while the tab was away', async () => { + const project = service.current.get()!; + /** The sweep closes a project no socket holds: the tab's socket is gone meanwhile. */ + editor.projects.sweep(() => false, -1); + expect(editor.projects.openIds).toEqual([]); + (rpc as unknown as { _socket: { close(): void } })._socket.close(); + await waitFor(() => editor.projects.openIds.includes(project.id), 3000); + expect(editor.projects.openIds).toEqual([project.id]); + + const changes: FileChange[] = []; + const subscription = project.fs.onDidChange((batch) => changes.push(...batch)); + /** Server watcher initial scan. */ + await new Promise((resolve) => setTimeout(resolve, 300)); + writeFileSync(join(workspace, 'pong/apps/client/src/after-sweep.ts'), '// outside\n'); + await waitFor(() => changes.length > 0); + subscription.dispose(); + expect(changes).toEqual([ + { type: 'created', path: 'apps/client/src/after-sweep.ts', kind: 'file' }, + ]); + await expect( + project.fs.write('apps/client/src/after-sweep.ts', '// saved\n'), + ).resolves.toMatchObject({ path: 'apps/client/src/after-sweep.ts' }); + rmSync(join(workspace, 'pong/apps/client/src/after-sweep.ts')); + + /** The model follows the project again too. */ + const manifest = join(workspace, 'pong/package.json'); + const original = readFileSync(manifest, 'utf8'); + writeFileSync(manifest, original.replace('"pong-network"', '"pong-after-sweep"')); + await waitFor(() => project.model.get().name === 'pong-after-sweep'); + writeFileSync(manifest, original); + expect(project.model.get().name).toBe('pong-after-sweep'); + }); }); From 8cd68783e6db14472c7e94ea3bbd59315ce05e3e Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:11:43 +0100 Subject: [PATCH 02/12] fix(project): check a remote change batch 16 stats at a time --- packages/project/src/fs/project-fs.ts | 39 +++++++++++++------ .../project/test/fs/project-fs-races.spec.ts | 35 +++++++++++++++++ 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index 4de3dcc0..a1940825 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -20,6 +20,8 @@ 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; /** Hides files from the whole editor (see the server's file system). */ export const NFIGNORE_FILE = '.nfignore'; @@ -319,24 +321,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(); + 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); @@ -446,15 +459,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): 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): 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; } } diff --git a/packages/project/test/fs/project-fs-races.spec.ts b/packages/project/test/fs/project-fs-races.spec.ts index cdc68fa7..c8087d76 100644 --- a/packages/project/test/fs/project-fs-races.spec.ts +++ b/packages/project/test/fs/project-fs-races.spec.ts @@ -278,6 +278,41 @@ describe('ProjectFs races', () => { fs.dispose(); }); + it('checks a large change batch 16 stats at a time, and tells it in its order', async () => { + const server = fakeServer({}); + const fs = await open(server, new MemoryContentCache()); + const paths = Array.from({ length: 40 }, (_, index) => `f${index}.ts`); + const answers = paths.map(() => held()); + server.stats.push(...answers.map((answer) => answer.promise)); + const changes: FileChange[] = []; + const subscription = fs.onDidChange((batch) => changes.push(...batch)); + server.change(paths.map((path) => ({ type: 'created', path, kind: 'file' }))); + await settle(); + expect(server.stats).toHaveLength(40 - 16); + for (const [index, answer] of [...answers.entries()].reverse()) + answer.release(fileEntry(paths[index]!, 'x')); + await settle(); + expect(changes.map((change) => change.path)).toEqual(paths); + subscription.dispose(); + fs.dispose(); + }); + + it('keeps a file a batch made in a folder the same batch saw deleted', async () => { + const server = fakeServer({}); + const folder: FileEntry = { path: 'dist', kind: 'directory', size: 0, mtime: 1 }; + server.lists.push(Promise.resolve([folder])); + const fs = await open(server, new MemoryContentCache()); + server.stats.push(Promise.resolve(null), Promise.resolve(fileEntry('dist/a.js', 'a'))); + server.change([ + { type: 'deleted', path: 'dist', kind: 'directory' }, + { type: 'created', path: 'dist/a.js', kind: 'file' }, + ]); + await settle(); + expect(fs.entry('dist')).toBeUndefined(); + expect(fs.entry('dist/a.js')?.hash).toBe(sha1('a')); + fs.dispose(); + }); + it('tells an outside change back to what the editor saved', async () => { const server = fakeServer({ 'a.ts': 'old' }); const fs = await open(server, new MemoryContentCache()); From 4dc2ef4ebea5222d791f420986e054357af38ab5 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:18:04 +0100 Subject: [PATCH 03/12] fix(project): look up at most 32 cached files at once --- packages/project/src/fs/project-fs.ts | 17 +++++++++----- .../project/test/fs/project-fs-races.spec.ts | 23 +++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index a1940825..09fb9200 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -22,6 +22,8 @@ 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'; @@ -374,14 +376,17 @@ export class ProjectFs implements Disposable { const found = new Map(); const cached = new Map(); 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) { diff --git a/packages/project/test/fs/project-fs-races.spec.ts b/packages/project/test/fs/project-fs-races.spec.ts index c8087d76..700eb024 100644 --- a/packages/project/test/fs/project-fs-races.spec.ts +++ b/packages/project/test/fs/project-fs-races.spec.ts @@ -389,6 +389,29 @@ describe('ProjectFs races', () => { fs.dispose(); }); + it('looks up at most 32 cached files at once, and gives them in their order', async () => { + const texts = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`f${i}.ts`, `${i}`])); + const server = fakeServer(texts); + const memory = new MemoryContentCache(); + for (const text of Object.values(texts)) await memory.set(sha1(text), encoder.encode(text)); + let inFlight = 0; + let peak = 0; + const contents: ContentCache = { + get: async (hash) => { + peak = Math.max(peak, ++inFlight); + await new Promise((resolve) => setTimeout(resolve, Math.random() * 3)); + inFlight--; + return memory.get(hash); + }, + set: (hash, bytes) => memory.set(hash, bytes), + }; + const fs = await open(server, contents); + const read = await fs.readMany(Object.keys(texts)); + expect(peak).toBe(32); + expect([...read.keys()]).toEqual(Object.keys(texts)); + fs.dispose(); + }); + it('saves without waiting for the content cache', async () => { const server = fakeServer({ 'a.ts': 'old' }); const stuck: ContentCache = { From 68aec5c63a5c2fc0433f66437952eea5324bac36 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:20:34 +0100 Subject: [PATCH 04/12] fix(project): index the file tree by folder for the files panel --- packages/project/src/fs/project-fs.ts | 48 +++++++++++++++---- .../project/test/fs/project-fs-races.spec.ts | 48 ++++++++++++++++++- 2 files changed, 86 insertions(+), 10 deletions(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index 09fb9200..90bb5dfa 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -40,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 { + private readonly _children = new Map>(); + + 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 { + 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 @@ -48,7 +83,7 @@ const sameEntry = (a: FileEntry, b: FileEntry): boolean => */ export class ProjectFs implements Disposable { private readonly _fs: RpcApi; - private readonly _tree = new Map(); + private readonly _tree = new FileTree(); private readonly _ready = new ObservableValue(false); private readonly _onDidChange = new Emitter(); private readonly _store = new DisposableStore(); @@ -151,14 +186,9 @@ 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)] + .filter((child) => child !== path) + .map((child) => this._tree.get(child)!) .sort((a, b) => a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1, ); diff --git a/packages/project/test/fs/project-fs-races.spec.ts b/packages/project/test/fs/project-fs-races.spec.ts index 700eb024..d21f3f63 100644 --- a/packages/project/test/fs/project-fs-races.spec.ts +++ b/packages/project/test/fs/project-fs-races.spec.ts @@ -53,8 +53,11 @@ const fakeServer = (initial: Record) => { })), rest: [], }), + mkdir: ({ path }: { path: string }) => + Promise.resolve({ path, kind: 'directory', size: 0, mtime: 1 } as FileEntry), delete: ({ path }: { path: string }) => { - files.delete(path); + for (const file of [...files.keys()]) + if (file === path || file.startsWith(`${path}/`)) files.delete(file); return Promise.resolve({ trashPath: `.trash/${path}` }); }, write: ({ path, content }: { path: string; content: string }) => { @@ -412,6 +415,49 @@ describe('ProjectFs races', () => { fs.dispose(); }); + it('lists the children of a folder as the whole tree has them, through every change', async () => { + /** What `children` gave when it filtered the whole tree. */ + const scan = (fs: ProjectFs, path: string) => { + const prefix = path ? `${path}/` : ''; + return fs.entries + .filter( + (entry) => + entry.path.startsWith(prefix) && + !entry.path.slice(prefix.length).includes('/') && + entry.path !== path, + ) + .sort((a, b) => + a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1, + ); + }; + /** The listing has no folder entries: a folder's files are still its children. */ + const server = fakeServer({ 'b.ts': 'b', 'a/y.ts': 'y', 'a/x.ts': 'x', 'a/k/z.ts': 'z' }); + const fs = await open(server, new MemoryContentCache()); + const check = () => { + for (const path of ['', 'a', 'a/k', 'missing']) + expect(fs.children(path)).toEqual(scan(fs, path)); + }; + check(); + expect(fs.children('a').map((entry) => entry.path)).toEqual(['a/x.ts', 'a/y.ts']); + await fs.mkdir('a/k'); + await fs.write('a/w.ts', 'w'); + check(); + await fs.delete('a/k'); + check(); + server.files.set('c.ts', 'c'); + server.files.delete('a/x.ts'); + server.change([ + { type: 'created', path: 'c.ts', kind: 'file' }, + { type: 'deleted', path: 'a/x.ts', kind: 'file' }, + ]); + await settle(); + check(); + expect(fs.children('').map((entry) => entry.path)).toEqual(['b.ts', 'c.ts']); + await fs.refresh(); + check(); + fs.dispose(); + }); + it('saves without waiting for the content cache', async () => { const server = fakeServer({ 'a.ts': 'old' }); const stuck: ContentCache = { From fff4528acf4022ffe45094afb894196ddeaf33bc Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:28:02 +0100 Subject: [PATCH 05/12] docs(project): record that a refused server stream is dropped by the rpc client --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index 48bc212f..384b4165 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `/.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`; `onDidLose` tells the tab). - **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. From a413bd7eb5b4b7a5c5f3c018f863c88f1f50bcc9 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:05:11 +0100 Subject: [PATCH 06/12] fix(project): tell when a project the sweep closed cannot be opened again --- AGENTS.md | 2 +- packages/project/src/fs/project-fs.ts | 12 +- .../project/src/service/client-project.ts | 59 ++++++-- .../test/service/client-project.spec.ts | 142 ++++++++++++++++++ 4 files changed, 202 insertions(+), 13 deletions(-) create mode 100644 packages/project/test/service/client-project.spec.ts diff --git a/AGENTS.md b/AGENTS.md index 384b4165..8f97e62d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,7 +256,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na - The e2e server reads its registry from `/.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`; `onDidLose` tells the tab). +- **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`). When it can't (no recent entry, another id or trust, a failed open, lost again within 30 s), it gives up and fires `ClientProject.onDidLose`; nothing listens to it 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 sweep: 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. diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index 90bb5dfa..eded3c4d 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -89,6 +89,8 @@ export class ProjectFs implements Disposable { private readonly _store = new DisposableStore(); private readonly _changes = this._store.add(new MutableDisposable()); private readonly _onDidLose = new Emitter(); + /** Bumped by `reattach`: a refusal of a request sent before it is old news. */ + private _attached = 0; private _treeSave: ReturnType | undefined; /** * Ticks at each change of the tree. A reply only updates the paths nothing changed since its @@ -129,12 +131,20 @@ export class ProjectFs implements Disposable { const cached = await this._treeCache.load(); for (const entry of cached ?? []) this._tree.set(entry.path, entry); this._subscribe(); - this._store.add(this._rpc.onDidReconnect(() => void this.refresh().catch(this._lost))); + this._store.add( + this._rpc.onDidReconnect(() => { + const attached = this._attached; + this.refresh().catch((error: unknown) => { + if (attached === this._attached) this._lost(error); + }); + }), + ); await this.refresh(); } /** Once the server has the project open again: follows its changes again and catches up. */ async reattach(): Promise { + this._attached++; this._subscribe(); await this.refresh(); } diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index bc34e32a..7c777bb7 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -2,7 +2,9 @@ import { type AppInfo, type Disposable, DisposableStore, + Emitter, type EngineLibProvider, + type Event, MutableDisposable, type Observable, ObservableValue, @@ -36,11 +38,25 @@ export class ClientProject implements Disposable, EngineLibProvider { private readonly _store = new DisposableStore(); private readonly _model: ObservableValue; private readonly _modelStream = this._store.add(new MutableDisposable()); + private readonly _onDidLose = new Emitter(); private _reopening: Promise | undefined; + /** When the last reopen began: a project lost again right after it is given up. */ + private _reopenedAt = -Infinity; + /** Given up: nothing is opened again. */ + private _done = false; + /** Lost again while the reopen was following the project again. */ + private _lostAgain = false; readonly fs: ProjectFs; /** Apps as the kernel sees them (engine lib gating). */ readonly apps: Observable; + /** + * The server closed the project and it could not be opened again here (no recent entry, another + * folder or trust, a failed open, or lost again at once): the tab should say it is not open + * anymore. Fires once. + * @internal for the project page. + */ + readonly onDidLose: Event = this._onDidLose.event; constructor( initial: ProjectModel, @@ -80,6 +96,7 @@ export class ClientProject implements Disposable, EngineLibProvider { dispose(): void { this._store.dispose(); + this._onDidLose.dispose(); } private _subscribeModel(): void { @@ -98,26 +115,46 @@ export class ClientProject implements Disposable, EngineLibProvider { /** * The server closed the project (idle sweep) while this tab was away: opens it again from its - * recent entry, the same folder with the same trust, and follows it again. Ids are stable, so - * the tab goes on as it was. Once at a time: the stream errors and the reconnect's refresh all - * report it. + * recent entry and follows it again. Ids are stable, so the tab goes on as it was. The server + * decides the trust; a project that comes back with another id or trust than this tab runs + * with is given up, so the tab never runs code under a trust it was not opened with. Once at a + * time: the stream errors and the reconnect's refresh all report it. */ private _reopen(): Promise { - this._reopening ??= (async () => { + if (this._done) return Promise.resolve(); + if (this._reopening) { + this._lostAgain = true; + return this._reopening; + } + /** The sweep closes a project after 30 minutes unused: lost again so soon, it stays lost. */ + if (Date.now() - this._reopenedAt < 30_000) { + this._giveUp(); + return Promise.resolve(); + } + this._reopening = (async () => { + this._reopenedAt = Date.now(); const api = this._rpc.api(ProjectsContract); - /** - * shortcut: a folder that moved or changed trust (or a failed open) leaves the tab as it was, - * until the project page shows its "not open anymore" screen for it. - */ const known = (await api.recent(null)).find((project) => project.id === this.id); - if (!known) return; + if (!known) return this._giveUp(); const opened = await api.open(known.ref); - if (opened.id !== this.id || opened.trusted !== this.trusted) return; + /** + * shortcut: the server copy opened here stays open (the contract has no close, and the + * session holds it); the sweep frees it once the tab is gone. Add a close when it matters. + */ + if (opened.id !== this.id || opened.trusted !== this.trusted) return this._giveUp(); + /** What was told before the open was the same loss. */ + this._lostAgain = false; this._subscribeModel(); await this.fs.reattach(); + if (this._lostAgain) this._giveUp(); })() - .catch(() => undefined) + .catch(() => this._giveUp()) .finally(() => (this._reopening = undefined)); return this._reopening; } + + private _giveUp(): void { + this._done = true; + this._onDidLose.fire(); + } } diff --git a/packages/project/test/service/client-project.spec.ts b/packages/project/test/service/client-project.spec.ts new file mode 100644 index 00000000..3b692c8f --- /dev/null +++ b/packages/project/test/service/client-project.spec.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + type ProjectModel, + ProjectsContract, + type RecentProject, +} from '@nanoforge-dev/editor-protocol'; +import { type RpcClient, RpcError } from '@nanoforge-dev/editor-rpc'; + +import { ClientProject, memoryCacheFactory } from '../../src/service/client-project'; + +const MODEL: ProjectModel = { id: 'p', name: 'p', location: '/p', apps: [], diagnostics: [] }; +const RECENT: RecentProject = { + id: 'p', + name: 'p', + location: '/p', + ref: { path: '/p' }, + openedAt: new Date(0), +}; + +type OnError = (error: RpcError) => void; + +/** An RPC client whose streams the test refuses, and whose `recent` and `open` it gives. */ +const fakeRpc = (projects: { + recent: () => Promise; + open: () => Promise<{ id: string; name: string; trusted: boolean }>; +}) => { + const streams: Record = { changes: [], model: [] }; + /** Every new `fs.changes` stream after the first is refused at once. */ + let refuseNewStreams = false; + const rpc = { + api: (contract: unknown) => + contract === ProjectsContract ? projects : { list: () => Promise.resolve([]) }, + subscribe: ( + _contract: unknown, + topic: string, + _params: unknown, + _onEvent: unknown, + handlers: { onError: OnError }, + ) => { + streams[topic]!.push(handlers.onError); + if (topic === 'changes' && refuseNewStreams && streams.changes!.length > 1) + queueMicrotask(() => handlers.onError(new RpcError('NOT_FOUND', 'Project p is not open'))); + return { dispose: () => undefined }; + }, + onDidReconnect: () => ({ dispose: () => undefined }), + } as unknown as RpcClient; + return { + rpc, + streams, + refuseNewStreams: () => (refuseNewStreams = true), + /** The server's sweep closed the project: its change stream is refused. */ + lose: () => streams.changes!.at(-1)!(new RpcError('NOT_FOUND', 'Project p is not open')), + }; +}; + +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); + +const start = async (server: ReturnType, trusted = false) => { + const project = new ClientProject(MODEL, server.rpc, memoryCacheFactory(), trusted); + await project.fs.initialize(); + const lost = vi.fn(); + project.onDidLose(lost); + return { project, lost }; +}; + +describe('ClientProject reopen', () => { + it('opens a project the server closed again, and follows it again', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledWith({ path: '/p' }); + expect(server.streams.changes).toHaveLength(2); + expect(server.streams.model).toHaveLength(2); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); + + it('gives up a project that comes back with another trust', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: true })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).toHaveBeenCalledOnce(); + expect(server.streams.changes).toHaveLength(1); + project.dispose(); + }); + + it('gives up a project the recent list does not have, without opening anything', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(projects.open).not.toHaveBeenCalled(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); + + it('gives up when the open fails', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.reject(new RpcError('NOT_FOUND', 'No project directory at /p'))), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); + + it('opens a project lost again and again only once', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + server.refuseNewStreams(); + const { project, lost } = await start(server); + server.lose(); + await settle(); + server.lose(); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); +}); From 3d399e455d966017de21ac2aac8f7dcb3f8b7301 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:05:17 +0100 Subject: [PATCH 07/12] fix(project): stop a reopen once the project is closed --- packages/project/src/service/client-project.ts | 12 ++++++++---- .../project/test/service/client-project.spec.ts | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index 7c777bb7..33172b14 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -42,7 +42,7 @@ export class ClientProject implements Disposable, EngineLibProvider { private _reopening: Promise | undefined; /** When the last reopen began: a project lost again right after it is given up. */ private _reopenedAt = -Infinity; - /** Given up: nothing is opened again. */ + /** Given up or disposed: nothing is opened again. */ private _done = false; /** Lost again while the reopen was following the project again. */ private _lostAgain = false; @@ -54,7 +54,6 @@ export class ClientProject implements Disposable, EngineLibProvider { * The server closed the project and it could not be opened again here (no recent entry, another * folder or trust, a failed open, or lost again at once): the tab should say it is not open * anymore. Fires once. - * @internal for the project page. */ readonly onDidLose: Event = this._onDidLose.event; @@ -95,6 +94,7 @@ export class ClientProject implements Disposable, EngineLibProvider { } dispose(): void { + this._done = true; this._store.dispose(); this._onDidLose.dispose(); } @@ -135,8 +135,10 @@ export class ClientProject implements Disposable, EngineLibProvider { this._reopenedAt = Date.now(); const api = this._rpc.api(ProjectsContract); const known = (await api.recent(null)).find((project) => project.id === this.id); + if (this._done) return; if (!known) return this._giveUp(); const opened = await api.open(known.ref); + if (this._done) return; /** * shortcut: the server copy opened here stays open (the contract has no close, and the * session holds it); the sweep frees it once the tab is gone. Add a close when it matters. @@ -146,9 +148,11 @@ export class ClientProject implements Disposable, EngineLibProvider { this._lostAgain = false; this._subscribeModel(); await this.fs.reattach(); - if (this._lostAgain) this._giveUp(); + if (this._lostAgain && !this._done) this._giveUp(); })() - .catch(() => this._giveUp()) + .catch(() => { + if (!this._done) this._giveUp(); + }) .finally(() => (this._reopening = undefined)); return this._reopening; } diff --git a/packages/project/test/service/client-project.spec.ts b/packages/project/test/service/client-project.spec.ts index 3b692c8f..3adc09ec 100644 --- a/packages/project/test/service/client-project.spec.ts +++ b/packages/project/test/service/client-project.spec.ts @@ -122,6 +122,23 @@ describe('ClientProject reopen', () => { project.dispose(); }); + it('opens nothing once disposed during the reopen', async () => { + let answer!: (recent: RecentProject[]) => void; + const projects = { + recent: vi.fn(() => new Promise((resolve) => (answer = resolve))), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + project.dispose(); + answer([RECENT]); + await settle(); + expect(projects.open).not.toHaveBeenCalled(); + expect(lost).not.toHaveBeenCalled(); + }); + it('opens a project lost again and again only once', async () => { const projects = { recent: vi.fn(() => Promise.resolve([RECENT])), From d2f4e1defa0a88df75b118d99dc83474ce917009 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:05:21 +0100 Subject: [PATCH 08/12] docs(project): mark the reopen hooks internal --- packages/project/src/fs/project-fs.ts | 6 +++++- packages/project/src/service/client-project.ts | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index eded3c4d..f01b63a7 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -109,6 +109,7 @@ export class ProjectFs implements Disposable { /** * 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 = this._onDidLose.event; @@ -142,7 +143,10 @@ export class ProjectFs implements Disposable { await this.refresh(); } - /** Once the server has the project open again: follows its changes again and catches up. */ + /** + * 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 { this._attached++; this._subscribe(); diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index 33172b14..2cb4649a 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -54,6 +54,7 @@ export class ClientProject implements Disposable, EngineLibProvider { * The server closed the project and it could not be opened again here (no recent entry, another * folder or trust, a failed open, or lost again at once): the tab should say it is not open * anymore. Fires once. + * @internal for the project page. */ readonly onDidLose: Event = this._onDidLose.event; From a7cea11706daec6ca1a877bb362f8e17b11e8826 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:05:27 +0100 Subject: [PATCH 09/12] refactor(project): drop a dead filter and shorten a test title --- packages/project/src/fs/project-fs.ts | 1 - packages/project/test/fs/project-fs-races.spec.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index f01b63a7..95ea5d2e 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -201,7 +201,6 @@ export class ProjectFs implements Disposable { /** Direct children of a directory, from the tree. */ children(path: string): FileEntry[] { return [...this._tree.childPaths(path)] - .filter((child) => child !== path) .map((child) => this._tree.get(child)!) .sort((a, b) => a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1, diff --git a/packages/project/test/fs/project-fs-races.spec.ts b/packages/project/test/fs/project-fs-races.spec.ts index d21f3f63..dc39ac2b 100644 --- a/packages/project/test/fs/project-fs-races.spec.ts +++ b/packages/project/test/fs/project-fs-races.spec.ts @@ -415,7 +415,7 @@ describe('ProjectFs races', () => { fs.dispose(); }); - it('lists the children of a folder as the whole tree has them, through every change', async () => { + it('lists the children of a folder as a scan of the whole tree would', async () => { /** What `children` gave when it filtered the whole tree. */ const scan = (fs: ProjectFs, path: string) => { const prefix = path ? `${path}/` : ''; From 82ea0d6d1f051d3a034ac7d9ec5173419e08c8dc Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:19:16 +0100 Subject: [PATCH 10/12] fix(project): try a reopen again after a failure that may pass --- .../project/src/service/client-project.ts | 16 ++++++--- .../test/service/client-project.spec.ts | 35 +++++++++++++++++-- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index 2cb4649a..62811bab 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -33,6 +33,9 @@ export const memoryCacheFactory = (): CacheFactory => { return { contents: () => contents, tree: () => new MemoryTreeCache() }; }; +/** Answers that say the project can't be opened again here (others may pass: offline, timeout). */ +const DEFINITE = new Set(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED']); + /** A project opened in this editor window. */ export class ClientProject implements Disposable, EngineLibProvider { private readonly _store = new DisposableStore(); @@ -51,9 +54,9 @@ export class ClientProject implements Disposable, EngineLibProvider { /** Apps as the kernel sees them (engine lib gating). */ readonly apps: Observable; /** - * The server closed the project and it could not be opened again here (no recent entry, another - * folder or trust, a failed open, or lost again at once): the tab should say it is not open - * anymore. Fires once. + * The server closed the project and it can't be opened again here (no recent entry, another id + * or trust, a refused request, or lost again at once): the tab should say it is not open + * anymore. Fires once. A failure that may pass (offline, timeout) waits for the next loss. * @internal for the project page. */ readonly onDidLose: Event = this._onDidLose.event; @@ -151,8 +154,11 @@ export class ClientProject implements Disposable, EngineLibProvider { await this.fs.reattach(); if (this._lostAgain && !this._done) this._giveUp(); })() - .catch(() => { - if (!this._done) this._giveUp(); + .catch((error: unknown) => { + if (this._done) return; + if (DEFINITE.has(errorCodeOf(error) ?? '')) return this._giveUp(); + /** It may pass: the next reconnect's refusal tries again. */ + this._reopenedAt = -Infinity; }) .finally(() => (this._reopening = undefined)); return this._reopening; diff --git a/packages/project/test/service/client-project.spec.ts b/packages/project/test/service/client-project.spec.ts index 3adc09ec..4c503b43 100644 --- a/packages/project/test/service/client-project.spec.ts +++ b/packages/project/test/service/client-project.spec.ts @@ -28,9 +28,14 @@ const fakeRpc = (projects: { const streams: Record = { changes: [], model: [] }; /** Every new `fs.changes` stream after the first is refused at once. */ let refuseNewStreams = false; + /** Answers of `fs.list` the test holds back, in call order (else an empty tree). */ + const lists: Promise<[]>[] = []; + let reconnected: (() => void) | undefined; const rpc = { api: (contract: unknown) => - contract === ProjectsContract ? projects : { list: () => Promise.resolve([]) }, + contract === ProjectsContract + ? projects + : { list: () => lists.shift() ?? Promise.resolve([]) }, subscribe: ( _contract: unknown, topic: string, @@ -43,12 +48,17 @@ const fakeRpc = (projects: { queueMicrotask(() => handlers.onError(new RpcError('NOT_FOUND', 'Project p is not open'))); return { dispose: () => undefined }; }, - onDidReconnect: () => ({ dispose: () => undefined }), + onDidReconnect: (listener: () => void) => { + reconnected = listener; + return { dispose: () => undefined }; + }, } as unknown as RpcClient; return { rpc, streams, + lists, refuseNewStreams: () => (refuseNewStreams = true), + reconnect: () => reconnected?.(), /** The server's sweep closed the project: its change stream is refused. */ lose: () => streams.changes!.at(-1)!(new RpcError('NOT_FOUND', 'Project p is not open')), }; @@ -156,4 +166,25 @@ describe('ClientProject reopen', () => { expect(lost).toHaveBeenCalledOnce(); project.dispose(); }); + + it('tries again on the next loss when the open may pass', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi + .fn() + .mockRejectedValueOnce(new RpcError('UNAVAILABLE', 'Editor server unreachable')) + .mockResolvedValue({ id: 'p', name: 'p', trusted: false }), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).not.toHaveBeenCalled(); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledTimes(2); + expect(server.streams.changes).toHaveLength(2); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); }); From 65729935bd11d1a83164d5fbe9d58dd87e094832 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:19:17 +0100 Subject: [PATCH 11/12] test(project): cover the reopen window and the reattach guard --- .../test/service/client-project.spec.ts | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/packages/project/test/service/client-project.spec.ts b/packages/project/test/service/client-project.spec.ts index 4c503b43..813b2a6f 100644 --- a/packages/project/test/service/client-project.spec.ts +++ b/packages/project/test/service/client-project.spec.ts @@ -187,4 +187,56 @@ describe('ClientProject reopen', () => { expect(lost).not.toHaveBeenCalled(); project.dispose(); }); + + it('gives up a project lost again within 30 s of its reopen, not later', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const later = fakeRpc(projects); + const first = await start(later); + later.lose(); + await settle(); + now.mockReturnValue(1_000_000 + 31_000); + later.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledTimes(2); + expect(first.lost).not.toHaveBeenCalled(); + first.project.dispose(); + + projects.open.mockClear(); + now.mockReturnValue(2_000_000); + const soon = fakeRpc(projects); + const second = await start(soon); + soon.lose(); + await settle(); + now.mockReturnValue(2_000_000 + 29_000); + soon.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(second.lost).toHaveBeenCalledOnce(); + second.project.dispose(); + now.mockRestore(); + }); + + it('takes no refusal of a request sent before the reopen for a new loss', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + let refuse!: (error: RpcError) => void; + server.lists.push(new Promise<[]>((_resolve, reject) => (refuse = reject))); + /** The reconnect's refresh is on its way when the stream reports the loss. */ + server.reconnect(); + server.lose(); + await settle(); + refuse(new RpcError('NOT_FOUND', 'Project p is not open')); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); }); From af9bf77c2057a045c251d53b2ef22853c6065975 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:19:18 +0100 Subject: [PATCH 12/12] docs(project): list when a reopen gives up --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 8f97e62d..2508322a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,7 +256,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na - The e2e server reads its registry from `/.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`). When it can't (no recent entry, another id or trust, a failed open, lost again within 30 s), it gives up and fires `ClientProject.onDidLose`; nothing listens to it 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 sweep: the projects contract has no close. +- **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.