fix(browser-relay): kept source startup working without the generated extension

- Builds swap the generated extension in for a committed null placeholder (`embedded-extension.ts`) via Bun.build `files`; source checkouts read `extension.generated.json` lazily through `loadRelayExtension()`.
- A checkout that never ran `bun run gen:relay-extension` now starts; only `omp browser-relay install`/`sync` fail, naming the command, and startup sync logs it.
- The generator writes one JSON instead of per-file `.txt` assets; binary and npm builds generate it themselves, so the explicit build-script steps are gone.
This commit is contained in:
can1357 committed 2026-11-21 03:16:16 +01:00
1 parent 69308e1345
commit e340bac0bb
14 files changed
+140 -86

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ pi-*.html
# Generated files
packages/coding-agent/export-assets/
packages/coding-agent/src/tools/browser/relay/extension-assets/
packages/coding-agent/src/tools/browser/relay/extension.generated.json
packages/natives/npm/
/runs/
sdk/python/omp-rpc/src/omp_rpc.egg-info/
+2 -2
View File
@@ -26,8 +26,8 @@ After that, updates need no action. omp keeps registered folders current: `omp u
## Development
- `bun run build` (after `bun install --frozen-lockfile` at the repository root) bundles the extension into `dist/extension/`, zips it for GitHub releases, and regenerates the CLI's embedded copy under `packages/coding-agent/src/tools/browser/relay/extension-assets/`.
- That embedded copy is generated, not committed: `bun install` (root `prepare`), binary and npm builds, and the release scripts write it with `bun run gen:embedded`. Run that after changing the extension to test `omp browser-relay install` from source.
- `bun run build` (after `bun install --frozen-lockfile` at the repository root) bundles the extension into `dist/extension/`, zips it for GitHub releases, and regenerates the CLI's embedded copy, `packages/coding-agent/src/tools/browser/relay/extension.generated.json`.
- That copy is generated, not committed. `bun install` (root `prepare`) writes it for source checkouts; run `bun run gen:relay-extension` after changing the extension, and the next `omp` launch rewrites registered extension folders. Binary and npm builds embed a fresh build themselves. A checkout without it still starts; only `omp browser-relay install`/`sync` fail, naming the command.
- `bun scripts/smoke.ts [relay-url] [target-substring]` — end-to-end smoke replicating omp's supervisor + tab-worker double-connection pattern against a live relay.
## Limitations
@@ -1,7 +1,8 @@
/**
* Builds the omp extension. `bun scripts/build-extension.ts` writes `dist/extension/`, the GitHub release ZIP, and
* the unstamped files embedded in the CLI for `omp browser-relay install`. `--embedded` writes only the embedded
* files: install, build and release scripts run it, since the generated directory is not committed.
* Builds the omp extension. `bun scripts/build-extension.ts` writes `dist/extension/`, the GitHub release ZIP, and the
* CLI's embedded copy for `omp browser-relay install`; `--embedded` writes only the embedded copy. That copy is
* generated, not committed: `bun install` writes it for source checkouts, and binary and npm builds embed it through
* {@link generateEmbeddedExtension}.
*/
import * as fs from "node:fs/promises";
import * as os from "node:os";
@@ -15,22 +16,38 @@ import {
const root = path.resolve(import.meta.dir, "..");
const source = path.join(root, "extension");
const dist = path.join(root, "dist");
const assetsDir = path.resolve(root, "../coding-agent/src/tools/browser/relay/extension-assets");
/** Where the CLI reads the embedded copy in a source checkout (see extension-files.ts). */
const embeddedFile = path.resolve(root, "../coding-agent/src/tools/browser/relay/extension.generated.json");
if (process.argv.includes("--embedded")) {
if (import.meta.main) {
if (process.argv.includes("--embedded")) {
await generateEmbeddedExtension();
console.log(`Generated ${embeddedFile}`);
} else {
await buildRelease();
}
}
/**
* Bundle the unstamped extension and write it to `extension.generated.json` as `{ build, files }`, binary files
* base64-encoded. Returns the JSON text written.
*/
export async function generateEmbeddedExtension(): Promise<string> {
const scratch = await fs.mkdtemp(path.join(os.tmpdir(), "omp-relay-extension-"));
try {
await bundleExtension(scratch);
await writeEmbeddedAssets(scratch);
return (await writeEmbedded(scratch)).json;
} finally {
await fs.rm(scratch, { recursive: true, force: true });
}
console.log(`Generated ${assetsDir}`);
} else {
}
/** `dist/extension/`, the pre-stamped release ZIP, and the embedded copy. */
async function buildRelease(): Promise<void> {
const distExtension = path.join(dist, "extension");
await fs.rm(dist, { recursive: true, force: true });
await bundleExtension(distExtension);
const build = await writeEmbeddedAssets(distExtension);
const { build } = await writeEmbedded(distExtension);
// Only the release ZIP is pre-stamped. CLI installs stamp their own version with this build.
const manifest = path.join(distExtension, "manifest.json");
const background = path.join(distExtension, "background.js");
@@ -45,7 +62,7 @@ if (process.argv.includes("--embedded")) {
]);
const zipPath = path.join(dist, "omp-browser-relay-extension.zip");
await $`zip -qr ${zipPath} .`.cwd(distExtension);
console.log(`Built:\n ${distExtension}\n ${zipPath}\n ${assetsDir}`);
console.log(`Built:\n ${distExtension}\n ${zipPath}\n ${embeddedFile}`);
}
/** Bundle the extension's scripts and copy its static files into `outDir`, unstamped. */
@@ -74,47 +91,21 @@ async function bundleExtension(outDir: string): Promise<void> {
}
}
/**
* Replace the CLI's embedded copy with the unstamped extension in `extensionDir`: one text asset per file (binary
* files base64-encoded) and an `index.ts` mapping names to them. Returns the build id it records.
*/
async function writeEmbeddedAssets(extensionDir: string): Promise<string> {
/** Write the unstamped extension in `extensionDir` to {@link embeddedFile}; returns its build id and the JSON text. */
async function writeEmbedded(extensionDir: string): Promise<{ build: string; json: string }> {
const names = [...new Bun.Glob("**/*").scanSync({ cwd: extensionDir, dot: true })]
.map(name => name.replaceAll(path.sep, "/"))
.sort();
const build = await buildId(extensionDir, names);
await fs.rm(assetsDir, { recursive: true, force: true });
const imports: string[] = [];
const entries: string[] = [];
for (const [index, name] of names.entries()) {
const files: Record<string, string | { base64: string }> = {};
for (const name of names) {
const file = Bun.file(path.join(extensionDir, name));
const isText = name === "LICENSE" || /\.(?:css|html|js|json|map|svg|txt)$/.test(name);
await Bun.write(
path.join(assetsDir, `${name}.txt`),
isText ? file : Buffer.from(await file.arrayBuffer()).toBase64(),
);
const binding = `asset${index}`;
const key = name === "LICENSE" ? name : JSON.stringify(name);
imports.push(`import ${binding} from ${JSON.stringify(`./${name}.txt`)} with { type: "text" };`);
entries.push(`\t${key}: ${isText ? binding : `{ base64: ${binding} }`},`);
files[name] = isText ? await file.text() : { base64: Buffer.from(await file.arrayBuffer()).toBase64() };
}
await Bun.write(
path.join(assetsDir, "index.ts"),
[
"// Generated by packages/browser-relay/scripts/build-extension.ts — do not edit.",
...imports,
"",
"/** The unstamped extension files, with binary assets encoded as base64. */",
"export const embeddedRelayFiles = {",
...entries,
"};",
"",
"/** Digest of the unstamped files above; installs stamp it into background.js so a relay can spot a stale build. */",
`export const embeddedRelayBuild = ${JSON.stringify(build)};`,
"",
].join("\n"),
);
return build;
const build = await buildId(extensionDir, names);
const json = JSON.stringify({ build, files });
await Bun.write(embeddedFile, json);
return { build, json };
}
/** First 16 hex chars of SHA-256 over each unstamped file's name and bytes, in `names` order. */
@@ -66,8 +66,6 @@ async function main(): Promise<void> {
// Embed metadata for the same content-addressed viewer used by source exports.
// Generate here too for clean checkouts that skipped install hooks.
await runCommand(["bun", "--cwd=../collab-web", "run", "gen:export-viewer"]);
// The relay extension `omp browser-relay install` writes is generated, not committed.
await runCommand(["bun", "--cwd=../browser-relay", "run", "gen:embedded"]);
await compileCodingAgent({
repoRoot,
entrypoint: path.join(packageDir, "src", "cli.ts"),
+3 -2
View File
@@ -3,6 +3,7 @@
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { isEnoent } from "@oh-my-pi/pi-utils";
import { embeddedRelayExtensionFiles } from "./embed-relay-extension";
import { buildDocsIndexPayload } from "./generate-docs-index";
import { createJsonParsePlugin } from "./json-parse-plugin";
import { createLegacyPiVirtualModulePlugin } from "./legacy-pi-virtual-module";
@@ -97,8 +98,6 @@ export async function bundleDist(outDir: string = defaultOutDir): Promise<void>
// archive the same way compiled binaries do (scripts/build-binary.ts). Reset
// afterwards to keep the checked-in placeholder empty.
await runCommand(["bun", "--cwd=../stats", "run", "gen:stats"]);
// The relay extension `omp browser-relay install` writes is generated, not committed; `src` ships it too.
await runCommand(["bun", "--cwd=../browser-relay", "run", "gen:embedded"]);
// One payload for both consumers: inlined into dist/cli.js via `--define` for
// the bundled CLI entrypoint, and written to dist/docs-index.generated.txt so
// SDK consumers importing `@oh-my-pi/pi-coding-agent/*` (TypeScript source, no
@@ -112,6 +111,8 @@ export async function bundleDist(outDir: string = defaultOutDir): Promise<void>
entrypoints: [path.join(packageDir, "src/cli.ts")],
outdir: outDir,
target: "bun",
// Also refreshes `src/.../extension.generated.json`, which SDK consumers of `src` read.
files: await embeddedRelayExtensionFiles(),
plugins: [createJsonParsePlugin(), await createLegacyPiVirtualModulePlugin(), inlineNativeNoticesPlugin],
external: [...ALWAYS_EXTERNAL, ...RUNTIME_EXTERNAL],
define: {
@@ -3,6 +3,7 @@
import { USER_AGENT } from "@oh-my-pi/pi-utils/dirs";
import { embeddedAddonFiles, type NativeEmbedTarget } from "../../natives/scripts/embed-native";
import { buildDocsIndexPayload } from "./generate-docs-index";
import { embeddedRelayExtensionFiles } from "./embed-relay-extension";
import { createJsonParsePlugin } from "./json-parse-plugin";
import { createLegacyPiVirtualModulePlugin } from "./legacy-pi-virtual-module";
@@ -50,7 +51,10 @@ export async function compileCodingAgent(options: CodingAgentCompileOptions): Pr
entrypoints: [options.entrypoint],
root: options.repoRoot,
external: [...COMPILED_EXTERNAL_DEPENDENCIES],
files: options.native ? await embeddedAddonFiles(options.native) : {},
files: {
...(options.native ? await embeddedAddonFiles(options.native) : {}),
...(await embeddedRelayExtensionFiles()),
},
define: {
"process.env.PI_COMPILED": JSON.stringify("true"),
"process.env.PI_DOCS_EMBED": JSON.stringify((await buildDocsIndexPayload()).payload),
@@ -0,0 +1,19 @@
import * as path from "node:path";
import { generateEmbeddedExtension } from "../../browser-relay/scripts/build-extension";
/** The module builds replace; null on disk. */
const PLACEHOLDER = path.resolve(import.meta.dir, "../src/tools/browser/relay/embedded-extension.ts");
let generated: Promise<string> | undefined;
/**
* Bun.build `files` that compile the omp extension into a binary or bundle. Generates it once per process (which
* also refreshes the checkout's `extension.generated.json`, shipped in the npm package's `src`) and swaps it in for
* the null placeholder.
*/
export async function embeddedRelayExtensionFiles(): Promise<Record<string, string>> {
generated ??= generateEmbeddedExtension();
return {
[PLACEHOLDER]: `export const embeddedRelayExtension = JSON.parse(${JSON.stringify(await generated)});\n`,
};
}
@@ -0,0 +1,6 @@
// Always null on disk. Binary and npm bundle builds replace this module in memory with the generated extension
// (scripts/embed-relay-extension.ts); a source checkout reads `extension.generated.json` instead (extension-files.ts).
import type { RelayExtensionBundle } from "./extension-files";
/** The omp extension compiled into this build; null when running from source. */
export const embeddedRelayExtension: RelayExtensionBundle | null = null;
@@ -6,7 +6,7 @@ import * as fs from "node:fs/promises";
import * as path from "node:path";
import { getBrowserRelayDir, isEnoent } from "@oh-my-pi/pi-utils";
import { replaceFileAtomically } from "../../../utils/atomic-file";
import { embeddedRelayBuild, embeddedRelayFiles } from "./extension-assets";
import { embeddedRelayExtension } from "./embedded-extension";
import {
type RelayExtensionStamp,
readRelayExtensionStamp,
@@ -14,29 +14,63 @@ import {
stampRelayExtensionScript,
} from "./protocol";
/** The extension build these omp files are (a digest of the unstamped files); stamped into every install. */
export const RELAY_EXTENSION_BUILD: string = embeddedRelayBuild;
/** The unstamped extension files, binary ones base64-encoded, as packages/browser-relay/scripts/build-extension.ts writes them. */
export interface RelayExtensionBundle {
/** Digest of the unstamped files; stamped into every install so a relay can spot a stale build. */
build: string;
files: Record<string, string | { base64: string }>;
}
/** Where a source checkout keeps the generated extension; builds embed it instead. */
const GENERATED_EXTENSION = path.join(
import.meta.dir,
"extension.generated.json",
);
let loading: Promise<RelayExtensionBundle> | undefined;
/**
* The extension this omp installs: embedded in binaries and bundles, read from `extension.generated.json` in a source
* checkout. A missing file fails only the caller, so startup survives a checkout that has not generated it.
*
* @throws Error naming `bun run gen:relay-extension` when a source checkout has not generated the extension.
*/
export function loadRelayExtension(): Promise<RelayExtensionBundle> {
if (embeddedRelayExtension) return Promise.resolve(embeddedRelayExtension);
loading ??= Bun.file(GENERATED_EXTENSION)
.json()
.catch((error: unknown) => {
loading = undefined;
if (!isEnoent(error)) throw error;
throw new Error(
`This omp checkout has not built the omp extension (${GENERATED_EXTENSION} is missing). Run \`bun run gen:relay-extension\` at the repository root.`,
);
});
return loading;
}
type ExtensionFiles = Record<string, string | Buffer> & {
"background.js": string;
"manifest.json": string;
};
/** The extension files `omp browser-relay install` writes, stamped with the installing omp's version. */
export function relayExtensionFiles(ompVersion: string): ExtensionFiles {
/**
* The extension files `omp browser-relay install` writes, stamped with the installing omp's version.
*
* @throws Error when the extension is missing (see {@link loadRelayExtension}) or lacks its manifest or service worker.
*/
export async function relayExtensionFiles(
ompVersion: string,
): Promise<ExtensionFiles> {
const { build, files: assets } = await loadRelayExtension();
const manifest = assets["manifest.json"];
const script = assets["background.js"];
if (typeof manifest !== "string" || typeof script !== "string")
throw new Error("The omp extension lacks manifest.json or background.js");
const files: ExtensionFiles = {
"manifest.json": stampRelayExtensionManifest(
embeddedRelayFiles["manifest.json"],
ompVersion,
),
"background.js": stampRelayExtensionScript(
embeddedRelayFiles["background.js"],
ompVersion,
RELAY_EXTENSION_BUILD,
),
"manifest.json": stampRelayExtensionManifest(manifest, ompVersion),
"background.js": stampRelayExtensionScript(script, ompVersion, build),
};
const assets: Readonly<Record<string, string | { base64: string }>> =
embeddedRelayFiles;
for (const name in assets) {
if (name === "background.js" || name === "manifest.json") continue;
const content = assets[name]!;
@@ -65,7 +99,7 @@ export async function writeRelayExtension(
dir: string,
ompVersion: string,
): Promise<boolean> {
const files = relayExtensionFiles(ompVersion);
const files = await relayExtensionFiles(ompVersion);
let changed = false;
for (const name in files) {
if (name === "background.js" || name === "manifest.json") continue;
@@ -12,7 +12,7 @@ import { writeFileAtomically } from "../../../utils/atomic-file";
import {
defaultRelayExtensionDir,
extensionIdForPath,
RELAY_EXTENSION_BUILD,
loadRelayExtension,
writeRelayExtension,
} from "./extension-files";
import { discoverRelayEndpoints } from "./discovery";
@@ -24,7 +24,9 @@ import {
} from "./protocol";
/** The files this omp writes: its version and extension build. A source checkout changes the build, not the version. */
const INSTALL_STAMP = `${VERSION}+${RELAY_EXTENSION_BUILD}`;
async function installStamp(): Promise<string> {
return `${VERSION}+${(await loadRelayExtension()).build}`;
}
/** Managed extension directory and the last asset version omp wrote there. */
export interface RelayInstall {
@@ -253,17 +255,18 @@ export async function syncRelayInstalls(
): Promise<RelayInstallSyncResult[]> {
const { registryFile, defaultDir, relayUrl } = resolveLocations(options);
const initial = await readRelayInstallRegistry(registryFile);
if (options.mode === "startup" && initial.lastSynced === INSTALL_STAMP)
return [];
if (
initial.installs.length === 0 &&
!(await Bun.file(path.join(defaultDir, "manifest.json")).exists())
)
return [];
// Nothing to write without the extension: a source checkout that never generated it fails here, not per folder.
const stamp = await installStamp();
if (options.mode === "startup" && initial.lastSynced === stamp) return [];
await fs.mkdir(path.dirname(registryFile), { recursive: true });
const synced = await withFileLock(registryFile, async () => {
const registry = await readRelayInstallRegistry(registryFile);
if (options.mode === "startup" && registry.lastSynced === INSTALL_STAMP)
if (options.mode === "startup" && registry.lastSynced === stamp)
return [];
let changed = await adoptDefaultInstall(registry, defaultDir);
const results: RelayInstallSyncResult[] = [];
@@ -315,10 +318,10 @@ export async function syncRelayInstalls(
{ dir: path.dirname(registryFile) },
);
if (
registry.lastSynced !== INSTALL_STAMP &&
registry.lastSynced !== stamp &&
!results.some((result) => result.status === "failed")
) {
registry.lastSynced = INSTALL_STAMP;
registry.lastSynced = stamp;
changed = true;
}
} catch (error) {
@@ -108,8 +108,8 @@ describe("omp browser-relay install", () => {
if (message === "extension connected") hello.resolve();
},
});
const runningScript = relayExtensionFiles("18.6.1")["background.js"]!;
const manifestOnDisk = JSON.parse(relayExtensionFiles(VERSION)["manifest.json"]!);
const runningScript = (await relayExtensionFiles("18.6.1"))["background.js"]!;
const manifestOnDisk = JSON.parse((await relayExtensionFiles(VERSION))["manifest.json"]!);
stopWorker = runExtensionWorker(runningScript, port, manifestOnDisk);
await hello.promise;
expect(await relayExtensionNotice(`http://127.0.0.1:${port}`)).toContain(
@@ -14,7 +14,7 @@ import { findFreeCdpPort } from "../../src/tools/browser/attach";
import {
extensionIdForPath,
installedRelayExtensionVersion,
RELAY_EXTENSION_BUILD,
loadRelayExtension,
writeRelayExtension,
} from "../../src/tools/browser/relay/extension-files";
import {
@@ -116,7 +116,7 @@ describe("browser relay install registry", () => {
expect(await installedRelayExtensionVersion(installed)).toBe(VERSION);
expect(await fs.stat(missing).catch(() => undefined)).toBeUndefined();
expect(await readRelayInstallRegistry(registryFile)).toMatchObject({
lastSynced: `${VERSION}+${RELAY_EXTENSION_BUILD}`,
lastSynced: `${VERSION}+${(await loadRelayExtension()).build}`,
});
expect(await readRelayInstalls({ registryFile })).toEqual([
{ dir: installed, version: VERSION, missing: false },
@@ -581,7 +581,7 @@ describe("writing the omp extension", () => {
const dir = home.join("extension");
expect(await writeRelayExtension(dir, VERSION)).toBe(true);
const files = relayExtensionFiles(VERSION);
const files = await relayExtensionFiles(VERSION);
for (const name of [
"LICENSE",
"background.js",
@@ -652,7 +652,7 @@ describe("writing the omp extension", () => {
spy.mockRestore();
}
expect(await Bun.file(home.join("extension/background.js")).text()).toBe(
relayExtensionFiles(OLD)["background.js"],
(await relayExtensionFiles(OLD))["background.js"],
);
expect(
(await fs.readdir(dir)).filter((name) => name.endsWith(".tmp")),
@@ -684,7 +684,7 @@ describe("writing the omp extension", () => {
expect(refused).toBeGreaterThan(1);
expect(await installedRelayExtensionVersion(dir)).toBe(VERSION);
expect(await Bun.file(home.join("extension/background.js")).text()).toBe(
relayExtensionFiles(VERSION)["background.js"],
(await relayExtensionFiles(VERSION))["background.js"],
);
expect(
(await fs.readdir(dir)).filter(
-2
View File
@@ -150,12 +150,10 @@ async function generateBundle(): Promise<void> {
if (isDryRun) {
console.log("DRY RUN bun run gen:stats");
console.log("DRY RUN bun --cwd=packages/collab-web run gen:export-viewer --check");
console.log("DRY RUN bun --cwd=packages/browser-relay run gen:embedded");
return;
}
await runCommand(["bun", "run", "gen:stats"], repoRoot);
await runCommand(["bun", "--cwd=packages/collab-web", "run", "gen:export-viewer", "--check"], repoRoot);
await runCommand(["bun", "--cwd=packages/browser-relay", "run", "gen:embedded"], repoRoot);
}
async function resetArtifacts(): Promise<void> {