feat: AI Router per session; Settings at the sidebar's foot; shipped tool icons

AI Router is a session's choice, not a workspace's:
- an AI Router select beside the model picker in the workspace home and a
  pane's run form (RouterPicker.tsx; hidden off Claude/Codex or with only
  Native; last pick remembered in agenthub.session.router)
- `router` on POST /api/lanes/:id/start and POST /api/run; Claude gets
  --settings=<data dir>/router-settings/<name>.json (0600, outranks project
  and user settings, key never in argv), Codex -p <name> + key via tmux -e
- dashboard_runs.router; a resume naming none goes back to it
- profile PATCH rewrites the session files, DELETE removes them
- gone: POST /api/lanes/:id/router/apply, LaneRouterRow, the Add-workspace
  router radio, the claude-/codex-home `routers` answers; clearLaneRouters
  takes the old keys out of each workspace's settings.local.json at start

Sidebar: Settings pinned to the foot, the collapse toggle beside it (stacked
on the rail) instead of in the brand's corner.

Icons: shipped SVG marks for claude, codex, openclaw and hermes (a
black/white pair swapped by theme) in client/public/ai-tools/, used by
AiToolIcon before the server's favicon.
This commit is contained in:
2026-10-02 14:19:02 +07:00
parent 5084334d81
commit c507d37baf
55 changed files with 851 additions and 1992 deletions
+12 -56
View File
@@ -278,65 +278,21 @@ describe("/api/lanes", () => {
ws.close();
});
it("broadcasts lane_update on router apply", async () => {
// Without this the client's cached row keeps the OLD router_profile: the
// picker looks right until the user switches lanes and back, at which
// point the effect re-reads the stale row and flips the selection.
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "lane-router-bcast-"));
const created = await request("POST", "/api/lanes", { cwd, title: "Router Lane" });
const id = created.body.lane.id;
// Start somewhere other than native, so the broadcast has to carry a
// CHANGED value rather than the one the row already held.
require("../lib/lanes").setRouterProfile(id, "some-router");
const ws = new WebSocket(`ws://127.0.0.1:${server.address().port}/ws`);
const messages = [];
await new Promise((resolve, reject) => {
ws.on("open", resolve);
ws.on("error", reject);
});
ws.on("message", (msg) => {
try {
messages.push(JSON.parse(msg));
} catch {
/* parse error */
}
});
try {
const applied = await request("POST", `/api/lanes/${id}/router/apply`, { profile: "native" });
assert.equal(applied.status, 200);
await new Promise((resolve) => setTimeout(resolve, 100));
const msg = messages.find((m) => m.type === "lane_update" && m.data.lane?.id === id);
assert.ok(msg, "router apply should broadcast lane_update");
// `native` is stored as null — what matters is that the pushed row is the
// post-apply one, not the "some-router" the client still has cached.
assert.equal(msg.data.lane.router_profile, null);
} finally {
// A socket left open by a failed assertion keeps the whole run alive.
ws.close();
}
await request("DELETE", `/api/lanes/${id}`);
fs.rmSync(cwd, { recursive: true, force: true });
});
it("router apply asks for a restart only while the lane's pane is live", async () => {
it("starts a session on the router it names, and refuses one the store lacks", async () => {
const tmux = require("../lib/tmux");
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "lane-router-live-"));
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "lane-router-start-"));
const id = (await request("POST", "/api/lanes", { cwd })).body.lane.id;
try {
for (const live of [false, true]) {
tmux.__setExecImpl((args) => {
if (args[0] === "has-session" && !live) throw new Error("no such session");
return "";
});
const r = await request("POST", `/api/lanes/${id}/router/apply`, { profile: "native" });
assert.equal(r.status, 200);
assert.equal(r.body.restart_required, live);
assert.equal(r.body.run_id, live ? `agenthub-lane-${id}` : null);
}
tmux.__setExecImpl((args) => {
if (args[0] === "has-session") throw new Error("no such session");
return "";
});
const bad = await request("POST", `/api/lanes/${id}/start`, { router: "nope" });
assert.equal(bad.status, 400);
assert.equal(bad.body.error.code, "EBADROUTER");
// The per-workspace route is gone: a router belongs to a session now.
const gone = await request("POST", `/api/lanes/${id}/router/apply`, { profile: "native" });
assert.equal(gone.status, 404);
} finally {
tmux.__reset();
fs.rmSync(cwd, { recursive: true, force: true });
+53
View File
@@ -267,6 +267,59 @@ describe("pty-run", () => {
}
});
it("spawnRun starts a session on ITS router: Claude by --settings, Codex by -p", () => {
let newSessionArgv = null;
tmux.__setExecImpl((args) => {
if (args[0] === "has-session") {
const e = new Error("gone");
e.status = 1;
throw e;
}
if (args[0] === "new-session") newSessionArgv = args;
return "";
});
// The router store and the files a spawn writes live under these homes.
const saved = ["CLAUDE_HOME", "CODEX_HOME", "DASHBOARD_DATA_DIR"].map((k) => [
k,
process.env[k],
]);
process.env.CLAUDE_HOME = path.join(TMP, "claude");
process.env.CODEX_HOME = path.join(TMP, "codex");
process.env.DASHBOARD_DATA_DIR = path.join(TMP, "data");
try {
const { name } = require("../lib/ai-routers").createRouter({
label: "Router",
baseUrl: "http://localhost:20128/v1",
apiKey: "sk-secret-value",
model: "M",
});
pty.spawnRun({ laneId: 51, cwd: "/tmp/repo", router: name, initialPrompt: "hi" });
const flag = newSessionArgv.find((a) => a.startsWith("--settings="));
assert.equal(flag, `--settings=${path.join(TMP, "data", "router-settings", `${name}.json`)}`);
assert.ok(!newSessionArgv.join(" ").includes("sk-secret-value"));
assert.equal(require("../lib/dashboard-runs").getRun("agenthub-lane-51").router, name);
pty.spawnRun({ laneId: 52, cwd: "/tmp/repo", tool: "codex", router: name });
const at = newSessionArgv.indexOf("-p");
assert.deepEqual(newSessionArgv.slice(at, at + 2), ["-p", name]);
// The key rides tmux's -e, never the command line.
assert.ok(newSessionArgv.includes("AGENTHUB_ROUTER_KEY=sk-secret-value"));
pty.spawnRun({ laneId: 53, cwd: "/tmp/repo" });
assert.ok(!newSessionArgv.some((a) => a.startsWith("--settings=")));
assert.equal(require("../lib/dashboard-runs").getRun("agenthub-lane-53").router, null);
assert.throws(
() => pty.spawnRun({ laneId: 54, cwd: "/tmp/repo", router: "nope" }),
(e) => e.code === "EBADROUTER"
);
} finally {
for (const [k, v] of saved) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
});
it("spawnRun offers bypass in the pane's shift+tab cycle without starting in it", () => {
let newSessionArgv = null;
tmux.__setExecImpl((args) => {
+149 -361
View File
@@ -1,18 +1,19 @@
/**
* @file Tests for attaching an AI Router profile to a lane — the Claude Code
* `settings.local.json` env merge and the Codex `<name>.config.toml` layer,
* including the guarantees that neither write destroys anything already there.
* @file Tests for starting one session on an AI Router profile — Claude Code's
* `--settings=<file>` env file and the Codex `<name>.config.toml` layer, an
* edit or delete reaching those files, and the one-time cleanup of the old
* per-workspace router out of a workspace's `settings.local.json`.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const os = require("node:os");
const path = require("node:path");
const fs = require("node:fs");
const { execFileSync } = require("node:child_process");
const SUITE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-router-apply-"));
process.env.CLAUDE_HOME = path.join(SUITE_ROOT, ".claude");
process.env.CODEX_HOME = path.join(SUITE_ROOT, ".codex");
process.env.DASHBOARD_DATA_DIR = path.join(SUITE_ROOT, "data");
process.env.DASHBOARD_DB_PATH = path.join(SUITE_ROOT, "dashboard.db");
const { describe, it, beforeEach, after } = require("node:test");
@@ -20,30 +21,30 @@ const assert = require("node:assert/strict");
const routers = require("../lib/ai-routers");
const lanesLib = require("../lib/lanes");
const { db } = require("../db");
const {
applyRouterToLane,
reapplyToLanes,
detachFromLanes,
routerEnvForSpawn,
routerArgvForSpawn,
resolveRouter,
resumeRouter,
routerForSpawn,
refreshProfileFiles,
removeProfileFiles,
clearLaneRouters,
} = require("../lib/router-apply");
const LANE_CWD = path.join(SUITE_ROOT, "project");
const SETTINGS = path.join(LANE_CWD, ".claude", "settings.local.json");
const settingsFile = (name) =>
path.join(process.env.DASHBOARD_DATA_DIR, "router-settings", `${name}.json`);
const layerFile = (name) => path.join(process.env.CODEX_HOME, `${name}.config.toml`);
after(() => fs.rmSync(SUITE_ROOT, { recursive: true, force: true }));
beforeEach(() => {
fs.rmSync(path.join(process.env.CLAUDE_HOME, "agenthub-routers"), {
recursive: true,
force: true,
});
fs.rmSync(LANE_CWD, { recursive: true, force: true });
fs.rmSync(process.env.CODEX_HOME, { recursive: true, force: true });
fs.mkdirSync(LANE_CWD, { recursive: true });
// The DB outlives each test; a profile name is reused, so lanes left behind
// would be picked up by the next test's `reapplyToLanes` and inflate its count.
for (const lane of lanesLib.listLanes()) lanesLib.deleteLane(lane.id);
for (const dir of [
path.join(process.env.CLAUDE_HOME, "agenthub-routers"),
process.env.CODEX_HOME,
process.env.DASHBOARD_DATA_DIR,
]) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
function saveNineRouter() {
@@ -55,388 +56,175 @@ function saveNineRouter() {
});
}
const claudeLane = () => ({ id: 7, cwd: LANE_CWD, tool: "claude" });
const codexLane = () => ({ id: 8, cwd: LANE_CWD, tool: "codex" });
const spawnFor = (tool, name) => routerForSpawn(tool, resolveRouter(tool, name));
describe("router-apply — Claude lane", () => {
it("writes the eight env keys the reference settings file swaps", () => {
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
const env = JSON.parse(fs.readFileSync(SETTINGS, "utf8")).env;
assert.equal(env.ANTHROPIC_BASE_URL, "http://localhost:20128/v1");
assert.equal(env.ANTHROPIC_AUTH_TOKEN, "sk-secret-value");
assert.equal(env.ANTHROPIC_MODEL, "Highest");
assert.equal(env.ANTHROPIC_DEFAULT_OPUS_MODEL, "Highest");
assert.equal(env.ANTHROPIC_DEFAULT_SONNET_MODEL, "Highest");
assert.equal(env.ANTHROPIC_DEFAULT_HAIKU_MODEL, "Highest");
assert.equal(env.ANTHROPIC_SMALL_FAST_MODEL, "Highest");
assert.equal(env.CLAUDE_CODE_SUBAGENT_MODEL, "Highest");
describe("resolveRouter", () => {
it("reads null, empty and native as the vendor's own API", () => {
for (const name of [null, undefined, "", "native"])
assert.equal(resolveRouter("claude", name), null);
});
it("keeps every unrelated key in the file it merges into", () => {
// A lane's settings.local.json is the user's file; this feature owns eight
// keys in it and nothing else.
fs.mkdirSync(path.dirname(SETTINGS), { recursive: true });
fs.writeFileSync(
SETTINGS,
JSON.stringify({
permissions: { defaultMode: "bypassPermissions" },
env: { MY_OWN_VAR: "keep me", ANTHROPIC_MODEL: "to be replaced" },
})
);
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
const saved = JSON.parse(fs.readFileSync(SETTINGS, "utf8"));
assert.equal(saved.permissions.defaultMode, "bypassPermissions");
assert.equal(saved.env.MY_OWN_VAR, "keep me");
assert.equal(saved.env.ANTHROPIC_MODEL, "Highest");
});
it("writes the file 0600, because it now holds an API key", () => {
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
assert.equal(fs.statSync(SETTINGS).mode & 0o777, 0o600);
});
it("blanks the connection variables for the native profile instead of dropping them", () => {
// Absent keys would let a user-level router base URL apply to a lane that
// explicitly asked for native.
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
applyRouterToLane(claudeLane(), "native");
const env = JSON.parse(fs.readFileSync(SETTINGS, "utf8")).env;
assert.equal(env.ANTHROPIC_BASE_URL, "");
assert.equal(env.ANTHROPIC_AUTH_TOKEN, "");
});
it("removes the model names for the native profile rather than pinning them", () => {
// The opposite of the connection pair above, and for the opposite reason:
// a project-scope model name overrides the user's own global choice, so a
// lane on native must leave that choice alone instead of writing whatever
// `claude-*` names this codebase happened to ship with.
fs.mkdirSync(path.dirname(SETTINGS), { recursive: true });
fs.writeFileSync(SETTINGS, JSON.stringify({ env: { MY_OWN_VAR: "keep me" } }));
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
applyRouterToLane(claudeLane(), "native");
const env = JSON.parse(fs.readFileSync(SETTINGS, "utf8")).env;
assert.equal(env.ANTHROPIC_MODEL, undefined);
assert.equal(env.ANTHROPIC_DEFAULT_OPUS_MODEL, undefined);
assert.equal(env.CLAUDE_CODE_SUBAGENT_MODEL, undefined);
assert.equal(env.MY_OWN_VAR, "keep me"); // clearing ours touches nothing else
});
it("refuses a profile that does not exist rather than writing a broken file", () => {
assert.throws(() => applyRouterToLane(claudeLane(), "ghost"), { code: "ENOTFOUND" });
assert.equal(fs.existsSync(SETTINGS), false);
});
it("leaves a settings file that is not valid JSON alone", () => {
fs.mkdirSync(path.dirname(SETTINGS), { recursive: true });
fs.writeFileSync(SETTINGS, "{not json");
const { name } = saveNineRouter();
assert.throws(() => applyRouterToLane(claudeLane(), name), { code: "EBADJSON" });
assert.equal(fs.readFileSync(SETTINGS, "utf8"), "{not json");
});
});
describe("router-apply — the written file must survive a lane reset", () => {
// Real repos, asserted through `git status`: a fake `.git` dir let a test pass
// while git itself never read the exclude file it checked.
const REPO = path.join(SUITE_ROOT, "repo");
// A pre-commit hook running this suite exports GIT_INDEX_FILE & co., which
// would point these fixture calls at the outer repo.
const git = (cwd, ...args) => {
const env = { ...process.env };
for (const name of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR"]) {
delete env[name];
}
return execFileSync("git", args, { cwd, env, encoding: "utf8" });
};
const untracked = (cwd) =>
git(cwd, "status", "--porcelain", "--untracked-files=all", "--ignored=no")
.split("\n")
.filter(Boolean);
// A machine-wide ignore (Claude Code adds one for settings.local.json) would
// hide the very file these tests look for.
beforeEach(() => {
process.env.GIT_CONFIG_GLOBAL = "/dev/null";
process.env.GIT_CONFIG_NOSYSTEM = "1";
fs.rmSync(REPO, { recursive: true, force: true });
fs.mkdirSync(REPO, { recursive: true });
git(REPO, "init", "-q");
git(
REPO,
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"--allow-empty",
"-m",
"init"
it("refuses a profile the store does not have", () => {
assert.throws(
() => resolveRouter("claude", "nope"),
(e) => e.code === "EBADROUTER"
);
});
const laneAt = (cwd) => ({ id: 7, cwd, tool: "claude" });
it("hides settings.local.json and its backups, so `git clean -fd` cannot delete them", () => {
// `agenthub lanes reset` runs `git clean -fd` (server/lib/worktree.js).
// Without -x that spares IGNORED files only — an untracked settings file
// would be deleted, silently detaching the lane from its router. The same
// entry also stops an API key from being committable.
const { name } = saveNineRouter();
applyRouterToLane(laneAt(REPO), name);
applyRouterToLane(laneAt(REPO), "native"); // a second write leaves a backup
assert.deepEqual(untracked(REPO), []);
});
it("hides them in a worktree lane, whose exclude file is the COMMON dir's", () => {
// git reads info/exclude from the common git dir only; a copy under
// .git/worktrees/<name>/info/ is never consulted.
const wt = path.join(SUITE_ROOT, "wt");
fs.rmSync(wt, { recursive: true, force: true });
git(REPO, "worktree", "add", "-q", "-b", "lane1", wt);
const { name } = saveNineRouter();
applyRouterToLane(laneAt(wt), name);
applyRouterToLane(laneAt(wt), "native");
assert.deepEqual(untracked(wt), []);
});
it("hides them in a lane that is a subdirectory of its repo", () => {
const sub = path.join(REPO, "packages", "app");
fs.mkdirSync(sub, { recursive: true });
const { name } = saveNineRouter();
applyRouterToLane(laneAt(sub), name);
applyRouterToLane(laneAt(sub), "native");
assert.deepEqual(untracked(REPO), []);
});
it("adds the entry once, however many times a router is applied", () => {
const { name } = saveNineRouter();
applyRouterToLane(laneAt(REPO), name);
applyRouterToLane(laneAt(REPO), "native");
const exclude = fs.readFileSync(path.join(REPO, ".git", "info", "exclude"), "utf8");
assert.equal(exclude.split("\n").filter((l) => l.includes("settings.local.json")).length, 1);
});
it("still writes the settings file when the lane is not a git repo at all", () => {
const { name } = saveNineRouter();
applyRouterToLane(claudeLane(), name);
assert.ok(fs.existsSync(SETTINGS));
});
});
describe("router-apply — Antigravity lane", () => {
const agyLane = () => ({ id: 9, cwd: LANE_CWD, tool: "antigravity" });
it("accepts native and writes nothing", () => {
assert.equal(applyRouterToLane(agyLane(), "native").file, null);
assert.equal(fs.existsSync(SETTINGS), false);
});
it("refuses a real router instead of writing Claude's settings file", () => {
it("refuses a router on a tool with no endpoint to point at one", () => {
const { name } = saveNineRouter();
assert.throws(
() => applyRouterToLane(agyLane(), name),
(err) => err.code === "EUNSUPPORTED"
() => resolveRouter("antigravity", name),
(e) => e.code === "EUNSUPPORTED"
);
assert.equal(fs.existsSync(SETTINGS), false);
assert.equal(resolveRouter("antigravity", "native"), null);
});
});
describe("router-apply — Codex lane", () => {
it("writes a profile layer file, never the base config", () => {
describe("routerForSpawn — Claude", () => {
it("passes a 0600 settings file holding the eight env keys, never the key in argv", () => {
const { name } = saveNineRouter();
const { argv, env } = spawnFor("claude", name);
assert.deepEqual(argv, [`--settings=${settingsFile(name)}`]);
assert.deepEqual(env, {});
assert.ok(!argv.join(" ").includes("sk-secret-value"));
const written = JSON.parse(fs.readFileSync(settingsFile(name), "utf8")).env;
assert.equal(written.ANTHROPIC_BASE_URL, "http://localhost:20128/v1");
assert.equal(written.ANTHROPIC_AUTH_TOKEN, "sk-secret-value");
for (const k of [
"ANTHROPIC_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"ANTHROPIC_SMALL_FAST_MODEL",
"CLAUDE_CODE_SUBAGENT_MODEL",
]) {
assert.equal(written[k], "Highest", k);
}
assert.equal(fs.statSync(settingsFile(name)).mode & 0o777, 0o600);
});
it("leaves a blank key out instead of blanking the user's own setting", () => {
const { name } = routers.createRouter({
label: "Local",
baseUrl: "http://127.0.0.1:20128/v1",
apiKey: "",
model: "Highest",
});
spawnFor("claude", name);
const written = JSON.parse(fs.readFileSync(settingsFile(name), "utf8")).env;
assert.equal("ANTHROPIC_AUTH_TOKEN" in written, false);
});
it("adds nothing for native", () => {
assert.deepEqual(spawnFor("claude", "native"), { argv: [], env: {} });
});
});
describe("routerForSpawn — Codex", () => {
it("writes a profile layer, never the base config, and hands the key over in env", () => {
const base = path.join(process.env.CODEX_HOME, "config.toml");
fs.mkdirSync(process.env.CODEX_HOME, { recursive: true });
fs.writeFileSync(base, 'approval_policy = "never"\n');
const { name } = saveNineRouter();
applyRouterToLane(codexLane(), name);
const { argv, env } = spawnFor("codex", name);
assert.deepEqual(argv, ["-p", name]);
assert.deepEqual(env, { AGENTHUB_ROUTER_KEY: "sk-secret-value" });
assert.equal(fs.readFileSync(base, "utf8"), 'approval_policy = "never"\n');
const layer = fs.readFileSync(path.join(process.env.CODEX_HOME, `${name}.config.toml`), "utf8");
const layer = fs.readFileSync(layerFile(name), "utf8");
assert.match(layer, /model_provider = "9router"/);
assert.match(layer, /base_url = "http:\/\/localhost:20128\/v1"/);
assert.match(layer, /env_key = "AGENTHUB_ROUTER_KEY"/);
});
it("keeps the key out of the config file, naming an env var instead", () => {
// Codex reads the key from the environment; writing it into config.toml
// would put a secret in a file with no reason to hold one.
const { name } = saveNineRouter();
applyRouterToLane(codexLane(), name);
const layer = fs.readFileSync(path.join(process.env.CODEX_HOME, `${name}.config.toml`), "utf8");
// Not "chat": codex-cli 0.149 refuses to load it at all.
assert.match(layer, /wire_api = "responses"/);
assert.ok(!layer.includes("sk-secret-value"));
});
it("writes no layer file for the native profile", () => {
// Native means "the base config as it already is" — a layer that overrode
// nothing would still shadow a model the user set in the base.
applyRouterToLane(codexLane(), "native");
assert.equal(fs.existsSync(path.join(process.env.CODEX_HOME, "native.config.toml")), false);
});
it("does not touch the lane's .claude directory", () => {
const { name } = saveNineRouter();
applyRouterToLane(codexLane(), name);
assert.equal(fs.existsSync(SETTINGS), false);
});
it('never writes wire_api = "chat", which codex refuses to load at all', () => {
// Verified against the installed codex-cli 0.149.0: `wire_api = "chat" is
// no longer supported` is a hard config error, so a layer carrying it makes
// the lane fail to start rather than fall back to anything.
const { name } = saveNineRouter();
applyRouterToLane(codexLane(), name);
const layer = fs.readFileSync(path.join(process.env.CODEX_HOME, `${name}.config.toml`), "utf8");
assert.match(layer, /wire_api = "responses"/);
assert.ok(!layer.includes('wire_api = "chat"'));
});
it("names no env_key when the profile has no key to put in it", () => {
// A local router needs no key — the reference 9Router provider has none.
// Naming a variable that is never set makes codex refuse to start.
it("names no env_key when the profile has no key", () => {
const { name } = routers.createRouter({
label: "Local gateway",
baseUrl: "http://127.0.0.1:20128/v1",
apiKey: "",
model: "Highest",
});
applyRouterToLane(codexLane(), name);
const layer = fs.readFileSync(path.join(process.env.CODEX_HOME, `${name}.config.toml`), "utf8");
assert.ok(!layer.includes("env_key"), layer);
const { env } = spawnFor("codex", name);
assert.deepEqual(env, {});
assert.ok(!fs.readFileSync(layerFile(name), "utf8").includes("env_key"));
});
});
describe("router-apply — an edit or a delete reaches the lanes already using it", () => {
// Attaching COPIES the profile into the lane's own config, so a store-only
// write is inert exactly where it matters: the key a lane authenticates with.
/** A real lane row in a directory of its own, already attached to `profile`. */
function laneOn(profile, dirName) {
const cwd = path.join(SUITE_ROOT, dirName);
fs.mkdirSync(cwd, { recursive: true });
const lane = lanesLib.createLane({ title: dirName, cwd, router_profile: profile });
applyRouterToLane(lane, profile);
return { lane, settings: path.join(cwd, ".claude", "settings.local.json") };
}
const envOf = (file) => JSON.parse(fs.readFileSync(file, "utf8")).env;
it("pushes a rotated key out to every claude lane on that profile", () => {
describe("an edit or a delete reaches the session files", () => {
it("an edit rewrites the files that exist and creates none", () => {
const { name } = saveNineRouter();
const a = laneOn(name, "rotate-a");
const b = laneOn(name, "rotate-b");
assert.equal(envOf(a.settings).ANTHROPIC_AUTH_TOKEN, "sk-secret-value");
spawnFor("claude", name);
routers.updateRouter(name, { apiKey: "sk-rotated" });
const result = reapplyToLanes(name);
assert.equal(result.updated, 2);
assert.deepEqual(result.failed, []);
assert.equal(envOf(a.settings).ANTHROPIC_AUTH_TOKEN, "sk-rotated");
assert.equal(envOf(b.settings).ANTHROPIC_AUTH_TOKEN, "sk-rotated");
refreshProfileFiles(name);
const env = JSON.parse(fs.readFileSync(settingsFile(name), "utf8")).env;
assert.equal(env.ANTHROPIC_AUTH_TOKEN, "sk-rotated");
assert.equal(fs.existsSync(layerFile(name)), false);
});
it("leaves lanes on a different profile alone", () => {
it("a delete removes both files", () => {
const { name } = saveNineRouter();
const other = routers.createRouter({
label: "OpenRouter",
baseUrl: "https://openrouter.ai/api/v1",
apiKey: "sk-other",
model: "auto",
});
const mine = laneOn(name, "mixed-mine");
const theirs = laneOn(other.name, "mixed-theirs");
routers.updateRouter(name, { apiKey: "sk-rotated" });
reapplyToLanes(name);
assert.equal(envOf(mine.settings).ANTHROPIC_AUTH_TOKEN, "sk-rotated");
assert.equal(envOf(theirs.settings).ANTHROPIC_AUTH_TOKEN, "sk-other");
});
it("clears the deleted router out of the lane's settings and its DB row", () => {
// Without this the lane keeps routing to an endpoint the user believes they
// removed, with a key they believe they revoked.
const { name } = saveNineRouter();
const { lane, settings } = laneOn(name, "deleted-router");
routers.removeRouter(name);
const result = detachFromLanes(name);
assert.equal(result.updated, 1);
assert.equal(envOf(settings).ANTHROPIC_BASE_URL, "");
assert.equal(envOf(settings).ANTHROPIC_AUTH_TOKEN, "");
assert.equal(envOf(settings).ANTHROPIC_MODEL, undefined);
assert.equal(lanesLib.getLane(lane.id).router_profile, null);
});
it("deletes the codex layer file, so a later same-named profile cannot inherit it", () => {
const { name } = saveNineRouter();
const layer = path.join(process.env.CODEX_HOME, `${name}.config.toml`);
applyRouterToLane(codexLane(), name);
assert.ok(fs.existsSync(layer));
routers.removeRouter(name);
detachFromLanes(name);
assert.equal(fs.existsSync(layer), false);
});
it("reports a lane it could not update instead of failing the whole edit", () => {
const { name } = saveNineRouter();
const ok = laneOn(name, "partial-ok");
const broken = laneOn(name, "partial-broken");
fs.writeFileSync(broken.settings, "{ not json");
const result = reapplyToLanes(name);
assert.equal(result.updated, 1);
assert.equal(result.failed.length, 1);
assert.match(result.failed[0], /partial-broken/);
assert.equal(envOf(ok.settings).ANTHROPIC_BASE_URL, "http://localhost:20128/v1");
});
it("has nothing to do for native, which is stored as no router at all", () => {
laneOn("native", "native-lane");
assert.deepEqual(reapplyToLanes("native"), { updated: 0, failed: [] });
spawnFor("claude", name);
spawnFor("codex", name);
removeProfileFiles(name);
assert.equal(fs.existsSync(settingsFile(name)), false);
assert.equal(fs.existsSync(layerFile(name)), false);
});
});
describe("router-apply — what a spawn adds", () => {
it("gives a codex lane the profile flag and the key in its environment", () => {
describe("resumeRouter", () => {
it("goes back to the router the session last ran on, while it exists", () => {
const { name } = saveNineRouter();
assert.deepEqual(routerArgvForSpawn({ ...codexLane(), router_profile: name }), ["-p", name]);
assert.deepEqual(routerEnvForSpawn({ ...codexLane(), router_profile: name }), {
AGENTHUB_ROUTER_KEY: "sk-secret-value",
const runs = require("../lib/dashboard-runs");
runs.recordRun({
id: "agenthub-lane-91",
sessionId: "sess-router-1",
mode: "interactive",
router: name,
});
});
it("adds nothing for a claude lane, whose settings file already carries it", () => {
const { name } = saveNineRouter();
assert.deepEqual(routerArgvForSpawn({ ...claudeLane(), router_profile: name }), []);
assert.deepEqual(routerEnvForSpawn({ ...claudeLane(), router_profile: name }), {});
});
it("adds nothing for a lane with no router, or one set to native", () => {
assert.deepEqual(routerArgvForSpawn({ ...codexLane(), router_profile: null }), []);
assert.deepEqual(routerArgvForSpawn({ ...codexLane(), router_profile: "native" }), []);
assert.deepEqual(routerEnvForSpawn({ ...codexLane(), router_profile: "native" }), {});
});
it("adds nothing when the profile a lane names has since been deleted", () => {
// Deleting a profile must degrade the lane to its base config, never crash
// the spawn that was about to start.
const { name } = saveNineRouter();
assert.equal(resumeRouter("sess-router-1"), name);
routers.removeRouter(name);
assert.deepEqual(routerArgvForSpawn({ ...codexLane(), router_profile: name }), []);
assert.deepEqual(routerEnvForSpawn({ ...codexLane(), router_profile: name }), {});
assert.equal(resumeRouter("sess-router-1"), null);
assert.equal(resumeRouter("sess-unknown"), null);
});
});
describe("clearLaneRouters", () => {
it("takes the old router's keys out of a workspace's settings and clears the column", () => {
const cwd = path.join(SUITE_ROOT, "old-lane");
const file = path.join(cwd, ".claude", "settings.local.json");
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(
file,
JSON.stringify({
permissions: { allow: ["Bash(ls)"] },
env: { ANTHROPIC_BASE_URL: "http://x", ANTHROPIC_AUTH_TOKEN: "sk", MY_VAR: "1" },
})
);
const lane = lanesLib.createLane({ title: "old", cwd, router_profile: "9router" });
clearLaneRouters();
const data = JSON.parse(fs.readFileSync(file, "utf8"));
assert.deepEqual(data.env, { MY_VAR: "1" });
assert.deepEqual(data.permissions, { allow: ["Bash(ls)"] });
assert.equal(
db.prepare("SELECT router_profile FROM lanes WHERE id = ?").get(lane.id).router_profile,
null
);
});
it("keeps the column of a workspace whose file it could not clean, to retry later", () => {
const cwd = path.join(SUITE_ROOT, "broken-lane");
const file = path.join(cwd, ".claude", "settings.local.json");
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, "{ not json");
const lane = lanesLib.createLane({ title: "broken", cwd, router_profile: "9router" });
clearLaneRouters();
assert.equal(fs.readFileSync(file, "utf8"), "{ not json");
assert.equal(
db.prepare("SELECT router_profile FROM lanes WHERE id = ?").get(lane.id).router_profile,
"9router"
);
});
});
+2 -32
View File
@@ -1,11 +1,7 @@
/**
* @file Tests GET/PUT /api/settings/codex-home and setCodexHome: the shared
* home-dir guard, persistence to the settings file, the `env_owned` flag, and
* the AI Router layer being re-written into the NEW home for every codex lane
* on a router (a `codex -p <name>` against a home without `<name>.config.toml`
* would fail at start); a home change from another site refused, and a
* CLAUDE_HOME change naming the lanes whose router profile the new home's
* store lacks. Everything lives in a temp dir.
* a home change from another site refused. Everything lives in a temp dir.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
@@ -25,9 +21,6 @@ const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const express = require("express");
const routers = require("../lib/ai-routers");
const lanesLib = require("../lib/lanes");
const { applyRouterToLane } = require("../lib/router-apply");
const { envOwned } = require("../lib/settings-env");
const settingsRouter = require("../routes/settings");
@@ -97,27 +90,13 @@ describe("/api/settings/codex-home", () => {
}
});
it("switches, persists, and re-writes every codex lane's router layer into the new home", async () => {
const cwd = path.join(ROOT, "lane");
fs.mkdirSync(cwd, { recursive: true });
const { name } = routers.createRouter({
label: "9Router",
baseUrl: "http://localhost:20128/v1",
apiKey: "sk-secret-value",
model: "Highest",
});
const lane = lanesLib.createLane({ title: "c", cwd, tool: "codex", router_profile: name });
applyRouterToLane(lane, name);
assert.ok(fs.existsSync(path.join(process.env.CODEX_HOME, `${name}.config.toml`)));
it("switches and persists", async () => {
const next = path.join(ROOT, "codex-b");
fs.mkdirSync(next);
const res = await request("PUT", "/api/settings/codex-home", { path: next });
assert.equal(res.status, 200);
assert.equal(res.body.codex_home, next);
assert.deepEqual(res.body.routers, { updated: 1, failed: [] });
assert.equal(process.env.CODEX_HOME, next);
assert.ok(fs.existsSync(path.join(next, `${name}.config.toml`)));
assert.match(
fs.readFileSync(process.env.AGENTHUB_SETTINGS_FILE, "utf8"),
new RegExp(`^CODEX_HOME=${next}$`, "m")
@@ -136,13 +115,4 @@ describe("/api/settings/codex-home", () => {
assert.equal(res.status, 403);
assert.notEqual(process.env.CODEX_HOME, next);
});
it("a CLAUDE_HOME change names the lanes whose router the new store lacks", async () => {
const next = path.join(ROOT, "claude-b");
fs.mkdirSync(next);
const res = await request("PUT", "/api/settings/claude-home", { path: next });
assert.equal(res.status, 200);
assert.equal(res.body.routers.missing.length, 1);
assert.match(res.body.routers.missing[0], /\(c\): 9router/i);
});
});