Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

14.4 KB
Raw Blame
import { readMainModule, readMainSource } from "./helpers/source-contracts.mjs";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";

const sidecarSource = await readFile(
  new URL("../../../packages/host-runtime/src/agent-sidecar.ts", import.meta.url),
  "utf8",
);
const runtimeSidecarSource = await readFile(
  new URL("../electron/main/runtime/sidecar.ts", import.meta.url),
  "utf8",
);
const hostSource = await readFile(
  new URL("../../../packages/host-runtime/src/host-process.ts", import.meta.url),
  "utf8",
);
const mainSource = await readMainSource();
const plansSource = await readMainModule("runtime/plans.ts");
const shutdownModuleSource = await readMainModule("bootstrap/shutdown.ts");
const mainIndexSource = await readMainModule("index.ts");
const runtimeSource = await readFile(
  new URL("../../../packages/agent-runtime/src/runtime.ts", import.meta.url),
  "utf8",
);
const rpcTimeoutSource = await readFile(
  new URL("../../../packages/shared/src/rpc-timeouts.ts", import.meta.url),
  "utf8",
);
const agentSidecarEntrySource = await readFile(
  new URL("../../../packages/agent-runtime/src/sidecar.ts", import.meta.url),
  "utf8",
);
const e2eHostSource = await readFile(
  new URL("../../../scripts/e2e/host.mjs", import.meta.url),
  "utf8",
);
const e2eSmokeSource = await readFile(
  new URL("../../../scripts/e2e-smoke.mjs", import.meta.url),
  "utf8",
);
const codexImporterSource = await readFile(
  new URL("../electron/main/importers/codex.ts", import.meta.url),
  "utf8",
);
const apiSource = await readFile(
  new URL("../src/lib/api.ts", import.meta.url),
  "utf8",
);

