feat(desktop): run the database on the host so chat opens before the private computer (#1570)
This commit is contained in:
1 parent
591788f66c
commit
f4497ca632
58 files changed
+2788
-1654
No files matched your search
@@ -98,6 +98,7 @@ export function selectChecks(paths, event = 'workflow_dispatch') {
|
||||
}
|
||||
if (path.startsWith('tests/')) {
|
||||
enable('types', 'integration');
|
||||
if (path === 'tests/desktop-database.test.ts') enable('windows');
|
||||
if (/^tests\/[^/]+\.test\.ts$/.test(path)) testFiles.push(path);
|
||||
else testMode = 'all';
|
||||
continue;
|
||||
@@ -124,7 +125,7 @@ export function selectChecks(paths, event = 'workflow_dispatch') {
|
||||
)
|
||||
enable('macos');
|
||||
if (
|
||||
/^desktop\/(package\.json|pnpm-(lock|workspace)\.yaml|main\/(settings|windows-update)\.mjs|runtime\/(index\.mjs|windows\.mjs|protect-profile\.ps1)|scripts\/(drop-admin-privileges\.ps1|check-windows-updates\.mjs|prepare-windows-electron\.mjs|windows-installer\.nsi)|test\/settings\.test\.mjs)$/.test(
|
||||
/^desktop\/(package\.json|pnpm-(lock|workspace)\.yaml|main\/(settings|windows-update)\.mjs|runtime\/(index\.mjs|windows\.mjs|database\.mjs|protect-profile\.ps1)|scripts\/(drop-admin-privileges\.ps1|check-windows-updates\.mjs|postgres-binaries\.mjs|prepare-windows-electron\.mjs|windows-installer\.nsi)|test\/settings\.test\.mjs)$/.test(
|
||||
path,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -53,6 +53,7 @@ test('container and native checks follow their inputs', () => {
|
||||
assert.equal(selectChecks(['src/server/vault-crypto.ts']).windows, true);
|
||||
assert.equal(selectChecks(['desktop/main/settings.mjs']).macos, true);
|
||||
assert.equal(selectChecks(['desktop/main/settings.mjs']).windows, true);
|
||||
assert.equal(selectChecks(['desktop/runtime/database.mjs']).windows, true);
|
||||
assert.equal(selectChecks(['desktop/ui/setup.tsx']).macos, false);
|
||||
assert.equal(selectChecks(['desktop/runtime/index.mjs']).network, true);
|
||||
assert.equal(selectChecks(['desktop/runtime/index.mjs']).desktop, true);
|
||||
|
||||
@@ -128,6 +128,9 @@ jobs:
|
||||
fi
|
||||
sudo ln -s "$PWD" /app
|
||||
mkdir -p "$RUNNER_TEMP/integration-timings"
|
||||
- name: Fetch the pinned PostgreSQL build for host database tests
|
||||
if: steps.scope.outputs.integration == 'true'
|
||||
run: node desktop/scripts/postgres-binaries.mjs
|
||||
- name: Install desktop tooling without downloading Electron
|
||||
if: steps.scope.outputs.desktop == 'true'
|
||||
env:
|
||||
@@ -375,6 +378,10 @@ jobs:
|
||||
tests/integrations.test.ts
|
||||
- name: Check local file rules on Windows
|
||||
run: pnpm exec tsx --test --test-name-pattern="local file rules" tests/sandbox.test.ts
|
||||
- name: Fetch the pinned PostgreSQL build for Windows
|
||||
run: node desktop/scripts/postgres-binaries.mjs
|
||||
- name: Check the host database on Windows
|
||||
run: pnpm exec tsx --test tests/desktop-database.test.ts
|
||||
- name: Execute the PowerShell installer fixtures
|
||||
shell: pwsh
|
||||
run: >-
|
||||
|
||||
@@ -30,6 +30,8 @@ on:
|
||||
- 'desktop/scripts/release-tools.mjs'
|
||||
- 'desktop/scripts/runtime-build-lock.json'
|
||||
- 'desktop/runtime/assets.mjs'
|
||||
- 'desktop/runtime/database.mjs'
|
||||
- 'desktop/scripts/postgres-binaries.mjs'
|
||||
- 'desktop/test/*linux*.test.mjs'
|
||||
- 'desktop/test/runtime-assets.test.mjs'
|
||||
|
||||
@@ -149,6 +151,17 @@ jobs:
|
||||
await pool.end();
|
||||
const sharp = (await import("sharp")).default;
|
||||
await sharp({ create: { width: 2, height: 2, channels: 4, background: "#ff0000" } }).png().toBuffer();
|
||||
const { mkdtemp } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const { openDatabase } = await import("./desktop/runtime/database.mjs");
|
||||
const database = await openDatabase({ dataRoot: await mkdtemp(join(tmpdir(), "nod-flatpak-")), resourcesPath: process.cwd() });
|
||||
const { default: pg } = await import("pg");
|
||||
const client = new pg.Client({ connectionString: database.url });
|
||||
await client.connect();
|
||||
await client.query("CREATE TABLE flatpak_check (value text)");
|
||||
await client.end();
|
||||
await database.close();
|
||||
'
|
||||
- name: Check power services through the installed Flatpak
|
||||
run: /usr/bin/python3 desktop/scripts/check-linux-power.py
|
||||
|
||||
@@ -14,3 +14,4 @@ dist/
|
||||
*.log
|
||||
coverage/
|
||||
.astro/
|
||||
/postgres/
|
||||
@@ -0,0 +1,42 @@
|
||||
# PostgreSQL
|
||||
|
||||
Nod runs PostgreSQL 17 on your computer to store your data. The binaries come from
|
||||
[embedded-postgres-binaries](https://github.com/zonkyio/embedded-postgres-binaries), published
|
||||
under the Apache License 2.0. The macOS and Windows builds repackage the PostgreSQL binaries
|
||||
published by EnterpriseDB.
|
||||
|
||||
## PostgreSQL License
|
||||
|
||||
PostgreSQL Database Management System (also known as Postgres, formerly known as Postgres95)
|
||||
|
||||
Portions Copyright (c) 1996-2025, The PostgreSQL Global Development Group
|
||||
|
||||
Portions Copyright (c) 1994, The Regents of the University of California
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its documentation for any
|
||||
purpose, without fee, and without a written agreement is hereby granted, provided that the above
|
||||
copyright notice and this paragraph and the following two paragraphs appear in all copies.
|
||||
|
||||
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
|
||||
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
|
||||
THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
|
||||
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
|
||||
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
|
||||
|
||||
## Bundled libraries
|
||||
|
||||
The binaries include shared libraries that keep their own licenses: ICU (Unicode License),
|
||||
OpenSSL (Apache License 2.0 or OpenSSL License), libxml2 (MIT), zlib (zlib License), LZ4
|
||||
(BSD 2-Clause), Zstandard (BSD), XZ Utils (public domain and 0BSD), MIT Kerberos (MIT),
|
||||
libedit (BSD), OSSP uuid (MIT-style), and GNU libiconv and gettext runtime (LGPL 2.1 or later,
|
||||
dynamically linked).
|
||||
|
||||
The LGPL 2.1 text is at https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. You may replace
|
||||
the libiconv and gettext libraries in the `lib` folder with your own builds. Their source is at
|
||||
https://ftp.gnu.org/gnu/libiconv/ and https://ftp.gnu.org/gnu/gettext/. To get the exact source of
|
||||
the versions Nod ships, open an issue at https://github.com/n8n-io/nod/issues for at least three
|
||||
years after Nod stops shipping them.
|
||||
+100
-60
@@ -15,22 +15,26 @@ export function startupErrorDetails(error, seen = new Set()) {
|
||||
}
|
||||
|
||||
export function createDesktopLifecycle({
|
||||
openDatabase,
|
||||
prepareRuntime,
|
||||
stopRuntime,
|
||||
validateStart,
|
||||
startEngine,
|
||||
stopEngine,
|
||||
onRuntimeStatus,
|
||||
onRuntime,
|
||||
}) {
|
||||
let database;
|
||||
let opened;
|
||||
let runtime;
|
||||
let storage;
|
||||
let warming;
|
||||
let starting;
|
||||
let serving;
|
||||
let installing;
|
||||
let closing;
|
||||
let closed = false;
|
||||
let failure;
|
||||
let cleanupRequired = false;
|
||||
let movedWaiters = [];
|
||||
let choose;
|
||||
const chosen = new Promise((resolve) => {
|
||||
choose = resolve;
|
||||
@@ -41,6 +45,18 @@ export function createDesktopLifecycle({
|
||||
if (closed || signal?.aborted) throw new Error('Nod is closing.');
|
||||
}
|
||||
|
||||
function controlled() {
|
||||
const controller = new AbortController();
|
||||
controllers.add(controller);
|
||||
return controller;
|
||||
}
|
||||
|
||||
function aborted(signal) {
|
||||
return new Promise((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(new Error('Nod is closing.')), { once: true }),
|
||||
);
|
||||
}
|
||||
|
||||
function report(value) {
|
||||
if (closed) return;
|
||||
onRuntimeStatus({
|
||||
@@ -66,56 +82,62 @@ export function createDesktopLifecycle({
|
||||
needsWsl: error.code === 'NOD_WSL_REQUIRED',
|
||||
needsStorage: error.code === 'NOD_COMPUTER_STORAGE_FULL',
|
||||
});
|
||||
if (!closed) onRuntime?.({ error });
|
||||
}
|
||||
|
||||
function storage(signal) {
|
||||
database ??= openDatabase({ signal }).then(
|
||||
(value) => (opened = value),
|
||||
(error) => {
|
||||
database = undefined;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
return database;
|
||||
}
|
||||
|
||||
function moved() {
|
||||
for (const resolve of movedWaiters.splice(0)) resolve();
|
||||
}
|
||||
|
||||
function warmup({ retry = false } = {}) {
|
||||
checkOpen();
|
||||
void serve().catch((error) => {
|
||||
if (!closed) runtimeFailure(error);
|
||||
});
|
||||
return computer({ retry });
|
||||
}
|
||||
|
||||
function computer({ retry = false } = {}) {
|
||||
checkOpen();
|
||||
if (runtime) return Promise.resolve(runtime);
|
||||
if (warming) return warming;
|
||||
if (installing) return installing;
|
||||
if (failure && !retry) return Promise.reject(failure);
|
||||
failure = undefined;
|
||||
const controller = new AbortController();
|
||||
controllers.add(controller);
|
||||
const controller = controlled();
|
||||
warming = Promise.resolve()
|
||||
.then(async () => {
|
||||
const value = await storage(controller.signal);
|
||||
checkOpen(controller.signal);
|
||||
report({ message: 'Setting up Nod on this computer…' });
|
||||
const prepared = await prepareRuntime({
|
||||
signal: controller.signal,
|
||||
onStorageReady: async (preparedStorage) => {
|
||||
await Promise.race([
|
||||
chosen,
|
||||
new Promise((_, reject) =>
|
||||
controller.signal.addEventListener(
|
||||
'abort',
|
||||
() => reject(new Error('Nod is closing.')),
|
||||
{ once: true },
|
||||
),
|
||||
),
|
||||
]);
|
||||
checkOpen(controller.signal);
|
||||
await validateStart();
|
||||
checkOpen(controller.signal);
|
||||
await startEngine({
|
||||
runtime: preparedStorage,
|
||||
signal: controller.signal,
|
||||
pending: true,
|
||||
});
|
||||
storage = preparedStorage;
|
||||
},
|
||||
onStatus: (value) =>
|
||||
database: value,
|
||||
onMoved: moved,
|
||||
onStatus: (status) =>
|
||||
report({
|
||||
message: typeof value === 'string' ? value : value.message,
|
||||
stage: typeof value === 'object' ? (value.stage ?? 'computer') : 'computer',
|
||||
progress: typeof value === 'object' ? value.progress : undefined,
|
||||
secondsLeft: typeof value === 'object' ? value.secondsLeft : undefined,
|
||||
message: typeof status === 'string' ? status : status.message,
|
||||
stage: typeof status === 'object' ? (status.stage ?? 'computer') : 'computer',
|
||||
progress: typeof status === 'object' ? status.progress : undefined,
|
||||
secondsLeft: typeof status === 'object' ? status.secondsLeft : undefined,
|
||||
}),
|
||||
});
|
||||
runtime = prepared;
|
||||
checkOpen(controller.signal);
|
||||
report({ phase: 'ready', stage: 'ready', message: 'Your local computer is ready.' });
|
||||
return runtime;
|
||||
report({ phase: 'ready', stage: 'ready', message: 'Your private computer is ready.' });
|
||||
onRuntime?.({ environment: prepared.environment });
|
||||
return prepared;
|
||||
})
|
||||
.catch((error) => {
|
||||
if ([error.code, error.cause?.code].includes('NOD_RUNTIME_STOP_FAILED'))
|
||||
@@ -130,35 +152,48 @@ export function createDesktopLifecycle({
|
||||
return warming;
|
||||
}
|
||||
|
||||
function serve(options) {
|
||||
checkOpen();
|
||||
if (serving) return serving;
|
||||
const controller = controlled();
|
||||
serving = Promise.resolve()
|
||||
.then(async () => {
|
||||
const value = await storage(controller.signal);
|
||||
checkOpen(controller.signal);
|
||||
if (value.pendingMove) {
|
||||
const waiting = new Promise((resolve) => movedWaiters.push(resolve));
|
||||
await Promise.race([waiting, computer(options), aborted(controller.signal)]);
|
||||
if (value.pendingMove) throw failure ?? new Error('Nod could not move your saved data.');
|
||||
}
|
||||
await Promise.race([chosen, aborted(controller.signal)]);
|
||||
checkOpen(controller.signal);
|
||||
await validateStart();
|
||||
checkOpen(controller.signal);
|
||||
await startEngine({ database: value, signal: controller.signal });
|
||||
})
|
||||
.finally(() => {
|
||||
serving = undefined;
|
||||
controllers.delete(controller);
|
||||
});
|
||||
return serving;
|
||||
}
|
||||
|
||||
function start(options) {
|
||||
checkOpen();
|
||||
choose();
|
||||
if (starting) return starting;
|
||||
const controller = new AbortController();
|
||||
controllers.add(controller);
|
||||
starting = Promise.resolve()
|
||||
.then(async () => {
|
||||
checkOpen(controller.signal);
|
||||
await validateStart();
|
||||
const prepared = await warmup(options);
|
||||
checkOpen(controller.signal);
|
||||
await validateStart();
|
||||
checkOpen(controller.signal);
|
||||
return startEngine({ runtime: prepared, signal: controller.signal });
|
||||
})
|
||||
.finally(() => {
|
||||
starting = undefined;
|
||||
controllers.delete(controller);
|
||||
return validateStart()
|
||||
.then(() => serve(options))
|
||||
.then(() => {
|
||||
if (!runtime && !warming && !installing && (!failure || options?.retry))
|
||||
void computer(options).catch(() => {});
|
||||
});
|
||||
return starting;
|
||||
}
|
||||
|
||||
function install(installer, { warmup: prepare = true } = {}) {
|
||||
checkOpen();
|
||||
if (warming || starting || installing || runtime)
|
||||
if (warming || installing || runtime)
|
||||
throw new Error('Wait for Nod to finish its current setup step.');
|
||||
const controller = new AbortController();
|
||||
controllers.add(controller);
|
||||
const controller = controlled();
|
||||
installing = Promise.resolve()
|
||||
.then(async () => {
|
||||
checkOpen(controller.signal);
|
||||
@@ -175,7 +210,7 @@ export function createDesktopLifecycle({
|
||||
installing = undefined;
|
||||
controllers.delete(controller);
|
||||
})
|
||||
.then(() => (prepare ? warmup({ retry: true }) : undefined));
|
||||
.then(() => (prepare ? computer({ retry: true }) : undefined));
|
||||
return installing;
|
||||
}
|
||||
|
||||
@@ -184,15 +219,20 @@ export function createDesktopLifecycle({
|
||||
closed = true;
|
||||
for (const controller of controllers) controller.abort();
|
||||
closing = (async () => {
|
||||
await Promise.allSettled([warming, starting, installing].filter(Boolean));
|
||||
await Promise.allSettled([warming, serving, installing, database].filter(Boolean));
|
||||
try {
|
||||
await stopEngine();
|
||||
} finally {
|
||||
if (runtime || storage) await (runtime || storage).close?.();
|
||||
else if (cleanupRequired) await stopRuntime?.();
|
||||
runtime = undefined;
|
||||
storage = undefined;
|
||||
cleanupRequired = false;
|
||||
try {
|
||||
if (runtime) await runtime.close?.();
|
||||
else if (cleanupRequired) await stopRuntime?.();
|
||||
runtime = undefined;
|
||||
cleanupRequired = false;
|
||||
} finally {
|
||||
await opened?.close();
|
||||
opened = undefined;
|
||||
database = undefined;
|
||||
}
|
||||
}
|
||||
})().catch((error) => {
|
||||
closing = undefined;
|
||||
@@ -208,7 +248,7 @@ export function createDesktopLifecycle({
|
||||
install,
|
||||
close,
|
||||
get busy() {
|
||||
return Boolean(warming || starting || installing);
|
||||
return Boolean(warming || serving || installing);
|
||||
},
|
||||
};
|
||||
}
|
||||
+190
-65
@@ -25,7 +25,17 @@ import {
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import {
|
||||
access,
|
||||
appendFile,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { homedir, uptime } from 'node:os';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
@@ -228,7 +238,8 @@ let welcomePassed = false;
|
||||
let welcomeNavigation = false;
|
||||
let transferringWelcome;
|
||||
let welcomeTransferError;
|
||||
let engineRuntimeReady = false;
|
||||
let engineReady = false;
|
||||
let computerState;
|
||||
let enginePreferencesReady = false;
|
||||
let preparing;
|
||||
let onboardingCompleted = false;
|
||||
@@ -327,7 +338,45 @@ let chatReadCursors = createChatReadCursorStore(join(profileRoot, 'chat-read-cur
|
||||
});
|
||||
|
||||
const lifecycle = createDesktopLifecycle({
|
||||
prepareRuntime: async ({ signal, onStatus, onStorageReady }) => {
|
||||
openDatabase: async ({ signal }) => {
|
||||
await mkdir(profileRoot, { recursive: true, mode: 0o700 });
|
||||
const started = Date.now();
|
||||
const { openDatabase } = await import(
|
||||
pathToFileURL(join(engineRoot, 'desktop', 'runtime', 'database.mjs')).href
|
||||
);
|
||||
try {
|
||||
const database = await openDatabase({
|
||||
dataRoot: profileRoot,
|
||||
resourcesPath: engineRoot,
|
||||
signal,
|
||||
onEvent: ({ event, error, details }) =>
|
||||
void writeDiagnostic(
|
||||
[
|
||||
event === 'database_restarted'
|
||||
? 'Database restarted after it stopped.'
|
||||
: 'Database restart failed.',
|
||||
details,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n'),
|
||||
{ event, ...(error ? { error } : {}) },
|
||||
).catch(() => {}),
|
||||
});
|
||||
knownSecrets.add(database.password);
|
||||
await writeDiagnostic(`Database opened. ${diagnosticFields({ ms: Date.now() - started })}`, {
|
||||
event: 'database_ready',
|
||||
durationMs: Date.now() - started,
|
||||
}).catch(() => {});
|
||||
return database;
|
||||
} catch (error) {
|
||||
await writeDiagnostic(
|
||||
`Database failed. ${diagnosticFields({ code: error.code, ms: Date.now() - started })}`,
|
||||
{ event: 'database_failed', error, durationMs: Date.now() - started },
|
||||
).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
prepareRuntime: async ({ signal, onStatus, database, onMoved }) => {
|
||||
await mkdir(profileRoot, { recursive: true, mode: 0o700 });
|
||||
await writeDiagnostic('Preparing local runtime.', { event: 'runtime_prepare' }).catch(() => {});
|
||||
const started = Date.now();
|
||||
@@ -349,9 +398,14 @@ const lifecycle = createDesktopLifecycle({
|
||||
step = typeof value === 'string' ? value : value?.message;
|
||||
onStatus(value);
|
||||
},
|
||||
onStorageReady: async (storage) => {
|
||||
database,
|
||||
onMoved: async () => {
|
||||
phase = 'engine';
|
||||
await onStorageReady(storage);
|
||||
await writeDiagnostic(
|
||||
`Saved data moved. ${diagnosticFields({ ms: Date.now() - started })}`,
|
||||
{ event: 'database_moved', durationMs: Date.now() - started },
|
||||
).catch(() => {});
|
||||
await onMoved();
|
||||
phase = 'runtime';
|
||||
},
|
||||
});
|
||||
@@ -389,6 +443,7 @@ const lifecycle = createDesktopLifecycle({
|
||||
() => {},
|
||||
);
|
||||
if (
|
||||
!engineReady &&
|
||||
preparing &&
|
||||
!engineFailure &&
|
||||
!welcomeTransferError &&
|
||||
@@ -404,14 +459,70 @@ const lifecycle = createDesktopLifecycle({
|
||||
secondsLeft: value.secondsLeft,
|
||||
needsRuntimeArchive: false,
|
||||
});
|
||||
else
|
||||
update({
|
||||
runtime,
|
||||
...(runtime.phase === 'error' ? { error: runtime.message, details: runtime.details } : {}),
|
||||
});
|
||||
else update({ runtime });
|
||||
},
|
||||
onRuntime: (value) => {
|
||||
computerState = value.error
|
||||
? {
|
||||
error: {
|
||||
code: typeof value.error.code === 'string' ? value.error.code : undefined,
|
||||
message: bounded(value.error.message),
|
||||
},
|
||||
}
|
||||
: { environment: value.environment };
|
||||
sendComputerState();
|
||||
preloadPendingUpdate();
|
||||
if (engineReady && computerState.error?.code === 'NOD_WSL_REQUIRED') void installWslOnce();
|
||||
},
|
||||
});
|
||||
|
||||
let wslInstall;
|
||||
let wslInstalled = false;
|
||||
|
||||
async function installWslOnce() {
|
||||
if (process.platform !== 'win32' || remoteConnection || quitting) return;
|
||||
if (!welcomePassed && !onboardingCompleted) return;
|
||||
if (wslInstalled) {
|
||||
update({
|
||||
runtime: {
|
||||
...status.runtime,
|
||||
message:
|
||||
'Restart your PC to finish installing WSL. Nod’s browser and workspace start after that.',
|
||||
needsWsl: false,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (wslInstall) return;
|
||||
const marker = join(profileRoot, 'wsl-install.json');
|
||||
wslInstall = (async () => {
|
||||
if (
|
||||
await access(marker).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
)
|
||||
return;
|
||||
await writeFile(marker, JSON.stringify({ requestedAt: new Date().toISOString() }), {
|
||||
mode: 0o600,
|
||||
});
|
||||
const { installWsl } = await import(
|
||||
pathToFileURL(join(engineRoot, 'desktop/runtime/windows.mjs')).href
|
||||
);
|
||||
await lifecycle.install(async (options) => {
|
||||
await installWsl(options);
|
||||
wslInstalled = true;
|
||||
});
|
||||
})().catch(
|
||||
(error) => void writeDiagnostic(`WSL install failed. ${error.message}`).catch(() => {}),
|
||||
);
|
||||
}
|
||||
|
||||
function sendComputerState() {
|
||||
if (engine && engineReady && computerState)
|
||||
engine.postMessage({ type: 'nod-runtime', ...computerState });
|
||||
}
|
||||
|
||||
const readinessNotice = createReadinessNotice({
|
||||
notify: async (eligible) => {
|
||||
const saved = await appPreferences.get();
|
||||
@@ -420,9 +531,7 @@ const readinessNotice = createReadinessNotice({
|
||||
const notification = new Notification({
|
||||
title: 'Nod is ready',
|
||||
icon: notificationIcon,
|
||||
body: onboardingCompleted
|
||||
? 'Your workspace and browser are ready.'
|
||||
: 'Your computer is ready. Come back to finish setup.',
|
||||
body: onboardingCompleted ? 'You can chat with Nod now.' : 'Come back to finish setup.',
|
||||
});
|
||||
displayedNotifications.add(notification);
|
||||
notification.on('show', () => {
|
||||
@@ -451,13 +560,13 @@ function focusedEngineWindow() {
|
||||
|
||||
function updateReadinessNotice() {
|
||||
void readinessNotice.update({
|
||||
runtimePhase: engineRuntimeReady ? status.runtime.phase : 'preparing',
|
||||
runtimePhase: engineReady ? 'ready' : 'preparing',
|
||||
guided: guidedStartup,
|
||||
enabled: preferences.notifications,
|
||||
foreground: foregroundWindow(),
|
||||
quitting,
|
||||
completed: onboardingCompleted,
|
||||
engineReady: Boolean(engine) && engineRuntimeReady && status.phase === 'ready',
|
||||
engineReady: Boolean(engine) && engineReady && status.phase === 'ready',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -932,6 +1041,11 @@ function allowSetup(event) {
|
||||
if (!isSetup(event)) throw new Error('This action is unavailable.');
|
||||
}
|
||||
|
||||
function allowLocalRuntime(event) {
|
||||
if (!isSetup(event) && !(isEngine(event) && !remoteConnection))
|
||||
throw new Error('This action is unavailable.');
|
||||
}
|
||||
|
||||
async function openExternal(value) {
|
||||
let url;
|
||||
try {
|
||||
@@ -1172,7 +1286,7 @@ function showEngine({ focus = true } = {}) {
|
||||
if (
|
||||
!enginePreferencesReady ||
|
||||
!engineOrigin ||
|
||||
(onboardingCompleted && !engineRuntimeReady) ||
|
||||
(onboardingCompleted && !engineReady) ||
|
||||
(!onboardingCompleted && !welcomePassed)
|
||||
) {
|
||||
showSettings('general', true);
|
||||
@@ -1876,7 +1990,7 @@ async function startRemote(connection) {
|
||||
authToken = connected.token;
|
||||
engineBound = true;
|
||||
enginePreferencesReady = true;
|
||||
engineRuntimeReady = true;
|
||||
engineReady = true;
|
||||
onboardingCompleted = true;
|
||||
welcomePassed = true;
|
||||
const id = createHash('sha256').update(`${connected.url}\0${connected.owner}`).digest('hex');
|
||||
@@ -1957,7 +2071,7 @@ async function stopEngine() {
|
||||
void computerHelper.cancel().catch(() => {});
|
||||
stayAwake(false);
|
||||
enginePreferencesReady = false;
|
||||
engineRuntimeReady = false;
|
||||
engineReady = false;
|
||||
stopNotifications?.();
|
||||
stopNotifications = undefined;
|
||||
unreadBadge?.stop();
|
||||
@@ -2019,9 +2133,10 @@ async function transferWelcome() {
|
||||
welcomeNavigation = true;
|
||||
welcomePassed = true;
|
||||
welcomeTransferError = undefined;
|
||||
if (computerState?.error?.code === 'NOD_WSL_REQUIRED') void installWslOnce();
|
||||
update({
|
||||
phase: engineRuntimeReady ? 'ready' : 'preparing',
|
||||
message: engineRuntimeReady ? 'Nod is running on your computer.' : status.runtime.message,
|
||||
phase: engineReady ? 'ready' : 'preparing',
|
||||
message: engineReady ? 'Nod is running on your computer.' : status.runtime.message,
|
||||
error: undefined,
|
||||
});
|
||||
if (pendingFeedback || foregroundWindow()) showEngine();
|
||||
@@ -2136,40 +2251,41 @@ async function reconcileLocalSetup(required = false) {
|
||||
updateReadinessNotice();
|
||||
}
|
||||
|
||||
async function finishEnginePreparation(pending = false) {
|
||||
async function finishEnginePreparation() {
|
||||
await appPreferences.sync();
|
||||
if (quitting || !engine) throw new Error(engineFailure || 'Nod is closing.');
|
||||
await reconcileLocalSetup();
|
||||
if (quitting || !engine) throw new Error(engineFailure || 'Nod is closing.');
|
||||
if (!pending && !engineRuntimeReady) {
|
||||
engine.postMessage({ type: 'nod-runtime-ready' });
|
||||
engineRuntimeReady = true;
|
||||
}
|
||||
engineReady = true;
|
||||
sendComputerState();
|
||||
if (computerState?.error?.code === 'NOD_WSL_REQUIRED') void installWslOnce();
|
||||
update({
|
||||
phase: pending ? 'preparing' : 'ready',
|
||||
stage: pending ? status.runtime.stage : 'ready',
|
||||
message: pending ? status.runtime.message : 'Nod is running on your computer.',
|
||||
progress: pending ? status.runtime.progress : undefined,
|
||||
secondsLeft: pending ? status.runtime.secondsLeft : undefined,
|
||||
phase: 'ready',
|
||||
stage: 'ready',
|
||||
message: 'Nod is running on your computer.',
|
||||
progress: undefined,
|
||||
secondsLeft: undefined,
|
||||
engineReady: true,
|
||||
});
|
||||
if (!welcomeTransferError) await transferWelcome().catch(() => {});
|
||||
if (welcomeTransferError)
|
||||
update({ phase: 'error', error: welcomeTransferError, message: welcomeTransferError });
|
||||
if ((!pending && onboardingCompleted) || welcomePassed) {
|
||||
if (onboardingCompleted || welcomePassed) {
|
||||
if (pendingFeedback || foregroundWindow()) showEngine();
|
||||
else if (setupWindow && !setupWindow.isDestroyed()) showEngine({ focus: false });
|
||||
}
|
||||
synchronizeNotifications();
|
||||
if (!pending && pendingPreload) {
|
||||
const assets = pendingPreload;
|
||||
pendingPreload = undefined;
|
||||
void preloadUpdateImages(assets);
|
||||
}
|
||||
updateReadinessNotice();
|
||||
return status;
|
||||
}
|
||||
|
||||
function preloadPendingUpdate() {
|
||||
if (!pendingPreload || !computerState?.environment) return;
|
||||
const assets = pendingPreload;
|
||||
pendingPreload = undefined;
|
||||
void preloadUpdateImages(assets);
|
||||
}
|
||||
|
||||
function reportUpdateStatus(phase, progress) {
|
||||
if (['checking', 'preparing', 'downloading'].includes(phase)) updateStep = phase;
|
||||
const percent = Number.isFinite(progress)
|
||||
@@ -2838,12 +2954,12 @@ async function validateStart() {
|
||||
if (quitting) throw new Error('Nod is closing.');
|
||||
}
|
||||
|
||||
async function startEngine({ runtime, signal, pending = false }) {
|
||||
async function startEngine({ database, signal }) {
|
||||
void writeDiagnostic('Starting the background service.', { event: 'engine_start' }).catch(
|
||||
() => {},
|
||||
);
|
||||
if (engineFailure) throw new Error(engineFailure);
|
||||
if (engine && enginePreferencesReady) return finishEnginePreparation(pending);
|
||||
if (engine && enginePreferencesReady) return finishEnginePreparation();
|
||||
if (engine) {
|
||||
if (!(await confirmRestart()))
|
||||
throw Object.assign(new Error('Restart Nod when it finishes its current work.'), {
|
||||
@@ -2874,7 +2990,11 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
const providerEnvironment = await settings.environment();
|
||||
const owner = await profileOwner();
|
||||
if (providerEnvironment.NOD_VAULT_KEY) knownSecrets.add(providerEnvironment.NOD_VAULT_KEY);
|
||||
if (runtime.env.DATABASE_URL) knownSecrets.add(runtime.env.DATABASE_URL);
|
||||
knownSecrets.add(database.url);
|
||||
const { computerNames } = await import(
|
||||
pathToFileURL(join(engineRoot, 'desktop', 'runtime', 'index.mjs')).href
|
||||
);
|
||||
const containers = computerNames(profileRoot);
|
||||
const { nodBuild } = JSON.parse(await readFile(join(desktopRoot, 'package.json'), 'utf8'));
|
||||
const tracesToken =
|
||||
typeof nodBuild?.tracesToken === 'string' ? nodBuild.tracesToken : process.env.NOD_TRACES_TOKEN;
|
||||
@@ -2884,7 +3004,9 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
const started = Date.now();
|
||||
const environment = {
|
||||
...baseEnvironment(),
|
||||
...runtime.env,
|
||||
DATABASE_URL: database.url,
|
||||
BROWSER_CONTAINER: containers.browser,
|
||||
WORKSPACE_CONTAINER: containers.workspace,
|
||||
...providerEnvironment,
|
||||
NODE_ENV: 'production',
|
||||
PORT: String(port),
|
||||
@@ -2897,7 +3019,6 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
NOD_OS_VERSION: process.getSystemVersion(),
|
||||
NOD_DESKTOP_OWNER_ID: owner,
|
||||
NOD_DESKTOP_AUTH_TOKEN: authToken,
|
||||
NOD_DESKTOP_RUNTIME_PENDING: 'true',
|
||||
NOD_ANALYTICS_ENABLED: String(!testInstall && analytics.enabled),
|
||||
NOD_ANALYTICS_ENVIRONMENT: analyticsEnvironment(nodBuild),
|
||||
NOD_PUBLIC_URL: engineOrigin,
|
||||
@@ -2954,7 +3075,7 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
let diagnostics = '';
|
||||
let failure = '';
|
||||
child.stderr?.on('data', (chunk) => {
|
||||
if (enginePreferencesReady && engineRuntimeReady) return;
|
||||
if (enginePreferencesReady && engineReady) return;
|
||||
diagnostics = (diagnostics + chunk.toString()).slice(-4000);
|
||||
const lines = diagnostics.split('\n');
|
||||
diagnostics = lines.pop() || '';
|
||||
@@ -2973,7 +3094,6 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
if (!closingEngine)
|
||||
failure =
|
||||
(status.phase === 'error' && status.error) ||
|
||||
(status.runtime.phase === 'error' && status.runtime.message) ||
|
||||
failure ||
|
||||
`Nod’s background service stopped${enginePreferencesReady ? '' : ' before it was ready'}${Number.isInteger(code) ? ` (code ${code})` : ''}. Try again to restart it.`;
|
||||
stopNotifications?.({ clear: closingEngine || quitting });
|
||||
@@ -2992,7 +3112,7 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
engineOrigin = '';
|
||||
engineBound = false;
|
||||
authToken = '';
|
||||
engineRuntimeReady = false;
|
||||
engineReady = false;
|
||||
update({ engineReady: false });
|
||||
if (status.phase !== 'updating') {
|
||||
void persistCurrentZoomFactor().catch(
|
||||
@@ -3056,7 +3176,7 @@ async function startEngine({ runtime, signal, pending = false }) {
|
||||
);
|
||||
}
|
||||
enginePreferencesReady = true;
|
||||
return finishEnginePreparation(pending);
|
||||
return finishEnginePreparation();
|
||||
}
|
||||
|
||||
async function prepare(options = {}) {
|
||||
@@ -3089,7 +3209,8 @@ async function prepare(options = {}) {
|
||||
needsRuntimeArchive: false,
|
||||
needsStorage: false,
|
||||
});
|
||||
return lifecycle.start({ retry: options?.retry === true });
|
||||
await lifecycle.start({ retry: options?.retry === true });
|
||||
return status;
|
||||
})()
|
||||
.catch((error) => {
|
||||
void writeDiagnostic(
|
||||
@@ -3139,10 +3260,10 @@ function replayOnboarding() {
|
||||
return status;
|
||||
}
|
||||
|
||||
async function chooseComputerDirectory() {
|
||||
async function chooseComputerDirectory(parent = setupWindow) {
|
||||
if (process.platform !== 'win32' || lifecycle.busy || quitting || !status.runtime.needsStorage)
|
||||
throw new Error('This setup action is unavailable.');
|
||||
const chosen = await dialog.showOpenDialog(setupWindow, {
|
||||
const chosen = await dialog.showOpenDialog(parent, {
|
||||
title: 'Choose a folder for Nod’s private computer',
|
||||
buttonLabel: 'Use this folder',
|
||||
properties: ['openDirectory', 'createDirectory'],
|
||||
@@ -3160,9 +3281,9 @@ async function chooseComputerDirectory() {
|
||||
return prepare({ retry: true });
|
||||
}
|
||||
|
||||
async function importRuntime() {
|
||||
async function importRuntime(parent = setupWindow) {
|
||||
if (lifecycle.busy || quitting) throw new Error('Wait for Nod to finish its current setup step.');
|
||||
const chosen = await dialog.showOpenDialog(setupWindow, {
|
||||
const chosen = await dialog.showOpenDialog(parent, {
|
||||
title: 'Choose the Nod Runtime pack',
|
||||
buttonLabel: 'Install runtime',
|
||||
properties: ['openFile'],
|
||||
@@ -3185,7 +3306,7 @@ async function importRuntime() {
|
||||
return prepare();
|
||||
} catch (error) {
|
||||
void writeDiagnostic(error.message).catch(() => {});
|
||||
if (onboardingCompleted)
|
||||
if (onboardingCompleted && !engineReady)
|
||||
update({
|
||||
phase: 'error',
|
||||
message: bounded(error.message),
|
||||
@@ -3328,7 +3449,7 @@ else {
|
||||
});
|
||||
void updateEvent('download-finished', { version, target: 'runtime', verified: true });
|
||||
report('preparing');
|
||||
if (!engine || closingEngine) pendingPreload = assets;
|
||||
if (!computerState?.environment || closingEngine) pendingPreload = assets;
|
||||
else await preloadUpdateImages(assets, signal);
|
||||
},
|
||||
restart: restartForUpdate,
|
||||
@@ -3694,8 +3815,11 @@ else {
|
||||
showEngine();
|
||||
if (enginePreferencesReady && status.runtime.phase !== 'error') return status;
|
||||
}
|
||||
if (engineRuntimeReady || (!options?.retry && enginePreferencesReady && preparing))
|
||||
if (engineReady && options?.retry === true && status.runtime.phase === 'error') {
|
||||
void lifecycle.warmup({ retry: true }).catch(() => {});
|
||||
return status;
|
||||
}
|
||||
if (engineReady || (!options?.retry && enginePreferencesReady && preparing)) return status;
|
||||
return prepare(options);
|
||||
});
|
||||
ipcMain.handle('nod:warmup', async (event) => {
|
||||
@@ -3706,14 +3830,15 @@ else {
|
||||
void lifecycle.warmup().catch(() => {});
|
||||
});
|
||||
ipcMain.handle('nod:runtime:import', (event) => {
|
||||
allowSetup(event);
|
||||
return importRuntime();
|
||||
allowLocalRuntime(event);
|
||||
return importRuntime(BrowserWindow.fromWebContents(event.sender) ?? setupWindow);
|
||||
});
|
||||
ipcMain.handle('nod:runtime:install-wsl', async (event) => {
|
||||
allowSetup(event);
|
||||
allowLocalRuntime(event);
|
||||
if (process.platform !== 'win32' || lifecycle.busy || quitting || !status.runtime.needsWsl)
|
||||
throw new Error('This setup action is unavailable.');
|
||||
const { response } = await dialog.showMessageBox(setupWindow, {
|
||||
const parent = BrowserWindow.fromWebContents(event.sender) ?? setupWindow;
|
||||
const { response } = await dialog.showMessageBox(parent, {
|
||||
type: 'question',
|
||||
message: 'Install Windows Subsystem for Linux?',
|
||||
detail:
|
||||
@@ -3728,17 +3853,17 @@ else {
|
||||
pathToFileURL(join(engineRoot, 'desktop/runtime/windows.mjs')).href
|
||||
);
|
||||
await lifecycle.install(installWsl, { warmup: false });
|
||||
update({
|
||||
phase: 'error',
|
||||
message: 'Restart your PC, then open Nod again.',
|
||||
error: 'Restart your PC, then open Nod again.',
|
||||
needsWsl: false,
|
||||
});
|
||||
const restart = 'Restart your PC, then open Nod again.';
|
||||
if (engineReady)
|
||||
update({
|
||||
runtime: { ...status.runtime, phase: 'error', message: restart, needsWsl: false },
|
||||
});
|
||||
else update({ phase: 'error', message: restart, error: restart, needsWsl: false });
|
||||
return status;
|
||||
});
|
||||
ipcMain.handle('nod:runtime:choose-folder', (event) => {
|
||||
allowSetup(event);
|
||||
return chooseComputerDirectory();
|
||||
allowLocalRuntime(event);
|
||||
return chooseComputerDirectory(BrowserWindow.fromWebContents(event.sender) ?? setupWindow);
|
||||
});
|
||||
ipcMain.handle('nod:chat-read:get', (event, ownerId, threadId) => {
|
||||
if (!isEngine(event)) throw new Error('This action is unavailable.');
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"description": "Nod, the open source personal agent from n8n",
|
||||
"scripts": {
|
||||
"postinstall": "node scripts/patch-osx-sign.mjs",
|
||||
"start": "electron .",
|
||||
"start": "node scripts/postgres-binaries.mjs && electron .",
|
||||
"build": "node scripts/build-app.mjs",
|
||||
"test": "node --test test/*.test.mjs"
|
||||
},
|
||||
|
||||
@@ -52,6 +52,9 @@ const localRuntime = remote
|
||||
return () => ipcRenderer.removeListener('nod:status', receive);
|
||||
},
|
||||
prepare: (options) => invoke('nod:prepare', options),
|
||||
installWsl: () => invoke('nod:runtime:install-wsl'),
|
||||
importRuntime: () => invoke('nod:runtime:import'),
|
||||
chooseComputerDirectory: () => invoke('nod:runtime:choose-folder'),
|
||||
setup: () => invoke('nod:setup:get'),
|
||||
completePreferences: () => invoke('nod:setup:preferences'),
|
||||
reconcileSetup: () => invoke('nod:setup:reconcile'),
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import {
|
||||
access,
|
||||
appendFile,
|
||||
mkdir,
|
||||
open,
|
||||
readdir,
|
||||
readFile,
|
||||
rename,
|
||||
rm,
|
||||
statfs,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { availablePort, execute } from './index.mjs';
|
||||
|
||||
const stateVersion = 1;
|
||||
|
||||
function toolEnvironment() {
|
||||
if (process.platform !== 'win32') return { PATH: '/usr/bin:/bin', HOME: homedir() };
|
||||
const environment = Object.fromEntries(
|
||||
['SYSTEMROOT', 'USERPROFILE', 'LOCALAPPDATA', 'TEMP', 'TMP'].flatMap((key) =>
|
||||
process.env[key] ? [[key, process.env[key]]] : [],
|
||||
),
|
||||
);
|
||||
environment.PATH = join(environment.SYSTEMROOT || 'C:\\Windows', 'System32');
|
||||
return environment;
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
return access(path).then(
|
||||
() => true,
|
||||
(error) => {
|
||||
if (error.code === 'ENOENT') return false;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function writeState(path, state) {
|
||||
const temporary = `${path}.${randomBytes(6).toString('hex')}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify(state), { mode: 0o600, flag: 'wx', flush: true });
|
||||
await rename(temporary, path);
|
||||
}
|
||||
|
||||
async function readState(path) {
|
||||
let state;
|
||||
try {
|
||||
state = JSON.parse(await readFile(path, 'utf8'));
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return undefined;
|
||||
throw Object.assign(new Error('Nod could not read its database settings.', { cause: error }), {
|
||||
code: 'NOD_DATABASE_STATE_INVALID',
|
||||
});
|
||||
}
|
||||
if (
|
||||
state?.version !== stateVersion ||
|
||||
!/^[a-f0-9]{64}$/.test(state.password) ||
|
||||
typeof state.ready !== 'boolean'
|
||||
)
|
||||
throw Object.assign(new Error('Nod’s database settings are invalid.'), {
|
||||
code: 'NOD_DATABASE_STATE_INVALID',
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
async function computerDatabaseExists(dataRoot) {
|
||||
try {
|
||||
const saved = JSON.parse(
|
||||
await readFile(join(dataRoot, 'desktop-runtime', 'state.json'), 'utf8'),
|
||||
);
|
||||
return saved?.initializing !== true;
|
||||
} catch (error) {
|
||||
return error.code !== 'ENOENT';
|
||||
}
|
||||
}
|
||||
|
||||
async function logTail(path) {
|
||||
const text = await readFile(path, 'utf8').catch(() => '');
|
||||
return text.slice(-4000);
|
||||
}
|
||||
|
||||
const requiredSpace = 256 * 1024 * 1024;
|
||||
|
||||
function failure(code, message, cause, details) {
|
||||
return Object.assign(new Error(message, { cause }), {
|
||||
code,
|
||||
details: [cause?.details || cause?.stack || cause?.message, details].filter(Boolean).join('\n'),
|
||||
});
|
||||
}
|
||||
|
||||
async function checkSpace(path, bytes = 0, purpose = 'for its database') {
|
||||
const required = requiredSpace + bytes;
|
||||
const { bavail, bsize } = await statfs(path).catch(() => ({ bavail: Infinity, bsize: 1 }));
|
||||
if (bavail * bsize < required)
|
||||
throw failure(
|
||||
'NOD_DATABASE_STORAGE_FULL',
|
||||
`Nod needs about ${Math.round(required / 1024 / 1024)} MB of free disk space ${purpose}. Free some space, then try again.`,
|
||||
);
|
||||
}
|
||||
|
||||
async function nativePath(path) {
|
||||
if (process.platform !== 'win32' || /^[\x20-\x7e]*$/.test(path)) return path;
|
||||
const env = toolEnvironment();
|
||||
const short = await execute(
|
||||
join(env.SYSTEMROOT || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
'(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:NOD_LONG_PATH).ShortPath',
|
||||
],
|
||||
{ env: { ...env, NOD_LONG_PATH: path }, timeout: 60_000 },
|
||||
).catch(() => '');
|
||||
return /^[\x20-\x7e]+$/.test(short) ? short : path;
|
||||
}
|
||||
|
||||
async function connect(port, password, database) {
|
||||
const { default: pg } = await import('pg');
|
||||
const client = new pg.Client({
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
user: 'nod',
|
||||
password,
|
||||
database,
|
||||
connectionTimeoutMillis: 10_000,
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
} catch (error) {
|
||||
await client.end().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
function alive(pid) {
|
||||
if (!Number.isSafeInteger(pid) || pid < 1) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return error.code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
async function lockOwner(data) {
|
||||
const lock = await readFile(join(data, 'postmaster.pid'), 'utf8').catch(() => undefined);
|
||||
if (lock === undefined) return undefined;
|
||||
const lines = lock.split('\n');
|
||||
return { pid: Number(lines[0]), port: Number(lines[3]) };
|
||||
}
|
||||
|
||||
async function stopLeftover({ data, password, pgCtl, env, signal }) {
|
||||
const lock = await lockOwner(data);
|
||||
if (!lock) return;
|
||||
for (let attempt = 0; alive(lock.pid) && attempt < 30; attempt++) {
|
||||
const client = await connect(lock.port, password, 'postgres').catch((error) => {
|
||||
if (error.code !== '57P03') return null;
|
||||
});
|
||||
if (client === null) break;
|
||||
if (client) {
|
||||
const directory = await client
|
||||
.query("SELECT current_setting('data_directory') AS value")
|
||||
.then(
|
||||
(result) => result.rows[0].value,
|
||||
() => undefined,
|
||||
)
|
||||
.finally(() => client.end().catch(() => {}));
|
||||
if (directory && resolve(directory).toLowerCase() === resolve(data).toLowerCase()) {
|
||||
await execute(
|
||||
pgCtl,
|
||||
['stop', '--pgdata', data, '--mode', 'fast', '--wait', '--timeout', '60'],
|
||||
{ env, signal, timeout: 90_000 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
await delay(1000, undefined, { signal });
|
||||
}
|
||||
await rm(join(data, 'postmaster.pid'), { force: true });
|
||||
}
|
||||
|
||||
export async function openDatabase({ dataRoot, resourcesPath, signal, onEvent }) {
|
||||
const root = join(resolve(dataRoot), 'database');
|
||||
const statePath = join(root, 'state.json');
|
||||
const env = toolEnvironment();
|
||||
await mkdir(root, { recursive: true, mode: 0o700 });
|
||||
for (const entry of await readdir(root))
|
||||
if (/\.[a-f0-9]{12}\.(?:tmp|password)$/.test(entry))
|
||||
await rm(join(root, entry), { recursive: true, force: true });
|
||||
let state = await readState(statePath);
|
||||
if (!state) {
|
||||
await checkSpace(root);
|
||||
state = {
|
||||
version: stateVersion,
|
||||
password: randomBytes(32).toString('hex'),
|
||||
ready: !(await computerDatabaseExists(dataRoot)),
|
||||
};
|
||||
await writeState(statePath, state);
|
||||
}
|
||||
const nativeRoot = await nativePath(root);
|
||||
const data = join(nativeRoot, 'data');
|
||||
const log = join(nativeRoot, 'postgres.log');
|
||||
const tools = await nativePath(join(resolve(resourcesPath), 'postgres', 'bin'));
|
||||
const tool = (name) => join(tools, process.platform === 'win32' ? `${name}.exe` : name);
|
||||
const pgCtl = tool('pg_ctl');
|
||||
if (!(await exists(join(data, 'PG_VERSION')))) {
|
||||
await checkSpace(root);
|
||||
const suffix = randomBytes(6).toString('hex');
|
||||
const temporary = join(nativeRoot, `data.${suffix}.tmp`);
|
||||
const passwordFile = join(nativeRoot, `state.${suffix}.password`);
|
||||
await writeFile(passwordFile, `${state.password}\n`, { mode: 0o600, flag: 'wx' });
|
||||
try {
|
||||
await execute(
|
||||
tool('initdb'),
|
||||
[
|
||||
'--pgdata',
|
||||
temporary,
|
||||
'--username',
|
||||
'nod',
|
||||
'--auth',
|
||||
'scram-sha-256',
|
||||
'--pwfile',
|
||||
passwordFile,
|
||||
'--encoding',
|
||||
'UTF8',
|
||||
'--no-locale',
|
||||
'--locale-provider',
|
||||
'builtin',
|
||||
'--builtin-locale',
|
||||
'C.UTF-8',
|
||||
'--no-instructions',
|
||||
],
|
||||
{ env, signal, timeout: 600_000 },
|
||||
);
|
||||
await appendFile(
|
||||
join(temporary, 'postgresql.conf'),
|
||||
"\nlisten_addresses = '127.0.0.1'\nunix_socket_directories = ''\ntimezone = 'UTC'\nlog_timezone = 'UTC'\n",
|
||||
);
|
||||
await rm(data, { recursive: true, force: true });
|
||||
await rename(temporary, data);
|
||||
} catch (cause) {
|
||||
await rm(temporary, { recursive: true, force: true }).catch(() => {});
|
||||
signal?.throwIfAborted();
|
||||
await checkSpace(root);
|
||||
throw failure('NOD_DATABASE_SETUP_FAILED', 'Nod could not create its database.', cause);
|
||||
} finally {
|
||||
await rm(passwordFile, { force: true });
|
||||
}
|
||||
}
|
||||
await stopLeftover({ data, password: state.password, pgCtl, env, signal }).catch(() => {});
|
||||
let port;
|
||||
const start = async (abort) => {
|
||||
abort?.throwIfAborted();
|
||||
await rm(log, { force: true }).catch(() => {});
|
||||
const output = await open(`${log}.start`, 'w');
|
||||
try {
|
||||
const code = await new Promise((resolveStart, reject) => {
|
||||
const child = spawn(
|
||||
pgCtl,
|
||||
[
|
||||
'start',
|
||||
'--pgdata',
|
||||
data,
|
||||
'--log',
|
||||
log,
|
||||
'--wait',
|
||||
'--timeout',
|
||||
'300',
|
||||
'--options',
|
||||
`-p ${port}`,
|
||||
],
|
||||
{ env, stdio: ['ignore', output.fd, output.fd], windowsHide: true },
|
||||
);
|
||||
const stop = () => child.kill();
|
||||
const timer = setTimeout(stop, 330_000);
|
||||
const settle = () => {
|
||||
clearTimeout(timer);
|
||||
abort?.removeEventListener('abort', stop);
|
||||
};
|
||||
abort?.addEventListener('abort', stop, { once: true });
|
||||
child.once('error', (error) => {
|
||||
settle();
|
||||
reject(error);
|
||||
});
|
||||
child.once('exit', (exitCode) => {
|
||||
settle();
|
||||
resolveStart(exitCode);
|
||||
});
|
||||
});
|
||||
abort?.throwIfAborted();
|
||||
if (code !== 0)
|
||||
throw Object.assign(new Error(`pg_ctl start failed (${code ?? 'stopped'}).`), {
|
||||
exitCode: code,
|
||||
details: (await readFile(`${log}.start`, 'utf8').catch(() => '')).slice(-4000),
|
||||
});
|
||||
} finally {
|
||||
await output.close();
|
||||
}
|
||||
};
|
||||
const running = async () => alive((await lockOwner(data))?.pid);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
port = await availablePort();
|
||||
try {
|
||||
await start(signal);
|
||||
break;
|
||||
} catch (cause) {
|
||||
signal?.throwIfAborted();
|
||||
const details = await logTail(log);
|
||||
if (attempt < 3) {
|
||||
await stopLeftover({ data, password: state.password, pgCtl, env, signal }).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
await checkSpace(root);
|
||||
throw failure(
|
||||
'NOD_DATABASE_START_FAILED',
|
||||
'Nod could not start its database.',
|
||||
cause,
|
||||
details,
|
||||
);
|
||||
}
|
||||
}
|
||||
let closing = false;
|
||||
let restarting;
|
||||
let restart;
|
||||
const watchdog = setInterval(() => {
|
||||
restarting ??= running()
|
||||
.then(async (up) => {
|
||||
if (up || closing) return;
|
||||
restart = new AbortController();
|
||||
await start(restart.signal);
|
||||
onEvent?.({ event: 'database_restarted' });
|
||||
})
|
||||
.catch(async (error) => {
|
||||
if (!closing)
|
||||
onEvent?.({ event: 'database_restart_failed', error, details: await logTail(log) });
|
||||
})
|
||||
.finally(() => {
|
||||
restarting = undefined;
|
||||
restart = undefined;
|
||||
});
|
||||
}, 5000);
|
||||
watchdog.unref?.();
|
||||
const close = async () => {
|
||||
closing = true;
|
||||
clearInterval(watchdog);
|
||||
restart?.abort();
|
||||
await restarting;
|
||||
try {
|
||||
await execute(
|
||||
pgCtl,
|
||||
['stop', '--pgdata', data, '--mode', 'fast', '--wait', '--timeout', '60'],
|
||||
{ env, timeout: 90_000 },
|
||||
);
|
||||
} catch (error) {
|
||||
if (await running()) throw error;
|
||||
}
|
||||
};
|
||||
try {
|
||||
const client = await connect(port, state.password, 'postgres');
|
||||
try {
|
||||
if (!(await client.query("SELECT 1 FROM pg_database WHERE datname='nod'")).rowCount)
|
||||
await client.query('CREATE DATABASE nod');
|
||||
} finally {
|
||||
await client.end().catch(() => {});
|
||||
}
|
||||
} catch (cause) {
|
||||
await close().catch(() => {});
|
||||
throw failure(
|
||||
'NOD_DATABASE_CONNECTION_FAILED',
|
||||
'Nod could not open its database.',
|
||||
cause,
|
||||
await logTail(log),
|
||||
);
|
||||
}
|
||||
return {
|
||||
url: `postgresql://nod:${state.password}@127.0.0.1:${port}/nod`,
|
||||
password: state.password,
|
||||
get pendingMove() {
|
||||
return !state.ready;
|
||||
},
|
||||
ensureSpace: (bytes) => checkSpace(root, bytes * 2, 'to move your saved data'),
|
||||
async moved() {
|
||||
state = { ...state, ready: true };
|
||||
await writeState(statePath, state);
|
||||
},
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
const restrictLine = /^\\(?:un)?restrict [A-Za-z0-9]+$/gm;
|
||||
|
||||
export async function moveDatabase({ source, target, schema, signal, space }) {
|
||||
const { default: pg } = await import('pg');
|
||||
const { from: copyFrom, to: copyTo } = await import('pg-copy-streams');
|
||||
const [pre, post] = await Promise.all([schema('pre-data'), schema('post-data')]);
|
||||
const legacy = new pg.Client({ connectionString: source, connectionTimeoutMillis: 10_000 });
|
||||
const host = new pg.Client({ connectionString: target, connectionTimeoutMillis: 10_000 });
|
||||
await legacy.connect();
|
||||
try {
|
||||
await host.connect();
|
||||
try {
|
||||
const copied = await host.query(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')) AS value",
|
||||
);
|
||||
if (copied.rows[0].value) return;
|
||||
await space?.(
|
||||
Number(
|
||||
(await legacy.query('SELECT pg_database_size(current_database())::text AS bytes')).rows[0]
|
||||
.bytes,
|
||||
),
|
||||
);
|
||||
await legacy.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
await host.query('BEGIN');
|
||||
try {
|
||||
await host.query(pre.replace(restrictLine, ''));
|
||||
const tables = (
|
||||
await legacy.query(`
|
||||
SELECT format('%I.%I', n.nspname, c.relname) AS name,
|
||||
string_agg(format('%I', a.attname), ',' ORDER BY a.attnum) AS columns
|
||||
FROM pg_class c
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0
|
||||
AND NOT a.attisdropped AND a.attgenerated = ''
|
||||
WHERE c.relkind = 'r'
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
||||
AND n.nspname NOT LIKE 'pg\\_%'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM pg_depend d
|
||||
WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e'
|
||||
)
|
||||
GROUP BY 1 ORDER BY 1`)
|
||||
).rows;
|
||||
for (const { name, columns } of tables) {
|
||||
signal?.throwIfAborted();
|
||||
await pipeline(
|
||||
legacy.query(copyTo(`COPY ${name} (${columns}) TO STDOUT (FORMAT binary)`)),
|
||||
host.query(copyFrom(`COPY ${name} (${columns}) FROM STDIN (FORMAT binary)`)),
|
||||
{ signal },
|
||||
);
|
||||
const [copied, original] = await Promise.all([
|
||||
host.query(`SELECT count(*)::text AS count FROM ${name}`),
|
||||
legacy.query(`SELECT count(*)::text AS count FROM ${name}`),
|
||||
]);
|
||||
if (copied.rows[0].count !== original.rows[0].count)
|
||||
throw new Error(
|
||||
`The copy of ${name} has ${copied.rows[0].count} rows instead of ${original.rows[0].count}.`,
|
||||
);
|
||||
}
|
||||
const sequences = (
|
||||
await legacy.query(`
|
||||
SELECT format('%I.%I', schemaname, sequencename) AS name
|
||||
FROM pg_sequences
|
||||
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')`)
|
||||
).rows;
|
||||
for (const { name } of sequences) {
|
||||
const sequence = (
|
||||
await legacy.query(`SELECT last_value::text AS value, is_called FROM ${name}`)
|
||||
).rows[0];
|
||||
await host.query('SELECT pg_catalog.setval($1::regclass, $2::bigint, $3)', [
|
||||
name,
|
||||
sequence.value,
|
||||
sequence.is_called,
|
||||
]);
|
||||
}
|
||||
await host.query(post.replace(restrictLine, ''));
|
||||
await host.query('COMMIT');
|
||||
} catch (error) {
|
||||
await host.query('ROLLBACK').catch(() => {});
|
||||
throw error;
|
||||
} finally {
|
||||
await legacy.query('ROLLBACK').catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
await host.end().catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
await legacy.end().catch(() => {});
|
||||
}
|
||||
}
|
||||
+143
-154
@@ -19,6 +19,7 @@ import { cpus as hostCpus, homedir, totalmem } from 'node:os';
|
||||
import { delimiter, join, resolve } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { moveDatabase } from './database.mjs';
|
||||
import { guestConfiguration, protectGuest, protectNetworks } from './guest-config.mjs';
|
||||
import {
|
||||
assetHash,
|
||||
@@ -30,7 +31,6 @@ import {
|
||||
export { installRuntimeArchive } from './assets.mjs';
|
||||
|
||||
const preparing = new Map();
|
||||
const storageReady = new Map();
|
||||
const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
||||
|
||||
async function fileHash(path) {
|
||||
@@ -566,7 +566,8 @@ async function prepare(options, onComputerStart, progress = {}) {
|
||||
signal,
|
||||
status,
|
||||
prepareImage,
|
||||
onStorageReady: options.onStorageReady,
|
||||
database: options.database,
|
||||
onMoved: options.onMoved,
|
||||
runtimeReady: runtimeAssets.done,
|
||||
});
|
||||
}
|
||||
@@ -735,62 +736,35 @@ export async function replaceContainer(
|
||||
}
|
||||
}
|
||||
|
||||
export async function finishRuntime({
|
||||
dataRoot,
|
||||
resourcesPath,
|
||||
assets,
|
||||
manifest,
|
||||
export function computerNames(dataRoot) {
|
||||
const root = resolve(dataRoot);
|
||||
const identity = createHash('sha256')
|
||||
.update(process.platform === 'win32' ? root.toLowerCase() : root)
|
||||
.digest('hex')
|
||||
.slice(0, 12);
|
||||
return {
|
||||
workspace: `nod-workspace-${identity}`,
|
||||
browser: `nod-browser-${identity}`,
|
||||
postgres: `nod-postgres-${identity}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function moveComputerDatabase({
|
||||
database,
|
||||
names,
|
||||
identity,
|
||||
saved,
|
||||
controlRoot,
|
||||
docker,
|
||||
path,
|
||||
dockerEnvironment,
|
||||
runDocker,
|
||||
runGuest,
|
||||
image,
|
||||
images,
|
||||
signal,
|
||||
status,
|
||||
prepareImage,
|
||||
onStorageReady,
|
||||
runtimeReady,
|
||||
}) {
|
||||
status('starting', 'Preparing secure storage and tools…', 'storage');
|
||||
const images = {};
|
||||
const loadImage = (name) => {
|
||||
images[name] = Promise.resolve().then(() => prepareImage?.(name));
|
||||
images[name].catch(() => {});
|
||||
};
|
||||
loadImage('postgres');
|
||||
const names = {
|
||||
workspace: `nod-workspace-${identity}`,
|
||||
browser: `nod-browser-${identity}`,
|
||||
postgres: `nod-postgres-${identity}`,
|
||||
};
|
||||
for (const [role, subnet, bridge] of [
|
||||
['control', '172.31.80.0/24', 'nod-control'],
|
||||
['workspace', '172.31.81.0/24', 'nod-workspace'],
|
||||
['browser', '172.31.82.0/24', 'nod-browser'],
|
||||
]) {
|
||||
const name = `nod-${role}-${identity}`;
|
||||
await ensureNetwork(runDocker, { name, subnet, bridge });
|
||||
}
|
||||
await runGuest(protectNetworks);
|
||||
const volumes = {
|
||||
postgres: `nod-postgres-${identity}`,
|
||||
browser: `nod-browser-${identity}`,
|
||||
workspace: `nod-workspace-${identity}`,
|
||||
tools: `nod-tools-${identity}`,
|
||||
};
|
||||
for (const volume of Object.values(volumes)) await runDocker(['volume', 'create', volume]);
|
||||
const image = (name) => manifest.images.find((item) => item.name === name).id;
|
||||
status('starting', 'Opening your saved data…', 'storage');
|
||||
await images.postgres;
|
||||
loadImage('workspace');
|
||||
loadImage('browser');
|
||||
const storage = storageReady.get(resolve(dataRoot));
|
||||
const port =
|
||||
process.platform === 'win32' ? (storage?.port ?? (await availablePort())) : saved.port;
|
||||
status('starting', 'Starting your database…', 'storage');
|
||||
const postgres = await replaceContainer(
|
||||
const port = process.platform === 'win32' ? await availablePort() : saved.port;
|
||||
await replaceContainer(
|
||||
runDocker,
|
||||
names.postgres,
|
||||
image('postgres'),
|
||||
@@ -810,16 +784,11 @@ export async function finishRuntime({
|
||||
'--env',
|
||||
'POSTGRES_PASSWORD',
|
||||
'--volume',
|
||||
`${volumes.postgres}:/var/lib/postgresql/data`,
|
||||
`nod-postgres-${identity}:/var/lib/postgresql/data`,
|
||||
],
|
||||
{
|
||||
env: { ...dockerEnvironment, POSTGRES_PASSWORD: saved.password },
|
||||
remember: true,
|
||||
reuse: storage?.postgres,
|
||||
},
|
||||
{ env: { ...dockerEnvironment, POSTGRES_PASSWORD: saved.password } },
|
||||
);
|
||||
const databaseUrl = `postgresql://nod:${saved.password}@127.0.0.1:${port}/nod`;
|
||||
status('starting', 'Waiting for your database to be ready…', 'storage');
|
||||
const source = `postgresql://nod:${saved.password}@127.0.0.1:${port}/nod`;
|
||||
try {
|
||||
await waitFor(
|
||||
() =>
|
||||
@@ -839,80 +808,121 @@ export async function finishRuntime({
|
||||
const { default: pg } = await import('pg');
|
||||
await waitFor(
|
||||
async () => {
|
||||
const client = new pg.Client({
|
||||
connectionString: databaseUrl,
|
||||
connectionTimeoutMillis: 5000,
|
||||
query_timeout: 5000,
|
||||
});
|
||||
const client = new pg.Client({ connectionString: source, connectionTimeoutMillis: 5000 });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.query('SELECT 1');
|
||||
} finally {
|
||||
await client.end().catch(() => {});
|
||||
}
|
||||
},
|
||||
{ signal, attempts: 12, interval: 1000 },
|
||||
{ signal, attempts: 30, interval: 1000 },
|
||||
);
|
||||
} catch (error) {
|
||||
if (storage) storage.postgres = undefined;
|
||||
signal?.throwIfAborted();
|
||||
let details = [error.code, error.stack || error.message, error.details]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
.replaceAll(saved.password, '[redacted]');
|
||||
let message = 'Nod could not connect to its local PostgreSQL database.';
|
||||
let code = 'NOD_DATABASE_CONNECTION_FAILED';
|
||||
if (process.platform === 'win32') {
|
||||
const [inspection, readiness] = await Promise.allSettled([
|
||||
status('starting', 'Moving your saved data to this computer…', 'storage');
|
||||
await moveDatabase({
|
||||
source,
|
||||
target: database.url,
|
||||
signal,
|
||||
space: database.ensureSpace,
|
||||
schema: (section) =>
|
||||
runDocker(
|
||||
[
|
||||
'inspect',
|
||||
'--format',
|
||||
'{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}',
|
||||
'exec',
|
||||
names.postgres,
|
||||
'pg_dump',
|
||||
'--username',
|
||||
'nod',
|
||||
'--dbname',
|
||||
'nod',
|
||||
'--no-owner',
|
||||
'--no-privileges',
|
||||
`--section=${section}`,
|
||||
],
|
||||
{ timeout: 10_000 },
|
||||
{ timeout: 300_000 },
|
||||
),
|
||||
runDocker(
|
||||
['exec', names.postgres, 'pg_isready', '-h', '127.0.0.1', '-U', 'nod', '-d', 'nod'],
|
||||
{ timeout: 10_000 },
|
||||
),
|
||||
]);
|
||||
signal?.throwIfAborted();
|
||||
const [state, exitCode, outOfMemory] =
|
||||
inspection.status === 'fulfilled' ? inspection.value.trim().split(' ') : [];
|
||||
details += `\n\nWSL container check:\n${
|
||||
inspection.status === 'fulfilled'
|
||||
? inspection.value
|
||||
: inspection.reason.details || inspection.reason.stack || inspection.reason.message
|
||||
}\n\nWSL TCP check:\n${
|
||||
readiness.status === 'fulfilled'
|
||||
? readiness.value
|
||||
: readiness.reason.details || readiness.reason.stack || readiness.reason.message
|
||||
}`;
|
||||
if (outOfMemory === 'true') {
|
||||
code = 'NOD_DATABASE_OUT_OF_MEMORY';
|
||||
message =
|
||||
'PostgreSQL stopped after it reached a memory limit. Close other apps before you retry.';
|
||||
} else if (state && state !== 'running') {
|
||||
code = 'NOD_DATABASE_STOPPED';
|
||||
message = `PostgreSQL is not running in WSL (state: ${state}, exit code: ${exitCode}).`;
|
||||
} else if (readiness.status === 'fulfilled') {
|
||||
message = `PostgreSQL accepts TCP connections inside WSL, but Windows could not complete the database check at 127.0.0.1:${port}.`;
|
||||
} else {
|
||||
code = 'NOD_DATABASE_NOT_READY';
|
||||
message = state
|
||||
? 'PostgreSQL does not answer TCP checks inside WSL.'
|
||||
: 'Nod could not check PostgreSQL inside WSL.';
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (cause) {
|
||||
signal?.throwIfAborted();
|
||||
if (cause.code === 'NOD_DATABASE_STORAGE_FULL') throw cause;
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
`${message} Quit Nod and open it again. If this repeats${process.platform === 'win32' ? ', restart Windows' : ', restart your computer'}. Keep your app data.`,
|
||||
'Nod could not move your saved data out of its private computer. Your data is unchanged. Select Try again.',
|
||||
),
|
||||
{ code, details: details.replaceAll(saved.password, '[redacted]') },
|
||||
{
|
||||
code: 'NOD_DATABASE_MOVE_FAILED',
|
||||
details: [cause.code, cause.stack || cause.message, cause.details]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
.replaceAll(saved.password, '[redacted]')
|
||||
.replaceAll(database.password, '[redacted]'),
|
||||
},
|
||||
);
|
||||
}
|
||||
await database.moved();
|
||||
}
|
||||
|
||||
export async function finishRuntime({
|
||||
dataRoot,
|
||||
resourcesPath,
|
||||
assets,
|
||||
manifest,
|
||||
identity,
|
||||
saved,
|
||||
controlRoot,
|
||||
docker,
|
||||
path,
|
||||
dockerEnvironment,
|
||||
runDocker,
|
||||
runGuest,
|
||||
signal,
|
||||
status,
|
||||
prepareImage,
|
||||
database,
|
||||
onMoved,
|
||||
runtimeReady,
|
||||
}) {
|
||||
status('starting', 'Preparing secure storage and tools…', 'storage');
|
||||
const images = {};
|
||||
const loadImage = (name) => {
|
||||
images[name] = Promise.resolve().then(() => prepareImage?.(name));
|
||||
images[name].catch(() => {});
|
||||
};
|
||||
const moving = database?.pendingMove === true;
|
||||
if (moving) loadImage('postgres');
|
||||
const names = computerNames(dataRoot);
|
||||
for (const [role, subnet, bridge] of [
|
||||
['control', '172.31.80.0/24', 'nod-control'],
|
||||
['workspace', '172.31.81.0/24', 'nod-workspace'],
|
||||
['browser', '172.31.82.0/24', 'nod-browser'],
|
||||
]) {
|
||||
const name = `nod-${role}-${identity}`;
|
||||
await ensureNetwork(runDocker, { name, subnet, bridge });
|
||||
}
|
||||
await runGuest(protectNetworks);
|
||||
const volumes = {
|
||||
browser: `nod-browser-${identity}`,
|
||||
workspace: `nod-workspace-${identity}`,
|
||||
tools: `nod-tools-${identity}`,
|
||||
};
|
||||
for (const volume of Object.values(volumes)) await runDocker(['volume', 'create', volume]);
|
||||
const image = (name) => manifest.images.find((item) => item.name === name).id;
|
||||
if (moving) {
|
||||
await moveComputerDatabase({
|
||||
database,
|
||||
names,
|
||||
identity,
|
||||
saved,
|
||||
dockerEnvironment,
|
||||
runDocker,
|
||||
image,
|
||||
images,
|
||||
signal,
|
||||
status,
|
||||
});
|
||||
await onMoved?.();
|
||||
}
|
||||
await runDocker(['rm', '--force', names.postgres]).catch(() => {});
|
||||
loadImage('workspace');
|
||||
loadImage('browser');
|
||||
const wrapperRoot = join(controlRoot, 'bin');
|
||||
if (process.platform !== 'win32') {
|
||||
await mkdir(wrapperRoot, { recursive: true, mode: 0o700 });
|
||||
@@ -945,36 +955,26 @@ exec "$docker" "$@"
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
}
|
||||
const env = {
|
||||
PATH:
|
||||
process.platform === 'win32'
|
||||
? path
|
||||
: [wrapperRoot, join(assets, 'docker-host/docker'), path].join(delimiter),
|
||||
...(process.platform === 'win32'
|
||||
? {
|
||||
NOD_WSL_DISTRIBUTION: dockerEnvironment.NOD_WSL_DISTRIBUTION,
|
||||
TEMP: dockerEnvironment.TEMP,
|
||||
TMP: dockerEnvironment.TMP,
|
||||
}
|
||||
: {}),
|
||||
DOCKER_HOST: dockerEnvironment.DOCKER_HOST,
|
||||
DOCKER_CONFIG: dockerEnvironment.DOCKER_CONFIG,
|
||||
DOCKER_CONTEXT: '',
|
||||
NOD_DATA_ROOT: dataRoot,
|
||||
BROWSER_CONTAINER: names.browser,
|
||||
WORKSPACE_CONTAINER: names.workspace,
|
||||
DATABASE_URL: databaseUrl,
|
||||
};
|
||||
const runtime = {
|
||||
env,
|
||||
environment: env,
|
||||
postgres,
|
||||
port,
|
||||
environment: {
|
||||
PATH:
|
||||
process.platform === 'win32'
|
||||
? path
|
||||
: [wrapperRoot, join(assets, 'docker-host/docker'), path].join(delimiter),
|
||||
...(process.platform === 'win32'
|
||||
? {
|
||||
NOD_WSL_DISTRIBUTION: dockerEnvironment.NOD_WSL_DISTRIBUTION,
|
||||
TEMP: dockerEnvironment.TEMP,
|
||||
TMP: dockerEnvironment.TMP,
|
||||
}
|
||||
: {}),
|
||||
DOCKER_HOST: dockerEnvironment.DOCKER_HOST,
|
||||
DOCKER_CONFIG: dockerEnvironment.DOCKER_CONFIG,
|
||||
DOCKER_CONTEXT: '',
|
||||
},
|
||||
close: () => stopRuntime({ dataRoot, resourcesPath }),
|
||||
};
|
||||
signal?.throwIfAborted();
|
||||
await onStorageReady?.(runtime);
|
||||
signal?.throwIfAborted();
|
||||
status('starting', 'Preparing your workspace…', 'workspace');
|
||||
await images.workspace;
|
||||
await replaceContainer(
|
||||
@@ -1062,17 +1062,7 @@ export function prepareRuntime(options) {
|
||||
preparing.set(
|
||||
key,
|
||||
prepare(
|
||||
{
|
||||
...options,
|
||||
...(options.onStorageReady
|
||||
? {
|
||||
onStorageReady: async (runtime) => {
|
||||
await options.onStorageReady(runtime);
|
||||
storageReady.set(key, runtime);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
options,
|
||||
() => {
|
||||
computerMayBeRunning = true;
|
||||
},
|
||||
@@ -1080,7 +1070,7 @@ export function prepareRuntime(options) {
|
||||
)
|
||||
.catch(async (error) => {
|
||||
if (error && typeof error === 'object') error.step ??= progress.step;
|
||||
if (computerMayBeRunning && !storageReady.has(key)) {
|
||||
if (computerMayBeRunning) {
|
||||
try {
|
||||
await stopRuntime(options);
|
||||
} catch (cleanupError) {
|
||||
@@ -1115,7 +1105,6 @@ export function prepareRuntime(options) {
|
||||
|
||||
export async function stopRuntime(options) {
|
||||
await stopComputer(options);
|
||||
storageReady.delete(resolve(options.dataRoot || options.root));
|
||||
}
|
||||
|
||||
export async function removeProfile(options) {
|
||||
|
||||
@@ -590,7 +590,8 @@ async function prepareWindows(options, onComputerStart, progress) {
|
||||
timeout: 600_000,
|
||||
});
|
||||
},
|
||||
onStorageReady: options.onStorageReady,
|
||||
database: options.database,
|
||||
onMoved: options.onMoved,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import { packager } from '@electron/packager';
|
||||
import { copyBundleSource as copy, copyEngineDependencies } from './engine-dependencies.mjs';
|
||||
import { assetHash, runtimeRelease as readRuntimeRelease } from '../runtime/assets.mjs';
|
||||
import { runtimeInputs } from './runtime-inputs.mjs';
|
||||
import { copyPostgres } from './postgres-binaries.mjs';
|
||||
import { buildDesktopUI } from './build-ui.mjs';
|
||||
import { checkRelease } from '../../.github/scripts/prepare-desktop-release.mjs';
|
||||
import {
|
||||
@@ -126,6 +127,7 @@ await mkdir(appSource, { recursive: true });
|
||||
await mkdir(output, { recursive: true });
|
||||
await copyEngineSource({ root, target: engine });
|
||||
await copyEngineDependencies({ root, target: engine, arch: process.arch });
|
||||
await copyPostgres({ target: engine });
|
||||
for (const path of ['main', 'preload']) await copy(join(desktop, path), join(appSource, path));
|
||||
await buildDesktopUI(join(appSource, 'ui'));
|
||||
if (full)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { packager } from '@electron/packager';
|
||||
import { copyEngineSource, verifyApplicationRuntime } from './engine-source.mjs';
|
||||
import { copyBundleSource as copy, copyEngineDependencies } from './engine-dependencies.mjs';
|
||||
import { copyPostgres } from './postgres-binaries.mjs';
|
||||
import { buildDesktopUI } from './build-ui.mjs';
|
||||
import { assetHash, runtimeRelease as readRuntimeRelease } from '../runtime/assets.mjs';
|
||||
import {
|
||||
@@ -59,6 +60,7 @@ await mkdir(appSource, { recursive: true });
|
||||
await mkdir(output, { recursive: true });
|
||||
await copyEngineSource({ root, target: engine, platform: 'linux' });
|
||||
await copyEngineDependencies({ root, target: engine, platform: 'linux', arch: process.arch });
|
||||
await copyPostgres({ target: engine });
|
||||
for (const path of ['main', 'preload']) await copy(join(desktop, path), join(appSource, path));
|
||||
await buildDesktopUI(join(appSource, 'ui'));
|
||||
if (full)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { packager } from '@electron/packager';
|
||||
import { assetHash } from '../runtime/assets.mjs';
|
||||
import { copyBundleSource, copyEngineDependencies } from './engine-dependencies.mjs';
|
||||
import { buildDesktopUI } from './build-ui.mjs';
|
||||
import { copyPostgres } from './postgres-binaries.mjs';
|
||||
import { copyAgentDesktop, desktopBuildOptions, hardenElectron, run } from './release-tools.mjs';
|
||||
import { signWindowsFiles, windowsCodeFiles } from './windows-signing.mjs';
|
||||
|
||||
@@ -48,6 +49,7 @@ await mkdir(engine, { recursive: true });
|
||||
await mkdir(output, { recursive: true });
|
||||
await copyEngineSource({ root, target: engine, platform: 'win32' });
|
||||
await copyEngineDependencies({ root, target: engine, platform: 'win32', arch: 'x64' });
|
||||
await copyPostgres({ target: engine, platform: 'win32', arch: 'x64' });
|
||||
console.log('Windows engine files prepared.');
|
||||
for (const path of ['main', 'preload'])
|
||||
await copyBundleSource(join(root, 'desktop', path), join(source, path));
|
||||
|
||||
@@ -58,11 +58,12 @@ async function launch(name, { limit = 900_000, reported = true, attempts = 1 } =
|
||||
const fresh = (await lines()).slice(seen);
|
||||
const failed = fresh.find((line) => /Startup failed|Local runtime failed/.test(line));
|
||||
const prepared = fresh.find((line) => line.includes('Local runtime prepared.'));
|
||||
const listening = fresh.some((line) => line.includes('Background service step: listening'));
|
||||
if (failed || Date.now() - started > limit) {
|
||||
console.log(fresh.map((line) => line.slice(0, 400)).join('\n'));
|
||||
assert.fail(failed ? `Nod failed to start: ${name}.` : `Nod did not start in time: ${name}.`);
|
||||
}
|
||||
if (prepared) {
|
||||
if (prepared && (listening || !reported)) {
|
||||
const steps = Object.fromEntries(
|
||||
fresh.flatMap((line) => {
|
||||
const match = /Background service step: ([a-z]+) after ([\d.]+)s\./.exec(line);
|
||||
@@ -77,6 +78,7 @@ async function launch(name, { limit = 900_000, reported = true, attempts = 1 } =
|
||||
fresh.find((line) => line.includes(' start version=')),
|
||||
)?.[1],
|
||||
steps,
|
||||
moved: fresh.some((line) => line.includes('Saved data moved')),
|
||||
};
|
||||
if (reported)
|
||||
assert.ok(steps.listening > 0, 'The background service did not report its startup steps.');
|
||||
@@ -148,6 +150,11 @@ try {
|
||||
await install(installer);
|
||||
const updated = await launch('first start after the update');
|
||||
assert.notEqual(updated.version, receipt.launches[0].version);
|
||||
assert.equal(updated.moved, true, 'Nod did not move the earlier version’s data.');
|
||||
assert.equal(
|
||||
JSON.parse(await readFile(join(profile, 'database/state.json'), 'utf8')).ready,
|
||||
true,
|
||||
);
|
||||
} else {
|
||||
await install(installer);
|
||||
await launch('first setup');
|
||||
@@ -156,6 +163,7 @@ try {
|
||||
}
|
||||
if (await running()) await quit();
|
||||
const warm = await launch('next start', { limit: 300_000 });
|
||||
assert.equal(warm.moved, false);
|
||||
assert.ok(
|
||||
warm.steps.listening < 120,
|
||||
'The background service took too long on a prepared computer.',
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { run } from './release-tools.mjs';
|
||||
import { assetHash } from '../runtime/assets.mjs';
|
||||
@@ -179,6 +180,9 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
{
|
||||
const profile = join(installation, 'synthetic-profile');
|
||||
const runtime = await import('../runtime/windows.mjs');
|
||||
const { openDatabase } = await import('../runtime/database.mjs');
|
||||
const { availablePort, computerNames } = await import('../runtime/index.mjs');
|
||||
const names = computerNames(profile);
|
||||
const system = (name) => join(process.env.SYSTEMROOT, 'System32', name);
|
||||
console.log('Checking that a WSL failure offers its repair and keeps the Windows error.');
|
||||
const automatic = /AUTO_START/.test(await run(system('sc.exe'), ['qc', 'WslService']));
|
||||
@@ -230,7 +234,18 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
}),
|
||||
);
|
||||
let prepared;
|
||||
let database;
|
||||
const computerEnvironment = () => ({
|
||||
...environment,
|
||||
...prepared.environment,
|
||||
NOD_DATA_ROOT: profile,
|
||||
WORKSPACE_CONTAINER: names.workspace,
|
||||
BROWSER_CONTAINER: names.browser,
|
||||
DATABASE_URL: database.url,
|
||||
});
|
||||
try {
|
||||
database = await openDatabase({ dataRoot: profile, resourcesPath: engine });
|
||||
assert.equal(database.pendingMove, false);
|
||||
await run(
|
||||
system('WindowsPowerShell/v1.0/powershell.exe'),
|
||||
[
|
||||
@@ -305,17 +320,17 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
'node',
|
||||
'--workdir',
|
||||
'/workspace/synthetic-windows-check',
|
||||
prepared.env.WORKSPACE_CONTAINER,
|
||||
names.workspace,
|
||||
'bash',
|
||||
'-c',
|
||||
'test ! -e /var/run/docker.sock && test ! -e /mnt/c && test ! -e /app/.env',
|
||||
],
|
||||
{ env: { ...environment, ...prepared.env }, timeout: 120_000 },
|
||||
{ env: computerEnvironment(), timeout: 120_000 },
|
||||
);
|
||||
assert.match(
|
||||
await run(application, [smoke], {
|
||||
cwd: engine,
|
||||
env: { ...environment, ...prepared.env },
|
||||
env: computerEnvironment(),
|
||||
timeout: 300_000,
|
||||
}),
|
||||
/Windows application and browser verified\./,
|
||||
@@ -328,7 +343,7 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
console.log(
|
||||
'Checking a relaunch without admin rights after the PC went off and WSL lost the computer.',
|
||||
);
|
||||
await run(wsl, ['--terminate', prepared.env.NOD_WSL_DISTRIBUTION]);
|
||||
await run(wsl, ['--terminate', prepared.environment.NOD_WSL_DISTRIBUTION]);
|
||||
await run(wsl, ['--shutdown']);
|
||||
const disk = join(saved.computerPath, 'ext4.vhdx');
|
||||
const kept = join(elsewhere, 'synthetic-kept-ext4.vhdx');
|
||||
@@ -352,6 +367,8 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
'-ProcessId',
|
||||
String(process.pid),
|
||||
]);
|
||||
await database.close();
|
||||
database = await openDatabase({ dataRoot: profile, resourcesPath: engine });
|
||||
prepared = await runtime.prepareWindowsRuntime(
|
||||
{
|
||||
dataRoot: profile,
|
||||
@@ -363,13 +380,131 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
assert.match(
|
||||
await run(application, [smoke], {
|
||||
cwd: engine,
|
||||
env: { ...environment, ...prepared.env, NOD_WINDOWS_REOPEN: '1' },
|
||||
env: { ...computerEnvironment(), NOD_WINDOWS_REOPEN: '1' },
|
||||
timeout: 300_000,
|
||||
}),
|
||||
/Windows application and browser verified\./,
|
||||
);
|
||||
receipt.reopened = true;
|
||||
receipt.reattached = true;
|
||||
console.log('Checking that data from an earlier version moves out of the private computer.');
|
||||
const docker = (args, env = {}) =>
|
||||
run(join(engine, 'windows-runtime/bin/docker.exe'), args, {
|
||||
env: { ...computerEnvironment(), ...env },
|
||||
timeout: 300_000,
|
||||
});
|
||||
const upgrade = async () => {
|
||||
await database.close();
|
||||
await rm(join(profile, 'database'), { recursive: true, force: true });
|
||||
database = await openDatabase({ dataRoot: profile, resourcesPath: engine });
|
||||
assert.equal(database.pendingMove, true);
|
||||
let moved = 0;
|
||||
prepared = await runtime.prepareWindowsRuntime(
|
||||
{
|
||||
dataRoot: profile,
|
||||
resourcesPath: engine,
|
||||
database,
|
||||
onMoved: () => moved++,
|
||||
onStatus: (value) => console.log(value.message),
|
||||
},
|
||||
() => {},
|
||||
);
|
||||
assert.equal(moved, 1);
|
||||
assert.equal(database.pendingMove, false);
|
||||
assert.doesNotMatch(
|
||||
await docker(['ps', '--all', '--format', '{{.Names}}']),
|
||||
new RegExp(names.postgres),
|
||||
);
|
||||
};
|
||||
await upgrade();
|
||||
const identity = distribution.slice(4);
|
||||
const { images } = JSON.parse(
|
||||
await readFile(join(engine, 'windows-runtime/manifest.json'), 'utf8'),
|
||||
);
|
||||
const legacyPassword = JSON.parse(
|
||||
await readFile(join(profile, 'desktop-runtime/state.json'), 'utf8'),
|
||||
).password;
|
||||
const legacyPort = await availablePort();
|
||||
await docker(
|
||||
[
|
||||
'run',
|
||||
'--detach',
|
||||
'--name',
|
||||
names.postgres,
|
||||
'--network',
|
||||
`nod-control-${identity}`,
|
||||
'--publish',
|
||||
`127.0.0.1:${legacyPort}:5432`,
|
||||
'--env',
|
||||
'POSTGRES_USER=nod',
|
||||
'--env',
|
||||
'POSTGRES_DB=nod',
|
||||
'--env',
|
||||
'POSTGRES_PASSWORD',
|
||||
'--volume',
|
||||
`nod-postgres-${identity}:/var/lib/postgresql/data`,
|
||||
images.find(({ name }) => name === 'postgres').id,
|
||||
],
|
||||
{ POSTGRES_PASSWORD: legacyPassword },
|
||||
);
|
||||
const legacyUrl = `postgresql://nod:${legacyPassword}@127.0.0.1:${legacyPort}/nod`;
|
||||
const { default: pg } = await import('pg');
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const client = new pg.Client({
|
||||
connectionString: legacyUrl,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
await client.end();
|
||||
break;
|
||||
} catch (error) {
|
||||
await client.end().catch(() => {});
|
||||
if (attempt === 60) throw error;
|
||||
await delay(1000);
|
||||
}
|
||||
}
|
||||
assert.match(
|
||||
await run(application, [smoke], {
|
||||
cwd: engine,
|
||||
env: { ...computerEnvironment(), DATABASE_URL: legacyUrl },
|
||||
timeout: 300_000,
|
||||
}),
|
||||
/Windows application and browser verified\./,
|
||||
);
|
||||
const fingerprint = `SELECT
|
||||
(SELECT count(*) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema'))::int AS tables,
|
||||
(SELECT md5(string_agg(body, ',' ORDER BY id)) FROM synthetic_bulk) AS bulk,
|
||||
(SELECT value FROM windows_check) AS marker`;
|
||||
const legacy = new pg.Client({ connectionString: legacyUrl });
|
||||
await legacy.connect();
|
||||
await legacy.query(
|
||||
'CREATE TABLE synthetic_bulk (id bigserial PRIMARY KEY, body text NOT NULL, at timestamptz NOT NULL DEFAULT now())',
|
||||
);
|
||||
await legacy.query(
|
||||
"INSERT INTO synthetic_bulk (body) SELECT repeat(md5(g::text), 4) || ' π' FROM generate_series(1, 200000) g",
|
||||
);
|
||||
const before = (await legacy.query(fingerprint)).rows[0];
|
||||
await legacy.end();
|
||||
assert.ok(before.tables > 10);
|
||||
await docker(['rm', '--force', names.postgres]);
|
||||
await upgrade();
|
||||
const host = new pg.Client({ connectionString: database.url });
|
||||
await host.connect();
|
||||
assert.deepEqual((await host.query(fingerprint)).rows[0], before);
|
||||
await host.end();
|
||||
assert.match(
|
||||
await run(application, [smoke], {
|
||||
cwd: engine,
|
||||
env: { ...computerEnvironment(), NOD_WINDOWS_REOPEN: '1' },
|
||||
timeout: 300_000,
|
||||
}),
|
||||
/Windows application and browser verified\./,
|
||||
);
|
||||
await database.close();
|
||||
database = await openDatabase({ dataRoot: profile, resourcesPath: engine });
|
||||
assert.equal(database.pendingMove, false);
|
||||
receipt.upgraded = true;
|
||||
} finally {
|
||||
await run(system('WindowsPowerShell/v1.0/powershell.exe'), [
|
||||
'-NoProfile',
|
||||
@@ -377,6 +512,9 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
'-Command',
|
||||
`Remove-Item -LiteralPath '${otherRegistration}' -Recurse -Force -ErrorAction SilentlyContinue`,
|
||||
]);
|
||||
await database
|
||||
?.close()
|
||||
.catch((error) => console.log(`The test database did not stop: ${error.message}`));
|
||||
console.log('Stopping the test computer.');
|
||||
await runtime.stopWindowsRuntime({ dataRoot: profile });
|
||||
const saved = await readFile(join(profile, 'desktop-runtime/state.json'), 'utf8')
|
||||
@@ -387,6 +525,21 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
else await run(wsl, ['--unregister', distribution]).catch(() => {});
|
||||
}
|
||||
}
|
||||
const leftover = await run(
|
||||
join(process.env.SYSTEMROOT, 'System32/WindowsPowerShell/v1.0/powershell.exe'),
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
"Get-CimInstance Win32_Process -Filter \"Name='postgres.exe'\" | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($env:NOD_INSTALLATION + '\\', 'OrdinalIgnoreCase') } | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CommandLine)\" }",
|
||||
],
|
||||
{ env: { ...process.env, NOD_INSTALLATION: installation } },
|
||||
);
|
||||
assert.equal(
|
||||
leftover.trim(),
|
||||
'',
|
||||
`PostgreSQL is still running from the installation:\n${leftover}`,
|
||||
);
|
||||
console.log('Checking that an update installs its runtime file.');
|
||||
await run(join(output, 'nod-Setup-x64.exe'), ['/S', `/D=${installation}`], { timeout: 600_000 });
|
||||
const { guest } = JSON.parse(
|
||||
@@ -397,7 +550,9 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
console.log(JSON.stringify(receipt));
|
||||
} finally {
|
||||
console.log('Removing the test installation.');
|
||||
await rm(installation, { recursive: true, force: true });
|
||||
await rm(installation, { recursive: true, force: true }).catch((error) =>
|
||||
console.log(`The test installation was not removed: ${error.message}`),
|
||||
);
|
||||
await rm(foreign, { recursive: true, force: true });
|
||||
await rm(alone, { recursive: true, force: true });
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export async function copyEngineSource({ root, target, platform = 'darwin' }) {
|
||||
'desktop/main/onepassword.mjs',
|
||||
'desktop/runtime/index.mjs',
|
||||
'desktop/runtime/assets.mjs',
|
||||
'desktop/runtime/database.mjs',
|
||||
'desktop/runtime/guest-config.mjs',
|
||||
...(platform === 'win32'
|
||||
? ['desktop/runtime/windows.mjs', 'desktop/runtime/protect-profile.ps1']
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
cp,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readdir,
|
||||
readFile,
|
||||
rename,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { dirname, join, relative } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { inflateRawSync } from 'node:zlib';
|
||||
import { run } from './release-tools.mjs';
|
||||
|
||||
export const postgresVersion = '17.12.0';
|
||||
|
||||
const builds = {
|
||||
'darwin-arm64': {
|
||||
artifact: 'embedded-postgres-binaries-darwin-arm64v8',
|
||||
sha256: '31fcf0b329fa909e050c1bc615bdb0fd6180add1043c2612f5acd5a086449c0b',
|
||||
architecture: 'arm64',
|
||||
},
|
||||
'darwin-x64': {
|
||||
artifact: 'embedded-postgres-binaries-darwin-amd64',
|
||||
sha256: 'aa639f96ffc1358a6191364835d93a8739289cee01d95ff1eab54ffe365625a8',
|
||||
architecture: 'x86_64',
|
||||
},
|
||||
'win32-x64': {
|
||||
artifact: 'embedded-postgres-binaries-windows-amd64',
|
||||
sha256: 'bebadbe868ed53adb1c12033a381e41005915205ea9fedaa2349f5467fa7016b',
|
||||
},
|
||||
'linux-x64': {
|
||||
artifact: 'embedded-postgres-binaries-linux-amd64',
|
||||
sha256: '7a8951dc117490f2d4161600836c8b1055306aff86e0a472aad55457651e5cbd',
|
||||
},
|
||||
'linux-arm64': {
|
||||
artifact: 'embedded-postgres-binaries-linux-arm64v8',
|
||||
sha256: 'b1b880df7027b711852b6fb64d8ceb4d149e1d02bc5fc7665b6af881c64d0fdc',
|
||||
},
|
||||
};
|
||||
|
||||
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
function archiveEntry(jar, pattern) {
|
||||
const end = jar.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
||||
if (end < 0) throw new Error('The PostgreSQL package is not a zip archive.');
|
||||
let offset = jar.readUInt32LE(end + 16);
|
||||
for (let index = 0; index < jar.readUInt16LE(end + 10); index++) {
|
||||
const nameLength = jar.readUInt16LE(offset + 28);
|
||||
const name = jar.toString('utf8', offset + 46, offset + 46 + nameLength);
|
||||
if (pattern.test(name)) {
|
||||
const method = jar.readUInt16LE(offset + 10);
|
||||
const size = jar.readUInt32LE(offset + 20);
|
||||
const local = jar.readUInt32LE(offset + 42);
|
||||
const start = local + 30 + jar.readUInt16LE(local + 26) + jar.readUInt16LE(local + 28);
|
||||
const data = jar.subarray(start, start + size);
|
||||
if (method === 0) return data;
|
||||
if (method === 8) return inflateRawSync(data);
|
||||
throw new Error('The PostgreSQL package uses an unsupported compression method.');
|
||||
}
|
||||
offset += 46 + nameLength + jar.readUInt16LE(offset + 30) + jar.readUInt16LE(offset + 32);
|
||||
}
|
||||
throw new Error('The PostgreSQL package has no binaries.');
|
||||
}
|
||||
|
||||
async function download(build, cacheDir) {
|
||||
const file = `${build.artifact}-${postgresVersion}.jar`;
|
||||
const cached = join(cacheDir, file);
|
||||
const saved = await readFile(cached).catch(() => undefined);
|
||||
if (saved && sha256(saved) === build.sha256) return saved;
|
||||
const url = `https://repo1.maven.org/maven2/io/zonky/test/postgres/${build.artifact}/${postgresVersion}/${file}`;
|
||||
let bytes;
|
||||
for (let attempt = 1; !bytes; attempt++) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(600_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`PostgreSQL download failed with HTTP ${response.status}.`);
|
||||
bytes = Buffer.from(await response.arrayBuffer());
|
||||
} catch (error) {
|
||||
if (attempt === 3) throw error;
|
||||
await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
|
||||
}
|
||||
}
|
||||
if (sha256(bytes) !== build.sha256)
|
||||
throw new Error('The PostgreSQL download does not match its checksum.');
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
await writeFile(`${cached}.download`, bytes);
|
||||
await rename(`${cached}.download`, cached);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
async function files(directory) {
|
||||
const found = [];
|
||||
for (const entry of await readdir(directory, { withFileTypes: true, recursive: true }))
|
||||
if (entry.isFile()) found.push(join(entry.parentPath, entry.name));
|
||||
return found;
|
||||
}
|
||||
|
||||
async function thinMac(root, architecture) {
|
||||
for (const path of await files(root)) {
|
||||
const archs = await run('/usr/bin/lipo', ['-archs', path]).catch(() => '');
|
||||
if (!archs.trim().includes(' ')) continue;
|
||||
await run('/usr/bin/lipo', [path, '-thin', architecture, '-output', `${path}.thin`]);
|
||||
await rename(`${path}.thin`, path);
|
||||
}
|
||||
const seen = new Map();
|
||||
const libraries = (await readdir(join(root, 'lib'), { withFileTypes: true }))
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => join(root, 'lib', entry.name))
|
||||
.sort((left, right) => left.length - right.length || left.localeCompare(right));
|
||||
for (const path of libraries) {
|
||||
const hash = sha256(await readFile(path));
|
||||
const original = seen.get(hash);
|
||||
if (!original) {
|
||||
seen.set(hash, path);
|
||||
continue;
|
||||
}
|
||||
await rm(path);
|
||||
await symlink(relative(dirname(path), original), path);
|
||||
}
|
||||
}
|
||||
|
||||
export async function copyPostgres({
|
||||
target,
|
||||
platform = process.platform,
|
||||
arch = process.arch,
|
||||
cacheDir = join(homedir(), '.cache', 'nod', 'postgres'),
|
||||
}) {
|
||||
const build = builds[`${platform}-${arch}`];
|
||||
if (!build) throw new Error(`Nod has no PostgreSQL build for ${platform}-${arch}.`);
|
||||
const archive = archiveEntry(await download(build, cacheDir), /^postgres-.+\.txz$/);
|
||||
const work = await mkdtemp(join(tmpdir(), 'nod-postgres-'));
|
||||
const output = join(target, 'postgres');
|
||||
try {
|
||||
await writeFile(join(work, 'postgres.txz'), archive);
|
||||
await rm(output, { recursive: true, force: true });
|
||||
await mkdir(output, { recursive: true });
|
||||
const tar =
|
||||
process.platform === 'win32'
|
||||
? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
|
||||
: process.platform === 'darwin'
|
||||
? '/usr/bin/tar'
|
||||
: 'tar';
|
||||
await run(tar, ['-xJf', join(work, 'postgres.txz'), '-C', output], { timeout: 600_000 });
|
||||
if (build.architecture) await thinMac(output, build.architecture);
|
||||
await cp(
|
||||
join(dirname(fileURLToPath(import.meta.url)), '..', 'licenses', 'postgresql.md'),
|
||||
join(output, 'LICENSE.md'),
|
||||
);
|
||||
await writeFile(join(output, 'VERSION'), `${postgresVersion} ${build.sha256}\n`);
|
||||
} finally {
|
||||
await rm(work, { recursive: true, force: true });
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
const build = builds[`${process.platform}-${process.arch}`];
|
||||
const current = await readFile(join(root, 'postgres', 'VERSION'), 'utf8').catch(() => '');
|
||||
if (current !== `${postgresVersion} ${build?.sha256}\n`) await copyPostgres({ target: root });
|
||||
}
|
||||
@@ -94,6 +94,9 @@ Function ${UN}CloseNod
|
||||
StrCpy $1 1
|
||||
Goto nod_check
|
||||
nod_closed:
|
||||
System::Call 'Kernel32::SetEnvironmentVariable(t "NOD_INSTALL_DIR", t "$INSTDIR")i'
|
||||
nsExec::Exec `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter 'Name=''postgres.exe''' | Where-Object { $$_.ExecutablePath -and $$_.ExecutablePath.StartsWith($$env:NOD_INSTALL_DIR + '\', 'OrdinalIgnoreCase') } | ForEach-Object { Stop-Process -Id $$_.ProcessId -Force -ErrorAction SilentlyContinue }"`
|
||||
Pop $0
|
||||
ClearErrors
|
||||
FunctionEnd
|
||||
!macroend
|
||||
|
||||
@@ -29,7 +29,7 @@ import { homedir, tmpdir } from 'node:os';
|
||||
import { delimiter, dirname, join, posix, relative, resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { createDesktopLifecycle } from '../main/lifecycle.mjs';
|
||||
import { createDesktopLifecycle, startupErrorDetails } from '../main/lifecycle.mjs';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { create } from 'tar';
|
||||
@@ -2285,6 +2285,7 @@ test('engine source includes startup reporting and documentation without site de
|
||||
'desktop/main/onepassword.mjs',
|
||||
'desktop/runtime/index.mjs',
|
||||
'desktop/runtime/assets.mjs',
|
||||
'desktop/runtime/database.mjs',
|
||||
'desktop/runtime/guest-config.mjs',
|
||||
]) {
|
||||
await mkdir(dirname(join(source, path)), { recursive: true });
|
||||
@@ -2302,6 +2303,7 @@ test('engine source includes startup reporting and documentation without site de
|
||||
);
|
||||
for (const path of [
|
||||
'desktop/main/feedback.mjs',
|
||||
'desktop/runtime/database.mjs',
|
||||
'src/shared/environment-secrets.mjs',
|
||||
'src/shared/literal-masks.mjs',
|
||||
'src/shared/startup-feedback-facts.mjs',
|
||||
@@ -4602,115 +4604,6 @@ test('runtime replaces owned containers even with unchanged images and retains t
|
||||
}
|
||||
});
|
||||
|
||||
test('runtime retries reuse only the same owned PostgreSQL container with unchanged storage, port and security', async () => {
|
||||
const { replaceContainer } = await import('../runtime/index.mjs');
|
||||
const name = 'nod-postgres-fixture';
|
||||
const image = `sha256:${'a'.repeat(64)}`;
|
||||
const args = [
|
||||
'--network',
|
||||
'nod-control-fixture',
|
||||
'--publish',
|
||||
'127.0.0.1:54329:5432',
|
||||
'--volume',
|
||||
`${name}:/var/lib/postgresql/data`,
|
||||
];
|
||||
const original = {
|
||||
Id: 'synthetic-postgres-container',
|
||||
Image: image,
|
||||
Config: { Labels: { 'dev.nod.desktop.experiment': 'true' }, Env: ['POSTGRES_DB=nod'] },
|
||||
Mounts: [{ Type: 'volume', Name: name, Destination: '/var/lib/postgresql/data', RW: true }],
|
||||
HostConfig: {
|
||||
Privileged: false,
|
||||
NetworkMode: 'nod-control-fixture',
|
||||
PortBindings: { '5432/tcp': [{ HostIp: '127.0.0.1', HostPort: '54329' }] },
|
||||
},
|
||||
NetworkSettings: { Networks: { 'nod-control-fixture': { NetworkID: 'owned-control' } } },
|
||||
State: { Running: true },
|
||||
};
|
||||
const reuse = await replaceContainer(
|
||||
async (args) => (args[1] === 'inspect' ? JSON.stringify([original]) : ''),
|
||||
name,
|
||||
image,
|
||||
args,
|
||||
{ remember: true },
|
||||
);
|
||||
for (const change of [
|
||||
undefined,
|
||||
(value) => {
|
||||
value.Id = 'replacement';
|
||||
},
|
||||
(value) => {
|
||||
value.Image = `sha256:${'b'.repeat(64)}`;
|
||||
},
|
||||
(value) => {
|
||||
value.State.Running = false;
|
||||
},
|
||||
(value) => {
|
||||
value.HostConfig.Privileged = true;
|
||||
},
|
||||
(value) => {
|
||||
value.HostConfig.PortBindings['5432/tcp'][0].HostIp = '0.0.0.0';
|
||||
},
|
||||
(value) => {
|
||||
value.HostConfig.PortBindings['5432/tcp'][0].HostPort = '54330';
|
||||
},
|
||||
(value) => {
|
||||
value.HostConfig.NetworkMode = 'host';
|
||||
},
|
||||
(value) => {
|
||||
value.Config.Env = ['POSTGRES_DB=foreign'];
|
||||
},
|
||||
(value) => {
|
||||
value.NetworkSettings.Networks['nod-control-fixture'].NetworkID = 'foreign';
|
||||
},
|
||||
]) {
|
||||
const current = structuredClone(original);
|
||||
change?.(current);
|
||||
const commands = [];
|
||||
await replaceContainer(
|
||||
async (args) => {
|
||||
commands.push(args);
|
||||
return args[1] === 'inspect' ? JSON.stringify([current]) : '';
|
||||
},
|
||||
name,
|
||||
image,
|
||||
args,
|
||||
{ reuse },
|
||||
);
|
||||
if (!change) assert.deepEqual(commands, [['container', 'inspect', name]]);
|
||||
else
|
||||
assert.deepEqual(
|
||||
commands.filter((args) => ['stop', 'rm', 'run'].includes(args[0])).map((args) => args[0]),
|
||||
['stop', 'rm', 'run'],
|
||||
);
|
||||
}
|
||||
for (const change of [
|
||||
(value) => {
|
||||
value.Config.Labels = {};
|
||||
},
|
||||
(value) => {
|
||||
value.Mounts[0].Name = 'foreign-data';
|
||||
},
|
||||
]) {
|
||||
const current = structuredClone(original);
|
||||
change(current);
|
||||
const commands = [];
|
||||
await assert.rejects(
|
||||
replaceContainer(
|
||||
async (args) => {
|
||||
commands.push(args);
|
||||
return JSON.stringify([current]);
|
||||
},
|
||||
name,
|
||||
image,
|
||||
args,
|
||||
{ reuse },
|
||||
),
|
||||
);
|
||||
assert.equal(commands.length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('native runtime can stop after the streaming runtime pack is removed', async (t) => {
|
||||
if (process.platform === 'win32') return t.skip('This fixture uses a Mac shell program.');
|
||||
const root = await mkdtemp(join(tmpdir(), 'nod-stop-runtime-'));
|
||||
@@ -4783,7 +4676,7 @@ test('native runtime can stop after the streaming runtime pack is removed', asyn
|
||||
});
|
||||
});
|
||||
|
||||
test('native runtime wrapper preserves handed-off storage through failed preparation and explicit retry until quit', async () => {
|
||||
test('a failed computer start stops a computer that may be running, and quit retries a failed stop', async () => {
|
||||
const source = await readFile(new URL('../runtime/index.mjs', import.meta.url), 'utf8');
|
||||
const wrapper = source
|
||||
.slice(
|
||||
@@ -4791,11 +4684,10 @@ test('native runtime wrapper preserves handed-off storage through failed prepara
|
||||
source.indexOf('async function stopComputer('),
|
||||
)
|
||||
.replaceAll('export ', '');
|
||||
for (const terminal of ['retry', 'quit', 'abort', 'cleanup-failed']) {
|
||||
let attempts = 0;
|
||||
for (const terminal of ['before-start', 'stopped', 'cleanup-failed']) {
|
||||
let stops = 0;
|
||||
let engineStops = 0;
|
||||
let retired = false;
|
||||
let databaseCloses = 0;
|
||||
const startupError = Object.assign(new Error('Synthetic startup failure'), {
|
||||
code: 'NOD_COMPUTER_PROTECTION_FAILED',
|
||||
details: 'Synthetic startup command details',
|
||||
@@ -4805,286 +4697,64 @@ test('native runtime wrapper preserves handed-off storage through failed prepara
|
||||
code: 'NOD_RUNTIME_STOP_FAILED',
|
||||
details: 'Synthetic stop command details',
|
||||
});
|
||||
const pending = [];
|
||||
let handed;
|
||||
const storageHanded = new Promise((accept) => {
|
||||
handed = accept;
|
||||
});
|
||||
const storage = {
|
||||
env: {},
|
||||
close: () => runtime.stopRuntime({ dataRoot: resolve('synthetic-profile') }),
|
||||
};
|
||||
const runtime = runInNewContext(`${wrapper}; ({ prepareRuntime, stopRuntime })`, {
|
||||
resolve,
|
||||
preparing: new Map(),
|
||||
storageReady: new Map(),
|
||||
prepare: async (options, started, progress) => {
|
||||
started();
|
||||
attempts++;
|
||||
progress.step = 'assets';
|
||||
if (terminal !== 'before-start') started();
|
||||
progress.step = 'start';
|
||||
if (terminal === 'cleanup-failed') throw startupError;
|
||||
if (retired) throw new Error('Synthetic new attempt before storage');
|
||||
if (attempts === 2) throw new Error('Synthetic retry before storage handshake');
|
||||
await options.onStorageReady(storage);
|
||||
handed();
|
||||
if (terminal === 'abort')
|
||||
await new Promise((_, reject) =>
|
||||
options.signal.addEventListener('abort', () => reject(new Error('Synthetic abort')), {
|
||||
once: true,
|
||||
}),
|
||||
);
|
||||
if (attempts === 1) throw new Error('Synthetic workspace startup failure');
|
||||
return storage;
|
||||
throw startupError;
|
||||
},
|
||||
stopComputer: async () => {
|
||||
stops++;
|
||||
if (terminal === 'cleanup-failed' && stops === 1) throw cleanupError;
|
||||
},
|
||||
});
|
||||
const failures = [];
|
||||
const lifecycle = createDesktopLifecycle({
|
||||
openDatabase: async () => ({
|
||||
url: 'postgresql://nod:synthetic@127.0.0.1:1/nod',
|
||||
password: 'synthetic',
|
||||
pendingMove: false,
|
||||
moved: async () => {},
|
||||
close: async () => {
|
||||
databaseCloses++;
|
||||
},
|
||||
}),
|
||||
prepareRuntime: (options) =>
|
||||
runtime.prepareRuntime({ ...options, dataRoot: resolve('synthetic-profile') }),
|
||||
validateStart: async () => {},
|
||||
startEngine: async ({ pending: waiting }) => pending.push(waiting === true),
|
||||
startEngine: async () => {},
|
||||
stopEngine: async () => {
|
||||
engineStops++;
|
||||
},
|
||||
stopRuntime: () => runtime.stopRuntime({ dataRoot: resolve('synthetic-profile') }),
|
||||
onRuntimeStatus() {},
|
||||
onRuntime: ({ error }) => failures.push(error),
|
||||
});
|
||||
if (terminal === 'cleanup-failed') {
|
||||
await assert.rejects(lifecycle.start(), (error) => {
|
||||
assert.equal(error.code, startupError.code);
|
||||
assert.match(error.message, /Synthetic startup failure.*Synthetic stop failure/);
|
||||
assert.equal(error.step, 'start');
|
||||
assert.equal(error.errors[0], startupError);
|
||||
assert.equal(error.errors[1], cleanupError);
|
||||
assert.equal(error.cause, cleanupError);
|
||||
assert.equal(error.cause.cause, stopError);
|
||||
assert.ok(error.details.includes(startupError.details));
|
||||
assert.ok(error.details.includes('Synthetic stop command details'));
|
||||
await assert.rejects(lifecycle.warmup(), (error) => {
|
||||
assert.equal(error.step, 'start');
|
||||
if (terminal !== 'cleanup-failed') {
|
||||
assert.equal(error, startupError);
|
||||
return true;
|
||||
});
|
||||
assert.equal(stops, 1);
|
||||
assert.deepEqual(pending, []);
|
||||
await lifecycle.close();
|
||||
assert.equal(stops, 2);
|
||||
assert.equal(engineStops, 1);
|
||||
continue;
|
||||
}
|
||||
if (terminal === 'abort') {
|
||||
const starting = assert.rejects(lifecycle.start(), /Synthetic abort/);
|
||||
await storageHanded;
|
||||
await lifecycle.close();
|
||||
await starting;
|
||||
assert.equal(engineStops, 1);
|
||||
assert.equal(stops, 1);
|
||||
continue;
|
||||
}
|
||||
await assert.rejects(lifecycle.start(), /Synthetic workspace startup failure/);
|
||||
assert.equal(stops, 0, `${terminal}: storage must remain usable after workspace failure`);
|
||||
assert.deepEqual(pending, [true]);
|
||||
if (terminal === 'retry') {
|
||||
await assert.rejects(lifecycle.start());
|
||||
assert.equal(attempts, 1);
|
||||
await assert.rejects(
|
||||
lifecycle.start({ retry: true }),
|
||||
/Synthetic retry before storage handshake/,
|
||||
);
|
||||
assert.equal(stops, 0);
|
||||
await lifecycle.start({ retry: true });
|
||||
assert.equal(attempts, 3);
|
||||
assert.deepEqual(pending, [true, true, false]);
|
||||
}
|
||||
}
|
||||
assert.equal(error.code, startupError.code);
|
||||
assert.match(error.message, /Synthetic startup failure.*Synthetic stop failure/);
|
||||
assert.equal(error.errors[0], startupError);
|
||||
assert.equal(error.errors[1], cleanupError);
|
||||
assert.equal(error.cause, cleanupError);
|
||||
assert.equal(error.cause.cause, stopError);
|
||||
assert.ok(error.details.includes(startupError.details));
|
||||
assert.ok(error.details.includes('Synthetic stop command details'));
|
||||
return true;
|
||||
});
|
||||
assert.equal(failures.length, 1);
|
||||
assert.equal(stops, terminal === 'before-start' ? 0 : 1);
|
||||
await lifecycle.close();
|
||||
assert.equal(stops, { 'before-start': 0, stopped: 1, 'cleanup-failed': 2 }[terminal]);
|
||||
assert.equal(engineStops, 1);
|
||||
assert.equal(stops, 1, `${terminal}: quit must close retained storage exactly once`);
|
||||
retired = true;
|
||||
await assert.rejects(
|
||||
runtime.prepareRuntime({
|
||||
dataRoot: resolve('synthetic-profile'),
|
||||
onStorageReady: async () => {},
|
||||
}),
|
||||
/Synthetic new attempt/,
|
||||
);
|
||||
assert.equal(stops, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test('Windows storage starts on a free port, and a readiness failure names its cause and replaces retained PostgreSQL on that port only on the next explicit retry', async (t) => {
|
||||
const source = await readFile(new URL('../runtime/index.mjs', import.meta.url), 'utf8');
|
||||
const functions = source
|
||||
.slice(
|
||||
source.indexOf('export async function finishRuntime('),
|
||||
source.indexOf('async function stopComputer('),
|
||||
)
|
||||
.replaceAll('export ', '')
|
||||
.replace("const { default: pg } = await import('pg');", '');
|
||||
const { availablePort, replaceContainer } = await import('../runtime/index.mjs');
|
||||
const taken = createServer();
|
||||
await new Promise((listening) => taken.listen(0, '127.0.0.1', listening));
|
||||
t.after(() => taken.close());
|
||||
for (const [failure, expectedCode] of [
|
||||
['pg_isready', 'NOD_DATABASE_NOT_READY'],
|
||||
['connect', 'NOD_DATABASE_CONNECTION_FAILED'],
|
||||
['query', 'NOD_DATABASE_CONNECTION_FAILED'],
|
||||
['stopped', 'NOD_DATABASE_STOPPED'],
|
||||
['memory', 'NOD_DATABASE_OUT_OF_MEMORY'],
|
||||
['wsl', 'NOD_DATABASE_NOT_READY'],
|
||||
]) {
|
||||
const containers = new Map();
|
||||
const commands = [];
|
||||
const connections = [];
|
||||
let fault = 'workspace';
|
||||
let created = 0;
|
||||
let stopped = 0;
|
||||
const runtime = runInNewContext(
|
||||
`${functions}; ({ finishRuntime, prepareRuntime, stopRuntime })`,
|
||||
{
|
||||
resolve,
|
||||
join,
|
||||
process: { platform: 'win32' },
|
||||
preparing: new Map(),
|
||||
storageReady: new Map(),
|
||||
replaceContainer,
|
||||
availablePort,
|
||||
ensureNetwork: async () => {},
|
||||
protectNetworks: '',
|
||||
waitFor: async (operation) => operation(),
|
||||
removeStaleImages: async () => {},
|
||||
pg: {
|
||||
Client: class {
|
||||
constructor({ connectionString }) {
|
||||
connections.push(new URL(connectionString).port);
|
||||
}
|
||||
async connect() {
|
||||
if (['connect', 'stopped', 'memory', 'wsl'].includes(fault))
|
||||
throw Object.assign(
|
||||
new Error(`Synthetic ${fault} failure: synthetic-fixture-password`),
|
||||
{ code: 'ECONNRESET' },
|
||||
);
|
||||
}
|
||||
async query() {
|
||||
if (fault === 'query') throw new Error('Synthetic query failure');
|
||||
}
|
||||
async end() {}
|
||||
},
|
||||
},
|
||||
prepare: async (options, started) => {
|
||||
started();
|
||||
return runtime.finishRuntime({
|
||||
...options,
|
||||
resourcesPath: 'synthetic-resources',
|
||||
assets: 'synthetic-assets',
|
||||
identity: 'fixture',
|
||||
manifest: {
|
||||
images: ['postgres', 'workspace', 'browser'].map((name) => ({
|
||||
name,
|
||||
id: `sha256:${name}`,
|
||||
})),
|
||||
},
|
||||
saved: { port: taken.address().port, password: 'synthetic-fixture-password' },
|
||||
controlRoot: 'synthetic-control',
|
||||
path: 'synthetic-path',
|
||||
dockerEnvironment: {},
|
||||
runGuest: async () => {},
|
||||
status: options.onStatus,
|
||||
prepareImage: async (name) => {
|
||||
if (name === fault) throw new Error(`Synthetic ${name} startup failure`);
|
||||
},
|
||||
runDocker: async (args, options) => {
|
||||
commands.push(args);
|
||||
if (options?.timeout === 10_000) {
|
||||
assert.ok(['inspect', 'exec'].includes(args[0]));
|
||||
if (fault === 'wsl')
|
||||
throw new Error('Synthetic WSL check failure: synthetic-fixture-password');
|
||||
}
|
||||
if (args[0] === 'container' && args[1] === 'inspect') {
|
||||
if (!containers.has(args[2])) throw new Error('Absent synthetic container');
|
||||
return JSON.stringify([containers.get(args[2])]);
|
||||
}
|
||||
if (args[0] === 'run') {
|
||||
const name = args[args.indexOf('--name') + 1];
|
||||
containers.set(name, {
|
||||
Id: `synthetic-container-${++created}`,
|
||||
Image: args.find((value) => value.startsWith('sha256:')),
|
||||
State: { Running: true },
|
||||
Config: { Labels: { 'dev.nod.desktop.experiment': 'true' } },
|
||||
Mounts: args.flatMap((value, index) => {
|
||||
if (value !== '--volume') return [];
|
||||
const [Name, Destination] = args[index + 1].split(':');
|
||||
return [{ Type: 'volume', Name, Destination }];
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (args[0] === 'exec' && args[2] === 'pg_isready' && fault === 'pg_isready')
|
||||
throw new Error('Synthetic pg_isready failure');
|
||||
if (
|
||||
args[0] === 'inspect' &&
|
||||
args.includes('{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}')
|
||||
)
|
||||
return fault === 'memory'
|
||||
? 'exited 137 true'
|
||||
: fault === 'stopped'
|
||||
? 'exited 1 false'
|
||||
: 'running 0 false';
|
||||
if (args[0] === 'inspect') return 'true';
|
||||
return '';
|
||||
},
|
||||
});
|
||||
},
|
||||
stopComputer: async () => {
|
||||
stopped++;
|
||||
},
|
||||
},
|
||||
);
|
||||
const lifecycle = createDesktopLifecycle({
|
||||
prepareRuntime: (options) =>
|
||||
runtime.prepareRuntime({ ...options, dataRoot: resolve('synthetic-profile') }),
|
||||
validateStart: async () => {},
|
||||
startEngine: async () => {},
|
||||
stopEngine: async () => {},
|
||||
onRuntimeStatus() {},
|
||||
});
|
||||
const postgres = () => containers.get('nod-postgres-fixture').Id;
|
||||
try {
|
||||
await assert.rejects(lifecycle.start(), /Synthetic workspace startup failure/);
|
||||
const original = postgres();
|
||||
fault = 'browser';
|
||||
await assert.rejects(lifecycle.start({ retry: true }), /Synthetic browser startup failure/);
|
||||
assert.equal(postgres(), original);
|
||||
fault = failure;
|
||||
await assert.rejects(lifecycle.start({ retry: true }), (error) => {
|
||||
assert.equal(error.code, expectedCode);
|
||||
assert.match(error.details, new RegExp(`Synthetic ${failure} failure`));
|
||||
assert.ok(!JSON.stringify(error).includes('synthetic-fixture-password'));
|
||||
return true;
|
||||
});
|
||||
assert.equal(postgres(), original);
|
||||
assert.equal(stopped, 0);
|
||||
const attempted = commands.length;
|
||||
fault = undefined;
|
||||
await assert.rejects(lifecycle.start());
|
||||
assert.equal(commands.length, attempted);
|
||||
await lifecycle.start({ retry: true });
|
||||
assert.notEqual(
|
||||
postgres(),
|
||||
original,
|
||||
`${failure}: explicit retry must replace failed PostgreSQL`,
|
||||
);
|
||||
const launches = commands.filter(
|
||||
(args) => args[0] === 'run' && args.includes('nod-postgres-fixture'),
|
||||
);
|
||||
assert.equal(launches.length, 2);
|
||||
assert.deepEqual(launches[1], launches[0]);
|
||||
const published = launches[0][launches[0].indexOf('--publish') + 1];
|
||||
assert.notEqual(published, `127.0.0.1:${taken.address().port}:5432`);
|
||||
assert.deepEqual(new Set(connections), new Set([published.split(':')[1]]));
|
||||
assert.equal(stopped, 0);
|
||||
} finally {
|
||||
await lifecycle.close();
|
||||
}
|
||||
assert.equal(stopped, 1);
|
||||
assert.equal(databaseCloses, 1);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -5539,26 +5209,26 @@ test('the Windows guest starts Docker and keeps waiting when a readiness check h
|
||||
assert.deepEqual((await windows.read()).commands, [['info'], ['dockerd'], ['info']]);
|
||||
});
|
||||
|
||||
test('runtime hands off verified storage before browser readiness and fences failed or aborted handoffs', async (t) => {
|
||||
const { finishRuntime } = await import('../runtime/index.mjs');
|
||||
test('the computer starts without PostgreSQL unless a data move is pending, and a failed move stays pending', async (t) => {
|
||||
const { computerNames, finishRuntime } = await import('../runtime/index.mjs');
|
||||
const { default: pg } = await import('pg');
|
||||
for (const outcome of [
|
||||
'ready',
|
||||
'callback-failed',
|
||||
'aborted-handoff',
|
||||
'aborted',
|
||||
'move-failed',
|
||||
'windows-ready',
|
||||
'windows-failed',
|
||||
'windows-damaged',
|
||||
]) {
|
||||
await t.test(outcome, async (t) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'nod-storage-ready-'));
|
||||
const root = await mkdtemp(join(tmpdir(), 'nod-computer-ready-'));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const names = computerNames(root);
|
||||
const identity = names.workspace.slice('nod-workspace-'.length);
|
||||
const signal = new AbortController();
|
||||
const windows = outcome.startsWith('windows-') ? await windowsImageFixture(t) : undefined;
|
||||
if (windows) {
|
||||
windows.run('start');
|
||||
assert.deepEqual((await windows.read()).images, {});
|
||||
if (outcome === 'windows-failed') await windows.wrong('browser');
|
||||
if (outcome === 'windows-damaged')
|
||||
await writeFile(
|
||||
@@ -5567,34 +5237,23 @@ test('runtime hands off verified storage before browser readiness and fences fai
|
||||
);
|
||||
}
|
||||
const calls = [];
|
||||
let storage;
|
||||
let callbacks = 0;
|
||||
let verified = false;
|
||||
let release;
|
||||
let blocked;
|
||||
let continueSetup;
|
||||
let handedOff;
|
||||
const handoff = new Promise((resolve) => {
|
||||
continueSetup = resolve;
|
||||
});
|
||||
const handed = new Promise((resolve) => {
|
||||
handedOff = resolve;
|
||||
});
|
||||
const browser = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const waiting = new Promise((resolve) => {
|
||||
blocked = resolve;
|
||||
});
|
||||
let moved = 0;
|
||||
const database = {
|
||||
url: 'postgresql://nod:synthetic-host-password@127.0.0.1:1/nod',
|
||||
password: 'synthetic-host-password',
|
||||
pendingMove: outcome === 'move-failed',
|
||||
moved: async () => {
|
||||
moved++;
|
||||
database.pendingMove = false;
|
||||
},
|
||||
};
|
||||
t.mock.method(pg.Client.prototype, 'connect', async () => {
|
||||
calls.push('database-connect');
|
||||
});
|
||||
t.mock.method(pg.Client.prototype, 'query', async (query) => {
|
||||
assert.equal(query, 'SELECT 1');
|
||||
verified = true;
|
||||
});
|
||||
t.mock.method(pg.Client.prototype, 'end', async () => {
|
||||
calls.push('database-end');
|
||||
t.mock.method(pg.Client.prototype, 'end', async () => {});
|
||||
let blocked;
|
||||
const waiting = new Promise((resolve) => {
|
||||
blocked = resolve;
|
||||
});
|
||||
const created = new Set();
|
||||
const runDocker = async (args) => {
|
||||
@@ -5623,47 +5282,42 @@ test('runtime hands off verified storage before browser readiness and fences fai
|
||||
return JSON.stringify([
|
||||
{
|
||||
Id: args[2],
|
||||
Image: 'sha256:postgres',
|
||||
State: { Running: true },
|
||||
Config: { Labels: { 'dev.nod.desktop.experiment': 'true' } },
|
||||
Mounts: [
|
||||
{
|
||||
Type: 'volume',
|
||||
Name: 'nod-postgres-fixture',
|
||||
Destination: '/var/lib/postgresql/data',
|
||||
},
|
||||
],
|
||||
Mounts: [],
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (args[0] === 'exec' && args.includes('pg_dump'))
|
||||
throw new Error('Synthetic dump failure synthetic-host-password synthetic-old-password');
|
||||
if (args[0] === 'inspect') return 'true';
|
||||
if (args[0] === 'exec' && args[1] === 'nod-browser-fixture') {
|
||||
if (args[0] === 'exec' && args[1] === names.browser && outcome === 'aborted') {
|
||||
blocked();
|
||||
if (outcome === 'callback-failed') release();
|
||||
await Promise.race([
|
||||
browser,
|
||||
new Promise((_, reject) =>
|
||||
signal.signal.addEventListener('abort', () => reject(signal.signal.reason), {
|
||||
once: true,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
await new Promise((_, reject) =>
|
||||
signal.signal.addEventListener('abort', () => reject(signal.signal.reason), {
|
||||
once: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
let settled = false;
|
||||
const operation = finishRuntime({
|
||||
const runs = (name) =>
|
||||
calls.filter(
|
||||
(command) => Array.isArray(command) && command[0] === 'run' && command.includes(name),
|
||||
).length;
|
||||
let onMoved = 0;
|
||||
const result = finishRuntime({
|
||||
dataRoot: root,
|
||||
resourcesPath: root,
|
||||
assets: root,
|
||||
identity: 'fixture',
|
||||
identity,
|
||||
manifest: {
|
||||
images: ['postgres', 'workspace', 'browser'].map((name) => ({
|
||||
name,
|
||||
id: `sha256:${name}`,
|
||||
})),
|
||||
},
|
||||
saved: { port: 54329, password: 'synthetic-fixture-password' },
|
||||
saved: { port: 54329, password: 'synthetic-old-password' },
|
||||
controlRoot: root,
|
||||
docker: join(root, 'docker-fixture'),
|
||||
path: process.env.PATH,
|
||||
@@ -5677,149 +5331,94 @@ test('runtime hands off verified storage before browser readiness and fences fai
|
||||
status() {},
|
||||
prepareImage: async (name) => {
|
||||
calls.push(['prepare-image', name]);
|
||||
if (name !== 'postgres') await handed;
|
||||
windows?.run('image', name);
|
||||
},
|
||||
async onStorageReady(runtime) {
|
||||
callbacks++;
|
||||
if (windows)
|
||||
assert.deepEqual(Object.keys((await windows.read()).images), ['synthetic:postgres']);
|
||||
assert.equal(verified, true);
|
||||
assert.ok(calls.includes('database-end'));
|
||||
assert.equal(
|
||||
calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
command[0] === 'run' &&
|
||||
command.includes('nod-workspace-fixture'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(runtime.env, runtime.environment);
|
||||
assert.equal(new URL(runtime.env.DATABASE_URL).port, '54329');
|
||||
assert.equal(runtime.env.WORKSPACE_CONTAINER, 'nod-workspace-fixture');
|
||||
if (process.platform !== 'win32')
|
||||
assert.ok((await stat(join(root, 'bin/docker'))).isFile());
|
||||
storage = runtime;
|
||||
handedOff();
|
||||
if (outcome === 'callback-failed') throw new Error('Synthetic engine startup failed');
|
||||
await handoff;
|
||||
database,
|
||||
onMoved: async () => {
|
||||
onMoved++;
|
||||
},
|
||||
}).then(
|
||||
(runtime) => {
|
||||
settled = true;
|
||||
return runtime;
|
||||
},
|
||||
(error) => {
|
||||
settled = true;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
const result = operation.then(
|
||||
(runtime) => ({ runtime }),
|
||||
(error) => ({ error }),
|
||||
);
|
||||
try {
|
||||
if (outcome === 'callback-failed') {
|
||||
const failed = await result;
|
||||
assert.match(failed.error?.message ?? '', /Synthetic engine startup failed/);
|
||||
assert.equal(
|
||||
calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
command[0] === 'run' &&
|
||||
command.includes('nod-browser-fixture'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
await Promise.race([
|
||||
handed,
|
||||
waiting.then(() => {
|
||||
throw new Error('Browser started before storage handoff');
|
||||
}),
|
||||
result.then((value) => {
|
||||
throw value.error ?? new Error('Runtime completed before storage handoff');
|
||||
}),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
calls.filter((command) => Array.isArray(command) && command[0] === 'prepare-image'),
|
||||
[
|
||||
['prepare-image', 'postgres'],
|
||||
['prepare-image', 'workspace'],
|
||||
['prepare-image', 'browser'],
|
||||
],
|
||||
);
|
||||
if (outcome === 'aborted-handoff') {
|
||||
signal.abort(new Error('Synthetic setup cancelled during handoff'));
|
||||
continueSetup();
|
||||
assert.equal((await result).error, signal.signal.reason);
|
||||
assert.equal(
|
||||
calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
command[0] === 'run' &&
|
||||
command.includes('nod-workspace-fixture'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
continueSetup();
|
||||
if (outcome === 'windows-failed' || outcome === 'windows-damaged') {
|
||||
assert.ok((await result).error);
|
||||
assert.ok(storage);
|
||||
assert.equal(callbacks, 1);
|
||||
if (outcome === 'windows-damaged')
|
||||
assert.equal(
|
||||
(await windows.read()).commands.some(
|
||||
(command) => command[0] === 'load' && command.at(-1).endsWith('/browser.tar.zst'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
command[0] === 'run' &&
|
||||
command.includes('nod-browser-fixture'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await Promise.race([
|
||||
waiting,
|
||||
result.then((value) => {
|
||||
throw value.error ?? new Error('Runtime completed before browser gate');
|
||||
}),
|
||||
]);
|
||||
assert.equal(callbacks, 1);
|
||||
assert.ok(storage);
|
||||
assert.equal(settled, false);
|
||||
if (outcome === 'aborted') signal.abort(new Error('Synthetic setup cancelled'));
|
||||
else release();
|
||||
const finished = await result;
|
||||
if (outcome === 'aborted') {
|
||||
assert.equal(finished.error?.name, 'AbortError');
|
||||
assert.equal(finished.error?.cause, signal.signal.reason);
|
||||
} else assert.equal(finished.runtime, storage);
|
||||
}
|
||||
assert.equal(callbacks, 1);
|
||||
assert.equal(
|
||||
calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
['volume', 'network'].includes(command[0]) &&
|
||||
command[1] === 'rm',
|
||||
),
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
continueSetup();
|
||||
release();
|
||||
await result;
|
||||
if (outcome === 'aborted') {
|
||||
await waiting;
|
||||
signal.abort(new Error('Synthetic setup cancelled'));
|
||||
}
|
||||
const { runtime, error } = await result;
|
||||
assert.equal(onMoved, 0);
|
||||
assert.equal(moved, 0);
|
||||
assert.equal(calls.includes('database-connect'), outcome === 'move-failed');
|
||||
assert.ok(
|
||||
!calls.some(
|
||||
(command) =>
|
||||
Array.isArray(command) &&
|
||||
['volume', 'network'].includes(command[0]) &&
|
||||
command[1] === 'rm',
|
||||
),
|
||||
);
|
||||
if (outcome === 'move-failed') {
|
||||
assert.equal(error.code, 'NOD_DATABASE_MOVE_FAILED');
|
||||
assert.match(error.details, /Synthetic dump failure/);
|
||||
assert.doesNotMatch(
|
||||
startupErrorDetails(error),
|
||||
/synthetic-host-password|synthetic-old-password/,
|
||||
);
|
||||
assert.equal(database.pendingMove, true);
|
||||
assert.equal(runs(names.postgres), 1);
|
||||
assert.equal(runs(names.workspace), 0);
|
||||
assert.deepEqual(
|
||||
calls.filter((command) => command[0] === 'prepare-image'),
|
||||
[['prepare-image', 'postgres']],
|
||||
);
|
||||
return;
|
||||
}
|
||||
assert.equal(runs(names.postgres), 0);
|
||||
assert.equal(
|
||||
calls.some((command) => Array.isArray(command) && command.includes('pg_isready')),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls.some((command) => command[0] === 'prepare-image' && command[1] === 'postgres'),
|
||||
false,
|
||||
);
|
||||
const removal = calls.findIndex(
|
||||
(command) => Array.isArray(command) && command.join(' ') === `rm --force ${names.postgres}`,
|
||||
);
|
||||
assert.ok(removal >= 0);
|
||||
assert.ok(
|
||||
removal <
|
||||
calls.findIndex(
|
||||
(command) =>
|
||||
Array.isArray(command) && command[0] === 'run' && command.includes(names.workspace),
|
||||
),
|
||||
);
|
||||
if (windows)
|
||||
assert.deepEqual(
|
||||
Object.keys((await windows.read()).images).sort(),
|
||||
outcome === 'windows-damaged'
|
||||
? ['synthetic:workspace']
|
||||
: ['synthetic:browser', 'synthetic:workspace'],
|
||||
);
|
||||
if (outcome === 'windows-failed' || outcome === 'windows-damaged') {
|
||||
assert.ok(error);
|
||||
assert.equal(runs(names.browser), 0);
|
||||
return;
|
||||
}
|
||||
if (outcome === 'aborted') {
|
||||
assert.equal(error?.name, 'AbortError');
|
||||
assert.equal(error?.cause, signal.signal.reason);
|
||||
return;
|
||||
}
|
||||
assert.equal(error, undefined);
|
||||
assert.deepEqual(Object.keys(runtime).sort(), ['close', 'environment']);
|
||||
assert.deepEqual(Object.keys(runtime.environment).sort(), [
|
||||
'DOCKER_CONFIG',
|
||||
'DOCKER_CONTEXT',
|
||||
'DOCKER_HOST',
|
||||
'PATH',
|
||||
]);
|
||||
if (process.platform !== 'win32') assert.ok((await stat(join(root, 'bin/docker'))).isFile());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+481
-346
File diff suppressed because it is too large.
Load diff
@@ -65,33 +65,33 @@ Desktop settings format 2 stores device setup progress without account completio
|
||||
```mermaid
|
||||
flowchart LR
|
||||
window[Nod window]:::accent -- per-launch token --> server[Nod server<br/>Electron]
|
||||
server --> db[(PostgreSQL)]
|
||||
server --> provider[Model provider]:::muted
|
||||
subgraph computer [Private Linux computer]
|
||||
db[(PostgreSQL)]
|
||||
workspace[Workspace<br/>container]
|
||||
browser[Browser<br/>container]
|
||||
end
|
||||
server --> db
|
||||
server --> workspace
|
||||
server --> browser
|
||||
```
|
||||
|
||||
Your data lives in PostgreSQL, which runs on your computer next to the Nod server. Chat, connected apps, memory, schedules, Telegram and WhatsApp need only these two. The private Linux computer runs code and web pages in isolation, so only the workspace and browser need it. It starts in the background, and chat doesn't wait for it, except once while Nod moves data that is still inside the private computer.
|
||||
|
||||
<Tabs syncKey="os">
|
||||
<TabItem label="Mac" icon="apple">
|
||||
|
||||
- Electron runs the app window and the Nod server. While you use 1Password, a separate helper talks to the 1Password app; it's the only Nod process allowed to load 1Password's library.
|
||||
- When you turn on [computer use](/connect/computer-use/), which is experimental, Nod runs [agent-desktop](https://github.com/vercel-labs/agent-desktop) by Vercel Labs, bundled in the app, to read app windows through macOS accessibility and act on them in the background where it can, bringing an app forward for some steps. Nod runs one command at a time, keeps its working files in Nod's private profile folder, and needs the Accessibility and, for window pictures, Screen Recording permissions you grant in System Settings.
|
||||
- Lima and Apple's Virtualization framework run a private Ubuntu virtual machine. New installations use Ubuntu 26.04 LTS, including the systemd fixes for a [first-boot login-session race](https://github.com/lima-vm/lima/issues/5570) that could otherwise stall startup for several minutes. Existing installations keep their guest and data. The VM gets half your memory, between 3 and 6 GiB, and a 24 GiB disk that grows as it's used. Its first boot installs the matching firewall packages from the runtime pack, and uses Ubuntu's package servers only if that installation fails.
|
||||
- The VM holds PostgreSQL and separate workspace and browser containers. Docker runs only inside the VM.
|
||||
- The VM holds separate workspace and browser containers. Docker runs only inside the VM.
|
||||
- The VM keeps automatic security updates for other packages. Automatic updates cannot replace its Linux kernel, GRUB, or shim, or restart the VM. Kernel security fixes need a tested, explicit upgrade. A new runtime pack does not upgrade an existing VM's kernel.
|
||||
- At each start, Nod loads its container protection before it starts PostgreSQL. The profile keeps Docker's restrictions and permits signals and process tracing with the exact `docker-default//&unconfined` stacked peer. This repairs the [Ubuntu kernel regression](https://github.com/containerd/containerd/issues/14485) without disabling AppArmor or its namespace restrictions. Existing installations receive the repair and keep their data.
|
||||
- At each start, Nod loads its container protection before it starts any container. The profile keeps Docker's restrictions and permits signals and process tracing with the exact `docker-default//&unconfined` stacked peer. This repairs the [Ubuntu kernel regression](https://github.com/containerd/containerd/issues/14485) without disabling AppArmor or its namespace restrictions. Existing installations receive the repair and keep their data.
|
||||
|
||||
</TabItem>
|
||||
<TabItem label="Windows" icon="seti:windows">
|
||||
|
||||
- Electron runs the app window and the Nod server. While you use 1Password, a separate helper talks to the 1Password app.
|
||||
- A private WSL 2 distribution named `nod-<profile>` holds PostgreSQL and separate workspace and browser containers. Docker runs only inside it.
|
||||
- Nod reaches PostgreSQL through WSL's localhost forwarding, on a loopback port it picks free at each launch.
|
||||
- A private WSL 2 distribution named `nod-<profile>` holds separate workspace and browser containers. Docker runs only inside it.
|
||||
- Nod doesn't change your default WSL distribution or global WSL settings.
|
||||
- [Computer use](/connect/computer-use/), experimental here, runs the bundled agent-desktop through Windows UI Automation. It needs no permission, and can't operate apps that run as administrator.
|
||||
|
||||
@@ -99,7 +99,7 @@ flowchart LR
|
||||
<TabItem label="Linux (preview)" icon="linux">
|
||||
|
||||
- A Flatpak runs Electron, the Nod server and the same Lima runtime as the Mac, with QEMU and KVM instead of Apple's Virtualization framework. Install the [Linux x64 preview](/get-started/install-desktop/#linux), or [build the Flatpak](/contribute/desktop-releases/#build-a-linux-flatpak).
|
||||
- The VM, its firewall rules, container protection and the PostgreSQL, workspace and browser containers are the same as on a Mac. Docker runs only inside the VM, and Nod never uses a Docker installation on your computer.
|
||||
- The VM, its firewall rules, container protection and the workspace and browser containers are the same as on a Mac. Docker runs only inside the VM, and Nod never uses a Docker installation on your computer.
|
||||
- Nod needs `/dev/kvm`. Without hardware virtualization it refuses to start its private computer rather than fall back to slow emulation.
|
||||
- The VM files live in `~/.nod-desktop`, as on a Mac. Saved keys use your desktop's Secret Service, such as GNOME Keyring or KWallet; Nod refuses to save keys when no secret store is available.
|
||||
- A Flatpak installed from a Nod repository updates itself through the Flatpak portal, once such a repository is published; none is yet. A Flatpak installed from a bundle file has no repository, so install the next release bundle to update it. An RPM install shows a notice that says to run `sudo dnf upgrade nod`, but the command needs a `dnf` package repository, which is not published yet. See [Update Nod](/get-started/install-desktop/#update-nod).
|
||||
@@ -111,15 +111,23 @@ flowchart LR
|
||||
|
||||
The workspace and browser have separate networks, no access to your home folder, no Docker socket and no model keys. Model requests go to the provider you connect, or to a [local model](/connect/local-models/) server you run.
|
||||
|
||||
## Your database
|
||||
|
||||
The app includes PostgreSQL 17 for Mac, Windows and Linux. Nod creates the database in the profile's `database` folder on first launch, which takes about a second. It listens only on `127.0.0.1`, on a port Nod picks at each launch, and needs a password that stays in the profile folder. Nod starts it before the server and stops it when you quit. If Nod quit unexpectedly, the next launch stops the old database process first.
|
||||
|
||||
If a profile's data is still inside the private computer, Nod moves it once. It starts the private computer, copies every table into the new database in one transaction, and checks that each table has the same number of rows. Only then does Nod use the new database. Before copying, Nod checks for free disk space of about twice the data's size plus 256 MB. If the copy fails, nothing changes; select **Try again** or open Nod again to retry. The old database stays on the private computer's disk.
|
||||
|
||||
When the private computer can't start, Nod keeps running. A tool that needs the workspace or browser waits while the computer starts, or reports why it can't. Nod shows the cause with **Try again**, or **Install WSL** on Windows.
|
||||
|
||||
## Onboarding during startup
|
||||
|
||||
On a new desktop profile, choose **Get started** to start a local assistant or **Connect to a server**. The private computer and its database start in the background as soon as the welcome screen opens, so they are often ready by the time you continue. On a new profile with no saved keys, Nod's own service starts then too. When the profile has saved keys, the service, and any request to unlock them, waits until you select **Get started**. If the service is still starting when you continue, Nod already shows the email step and turns on its Connect buttons when the service is ready. Choosing a server stops the local computer when the app restarts. Nod waits for PostgreSQL and the server when needed, then continues at the email step. Email is offered before model selection and can be skipped. The workspace and browser continue starting during onboarding. A model is required to finish local desktop setup, and Nod tries to turn on Open at login when setup finishes. Usage data sharing is on by default for a new profile and can be turned off in **Settings → Privacy & data**. Conversation traces, other apps, Telegram and WhatsApp are optional.
|
||||
On a new desktop profile, choose **Get started** to start a local assistant or **Connect to a server**. The database and the private computer start as soon as the welcome screen opens. The database is ready in seconds; the private computer keeps starting in the background. On a new profile with no saved keys, Nod's own service starts then too. When the profile has saved keys, the service, and any request to unlock them, waits until you select **Get started**. If the service is still starting when you continue, Nod already shows the email step and turns on its Connect buttons when the service is ready. Choosing a server stops the local computer when the app restarts. Nod waits for the database and the server when needed, then continues at the email step. Email is offered before model selection and can be skipped. Onboarding never waits for the workspace or browser, and chat opens as soon as setup finishes. A model is required to finish local desktop setup, and Nod tries to turn on Open at login when setup finishes. Usage data sharing is on by default for a new profile and can be turned off in **Settings → Privacy & data**. Conversation traces, other apps, Telegram and WhatsApp are optional.
|
||||
|
||||
Before the server starts, the native window saves only the usage data setting and whether Welcome was completed. After the ordinary account API accepts that choice, Nod records its acknowledgment. The email step preview stays visible until the main window can show its account choices or an actionable error. That handoff does not wait for the full app catalog, workspace or browser. A restart does not repeat Welcome or overwrite the saved analytics choice; the temporary marker is removed when device setup progress is saved. Sign-ins, keys and connections use the normal server and storage from the beginning; there is no separate setup backend or credential transfer. The first chat opens with a short greeting and idea cards, under the normal chat and memory rules.
|
||||
|
||||
When local setup finishes, Nod tries to turn on Open at login and checks it with the operating system. On Linux, Open at login adds `io.n8n.Nod.desktop` to your autostart folder, `$XDG_CONFIG_HOME/autostart` or `~/.config/autostart`. In the Flatpak the entry runs `flatpak run io.n8n.Nod`; in the RPM it runs `nod`. If the operating system blocks this setting, setup still finishes. A restart does not repeat this attempt. A settings storage error still requires a retry. You can turn it off in **Settings → General**. The first stored chat introduction offers an explicit choice to enable notifications. Rendering the introduction does not change the saved preference. macOS may ask for permission; your system settings control delivery. Existing notification choices are preserved. Enabling delivery does not authorize app monitoring or scheduled work. If alerts are blocked, allow Nod in the computer’s notification settings. The web app uses the same onboarding. A completed installation keeps its choices and skips onboarding after an update.
|
||||
|
||||
If the user finishes first, an animated Nod logo stays visible until the workspace and browser are ready and completion has been saved. If the services are already ready, chat opens directly without a preparation screen. Runtime failures offer an explicit retry without clearing saved connections. The logo uses the same bounce as Welcome while work continues and pauses on an error. While the runtime pack downloads, the logo's dot travels around its ring as the download progresses, and the screen shows the percentage and the time left, estimated from the last 45 seconds. If no data arrives for five seconds, the dot fades and the screen says Nod is waiting for the network. The Dock icon, or the taskbar button on Windows, shows the same progress. On a Mac, the Dock icon bounces once when Nod is ready for you to carry on, if you're using another app. Assistive technology reads the same progress. The screen groups detailed startup events into a few messages, while diagnostics keep the individual stages. If completion reports a missing setup requirement, onboarding returns to the relevant step. If notifications are enabled and Nod is not focused, a single notification announces when setup is ready.
|
||||
If you finish before the server is ready, an animated Nod logo stays visible until it is ready and completion has been saved. Otherwise chat opens directly. After an update from a version that kept the database inside the private computer, the logo stays until the private computer has started and the data has moved. Database and server failures offer an explicit retry without clearing saved connections. The logo uses the same bounce as Welcome while work continues and pauses on an error. While the runtime pack downloads during that move, the logo's dot travels around its ring as the download progresses, and the screen shows the percentage and the time left, estimated from the last 45 seconds. If no data arrives for five seconds, the dot fades and the screen says Nod is waiting for the network. The Dock icon, or the taskbar button on Windows, shows the same progress. On a Mac, the Dock icon bounces once when Nod is ready for you to carry on, if you're using another app. Assistive technology reads the same progress. The screen groups detailed startup events into a few messages, while diagnostics keep the individual stages. If completion reports a missing setup requirement, onboarding returns to the relevant step. If notifications are enabled and Nod is not focused, a single notification announces when setup is ready.
|
||||
|
||||
## The runtime pack
|
||||
|
||||
@@ -153,30 +161,33 @@ App connections use Nod's connection service. The private installation identity
|
||||
<Tabs syncKey="os">
|
||||
<TabItem label="Mac" icon="apple">
|
||||
|
||||
| What | Where |
|
||||
| ------------------------------- | ----------------------------------------------------- |
|
||||
| App settings and profile | `~/Library/Application Support/nod/profiles/local` |
|
||||
| Private VM, database, workspace | `~/.nod-desktop/<profile>` |
|
||||
| Runtime packs | `~/Library/Application Support/nod/runtime/<release>` |
|
||||
| What | Where |
|
||||
| ------------------------ | ----------------------------------------------------------- |
|
||||
| App settings and profile | `~/Library/Application Support/nod/profiles/local` |
|
||||
| Database | `~/Library/Application Support/nod/profiles/local/database` |
|
||||
| Private VM and workspace | `~/.nod-desktop/<profile>` |
|
||||
| Runtime packs | `~/Library/Application Support/nod/runtime/<release>` |
|
||||
|
||||
</TabItem>
|
||||
<TabItem label="Windows" icon="seti:windows">
|
||||
|
||||
| What | Where |
|
||||
| ----------------------------- | -------------------------------- |
|
||||
| App settings and profile | `%APPDATA%\nod\profiles\local` |
|
||||
| Private computer and database | WSL distribution `nod-<profile>` |
|
||||
| What | Where |
|
||||
| ------------------------ | --------------------------------------- |
|
||||
| App settings and profile | `%APPDATA%\nod\profiles\local` |
|
||||
| Database | `%APPDATA%\nod\profiles\local\database` |
|
||||
| Private computer | WSL distribution `nod-<profile>` |
|
||||
|
||||
Windows file permissions protect the profile folder. Uninstalling removes the app but keeps the profile and the distribution.
|
||||
|
||||
</TabItem>
|
||||
<TabItem label="Linux (preview)" icon="linux">
|
||||
|
||||
| What | Where |
|
||||
| ------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| App settings and profile | `~/.var/app/io.n8n.Nod/config/nod/profiles/local` |
|
||||
| Private VM, database, workspace | `~/.nod-desktop/<profile>` |
|
||||
| Runtime packs | `$XDG_DATA_HOME/nod/runtime/<release>`, or `~/.var/app/io.n8n.Nod/data/nod/runtime/<release>` in the Flatpak |
|
||||
| What | Where |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------------------------------ |
|
||||
| App settings and profile | `~/.var/app/io.n8n.Nod/config/nod/profiles/local` |
|
||||
| Database | `~/.var/app/io.n8n.Nod/config/nod/profiles/local/database` |
|
||||
| Private VM and workspace | `~/.nod-desktop/<profile>` |
|
||||
| Runtime packs | `$XDG_DATA_HOME/nod/runtime/<release>`, or `~/.var/app/io.n8n.Nod/data/nod/runtime/<release>` in the Flatpak |
|
||||
|
||||
To remove Nod completely, choose **Remove all data** first, then run `flatpak uninstall --delete-data io.n8n.Nod`. If you only uninstall, the private computer stays in `~/.nod-desktop` and the runtime packs stay too. `--delete-data` removes the runtime packs along with the rest of the app's data directory.
|
||||
|
||||
@@ -254,12 +265,12 @@ If a manual update check fails, choose **Try again** or **Not now** and keep usi
|
||||
|
||||
The Windows app has a few extra needs.
|
||||
|
||||
| Need | Detail |
|
||||
| ------- | ------------------------------------------------------------------------------------------- |
|
||||
| System | Windows 11 x64 with hardware virtualization |
|
||||
| WSL | WSL 2 with default localhost forwarding or mirrored networking. Nod offers **Install WSL**. |
|
||||
| Disk | At least 20 GB free |
|
||||
| Signing | Signed by n8n GmbH. SmartScreen can still warn about a new release. |
|
||||
| Need | Detail |
|
||||
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| System | Windows 11 x64 with hardware virtualization |
|
||||
| WSL | WSL 2 for the workspace and browser. When it's missing, Nod installs it once after setup; approve the administrator request and restart the PC. Chat works without it. |
|
||||
| Disk | At least 20 GB free |
|
||||
| Signing | Signed by n8n GmbH. SmartScreen can still warn about a new release. |
|
||||
|
||||
Inside Nod's distribution, drive mounts and Windows process access are turned off. Closing the window keeps Nod in the tray. **Quit Nod** stops only its own distribution.
|
||||
|
||||
@@ -307,6 +318,8 @@ The packaged engine includes only the packages in `dependencies` and what they d
|
||||
| Replay onboarding | `pnpm --dir desktop start --onboarding` |
|
||||
| Use a fresh, throwaway profile | `NOD_DESKTOP_USER_DATA=/tmp/nod-onboarding-review pnpm --dir desktop start --onboarding` |
|
||||
|
||||
The first unpackaged start downloads the PostgreSQL build for your computer into `postgres/` at the repository root, checks its SHA-256 and reuses it afterwards. Packaged builds include it.
|
||||
|
||||
`NOD_DESKTOP_USER_DATA` works in development and in the deliberately marked [isolated test build](/contribute/desktop-releases/#test-a-local-mac-build). Normal packaged apps always use their own profile.
|
||||
|
||||
To test a local connection service, run the unpackaged app with a new, absolute profile path and a proxy origin:
|
||||
|
||||
@@ -119,14 +119,14 @@ Startup repairs the private computer instead of stopping:
|
||||
|
||||
- If WSL no longer lists a completed computer, Nod registers its saved disk again. Your data stays.
|
||||
- If that disk is gone or WSL can't open it, Nod sets up a new computer and leaves the old disk where it was.
|
||||
- If the saved configuration is missing, damaged or invalid while WSL still lists the computer, Nod can't open its database. It removes that computer, which deletes its data, and sets up a new one.
|
||||
- If WSL lists the computer but still reports it as installing or uninstalling, its disk is unfinished. Nod removes it, which deletes its data, and sets up a new one.
|
||||
- If the saved configuration is missing, damaged or invalid while WSL still lists the computer, Nod can't open it. It removes that computer, which deletes its workspace files, and sets up a new one. Conversations and settings stay in your database, unless its data had not moved out of that computer yet.
|
||||
- If WSL lists the computer but still reports it as installing or uninstalling, its disk is unfinished. Nod removes it, which deletes its workspace files, and sets up a new one.
|
||||
|
||||
If setup needs more disk space, select a folder on another drive or free space. A different folder on the same drive still needs space for both the setup files and the private computer. Nod keeps a verified download for the next attempt.
|
||||
|
||||
On a Mac, setup keeps runtime files that passed their checks, even if a later download fails. **Try again** checks and reuses those files. It does not remove a verified image while the private computer loads it.
|
||||
|
||||
On Windows, database errors show whether PostgreSQL stopped, reached a memory limit, or failed its TCP check inside WSL. If PostgreSQL answers inside WSL, the error names the Windows connection that failed. Open **Technical details** to read the original error, its code, its stack, and available native command output. These details also appear in the startup log. Saved secrets are removed.
|
||||
Database errors name the step that failed: reading its saved settings (`NOD_DATABASE_STATE_INVALID`), finding free disk space (`NOD_DATABASE_STORAGE_FULL`), creating the database (`NOD_DATABASE_SETUP_FAILED`), starting it (`NOD_DATABASE_START_FAILED`), connecting to it (`NOD_DATABASE_CONNECTION_FAILED`), or moving data out of the private computer (`NOD_DATABASE_MOVE_FAILED`). A failed move changes nothing; select **Try again** or open Nod again to retry it. Before a move, Nod checks for free disk space of about twice the data's size plus 256 MB and reports `NOD_DATABASE_STORAGE_FULL` when there isn't enough. Open **Technical details** to read the original error, its code, its stack, the last lines of the database log and available native command output. These details also appear in the startup log. Saved secrets are removed.
|
||||
|
||||
During use, Nod waits up to 30 seconds for each query reply after it gets a database connection. The wait for a connection has a separate timeout. If the connection stops returning data, Nod closes it and reports the failure. Nod does not repeat the failed work. After the connection is restored, a new request can use a new connection. Check the result of an action before you ask Nod to do it again.
|
||||
|
||||
@@ -148,15 +148,15 @@ Nod versions before 0.7.0 on Windows can't install their own updates. Quit Nod f
|
||||
|
||||
### Windows says WSL is missing
|
||||
|
||||
Nod says it could not start WSL 2 when WSL is missing, when Windows has not turned on its virtual machine feature, or when WSL needs an update. The message ends with the error from Windows, in your language.
|
||||
Nod needs WSL 2 only for its workspace and browser. Chat, apps, memory and schedules work without it. Nod says it could not start WSL 2 when WSL is missing, when Windows has not turned on its virtual machine feature, or when WSL needs an update. The message ends with the error from Windows, in your language.
|
||||
|
||||
Select **Install WSL** in Nod, approve the administrator request, restart the PC and open Nod again. This installs or updates WSL and turns on the features it needs. A device policy can block WSL installation. If the Windows error says virtualization is turned off, turn it on in your PC's firmware settings first.
|
||||
When WSL is missing, Nod starts installing it once after setup. Approve the administrator request, then restart the PC. If you declined or the install failed, select **Install WSL** in Nod's notice. This installs or updates WSL and turns on the features it needs. A device policy can block WSL installation. If the Windows error says virtualization is turned off, turn it on in your PC's firmware settings first.
|
||||
|
||||
A recognized WSL location conflict, access error, or import error keeps its specific cause. These errors do not offer **Install WSL**.
|
||||
|
||||
### PostgreSQL fails after a Mac VM kernel update
|
||||
### Moving data fails after a Mac VM kernel update
|
||||
|
||||
Ubuntu kernels `7.0.0-42` and `7.0.0-43` can block signals inside containers. The PostgreSQL user-switch process then waits forever, and Nod reports `NOD_DATABASE_CONNECTION_FAILED`.
|
||||
Ubuntu kernels `7.0.0-42` and `7.0.0-43` can block signals inside containers. When Nod starts the old PostgreSQL inside the private computer to move your data, its user-switch process then waits forever, and Nod reports `NOD_DATABASE_MOVE_FAILED`.
|
||||
|
||||
Install a Nod build with the container profile repair, then quit and reopen Nod. The repair keeps AppArmor active and preserves the database volume. It also prevents further automatic kernel changes and VM restarts. A restart alone does not repair the old profile. Do not delete the VM or database to fix this failure.
|
||||
|
||||
|
||||
@@ -69,9 +69,10 @@ Before it replaces Nod, the installer stops any old ShipIt update job and remove
|
||||
</TabItem>
|
||||
<TabItem label="Windows" icon="seti:windows">
|
||||
|
||||
You need Windows 11 on an Intel or AMD x64 computer. A local assistant also needs WSL
|
||||
2 with hardware virtualization and at least 20 GB of free disk space. Its app and runtime are about
|
||||
2.1 GB to download. Connecting to a server doesn't need WSL or a local runtime.
|
||||
You need Windows 11 on an Intel or AMD x64 computer. Chat works as soon as setup finishes. A local
|
||||
assistant's workspace and browser also need WSL 2 with hardware virtualization and at least 20 GB of
|
||||
free disk space; their runtime downloads in the background. Connecting to a server doesn't need WSL
|
||||
or a local runtime.
|
||||
|
||||
The desktop app does not support Windows on Arm. You can open a [self-hosted Nod server](/deploy/self-host/#open-a-remote-server-without-a-domain) in your browser instead.
|
||||
|
||||
@@ -83,7 +84,7 @@ The desktop app does not support Windows on Arm. You can open a [self-hosted Nod
|
||||
|
||||
3. At Welcome, choose **Connect to a server** to use an existing assistant, or **Get started** to start a local one. Local setup offers an optional email connection, a few optional questions about you, a model if none works yet, a choice about conversation traces, which also says basic usage data is shared by default for new owners and can be turned off in **Settings → Privacy & data**, and an optional email address for updates about Nod and other n8n products, with its own consent checkbox. Discord and forum links are also in **Settings → General**. Other apps can be connected later from the first chat or **Apps**. Nod tries to turn on **Open at login** when local setup finishes. If the operating system blocks this setting, setup still finishes. After the first chat introduction, choose **Enable notifications** if you want Nod to alert you while you’re away. Windows notification settings control delivery. You can change these preferences later in Settings.
|
||||
|
||||
4. If Nod needs WSL, follow its setup instructions and approve the administrator request. If Windows needs a restart, open Nod again afterwards; your saved connections and settings are kept.
|
||||
4. If WSL is missing, Nod starts installing it after setup. Approve the administrator request and restart Windows when it's convenient; chat keeps working until then, and your saved connections and settings are kept.
|
||||
|
||||
5. Keep your internet connection on. When setup is ready, Nod opens your chat with your saved connections. See [Your first conversation](/get-started/first-conversation/).
|
||||
|
||||
|
||||
@@ -48,12 +48,12 @@ Nod is designed to check with you before it sends, posts or deletes anything you
|
||||
|
||||
## Where Nod runs
|
||||
|
||||
| | Local desktop assistant | Local source install | Self-hosted server |
|
||||
| -------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | --------------------------------------------------------------- |
|
||||
| Best for | Using Nod on your own computer | Running from source, or changing Nod's code | Reaching one assistant from several devices |
|
||||
| Runs on | Mac (Apple silicon or Intel), Windows 11, Linux x64 preview | macOS, Linux or Windows with Docker | A machine with Docker Compose |
|
||||
| You need | Mac: macOS 14 or later. Windows local: WSL 2 and virtualization. Linux: Flatpak and a secret store; KVM for local use. | Node.js, pnpm, Docker and Git | [Server setup](/deploy/self-host/) and HTTPS for network access |
|
||||
| Updates | Automatic on Mac and Windows; Linux bundle installs get the next bundle manually | `git pull` and restart | [Update the server](/deploy/server-operations/) |
|
||||
| | Local desktop assistant | Local source install | Self-hosted server |
|
||||
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | --------------------------------------------------------------- |
|
||||
| Best for | Using Nod on your own computer | Running from source, or changing Nod's code | Reaching one assistant from several devices |
|
||||
| Runs on | Mac (Apple silicon or Intel), Windows 11, Linux x64 preview | macOS, Linux or Windows with Docker | A machine with Docker Compose |
|
||||
| You need | Mac: macOS 14 or later. Windows local: WSL 2 and virtualization for the workspace and browser. Linux: Flatpak and a secret store; KVM for local use. | Node.js, pnpm, Docker and Git | [Server setup](/deploy/self-host/) and HTTPS for network access |
|
||||
| Updates | Automatic on Mac and Windows; Linux bundle installs get the next bundle manually | `git pull` and restart | [Update the server](/deploy/server-operations/) |
|
||||
|
||||
The desktop app can also connect to a server. Its chat, files, model connections and connected apps then come from that server. Closing the client doesn't stop the assistant.
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ See [Task sessions](/how-it-works/task-sessions/) for the architecture diagram,
|
||||
|
||||
## One process and a few containers
|
||||
|
||||
One Node process serves the React client and runs the Fastify API, the agent runtime, the thread-drain worker and the schedulers. Docker containers run PostgreSQL, the workspace and the browser. While you pick a login from 1Password, a separate helper process talks to the 1Password app, so the server never loads 1Password's code.
|
||||
One Node process serves the React client and runs the Fastify API, the agent runtime, the thread-drain worker and the schedulers. It stores its records in PostgreSQL. Docker containers run the workspace and the browser. The desktop app runs PostgreSQL next to the server and the containers inside its private computer, so chat never waits for the containers; a server you host runs PostgreSQL as a container too. While you pick a login from 1Password, a separate helper process talks to the 1Password app, so the server never loads 1Password's code.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
"pdfjs-dist": "6.4.299",
|
||||
"pg": "^8.23.1",
|
||||
"pg-boss": "12.38.2",
|
||||
"pg-copy-streams": "7.0.0",
|
||||
"pi-web-access": "0.41.0",
|
||||
"posthog-node": "5.71.0",
|
||||
"react": "^19.3.1",
|
||||
|
||||
Generated
+8
@@ -143,6 +143,9 @@ importers:
|
||||
pg-boss:
|
||||
specifier: 12.38.2
|
||||
version: 12.38.2(@opentelemetry/api@1.9.1)
|
||||
pg-copy-streams:
|
||||
specifier: 7.0.0
|
||||
version: 7.0.0
|
||||
pi-web-access:
|
||||
specifier: 0.41.0
|
||||
version: 0.41.0(@cfworker/json-schema@4.1.6)(@earendil-works/pi-ai@1.5.2(patch_hash=ddb0630891a99c017c0a5add6245d04bb2f7b7b2bcf3aaf6c8a97aaa64fa45a5)(@aws-sdk/credential-provider-node@3.972.88)(@modelcontextprotocol/sdk@1.32.1(@cfworker/json-schema@4.1.6)(zod@4.6.7))(@smithy/signature-v4@5.7.4)(undici@8.12.4)(ws@8.22.0)(zod@4.6.7))(@earendil-works/pi-coding-agent@1.5.2(patch_hash=d0bb250616598663804958959a0bd72f2872a2537f264616aced3f9c5bf3c6c7)(@aws-sdk/credential-provider-node@3.972.88)(@modelcontextprotocol/sdk@1.32.1(@cfworker/json-schema@4.1.6)(zod@4.6.7))(@smithy/signature-v4@5.7.4)(ws@8.22.0)(zod@4.6.7))(@earendil-works/pi-tui@1.5.2)(@napi-rs/canvas@1.1.1)(typebox@1.4.4)(zod@4.6.7)
|
||||
@@ -3912,6 +3915,9 @@ packages:
|
||||
pg-connection-string@2.14.1:
|
||||
resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==}
|
||||
|
||||
pg-copy-streams@7.0.0:
|
||||
resolution: {integrity: sha512-zBvnY6wtaBRE2ae2xXWOOGMaNVPkXh1vhypAkNSKgMdciJeTyIQAHZaEeRAxUjs/p1El5jgzYmwG5u871Zj3dQ==}
|
||||
|
||||
pg-int8@1.0.1:
|
||||
resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==}
|
||||
engines: {node: '>=4.0.0'}
|
||||
@@ -8844,6 +8850,8 @@ snapshots:
|
||||
|
||||
pg-connection-string@2.14.1: {}
|
||||
|
||||
pg-copy-streams@7.0.0: {}
|
||||
|
||||
pg-int8@1.0.1: {}
|
||||
|
||||
pg-pool@3.14.0(pg@8.23.1):
|
||||
|
||||
@@ -218,6 +218,7 @@ export interface ConnectedCliResult {
|
||||
export interface WorkspaceSession {
|
||||
path: string;
|
||||
instructions: string;
|
||||
available?(): boolean;
|
||||
exec(command: string, options?: WorkspaceExecOptions): Promise<{ exitCode: number }>;
|
||||
runConnectedCli?(
|
||||
cli: ConnectedCli,
|
||||
@@ -228,6 +229,7 @@ export interface WorkspaceSession {
|
||||
}
|
||||
export interface Workspace {
|
||||
connectedCliAvailable?: boolean;
|
||||
available?(): boolean;
|
||||
writeArtifact(
|
||||
threadId: string,
|
||||
path: string,
|
||||
|
||||
@@ -59,6 +59,7 @@ export function createBridgeComputer(options: {
|
||||
launch(input: BrowserCall): CommandProcess;
|
||||
launchPersistent?(): CommandProcess;
|
||||
available?(input: BrowserCall): boolean;
|
||||
ready?(signal?: AbortSignal): Promise<void>;
|
||||
timeoutMs?: number;
|
||||
drainTimeoutMs?: number;
|
||||
readyTimeoutMs?: number;
|
||||
@@ -270,6 +271,20 @@ export function createBridgeComputer(options: {
|
||||
transfer: { data?: Uint8Array; chunks?: Buffer[] } = {},
|
||||
recovery = false,
|
||||
forceOneShot = false,
|
||||
): Promise<unknown> {
|
||||
if (!options.ready || input.method === 'dispose')
|
||||
return dispatch(input, signal, transfer, recovery, forceOneShot);
|
||||
return options
|
||||
.ready(signal)
|
||||
.then(() => dispatch(input, signal, transfer, recovery, forceOneShot));
|
||||
}
|
||||
|
||||
function dispatch(
|
||||
input: BrowserCall,
|
||||
signal?: AbortSignal,
|
||||
transfer: { data?: Uint8Array; chunks?: Buffer[] } = {},
|
||||
recovery = false,
|
||||
forceOneShot = false,
|
||||
): Promise<unknown> {
|
||||
signal?.throwIfAborted();
|
||||
const request = browserRequest.parse({
|
||||
@@ -631,6 +646,7 @@ export function createBridgeComputer(options: {
|
||||
|
||||
async function* view(id: string, signal: AbortSignal): AsyncGenerator<Buffer> {
|
||||
const threadId = threadIdentity(id);
|
||||
await options.ready?.(signal);
|
||||
signal.throwIfAborted();
|
||||
if (
|
||||
disposed ||
|
||||
|
||||
@@ -24,6 +24,7 @@ export function createContainerBrowserComputer(options: {
|
||||
spawn?: BrowserBridgeLauncher;
|
||||
timeoutMs?: number;
|
||||
drainTimeoutMs?: number;
|
||||
ready?(signal?: AbortSignal): Promise<void>;
|
||||
}): Computer {
|
||||
const container = options.container ?? 'nod-browser';
|
||||
if (!/^nod-browser(?:-[a-zA-Z0-9_-]+)?$/.test(container))
|
||||
@@ -33,6 +34,7 @@ export function createContainerBrowserComputer(options: {
|
||||
namespace: browserNamespace(options.dataRoot),
|
||||
timeoutMs: options.timeoutMs,
|
||||
drainTimeoutMs: options.drainTimeoutMs,
|
||||
ready: options.ready,
|
||||
launch: () =>
|
||||
launch('docker', ['exec', '-i', '--user', 'node', container, 'node', '/app/bridge.mjs'], {
|
||||
env: serviceEnvironment(),
|
||||
|
||||
@@ -99,27 +99,31 @@ export function createDockerWorkspace(options: {
|
||||
container: string;
|
||||
workspaceRoot: string;
|
||||
spawn?: WorkspaceCommandLauncher;
|
||||
ready?(signal?: AbortSignal): Promise<void>;
|
||||
available?(): boolean;
|
||||
}): Workspace {
|
||||
const command = (threadId: string, args: string[], input: CommandInput) =>
|
||||
runWorkspaceCommand({
|
||||
container: options.container,
|
||||
threadId,
|
||||
args,
|
||||
...input,
|
||||
spawn: options.spawn,
|
||||
});
|
||||
const ready = options.ready;
|
||||
const run = ready
|
||||
? async (threadId: string, args: string[], input: CommandInput) => {
|
||||
await ready(input.signal);
|
||||
return command(threadId, args, input);
|
||||
}
|
||||
: command;
|
||||
return createCommandWorkspace({
|
||||
workspaceRoot: options.workspaceRoot,
|
||||
instructions:
|
||||
'Installed: Node, Python (pypdf, pdfplumber, pillow_heif, openpyxl, python-docx, python-pptx), LibreOffice (soffice), ffmpeg, yt-dlp, poppler-utils, qpdf, Ghostscript, Tesseract OCR, git, curl, ripgrep, jq and pipx. Install trusted Python libraries with pip install <package>, trusted CLIs with npm install -g <package> or pipx install <package>; /home/node persists across tasks and restarts. You have no sudo or display, so use a CLI or a web app in the browser, and IPv4 for internet access. Keep outputs in this workspace and never install on the owner\u2019s device.',
|
||||
runCommand: (id, args, input) =>
|
||||
runWorkspaceCommand({
|
||||
container: options.container,
|
||||
threadId: id,
|
||||
args,
|
||||
...input,
|
||||
spawn: options.spawn,
|
||||
}),
|
||||
runConnectedCommand: (id, args, input) =>
|
||||
runWorkspaceCommand({
|
||||
container: options.container,
|
||||
threadId: id,
|
||||
args,
|
||||
...input,
|
||||
spawn: options.spawn,
|
||||
}),
|
||||
runCommand: run,
|
||||
runConnectedCommand: run,
|
||||
available: options.available,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -143,6 +147,7 @@ export function createCommandWorkspace(options: {
|
||||
args: string[],
|
||||
input: CommandInput & { environment: Record<string, string>; cli: ConnectedCli },
|
||||
): Promise<CommandResult>;
|
||||
available?(): boolean;
|
||||
}): Workspace {
|
||||
let unavailable: string | undefined;
|
||||
let disposed = false;
|
||||
@@ -200,8 +205,10 @@ export function createCommandWorkspace(options: {
|
||||
if (result.exitCode) throw new Error('The workspace file operation failed.');
|
||||
return result;
|
||||
}
|
||||
const available = () => !disposed && !unavailable && options.available?.() !== false;
|
||||
return {
|
||||
connectedCliAvailable: Boolean(options.runConnectedCommand),
|
||||
available,
|
||||
dispose: async () => {
|
||||
disposed = true;
|
||||
lifecycle.abort();
|
||||
@@ -286,6 +293,7 @@ export function createCommandWorkspace(options: {
|
||||
return {
|
||||
path: `/workspace/${id}`,
|
||||
instructions: options.instructions,
|
||||
available,
|
||||
async exec(script, { input: stdin, signal, timeoutMs = 600_000, onData, notices } = {}) {
|
||||
const result = await command(
|
||||
id,
|
||||
|
||||
@@ -41,6 +41,18 @@ export function createContextOutput(workspace: WorkspaceSession, ownerHeader?: s
|
||||
signal?.throwIfAborted();
|
||||
const text = content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\n');
|
||||
const key = createHash('sha256').update(JSON.stringify(content)).digest('hex');
|
||||
const tail = Math.floor(previewCharacters / 2);
|
||||
const preview =
|
||||
text.length > previewCharacters ? text.slice(0, previewCharacters - tail) : text;
|
||||
const ending = tail && text.length > previewCharacters ? { tail: text.slice(-tail) } : {};
|
||||
if (!files.has(key) && workspace.available?.() === false)
|
||||
return JSON.stringify({
|
||||
characters: text.length,
|
||||
preview,
|
||||
...ending,
|
||||
message:
|
||||
'Nod’s workspace is unavailable right now, so only this preview of the full content is kept.',
|
||||
});
|
||||
let file = files.get(key);
|
||||
if (!file) {
|
||||
const directory = `${workspace.path}/.nod/outputs`;
|
||||
@@ -81,12 +93,11 @@ export function createContextOutput(workspace: WorkspaceSession, ownerHeader?: s
|
||||
await writeWorkspaceFile(workspace, `${workspace.path}/${file}`, Buffer.from(text), signal);
|
||||
files.set(key, file);
|
||||
}
|
||||
const tail = Math.floor(previewCharacters / 2);
|
||||
return JSON.stringify({
|
||||
workspaceFile: file,
|
||||
characters: text.length,
|
||||
preview: text.length > previewCharacters ? text.slice(0, previewCharacters - tail) : text,
|
||||
...(tail && text.length > previewCharacters ? { tail: text.slice(-tail) } : {}),
|
||||
preview,
|
||||
...ending,
|
||||
});
|
||||
};
|
||||
return {
|
||||
|
||||
+42
-11
@@ -33,7 +33,7 @@ import {
|
||||
OutputLimitError,
|
||||
ToolFailureError,
|
||||
} from '../ports/agent.ts';
|
||||
import type { Computer, Workspace } from '../ports/computer.ts';
|
||||
import type { Computer, Workspace, WorkspaceSession } from '../ports/computer.ts';
|
||||
import { BrowserActionError } from '../ports/computer.ts';
|
||||
import { threadIdentity } from '../ports/thread-identity.ts';
|
||||
import {
|
||||
@@ -201,6 +201,39 @@ function isToolResult(value: unknown): value is AgentToolResult {
|
||||
);
|
||||
}
|
||||
|
||||
function withFolders(session: WorkspaceSession, path: string, folders: string[]): WorkspaceSession {
|
||||
let created: Promise<void> | undefined;
|
||||
const ensure = (signal?: AbortSignal) =>
|
||||
(created ??= session
|
||||
.exec(`mkdir -p -- ${folders.map((folder) => `'${folder}'`).join(' ')}`, { signal })
|
||||
.then((result) => {
|
||||
if (result.exitCode)
|
||||
throw new Error(
|
||||
`Nod could not create the working folders for this work (exit code ${result.exitCode}).`,
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
created = undefined;
|
||||
throw error;
|
||||
}));
|
||||
return {
|
||||
...session,
|
||||
path,
|
||||
exec: async (command, options) => {
|
||||
await ensure(options?.signal);
|
||||
return session.exec(command, options);
|
||||
},
|
||||
...(session.runConnectedCli
|
||||
? {
|
||||
runConnectedCli: async (cli, args, environment, timeoutSeconds) => {
|
||||
await ensure();
|
||||
return session.runConnectedCli!(cli, args, environment, timeoutSeconds);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
||||
work.catch(() => {});
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
@@ -499,6 +532,7 @@ export function createAgentRuntime(dependencies: {
|
||||
|
||||
const spill = async (text: string) => {
|
||||
if (text.length <= inlineChars) return text;
|
||||
if (dependencies.workspace.available?.() === false) return text.slice(0, inlineChars);
|
||||
const name = `${randomUUID()}-error.txt`;
|
||||
try {
|
||||
await dependencies.workspace.writeArtifact(threadId, name, Buffer.from(text), signal);
|
||||
@@ -842,12 +876,11 @@ export function createAgentRuntime(dependencies: {
|
||||
let workspace = rootWorkspace;
|
||||
if (context.taskContext) {
|
||||
const path = `${rootWorkspace.path}/tasks/${context.taskContext.id}`;
|
||||
const created = await rootWorkspace.exec(
|
||||
`mkdir -p '${path}/drafts' '${path}/outputs' '${rootWorkspace.path}/shared'`,
|
||||
{ signal },
|
||||
);
|
||||
if (created.exitCode) throw new Error('The task folder could not be created.');
|
||||
workspace = { ...rootWorkspace, path };
|
||||
workspace = withFolders(rootWorkspace, path, [
|
||||
`${path}/drafts`,
|
||||
`${path}/outputs`,
|
||||
`${rootWorkspace.path}/shared`,
|
||||
]);
|
||||
}
|
||||
const browser: Computer = {
|
||||
...computer,
|
||||
@@ -1105,9 +1138,7 @@ export function createAgentRuntime(dependencies: {
|
||||
browserId: childBrowser,
|
||||
};
|
||||
const childPath = `${workspace.path}/.nod/runs/${runId}`;
|
||||
if ((await workspace.exec(`mkdir -p -- '${childPath}'`, { signal })).exitCode)
|
||||
throw new Error('The subagent workspace could not be opened.');
|
||||
assertActive();
|
||||
const childWorkspace = withFolders(workspace, workspace.path, [childPath]);
|
||||
let browsed = false;
|
||||
let answer = '';
|
||||
let partialAnswer = '';
|
||||
@@ -1188,7 +1219,7 @@ export function createAgentRuntime(dependencies: {
|
||||
return result;
|
||||
},
|
||||
})),
|
||||
workspace: { ...workspace, path: childPath },
|
||||
workspace: { ...childWorkspace, path: childPath },
|
||||
timeZone: context.timeZone,
|
||||
runTool: async (name, params, run, options) => {
|
||||
if (capped) return spent();
|
||||
|
||||
@@ -30,7 +30,6 @@ export function createAccountSession(options: {
|
||||
traces?: boolean;
|
||||
onTraces?(enabled: boolean): void;
|
||||
updatesEmail?: boolean;
|
||||
prepare?(signal: AbortSignal): Promise<void>;
|
||||
}) {
|
||||
const user = options.localUser;
|
||||
const owner = user.id;
|
||||
@@ -149,17 +148,6 @@ export function createAccountSession(options: {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
async function prepare(reply: FastifyReply) {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
reply.raw.once('close', abort);
|
||||
try {
|
||||
if (reply.raw.destroyed) controller.abort();
|
||||
await options.prepare?.(controller.signal);
|
||||
} finally {
|
||||
reply.raw.off('close', abort);
|
||||
}
|
||||
}
|
||||
function setupFailed(reply: FastifyReply, error: unknown, what: string) {
|
||||
logFailure('setup_failed', error);
|
||||
const reason =
|
||||
@@ -168,7 +156,6 @@ export function createAccountSession(options: {
|
||||
}
|
||||
async function start(reply: FastifyReply, complete?: () => Promise<unknown>) {
|
||||
try {
|
||||
await prepare(reply);
|
||||
await options.start?.();
|
||||
await complete?.();
|
||||
return true;
|
||||
@@ -182,19 +169,6 @@ export function createAccountSession(options: {
|
||||
reply.header('cache-control', 'no-store');
|
||||
return response();
|
||||
});
|
||||
app.post('/api/account/prepare', async (request, reply) => {
|
||||
if (!guard(request, reply)) return;
|
||||
z.object({})
|
||||
.strict()
|
||||
.parse(request.body ?? {});
|
||||
reply.header('cache-control', 'no-store');
|
||||
try {
|
||||
await prepare(reply);
|
||||
} catch (error) {
|
||||
return setupFailed(reply, error, 'Setup could not be completed.');
|
||||
}
|
||||
return { ok: true };
|
||||
});
|
||||
app.post('/api/account/model-setup', async (request, reply) => {
|
||||
if (!guard(request, reply)) return;
|
||||
z.object({})
|
||||
|
||||
@@ -355,6 +355,7 @@ export function modelEnvironment(
|
||||
|
||||
export function createDefaultAdapters(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
computer?: { ready(signal?: AbortSignal): Promise<void>; available(): boolean },
|
||||
): ApplicationAdapters {
|
||||
const bootstrap = modelEnvironment(env);
|
||||
const { provider } = bootstrap;
|
||||
@@ -536,7 +537,11 @@ export function createDefaultAdapters(
|
||||
configRoot: join(dataRoot, 'pi'),
|
||||
traces,
|
||||
}),
|
||||
computer: createContainerBrowserComputer({ dataRoot, container: env.BROWSER_CONTAINER }),
|
||||
computer: createContainerBrowserComputer({
|
||||
dataRoot,
|
||||
container: env.BROWSER_CONTAINER,
|
||||
ready: computer?.ready,
|
||||
}),
|
||||
passwordManager: createOnePassword({
|
||||
open: desktopMode ? desktopOnePassword() : forkedOnePassword(env.NOD_APP_VERSION || 'source'),
|
||||
}),
|
||||
@@ -546,6 +551,8 @@ export function createDefaultAdapters(
|
||||
workspace: createDockerWorkspace({
|
||||
container: env.WORKSPACE_CONTAINER || 'nod-workspace',
|
||||
workspaceRoot: join(dataRoot, 'workspaces'),
|
||||
ready: computer?.ready,
|
||||
available: computer?.available,
|
||||
}),
|
||||
localSpeech,
|
||||
speechInputFormat: (voice) => {
|
||||
@@ -744,7 +751,6 @@ export async function createApplication(
|
||||
channels?: boolean;
|
||||
heartbeat?: boolean;
|
||||
rateLimit?: boolean;
|
||||
runtimeReady?: Promise<void>;
|
||||
starting?: (step: string) => void;
|
||||
} = {},
|
||||
) {
|
||||
@@ -780,7 +786,6 @@ async function initializeApplication(
|
||||
channels?: boolean;
|
||||
heartbeat?: boolean;
|
||||
rateLimit?: boolean;
|
||||
runtimeReady?: Promise<void>;
|
||||
starting?: (step: string) => void;
|
||||
},
|
||||
diagnostics: {
|
||||
@@ -855,28 +860,6 @@ async function initializeApplication(
|
||||
const admission = createWorkAdmission();
|
||||
const consumers = createWorkConsumers();
|
||||
const closing = new AbortController();
|
||||
if (options.runtimeReady) await consumers.pause();
|
||||
const runtimeReady =
|
||||
options.runtimeReady?.then(() => {
|
||||
if (!closing.signal.aborted) return consumers.resume();
|
||||
}) ?? Promise.resolve();
|
||||
void runtimeReady.catch(() => {});
|
||||
async function prepareRuntime(signal: AbortSignal) {
|
||||
const lifetime = AbortSignal.any([signal, closing.signal]);
|
||||
lifetime.throwIfAborted();
|
||||
let aborted: () => void;
|
||||
try {
|
||||
await Promise.race([
|
||||
runtimeReady,
|
||||
new Promise<never>((_, reject) => {
|
||||
aborted = () => reject(lifetime.reason);
|
||||
lifetime.addEventListener('abort', aborted, { once: true });
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
lifetime.removeEventListener('abort', aborted!);
|
||||
}
|
||||
}
|
||||
const privacyNotice = await loadPrivacyNoticeFile(process.env.NOD_PRIVACY_NOTICE_FILE);
|
||||
await mkdir(dataRoot, { recursive: true, mode: 0o700 });
|
||||
options.starting?.('database');
|
||||
@@ -2602,6 +2585,7 @@ async function initializeApplication(
|
||||
consumers,
|
||||
artifacts,
|
||||
writeArtifact: workspace.writeArtifact.bind(workspace),
|
||||
workspaceAvailable: () => workspace.available?.() !== false,
|
||||
readArtifact: workspace.readArtifact.bind(workspace),
|
||||
cardImage: previews?.image ? (url, signal) => previews.image!(url, signal) : undefined,
|
||||
mapTile: previews?.mapTile
|
||||
@@ -3581,7 +3565,6 @@ async function initializeApplication(
|
||||
developerIds,
|
||||
turnTraceIds,
|
||||
start: welcome,
|
||||
prepare: prepareRuntime,
|
||||
onboardingMissing: async () => (adapters.model.configured ? null : 'brain'),
|
||||
traces: adapters.traces?.available ?? false,
|
||||
onTraces: (enabled) => adapters.traces?.configure({ enabled }),
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
type Waiter = { resolve(): void; reject(error: Error): void };
|
||||
|
||||
export type ComputerUpdate = { ready: true } | { error: { code?: string; message: string } };
|
||||
|
||||
export function createComputerReadiness() {
|
||||
let state: ComputerUpdate | undefined;
|
||||
const waiters = new Set<Waiter>();
|
||||
const failure = (error: { code?: string; message: string }) =>
|
||||
Object.assign(new Error(`Nod’s private computer is unavailable. ${error.message}`), {
|
||||
code: error.code,
|
||||
});
|
||||
return {
|
||||
available: () => Boolean(state && 'ready' in state),
|
||||
update(next: ComputerUpdate) {
|
||||
state = next;
|
||||
for (const waiter of [...waiters]) {
|
||||
waiters.delete(waiter);
|
||||
if ('error' in next) waiter.reject(failure(next.error));
|
||||
else waiter.resolve();
|
||||
}
|
||||
},
|
||||
ready(signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted) return Promise.reject(signal.reason);
|
||||
if (state && 'ready' in state) return Promise.resolve();
|
||||
if (state && 'error' in state) return Promise.reject(failure(state.error));
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const abort = () => {
|
||||
waiters.delete(waiter);
|
||||
reject(signal!.reason);
|
||||
};
|
||||
const waiter: Waiter = {
|
||||
resolve: () => {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
resolve();
|
||||
},
|
||||
reject: (error) => {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
reject(error);
|
||||
},
|
||||
};
|
||||
signal?.addEventListener('abort', abort, { once: true });
|
||||
waiters.add(waiter);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
+37
-15
@@ -2,6 +2,7 @@ import { pool } from './db.ts';
|
||||
import { authToken, dataRoot, desktopMode, host, port, publicOrigin, webRoot } from './config.ts';
|
||||
import { accessKey } from './access.ts';
|
||||
import { createApplication, createDefaultAdapters } from './composition.ts';
|
||||
import { createComputerReadiness } from './computer-readiness.ts';
|
||||
|
||||
let stopping = false;
|
||||
let closeApplication: (() => Promise<void>) | undefined;
|
||||
@@ -9,22 +10,44 @@ const parent = (
|
||||
process as NodeJS.Process & {
|
||||
parentPort?: {
|
||||
on(event: 'message', listener: (event: { data: unknown }) => void): void;
|
||||
removeListener(event: 'message', listener: (event: { data: unknown }) => void): void;
|
||||
};
|
||||
}
|
||||
).parentPort;
|
||||
const runtimeReady =
|
||||
desktopMode && process.env.NOD_DESKTOP_RUNTIME_PENDING === 'true'
|
||||
? new Promise<void>((resolve) => {
|
||||
if (!parent) throw new Error('Desktop startup requires Nod.');
|
||||
const ready = (event: { data: unknown }) => {
|
||||
if ((event.data as { type?: string })?.type !== 'nod-runtime-ready') return;
|
||||
parent.removeListener('message', ready);
|
||||
resolve();
|
||||
};
|
||||
parent.on('message', ready);
|
||||
})
|
||||
: undefined;
|
||||
const computerEnvironment = [
|
||||
'PATH',
|
||||
'DOCKER_HOST',
|
||||
'DOCKER_CONFIG',
|
||||
'DOCKER_CONTEXT',
|
||||
'NOD_WSL_DISTRIBUTION',
|
||||
'TEMP',
|
||||
'TMP',
|
||||
];
|
||||
const computer = desktopMode && parent ? createComputerReadiness() : undefined;
|
||||
if (computer && parent) {
|
||||
parent.on('message', (event) => {
|
||||
const message = event.data as {
|
||||
type?: string;
|
||||
environment?: Record<string, unknown>;
|
||||
error?: { code?: unknown; message?: unknown };
|
||||
} | null;
|
||||
if (message?.type !== 'nod-runtime') return;
|
||||
if (message.error)
|
||||
return computer.update({
|
||||
error: {
|
||||
code: typeof message.error.code === 'string' ? message.error.code : undefined,
|
||||
message:
|
||||
typeof message.error.message === 'string'
|
||||
? message.error.message
|
||||
: 'It could not start.',
|
||||
},
|
||||
});
|
||||
for (const key of computerEnvironment) {
|
||||
const value = message.environment?.[key];
|
||||
if (typeof value === 'string') process.env[key] = value;
|
||||
}
|
||||
computer.update({ ready: true });
|
||||
});
|
||||
}
|
||||
const starting = (step: string) => {
|
||||
if (desktopMode)
|
||||
(
|
||||
@@ -32,8 +55,7 @@ const starting = (step: string) => {
|
||||
).parentPort?.postMessage({ type: 'nod-starting', step });
|
||||
};
|
||||
starting('loaded');
|
||||
const { app } = await createApplication(createDefaultAdapters(process.env), {
|
||||
runtimeReady,
|
||||
const { app } = await createApplication(createDefaultAdapters(process.env, computer), {
|
||||
starting,
|
||||
});
|
||||
closeApplication = () => app.close();
|
||||
|
||||
@@ -281,6 +281,7 @@ export interface ThreadDependencies {
|
||||
signal?: AbortSignal,
|
||||
) => Promise<void>;
|
||||
readArtifact?: (threadId: string, path: string, maxBytes: number) => Promise<Uint8Array>;
|
||||
workspaceAvailable?: () => boolean;
|
||||
cardImage?: (url: string, signal: AbortSignal) => Promise<PreviewImage | null>;
|
||||
mapTile?: (
|
||||
zoom: number,
|
||||
@@ -2549,15 +2550,18 @@ async function executeTurn(turn: any, dependencies: ThreadDependencies) {
|
||||
operation.throwIfAborted();
|
||||
const value = await inlineAppResult(
|
||||
result,
|
||||
async (text) =>
|
||||
workspaceReference(
|
||||
async (text) => {
|
||||
if (dependencies.workspaceAvailable?.() === false)
|
||||
throw new Error('Nod’s workspace is unavailable right now');
|
||||
return workspaceReference(
|
||||
await stage(
|
||||
randomUUID(),
|
||||
`${action.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80)}.json`,
|
||||
Buffer.from(text),
|
||||
operation,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
dependencies.mailCheck ?? noMailCheck,
|
||||
operation,
|
||||
nested,
|
||||
|
||||
@@ -85,11 +85,10 @@ export function createWorkConsumers() {
|
||||
instances: Set<Instance>;
|
||||
};
|
||||
const consumers = new Set<Consumer>();
|
||||
let paused = false;
|
||||
let closed = false;
|
||||
|
||||
function start(consumer: Consumer) {
|
||||
if (paused || closed) return Promise.resolve();
|
||||
if (closed) return Promise.resolve();
|
||||
if ([...consumer.instances].some((instance) => instance.failed))
|
||||
return Promise.reject(unavailable());
|
||||
const existing = [...consumer.instances].find((instance) => !instance.stopping);
|
||||
@@ -110,8 +109,7 @@ export function createWorkConsumers() {
|
||||
});
|
||||
return instance.stopping;
|
||||
}
|
||||
function pause() {
|
||||
paused = true;
|
||||
function stopAll() {
|
||||
return Promise.all(
|
||||
[...consumers].flatMap((consumer) =>
|
||||
[...consumer.instances].map((instance) => stop(consumer, instance)),
|
||||
@@ -125,15 +123,9 @@ export function createWorkConsumers() {
|
||||
consumers.add(consumer);
|
||||
await start(consumer);
|
||||
},
|
||||
pause,
|
||||
async resume() {
|
||||
if (closed) throw unavailable();
|
||||
paused = false;
|
||||
await Promise.all([...consumers].map(start));
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
return pause();
|
||||
return stopAll();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,8 +36,4 @@ export interface AccountUpdate {
|
||||
traces?: boolean;
|
||||
}
|
||||
|
||||
export interface AccountPreparationResponse {
|
||||
ok: true;
|
||||
}
|
||||
|
||||
export type AccountPreferences = Preferences;
|
||||
@@ -49,6 +49,11 @@ export type StartupStage =
|
||||
| 'ready'
|
||||
| 'unknown';
|
||||
export type StartupEvent =
|
||||
| 'database_ready'
|
||||
| 'database_failed'
|
||||
| 'database_restarted'
|
||||
| 'database_moved'
|
||||
| 'database_restart_failed'
|
||||
| 'runtime_prepare'
|
||||
| 'runtime_ready'
|
||||
| 'runtime_failed'
|
||||
|
||||
@@ -25,6 +25,11 @@ const stages = new Set([
|
||||
'ready',
|
||||
]);
|
||||
const events = new Set([
|
||||
'database_ready',
|
||||
'database_failed',
|
||||
'database_restarted',
|
||||
'database_moved',
|
||||
'database_restart_failed',
|
||||
'runtime_prepare',
|
||||
'runtime_ready',
|
||||
'runtime_failed',
|
||||
|
||||
+8
-1
@@ -18,6 +18,7 @@ import { SetupProgress } from './components/setup-progress';
|
||||
import { ServerAccess } from './components/server-access';
|
||||
import { Sidebar } from './components/sidebar';
|
||||
import { DesktopToolbar } from './components/desktop-toolbar';
|
||||
import { ComputerNotice } from './components/computer-notice';
|
||||
import { DesktopUpdateToast } from './components/desktop-update-toast';
|
||||
import { SidebarToggle } from './components/sidebar-toggle';
|
||||
import { FeedbackDialog } from './components/feedback';
|
||||
@@ -39,6 +40,7 @@ import { resolveBrowserRegion, setDateFormat } from './lib/date-format';
|
||||
import { useBrowserTimeZone } from './hooks/use-browser-time-zone';
|
||||
import { finishOnboarding } from './lib/onboarding';
|
||||
import {
|
||||
desktopRuntimeAvailable,
|
||||
desktopSettingsAvailable,
|
||||
desktopRendererReady,
|
||||
onFeedbackRequested,
|
||||
@@ -792,7 +794,12 @@ export function App({ sessionState }: { sessionState: ReturnType<typeof useSessi
|
||||
onFeedbackHandled={() => setFeedbackRequest(0)}
|
||||
/>
|
||||
)}
|
||||
{desktopSettingsAvailable() && !updating && <DesktopUpdateToast />}
|
||||
{desktopSettingsAvailable() && !updating && (
|
||||
<div className="desktop-toasts">
|
||||
{desktopRuntimeAvailable() && <ComputerNotice />}
|
||||
<DesktopUpdateToast />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button } from './ui';
|
||||
import {
|
||||
chooseDesktopComputerFolder,
|
||||
desktopStatus,
|
||||
importDesktopRuntime,
|
||||
installDesktopWsl,
|
||||
retryDesktopComputer,
|
||||
subscribeDesktopStatus,
|
||||
type DesktopStatus,
|
||||
} from '../lib/desktop';
|
||||
|
||||
export function ComputerNotice() {
|
||||
const [status, setStatus] = useState<DesktopStatus>();
|
||||
const [dismissed, setDismissed] = useState<string>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [failed, setFailed] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
let received = false;
|
||||
const unsubscribe = subscribeDesktopStatus((value) => {
|
||||
received = true;
|
||||
setStatus(value);
|
||||
});
|
||||
void desktopStatus()
|
||||
?.then((value) => {
|
||||
if (!received) setStatus(value);
|
||||
})
|
||||
.catch(() => {});
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
const runtime = status?.runtime;
|
||||
const message = runtime?.message ?? '';
|
||||
if (status?.phase !== 'ready' || runtime?.phase !== 'error' || dismissed === message) return null;
|
||||
|
||||
const [label, action] = runtime.needsWsl
|
||||
? ['Install WSL', installDesktopWsl]
|
||||
: runtime.needsStorage
|
||||
? ['Choose folder', chooseDesktopComputerFolder]
|
||||
: runtime.needsRuntimeArchive
|
||||
? ['Choose Runtime pack', importDesktopRuntime]
|
||||
: ['Try again', retryDesktopComputer];
|
||||
|
||||
const act = (action: () => Promise<unknown>) => {
|
||||
setBusy(true);
|
||||
setFailed(undefined);
|
||||
void action()
|
||||
.catch((error: Error) => setFailed(error.message))
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="desktop-update-toast" role="status" aria-label="Private computer">
|
||||
<div className="desktop-update-toast-content">
|
||||
<strong>Nod’s browser and workspace aren’t available</strong>
|
||||
<p role="alert">{message}</p>
|
||||
<p>Chat, your apps and schedules keep working.</p>
|
||||
{failed && <p role="alert">{failed}</p>}
|
||||
<div className="desktop-update-toast-actions">
|
||||
<Button type="button" size="sm" disabled={busy} onClick={() => act(action)}>
|
||||
{busy ? 'Please wait…' : label}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => setDismissed(message)}
|
||||
>
|
||||
Not now
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,28 @@
|
||||
.desktop-update-toast {
|
||||
.desktop-toasts {
|
||||
--toast-top: calc(var(--page-top) + var(--shell-heading-height) + 16px);
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
top: var(--toast-top);
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
justify-items: end;
|
||||
max-height: calc(100dvh - var(--toast-top) - 16px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
:root[data-desktop='true'] .desktop-toasts {
|
||||
--toast-top: calc(
|
||||
var(--desktop-titlebar-height) + var(--page-top) + var(--shell-heading-height) + 16px
|
||||
);
|
||||
}
|
||||
.desktop-toasts:empty {
|
||||
display: none;
|
||||
}
|
||||
.desktop-update-toast {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
width: min(360px, calc(100vw - 32px));
|
||||
max-height: calc(100dvh - 48px);
|
||||
overflow-y: auto;
|
||||
|
||||
padding: 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--card-radius);
|
||||
@@ -54,12 +69,8 @@
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
body:has(.feedback-toast) .desktop-update-toast {
|
||||
bottom: 92px;
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.desktop-update-toast {
|
||||
.desktop-toasts {
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
}
|
||||
}
|
||||
+30
-9
@@ -16,6 +16,9 @@ type LocalRuntime = {
|
||||
status(): Promise<DesktopStatus>;
|
||||
subscribeStatus(listener: (status: DesktopStatus) => void): () => void;
|
||||
prepare(options?: { retry: boolean }): Promise<DesktopStatus>;
|
||||
installWsl?(): Promise<DesktopStatus>;
|
||||
importRuntime?(): Promise<DesktopStatus>;
|
||||
chooseComputerDirectory?(): Promise<DesktopStatus>;
|
||||
setup(): Promise<LocalSetup>;
|
||||
completePreferences(): Promise<LocalSetup>;
|
||||
reconcileSetup(): Promise<void>;
|
||||
@@ -40,6 +43,9 @@ export type DesktopStatus = {
|
||||
error?: string;
|
||||
progress?: number;
|
||||
secondsLeft?: number;
|
||||
needsWsl?: boolean;
|
||||
needsStorage?: boolean;
|
||||
needsRuntimeArchive?: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -100,6 +106,9 @@ type DesktopWindow = Window & {
|
||||
downloadUpdate?(): Promise<void>;
|
||||
restartUpdate?(): Promise<void>;
|
||||
prepare?(options?: { retry: boolean }): Promise<DesktopStatus>;
|
||||
installWsl?(): Promise<DesktopStatus>;
|
||||
importRuntime?(): Promise<DesktopStatus>;
|
||||
chooseComputerDirectory?(): Promise<DesktopStatus>;
|
||||
savePreferences?(input: DesktopSettingsChange): Promise<DesktopSettings>;
|
||||
saveSettings(
|
||||
input:
|
||||
@@ -160,6 +169,9 @@ export function clientPlatform(): ClientPlatform {
|
||||
if (!bridge.prepare) throw new Error('Restart Nod to try setting up your workspace again.');
|
||||
return bridge.prepare(options);
|
||||
},
|
||||
installWsl: bridge.installWsl,
|
||||
importRuntime: bridge.importRuntime,
|
||||
chooseComputerDirectory: bridge.chooseComputerDirectory,
|
||||
setup: async () => ({
|
||||
preferenceStep: (await bridge.getSettings()).onboardingPreferenceStep ?? 'launchAtLogin',
|
||||
}),
|
||||
@@ -361,17 +373,26 @@ export function restartDesktopUpdate() {
|
||||
return restart();
|
||||
}
|
||||
|
||||
export async function retryDesktopRuntime() {
|
||||
const status = await localRuntime().prepare({ retry: true });
|
||||
const failure =
|
||||
status.error ||
|
||||
(status.phase === 'error' ? status.message : undefined) ||
|
||||
status.runtime?.error ||
|
||||
(status.runtime?.phase === 'error' ? status.runtime.message : undefined);
|
||||
if (failure || status.phase !== 'ready' || status.runtime?.phase !== 'ready')
|
||||
throw new Error(failure || 'Your workspace is not ready yet. Try again.');
|
||||
export function retryDesktopComputer() {
|
||||
return localRuntime().prepare({ retry: true });
|
||||
}
|
||||
|
||||
const runtimeActions = {
|
||||
installWsl: 'install WSL',
|
||||
importRuntime: 'choose a Runtime pack',
|
||||
chooseComputerDirectory: 'choose a folder for the private computer',
|
||||
};
|
||||
|
||||
function runtimeAction(name: keyof typeof runtimeActions) {
|
||||
const action = localRuntime()[name];
|
||||
if (!action) return Promise.reject(new Error(`Update Nod to ${runtimeActions[name]} from here.`));
|
||||
return action();
|
||||
}
|
||||
|
||||
export const installDesktopWsl = () => runtimeAction('installWsl');
|
||||
export const importDesktopRuntime = () => runtimeAction('importRuntime');
|
||||
export const chooseDesktopComputerFolder = () => runtimeAction('chooseComputerDirectory');
|
||||
|
||||
export function desktopFilesAvailable() {
|
||||
return (
|
||||
typeof (window as DesktopWindow & { nodDesktop?: { fileAction?: unknown } }).nodDesktop
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType } from 'react';
|
||||
import type { AccountPreparationResponse, AccountUser } from '../../../shared/account';
|
||||
import { startupMessage } from '../../../shared/desktop-startup';
|
||||
import type { AccountUser } from '../../../shared/account';
|
||||
import type { ModelsResponse } from '../../../shared/models';
|
||||
import {
|
||||
onboardingSteps,
|
||||
@@ -9,14 +8,7 @@ import {
|
||||
} from '../../../shared/onboarding';
|
||||
import { Button, Notice } from '../../components/ui';
|
||||
import { SetupProgress } from '../../components/setup-progress';
|
||||
import {
|
||||
desktopRuntimeAvailable,
|
||||
desktopRendererReady,
|
||||
desktopStatus,
|
||||
subscribeDesktopStatus,
|
||||
retryDesktopRuntime,
|
||||
type DesktopStatus,
|
||||
} from '../../lib/desktop';
|
||||
import { desktopRuntimeAvailable, desktopRendererReady } from '../../lib/desktop';
|
||||
import { DesktopPreferencesSetup } from './steps/desktop-preferences';
|
||||
import { useBrowserTimeZone } from '../../hooks/use-browser-time-zone';
|
||||
import { modelReady } from '../../hooks/use-models';
|
||||
@@ -123,17 +115,8 @@ export function Onboarding({
|
||||
const { arrived } = position;
|
||||
const step = position.step === 'privacy' && !privacy ? 'join' : position.step;
|
||||
const index = step === 'preferences' ? onboardingSteps.length : onboardingSteps.indexOf(step);
|
||||
const [preparation, setPreparation] = useState<'pending' | 'ready' | 'failed'>('pending');
|
||||
const [preparationError, setPreparationError] = useState<{
|
||||
message: string;
|
||||
details?: string;
|
||||
}>();
|
||||
const [finishing, setFinishing] = useState(0);
|
||||
const [waitingForServices, setWaitingForServices] = useState(false);
|
||||
const [completionFailed, setCompletionFailed] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [runtimeError, setRuntimeError] = useState('');
|
||||
const [runtimeStatus, setRuntimeStatus] = useState<DesktopStatus | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [missing, setMissing] = useState<'brain' | 'email' | null>(null);
|
||||
const [skipModelStep, setSkipModelStep] = useState<boolean | null>(null);
|
||||
@@ -142,10 +125,7 @@ export function Onboarding({
|
||||
);
|
||||
const [mining, setMining] = useState(false);
|
||||
const emailSkipped = useRef(false);
|
||||
const started = useRef(false);
|
||||
const preparationRequest = useRef<AbortController | null>(null);
|
||||
const active = useRef(false);
|
||||
const retrying = useRef(false);
|
||||
const initialModelsChecked = useRef(false);
|
||||
const main = useRef<HTMLElement>(null);
|
||||
const viewed = useRef<{
|
||||
@@ -238,19 +218,11 @@ export function Onboarding({
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
started.current = false;
|
||||
preparationRequest.current?.abort();
|
||||
};
|
||||
}, [user.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (step === 'welcome' || started.current) return;
|
||||
started.current = true;
|
||||
void prepare();
|
||||
}, [step, user.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!finishing || preparation !== 'ready') return;
|
||||
if (!finishing) return;
|
||||
const capture = analyticsForCurrentSession();
|
||||
onComplete()
|
||||
.then(() => {
|
||||
@@ -268,91 +240,12 @@ export function Onboarding({
|
||||
);
|
||||
}
|
||||
});
|
||||
}, [finishing, preparation]);
|
||||
}, [finishing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!desktop) return;
|
||||
let current = true;
|
||||
let received = false;
|
||||
function accept(status: DesktopStatus) {
|
||||
if (!current) return;
|
||||
const failure =
|
||||
status.error ||
|
||||
(status.phase === 'error' ? status.message : undefined) ||
|
||||
status.runtime?.error ||
|
||||
(status.runtime?.phase === 'error' ? status.runtime.message : undefined);
|
||||
setRuntimeError(failure || '');
|
||||
setRuntimeStatus(status);
|
||||
}
|
||||
const stop = subscribeDesktopStatus((status) => {
|
||||
received = true;
|
||||
accept(status);
|
||||
});
|
||||
void desktopStatus()
|
||||
?.then((status) => {
|
||||
if (!received) accept(status);
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
current = false;
|
||||
stop();
|
||||
};
|
||||
}, [desktop]);
|
||||
|
||||
async function prepare() {
|
||||
const capture = analyticsForCurrentSession();
|
||||
preparationRequest.current?.abort();
|
||||
const request = new AbortController();
|
||||
preparationRequest.current = request;
|
||||
setPreparation('pending');
|
||||
setPreparationError(undefined);
|
||||
try {
|
||||
const response = await api<AccountPreparationResponse>('/api/account/prepare', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
signal: request.signal,
|
||||
});
|
||||
if (response.ok !== true) throw new Error('Setup could not be completed.');
|
||||
if (!request.signal.aborted) setPreparation('ready');
|
||||
} catch (cause) {
|
||||
if (!request.signal.aborted) {
|
||||
setPreparation('failed');
|
||||
setPreparationError({
|
||||
message: cause instanceof ApiError ? cause.message : 'Nod could not finish setup.',
|
||||
details: cause instanceof ApiError ? `HTTP ${cause.status}` : errorMessage(cause),
|
||||
});
|
||||
capture('ui_error', { area: 'onboarding', action: 'prepare' });
|
||||
}
|
||||
} finally {
|
||||
if (preparationRequest.current === request) preparationRequest.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
if (retrying.current) return;
|
||||
retrying.current = true;
|
||||
setSaving(true);
|
||||
function retry() {
|
||||
setError('');
|
||||
try {
|
||||
if (runtimeError) await retryDesktopRuntime();
|
||||
if (active.current) {
|
||||
setRuntimeError('');
|
||||
if (completionFailed) {
|
||||
setCompletionFailed(false);
|
||||
setFinishing((attempt) => attempt + 1);
|
||||
if (preparation !== 'ready') void prepare();
|
||||
} else void prepare();
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current) {
|
||||
const message = errorMessage(cause);
|
||||
setError(message);
|
||||
if (runtimeError) setRuntimeError(message);
|
||||
}
|
||||
} finally {
|
||||
retrying.current = false;
|
||||
if (active.current) setSaving(false);
|
||||
}
|
||||
setCompletionFailed(false);
|
||||
setFinishing((attempt) => attempt + 1);
|
||||
}
|
||||
|
||||
function go(offset: 1 | -1) {
|
||||
@@ -383,40 +276,19 @@ export function Onboarding({
|
||||
if (step !== 'join' && step !== 'preferences') return void go(1);
|
||||
if (desktop && step === 'join') return setPosition({ step: 'preferences', arrived: 'forward' });
|
||||
if (finishing) return;
|
||||
setWaitingForServices(preparation !== 'ready' || Boolean(runtimeError));
|
||||
setError('');
|
||||
setCompletionFailed(false);
|
||||
if (preparation === 'failed') void prepare();
|
||||
setFinishing((attempt) => attempt + 1);
|
||||
retry();
|
||||
}
|
||||
|
||||
if (
|
||||
finishing &&
|
||||
(waitingForServices || preparation !== 'ready' || completionFailed || runtimeError)
|
||||
) {
|
||||
const failure = runtimeError || error || preparationError?.message || '';
|
||||
const runtime = runtimeStatus?.runtime;
|
||||
const activeRuntime = runtime && runtime.phase !== 'ready' ? runtime : runtimeStatus;
|
||||
const title =
|
||||
preparation === 'ready'
|
||||
? startupMessage('ready')
|
||||
: startupMessage(activeRuntime?.stage ?? 'workspace');
|
||||
if (finishing && !completionFailed) return <SetupProgress title="Getting ready…" />;
|
||||
|
||||
if (finishing) {
|
||||
return (
|
||||
<SetupProgress
|
||||
title={failure ? 'Setup needs another try.' : title}
|
||||
progress={preparation === 'pending' ? activeRuntime?.progress : undefined}
|
||||
secondsLeft={preparation === 'pending' ? activeRuntime?.secondsLeft : undefined}
|
||||
description={
|
||||
failure
|
||||
? 'Your progress is saved.'
|
||||
: mining
|
||||
? 'Meanwhile, I’m reading your recent email to find things I can take off your plate.'
|
||||
: 'Your workspace and browser are getting ready. This only happens once.'
|
||||
}
|
||||
error={failure || undefined}
|
||||
details={!runtimeError && !error ? preparationError?.details : undefined}
|
||||
title="Setup needs another try."
|
||||
description="Your progress is saved."
|
||||
error={error}
|
||||
>
|
||||
{failure && missing && (
|
||||
{missing ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
@@ -429,9 +301,8 @@ export function Onboarding({
|
||||
>
|
||||
{missing === 'brain' ? 'Connect an AI provider' : 'Connect Gmail'}
|
||||
</Button>
|
||||
)}
|
||||
{failure && !missing && (
|
||||
<Button variant="outline" disabled={saving} onClick={() => void retry()}>
|
||||
) : (
|
||||
<Button variant="outline" onClick={retry}>
|
||||
Try again
|
||||
</Button>
|
||||
)}
|
||||
@@ -439,28 +310,7 @@ export function Onboarding({
|
||||
);
|
||||
}
|
||||
|
||||
const recovery = desktop && (runtimeError || error || saving || preparation === 'failed') && (
|
||||
<div className="ob-runtime">
|
||||
<Notice>
|
||||
{runtimeError ||
|
||||
error ||
|
||||
preparationError?.message ||
|
||||
(saving ? 'Trying setup again…' : 'Setup needs another try.')}{' '}
|
||||
<Button variant="ghost" disabled={saving} onClick={() => void retry()}>
|
||||
Try again
|
||||
</Button>
|
||||
{!runtimeError && !error && preparationError?.details && (
|
||||
<details className="setup-progress-details" data-analytics-private>
|
||||
<summary>Details</summary>
|
||||
<pre>{preparationError.details}</pre>
|
||||
</details>
|
||||
)}
|
||||
</Notice>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (step === 'preferences')
|
||||
return <DesktopPreferencesSetup notice={recovery} onReady={next} steps={steps} />;
|
||||
if (step === 'preferences') return <DesktopPreferencesSetup onReady={next} steps={steps} />;
|
||||
|
||||
const Screen = screens[step];
|
||||
return (
|
||||
@@ -483,7 +333,6 @@ export function Onboarding({
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{recovery}
|
||||
</OnboardingFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { OnboardingStep } from '../../../../shared/onboarding';
|
||||
import { OnboardingFrame } from '../frame';
|
||||
import { Button, Notice } from '../../../components/ui';
|
||||
@@ -9,11 +9,9 @@ import { Messages } from '../motion';
|
||||
|
||||
export function DesktopPreferencesSetup({
|
||||
onReady,
|
||||
notice,
|
||||
steps,
|
||||
}: {
|
||||
onReady(): void;
|
||||
notice?: ReactNode;
|
||||
steps: readonly OnboardingStep[];
|
||||
}) {
|
||||
const [error, setError] = useState('');
|
||||
@@ -67,7 +65,6 @@ export function DesktopPreferencesSetup({
|
||||
</Notice>
|
||||
)}
|
||||
</section>
|
||||
{notice}
|
||||
</OnboardingFrame>
|
||||
);
|
||||
}
|
||||
@@ -2113,7 +2113,7 @@ describe('account routes', () => {
|
||||
const reason = 'The local computer could not start: Docker daemon is not running';
|
||||
const failure = new Error(`${reason} (Bearer synthetic-secret-token-0123456789)`);
|
||||
const preparing = await fixture(undefined, undefined, undefined, async () => null, undefined, {
|
||||
async prepare() {
|
||||
async start() {
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
@@ -2126,20 +2126,18 @@ describe('account routes', () => {
|
||||
f.app.inject({ method, url, headers: { origin }, payload });
|
||||
const responses = [
|
||||
await send(preparing, 'PATCH', '/api/account', { onboardingCompleted: true }),
|
||||
await send(preparing, 'POST', '/api/account/prepare', {}),
|
||||
await send(verifying, 'PATCH', '/api/account', { onboardingCompleted: true }),
|
||||
];
|
||||
assert.deepEqual(
|
||||
responses.map((response) => [response.statusCode, response.json().error]),
|
||||
[
|
||||
[503, `Setup could not be completed. ${reason} ([redacted])`],
|
||||
[503, `Setup could not be completed. ${reason} ([redacted])`],
|
||||
[503, `Could not verify setup. ${reason} ([redacted])`],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
logged.mock.calls.map((call) => JSON.parse(String(call.arguments[0])).event),
|
||||
['setup_failed', 'setup_failed', 'setup_failed'],
|
||||
['setup_failed', 'setup_failed'],
|
||||
);
|
||||
const written = JSON.stringify(logged.mock.calls.map((call) => call.arguments));
|
||||
assert.doesNotMatch(written, /synthetic-secret-token|Docker daemon/);
|
||||
@@ -2627,11 +2625,11 @@ describe('account routes', () => {
|
||||
for (const loopback of ['127.0.0.1:4399', '[::1]:4399']) {
|
||||
const response = await f.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/account/prepare',
|
||||
url: '/api/account/model-setup',
|
||||
headers: { ...access, host: loopback, origin: `http://${loopback}` },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.equal(response.statusCode, 409);
|
||||
}
|
||||
for (const input of [
|
||||
{ headers: { ...access, origin: 'https://foreign.example.test' }, payload: {}, status: 403 },
|
||||
@@ -2644,7 +2642,7 @@ describe('account routes', () => {
|
||||
]) {
|
||||
const response = await f.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/account/prepare',
|
||||
url: '/api/account/model-setup',
|
||||
headers: input.headers,
|
||||
payload: input.payload,
|
||||
});
|
||||
@@ -2677,11 +2675,11 @@ describe('account routes', () => {
|
||||
assert.equal(welcome.statusCode, 409);
|
||||
const prepared = await f.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/account/prepare',
|
||||
url: '/api/account/model-setup',
|
||||
headers: { ...headers, 'x-nod-account': 'local-owner' },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(prepared.statusCode, 200);
|
||||
assert.equal(prepared.statusCode, 409);
|
||||
assert.equal(f.calls.writes, 0);
|
||||
assert.equal(f.calls.started, 0);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { createServer } from 'node:net';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { test } from 'node:test';
|
||||
import pg from 'pg';
|
||||
|
||||
type HostDatabase = { url: string; pendingMove: boolean; close(): Promise<void> };
|
||||
const { moveDatabase, openDatabase } = (await import(
|
||||
'../desktop/runtime/database.mjs' as string
|
||||
)) as {
|
||||
moveDatabase(options: {
|
||||
source: string;
|
||||
target: string;
|
||||
schema(section: string): Promise<string>;
|
||||
signal?: AbortSignal;
|
||||
space?(bytes: number): Promise<void>;
|
||||
}): Promise<void>;
|
||||
openDatabase(options: { dataRoot: string; resourcesPath: string }): Promise<HostDatabase>;
|
||||
};
|
||||
const binaries = join(
|
||||
process.cwd(),
|
||||
'postgres',
|
||||
'bin',
|
||||
process.platform === 'win32' ? 'postgres.exe' : 'postgres',
|
||||
);
|
||||
|
||||
const pre = `\\restrict synthetic
|
||||
CREATE SCHEMA jobs;
|
||||
CREATE TABLE public.threads (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY,
|
||||
title text NOT NULL,
|
||||
meta jsonb,
|
||||
at timestamptz NOT NULL,
|
||||
raw bytea
|
||||
);
|
||||
CREATE TABLE jobs.queue (id serial, thread_id bigint NOT NULL, state text);
|
||||
\\unrestrict synthetic`;
|
||||
const post = `ALTER TABLE ONLY public.threads ADD CONSTRAINT threads_pkey PRIMARY KEY (id);
|
||||
ALTER TABLE ONLY jobs.queue ADD CONSTRAINT queue_pkey PRIMARY KEY (id);
|
||||
ALTER TABLE ONLY jobs.queue ADD CONSTRAINT queue_thread FOREIGN KEY (thread_id) REFERENCES public.threads(id);
|
||||
CREATE INDEX threads_at ON public.threads (at);`;
|
||||
|
||||
const snapshot = `SELECT
|
||||
(SELECT md5(string_agg(concat_ws('|', id, title, meta::text, to_char(at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US'), encode(raw, 'hex')), ',' ORDER BY id)) FROM public.threads) AS threads,
|
||||
(SELECT md5(string_agg(concat_ws('|', id, thread_id, state), ',' ORDER BY id)) FROM jobs.queue) AS queue,
|
||||
(SELECT count(*)::int FROM pg_indexes WHERE indexname = 'threads_at') AS indexes`;
|
||||
|
||||
test(
|
||||
'moving the database copies every row, sequence and constraint, or nothing',
|
||||
{ skip: !process.env.TEST_DATABASE_URL && !existsSync(binaries) },
|
||||
async (t) => {
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
t.after(async () => {
|
||||
for (const step of cleanup.reverse()) await step().catch(() => {});
|
||||
});
|
||||
let url = process.env.TEST_DATABASE_URL;
|
||||
if (!url) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'nod-move-server-'));
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const server = await openDatabase({ dataRoot: root, resourcesPath: process.cwd() });
|
||||
cleanup.push(() => server.close());
|
||||
url = server.url;
|
||||
}
|
||||
const databaseUrl = (name: string) => {
|
||||
const address = new URL(url);
|
||||
address.pathname = `/${name}`;
|
||||
return address.toString();
|
||||
};
|
||||
const suffix = randomUUID().replaceAll('-', '').slice(0, 12);
|
||||
const names = ['from', 'to', 'busy', 'broken'].map((name) => `move_${name}_${suffix}`);
|
||||
const [source, target, busy, broken] = names;
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
const clients: pg.Client[] = [];
|
||||
cleanup.push(async () => {
|
||||
await Promise.all(clients.map((client) => client.end()));
|
||||
for (const name of names) await admin.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);
|
||||
await admin.end();
|
||||
});
|
||||
await admin.connect();
|
||||
for (const name of names) await admin.query(`CREATE DATABASE ${name}`);
|
||||
const open = async (name: string) => {
|
||||
const client = new pg.Client({ connectionString: databaseUrl(name) });
|
||||
await client.connect();
|
||||
clients.push(client);
|
||||
return client;
|
||||
};
|
||||
const tables = async (client: pg.Client) =>
|
||||
(
|
||||
await client.query(
|
||||
"SELECT tablename FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')",
|
||||
)
|
||||
).rows;
|
||||
const original = await open(source);
|
||||
await original.query(pre.replace(/^\\(?:un)?restrict .+$/gm, ''));
|
||||
await original.query(post);
|
||||
for (let index = 0; index < 40; index++)
|
||||
await original.query(
|
||||
`INSERT INTO public.threads (title, meta, at, raw)
|
||||
VALUES ($1, $2, '2026-11-27T09:00:00Z'::timestamptz + make_interval(secs => $3), $4)`,
|
||||
[
|
||||
`Synthetic thread ${index}\nwith ünïcödé, a tab\tand a \\ backslash`,
|
||||
{ index, nested: { list: [index, null, 'x'] } },
|
||||
index * 1.234567,
|
||||
Buffer.from([0, index, 255, 0]),
|
||||
],
|
||||
);
|
||||
await original.query(
|
||||
'INSERT INTO jobs.queue (thread_id, state) SELECT id, $1 FROM public.threads WHERE id % 3 = 0',
|
||||
['queued'],
|
||||
);
|
||||
const expected = (await original.query(snapshot)).rows[0];
|
||||
const schema = async (section: string) => (section === 'pre-data' ? pre : post);
|
||||
|
||||
await moveDatabase({ source: databaseUrl(source), target: databaseUrl(target), schema });
|
||||
|
||||
const moved = await open(target);
|
||||
assert.deepEqual((await moved.query(snapshot)).rows[0], expected);
|
||||
assert.equal(
|
||||
(
|
||||
await moved.query(
|
||||
"INSERT INTO public.threads (title, at) VALUES ('next', now()) RETURNING id::int",
|
||||
)
|
||||
).rows[0].id,
|
||||
41,
|
||||
);
|
||||
assert.equal(
|
||||
(await moved.query('INSERT INTO jobs.queue (thread_id) VALUES (1) RETURNING id')).rows[0].id,
|
||||
14,
|
||||
);
|
||||
await assert.rejects(
|
||||
moved.query('INSERT INTO jobs.queue (thread_id) VALUES (999)'),
|
||||
/queue_thread/,
|
||||
);
|
||||
await assert.rejects(
|
||||
moved.query(
|
||||
"INSERT INTO public.threads (id, title, at) OVERRIDING SYSTEM VALUE VALUES (1, 'twin', now())",
|
||||
),
|
||||
/threads_pkey/,
|
||||
);
|
||||
await assert.rejects(moved.query('INSERT INTO public.threads (at) VALUES (now())'), /not-null/);
|
||||
|
||||
const current = (await moved.query(snapshot)).rows[0];
|
||||
await moveDatabase({
|
||||
source: databaseUrl(source),
|
||||
target: databaseUrl(target),
|
||||
schema,
|
||||
space: async () => {
|
||||
throw new Error('A committed move must not need disk space again.');
|
||||
},
|
||||
});
|
||||
assert.deepEqual((await moved.query(snapshot)).rows[0], current);
|
||||
|
||||
const occupied = await open(busy);
|
||||
await occupied.query('CREATE SCHEMA jobs');
|
||||
await assert.rejects(
|
||||
moveDatabase({ source: databaseUrl(source), target: databaseUrl(busy), schema }),
|
||||
/already exists/,
|
||||
);
|
||||
assert.deepEqual(await tables(occupied), []);
|
||||
|
||||
let needed = 0;
|
||||
await assert.rejects(
|
||||
moveDatabase({
|
||||
source: databaseUrl(source),
|
||||
target: databaseUrl(broken),
|
||||
schema,
|
||||
space: async (bytes) => {
|
||||
needed = bytes;
|
||||
throw Object.assign(new Error('Synthetic disk is full.'), {
|
||||
code: 'NOD_DATABASE_STORAGE_FULL',
|
||||
});
|
||||
},
|
||||
}),
|
||||
{ code: 'NOD_DATABASE_STORAGE_FULL' },
|
||||
);
|
||||
assert.ok(needed > 0);
|
||||
assert.deepEqual(await tables(await open(broken)), []);
|
||||
|
||||
await assert.rejects(
|
||||
moveDatabase({
|
||||
source: databaseUrl(source),
|
||||
target: databaseUrl(broken),
|
||||
schema: async (section) => (section === 'pre-data' ? pre : `${post}\nSELECT missing();`),
|
||||
}),
|
||||
/missing/,
|
||||
);
|
||||
assert.deepEqual(await tables(await open(broken)), []);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'the host database restarts after a crash, quits cleanly and keeps its data',
|
||||
{ skip: !existsSync(binaries) },
|
||||
async (t) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'nod-host-database-ü-'));
|
||||
const opened: HostDatabase[] = [];
|
||||
let pool: pg.Pool | undefined;
|
||||
t.after(async () => {
|
||||
await pool?.end().catch(() => {});
|
||||
for (const database of opened.reverse()) await database.close().catch(() => {});
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
const open = async () => {
|
||||
const database = await openDatabase({ dataRoot: root, resourcesPath: process.cwd() });
|
||||
opened.push(database);
|
||||
return database;
|
||||
};
|
||||
const postmaster = () =>
|
||||
Number(readFileSync(join(root, 'database', 'data', 'postmaster.pid'), 'utf8').split('\n')[0]);
|
||||
const database = await open();
|
||||
assert.equal(database.pendingMove, false);
|
||||
pool = new pg.Pool({ connectionString: database.url, max: 2 });
|
||||
pool.on('error', () => {});
|
||||
await pool.query('CREATE TABLE synthetic (value text)');
|
||||
await pool.query("INSERT INTO synthetic VALUES ('kept')");
|
||||
const crashed = postmaster();
|
||||
process.kill(crashed, 'SIGKILL');
|
||||
let value: string | undefined;
|
||||
for (let attempt = 0; attempt < 60 && !value; attempt++) {
|
||||
await delay(500);
|
||||
value = await pool.query('SELECT value FROM synthetic').then(
|
||||
(result) => result.rows[0].value,
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
assert.equal(value, 'kept');
|
||||
assert.notEqual(postmaster(), crashed);
|
||||
process.kill(postmaster(), 'SIGKILL');
|
||||
await database.close();
|
||||
const kept = async (handle: HostDatabase) => {
|
||||
const client = new pg.Client({ connectionString: handle.url });
|
||||
await client.connect();
|
||||
try {
|
||||
return (await client.query('SELECT value FROM synthetic')).rows[0].value;
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
};
|
||||
const reopened = await open();
|
||||
assert.equal(await kept(reopened), 'kept');
|
||||
await reopened.close();
|
||||
const closed = createServer();
|
||||
await new Promise<void>((resolve) => closed.listen(0, '127.0.0.1', resolve));
|
||||
const { port } = closed.address() as AddressInfo;
|
||||
await new Promise((resolve) => closed.close(resolve));
|
||||
writeFileSync(
|
||||
join(root, 'database', 'data', 'postmaster.pid'),
|
||||
`${process.pid}\n${join(root, 'database', 'data')}\n0\n${port}\n\n127.0.0.1\n0 0\nready \n`,
|
||||
);
|
||||
const reused = await open();
|
||||
assert.equal(await kept(reused), 'kept');
|
||||
},
|
||||
);
|
||||
@@ -101,10 +101,6 @@ test(
|
||||
}));
|
||||
return options.tools.find((tool) => tool.name === step.tool)!.execute(step.args);
|
||||
};
|
||||
let storageReady!: () => void;
|
||||
const runtimeReady = new Promise<void>((resolve) => {
|
||||
storageReady = resolve;
|
||||
});
|
||||
const model = { provider: 'fixture', name: 'fixture', configured: true };
|
||||
let onboardingInboxReads = 0;
|
||||
const application = await createApplication(
|
||||
@@ -187,7 +183,7 @@ test(
|
||||
keyStore: { id: 'fixture', configured: true, getKey: async () => Buffer.alloc(32, 7) },
|
||||
model,
|
||||
},
|
||||
{ channels: false, runtimeReady },
|
||||
{ channels: false },
|
||||
);
|
||||
const headers = {
|
||||
host: `localhost:${port}`,
|
||||
@@ -318,50 +314,29 @@ test(
|
||||
}
|
||||
assert.equal(handled.mock.callCount(), 0);
|
||||
});
|
||||
await t.test(
|
||||
'one backend serves setup while queued turns wait for the computer',
|
||||
async () => {
|
||||
const session = await application.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/session',
|
||||
headers,
|
||||
});
|
||||
assert.equal(session.statusCode, 200);
|
||||
const choice = await application.app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/account',
|
||||
headers,
|
||||
payload: { usageData: false },
|
||||
});
|
||||
assert.equal(choice.statusCode, 200);
|
||||
let prepared = false;
|
||||
const preparation = application.app
|
||||
.inject({
|
||||
method: 'POST',
|
||||
url: '/api/account/prepare',
|
||||
headers,
|
||||
payload: {},
|
||||
})
|
||||
.then((response) => {
|
||||
prepared = true;
|
||||
return response;
|
||||
});
|
||||
const turn = await send({ text: 'Synthetic runtime startup probe.' });
|
||||
await delay(100);
|
||||
assert.equal(prepared, false);
|
||||
assert.equal((await turnStatus(turn)).status, 'queued');
|
||||
assert.equal(contexts.length, 0);
|
||||
storageReady();
|
||||
assert.equal((await preparation).statusCode, 200);
|
||||
await settle(turn, 'succeeded');
|
||||
assert.ok(contexts.length > 0);
|
||||
assert.equal(
|
||||
(await application.app.inject({ method: 'GET', url: '/api/session', headers })).json()
|
||||
.user.id,
|
||||
session.json().user.id,
|
||||
);
|
||||
},
|
||||
);
|
||||
await t.test('one backend serves setup and runs turns', async () => {
|
||||
const session = await application.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/session',
|
||||
headers,
|
||||
});
|
||||
assert.equal(session.statusCode, 200);
|
||||
const choice = await application.app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/account',
|
||||
headers,
|
||||
payload: { usageData: false },
|
||||
});
|
||||
assert.equal(choice.statusCode, 200);
|
||||
const turn = await send({ text: 'Synthetic runtime startup probe.' });
|
||||
await settle(turn, 'succeeded');
|
||||
assert.ok(contexts.length > 0);
|
||||
assert.equal(
|
||||
(await application.app.inject({ method: 'GET', url: '/api/session', headers })).json()
|
||||
.user.id,
|
||||
session.json().user.id,
|
||||
);
|
||||
});
|
||||
const assertSilent = async (
|
||||
turnId: string,
|
||||
finalText = 'Synthetic memory request handled.',
|
||||
|
||||
+27
-7
@@ -867,6 +867,28 @@ test('small Pi sessions save full output and keep nested results available to sc
|
||||
await session.dispose();
|
||||
});
|
||||
|
||||
test('an oversized result keeps an inline preview while the workspace is unavailable', async () => {
|
||||
const { createContextOutput } = await import('../src/providers/pi/context-output.ts');
|
||||
let commands = 0;
|
||||
const output = createContextOutput({
|
||||
path: '/workspace/fixture',
|
||||
instructions: '',
|
||||
available: () => false,
|
||||
exec: async () => {
|
||||
commands++;
|
||||
return { exitCode: 0 };
|
||||
},
|
||||
});
|
||||
const full = `${'synthetic result line\n'.repeat(5000)}synthetic last line`;
|
||||
const saved = JSON.parse(await output.save([{ type: 'text', text: full }], 1000));
|
||||
assert.equal(commands, 0);
|
||||
assert.equal(saved.workspaceFile, undefined);
|
||||
assert.equal(saved.characters, full.length);
|
||||
assert.ok(saved.preview.startsWith('synthetic result line'));
|
||||
assert.ok(saved.tail.endsWith('synthetic last line'));
|
||||
assert.match(saved.message, /unavailable/);
|
||||
});
|
||||
|
||||
test('direct image results save over-budget images in the workspace', async (t) => {
|
||||
const { workspace, prefix, root } = await hostSandbox(t);
|
||||
const directory = await mkdtemp(join(tmpdir(), 'nod-image-output-'));
|
||||
@@ -3447,7 +3469,7 @@ test('task handoff shows only the start message unless a steered request needs a
|
||||
test('a paused turn cannot start a subagent still preparing and failed children return errors', async (t) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'nod-delegate-stop-'));
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
let opened = 0;
|
||||
let started = 0;
|
||||
let preparing = 0;
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
@@ -3457,13 +3479,14 @@ test('a paused turn cannot start a subagent still preparing and failed children
|
||||
agent: {
|
||||
open: async (input) => {
|
||||
const child = Boolean(input.ephemeral);
|
||||
if (child) opened++;
|
||||
if (child && ++preparing === 3) await gate;
|
||||
return {
|
||||
resumed: false,
|
||||
abort: () => release(),
|
||||
dispose() {},
|
||||
prompt: async () => {
|
||||
if (child) {
|
||||
started++;
|
||||
await gate;
|
||||
input.onEvent({ type: 'error', message: '402 Insufficient credits' });
|
||||
input.onEvent({ type: 'message_end', status: 'failed' });
|
||||
@@ -3479,7 +3502,7 @@ test('a paused turn cannot start a subagent still preparing and failed children
|
||||
.find((tool) => tool.name === 'ask_user')!
|
||||
.execute({ question: 'Which source should I use?' });
|
||||
const outcomes = await Promise.allSettled(pending);
|
||||
assert.equal(opened, 2);
|
||||
assert.equal(started, 2);
|
||||
assert.ok(outcomes.every((outcome) => outcome.status === 'rejected'));
|
||||
assert.ok(
|
||||
outcomes
|
||||
@@ -3502,10 +3525,7 @@ test('a paused turn cannot start a subagent still preparing and failed children
|
||||
open: () => ({
|
||||
path: '/fixture/workspace',
|
||||
instructions: 'Fixture workspace only.',
|
||||
exec: async () => {
|
||||
if (++preparing === 3) await gate;
|
||||
return { exitCode: 0 };
|
||||
},
|
||||
exec: async () => ({ exitCode: 0 }),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
+35
-1
@@ -541,7 +541,10 @@ test('connected CLIs run only their sealed install with a clean environment', as
|
||||
}
|
||||
});
|
||||
|
||||
function fakeDocker(check: (args: string[]) => Promise<{ code: number; stderr?: string }>) {
|
||||
function fakeDocker(
|
||||
check: (args: string[]) => Promise<{ code: number; stderr?: string }>,
|
||||
ready?: (signal?: AbortSignal) => Promise<void>,
|
||||
) {
|
||||
const launches: Array<{
|
||||
workdir: string;
|
||||
request: Promise<{ args: string[] }>;
|
||||
@@ -599,6 +602,7 @@ function fakeDocker(check: (args: string[]) => Promise<{ code: number; stderr?:
|
||||
container: 'nod-workspace-fixture',
|
||||
workspaceRoot: '/synthetic',
|
||||
spawn: launch,
|
||||
ready,
|
||||
});
|
||||
const session = workspace.open({
|
||||
threadId: 'fixture',
|
||||
@@ -608,6 +612,36 @@ function fakeDocker(check: (args: string[]) => Promise<{ code: number; stderr?:
|
||||
return { launches, workspace, session, exit };
|
||||
}
|
||||
|
||||
test('workspace commands wait for the private computer and fail with its reason', async () => {
|
||||
const { createComputerReadiness } = await import('../src/server/computer-readiness.ts');
|
||||
const starting = createComputerReadiness();
|
||||
const failed = createComputerReadiness();
|
||||
const waiting = fakeDocker(async () => ({ code: 0 }), starting.ready);
|
||||
const refused = fakeDocker(async () => ({ code: 0 }), failed.ready);
|
||||
try {
|
||||
const command = execute(waiting.session, 'ok');
|
||||
const stopping = new AbortController();
|
||||
const stopped = waiting.session.exec('ok', { signal: stopping.signal });
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(waiting.launches.length, 0);
|
||||
stopping.abort(new Error('Stopped by the owner.'));
|
||||
await assert.rejects(stopped, /Stopped by the owner/);
|
||||
starting.update({ ready: true });
|
||||
assert.equal(await command, '');
|
||||
assert.equal(waiting.launches.length, 1);
|
||||
failed.update({ error: { code: 'NOD_WSL_REQUIRED', message: 'WSL 2 is not installed.' } });
|
||||
await assert.rejects(
|
||||
execute(refused.session, 'ok'),
|
||||
(error: Error & { code?: string }) =>
|
||||
error.code === 'NOD_WSL_REQUIRED' && error.message.includes('WSL 2 is not installed.'),
|
||||
);
|
||||
assert.equal(refused.launches.length, 0);
|
||||
} finally {
|
||||
await waiting.workspace.dispose();
|
||||
await refused.workspace.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('an uncertain command is stopped once and the workspace keeps working', async () => {
|
||||
const docker = fakeDocker(async () => ({ code: 0 }));
|
||||
const first = execute(docker.session, 'first');
|
||||
|
||||
@@ -278,9 +278,7 @@ test(
|
||||
});
|
||||
await thread.initializeThreads();
|
||||
await t.test('periodic checks use an installation-spread five-minute schedule', async () => {
|
||||
const { createWorkConsumers } = await import('../src/server/work-admission.ts');
|
||||
const consumers = createWorkConsumers();
|
||||
await consumers.pause();
|
||||
const consumers = { register: async () => {}, close: async () => {} };
|
||||
await thread.boss.createQueue('heartbeat', { retryLimit: 0 });
|
||||
await thread.boss.schedule('heartbeat', '*/5 * * * *', {}, { tz: 'UTC' });
|
||||
try {
|
||||
|
||||
+22
-38
@@ -4563,8 +4563,7 @@ let saves=0;
|
||||
let reads=0;
|
||||
let rendererReady=0;
|
||||
let delayApps=false;
|
||||
let completePreparation;
|
||||
let preparationCompleted=false;
|
||||
let completionFailure;
|
||||
let completions=0;
|
||||
let statusListener;
|
||||
let modelConnected=true;
|
||||
@@ -4581,7 +4580,6 @@ window.nodDesktop={
|
||||
const calls=[];
|
||||
window.fetch=globalThis.fetch=async(url,options={})=>{
|
||||
const path=new URL(url,window.location.href).pathname;calls.push(path);
|
||||
if(path==='/api/account/prepare')return new Promise((resolve,reject)=>{completePreparation=(response=Response.json({ok:true}))=>response instanceof Error?reject(response):resolve(response)});
|
||||
if(path==='/api/models'){modelReads++;return Response.json({connections:modelConnected?[{id:'synthetic',provider:'anthropic',method:'api_key',label:'Synthetic model',managed:false,status:'connected',models:[{id:'synthetic-model',name:'Synthetic model',efforts:['medium'],images:false,contextWindow:1000}]}]:[],selection:modelConnected?{connectionId:'synthetic',modelId:'synthetic-model',effort:'medium'}:null,...(modelFailure?{selectionIssue:{reason:modelFailure}}:{})})}
|
||||
if(path==='/api/preferences')return Response.json({timeZone:'Europe/Lisbon',locale:'en-GB',hourCycle:'h23',quietHoursEnabled:false,quietStart:'22:00',quietEnd:'08:00',speechReply:'auto',speechVoice:null});
|
||||
if(path==='/api/speech')return Response.json({transcription:false,synthesis:false,voices:[],speechVoice:null,speechReply:'auto'});
|
||||
@@ -4610,7 +4608,7 @@ globalThis.EventSource=class{
|
||||
close(){this.closed=true;this.readyState=2}
|
||||
};
|
||||
let root=createRoot(document.getElementById('root'));
|
||||
const render=()=>act(async()=>root.render(createElement(Onboarding,{user:session.user,onComplete:async()=>{completions++;assert.equal(preparationCompleted,true,'No completion before server preparation finishes')}})));
|
||||
const render=()=>act(async()=>root.render(createElement(Onboarding,{user:session.user,onComplete:async()=>{completions++;if(completionFailure){const failure=completionFailure;completionFailure=undefined;throw failure}}})));
|
||||
const realTimeout=setTimeout;
|
||||
mock.timers.enable({apis:['setTimeout']});
|
||||
const settle=()=>act(async()=>{await new Promise(resolve=>realTimeout(resolve,20));mock.timers.tick(20)});
|
||||
@@ -4631,16 +4629,20 @@ assert.equal(saves,1);
|
||||
assert.notEqual((await store.get()).onboardingPreferenceStep,'complete');
|
||||
failSave=false;
|
||||
await act(async()=>button('Try again').click());
|
||||
await waitFor(()=>document.querySelector('main [role="status"]'));
|
||||
await waitFor(async()=>(await store.get()).onboardingPreferenceStep==='complete');
|
||||
assert.equal((await store.get()).launchAtLogin,true);
|
||||
assert.equal((await store.get()).notifications,false,'onboarding does not request notification permission');
|
||||
assert.equal((await store.get()).onboardingPreferenceStep,'complete');
|
||||
assert.equal(saves,2);
|
||||
await waitFor(()=>completions===1);
|
||||
await act(async()=>root.unmount());
|
||||
store=createSettingsStore(join(directory,'settings.json'),{});
|
||||
const completedReads=reads;
|
||||
window.history.replaceState(null,'','/onboarding?preferences=required');
|
||||
root=createRoot(document.getElementById('root'));
|
||||
await render();
|
||||
await waitFor(()=>document.querySelector('main [role="status"]'));
|
||||
await waitFor(()=>reads>completedReads);
|
||||
await waitFor(()=>completions===2);
|
||||
assert.equal(document.querySelector('[role="switch"]'),null);
|
||||
assert.equal(saves,2,'a completed native step is never written again');
|
||||
await act(async()=>root.unmount());
|
||||
@@ -4673,17 +4675,22 @@ const blockedPath=join(directory,'blocked-settings.json');
|
||||
store=createSettingsStore(blockedPath,{});
|
||||
failLogin=true;
|
||||
const beforeBlocked=saves;
|
||||
window.history.replaceState(null,'','/onboarding?preferences=required');
|
||||
root=createRoot(document.getElementById('root'));
|
||||
await render();
|
||||
await waitFor(async()=>(await store.get()).onboardingPreferenceStep==='complete');
|
||||
await waitFor(()=>completions===3);
|
||||
assert.equal(saves,beforeBlocked+1);
|
||||
assert.equal((await store.get()).launchAtLogin,false);
|
||||
assert.equal((await store.get()).onboardingPreferenceStep,'complete');
|
||||
await act(async()=>root.unmount());
|
||||
store=createSettingsStore(blockedPath,{});
|
||||
const blockedReads=reads;
|
||||
window.history.replaceState(null,'','/onboarding?preferences=required');
|
||||
root=createRoot(document.getElementById('root'));
|
||||
await render();
|
||||
await waitFor(()=>document.querySelector('main [role="status"]'));
|
||||
await waitFor(()=>reads>blockedReads);
|
||||
await waitFor(()=>completions===4);
|
||||
assert.equal(saves,beforeBlocked+1);
|
||||
assert.equal(Object.hasOwn(await store.get(),'onboardingCompleted'),false);
|
||||
assert.equal((await store.get()).onboardingPreferenceStep,'complete');
|
||||
@@ -4721,41 +4728,18 @@ await act(async()=>button('Continue').click());
|
||||
await waitFor(()=>document.querySelector('[data-step="join"]'));
|
||||
assert.ok(calls.includes('/api/onboarding/profile'));
|
||||
assert.equal(document.querySelector('.ob-dots').getAttribute('aria-label'),'Step 4 of 4');
|
||||
completionFailure=new Error('Synthetic account save failed.');
|
||||
const beforeFinish=completions;
|
||||
await act(async()=>button('Continue').click());
|
||||
await waitFor(()=>document.querySelector('.setup-progress [role="status"]'));
|
||||
await waitFor(()=>document.querySelector('.setup-progress [role="alert"]'));
|
||||
assert.ok(document.querySelector('.setup-progress [role="alert"]').textContent.includes('Synthetic account save failed.'));
|
||||
assert.equal((await store.get()).onboardingPreferenceStep,'complete');
|
||||
assert.equal(completions,0);
|
||||
await act(async()=>statusListener({phase:'ready',runtime:{phase:'ready'}}));
|
||||
await settle();
|
||||
assert.equal(completions,0,'Desktop readiness must not complete onboarding before server preparation');
|
||||
assert.ok(document.querySelector('.setup-progress [role="status"]'));
|
||||
const preparationFailure='Synthetic workspace could not mount its volume.';
|
||||
await act(async()=>completePreparation(Response.json({error:preparationFailure},{status:503})));
|
||||
await waitFor(()=>document.querySelector('.setup-progress [role="alert"]'));
|
||||
assert.ok(document.querySelector('.setup-progress [role="alert"]').textContent.includes(preparationFailure));
|
||||
assert.ok(document.querySelector('.setup-progress details').textContent.includes('503'));
|
||||
assert.equal(document.querySelector('.setup-progress details').open,false);
|
||||
assert.equal(completions,0);
|
||||
await act(async()=>statusListener({phase:'ready',runtime:{phase:'ready'}}));
|
||||
assert.ok(document.querySelector('.setup-progress [role="alert"]').textContent.includes(preparationFailure));
|
||||
const preparationCalls=calls.filter(path=>path==='/api/account/prepare').length;
|
||||
assert.equal(completions,beforeFinish+1);
|
||||
await act(async()=>button('Try again').click());
|
||||
await waitFor(()=>calls.filter(path=>path==='/api/account/prepare').length===preparationCalls+1);
|
||||
assert.equal(document.querySelector('.setup-progress [role="alert"]'),null);
|
||||
assert.equal(completions,0);
|
||||
const transportFailure='Synthetic fetch TypeError during workspace setup.';
|
||||
await act(async()=>completePreparation(new TypeError(transportFailure)));
|
||||
await waitFor(()=>document.querySelector('.setup-progress [role="alert"]'));
|
||||
assert.equal(document.querySelector('.setup-progress [role="alert"]').textContent.includes(transportFailure),false);
|
||||
assert.ok(document.querySelector('.setup-progress details').textContent.includes(transportFailure));
|
||||
assert.equal(completions,0);
|
||||
await act(async()=>button('Try again').click());
|
||||
await waitFor(()=>calls.filter(path=>path==='/api/account/prepare').length===preparationCalls+2);
|
||||
assert.equal(document.querySelector('.setup-progress [role="alert"]'),null);
|
||||
await act(async()=>{preparationCompleted=true;completePreparation()});
|
||||
await waitFor(()=>completions===1);
|
||||
await waitFor(()=>completions===beforeFinish+2);
|
||||
await settle();
|
||||
assert.equal(completions,1);
|
||||
assert.equal(completions,beforeFinish+2);
|
||||
assert.equal(calls.includes('/api/account/prepare'),false);
|
||||
await act(async()=>root.unmount());
|
||||
modelConnected=false;
|
||||
writeStep({owner:session.user.id,step:'brain',version:onboardingVersion});
|
||||
|
||||
Reference in new issue
Block a user