Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
CI flakes follow-up: checkpoint cleanup no longer forgotten, installer token fallback, wait_healthy one container, MOCA-202 (#6872)
Milind Sonic331495b4d9a
diff --git a/.github/workflows/server-installer.yml b/.github/workflows/server-installer.ymlindex d68ad7a21c..a11dc9b205 100644--- a/.github/workflows/server-installer.yml+++ b/.github/workflows/server-installer.yml@@ -2,7 +2,8 @@ name: Server installer# The self-hosted server's installer (deploy/install.sh) on a stock ubuntu-24.04 runner, as a person runs it on a fresh# server: shellcheck, its checks against made-up servers, then the checks and a real install of the published image-# (deploy/e2e/run.sh). It talks to no production service and needs no secret.+# (deploy/e2e/run.sh). It talks to no production service and needs no secret of its own: only the workflow's own+# GITHUB_TOKEN, read-only, for the installer's lookup of the newest release (OMB_INSTALL_GITHUB_TOKEN).on:pull_request:paths:diff --git a/deploy/install.sh b/deploy/install.shindex c43b74f24e..51c2152897 100755--- a/deploy/install.sh+++ b/deploy/install.sh@@ -510,14 +510,23 @@ note_sandbox() { # tag or sha256:digestfi}+release_tag() { sed -n 's/.*"tag_name": *"\(v[0-9][0-9.]*\)".*/\1/p' | head -n 1; }+newest_release() {# OMB_INSTALL_GITHUB_TOKEN, for a test run on a shared CI machine only: api.github.com answers few reads without one- # from an address many others share. A person's run sends none. The token goes to curl on its standard input.- if [ -n "${OMB_INSTALL_GITHUB_TOKEN:-}" ]; then- printf 'header = "Authorization: Bearer %s"\n' "$OMB_INSTALL_GITHUB_TOKEN" | curl -K - -fsS --max-time 15 "$RELEASES_URL" 2>/dev/null- else- curl -fsS --max-time 15 "$RELEASES_URL" 2>/dev/null- fi | sed -n 's/.*"tag_name": *"\(v[0-9][0-9.]*\)".*/\1/p' | head -n 1+ # from an address many others share. A person's run sends none. The token goes to curl on its standard input, inside a+ # quoted value, so one with anything but letters, digits and _ (as GitHub's have) is not sent. A token GitHub refuses+ # (401) answers nothing: the lookup is then made once more without it, as a person's run makes it.+ gh_token=${OMB_INSTALL_GITHUB_TOKEN:-}+ case "$gh_token" in *[!A-Za-z0-9_]*) gh_token="" ;; esac+ if [ -n "$gh_token" ]; then+ gh_tag=$(printf 'header = "Authorization: Bearer %s"\n' "$gh_token" | curl -K - -fsS --max-time 15 "$RELEASES_URL" 2>/dev/null | release_tag)+ if [ -n "$gh_tag" ]; then+ printf '%s\n' "$gh_tag"+ return 0+ fi+ fi+ curl -fsS --max-time 15 "$RELEASES_URL" 2>/dev/null | release_tag}# The stable channel when it is published, else the newest release. Never `latest`, which follows every commit.diff --git a/deploy/update.sh b/deploy/update.shindex 8adb139fb5..3a274e7a47 100755--- a/deploy/update.sh+++ b/deploy/update.sh@@ -551,18 +551,26 @@ last_words() { compose logs --no-color --no-log-prefix --tail 40 "$SERVICE" 2>/d# The server runs image $1, answers /api/health three times in a row, and (with $2) says it is version $2. Sets WHY.wait_healthy() {- local want=$1 version=${2:-} deadline=$(($(date +%s) + WAIT_S)) streak=0 cid state status restarts image said+ local want=$1 version=${2:-} deadline=$(($(date +%s) + WAIT_S)) streak=0 cid last_cid="" state status restarts image saidWHY=""while :; docid=$(container)# A Podman install's container goes with the process it ran (systemd starts a new one): gone is stopped.if [ -z "$cid" ] && [ -n "$UNIT" ]; then WHY="it stopped as it started ($(last_words))"; return 1; fiif [ -z "$cid" ]; then WHY="its container is gone"; return 1; fi+ # Three answers in a row count only from one container: a new one (systemd starts another) begins the count again.+ if [ "$cid" != "$last_cid" ]; then streak=0; last_cid=$cid; fistate=$(inspect '{{.State.Status}} {{.RestartCount}} {{.Image}}' "$cid")# Gone between the two reads: Podman removes a container that exits as it starts, so the next read says what became# of it. An empty answer is never taken for a container on another image.if [ -z "$state" ]; then- if [ "$(date +%s)" -ge "$deadline" ]; then WHY="its container is gone"; return 1; fi+ streak=0+ if [ "$(date +%s)" -ge "$deadline" ]; then+ if [ -n "$UNIT" ]; then WHY="it stopped as it started ($(last_words))"+ elif [ -n "$(container)" ]; then WHY="its container could not be inspected ($STORE answered nothing about $cid)"+ else WHY="its container is gone"; fi+ return 1+ fisleep "$POLL_S"continuefidiff --git a/scripts/server-installer.test.ts b/scripts/server-installer.test.tsindex d1975818db..9bba103c1c 100644--- a/scripts/server-installer.test.ts+++ b/scripts/server-installer.test.ts@@ -62,7 +62,7 @@ esac`,curl: `echo "curl $*" >> "$FAKE_LOG"blocked() { case " \${FAKE_BLOCKED:-} " in *" $1 "*) return 0 ;; esac; return 1; }case "$*" in- *"-K -"*releases/latest*) cat >> "$FAKE_LOG.stdin"; printf '{\\n "tag_name": "%s",\\n "name": "x"\\n}\\n' "$FAKE_RELEASE" ;;+ *"-K -"*releases/latest*) cat >> "$FAKE_LOG.stdin"; [ -z "\${FAKE_TOKEN_REFUSED:-}" ] || exit 22; printf '{\\n "tag_name": "%s",\\n "name": "x"\\n}\\n' "$FAKE_RELEASE" ;;*"-K - -fsSL"*) cat >> "$FAKE_LOG.stdin"case "$*" in*/manifests/sha256:*) printf '%s' "\${FAKE_MANIFEST:-}" ;;@@ -359,16 +359,33 @@ describe.skipIf(!posix)("deploy/install.sh", () => {it("reads the newest release without a token, and sends one only when a test run's OMB_INSTALL_GITHUB_TOKEN gives it, never on a command line", () => {const stdin = (dir: string) => (existsSync(join(dir, "calls.log.stdin")) ? readFileSync(join(dir, "calls.log.stdin"), "utf8") : "");+ const lookups = (result: { calls: string[] }) => result.calls.filter((call) => call.includes("releases/latest"));+ const PLAIN = "curl -fsS --max-time 15 https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest";+ const WITH_TOKEN = "curl -K - -fsS --max-time 15 https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest";const plain = run(["--check", "--domain", "maus.example.com"]);expect(plain.stdout).toContain(" ok version: v0.1.151, the newest release");- expect(plain.calls.filter((call) => call.includes("releases/latest"))).toEqual(["curl -fsS --max-time 15 https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest"]);- expect(stdin(plain.dir)).not.toContain("api-token");+ expect(lookups(plain)).toEqual([PLAIN]);+ // Only the registry's pull token goes to curl's standard input.+ expect(stdin(plain.dir).split("\n").filter((line) => line.includes("Authorization") && !line.includes(TOKEN))).toEqual([]);- const token = run(["--check", "--domain", "maus.example.com"], { env: { OMB_INSTALL_GITHUB_TOKEN: "api-token-123" } });+ const token = run(["--check", "--domain", "maus.example.com"], { env: { OMB_INSTALL_GITHUB_TOKEN: "ghs_apiToken123" } });expect(token.stdout).toContain(" ok version: v0.1.151, the newest release");- expect(token.calls.filter((call) => call.includes("releases/latest"))).toEqual(["curl -K - -fsS --max-time 15 https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest"]);- expect(token.calls.some((call) => call.includes("api-token-123"))).toBe(false);- expect(stdin(token.dir)).toContain('header = "Authorization: Bearer api-token-123"\n');+ expect(lookups(token)).toEqual([WITH_TOKEN]);+ expect(token.calls.some((call) => call.includes("ghs_apiToken123"))).toBe(false);+ expect(stdin(token.dir)).toContain('header = "Authorization: Bearer ghs_apiToken123"\n');++ // A token GitHub refuses: the lookup is made once more without it, and the version is found.+ const refused = run(["--check", "--domain", "maus.example.com"], { env: { OMB_INSTALL_GITHUB_TOKEN: "ghs_expired", FAKE_TOKEN_REFUSED: "1" } });+ expect(refused.stdout).toContain(" ok version: v0.1.151, the newest release");+ expect(refused.fixes).toEqual([]);+ expect(lookups(refused)).toEqual([WITH_TOKEN, PLAIN]);+ });++ it.each(['abc"def', "abc def", "abc\ndef", "abc\\def", "abc-def"])("never puts a token with anything but letters, digits and _ into curl's config (%j)", (bad) => {+ const result = run(["--check", "--domain", "maus.example.com"], { env: { OMB_INSTALL_GITHUB_TOKEN: bad } });+ expect(result.stdout).toContain(" ok version: v0.1.151, the newest release");+ expect(result.calls.filter((call) => call.includes("releases/latest"))).toEqual(["curl -fsS --max-time 15 https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest"]);+ expect(existsSync(join(result.dir, "calls.log.stdin")) ? readFileSync(join(result.dir, "calls.log.stdin"), "utf8") : "").not.toContain(bad);});it("uses the stable channel once it is published, and never the latest tag", () => {diff --git a/scripts/testing/deploy-update-podman.test.ts b/scripts/testing/deploy-update-podman.test.tsindex d6ecb32e61..0cbf75ca59 100644--- a/scripts/testing/deploy-update-podman.test.ts+++ b/scripts/testing/deploy-update-podman.test.ts@@ -166,6 +166,14 @@ describe.skipIf(!posix)("deploy/update.sh on a Podman install", () => {expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });});+ it("says why in the server's own words when the new version's container stays listed but never answers a read", () => {+ const box = install({ behaviour: "uninspectable", lastWords: "broken on purpose" });+ const failed = box.run([], { OMB_UPDATE_WAIT_S: "2" });+ expect(failed.status, failed.stdout + failed.stderr).toBe(1);+ expect(failed.said.at(-3)).toBe("The update to 0.1.151 did not work: it stopped as it started (broken on purpose).");+ expect(box.unit()).toBe(unitText(OLD.refs[1]!));+ });+it("names systemctl and journalctl, never docker compose, when a person has to step in", () => {// The data cannot be put back: the way to run the server on the data as it is.const restore = install({ behaviour: "silent" }, { failRestore: true });diff --git a/scripts/testing/deploy-update.test.ts b/scripts/testing/deploy-update.test.tsindex e28e6e1f0d..251be6a656 100644--- a/scripts/testing/deploy-update.test.ts+++ b/scripts/testing/deploy-update.test.ts@@ -165,6 +165,29 @@ describe.skipIf(!posix)("deploy/update.sh", () => {expect(box.journal()).toBe(false);});+ it("reads a container's state again when a read answers nothing, and the update goes on", () => {+ const box = install({ behaviour: "inspect-fails-once" });+ const done = box.run();+ expect(done.status, done.stdout + done.stderr).toBe(0);+ expect(done.said).toContain("Updated from 0.1.150 to 0.1.151.");+ });++ it("says a container that never answers a read could not be inspected, never that it is gone", () => {+ const box = install({ behaviour: "uninspectable" });+ const failed = box.run([], { env: { OMB_UPDATE_WAIT_S: "2" } });+ expect(failed.status).toBe(1);+ expect(failed.said.at(-3)).toMatch(/^The update to 0\.1\.151 did not work: its container could not be inspected \(Docker answered nothing about omb-\d+\)\.$/);+ expect(failed.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ });++ it("counts three answers in a row only from one container", () => {+ // Each read finds another container that answers: no one of them has answered three times.+ const box = install({ behaviour: "replaced" });+ const failed = box.run([], { env: { OMB_UPDATE_WAIT_S: "2" } });+ expect(failed.status).toBe(1);+ expect(failed.said.at(-3)).toBe("The update to 0.1.151 did not work: it did not answer within 2 seconds.");+ });+it("says why in the server's own last words when the new version stops as it starts", () => {const box = install({ behaviour: "crashes", lastWords: "This data was written by a newer MausBot." });const failed = box.run();diff --git a/scripts/testing/fake-compose-docker.mjs b/scripts/testing/fake-compose-docker.mjsindex 44acd809ab..0cfcf17553 100644--- a/scripts/testing/fake-compose-docker.mjs+++ b/scripts/testing/fake-compose-docker.mjs@@ -46,6 +46,11 @@ function composeUp() {// `exits`: it stops as it starts, and Podman removes the container (--rm): it is listed once, then gone before anyone// inspects it. Its unit's log keeps its last words.if (wanted.behaviour === "exits") Object.assign(state.containers.omb, { status: "exited", vanishes: true });+ // `uninspectable`: listed, but its state never reads; `inspect-fails-once`: its first read answers nothing;+ // `replaced`: a new container (another id) at every read, each one answering.+ if (wanted.behaviour === "uninspectable") state.containers.omb.inspectFails = 1e9; // (JSON has no Infinity)+ if (wanted.behaviour === "inspect-fails-once") state.containers.omb.inspectFails = 1;+ if (wanted.behaviour === "replaced") state.containers.omb.replaced = true;state.lastImage = wanted.id;state.containers.caddy = { id: `caddy-${state.serial}`, status: wanted.behaviour === "no-caddy" ? "exited" : "running" };// A server that starts writes to its data, as a new version's migrations do.@@ -59,6 +64,7 @@ function compose(rest) {if (verb === "config") return out(`services:\n omb:\n image: ${composeImage()}`);if (verb === "ps" && more.includes("-aq")) {if (omb?.vanishes) delete state.containers.omb;+ if (omb?.replaced) omb.id = `omb-${++state.serial}`;return omb ? out(omb.id) : undefined;}if (verb === "ps") return Object.entries(state.containers).filter(([, container]) => container?.status === "running").forEach(([name]) => out(name));@@ -112,7 +118,13 @@ function inspect(format, target) {if (!omb || omb.id !== target) fail(`No such object: ${target}`);if (format === "{{.Image}}") return out(omb.image);if (format === "{{.State.Running}}") return out(String(omb.status === "running"));- if (format === "{{.State.Status}} {{.RestartCount}} {{.Image}}") return out(`${omb.status} ${omb.restarts} ${omb.image}`);+ if (format === "{{.State.Status}} {{.RestartCount}} {{.Image}}") {+ if (omb.inspectFails > 0) {+ omb.inspectFails -= 1;+ fail(`Error: No such object: ${target}`);+ }+ return out(`${omb.status} ${omb.restarts} ${omb.image}`);+ }// Where /data is on the host: the volume's folder here (update-runner.sh reads its owner).if (format.includes(".Mounts") && !format.includes(".Name")) return out(volume(state.dataVolume));if (format.includes(".Mounts")) return out(state.dataVolume);diff --git a/server/checkpoints-perf.test.ts b/server/checkpoints-perf.test.tsindex 9ab216ca94..d39fc4ec04 100644--- a/server/checkpoints-perf.test.ts+++ b/server/checkpoints-perf.test.ts@@ -404,6 +404,77 @@ describe("incremental shadow index", () => {expect(snapshotHashes(bot, cwd)).toEqual([stopped]);});+ /** A collection made due by its loose objects (only while `due()` says so), held by a pinned snapshot and then released. */+ async function dueCollection(bot: string, cwd: string, label: string, due: () => boolean) {+ hooks.inject = (args) => {+ if (args[0] === "count-objects" && due()) return { stdout: countObjects({ count: 7000 }) };+ return gcInject?.(args);+ };+ writeFileSync(join(cwd, "a.txt"), label);+ await snapshot(bot, cwd, label, undefined, { pin: `dispatch-${label}` });+ await drain(bot, cwd);+ await release(bot, cwd, `dispatch-${label}`);+ await drain(bot, cwd);+ }+ let gcInject: ((args: string[]) => Injected | undefined) | undefined;+ afterEach(() => { gcInject = undefined; });+ const gitRefuses = (): Injected => ({ error: Object.assign(new Error("Command failed: git gc"), { code: 128 }), stderr: "fatal: gc is already running on machine 'fixture' pid 4242" });++ it("runs a collection whose git fails once again at once, and it succeeds", async () => {+ const { bot, cwd } = workspace();+ writeFileSync(join(cwd, "a.txt"), "one");+ await snapshot(bot, cwd, "first");+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ let gcs = 0;+ gcInject = (args) => (args[0] === "gc" && (gcs += 1) === 1 ? gitRefuses() : undefined);+ await dueCollection(bot, cwd, "due", () => gcs === 0);+ expect(gcs).toBe(2);+ expect(warn).not.toHaveBeenCalled();+ // Collected: the next commit owes nothing.+ hooks.calls = [];+ await dueCollection(bot, cwd, "after", () => false);+ expect(subcommands()).not.toContain("gc");+ });++ it("keeps a collection that keeps failing owed, tries it again on later commits with growing gaps, never in a loop, and says git's reason", async () => {+ const { bot, cwd } = workspace();+ writeFileSync(join(cwd, "a.txt"), "one");+ await snapshot(bot, cwd, "first");+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ let gcs = 0;+ gcInject = (args) => (args[0] === "gc" ? ((gcs += 1), gitRefuses()) : undefined);+ await dueCollection(bot, cwd, "due", () => gcs === 0);+ // The try and one more after clearing locks; then nothing until a later commit.+ expect(gcs).toBe(2);+ expect(warn).toHaveBeenCalledTimes(1);+ expect(String(warn.mock.calls[0]![0])).toContain("fatal: gc is already running on machine 'fixture' pid 4242");+ await drain(bot, cwd);+ expect(gcs).toBe(2);+ // Owed after one failure: the next commit queues it again.+ await dueCollection(bot, cwd, "c1", () => false);+ expect(gcs).toBe(4);+ // After two in a row: two more commits.+ await dueCollection(bot, cwd, "c2", () => false);+ expect(gcs).toBe(4);+ await dueCollection(bot, cwd, "c3", () => false);+ expect(gcs).toBe(6);+ // After three: four more.+ for (const label of ["c4", "c5", "c6"]) await dueCollection(bot, cwd, label, () => false);+ expect(gcs).toBe(6);+ await dueCollection(bot, cwd, "c7", () => false);+ expect(gcs).toBe(8);+ expect(warn).toHaveBeenCalledTimes(4);+ // Once git works again the collection runs, and nothing is owed after it.+ gcInject = undefined;+ for (const label of ["c8", "c9", "c10", "c11", "c12", "c13", "c14"]) await dueCollection(bot, cwd, label, () => false);+ hooks.calls = [];+ await dueCollection(bot, cwd, "c15", () => false);+ expect(subcommands().filter((command) => command === "gc")).toHaveLength(1);+ hooks.calls = [];+ await dueCollection(bot, cwd, "c16", () => false);+ expect(subcommands()).not.toContain("gc");+ });+it.skipIf(process.platform === "win32")("stops a running collection for a new turn's snapshot, and runs it again behind that turn", async () => {const { bot, cwd } = workspace();writeFileSync(join(cwd, "a.txt"), "one");diff --git a/server/checkpoints.ts b/server/checkpoints.tsindex 205dc68595..158ca9bca2 100644--- a/server/checkpoints.ts+++ b/server/checkpoints.ts@@ -675,6 +675,14 @@ const commitsSinceGc = new Map<string, number>();/** Packs grow between collections because `git add` writes files over core.bigFileThreshold straight into packs. */const packBaselineKib = new Map<string, number>();+/** A collection that failed by itself (not stopped to make way): owed, with how many failed in a row. The next snapshot+ * that adds a commit queues it again, after 1, 2, 4… up to GC_EVERY_COMMITS commits, so one that keeps failing costs+ * a try now and then, never one per turn. A collection decided due resets the counts above; this keeps it owed. */+const owedCollections = new Map<string, number>();++/** The pack baseline a due collection set aside, put back when that collection fails. */+const baselineBeforeCollection = new Map<string, number | undefined>();+/** Held until that turn's settled diff is queued or its pin is released, whichever comes first. */const pendingCollections = new Map<string, (stop: AbortController) => Promise<void>>();@@ -708,7 +716,9 @@ async function collectionDue(shadow: string, result: CommitResult, cwd: string,if (!result.advanced && !freed) return false;const commits = (commitsSinceGc.get(shadow) ?? 0) + (result.advanced ? 1 : 0);commitsSinceGc.set(shadow, commits);- let due = freed || commits >= GC_EVERY_COMMITS;+ const failed = owedCollections.get(shadow);+ const owed = failed !== undefined && commits >= Math.min(GC_EVERY_COMMITS, 2 ** (failed - 1));+ let due = freed || owed || commits >= GC_EVERY_COMMITS;if (!due) {const counted = await runGit(["count-objects", "-v"], cwd, env).catch(() => "");if (counted !== "") {@@ -721,6 +731,7 @@ async function collectionDue(shadow: string, result: CommitResult, cwd: string,}if (due) {commitsSinceGc.set(shadow, 0);+ if (!baselineBeforeCollection.has(shadow)) baselineBeforeCollection.set(shadow, packBaselineKib.get(shadow));packBaselineKib.delete(shadow);}return due;@@ -733,14 +744,33 @@ async function collectObsolete(shadow: string, cwd: string, env: NodeJS.ProcessEconst signal = process.platform === "win32" ? undefined : stop.signal;const marker = join(shadow, ".git", COLLECTING);const before = Math.floor(Date.now() / 1000);- try {- writeFileSync(marker, String(before), { mode: 0o600 });+ const collect = async () => {await runGit(["reflog", "expire", "--expire=now", "--all"], cwd, env, signal);stop.signal.throwIfAborted();await runGit(["gc", `--prune=${before}`, "--quiet"], cwd, env, signal);- } catch {- if (!stop.signal.aborted) console.warn("checkpoint cleanup deferred; the latest snapshot is preserved");- else if (!pendingCollections.has(shadow)) pendingCollections.set(shadow, (again) => collectObsolete(shadow, cwd, env, again));+ };+ try {+ writeFileSync(marker, String(before), { mode: 0o600 });+ // Once more, without whatever lock a git stopped by force left behind; a git that ran out of time is not tried again.+ await collect().catch(async (e: unknown) => {+ if (e instanceof GitTimeoutError || stop.signal.aborted) throw e;+ await clearStaleLocks(shadow, 0);+ stop.signal.throwIfAborted();+ await collect();+ });+ owedCollections.delete(shadow);+ baselineBeforeCollection.delete(shadow);+ } catch (e) {+ if (stop.signal.aborted) {+ if (!pendingCollections.has(shadow)) pendingCollections.set(shadow, (again) => collectObsolete(shadow, cwd, env, again));+ return;+ }+ // Still owed: a later snapshot queues it again, and the growth it was due for still counts.+ owedCollections.set(shadow, (owedCollections.get(shadow) ?? 0) + 1);+ const baseline = baselineBeforeCollection.get(shadow);+ baselineBeforeCollection.delete(shadow);+ if (baseline !== undefined && !packBaselineKib.has(shadow)) packBaselineKib.set(shadow, baseline);+ console.warn(`checkpoint cleanup deferred; the latest snapshot is preserved: ${e instanceof Error ? e.message : String(e)}`);} finally {rmSync(marker, { force: true });}diff --git a/server/digest.e2e.test.ts b/server/digest.e2e.test.tsindex 5ed636a3f6..08d05de14d 100644--- a/server/digest.e2e.test.ts+++ b/server/digest.e2e.test.ts@@ -177,7 +177,9 @@ posixOnly("work digest e2e (every fake engine)", () => {// the staged folder in the shadow itself, not for the first index that appears (the draft's, before the rename).const shadow = () => (existsSync(shadows) ? readdirSync(shadows) : []).filter((name) => !name.endsWith(".new")).map((name) => join(shadows, name, ".git")).find((dir) => existsSync(join(dir, "index")));const shadowGit = (...args: string[]) => execFileSync("git", args, { encoding: "utf8", env: { ...process.env, GIT_DIR: shadow()! } }).trim();- await waitFor(async () => shadow() !== undefined && shadowGit("ls-files") !== "", "the project to be read ahead of the first message");+ // The shadow can still be moving into place as it is read: a git that finds no repository there is "not yet".+ const staged = () => { try { return shadowGit("ls-files") !== ""; } catch { return false; } };+ await waitFor(async () => shadow() !== undefined && staged(), "the project to be read ahead of the first message");expect(shadowGit("ls-files")).toBe("README.md");expect(shadowGit("log", "--format=%s")).toBe("checkpoint base");diff --git a/server/thread-aware-bots.e2e.test.ts b/server/thread-aware-bots.e2e.test.tsindex be2dd5b4ed..4f9e0e72a9 100644--- a/server/thread-aware-bots.e2e.test.ts+++ b/server/thread-aware-bots.e2e.test.ts@@ -916,6 +916,9 @@ describe("a Chief of Staff tidying its team (MOCA-202)", () => {await expect.poll(() => handoffs().find(node => node.id === child.id)?.status, { timeout: 15_000 }).toBe("completed");await expect.poll(async () => (await taskOf(qa.id, child.threadId)).closedBy, { timeout: 15_000 }).toMatchObject({ botId: pm.id, name: "Parker" });+ // The settled handoff wakes Parker once more on this thread. Between the first turn's end and that wake's start Parker+ // is not busy, so a message sent then queues behind the wake: wait until the wake has started, then until it ends.+ await expect.poll(() => promptsOf(pm.threadId).some((prompt) => JSON.stringify(prompt).includes("Your downstream room requests have settled.")), { timeout: 15_000 }).toBe(true);token = await heldTurn(pm, "Close the completed QA task.");const closed = await close(opened.body.threadId);expect(closed.status).toBe(200);diff --git a/shared/app-frame/jsx-page.test.ts b/shared/app-frame/jsx-page.test.tsindex 479ca9825c..d513801d12 100644--- a/shared/app-frame/jsx-page.test.ts+++ b/shared/app-frame/jsx-page.test.ts@@ -137,6 +137,9 @@ export default function Page() { const theme = useTheme(); return <div><p id="th// The chart is drawn in an effect after the render: wait for it, not for a fixed time.await vi.waitFor(() => expect(fakeEcharts.made).toHaveLength(1), { timeout: 10_000 });expect(fakeEcharts.made[0]).toMatchObject({ theme: "dark", options: [{ backgroundColor: "transparent", series: [{ type: "bar", data: [1, 2] }] }] });+ // An error in the chart's effect shows only after it ran.+ expect(problems).toEqual([]);+ expect(document.querySelector("[data-page-problem]")).toBeNull();});it("runs a published page's transpiled code without loading the compiler", async () => {