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
57 changes: 45 additions & 12 deletions apps/editor/e2e/trust.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
import type { TestInfo } from '@playwright/test';
import { cpSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';

import { openProject } from './helpers';
import { expect, test } from './test';
import { PONG, WORKSPACE } from './workspace';

/** A copy of pong never trusted before, with a plugin of its own. */
const FOLDER = join(WORKSPACE, 'restricted');

test.beforeAll(() => {
rmSync(FOLDER, { recursive: true, force: true });
cpSync(PONG, FOLDER, {
/**
* A copy of pong never trusted before, named after the test, its repeat and its retry: the server
* remembers a trusted folder until the run ends.
*/
const copyPong = (prefix: string, { repeatEachIndex, retry }: TestInfo) => {
const name = `${prefix}-${repeatEachIndex}-${retry}`;
const folder = join(WORKSPACE, name);
rmSync(folder, { recursive: true, force: true });
cpSync(PONG, folder, {
recursive: true,
filter: (source) => !source.includes(`${PONG}/.nanoforge`),
});
const plugin = join(FOLDER, '.nanoforge/plugins/@acme/restricted');
return { name, folder };
};

/** Removes the copies the tests made. */
const copies: string[] = [];
test.afterAll(() => {
for (const folder of copies) rmSync(folder, { recursive: true, force: true });
});

test('opens a folder in restricted mode until it is trusted', async ({ page }, testInfo) => {
/** With a plugin of its own. */
const { name, folder } = copyPong('restricted', testInfo);
copies.push(folder);
const plugin = join(folder, '.nanoforge/plugins/@acme/restricted');
mkdirSync(plugin, { recursive: true });
writeFileSync(
join(plugin, 'nanoforge.manifest.json'),
Expand All @@ -26,12 +44,8 @@ test.beforeAll(() => {
}),
);
writeFileSync(join(plugin, 'index.js'), 'export const activate = () => {};\n');
});

test.afterAll(() => rmSync(FOLDER, { recursive: true, force: true }));

test('opens a folder in restricted mode until it is trusted', async ({ page }) => {
await page.goto('/load?path=restricted');
await page.goto(`/load?path=${name}`);
await page.getByRole('button', { name: 'Open in restricted mode', exact: true }).click();
await page.waitForURL(/\/project\//);
const restricted = page.getByText(/^Restricted mode: .* code does not run$/);
Expand Down Expand Up @@ -68,3 +82,22 @@ test('opens a folder in restricted mode until it is trusted', async ({ page }) =
).toBeVisible();
await page.keyboard.press('Escape');
});

test('the first Trust and open of a folder logs no error', async ({ page }, testInfo) => {
const { name, folder } = copyPong('first-trust', testInfo);
copies.push(folder);
const errors: string[] = [];
page.on('console', (message) => {
if (message.type() === 'error') errors.push(message.text());
});
/** The last requests of the project opening: the plugins' suggestions and the git state. */
const settled = (method: string) =>
page.waitForResponse((response) => response.url().endsWith(`/rpc/${method}`));
const opened = Promise.all([settled('plugins.suggestions'), settled('git.status')]);
await openProject(page, name);
await page.waitForURL(/\/project\//);
await expect(page.getByRole('tab', { name: 'Files' })).toBeVisible();
await opened;
await expect(page.getByText('Could not read the repository')).toHaveCount(0);
expect(errors).toEqual([]);
});
14 changes: 11 additions & 3 deletions apps/editor/src/lib/plugin/follow-project-plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export const followProjectPlugins = (options: {
const suggested = new Set<string>();
const offered = new Set<string>();
let listedFor: string | undefined;
/** Counts the follow calls: a listing of an earlier one is dropped. */
let follows = 0;
let queue = Promise.resolve();

const trusted = (project: string) =>
Expand Down Expand Up @@ -191,17 +193,23 @@ export const followProjectPlugins = (options: {
function follow(project: string | undefined) {
if (project === listedFor) return;
listedFor = project;
/** Not the id: trusting a folder closes its project and opens it again under the same id. */
const followed = ++follows;
const stale = () => followed !== follows;
queue = queue
.then(async () => {
const listings = await api.list(project ? { project } : null);
if (listedFor !== project) return;
if (stale()) return;
await plugins.update(
allowed(project, listings).flatMap((listing) => toDescriptor(listing, logger) ?? []),
);
if (stale()) return;
if (!options.online) await runServers(project ?? null);
if (project) await suggest(project);
if (project && !stale()) await suggest(project);
})
.catch((error: unknown) => logger.error('Could not load the project plugins', error));
.catch((error: unknown) => {
if (!stale()) logger.error('Could not load the project plugins', error);
});
}

return toDisposable(options.projects.current.subscribe((project) => follow(project?.id)));
Expand Down
5 changes: 2 additions & 3 deletions apps/editor/src/routes/(editor)/load/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,8 @@
let disposed = false;
const open = (trust = false) =>
editor.projects
.open(ref)
.then(async (project) => {
if (trust && !project.trusted) await editor.projects.trust();
.open(ref, { trust })
.then((project) => {
if (!disposed) void goto(`/project/${project.id}`, { replaceState: true });
})
.catch((reason: unknown) => {
Expand Down
42 changes: 42 additions & 0 deletions apps/editor/test/plugin/follow-project-plugins.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,46 @@ describe('followProjectPlugins', () => {
await expect.poll(() => suggestion(notify)?.[2].actions?.length).toBe(2);
disposable.dispose();
});

it('drops the errors of a project closed and opened again under the same id', async () => {
const current = new ObservableValue<{ id: string; trusted: boolean } | undefined>(undefined);
const error = vi.fn();
let release!: () => void;
const first = new Promise<void>((resolve) => (release = resolve));
const runProjectServers = vi
.fn()
.mockImplementationOnce(async () => {
await first;
throw new Error('Project pong is not open');
})
.mockResolvedValue(undefined);
const disposable = followProjectPlugins({
rpc: {
api: () => ({ list: async () => [], runProjectServers, suggestions: async () => [] }),
} as never,
projects: { current } as never,
plugins: {
update: async () => {},
getPlugin: () => undefined,
plugins: { get: () => [] },
} as never,
notifications: { notify: vi.fn() } as never,
logger: { warn: vi.fn(), error } as never,
settings: { get: () => [] } as never,
online: false,
});
current.set({ id: 'pong', trusted: false });
await expect.poll(() => runProjectServers.mock.calls.length).toBe(1);
current.set(undefined);
current.set({ id: 'pong', trusted: true });
release();

/**
* The stale run, then the reopened project's (the closed window's is stale before it lists).
*/
await expect.poll(() => runProjectServers.mock.calls.length).toBe(2);
expect(runProjectServers.mock.calls[1]![0].project).toBe('pong');
expect(error).not.toHaveBeenCalled();
disposable.dispose();
});
});
10 changes: 9 additions & 1 deletion packages/project/src/service/project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,16 @@ export class ProjectService implements Disposable {
return this._current.readonly();
}

async open(ref: ProjectRef): Promise<ClientProject> {
/**
* Opens a project. `trust`: a local folder not trusted yet is trusted first, before this window
* loads it, so nothing asks for the instance the server closes when it trusts it.
*/
async open(ref: ProjectRef, options: { trust?: boolean } = {}): Promise<ClientProject> {
const projects = this._rpc.api(ProjectsContract);
const opened = await projects.open(ref);
if (!options.trust || opened.trusted) return this.load(opened.id);
if (this._current.get()?.id === opened.id) this.close();
await projects.trust({ id: opened.id });
const { id } = await projects.open(ref);
return this.load(id);
}
Expand Down
106 changes: 106 additions & 0 deletions packages/project/test/service/project-service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { cpSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

import type { RpcClient } from '@nanoforge-dev/editor-rpc';
import { type EditorServer, createEditorServer, loadEnv } from '@nanoforge-dev/editor-server-core';
import { createLoopbackClient } from '@nanoforge-dev/editor-server-core/testing';

import { MemoryContentCache } from '../../src/cache/memory.content-cache';
import { MemoryTreeCache } from '../../src/cache/memory.tree-cache';
import { ProjectService } from '../../src/service/project-service';

const FIXTURE = join(import.meta.dirname, '../../../server-core/test/fixtures/pong-network');

let workspace: string;
let editor: EditorServer;
let rpc: RpcClient;
/** Every RPC call the window made, as `<namespace>.<method>`. */
const calls: string[] = [];

const createService = () =>
new ProjectService(rpc, {
contents: () => new MemoryContentCache(),
tree: () => new MemoryTreeCache(),
});

beforeAll(() => {
workspace = mkdtempSync(join(import.meta.dirname, '../../../server-core/test/.tmp-service-'));
for (const name of ['pong', 'restricted', 'trusted'])
cpSync(FIXTURE, join(workspace, name), { recursive: true });
editor = createEditorServer({
env: loadEnv(
{ NODE_ENV: 'test', FS_ROOT: workspace, DATA_DIR: mkdtempSync(join(tmpdir(), 'nf-data-')) },
workspace,
),
version: 'test',
});
rpc = createLoopbackClient(editor);
const api = rpc.api.bind(rpc);
rpc.api = ((contract: Parameters<RpcClient['api']>[0]) => {
const methods = api(contract) as Record<string, (input: unknown) => Promise<unknown>>;
return Object.fromEntries(
Object.keys(contract.methods).map((name) => [
name,
(input: unknown) => {
calls.push(`${contract.namespace}.${name}`);
return methods[name]!(input);
},
]),
);
}) as RpcClient['api'];
});

afterAll(() => {
rpc.dispose();
editor.dispose();
rmSync(workspace, { recursive: true, force: true });
});

describe('ProjectService', () => {
/** Nothing asks for the instance the server closes when it trusts the folder. */
it('trusts a folder before it loads it', async () => {
const service = createService();
const project = await service.open({ path: 'pong' }, { trust: true });

expect(project.trusted).toBe(true);
expect(service.current.get()).toBe(project);
const trust = calls.indexOf('projects.trust');
expect(calls.slice(0, trust + 2)).toEqual(['projects.open', 'projects.trust', 'projects.open']);
service.dispose();
});

it("closes the window's untrusted instance before it trusts the folder", async () => {
const service = createService();
const restricted = await service.open({ path: 'restricted' });
expect(restricted.trusted).toBe(false);
const unsubscribe = service.current.subscribe((project) => {
if (!project) calls.push('closed');
});
calls.length = 0;

const project = await service.open({ path: 'restricted' }, { trust: true });

unsubscribe();
expect(project).not.toBe(restricted);
expect(project.trusted).toBe(true);
expect(calls.slice(0, 4)).toEqual([
'projects.open',
'closed',
'projects.trust',
'projects.open',
]);
service.dispose();
});

it('does not trust a folder trusted already', async () => {
const service = createService();
await service.open({ path: 'trusted' }, { trust: true });
calls.length = 0;
const project = await service.open({ path: 'trusted' }, { trust: true });
expect(project.trusted).toBe(true);
expect(calls).not.toContain('projects.trust');
service.dispose();
});
});
Loading