Merge PR #5505: fix(plugins): refresh stale Bun git cache before reinstall (@roboomp)

This commit is contained in:
can1357
2026-07-14 23:11:07 +02:00
4 changed files with 199 additions and 9 deletions
+3
View File
@@ -71,6 +71,9 @@
- Fixed Pyright LSP semantic requests hanging during startup.
- Fixed Codex web search requests for GPT-5.6 Responses-Lite models.
- Fixed custom model/provider configuration discovery to correctly load ~/.omp/agent/models.yaml when models.yml is absent.
### Fixed
- Fixed git plugin re-installs retaining stale commits by fetching Bun's cached clone before updating the lockfile pin ([#5401](https://github.com/can1357/oh-my-pi/issues/5401)).
## [16.5.0] - 2026-07-13
@@ -0,0 +1,91 @@
import type { Dirent } from "node:fs";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { isEnoent } from "@oh-my-pi/pi-utils";
import type { GitSource } from "./git-url";
interface CommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
async function runCommand(command: string[], cwd: string): Promise<CommandResult> {
const proc = Bun.spawn(command, {
cwd,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
windowsHide: true,
});
const [exitCode, stdout, stderr] = await Promise.all([
proc.exited,
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
return { exitCode, stdout, stderr };
}
function normalizeRepositoryUrl(repository: string): string {
const withoutFragment = repository.replace(/^git\+/i, "").replace(/#.*$/, "");
const scpLike = withoutFragment.match(/^(?:[^@]+@)?([^:]+):(.+)$/);
if (scpLike && !withoutFragment.includes("://")) {
const host = scpLike[1]?.toLowerCase() ?? "";
const repoPath = (scpLike[2] ?? "").replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
return `ssh://${host}/${repoPath}`;
}
try {
const parsed = new URL(withoutFragment);
const repoPath = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}/${repoPath}`;
} catch {
return withoutFragment.replace(/\/+$/g, "").replace(/\.git$/i, "");
}
}
/** Fetches current heads and tags into Bun's matching cached bare clone before a plugin update. */
export async function refreshBunGitCache(source: GitSource, cwd: string): Promise<void> {
const cacheResult = await runCommand(["bun", "pm", "cache"], cwd);
if (cacheResult.exitCode !== 0) {
throw new Error(`bun pm cache failed: ${cacheResult.stderr}`);
}
const cacheDir = cacheResult.stdout.trim();
if (!cacheDir) {
throw new Error("bun pm cache returned an empty cache path");
}
let entries: Dirent[];
try {
entries = await fs.readdir(cacheDir, { withFileTypes: true });
} catch (err) {
if (isEnoent(err)) return;
throw err;
}
const repositoryUrl = normalizeRepositoryUrl(source.repo);
for (const entry of entries) {
if (!entry.isDirectory() || !entry.name.endsWith(".git")) continue;
const repositoryDir = path.join(cacheDir, entry.name);
const originResult = await runCommand(["git", "-C", repositoryDir, "config", "--get", "remote.origin.url"], cwd);
if (originResult.exitCode !== 0 || normalizeRepositoryUrl(originResult.stdout.trim()) !== repositoryUrl) continue;
const fetchResult = await runCommand(
[
"git",
"-C",
repositoryDir,
"fetch",
"--force",
"--prune",
"origin",
"+refs/heads/*:refs/heads/*",
"+refs/tags/*:refs/tags/*",
],
cwd,
);
if (fetchResult.exitCode !== 0) {
throw new Error(`Failed to refresh Bun's git cache for ${source.host}/${source.path}: ${fetchResult.stderr}`);
}
}
}
@@ -12,6 +12,7 @@ import {
logger,
} from "@oh-my-pi/pi-utils";
import { withExitGuard } from "../utils";
import { refreshBunGitCache } from "./bun-git-cache";
import { type GitSource, parseGitUrl } from "./git-url";
import { installLegacyPiSpecifierShim, loadLegacyPiModule } from "./legacy-pi-compat";
import { resolvePluginManifestEntries } from "./loader";
@@ -521,14 +522,13 @@ export class PluginManager {
// Step 2: refresh the git lockfile pin when re-installing an existing
// git plugin. `bun install <spec>` is a no-op when the spec matches the
// lockfile entry — it never re-resolves the remote ref — so re-running
// `omp plugin install github:owner/repo` would silently keep the user on
// the original resolved commit even after upstream moved (#3063).
// `bun update <name>` re-resolves the ref against the remote and
// rewrites the pin; SHA-pinned refs stay put because the commit can't
// move. First-time installs skip this — the initial `bun install` already
// fetched HEAD. Rollback is handled by the outer catch.
// lockfile entry, while `bun update <name>` resolves through Bun's bare
// clone cache. Fetch the matching cache clone first so a stale cached
// ref cannot silently preserve the old pin (#3063, #5401). First-time
// installs skip this because the initial `bun install` populated the
// cache from the remote. Rollback is handled by the outer catch.
if (gitSource && existingActualName) {
await refreshBunGitCache(gitSource, getPluginsDir());
const updateProc = Bun.spawn(["bun", "update", actualName], {
cwd: getPluginsDir(),
stdin: "ignore",
@@ -31,6 +31,24 @@ function emptyStream(): ReadableStream<Uint8Array> {
return body;
}
async function runCommand(command: string[], cwd: string): Promise<string> {
const proc = Bun.spawn(command, {
cwd,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [exitCode, stdout, stderr] = await Promise.all([
proc.exited,
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
if (exitCode !== 0) {
throw new Error(`${command.join(" ")} failed (${exitCode}): ${stderr}`);
}
return stdout.trim();
}
describe("PluginManager.install with git sources", () => {
let tmpRoot: string;
let pluginsDir: string;
@@ -161,7 +179,7 @@ describe("PluginManager.install with git sources", () => {
expect(result.version).toBe("1.0.0");
});
test("re-installing a github plugin runs `bun update` to refresh the stale lockfile pin (#3063)", async () => {
test("refreshes Bun's git cache before updating a re-installed github plugin (#3063)", async () => {
// Seed plugins/package.json + node_modules with a previously-installed
// github plugin. `findGitPackageName` matches the new install spec to
// this existing dep (by repository identity), which is the signal the
@@ -184,6 +202,8 @@ describe("PluginManager.install with git sources", () => {
path.join(seedDir, "package.json"),
JSON.stringify({ name: "stale-plugin", version: "0.1.0" }, null, 2),
);
const cacheDir = path.join(tmpRoot, "bun-cache");
await fs.mkdir(cacheDir);
const spawnedCommands: string[][] = [];
vi.spyOn(Bun, "spawn").mockImplementation(((cmd: string[]) => {
@@ -200,6 +220,16 @@ describe("PluginManager.install with git sources", () => {
exited: Promise.resolve(0),
} as Subprocess;
}
if (cmd[1] === "pm") {
const stdout = new Response(`${cacheDir}\n`).body;
if (!stdout) throw new Error("Failed to create cache path stream");
return {
pid: 2,
stdout,
stderr: emptyStream(),
exited: Promise.resolve(0),
} as Subprocess;
}
// The follow-up call: simulate bun resolving the upstream HEAD to a
// newer commit and bumping the on-disk version. The manager should
// read the new version from package.json after this step returns.
@@ -211,7 +241,7 @@ describe("PluginManager.install with git sources", () => {
);
})();
return {
pid: 2,
pid: 3,
stdout: emptyStream(),
stderr: emptyStream(),
exited: prepare.then(() => 0),
@@ -224,6 +254,7 @@ describe("PluginManager.install with git sources", () => {
expect(result.version).toBe("0.1.6");
expect(spawnedCommands).toEqual([
["bun", "install", "github:foo/bar"],
["bun", "pm", "cache"],
["bun", "update", "stale-plugin"],
]);
});
@@ -403,6 +434,71 @@ describe("PluginManager.install with git sources", () => {
expect(installed.name).toBe("real-name");
});
test("refreshes Bun's cached git clone before updating an existing plugin (#5401)", async () => {
const sourceDir = path.join(tmpRoot, "source");
const httpRoot = path.join(tmpRoot, "http");
const remoteDir = path.join(httpRoot, "testuser", "remote.git");
const cacheDir = path.join(tmpRoot, "bun-cache");
await fs.mkdir(sourceDir, { recursive: true });
await fs.mkdir(path.dirname(remoteDir), { recursive: true });
await runCommand(["git", "init", "-b", "main"], sourceDir);
await runCommand(["git", "config", "user.name", "Plugin test"], sourceDir);
await runCommand(["git", "config", "user.email", "plugin-test@example.com"], sourceDir);
await Bun.write(
path.join(sourceDir, "package.json"),
JSON.stringify({ name: "@test/pi-package", version: "1.0.0" }, null, 2),
);
await runCommand(["git", "add", "package.json"], sourceDir);
await runCommand(["git", "commit", "-m", "version A"], sourceDir);
await runCommand(["git", "clone", "--bare", sourceDir, remoteDir], tmpRoot);
await runCommand(["git", "update-server-info"], remoteDir);
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
async fetch(request) {
const url = new URL(request.url);
const relativePath = decodeURIComponent(url.pathname).replace(/^\/+/, "");
const filePath = path.resolve(httpRoot, relativePath);
if (!filePath.startsWith(`${httpRoot}${path.sep}`)) {
return new Response("Not found", { status: 404 });
}
try {
return new Response(await Bun.file(filePath).arrayBuffer(), {
headers: { "Content-Type": "application/octet-stream" },
});
} catch {
return new Response("Not found", { status: 404 });
}
},
});
try {
await Bun.write(
pluginsPkgJson,
JSON.stringify({ name: "omp-plugins", private: true, dependencies: {} }, null, 2),
);
await Bun.write(path.join(pluginsDir, "bunfig.toml"), `[install.cache]\ndir = ${JSON.stringify(cacheDir)}\n`);
const spec = `git+http://127.0.0.1:${server.port}/testuser/remote.git#main`;
const mgr = new PluginManager(tmpRoot);
expect((await mgr.install(spec)).version).toBe("1.0.0");
await Bun.write(
path.join(sourceDir, "package.json"),
JSON.stringify({ name: "@test/pi-package", version: "2.0.0" }, null, 2),
);
await runCommand(["git", "add", "package.json"], sourceDir);
await runCommand(["git", "commit", "-m", "version B"], sourceDir);
await runCommand(["git", "push", remoteDir, "main"], sourceDir);
await runCommand(["git", "update-server-info"], remoteDir);
const reinstalled = await mgr.install(spec);
expect(reinstalled.version).toBe("2.0.0");
} finally {
await server.stop(true);
}
});
test("rejects git specs containing shell metacharacters", async () => {
const mgr = new PluginManager(tmpRoot);
await expect(mgr.install("github:foo/bar; rm -rf /")).rejects.toThrow(/Invalid characters in plugin source/);