From b6ddd602b88f6ee5618492cf8bad7d305e8a3516 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:16:52 +0000 Subject: [PATCH] upstream agy-cli 0.1.178 (magpie-community/plugins@74cbf719b10e1605630dfaa82c2f8a189e577de9) --- agy-cli.test.mjs | 1 + index.mjs | 169 ++++++++++++++++++++++++---- model-ids.mjs | 80 +++++++------ package.json | 2 +- test/catalog.mjs | 90 +++++++++++++++ test/rebase-resume.mjs | 35 ++++++ test/usage.mjs | 52 ++++++++- test/windows-nc.mjs | 23 ++++ test/workspace-handoff.mjs | 223 +++++++++++++++++++++++++++++++++++++ 9 files changed, 613 insertions(+), 62 deletions(-) create mode 100644 test/workspace-handoff.mjs diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index 7386ab9..bb2fa11 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -62,6 +62,7 @@ for (const [name, mocks] of [ ["claude-code-sessions.mjs", false], ["media-input.mjs", false], ["default-agent.mjs", false], + ["workspace-handoff.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests diff --git a/index.mjs b/index.mjs index e0c65c5..c69ee31 100644 --- a/index.mjs +++ b/index.mjs @@ -2539,6 +2539,8 @@ class Turn { if (type === "tool_call_update" && update.status && update.status !== "in_progress" && update.status !== "pending") { const wasActive = this.activeAcpToolCalls.delete(id) + // a call the gate couldn't start: the next one finds the folder again + if (update.status === "failed") this.proc.keepWorkspace() if (wasActive && update.status === "failed" && typeof update.rawOutput === "string" && update.rawOutput.startsWith("tool call denied by pre-tool hook: ")) { this.proc.deniedHooks++ @@ -2783,14 +2785,24 @@ class Proc { await ensureControlServer() const bin = await ensureShimDir() sessions.set(this.token, this) + this.workspaceOwner = randomUUID() if (this.workspace) { // agy's prompt cache follows the folder it runs in: a session resumed // anywhere else replays its whole history uncached. It // starts again in its own folder, made again if it was removed. await workspaceRemovals.get(this.workspace)?.catch(() => {}) - await fs.promises.mkdir(this.workspace, { recursive: true, mode: 0o700 }) - } else { + if (!await claimWorkspace(this.workspace, this.workspaceOwner)) { + // A consumed rebase entry hands over cleanup once its agy has exited. + // Keep that responsibility when this agy needs a different directory. + if (this.resumeFrom?.rebase && this.resumeFrom.workspaceOwner) { + this.abandonedWorkspace = { path: this.workspace, owner: this.resumeFrom.workspaceOwner } + } + this.workspace = null + } + } + if (!this.workspace) { this.workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-bridge-")) + fs.writeFileSync(path.join(this.workspace, WORKSPACE_OWNER_FILE), this.workspaceOwner, { mode: 0o600 }) } // Opt-in: AGY_BRIDGE_ALLOW_AGY_TOOLS=1 hands every session/request_permission // to agy's own --dangerously-skip-permissions, so agy's built-in tools (shell, @@ -2802,6 +2814,7 @@ class Proc { const home = currentHome() const geminiDir = own.dir || path.join(home || os.homedir(), ".gemini") const hookEnv = await writeDefaultAgentFiles(this.workspace, { ...bridgeAgentFiles(this.media, allowAgyTools), geminiDir }) + this.workspaceFiles = workspaceSnapshot(this.workspace) this.logPath = path.join(this.workspace, "agy-acp.log") const args = [ @@ -2866,6 +2879,31 @@ class Proc { }) } + // agy starts the tool gate in the folder that holds hooks.json, by path, + // for every tool call: with that folder gone, the hook can't start + // ("fork/exec /bin/sh: no such file or directory", "The directory name + // is invalid." on Windows) and every call fails. Another host still on an + // older plugin, or a temp cleaner, can remove it from under a live agy; + // it is made again before each prompt and each step's results. + keepWorkspace() { + if (!this.workspace || !this.workspaceFiles || this.stopping || this.dead) return + // the claim only on a folder that was gone whole: one there names + // whichever agy claimed it since + const gone = !fs.existsSync(this.workspace) + let restored = 0 + for (const [name, bytes] of this.workspaceFiles) { + const file = path.join(this.workspace, name) + if (name === WORKSPACE_OWNER_FILE && !gone) continue + if (fs.existsSync(file)) continue + try { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }) + fs.writeFileSync(file, bytes, { mode: 0o600, flag: "wx" }) + restored++ + } catch {} + } + if (restored) logBridgeEvent(this, this.turn, "workspace_restored", "missing", {}, { files: restored }) + } + async #withStartTimeout(step) { // a spare that died while it waited if (this.dead) throw new Error(`agy failed before the ACP session started: ${this.deadError?.message || "agy exited"}`) @@ -3308,6 +3346,7 @@ class Proc { async steerInSession(turn, results, history) { if (this.dead || this.stopping || this.retiring || this.turn !== turn || turn.steering || turn.done || turn.finalized || !Array.isArray(history)) return false + this.keepWorkspace() // agy offloads an image in an MCP result to a file the model can't open, // so the call is answered with its text and the image goes in the // steer's prompt (withoutAnswered keeps it there). @@ -3356,6 +3395,7 @@ class Proc { async #runTurn(turn, content, model, selection, seeds = []) { let logWatch try { + this.keepWorkspace() turn.arm() logWatch = turn.logWatch = this.#watchTurnLog(turn) if (model) await this.#setModel(model, selection) @@ -3396,6 +3436,7 @@ class Proc { return } turn.arm() + this.keepWorkspace() this.hasSentFirstTurn = true // the session is about to hold this turn's messages: a restart from // here resumes at them (parkStep), never at the turn before @@ -3896,6 +3937,7 @@ class Proc { const turn = this.turn if (!turn || turn.finalized) throw new BusyError("agy bridge: no response is waiting for these tool results") turn.touchClient() + this.keepWorkspace() let delivered = 0 for (const { call, result, rawKey } of this.validateResults(results).values()) { clearTimeout(call.deadline) @@ -4129,36 +4171,108 @@ class Proc { // the folder never goes from under an agy that resumed in it. if (![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) { const { convKey, sessionId, workspace } = this - try { - withStateLock(sessionStateFile(), () => { - if (!readStateFile().some((entry) => entry?.key === convKey && entry.sessionId === sessionId && entry.rebase)) { - // taken by another host: never written back from this one's copy - if (parked.get(convKey)?.sessionId === sessionId) parked.delete(convKey) - return - } - fs.rmSync(workspace, { recursive: true, force: true }) - }) - } catch {} + await releaseWorkspace(workspace, this.workspaceOwner, () => { + if (readStateFile().some((entry) => entry?.key === convKey && entry.sessionId === sessionId && entry.rebase)) return true + // Taken by another host. Never write it back from this one's copy. + if (parked.get(convKey)?.sessionId === sessionId) parked.delete(convKey) + return false + }) } } else if (this.workspace && ![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) { - const removal = this.#removeWorkspace() + const removal = releaseWorkspace(this.workspace, this.workspaceOwner) workspaceRemovals.set(this.workspace, removal) await removal if (workspaceRemovals.get(this.workspace) === removal) workspaceRemovals.delete(this.workspace) } + if (this.abandonedWorkspace) { + const { path, owner } = this.abandonedWorkspace + await releaseWorkspace(path, owner) + } allProcs.delete(this) } +} - async #removeWorkspace() { - for (let attempt = 0; attempt < 4; attempt++) { - try { - await fs.promises.rm(this.workspace, { recursive: true, force: true }) - break - } catch (error) { - if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break - await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))) +// A session's folder names the agy that last started in it, the bridge +// process by its workspace owner ID. Another host resumes a parked +// session in the same folder (agy's prompt cache follows it) while the +// host that parked it may still be stopping its own agy there: magpie keeps +// a host it replaced (a plugin update, a recycle) answering its calls for +// up to ten minutes. That host removed the folder when its agy stopped, +// from under the new host's agy, whose every tool call then failed: agy +// starts the tool gate there (keepWorkspace). A folder is now removed only +// by the agy that claimed it last, checked and moved aside under the state +// file's lock, which a claim holds too. +const WORKSPACE_OWNER_FILE = ".magpie-agy-owner" + +async function claimWorkspace(workspace, owner) { + for (let attempt = 0; attempt < 4; attempt++) { + const claimed = withStateLock(sessionStateFile(), () => { + fs.mkdirSync(workspace, { recursive: true, mode: 0o700 }) + fs.writeFileSync(path.join(workspace, WORKSPACE_OWNER_FILE), owner, { mode: 0o600 }) + return true + }) + if (claimed) return true + if (attempt < 3) await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))) + } + // Leave the cached directory alone if its ownership could not be transferred. + // The ACP session can still resume in a new workspace. + return false +} + +// What #spawn wrote, for keepWorkspace to write again. +function workspaceSnapshot(workspace) { + const files = new Map() + for (const name of [WORKSPACE_OWNER_FILE, "AGENTS.md", path.join(".agents", "skills.json"), + path.join(".agents", "hooks.json"), path.join(".agents", "tool-gate.cmd")]) { + try { files.set(name, fs.readFileSync(path.join(workspace, name))) } catch {} + } + return files +} + +// Under the state file's lock: { aside } is the folder, moved out of the +// way to be removed, when owner claimed it last; { kept } when another agy +// did (or an older bridge's, which names none); { busy } when Windows +// still holds it for an agy that just ended; {} when it is gone already. +function takeWorkspaceLocked(workspace, owner) { + let held + try { + held = fs.readFileSync(path.join(workspace, WORKSPACE_OWNER_FILE), "utf8") + } catch (error) { + return error?.code === "ENOENT" && !fs.existsSync(workspace) ? {} : { kept: true } + } + if (!owner || held !== owner) return { kept: true } + const aside = `${workspace}.gone-${randomUUID().slice(0, 8)}` + try { + fs.renameSync(workspace, aside) + } catch (error) { + return ["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"].includes(error?.code) ? { busy: true } : {} + } + return { aside } +} + +async function releaseWorkspace(workspace, owner, shouldRelease = () => true) { + for (let attempt = 0; attempt < 4; attempt++) { + const taken = withStateLock(sessionStateFile(), () => shouldRelease() ? takeWorkspaceLocked(workspace, owner) : { kept: true }) + if (taken && !taken.busy) { + if (taken.aside) await fs.promises.rm(taken.aside, { recursive: true, force: true, maxRetries: 3 }).catch(() => {}) + return + } + // the lock taken elsewhere, or the folder still held + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))) + } +} + +function releaseWorkspaceSync(workspace, owner, attempts) { + const wait = new Int32Array(new SharedArrayBuffer(4)) + for (let attempt = 0; attempt < attempts; attempt++) { + const taken = withStateLock(sessionStateFile(), () => takeWorkspaceLocked(workspace, owner)) + if (taken && !taken.busy) { + if (taken.aside) { + try { fs.rmSync(taken.aside, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }) } catch {} } + return } + Atomics.wait(wait, 0, 0, 50) } } @@ -4595,6 +4709,7 @@ function writeParked(proc, midTurn, rebase = null) { rebase: true, count: rebase.rows.length, beyond: !!rebase.beyond, requestHash: digest(historyKey(rebase.messages)), requestCount: rebase.messages.length, stopping: true, holder: { pid: proc.child?.pid ?? null, host: HOST_ID }, + workspaceOwner: proc.workspaceOwner, } : midTurn ? { midTurn: true, count: proc.expectedMessages.length } : {}, at: Date.now(), @@ -4817,6 +4932,7 @@ function takeParked(convKey, opts, miss = {}) { return { sessionId: entry.sessionId, expectedMessages: prefix, workspace, rebase: true, beyond: entry.beyond !== false, holder: entry.holder ?? null, + workspaceOwner: entry.workspaceOwner, } } // A step parked mid-turn is taken only by its results: the request goes @@ -10046,6 +10162,7 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a let flattened = proc.pendingFlattenedTurn proc.pendingFlattenedTurn = null const isFirstTurn = !proc.hasSentFirstTurn + proc.keepWorkspace() // the prompt names each video or audio by its file; the session is still // matched by body.messages const messages = body.messages.map((message) => stageMedia(message, proc.workspace)) @@ -10353,6 +10470,10 @@ function readUsageOf(home, email = "") { } await keepOwn(email, stored) } + // Load this account's saved catalog rows before reading usage so its + // windows map its own models even when usage runs before models(). + const agy = findAgy() + if (agy) useAgyPath(agy) const result = await read() if (email && !result.error && toldNotHeld.delete(email.toLowerCase()) && result.signIn === "kept") { return { ...result, signIn: "renewed" } @@ -11072,8 +11193,10 @@ function reapOnExit() { } for (const proc of allProcs) { // A process that just ended can hold its cwd (the workspace) for a moment. - if (proc.workspace) { - try { fs.rmSync(proc.workspace, { recursive: true, force: true, maxRetries: windows ? 10 : 0, retryDelay: 50 }) } catch {} + if (proc.workspace) releaseWorkspaceSync(proc.workspace, proc.workspaceOwner, windows ? 10 : 2) + if (proc.abandonedWorkspace) { + const { path, owner } = proc.abandonedWorkspace + releaseWorkspaceSync(path, owner, windows ? 10 : 2) } } if (shimDir && shimDirOwned) { diff --git a/model-ids.mjs b/model-ids.mjs index 5650ce0..2976fc3 100644 --- a/model-ids.mjs +++ b/model-ids.mjs @@ -1,5 +1,9 @@ -// The runtime catalog `agy models` listed, so usage windows can name the ids -// the provider serves (usage.mjs stays import-free of index.mjs). +import { currentHome } from "./account.mjs" + +// The runtime catalog `agy models` listed for each account (keyed by +// currentHome() ?? ""), so usage windows name the ids that account serves +// without one account's refresh overwriting another's (usage.mjs stays +// import-free of index.mjs). // // rows(): [{ id, name, effort? }] — the shape `agy models` parses into // (parseAgyModels), the saved catalog, and FALLBACK_MODELS. @@ -9,15 +13,20 @@ // in it, plus the bare family id itself even when agy lists no variant of // that name (the catalog serves it as its default). -let rows = null -let index = new Map() +const states = new Map() export function storeCatalogRows(list) { - rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id) : null - index = null + const key = currentHome() ?? "" + const rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id) : null + if (!rows) { + states.delete(key) + return + } + states.set(key, { rows, index: null }) } export function catalogRows() { + const rows = states.get(currentHome() ?? "")?.rows return rows ? [...rows] : null } @@ -40,37 +49,38 @@ function listedNames(description) { } export function nameIndex() { - if (index) return index - index = new Map() - if (rows) { - const families = new Map() - const shown = new Map() // family -> its display name - const claims = new Map() // display name -> the families that use it - for (const model of rows) { - const effort = /-(high|medium|low|minimal|xhigh|max)$/i.exec(model.id)?.[1]?.toLowerCase() || "" - const family = effort ? model.id.slice(0, -(effort.length + 1)) : model.id - if (!families.has(family)) families.set(family, new Set()) - families.get(family).add(model.id) - const name = normalizeName(model.name) - if (!name) continue - // the family's name as agy shows it, its effort word left off - if (!shown.has(family)) shown.set(family, stripEffortSuffix(String(model.name).trim().replace(/\s+/g, " "))) - for (const alias of [name, stripEffortSuffix(name)]) { - if (!claims.has(alias)) claims.set(alias, new Set()) - claims.get(alias).add(family) - } - } - for (const [family, ids] of families) { - // the bare id the catalog serves even when agy lists no variant of it - ids.add(family) - } - for (const [name, owners] of claims) { - // one name, two families: no match, rather than whichever came first - if (owners.size !== 1) continue - const [family] = owners - index.set(name, { family, ids: families.get(family), name: shown.get(family) || family }) + const state = states.get(currentHome() ?? "") + if (!state?.rows) return new Map() + if (state.index) return state.index + const index = new Map() + const families = new Map() + const shown = new Map() // family -> its display name + const claims = new Map() // display name -> the families that use it + for (const model of state.rows) { + const effort = /-(high|medium|low|minimal|xhigh|max)$/i.exec(model.id)?.[1]?.toLowerCase() || "" + const family = effort ? model.id.slice(0, -(effort.length + 1)) : model.id + if (!families.has(family)) families.set(family, new Set()) + families.get(family).add(model.id) + const name = normalizeName(model.name) + if (!name) continue + // the family's name as agy shows it, its effort word left off + if (!shown.has(family)) shown.set(family, stripEffortSuffix(String(model.name).trim().replace(/\s+/g, " "))) + for (const alias of [name, stripEffortSuffix(name)]) { + if (!claims.has(alias)) claims.set(alias, new Set()) + claims.get(alias).add(family) } } + for (const [family, ids] of families) { + // the bare id the catalog serves even when agy lists no variant of it + ids.add(family) + } + for (const [name, owners] of claims) { + // one name, two families: no match, rather than whichever came first + if (owners.size !== 1) continue + const [family] = owners + index.set(name, { family, ids: families.get(family), name: shown.get(family) || family }) + } + state.index = index return index } diff --git a/package.json b/package.json index ca291aa..bba5650 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.175", + "version": "0.1.178", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/test/catalog.mjs b/test/catalog.mjs index 1df91a6..2ef7394 100644 --- a/test/catalog.mjs +++ b/test/catalog.mjs @@ -1750,3 +1750,93 @@ test("列表里有 flash-image 档位时,flash 别名仍落到聊天用的 fla } }) }) + +test("each account keeps its own catalogRows for usage windows, including cold-start saved catalogs", async () => { + const shared = fs.mkdtempSync(path.join(os.tmpdir(), "agy-usage-catalog-rows-")) + const ultraRows = [ + ["gemini-4-neon-high", "Gemini 4 Neon (High)"], ["gemini-4-neon-low", "Gemini 4 Neon (Low)"], + ["claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"], ["claude-sonnet-5-5-low", "Claude Sonnet 5.5 (Low)"], + ] + const proRows = [ + ["gemini-4-hydrogen-high", "Gemini 4 Hydrogen (High)"], ["gemini-4-hydrogen-low", "Gemini 4 Hydrogen (Low)"], + ["claude-sonnet-4-6", "Claude Sonnet 4.6"], + ] + const keyring = "go-keyring-base64:" + Buffer.from(JSON.stringify({ + token: { access_token: "ya29.ultra", refresh_token: "1//r", expiry: "0001-01-01T00:00:00Z" }, + auth_method: "consumer", id_token_email: "ultra@example.com", + })).toString("base64") + "\n" + const otherAuth = { type: "oauth", key: "agy", metadata: { agyHome: "otheracct1" } } + const ownAuth = { type: "oauth", key: "agy", metadata: { email: "ultra@example.com" } } + const agy = path.join(shared, process.platform === "win32" ? "agy.exe" : "agy") + fs.writeFileSync(agy, "#!/bin/sh\nexit 99\n", { mode: 0o755 }) + const stateHome = path.join(shared, "state") + const otherToken = path.join(stateHome, "magpie-agy-bridge", "accounts", "otheracct1", ".gemini", "antigravity-cli", "antigravity-oauth-token") + fs.mkdirSync(path.dirname(otherToken), { recursive: true }) + fs.writeFileSync(otherToken, JSON.stringify({ + token: { access_token: "ya29.pro", refresh_token: "1//r", expiry: "0001-01-01T00:00:00Z" }, + auth_method: "consumer", id_token_email: "pro@example.com", + })) + const usageSpawn = (_file, args, opts) => { + if (args[0] === "--version") return { code: 0, stdout: "1.5.19\n" } + if (args[0] !== "-p") return 1 + const isOther = Boolean(opts?.env?.SSH_CONNECTION && /otheracct1$/.test(opts.env.HOME ?? "")) + const groups = isOther + ? [{ + name: "Claude and GPT models", + description: "Models within this group: Claude Sonnet 4.6", + buckets: [{ id: "3p-weekly", name: "Weekly Limit Remaining", window: "weekly", reset_time: "2026-11-22T00:00:00Z", remaining_fraction: 0.7 }], + }] + : [{ + name: "Claude and GPT models", + description: "Models within this group: Claude Sonnet 5.5", + buckets: [{ id: "3p-weekly", name: "Weekly Limit Remaining", window: "weekly", reset_time: "2026-11-22T00:00:00Z", remaining_fraction: 0.4 }], + }] + return { code: 0, stdout: JSON.stringify({ status: "SUCCESS", command: { name: "usage", data: { groups } } }) } + } + const env = { XDG_STATE_HOME: stateHome } + const net = noFetch() + try { + // 1. Live models() on both accounts: refreshing the Pro account must not + // overwrite the Ultra account's catalogRows when reading usage. + await withKit({ + agyPath: agy, env, platform: "darwin", storedSignIn: keyring, + modelsBehavior: { stdout: modelsOutput(ultraRows) }, + offeredModels: (home) => /otheracct1$/.test(home) ? proRows : ultraRows, + onSpawn: usageSpawn, + }, async (kit) => { + await kit.plugin.provider.models() + await warmed(kit) + kit.modelsBehavior = { stdout: modelsOutput(proRows) } + await kit.plugin.provider.models(undefined, { auth: otherAuth }) + await warmed(kit) + + const uUltra = await kit.plugin.auth.usage(async () => ownAuth, {}) + const uPro = await kit.plugin.auth.usage(async () => otherAuth, {}) + assert.equal(uUltra.error, undefined, JSON.stringify(uUltra)) + assert.equal(uPro.error, undefined, JSON.stringify(uPro)) + assert.deepEqual(uUltra.windows.find(w => w.aside)?.models, ["claude-sonnet-5-5", "claude-sonnet-5-5-high", "claude-sonnet-5-5-low"]) + assert.deepEqual(uPro.windows.find(w => w.aside)?.models, ["claude-sonnet-4-6"]) + await settle(kit) + }) + + // 2. Restart with saved models.json: auth.usage called BEFORE models() + // loads each account's saved catalog rows via useAgyPath. + await withKit({ + agyPath: agy, env, platform: "darwin", storedSignIn: keyring, + modelsBehavior: { code: 1, stderr: "not called" }, + onSpawn: usageSpawn, + }, async (kit) => { + const uUltra = await kit.plugin.auth.usage(async () => ownAuth, {}) + const uPro = await kit.plugin.auth.usage(async () => otherAuth, {}) + assert.equal(uUltra.error, undefined, JSON.stringify(uUltra)) + assert.equal(uPro.error, undefined, JSON.stringify(uPro)) + assert.deepEqual(uUltra.windows.find(w => w.aside)?.models, ["claude-sonnet-5-5", "claude-sonnet-5-5-high", "claude-sonnet-5-5-low"]) + assert.deepEqual(uPro.windows.find(w => w.aside)?.models, ["claude-sonnet-4-6"]) + assert.equal(kit.modelsSpawns.length, 0) + await settle(kit) + }) + } finally { + net.restore() + fs.rmSync(shared, { recursive: true, force: true }) + } +}) diff --git a/test/rebase-resume.mjs b/test/rebase-resume.mjs index b3b8869..281c301 100644 --- a/test/rebase-resume.mjs +++ b/test/rebase-resume.mjs @@ -338,6 +338,41 @@ test("the old host does not save a rebase entry another host already took", asyn }) }) +for (const reclaimed of [false, true]) { + test("a rebase fallback cleans up the old workspace only if it was not reclaimed (" + reclaimed + ")", async () => { + await twoHosts({}, async ({ old, fresh, file }) => { + const { body, holder, pending, entry } = await parkedByOld(old, file) + recordPrompts(fresh, { prompts: [] }) + const answer = fresh.request(structuredClone(body)) + const lock = file + ".lock" + let locked = false + try { + await until(() => !stateEntries(file).some((item) => item.key === entry.key)) + fs.writeFileSync(lock, JSON.stringify({ pid: process.pid }), { flag: "wx" }) + locked = true + await holder.release() + await (await pending).text() + assert.equal((await readSse(await answer)).stopReason, "end_turn") + const [{ params }] = methods(fresh, "session/resume") + assert.equal(params.sessionId, entry.sessionId) + assert.notEqual(params.cwd, entry.workspace) + } finally { + if (locked) fs.rmSync(lock, { force: true }) + await holder.release() + } + + const newOwner = path.join(entry.workspace, ".magpie-agy-owner") + if (reclaimed) fs.writeFileSync(newOwner, "another host now owns the directory") + for (const kit of [old, fresh]) { + for (const proc of [...kit.module.__agyTestAllProcs]) await proc.stop() + } + assert.deepEqual(fs.readdirSync(path.dirname(file)).filter(name => /^magpie-agy-bridge-(?!bin)/.test(name)), + reclaimed ? [path.basename(entry.workspace)] : []) + if (reclaimed) assert.equal(fs.readFileSync(newOwner, "utf8"), "another host now owns the directory") + }) + }) +} + test("an old agy that outlives the wait: the new host replays in a new session, never resumes beside it", async () => { await twoHosts({ env: { AGY_BRIDGE_REBASE_HOLDER_WAIT_MS: "200" } }, async ({ old, fresh, file }) => { const capture = captureEvents() diff --git a/test/usage.mjs b/test/usage.mjs index 439e0ee..7ce3237 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -7,7 +7,8 @@ import os from "node:os" import path from "node:path" import { test } from "node:test" import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" -import { modelsInGroup, storeCatalogRows } from "../model-ids.mjs" +import { catalogRows, familiesInGroup, modelsInGroup, storeCatalogRows } from "../model-ids.mjs" +import { inAccount } from "../account.mjs" import { forgetStoredSignIn } from "../signin.mjs" // Live data captured from `agy -p /usage --output-format json` (agy 1.5.9, @@ -170,6 +171,44 @@ test("ids on windows follow the catalog, and names agy adds match nothing until storeCatalogRows(null) }) +test("catalogRows and nameIndex stay isolated per account", () => { + const ultra = [ + { id: "claude-sonnet-5-5-high", name: "Claude Sonnet 5.5 (High)", effort: "high" }, + { id: "claude-sonnet-5-5-low", name: "Claude Sonnet 5.5 (Low)", effort: "low" }, + { id: "gemini-4-neon-high", name: "Gemini 4 Neon (High)", effort: "high" }, + ] + const pro = [ + { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, + { id: "gemini-4-hydrogen-high", name: "Gemini 4 Hydrogen (High)", effort: "high" }, + ] + const claudeGroup = { description: "Models within this group: Claude Sonnet 5.5, Claude Sonnet 4.6" } + const homeA = "/tmp/agy-test-home-a" + const homeB = "/tmp/agy-test-home-b" + try { + storeCatalogRows(ultra) + inAccount(homeA, () => storeCatalogRows(pro)) + inAccount(homeB, () => storeCatalogRows([{ id: "gemini-3.8-flash-high", name: "Gemini 3.8 Flash (High)", effort: "high" }])) + + assert.deepEqual(catalogRows().map(r => r.id), ultra.map(r => r.id)) + assert.deepEqual(modelsInGroup(claudeGroup), ["claude-sonnet-5-5", "claude-sonnet-5-5-high", "claude-sonnet-5-5-low"]) + assert.deepEqual(inAccount(homeA, () => catalogRows().map(r => r.id)), pro.map(r => r.id)) + assert.deepEqual(inAccount(homeA, () => modelsInGroup(claudeGroup)), ["claude-sonnet-4-6"]) + assert.deepEqual(inAccount(homeA, () => familiesInGroup(claudeGroup).map(f => f.id)), ["claude-sonnet-4-6"]) + assert.deepEqual(inAccount(homeB, () => modelsInGroup(claudeGroup)), []) + + // Clearing one account does not clear the others. + inAccount(homeA, () => storeCatalogRows(null)) + assert.equal(inAccount(homeA, () => catalogRows()), null) + assert.deepEqual(inAccount(homeA, () => modelsInGroup(claudeGroup)), []) + assert.deepEqual(modelsInGroup(claudeGroup), ["claude-sonnet-5-5", "claude-sonnet-5-5-high", "claude-sonnet-5-5-low"]) + assert.deepEqual(inAccount(homeB, () => catalogRows().map(r => r.id)), ["gemini-3.8-flash-high"]) + } finally { + storeCatalogRows(null) + inAccount(homeA, () => storeCatalogRows(null)) + inAccount(homeB, () => storeCatalogRows(null)) + } +}) + const report = groups => ({ status: "SUCCESS", command: { name: "usage", data: { groups } } }) const group = (buckets, name = "Gemini Models", description = "For paid Pro plans, Argon quota is separate.") => ({ name, description, buckets }) const bucket = (overrides = {}) => ({ id: "gemini-5h", name: "Five Hour Limit Remaining", window: "5h", remaining_fraction: 0.75, ...overrides }) @@ -1320,9 +1359,16 @@ test("a read longer than magpie waits says agy is still reading, and the next ca assert.equal(next.signIn, "kept") assert.equal(next.windows.length, 1) assert.equal(await runs(), 1, "the late answer is taken, agy isn't run again") - // taken once: the call after it reads again + // taken once: the call after it reads again. That run has the same + // waitMs (300ms) as the rest, which a loaded machine can spend before it + // ends (#1622): then the call after it takes the answer. f.env.TEST_MODE = "" - const again = await read() + const ran = new Promise(r => { settled = r }) + let again = await read() + if (again.error === STILL_READING) { + await ran + again = await read() + } assert.equal(again.windows.length, 1) assert.equal(await runs(), 2) await f.assertClean() diff --git a/test/windows-nc.mjs b/test/windows-nc.mjs index 4ccfb88..363be9b 100644 --- a/test/windows-nc.mjs +++ b/test/windows-nc.mjs @@ -222,6 +222,29 @@ test("at exit on Windows every live agy's tree is ended and the workspaces remov } }) +test("Windows exit retries a workspace rename while the directory is still busy", async () => { + const kit = await windowsKit() + try { + await turn(kit, "one") + const [{ cwd }] = kit.acpSpawns + const rename = fs.renameSync + let attempts = 0 + fs.renameSync = (from, to) => { + if (from === cwd && ++attempts <= 2) throw Object.assign(new Error("workspace still in use"), { code: "EPERM" }) + return rename(from, to) + } + try { + kit.module.__agyTestReapOnExit() + } finally { + fs.renameSync = rename + } + assert.equal(attempts, 3) + assert.equal(fs.existsSync(cwd), false) + } finally { + await kit.dispose() + } +}) + test("at exit a shim dir this host made is removed", async () => { const kit = await windowsKit({ onSpawn: () => 1 }) try { diff --git a/test/workspace-handoff.mjs b/test/workspace-handoff.mjs new file mode 100644 index 0000000..beb2a7e --- /dev/null +++ b/test/workspace-handoff.mjs @@ -0,0 +1,223 @@ +// agy runs a session's PreToolUse hook (.agents/hooks.json, the tool gate) +// in the folder that holds hooks.json, the session's workspace. With that +// folder gone, agy can't start the hook at all: every tool call then fails +// with "jsonhook__magpie-tool-gate_PreToolUse_0_0: fork/exec /bin/sh: no +// such file or directory" (Go's error for a missing working directory) and +// the session can't use a tool again (aodlaodl261224 on X). +// +// It went from under a live agy when two plugin hosts overlap: magpie keeps +// a host it replaced (a plugin update, a recycle) answering its calls for up +// to ten minutes, the new host resumes a parked session in the same folder, +// and the old host removed that folder when its own agy for the session +// stopped. +// +// bun test ./workspace-handoff.mjs + +import assert from "node:assert/strict" +import fs from "node:fs" +import path from "node:path" +import { test } from "node:test" +import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +globalThis.fetch = () => { throw new Error("offline fixture") } + +const calls = (kit, method) => kit.acpLog.filter((entry) => entry.method === method) +const hooksFile = (workspace) => path.join(workspace, ".agents", "hooks.json") +const stateEntries = (file) => fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")).entries : [] + +// Two hosts sharing the state file and the temp folder, as magpie's do. +async function twoHosts(fn) { + const shared = fs.mkdtempSync(path.join(process.env.TMPDIR || "/tmp", "agy-handoff-")) + const env = { AGY_BRIDGE_STATE_FILE: path.join(shared, "sessions.json") } + const old = await createBridgeKit({ agentVersion: "1.5.19", sessionResume: true, tmpdir: shared, env }) + const fresh = await createBridgeKit({ agentVersion: "1.5.19", sessionResume: true, tmpdir: shared, env }) + for (const kit of [old, fresh]) { + kit.defaultPrompt = async (agent) => { + await agent.text("OK") + return { stopReason: "end_turn" } + } + } + try { + return await fn({ old, fresh, file: env.AGY_BRIDGE_STATE_FILE }) + } finally { + await old.dispose() + await fresh.dispose() + fs.rmSync(shared, { recursive: true, force: true }) + } +} + +// The old host's agy stops, as the host goes (its exit) or retires it. +async function oldHostStops(old, how) { + if (how === "exit") { + old.module.__agyTestReapOnExit() + return + } + for (const proc of [...old.module.__agyTestAllProcs]) await proc.stop().catch(() => {}) +} + +function holdStateLock(file) { + const lock = file + ".lock" + fs.writeFileSync(lock, JSON.stringify({ pid: process.pid }), { flag: "wx" }) + return () => fs.rmSync(lock, { force: true }) +} + +for (const how of ["stop", "exit"]) { + test(`a session resumed by the next host keeps its folder when the old host's agy goes (${how})`, async () => { + await twoHosts(async ({ old, fresh, file }) => { + // the old host: a tool loop, parked at its step (parkStep) + old.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/a" }) + await agent.text("never reached") + return { stopReason: "end_turn" } + }) + let body = baseBody() + const parsed = await readSse(await old.request(body)) + assert.equal(parsed.stopReason, "tool_use") + const entry = stateEntries(file).find((item) => item.midTurn) + assert.ok(entry?.workspace, "the step is parked with its folder") + const original = fs.readFileSync(hooksFile(entry.workspace), "utf8") + + // the step's results reach the new host, which resumes there + let hookSeen = null + fresh.prompts.push(async (agent) => { + hookSeen = fs.existsSync(hooksFile(agent.cwd)) + await agent.tool("Read", { path: "/b" }) + hookSeen = hookSeen && fs.existsSync(hooksFile(agent.cwd)) + await agent.text("done") + return { stopReason: "end_turn" } + }) + body = continueWithToolResults(body, parsed) + const second = await readSse(await fresh.request(body)) + assert.equal(second.stopReason, "tool_use") + assert.equal(calls(fresh, "session/resume").length, 1) + assert.equal(fresh.acpSpawns[0].cwd, entry.workspace, "resumed in the same folder") + + // the old host's agy for the session stops now + await oldHostStops(old, how) + assert.ok(fs.existsSync(hooksFile(entry.workspace)), "the old host removed the folder the new host's agy runs in") + assert.equal(fs.readFileSync(hooksFile(entry.workspace), "utf8"), original) + + body = continueWithToolResults(body, second) + assert.equal((await readSse(await fresh.request(body))).stopReason, "end_turn") + assert.equal(hookSeen, true) + }) + }) +} + +for (const how of ["stop", "exit"]) { + test("the old host still removes a folder no other host took (" + how + ")", async () => { + await twoHosts(async ({ old }) => { + assert.equal((await readSse(await old.request(baseBody()))).stopReason, "end_turn") + const workspace = old.acpSpawns[0].cwd + assert.ok(fs.existsSync(workspace)) + await oldHostStops(old, how) + assert.equal(fs.existsSync(workspace), false) + }) + }) +} + +test("a stop retries cleanup after another process releases the state lock", async () => { + await twoHosts(async ({ old, file }) => { + assert.equal((await readSse(await old.request(baseBody()))).stopReason, "end_turn") + const { cwd } = old.acpSpawns[0] + const unlock = holdStateLock(file) + const timer = setTimeout(unlock, 250) + try { + await oldHostStops(old, "stop") + assert.equal(fs.existsSync(cwd), false) + } finally { + clearTimeout(timer) + unlock() + } + }) +}) + +test("a resume under a persistently busy lock uses a separate workspace", async () => { + await twoHosts(async ({ old, fresh, file }) => { + old.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/a" }) + return { stopReason: "end_turn" } + }) + const body = baseBody() + const step = await readSse(await old.request(body)) + assert.equal(step.stopReason, "tool_use") + const entry = stateEntries(file).find((item) => item.midTurn) + const ownerFile = path.join(entry.workspace, ".magpie-agy-owner") + const owner = fs.readFileSync(ownerFile, "utf8") + const unlock = holdStateLock(file) + try { + const response = await readSse(await fresh.request(continueWithToolResults(body, step))) + assert.equal(response.stopReason, "end_turn") + const [resume] = calls(fresh, "session/resume") + assert.equal(resume.params.sessionId, entry.sessionId) + assert.notEqual(resume.params.cwd, entry.workspace) + assert.ok(fs.existsSync(hooksFile(resume.params.cwd))) + assert.equal(fs.readFileSync(ownerFile, "utf8"), owner) + } finally { + unlock() + } + }) +}) + +test("the workspace ownership marker contains no control credential", async () => { + await twoHosts(async ({ old }) => { + assert.equal((await readSse(await old.request(baseBody()))).stopReason, "end_turn") + const { cwd, env } = old.acpSpawns[0] + assert.ok(env.AGY_BRIDGE_TOKEN) + const owner = fs.readFileSync(path.join(cwd, ".magpie-agy-owner"), "utf8") + assert.ok(owner.trim()) + assert.equal(owner.includes(env.AGY_BRIDGE_TOKEN), false) + }) +}) + +async function withKit(fn) { + const kit = await createBridgeKit({ agentVersion: "1.5.19", sessionResume: true }) + try { return await fn(kit) } finally { await kit.dispose() } +} + +test("a folder removed from under a live agy is made again before its next prompt", async () => { + await withKit(async (kit) => { + kit.prompts.push(async (agent) => { + await agent.text("first") + return { stopReason: "end_turn" } + }) + let body = baseBody() + assert.equal((await readSse(await kit.request(body))).stopReason, "end_turn") + const workspace = kit.acpSpawns[0].cwd + const original = fs.readFileSync(hooksFile(workspace), "utf8") + // anything else removing it: another host on an older plugin, a temp cleaner + fs.rmSync(workspace, { recursive: true, force: true }) + + let seen = null + kit.prompts.push(async (agent) => { + seen = fs.existsSync(hooksFile(agent.cwd)) && fs.readFileSync(hooksFile(agent.cwd), "utf8") + await agent.text("second") + return { stopReason: "end_turn" } + }) + body = { ...body, messages: [...body.messages, { role: "assistant", content: [{ type: "text", text: "first" }] }, + { role: "user", content: "and the next thing" }] } + assert.equal((await readSse(await kit.request(body))).stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1, "the same agy") + assert.equal(seen, original, "the hook's folder is back before the prompt") + assert.ok(fs.existsSync(path.join(workspace, "AGENTS.md"))) + }) +}) + +test("a folder removed in the middle of a tool loop is made again before the results go back", async () => { + await withKit(async (kit) => { + let seen = null + kit.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/a" }) + seen = fs.existsSync(hooksFile(agent.cwd)) + await agent.text("done") + return { stopReason: "end_turn" } + }) + let body = baseBody() + const parsed = await readSse(await kit.request(body)) + assert.equal(parsed.stopReason, "tool_use") + fs.rmSync(kit.acpSpawns[0].cwd, { recursive: true, force: true }) + body = continueWithToolResults(body, parsed) + assert.equal((await readSse(await kit.request(body))).stopReason, "end_turn") + assert.equal(seen, true, "the model's next call finds the hook's folder") + }) +})