Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

test(node-services): poll waits faster and build the daemon once per file

shoudi zhengb5f5375039f5
diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts
index 95e32055..ee71b085 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts
@@ -45,6 +45,8 @@ export interface AttachRunnerGatewayWebSocketOptions {
readonly path?: string;
readonly rejectUnmatchedUpgrades?: boolean;
readonly helloTimeoutMs?: number;
+ /** How long a protocol close waits for the peer before terminating. */
+ readonly closeTimeoutMs?: number;
readonly onSessionError?: (
error: unknown,
context: RunnerSessionErrorContext,
@@ -63,7 +65,7 @@ export interface RunnerGatewayWebSocketHandle {
const DEFAULT_PATH = "/v1/runner-gateway";
const DEFAULT_HELLO_TIMEOUT_MS = 10_000;
-const CLOSE_TIMEOUT_MS = 1_000;
+const DEFAULT_CLOSE_TIMEOUT_MS = 1_000;
const MAX_QUEUED_FRAMES = 1_024;
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
const MAX_TIMER_DELAY_MS = 2_147_000_000;
@@ -85,6 +87,10 @@ export const attachRunnerGatewayWebSocket = (
if (!Number.isSafeInteger(helloTimeoutMs) || helloTimeoutMs < 1) {
throw new TypeError("Runner Gateway hello timeout must be positive");
}
+ const closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
+ if (!Number.isSafeInteger(closeTimeoutMs) || closeTimeoutMs < 1) {
+ throw new TypeError("Runner Gateway close timeout must be positive");
+ }
const credentials = new CredentialCatalog(options.credentialAuthenticators);
const webSocketServer = new WebSocketServer({
noServer: true,
@@ -143,6 +149,7 @@ export const attachRunnerGatewayWebSocket = (
credentialStatus: async () =>
credentialIsActive(credential) ? "active" : "revoked",
helloTimeoutMs,
+ closeTimeoutMs,
onClose: () => sessions.delete(session),
onError: options.onSessionError,
});
@@ -249,6 +256,7 @@ export class RunnerSocketSession {
readonly #credential: RunnerGatewayCredential;
readonly #credentialStatus: () => Promise<CredentialStatus>;
readonly #helloTimeoutMs: number;
+ readonly #closeTimeoutMs: number;
readonly #onClose: () => void;
readonly #onError?: AttachRunnerGatewayWebSocketOptions["onSessionError"];
readonly #frames: Array<
@@ -290,6 +298,7 @@ export class RunnerSocketSession {
readonly credential: RunnerGatewayCredential;
readonly credentialStatus: () => Promise<CredentialStatus>;
readonly helloTimeoutMs: number;
+ readonly closeTimeoutMs: number;
readonly onClose: () => void;
readonly onError?: AttachRunnerGatewayWebSocketOptions["onSessionError"];
}) {
@@ -298,6 +307,7 @@ export class RunnerSocketSession {
this.#credential = options.credential;
this.#credentialStatus = options.credentialStatus;
this.#helloTimeoutMs = options.helloTimeoutMs;
+ this.#closeTimeoutMs = options.closeTimeoutMs;
this.#onClose = options.onClose;
this.#onError = options.onError;
}
@@ -693,7 +703,7 @@ export class RunnerSocketSession {
this.#webSocket.close(code, reason);
this.#closeTimer ??= setTimeout(
() => this.#webSocket.terminate(),
- CLOSE_TIMEOUT_MS,
+ this.#closeTimeoutMs,
);
this.#closeTimer.unref();
}
diff --git a/apps/node-services/src/document/main.ts b/apps/node-services/src/document/main.ts
index 287f86f4..dab3a385 100644
--- a/apps/node-services/src/document/main.ts
+++ b/apps/node-services/src/document/main.ts
@@ -19,12 +19,16 @@ const maxRestartDelayMs = 60_000;
export async function startDocumentService(options: {
logger: JsonLogger;
createThread?: () => Worker;
+ /** Delay before the first rebuild; doubles per failure up to the maximum. */
+ firstRestartDelayMs?: number;
}): Promise<{ stop(): Promise<void> }> {
const createThread = options.createThread ?? createDocumentThread;
let current: Worker | undefined;
let launching: Promise<void> | undefined;
let restartTimer: ReturnType<typeof setTimeout> | undefined;
- let restartDelayMs = firstRestartDelayMs;
+ const initialRestartDelayMs =
+ options.firstRestartDelayMs ?? firstRestartDelayMs;
+ let restartDelayMs = initialRestartDelayMs;
let stopping = false;
const restartLater = (error: unknown): void => {
@@ -59,7 +63,7 @@ export async function startDocumentService(options: {
if (current !== thread) return;
current = undefined;
if (Date.now() - startedAt >= maxRestartDelayMs) {
- restartDelayMs = firstRestartDelayMs;
+ restartDelayMs = initialRestartDelayMs;
}
void thread.terminate().then(() => restartLater(error));
};
diff --git a/apps/node-services/tests/agent/agent-features/inbox-source/teamhub-agent-wake-stream.test.ts b/apps/node-services/tests/agent/agent-features/inbox-source/teamhub-agent-wake-stream.test.ts
index 4e2557d9..b873cb97 100644
--- a/apps/node-services/tests/agent/agent-features/inbox-source/teamhub-agent-wake-stream.test.ts
+++ b/apps/node-services/tests/agent/agent-features/inbox-source/teamhub-agent-wake-stream.test.ts
@@ -190,14 +190,19 @@ describe("TeamHub Agent wake stream", () => {
onReconcile: vi.fn(),
onConnectionChanged,
});
+ // The reconnect backoff runs on the fake clock: 1 s, then 2 s.
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
handle.start();
- await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(3), {
- timeout: 10_000,
- });
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
+ await vi.advanceTimersByTimeAsync(1_000);
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ await vi.advanceTimersByTimeAsync(2_000);
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(3));
expect(onConnectionChanged.mock.calls).toEqual([[true], [false]]);
} finally {
await handle.close();
+ vi.useRealTimers();
}
});
diff --git a/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts b/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts
index 952969f3..27c7160c 100644
--- a/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts
@@ -8,6 +8,8 @@ import { execFile, spawn, type ChildProcess } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import {
chmod,
+ copyFile,
+ cp,
mkdir,
mkdtemp,
readdir,
@@ -22,7 +24,7 @@ import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
-import { afterEach, expect, it, vi } from "vitest";
+import { afterAll, afterEach, expect, it, vi } from "vitest";
import {
createTeamHubAgentCliCredentialIssuer,
@@ -73,6 +75,57 @@ afterEach(async () => {
await Promise.all(cleanups.splice(0).map((cleanup) => cleanup()));
});
+// Each test needs the Daemon binary and the TeamHub CLI at its own path, since
+// the Daemon finds the CLI beside its binary. Build both once per file run from
+// the current sources and copy them per test; nothing is reused across runs.
+let builds: Promise<{ daemon: string; cli: string }> | undefined;
+
+afterAll(async () => {
+ const built = await builds?.catch(() => undefined);
+ if (built)
+ await rm(path.dirname(built.daemon), { recursive: true, force: true });
+});
+
+const buildOnce = (): Promise<{ daemon: string; cli: string }> =>
+ (builds ??= (async () => {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), "linger-go-daemon-build-"),
+ );
+ const daemon = path.join(root, "linger-computer-daemon");
+ const cli = path.join(root, "cli");
+ await Promise.all([
+ execFileAsync(
+ "go",
+ ["build", "-o", daemon, "./cmd/linger-computer-daemon"],
+ {
+ cwd: path.resolve(process.cwd(), "../computer/local-daemon"),
+ timeout: 60_000,
+ },
+ ),
+ execFileAsync(
+ process.execPath,
+ [
+ path.resolve(process.cwd(), "../teamhub-cli/scripts/build-cli.mjs"),
+ "--outdir",
+ cli,
+ ],
+ { timeout: 15_000 },
+ ),
+ ]);
+ return { daemon, cli };
+ })());
+
+const installDaemonBinary = async (binary: string): Promise<void> => {
+ const { daemon } = await buildOnce();
+ await mkdir(path.dirname(binary), { recursive: true });
+ await copyFile(daemon, binary);
+};
+
+const installTeamHubCli = async (directory: string): Promise<void> => {
+ const { cli } = await buildOnce();
+ await cp(cli, directory, { recursive: true });
+};
+
const processTest =
process.env.LINGER_GO_LOCAL_DAEMON_TEST === "1" ? it : it.skip;
@@ -379,24 +432,8 @@ processTest(
mkdir(state),
mkdir(workspace),
]);
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- {
- cwd: path.resolve(process.cwd(), "../computer/local-daemon"),
- signal,
- timeout: 60_000,
- },
- );
- await execFileAsync(
- process.execPath,
- [
- path.resolve(process.cwd(), "../teamhub-cli/scripts/build-cli.mjs"),
- "--outdir",
- path.join(root, "cli"),
- ],
- { signal, timeout: 15_000 },
- );
+ await installDaemonBinary(binary);
+ await installTeamHubCli(path.join(root, "cli"));
await symlink(
process.execPath,
path.join(root, "runtime", "bin", "node"),
@@ -690,18 +727,8 @@ processTest(
"connects the real Go Local Computer Daemon through Registration reconciliation",
async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "linger-go-daemon-"));
- const localDaemonRoot = path.resolve(
- process.cwd(),
- "../computer/local-daemon",
- );
const binary = path.join(root, "linger-computer-daemon");
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- {
- cwd: localDaemonRoot,
- },
- );
+ await installDaemonBinary(binary);
const computerId = "computer-go-canary";
const tenantId = "tenant-acme";
const ownerActorId = "actor-alice";
@@ -1643,23 +1670,11 @@ processTest(
let child: ChildProcess | undefined;
let shell: ContextExecutor<LocalRuntimeSettings> | undefined;
try {
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- { cwd: path.resolve(process.cwd(), "../computer/local-daemon") },
- );
+ await installDaemonBinary(binary);
await mkdir(state, { mode: 0o700 });
await mkdir(workspace, { mode: 0o700 });
await mkdir(path.join(root, "runtime", "bin"), { recursive: true });
- await execFileAsync(
- process.execPath,
- [
- path.resolve(process.cwd(), "../teamhub-cli/scripts/build-cli.mjs"),
- "--outdir",
- path.join(root, "cli"),
- ],
- { timeout: 15_000 },
- );
+ await installTeamHubCli(path.join(root, "cli"));
await symlink(
process.execPath,
path.join(root, "runtime", "bin", "node"),
@@ -1985,11 +2000,7 @@ processTest(
await writeFile(path.join(root, "cli", "teamhub"), "#!/bin/sh\nexit 0\n", {
mode: 0o700,
});
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- { cwd: path.resolve(process.cwd(), "../computer/local-daemon") },
- );
+ await installDaemonBinary(binary);
const computerId = "computer-presence";
const tenantId = "tenant-acme";
const ownerActorId = "actor-alice";
@@ -2549,11 +2560,7 @@ const openProcessHarness = async (mode: CodexMode) => {
},
/** Starts the Daemon, waits until this Gateway sees the Computer online. */
async boot(): Promise<void> {
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- { cwd: path.resolve(process.cwd(), "../computer/local-daemon") },
- );
+ await installDaemonBinary(binary);
await mkdir(state);
await mkdir(workspace);
await writeFile(credential, token, { mode: 0o600 });
@@ -2881,13 +2888,7 @@ processTest(
});
let child: ChildProcess | undefined;
try {
- await execFileAsync(
- "go",
- ["build", "-o", binary, "./cmd/linger-computer-daemon"],
- {
- cwd: path.resolve(process.cwd(), "../computer/local-daemon"),
- },
- );
+ await installDaemonBinary(binary);
await Promise.all([mkdir(state), mkdir(workspace)]);
await writeFile(credential, token, { mode: 0o600 });
await writeFile(hangMarker, "wait");
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts
index f0d88181..5682aa00 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts
@@ -439,8 +439,11 @@ describe("Runner Gateway WebSocket", () => {
it("drops frames that arrive after a heartbeat timeout while the close is pending", async () => {
const onSessionError = vi.fn();
+ // The close stays pending from the 200 ms timeout until 600 ms, so the
+ // heartbeat sent at 300 ms lands while the gateway is CLOSING.
const fixture = await startFixture({
heartbeatTimeoutMs: 200,
+ closeTimeoutMs: 400,
onSessionError,
});
const socket = new WebSocket(fixture.url, {
@@ -468,7 +471,7 @@ describe("Runner Gateway WebSocket", () => {
it("drops frames from a replaced connection while its close is pending", async () => {
const onSessionError = vi.fn();
- const fixture = await startFixture({ onSessionError });
+ const fixture = await startFixture({ closeTimeoutMs: 300, onSessionError });
const connect = async (): Promise<WebSocket> => {
const socket = new WebSocket(fixture.url, {
headers: { Authorization: "Bearer runner-secret" },
@@ -1568,6 +1571,7 @@ const startFixture = async (
credentialAuthenticators?: readonly RunnerCredentialAuthenticator[];
rejectUnmatchedUpgrades?: boolean;
helloTimeoutMs?: number;
+ closeTimeoutMs?: number;
heartbeatTimeoutMs?: number;
computerDaemonIdentityVerifier?: ComputerDaemonIdentityVerifier;
onSessionError?: AttachRunnerGatewayWebSocketOptions["onSessionError"];
@@ -1607,6 +1611,7 @@ const startFixture = async (
],
rejectUnmatchedUpgrades: options.rejectUnmatchedUpgrades,
helloTimeoutMs: options.helloTimeoutMs,
+ closeTimeoutMs: options.closeTimeoutMs,
onSessionError: options.onSessionError,
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
diff --git a/apps/node-services/tests/document/main.test.ts b/apps/node-services/tests/document/main.test.ts
index d2d08696..568515fa 100644
--- a/apps/node-services/tests/document/main.test.ts
+++ b/apps/node-services/tests/document/main.test.ts
@@ -89,7 +89,8 @@ describe("Document role", () => {
);
});
- // Two real worker startups and teardown surround the bounded 10s wait.
+ // Two real worker startups and teardown surround the bounded 10s wait. A
+ // short first restart delay keeps the wait on the rebuild, not the backoff.
it("starts without the thread while its port is busy and serves once the port frees", async () => {
const blocker = createServer();
const port = await occupyPort(blocker);
@@ -99,12 +100,15 @@ describe("Document role", () => {
});
const { logger, log } = testLogger();
- const role = await startDocumentService({ logger });
+ const role = await startDocumentService({
+ logger,
+ firstRestartDelayMs: 50,
+ });
try {
expect(log).toHaveBeenCalledWith(
"error",
"document.thread_failed",
- expect.objectContaining({ restart_in_ms: 1_000 }),
+ expect.objectContaining({ restart_in_ms: 50 }),
);
await new Promise<void>((resolve) => blocker.close(() => resolve()));
await vi.waitFor(
@@ -112,7 +116,7 @@ describe("Document role", () => {
const response = await fetch(`http://127.0.0.1:${port}/healthz`);
expect(response.status).toBe(200);
},
- { timeout: 10_000, interval: 100 },
+ { timeout: 10_000, interval: 20 },
);
} finally {
blocker.close();
diff --git a/apps/node-services/tests/document/realtime-mutation-queue.api.test.ts b/apps/node-services/tests/document/realtime-mutation-queue.api.test.ts
index 8d5642b8..3ae6375e 100644
--- a/apps/node-services/tests/document/realtime-mutation-queue.api.test.ts
+++ b/apps/node-services/tests/document/realtime-mutation-queue.api.test.ts
@@ -18,10 +18,11 @@ interface CloseEvent {
// The deadline tests wait for a held validation to time out; a short deadline
// proves the same close without waiting for the production default. The
-// queue-full head's deadline starts before the test's 2 s window to queue 129
-// frames, so it keeps a margin over that window.
+// queue-full head's deadline starts before the test's window to queue 129
+// frames (which takes about 10 ms), so it keeps a margin over that window.
const authorizationDeadlineMs = 1_000;
-const queueFullAuthorizationDeadlineMs = 3_500;
+const queueFullWindowMs = 1_000;
+const queueFullAuthorizationDeadlineMs = 1_500;
describe("Document Runtime mutation queue", () => {
it("keeps one rapidly editing client connected across a transient autosave lock", async () => {
@@ -251,7 +252,7 @@ describe("Document Runtime mutation queue", () => {
const rejected = await Promise.race([
queueFull,
- rejectAfter(2_000, "queue-full close"),
+ rejectAfter(queueFullWindowMs, "queue-full close"),
]);
expect(rejected.event).toEqual({
code: 1000,
diff --git a/apps/node-services/tests/wait-for-interval.ts b/apps/node-services/tests/wait-for-interval.ts
new file mode 100644
index 00000000..0e42b881
--- /dev/null
+++ b/apps/node-services/tests/wait-for-interval.ts
@@ -0,0 +1,28 @@
+import { vi } from "vitest";
+
+// Vitest polls waitFor every 50 ms by default, so a condition that becomes
+// true just after the first check costs a whole interval. Tests here wait on
+// in-process events that settle within microtasks, so poll more often. The
+// timeout stays the caller's; under fake timers each poll still advances the
+// clock by the interval, keeping the total advanced time per real timeout.
+const WAIT_FOR_INTERVAL_MS = 5;
+
+type WaitForOptions = Parameters<typeof vi.waitFor>[1];
+
+const waitFor = vi.waitFor.bind(vi);
+vi.waitFor = ((
+ callback: Parameters<typeof vi.waitFor>[0],
+ options?: WaitForOptions,
+) => waitFor(callback, withInterval(options))) as typeof vi.waitFor;
+const waitUntil = vi.waitUntil.bind(vi);
+vi.waitUntil = ((
+ callback: Parameters<typeof vi.waitUntil>[0],
+ options?: Parameters<typeof vi.waitUntil>[1],
+) => waitUntil(callback, withInterval(options))) as typeof vi.waitUntil;
+
+function withInterval(options: WaitForOptions): WaitForOptions {
+ if (typeof options === "number") {
+ return { timeout: options, interval: WAIT_FOR_INTERVAL_MS };
+ }
+ return { interval: WAIT_FOR_INTERVAL_MS, ...options };
+}
diff --git a/apps/node-services/vitest.config.ts b/apps/node-services/vitest.config.ts
index 4272a4db..86d95b7c 100644
--- a/apps/node-services/vitest.config.ts
+++ b/apps/node-services/vitest.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
// Real conversion workers run alongside the existing process tests.
maxWorkers: 2,
testTimeout: 5_000,
+ setupFiles: ["tests/wait-for-interval.ts"],
environment: "node",
// Memory's days follow the process time zone; pin one so dates in tests
// hold on every machine. A test that needs another zone stubs TZ.