test("stdio RPC readers split frames on LF only", () => {
  for (const [name, source] of [
    ["host-process", hostSource],
    ["agent-sidecar", sidecarSource],
    ["runtime sidecar", agentSidecarEntrySource],
    ["e2e host harness", e2eHostSource],
    ["e2e smoke host", e2eSmokeSource],
    ["codex importer", codexImporterSource],
  ]) {
    assert.match(source, /readNdjsonLines/, `${name} must use LF NDJSON framing`);
    assert.doesNotMatch(
      source,
      /from ["']node:readline["']/,
      `${name} must not use readline`,
    );
    assert.doesNotMatch(
      source,
      /createInterface/,
      `${name} must not call createInterface`,
    );
  }
});

test("sidecar detaches host listeners and gates every child write", () => {
  assert.match(sidecarSource, /private closeTransport\(error: Error\)/);
  assert.match(sidecarSource, /unsubscribeHostExit/);
  assert.match(sidecarSource, /private writeToChild\(payload: string\)/);
  assert.match(sidecarSource, /private localToolTimers = new Set/);
  assert.match(sidecarSource, /this\.localToolTimers\.clear\(\)/);
  assert.match(sidecarSource, /this\.child\.stdin\.destroyed/);
  assert.doesNotMatch(
    sidecarSource.replace(/private writeToChild\([\s\S]*?\n  \}/, ""),
    /this\.child\.stdin\.write\(/,
  );
});

test("tool diagnostics emit one bounded outcome instead of start/end spam", () => {
  assert.match(runtimeSidecarSource, /summarizeToolResult/);
  assert.match(runtimeSidecarSource, /tool execution completed/);
  assert.match(runtimeSidecarSource, /tool execution failed/);
  assert.match(runtimeSidecarSource, /tool execution interrupted/);
  assert.doesNotMatch(runtimeSidecarSource, /logger\.app\([\s\S]*?"tool start"/);
  assert.doesNotMatch(runtimeSidecarSource, /logger\.app\([\s\S]*?"tool end"/);
});

test("host transport closes pending calls and listeners on process death", () => {
  assert.match(hostSource, /private closed = false/);
  assert.match(hostSource, /this\.handlers\.clear\(\)/);
  // Tagged, not a bare Error: a caller has to be able to tell routine teardown
  // from a registry that genuinely failed without matching message text.
  assert.match(
    hostSource,
    /if \(this\.closed\) throw this\.unavailableError\("host-core is unavailable"\)/,
  );
  assert.match(hostSource, /errorCode: ErrorCodes\.HOST_UNAVAILABLE,/);
  assert.match(hostSource, /private notifyExit\(/);
});

test("host transport rejects oversized request lines before writing", () => {
  assert.match(hostSource, /MAX_HOST_STDIN_LINE_BYTES/);
  assert.match(hostSource, /errorCode: ErrorCodes.LIMIT_EXCEEDED/);
  assert.match(hostSource, /request line exceeds 64 MiB/);
  assert.ok(
    hostSource.indexOf("Buffer.byteLength(payload") <
      hostSource.indexOf("this.child.stdin.write(payload"),
    "oversize must be rejected before stdin.write",
  );
});

test("host transport retries transient RPC overload with a bounded backoff", () => {
  assert.match(hostSource, /HOST_OVERLOAD_RETRY_DELAYS_MS = \[50, 100, 200, 400\]/);
  assert.match(hostSource, /typeof msg\.error\.data\.errorCode === "string"/);
  assert.match(hostSource, /function isHostOverloaded\(/);
  assert.match(hostSource, /private async callOnce<.*>\(/);
  assert.match(hostSource, /!isHostOverloaded\(error\)/);
});

test("host disposal closes stdin, observes exit, and force-kills only after grace", () => {
  const disposeSource = hostSource.slice(hostSource.indexOf("async dispose()"));
  const closeTransportSource = hostSource.slice(
    hostSource.indexOf("private closeTransport"),
    hostSource.indexOf("private cleanupProcessListeners"),
  );

  assert.match(hostSource, /private disposePromise\?: Promise<void>/);
  assert.match(hostSource, /private waitForExit\(timeoutMs: number\)/);
  const graceMatch = hostSource.match(/const HOST_DISPOSE_GRACE_MS = ([\d_]+);/);
  assert.ok(graceMatch, "host disposal must define a graceful wait");
  const graceMs = Number(graceMatch[1].replace(/_/g, ""));
  assert.ok(
    graceMs >= 2_500 && graceMs <= 3_000,
    "host disposal must allow the documented process-tree cleanup time",
  );
  assert.match(hostSource, /this\.child\.kill\("SIGKILL"\)/);
  assert.match(disposeSource, /if \(this\.disposePromise\) return this\.disposePromise/);
  assert.ok(
    disposeSource.indexOf("this.child.stdin.end()") <
      disposeSource.indexOf("this.closeTransport("),
    "stdin must close before pending RPCs are rejected",
  );
  assert.doesNotMatch(
    closeTransportSource,
    /removeAllListeners\("exit"\)|removeAllListeners\("error"\)/,
  );
});

test("Bash execution remains bounded while permission transport has no deadline", () => {
  assert.match(runtimeSource, /DEFAULT_COMMAND_TIMEOUT_MS/);
  assert.match(runtimeSource, /defaults to a 60-second timeout/);
  // Bash may carry additive options after its timeout. Runtime tests exercise
  // the default and override values at the tools.execute boundary.
  assert.match(runtimeSource, /\btimeoutMs,/);
  assert.doesNotMatch(rpcTimeoutSource, /DEFAULT_BASH_RPC_TIMEOUT_MS/);
  // A tool relay carries its own budget; the transport must not cut it with the
  // flat default. The same holds for the remote workspace counterpart.
  assert.match(
    rpcTimeoutSource,
    /if \(method === "tools\.execute" \|\| method === "tools\.workspaceExecute"\) return undefined/,
  );
});

test("turn ownership and execution queue wake only after durable turn settlement", () => {
  const finishStart = plansSource.indexOf("function finishTurn(");
  const finishEnd = plansSource.indexOf("async function finishApprovedExecution(", finishStart);
  const finishSource = plansSource.slice(finishStart, finishEnd);

  // The claim is addressed by the turn, not by the session alone: a late
  // terminal event for an older turn must not join or release a newer turn's
  // record, and the busy check can still find a session's records by prefix.
  assert.match(plansSource, /const finalizationKey = planSubmissionTurnKey\(id, turnId\)/);
  assert.match(plansSource, /turnFinalizations\.get\(finalizationKey\)/);
  assert.match(plansSource, /turnFinalizations\.set\(finalizationKey, finalization\)/);
  assert.match(finishSource, /await runtimeState\.host\.call<[\s\S]*?\("session\.endTurn"/);
  assert.ok(
    finishSource.indexOf('"session.endTurn"') <
      finishSource.lastIndexOf("activeTurns.delete"),
    "local session ownership must remain until session.endTurn settles",
  );
  assert.match(finishSource, /for \(const resolve of waiters\) resolve\(\)/);
});

test("late tool metadata cleanup is scoped to the turn that started the call", () => {
  const finishStart = mainSource.indexOf("function finishTurn(");
  const finishEnd = mainSource.indexOf("function isRecord", finishStart);
  const finishSource = mainSource.slice(finishStart, finishEnd);

  assert.match(mainSource, /turnId\?: string;/);
  assert.match(mainSource, /turnId: envelope\.turnId \?\? turnId/);
  assert.match(
    finishSource,
    /key\.startsWith\(toolPrefix\) && call\.turnId === turnId/,
  );
  assert.match(
    mainSource,
    /turnId: started\?\.turnId \?\? envelope\.turnId \?\? turnId/,
  );
  assert.match(
    mainSource,
    /event: \{ type: "message_end", message: persistedMessage \}/,
  );
});

test("app quit waits for one idempotent teardown before allowing the follow-up quit", () => {
  const shutdownSource = shutdownModuleSource.slice(
    shutdownModuleSource.indexOf('app.on("before-quit"'),
  );

  assert.match(shutdownModuleSource, /shutdownComplete: boolean/);
  assert.match(shutdownModuleSource, /shutdownPromise: Promise<void> \| null/);
  assert.match(shutdownSource, /if \(state\.shutdownComplete\) return/);
  assert.match(shutdownSource, /event\.preventDefault\(\)/);
  assert.match(shutdownSource, /if \(state\.shutdownPromise \|\| quitConfirmationPending\) return/);
  assert.ok(
    shutdownSource.indexOf('logger.app("lifecycle", "info", "app shutdown")') <
      shutdownSource.indexOf("await liveCallService?.endForLifecycle"),
    "the confirmed shutdown boundary must be logged before awaited cleanup",
  );
  assert.ok(
    shutdownSource.indexOf("event.preventDefault()") <
      shutdownSource.indexOf("if (state.shutdownPromise || quitConfirmationPending) return"),
    "the first quit must be prevented before the idempotence guard returns",
  );
  // Panel windows and docked views are the only pages that call the host and the
  // plugin runtime over the panel bridge. Their pages are gone before either
  // stops: a call a page already sent while its surface was closing is otherwise
  // answered by a runtime that is already shutting down, and is reported as a
  // bridge failure nobody can act on.
  assert.ok(
    shutdownSource.indexOf("await pluginSurfacesShutdown") <
      shutdownSource.indexOf("getHost()?.dispose()"),
    "panel and view pages must be gone before the host stops",
  );
  assert.ok(
    shutdownSource.indexOf("await pluginSurfacesShutdown") <
      shutdownSource.indexOf("plugins.disposeAll()"),
    "no panel page may still call a plugin runtime that is stopping",
  );
  assert.match(shutdownSource, /await hostShutdown/);
  assert.match(
    shutdownSource,
    /await Promise\.allSettled\(\[\s*pluginShutdown,\s*sidecarShutdown,\s*mcpShutdown,\s*remoteHostsShutdown,\s*\]\)/,
  );
  const releaseQuit = shutdownSource.match(
    /const releaseQuit = \(\) => \{[\s\S]*?shutdownComplete = true;[\s\S]*?app\.quit\(\);[\s\S]*?\};/,
  );
  assert.ok(
    releaseQuit,
    "the follow-up quit must run only after shutdownComplete is set",
  );
  assert.match(shutdownSource, /void state\.shutdownPromise\.then\(releaseQuit, releaseQuit\)/);
});

test("settings writes validate without applying read defaults", async () => {
  const settingsIpc = await readMainModule("ipc/settings-ipc.ts");
  assert.match(settingsIpc, /const validatedSettings = validateSettingsWrite\(settings\)/);
  // The write contract concerns the payload, not the host acknowledgement type.
  assert.match(settingsIpc, /host\.call(?:<[^>\n]+>)?\("settings\.set", validatedSettings\)/);
  assert.doesNotMatch(settingsIpc, /\("settings\.set", normalizedSettings\)/);
  assert.match(apiSource, /export function validateSettingsWrite/);
  assert.match(apiSource, /invoke\(IPC\.invoke\.settingsSet, validateSettingsWrite\(settings\)\)/);
  assert.match(mainSource, /hasOwnProperty\.call\(value, "defaultCommandShell"\)/);
  assert.match(mainSource, /COMMAND_SHELL_INVALID/);
  assert.match(apiSource, /hasOwnProperty\.call\(value, "defaultCommandShell"\)/);
  assert.match(apiSource, /normalizeLargePasteThreshold/);
  assert.match(apiSource, /hasOwnProperty\.call\(value, "largePasteThreshold"\)/);
  assert.match(apiSource, /resolveFontScale/);
  assert.match(apiSource, /hasOwnProperty\.call\(value, "fontScale"\)/);
  assert.doesNotMatch(mainSource, /planApprovalPermissionMode/);
  assert.doesNotMatch(apiSource, /planApprovalPermissionMode/);
});

test("renderer notification drops silently when the render frame is disposed", () => {
  const sendStart = mainIndexSource.indexOf("function sendToRenderer(");
  const sendEnd = mainIndexSource.indexOf(
    "function resetMenuRendererReady",
    sendStart,
  );
  const sendSource = mainIndexSource.slice(sendStart, sendEnd);
  assert.ok(sendSource.includes("window.webContents.send(channel, payload)"));
  assert.ok(sendSource.includes("try {"));
  assert.ok(sendSource.includes("} catch {"));
  // A disposed frame during teardown is routine; logging it as an error would
  // spam the same line on every sidecar crash while the window is closed.
  assert.ok(
    !sendSource.includes("console.error") && !sendSource.includes("console.warn"),
    "disposed-frame sends are dropped silently",
  );
});

test("sidecar crash reports carry the last stderr lines", () => {
  assert.match(sidecarSource, /SIDECAR_STDERR_TAIL_LINES/);
  assert.match(sidecarSource, /private stderrTail/);
  assert.ok(
    sidecarSource.includes("h({ ...info, stderrTail })"),
    "exit handlers receive the stderr tail",
  );
  assert.ok(
    sidecarSource.includes("this.stderrTail.slice()"),
    "stderr tail is snapshotted at exit",
  );
  assert.match(mainSource, /agent sidecar exited unexpectedly/);
  assert.ok(
    mainSource.includes("stderrTail,"),
    "crash log carries the tail",
  );
  // The crash kind is classified once from the tail and reaches both the
  // settlement code and the log line, so an OOM death never reads as an
  assert.match(runtimeSidecarSource, /classifySidecarCrash\(stderrTail\)/);
  assert.match(runtimeSidecarSource, /sidecarCrashErrorCode\(crash\.kind\)/);
  assert.match(runtimeSidecarSource, /crashKind: crash\.kind/);
  assert.ok(
    runtimeSidecarSource.includes(
      "settleCrashedSession(sessionId, crashedTurnId, crashErrorCode)",
    ),
    "the owning turn settles with the classified code",
  );
  assert.doesNotMatch(runtimeSidecarSource, /finishTurn\([^)]*"PLAN_APPROVAL_INTERRUPTED"/);
  assert.match(
    runtimeSidecarSource,
    /finishTurn\(sessionId, "aborted", errorCode, \{/,
  );
});