Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/run-ci-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const LIVE_FILES = [
"tests/hook-command.test.ts",
"tests/index-entry-guard.test.ts",
"tests/issue1958-routed-warn.test.ts",
"tests/issue2752-forward-partial-outcome.test.ts",
"tests/issue760-percall-conversation.test.ts",
"tests/issue927-opencode-install.test.ts",
"tests/kimi-native.test.ts",
Expand Down
44 changes: 44 additions & 0 deletions src/dsh-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,50 @@ export function dshProfileDependsOnBili(profileDir: string): boolean {
return dshProfileDepSpec(profileDir) !== undefined;
}

/** #2894: converge this profile's declared billion-context spec to the version
* bili just installed IN PLACE (the dsh desktop lane — #1575). The desktop
* copy's node_modules entry is swapped by bili's own tarball installer while
* the profile's package.json still declares the OLD version; dsh's in-app
* plugin manager reconciles node_modules through pnpm against that manifest,
* so a user clicking "install" restores the old version and silently reverts
* the auto-update. Rewriting the spec to the installed version (caret/exact
* style preserved) makes the lockfile pin on the old version unsatisfiable,
* forcing the next pnpm reconciliation to re-resolve FORWARD instead of
* rolling back. Deliberate local pins (link:/file:/git+…) and non-version
* specs (dist-tags, other ranges) are respected and left alone. Returns
* undefined when the manifest now declares the installed version (written or
* already in step), or a short reason when it was left untouched — callers
* log, never throw on this. */
export function syncDshProfileManifestSpec(profileDir: string, installedVersion: string): string | undefined {
const file = path.join(profileDir, "package.json");
let raw: string;
try {
raw = fs.readFileSync(file, "utf8");
} catch {
return "no readable package.json";
}
let doc: { dependencies?: Record<string, unknown> };
try {
doc = JSON.parse(raw) as { dependencies?: Record<string, unknown> };
} catch {
return "malformed package.json";
}
const deps = doc.dependencies;
if (!deps || typeof deps[DSH_PACKAGE] !== "string") return "no billion-context dependency declared";
const spec = deps[DSH_PACKAGE];
if (!isRegistryDepSpec(spec)) return `local pin ${spec} respected`;
const m = spec.match(/^\^?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);
if (!m) return `non-version spec ${spec} respected`;
if (m[1] === installedVersion) return undefined; // already in step — no rewrite
deps[DSH_PACKAGE] = spec.startsWith("^") ? `^${installedVersion}` : installedVersion;
try {
fs.writeFileSync(file, JSON.stringify(doc, null, 2) + "\n");
} catch (e) {
return `manifest write failed: ${e instanceof Error ? e.message : String(e)}`;
}
return undefined;
}

/** The version of the profile's installed billion-context copy, or undefined
* when there is no readable copy yet (declared but never installed). #1803:
* refresh skips profiles already sitting at the target version so a stale
Expand Down
26 changes: 25 additions & 1 deletion src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { fileURLToPath } from "node:url";
import { safeSuffix } from "./text-safe.js";
import { cacheDir } from "./paths.js";
import { log as loggerLog, type Logger } from "./logger.js";
import { refreshDshProfileBundles, isDshProfileCopy, dshProfileDirs, dshProfileDependsOnBili, dshProfileDepSpec, isRegistryDepSpec, DSH_PACKAGE, DSH_DESKTOP_PROFILE } from "./dsh-channel.js";
import { refreshDshProfileBundles, isDshProfileCopy, dshProfileDirs, dshProfileDependsOnBili, dshProfileDepSpec, isRegistryDepSpec, syncDshProfileManifestSpec, DSH_PACKAGE, DSH_DESKTOP_PROFILE } from "./dsh-channel.js";
import { isPiNpmCopy, piNpmEntrySpec, runPiAsync, PI_NPM_SPEC } from "./pi-channel.js";
import { resolveDshHome, resolveKimiHome, resolveOmpHome, resolvePiHome } from "./client-config.js";
import { proxyDispatcher } from "./upstream-proxy.js";
Expand Down Expand Up @@ -1630,6 +1630,13 @@ export async function installViaTarball(
return { ok: false, error: `install dir is a git working tree (${installDir}) \u2014 refusing to overwrite a source checkout (use npm install -g)` };
}

let real = installDir;
try {
real = realpathSync(installDir);
} catch {
// nonexistent or unreadable — evaluate the literal path
}

// #991 single-writer: refuse to overwrite a host-managed copy (pnpm
// store, host agent data trees) — only its owner may update it.
// Exception: the dsh desktop-profile copy is bili-owned in place (#1575).
Expand Down Expand Up @@ -1853,6 +1860,23 @@ export async function installViaTarball(
}
await rm(workDir, { recursive: true, force: true });

// #2894: the dsh desktop lane is the only one bili overwrites in place
// while the host's pnpm bookkeeping (profile package.json spec + lockfile
// pin) still names the OLD version — dsh's in-app plugin manager then
// reconciles node_modules back to that stale manifest on the user's next
// "install" click, silently reverting the update. Converge the declared
// spec to the version just installed so every in-place write (auto-update,
// self-update from this copy, advisory force-install) stays sticky.
if (isDshDesktopBiliCopy(installDir, real, env)) {
const profileDir = path.join(resolveDshHome(env), "profiles", DSH_DESKTOP_PROFILE);
const note = syncDshProfileManifestSpec(profileDir, version);
if (note !== undefined) {
loggerLog("warn", `[update] dsh ${DSH_DESKTOP_PROFILE} profile copy replaced but its manifest spec was not synced (${note}) — dsh may revert the copy on its next plugin install`);
} else {
loggerLog("info", `[update] dsh ${DSH_DESKTOP_PROFILE} profile manifest spec now declares ${version}`);
}
}

return { ok: true };
}

Expand Down
113 changes: 112 additions & 1 deletion tests/update-desktop-inplace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import * as tar from "tar";
const __cacheRoot = mkdtempSync(path.join(tmpdir(), "bc-desktop-inplace-cache-"));
process.env.XDG_CACHE_HOME = path.join(__cacheRoot, "cache");
const { installViaTarball, readDiskVersion, refreshDshDesktopCopy } = await import("../src/update.ts");
import { refreshDshProfileBundles } from "../src/dsh-channel.ts";
import { refreshDshProfileBundles, syncDshProfileManifestSpec } from "../src/dsh-channel.ts";
import { rmrf } from "./tmp-rm.ts";

function integrityField(buf: Buffer, alg = "sha512"): string {
Expand Down Expand Up @@ -250,3 +250,114 @@ test("refreshDshProfileBundles skips the desktop profile without spawning the CL
// not a missing probe.
assert.ok(lines.some((l) => l.includes("profile web") && l.includes("failed")), `expected the web profile's CLI attempt to fail visibly: ${lines.join(" | ")}`);
});

// —— #2894: the in-place swap must converge the profile's pnpm manifest too ———

test("refreshDshDesktopCopy: manifest spec converges to the installed version, rest of the manifest preserved (#2894)", { timeout: 30_000 }, async (t) => {
const root = mkdtempSync(path.join(tmpdir(), "bc-desktop-manifest-"));
const prevDshHome = process.env.DSH_HOME;
const prevXdgCacheHome = process.env.XDG_CACHE_HOME;
const originalFetch = globalThis.fetch;
t.after(() => {
globalThis.fetch = originalFetch;
if (prevDshHome === undefined) delete process.env.DSH_HOME;
else process.env.DSH_HOME = prevDshHome;
if (prevXdgCacheHome === undefined) delete process.env.XDG_CACHE_HOME;
else process.env.XDG_CACHE_HOME = prevXdgCacheHome;
rmrf(root);
});
try {
const fx = buildDesktopFixture(root, "0.1.180", "0.1.194");
const manifestPath = path.join(fx.dshHome, "profiles", "desktop", "package.json");
writeFileSync(manifestPath, JSON.stringify({
name: "@dsh/profile-desktop",
dependencies: { "billion-context": "^0.1.180", "other-dep": "^1.2.3" },
dsh: { profile: { bundles: ["billion-context"] } },
}, null, 2) + "\n");
process.env.DSH_HOME = fx.dshHome;
process.env.XDG_CACHE_HOME = path.join(root, "cache");
stubRegistryFetch(fx.tgz, "https://registry.test/bc-0.1.194.tgz", "0.1.194", integrityField(fx.tgz));
await refreshDshDesktopCopy("0.1.194", captureLog().log, process.env);

assert.equal(await readDiskVersion(fx.flat), "0.1.194");
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
name?: string;
dependencies?: Record<string, string>;
dsh?: { profile?: { bundles?: string[] } };
};
assert.equal(manifest.dependencies?.["billion-context"], "^0.1.194", "the declared spec must follow the installed version so pnpm reconciles forward");
assert.equal(manifest.dependencies?.["other-dep"], "^1.2.3", "unrelated deps must survive untouched");
assert.deepEqual(manifest.dsh?.profile?.bundles, ["billion-context"], "the bundle registration must survive untouched");
assert.equal(manifest.name, "@dsh/profile-desktop");
} catch (e) {
if (String(e).includes("EPERM")) {
t.skip("creating directory symlinks requires elevated privileges on this platform");
return;
}
throw e;
}
});

test("syncDshProfileManifestSpec: style-preserving convergence, pins and odd specs respected (#2894)", () => {
const root = mkdtempSync(path.join(tmpdir(), "bc-desktop-spec-"));
try {
const writeManifest = (spec: string | undefined, extra = ""): string => {
const dir = mkdtempSync(path.join(root, "profile-"));
if (extra !== "malformed") {
const doc: Record<string, unknown> = { name: "@dsh/profile-test" };
if (spec !== undefined) doc.dependencies = { "billion-context": spec };
writeFileSync(path.join(dir, "package.json"), JSON.stringify(doc, null, 2) + "\n");
} else {
writeFileSync(path.join(dir, "package.json"), "{ not json");
}
return dir;
};

// caret bump keeps caret style
let dir = writeManifest("^0.1.180");
assert.equal(syncDshProfileManifestSpec(dir, "0.1.194"), undefined);
assert.equal((JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) as { dependencies: Record<string, string> }).dependencies["billion-context"], "^0.1.194");

// exact bump keeps exact style
dir = writeManifest("0.1.180");
assert.equal(syncDshProfileManifestSpec(dir, "0.1.194"), undefined);
assert.equal((JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) as { dependencies: Record<string, string> }).dependencies["billion-context"], "0.1.194");

// already in step: no rewrite at all (bytes unchanged)
dir = writeManifest("^0.1.194");
const before = readFileSync(path.join(dir, "package.json"), "utf8");
assert.equal(syncDshProfileManifestSpec(dir, "0.1.194"), undefined);
assert.equal(readFileSync(path.join(dir, "package.json"), "utf8"), before);

// downgrade convergence (advisory rollback direction): the spec must
// follow DOWN too, or the next reconciliation undoes the rollback
dir = writeManifest("^2.0.0");
assert.equal(syncDshProfileManifestSpec(dir, "1.5.0"), undefined);
assert.equal((JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) as { dependencies: Record<string, string> }).dependencies["billion-context"], "^1.5.0");

// deliberate local pin respected
dir = writeManifest("link:/somewhere/dev");
assert.ok(syncDshProfileManifestSpec(dir, "0.1.194")?.includes("local pin") ?? false);
assert.equal((JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) as { dependencies: Record<string, string> }).dependencies["billion-context"], "link:/somewhere/dev");

// dist-tag and non-version ranges left alone
for (const odd of ["latest", ">=0.1.0", "~0.1.180"]) {
dir = writeManifest(odd);
const oddBefore = readFileSync(path.join(dir, "package.json"), "utf8");
const reason = syncDshProfileManifestSpec(dir, "0.1.194");
assert.ok(reason !== undefined && reason.includes(odd), `expected ${odd} to be respected, got: ${reason ?? "changed"}`);
assert.equal(readFileSync(path.join(dir, "package.json"), "utf8"), oddBefore);
}

// no dependency declared / malformed / missing file: reason, no throw, no clobber
dir = writeManifest(undefined);
assert.ok(syncDshProfileManifestSpec(dir, "0.1.194")?.includes("no billion-context") ?? false);
dir = writeManifest(undefined, "malformed");
const malformedBefore = readFileSync(path.join(dir, "package.json"), "utf8");
assert.ok(syncDshProfileManifestSpec(dir, "0.1.194")?.includes("malformed") ?? false);
assert.equal(readFileSync(path.join(dir, "package.json"), "utf8"), malformedBefore);
assert.ok(syncDshProfileManifestSpec(path.join(root, "no-such-profile"), "0.1.194")?.includes("no readable") ?? false);
} finally {
rmrf(root);
}
});
Loading