Files
openbot/scripts/reset-dev-state.ts
T
NBandClaude Opus 5 2fb01dbb9d fix: keep one provider CLI store for each computer (#466)
* fix: keep one provider CLI store for each computer

The "OpenCode update available" notification returned after every restart
because the managed CLI store lived in `userData`, which development gives to
each renderer port and each isolated worktree. A profile with no managed copy
fell back to the user's own CLI, reported its older version, and was offered the
pinned update again - after another 144 MB download.

The store moves to `appData/OpenBot/provider-runtimes`, which is byte-identical
to the packaged app's current path, so no released path moves and no migration
is needed. `--user-data-dir` keeps the store in that directory, so an explicitly
named profile stays self-contained. Partial downloads stay per profile.

A shared root can have several instances in it at once, so installs are now
safe to run side by side: staging directories carry a pid and random suffix and
are swept by age, a commit that finds the destination occupied verifies it and
adopts it instead of deleting it, version collection keeps anything a live
instance stamped within the month and never fails startup, and `download()`
re-inspects the store before it starts.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: activate a runtime a sibling instance installed

Two defects in the shared store, from the code review.

An update that found the version already in the store set `ready` and returned
without the activation callback, so the agent service kept the old CLI in its
running clients, `trackSystemCliVersions` kept reporting the old version, and
the offer stayed on screen with no way left to answer it - every later attempt
returned at once, because the manager was already `ready`. The store read moves
into the update task: a sibling's install skips the transfer, not the swap.

That read also sat between the `#tasks.has` guard and the registration of the
task, so two requests for one provider could both pass the guard and register
separate tasks. The second overwrote the first's controller, and the first
task's cleanup then dropped the second's record, which broke cancellation and
shutdown tracking. Nothing is awaited between the guard and the registration
now, and the task rechecks the stopping state before it starts a transfer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: keep a runtime an instance one pin behind still runs

Two more findings from the code review, both on the store the computer shares.

Only the pinned version was stamped as in use, so the older version an instance
falls back to until the pinned one arrives carried no record at all. A worktree
pinned further ahead keeps its own spare and collects that one once it is a
month old, which takes the CLI away from underneath the agent service running
it. `#previousVersion` now stamps what it selects.

A commit that has to replace a damaged destination can also meet another
instance replacing the same one. The destination can be moved, filled, or taken
away between any two steps, and the commit answered a vanished destination with
ENOENT and a refilled one with an occupied-destination error. It now reads the
destination again on each pass, up to three: a verified copy is adopted, only
what is still damaged is replaced, and a store that keeps answering that way
fails the update rather than looping.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: read a replaced runtime once more before discarding it

The remaining review finding: two instances can both reject the same damaged
destination, and the second could then move the good install the first had just
committed aside and remove it.

The copy that was moved aside is now read once more, when nothing else can
reach it. One that verifies is an install a sibling made between the check and
the move, and the sibling is running it, so it goes back where it was and this
instance adopts it. Only a copy that is still damaged is replaced and removed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: claim a damaged runtime before replacing it

The review is right that reading the destination and replacing it are two
steps: two instances can both reject the same damaged copy, and the second then
moves the install the first has just committed, leaving the shared path absent
while it verifies what it took.

A commit now claims the destination first. The claim is a lock directory beside
the staging ones, which `mkdir` grants to one instance at a time on every
platform and across users, with nothing to clean up but a directory. Whoever
holds it reads the destination again, so a copy a sibling committed in the
meantime is adopted and never moved, and the path is absent only for the rename
of the one instance entitled to replace it. A claim as old as an abandoned
staging directory is one a killed instance left behind, so it is taken over -
age is the same evidence the sweep already uses, and the sweep collects these
too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: recover an abandoned runtime claim exactly once

The review is right that the recovery path was itself a race: two instances
could read the same old timestamp, and the second's removal would take away the
claim the first had just made, leaving both of them entitled to replace the
destination.

An abandoned claim is now cleared by moving it away, so the only instance that
goes on to claim the path is the one whose rename found it still there. The
claim carries a token, and a release removes the directory only while the token
is still this attempt's. The sweep no longer collects claims: it holds none
itself, so it would be one more unsynchronised writer of the path the claim
exists to serialise, and what a recovery leaves behind is swept under the
`.replaced-` prefix instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: put back a claim made while an abandoned one was recovered

The sequence the review describes is real: two instances that read the same old
timestamp both enter recovery, and the second's rename moves the claim the
first has just made rather than the abandoned one, so both end up entitled to
replace the destination.

A recovery now reads the age of what it moved once more, where nothing else can
reach it. A claim that is fresh by then is not the abandoned one at all, so it
goes back where it was and that instance gives up the path. The holder also
reads the claim again immediately before it moves the destination, so an
instance that lost the claim in any other order stops before touching it rather
than after.

What is left is one filesystem operation wide - no portable primitive compares
and swaps a directory - against a claim that is already six hours stale, and it
ends with two identical, checksum-verified copies of the same pinned version.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: keep a claim and a stage out of another build's way

A claim directory used to exist for a moment with nothing in it, between the `mkdir` that took it
and the write that named its owner. An instance that read its age in that moment saw a fresh claim
it could neither take nor recover. The claim is now built beside the path, with its owner already
inside it, and moved onto the path in one step, so it never exists without naming an owner, and the
recovery that put a moved claim back -- which could leave an unowned one behind -- is no longer
needed.

Released builds share this store and carry the manager this one replaces, whose sweep deletes every
`.installing-` directory when it starts, whatever its age and whoever is filling it. Stages are now
named `.staging-`, out of that sweep's reach; the older prefix stays on the age sweep here to
collect what those builds abandon.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: recover only the runtime claim whose age was read

Two instances can both read the same abandoned claim, and the one that moves it away second moves
the claim the first made while recovering it. It then took the path, so both believed they held it,
and only the holder's re-read kept the second away from the destination.

The move is atomic, so what it moved is that instance's alone to read: the claim it names is either
the abandoned one, which was the point of the move, or one made in between, which belongs to an
instance that recovered the path first. In that case this attempt takes nothing.

The released collector of old versions is left as the one thing the shared store cannot defend, and
is written down in the architecture notes with what a store of its own would cost.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: read who holds a runtime claim before reading its age

The age and the name could come from two different directories: an instance read the age of the
abandoned claim, then read the name of the claim another instance made while recovering it. Both
then held the same path, because the name it moved matched the name it had read.

A claim on the path is only ever replaced by a newer one, so reading the name first settles it: an
age that still reads old belongs to the directory the name came from, or to one it already
replaced, and a name older than the path now holds costs one more attempt and nothing else.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: read a moved runtime once more before replacing it

The claim says no other instance may move this destination, and the reading before the move says
this one was damaged. Both are true when they are read, and neither is a promise about the moment
of the move: an instance whose claim was taken from it can still be between its own check and its
rename, and can commit a good install into the destination in between.

What was moved aside is now read once more, where nothing else can change it. A runtime that
verifies is a sibling's install, so it goes back where the sibling left it and is adopted. Nothing
that verifies is replaced, whatever the claim said.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: keep a runtime that verifies when an install reports failure

The reading that follows a commit can fail because a sibling was replacing the destination while it
ran, not because the runtime is bad. The failure path then removed the install root, which on a
shared store is the copy the sibling just put back.

It now removes the destination only while the destination does not verify. A rejected artifact is
still taken away, which is what the rule is for; a runtime that verifies is left where it is, and
the install reports its failure without taking the store with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: hold a rejected runtime before reading and removing it

A reading and a delete are two steps, and the path can change between them: the destination could
be read as absent, a sibling could put its own copy there, and the delete that followed took the
copy away.

Nothing is read in place and nothing is deleted in place any more. What is there is moved away
first, which the filesystem grants to one instance at a time, and read where nothing else can reach
it: a runtime that verifies goes back where the sibling left it, and only what does not verify is
removed, by the one instance that can see it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: describe how a rejected runtime is taken away

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: keep a sibling's runtime when an adopted copy fails to activate

An activation failure removed the install root whenever this instance ran
a download, including when the commit adopted the copy a sibling had put
in the shared store first. The sibling runs its CLI from that directory.
The install now reports whether it committed or adopted, and only what
this instance wrote is taken away.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 16:33:41 +02:00

91 lines
3.1 KiB
TypeScript

import { lstat, rm } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, parse, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { createOpenBotLogger, toLogValue } from "@openbot/logging";
import { type DevelopmentProfile, developmentUserDataName } from "../src/main/development-profile";
import { resolveDevelopmentAppDataRoot } from "./development-state-paths";
import { cleanupSeedOwnedTransfers } from "./seed-dev-state";
export { resolveDevelopmentAppDataRoot } from "./development-state-paths";
const logger = createOpenBotLogger("reset-dev-state");
const developmentProfiles = ["app", "test-client"] as const satisfies readonly DevelopmentProfile[];
const legacyDevelopmentStateNames = ["OpenBot Dev Host"] as const;
export function developmentStatePaths(appDataRoot: string): string[] {
const safeRoot = resolve(appDataRoot);
if (safeRoot === parse(safeRoot).root) {
throw new Error("The application data root cannot be a filesystem root.");
}
return [
...developmentProfiles.map((profile) => developmentUserDataName(profile)),
...legacyDevelopmentStateNames,
].map((name) => {
const target = resolve(safeRoot, name);
if (dirname(target) !== safeRoot) {
throw new Error(`Unsafe OpenBot dev state path: ${target}`);
}
return target;
});
}
export async function resetDevelopmentState(appDataRoot: string, homeDirectory = homedir()): Promise<string[]> {
const deletedPaths: string[] = [];
for (const statePath of developmentStatePaths(appDataRoot)) {
try {
await lstat(statePath);
} catch (error) {
if (isMissing(error)) {
continue;
}
throw error;
}
await cleanupSeedOwnedTransfers(statePath, homeDirectory);
await rm(statePath, { force: true, maxRetries: 3, recursive: true, retryDelay: 100 });
deletedPaths.push(statePath);
}
return deletedPaths;
}
async function main(): Promise<void> {
const appDataRoot = resolveDevelopmentAppDataRoot();
const deletedPaths = await resetDevelopmentState(appDataRoot);
if (deletedPaths.length === 0) {
logger.info("No OpenBot development state was found.");
} else {
logger.info("OpenBot development state reset:");
for (const deletedPath of deletedPaths) {
logger.info(`- ${deletedPath}`);
}
}
logger.info("Seed-owned transfer files were removed. Other shared files were not changed.");
logger.info("Agent workspaces, ~/.codex, and ~/.claude were not changed.");
// The downloaded provider CLIs are the computer's now, not this profile's, so a reset no longer
// takes them. Say so: it used to cost a fresh download of every one of them.
logger.info("Downloaded provider CLIs were not changed.");
}
function isMissing(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error && error.code === "ENOENT";
}
function isMainModule(): boolean {
const entryPath = process.argv[1];
return entryPath !== undefined && import.meta.url === pathToFileURL(resolve(entryPath)).href;
}
if (isMainModule()) {
main().catch((error: unknown) => {
logger.error(toLogValue(error));
process.exitCode = 1;
});
}