physical_byte_agent/tests/persistent-shell.test.ts
d-robotics 06a19a61e8 refactor: 重构为生产级 pi Agent 项目(散装脚本 → npm 库包 + 单一 barrel 装配)
- 工程形态:@d-robotics/physical-byte-agent npm 库包
  - 单一 barrel src/extensions/index.ts 装配 21 域扩展(package.json pi.extensions 清单 + .pi/extensions/index.ts 重导出,pi 自动加载)
  - src/agent.ts PhysicalByteAgent(launch() 程序化调 createAgentSession + verifyAssembly() 离线自检)
  - bin/pba.ts CLI、models.json(glm-5.2 条目)、README.md、AGENTS.md
- 命名:全部域命名(glm-provider/safety-gate/flash/jtag-debugger/loop-orchestrator…),去掉 F 编号
- 架构:内联逻辑 + 顶层仅 import type(esbuild 擦除)+ 工厂内动态 import defineTool/Type
  - 逻辑离线可单测(不解析 pi),工厂在真 pi 内装配;fail-closed 语义保留
- 两命门:glm-provider.ts buildGlmModelConfig()(thinkingFormat:qwen + maxTokens:8192 + thinkingLevelMap 全 null)+ detectEmptyOutput();normalizeHexArg() + makeHexNormalizingPrepareArguments()
- 验证:tsc --noEmit 0 错(对 src/types/pi.d.ts 类型镜像)+ vitest 732 用例/21 文件全绿 + tsx 离线装配冒烟 21 扩展全就位
- 密钥铁律:grep sk-nAm 在 src/tests/bin/.pi = 0,key 全程 ${DROBOTICS_LLM_KEY} 占位

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-13 19:54:20 +08:00

318 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, it, expect } from "vitest";
import {
PShellPool,
buildSentinelCommand,
parseSentinelOutput,
PSHELL_SENTINEL,
type PShellSendResult,
} from "../src/extensions/persistent-shell.js";
import type { ExecFn, ExecResult } from "../src/shared/types.js";
/** 构造一个 mock ExecFn:直接把命令"执行"成带哨兵的 stdout。 */
function makeMockExec(reply: (cmd: string) => string): ExecFn {
return async (command: string) => {
const out = reply(command);
return { stdout: out, stderr: "", exitCode: 0 } as ExecResult;
};
}
describe("persistent-shell sentinel — buildSentinelCommand", () => {
it("给命令追加哨兵 + exitCode 回显", () => {
const c = buildSentinelCommand("break main");
expect(c).toBe(`break main; echo "${PSHELL_SENTINEL}$?"`);
});
it("空命令也安全(仅回显哨兵)", () => {
const c = buildSentinelCommand("");
expect(c).toBe(`echo "${PSHELL_SENTINEL}$?"`);
});
it("尾部空白被 trim", () => {
const c = buildSentinelCommand("ls -la\n");
expect(c).toBe(`ls -la; echo "${PSHELL_SENTINEL}$?"`);
});
});
describe("persistent-shell sentinel — parseSentinelOutput", () => {
it("解析正常 stdout + exit 0", () => {
const raw = `Breakpoint 1 at 0x...\n${PSHELL_SENTINEL}0\n`;
const p = parseSentinelOutput(raw);
expect(p.found).toBe(true);
expect(p.exitCode).toBe(0);
expect(p.stdout).toBe("Breakpoint 1 at 0x...");
});
it("解析非零 exitCode", () => {
const raw = `err\n${PSHELL_SENTINEL}127\n`;
const p = parseSentinelOutput(raw);
expect(p.exitCode).toBe(127);
expect(p.stdout).toBe("err");
});
it("兼容 PTY 的 \\r 混杂", () => {
const raw = `out\r\n${PSHELL_SENTINEL}0\r\n`;
const p = parseSentinelOutput(raw);
expect(p.found).toBe(true);
expect(p.exitCode).toBe(0);
});
it("未找到哨兵 → found=false exitCode=null(fail-closed)", () => {
const p = parseSentinelOutput("partial output, no sentinel");
expect(p.found).toBe(false);
expect(p.exitCode).toBeNull();
expect(p.stdout).toBe("partial output, no sentinel");
});
it("null 输入安全", () => {
const p = parseSentinelOutput(null as unknown as string);
expect(p.found).toBe(false);
});
});
describe("persistent-shell PShellPool — open/close/list", () => {
it("open 返回非空 id", () => {
const pool = new PShellPool();
const id = pool.open();
expect(typeof id).toBe("string");
expect(id.length).toBeGreaterThan(0);
expect(pool.has(id)).toBe(true);
});
it("open 接受自定义 id 生成器(确定性 id)", () => {
let n = 0;
const pool = new PShellPool({ idGenerator: () => `fixed-${++n}` });
expect(pool.open()).toBe("fixed-1");
expect(pool.open()).toBe("fixed-2");
});
it("close 释放会话", () => {
const pool = new PShellPool();
const id = pool.open();
expect(pool.close(id)).toBe(true);
expect(pool.has(id)).toBe(false);
});
it("close 不存在的 id 返回 false 不抛", () => {
const pool = new PShellPool();
expect(pool.close("nope")).toBe(false);
});
it("list 列出全部会话(按创建顺序)", () => {
const pool = new PShellPool();
pool.open({ id: "a" });
pool.open({ id: "b" });
const all = pool.list();
expect(all.map((s) => s.id)).toEqual(["a", "b"]);
expect(all[0]).toMatchObject({ id: "a", busy: false });
});
it("closeAll 清空全部并返回 id 列表", () => {
const pool = new PShellPool();
pool.open({ id: "a" });
pool.open({ id: "b" });
const closed = pool.closeAll();
expect(closed.sort()).toEqual(["a", "b"]);
expect(pool.list()).toHaveLength(0);
});
it("get 投影公开字段,不泄露 pending/cwd", () => {
const pool = new PShellPool({ defaultCwd: "/work" });
const id = pool.open();
const s = pool.get(id);
expect(s).toBeDefined();
expect(s).toHaveProperty("createdAt");
expect(s).toHaveProperty("busy");
// 不应包含内部字段
expect(s).not.toHaveProperty("pending");
expect(s).not.toHaveProperty("cwd");
});
});
describe("persistent-shell PShellPool — send", () => {
it("send 在未知 session 上 fail-closed", async () => {
const pool = new PShellPool();
const r = await pool.send("ghost", "ls", makeMockExec(() => `${PSHELL_SENTINEL}0\n`));
expect(r.ok).toBe(false);
expect(r.error).toBe("session-not-found");
});
it("send 执行命令并解析 stdout/exitCode", async () => {
const pool = new PShellPool();
const id = pool.open();
const r = await pool.send(id, "echo hello", makeMockExec(() => `hello\n${PSHELL_SENTINEL}0\n`));
expect(r.ok).toBe(true);
expect(r.stdout).toBe("hello");
expect(r.exitCode).toBe(0);
// lastCommand 记录
expect(pool.get(id)?.lastCommand).toBe("echo hello");
});
it("send 传非零 exitCode", async () => {
const pool = new PShellPool();
const id = pool.open();
const r: PShellSendResult = await pool.send(
id,
"false",
makeMockExec(() => `${PSHELL_SENTINEL}1\n`),
);
expect(r.ok).toBe(true);
expect(r.exitCode).toBe(1);
});
it("execFn 抛错(超时)→ ok=false error=timeout,会话不锁死", async () => {
const pool = new PShellPool();
const id = pool.open();
const execFn = async () => {
throw new Error("command timed out after 1000ms");
};
const r = await pool.send(id, "sleep 100", execFn, { timeoutMs: 1000 });
expect(r.ok).toBe(false);
expect(r.error).toBe("timeout");
expect(pool.isBusy(id)).toBe(false); // 未锁死
});
it("哨兵缺失 → ok=false error=sentinel-missing(不信伪完成)", async () => {
const pool = new PShellPool();
const id = pool.open();
const r = await pool.send(id, "hang", makeMockExec(() => "never finishes..."));
expect(r.ok).toBe(false);
expect(r.error).toBe("sentinel-missing");
});
it("execFn 抛非超时错 → error=exec-failed", async () => {
const pool = new PShellPool();
const id = pool.open();
const execFn = async () => {
throw new Error("spawn ENOENT");
};
const r = await pool.send(id, "nope", execFn);
expect(r.ok).toBe(false);
expect(r.error).toBe("exec-failed");
expect(pool.isBusy(id)).toBe(false);
});
});
describe("persistent-shell PShellPool — busy reject(默认 fail-closed)", () => {
it("busy 时 send 被拒绝", async () => {
const pool = new PShellPool({ busyPolicy: "reject" });
const id = pool.open();
// 用一个 block 的 execFn 模拟 gdb 长会话占用
let release: () => void = () => {};
const block = new Promise<void>((res) => {
release = res;
});
const execFn = async () => {
await block;
return { stdout: `${PSHELL_SENTINEL}0\n`, stderr: "", exitCode: 0 } as ExecResult;
};
const inFlight = pool.send(id, "run", execFn);
// 等一拍让上面进入 busy
await Promise.resolve();
expect(pool.isBusy(id)).toBe(true);
const r = await pool.send(id, "info breakpoints", makeMockExec(() => `${PSHELL_SENTINEL}0\n`));
expect(r.ok).toBe(false);
expect(r.error).toBe("busy");
release();
const done = await inFlight;
expect(done.ok).toBe(true);
expect(pool.isBusy(id)).toBe(false);
});
});
describe("persistent-shell PShellPool — busy queue", () => {
it("busy 时 send 排队,当前完成后 drain 执行", async () => {
const pool = new PShellPool({ busyPolicy: "queue" });
const id = pool.open();
let release: () => void = () => {};
const block = new Promise<void>((res) => {
release = res;
});
const execFn = async (command: string) => {
// 第一条命令 block;后续 drain 的命令立即返回
if (command.includes("run")) {
await block;
}
return { stdout: `ok\n${PSHELL_SENTINEL}0\n`, stderr: "", exitCode: 0 } as ExecResult;
};
const first = pool.send(id, "run", execFn);
await Promise.resolve();
expect(pool.isBusy(id)).toBe(true);
const queued = await pool.send(id, "info breakpoints", execFn);
expect(queued.ok).toBe(false);
expect(queued.queued).toBe(true);
expect(queued.error).toBe("busy");
release();
const done = await first;
expect(done.ok).toBe(true);
// 让 drain 的微任务/await 跑完
await new Promise((res) => setTimeout(res, 30));
// 排队命令已 drain,lastCommand 更新为后一条
expect(pool.get(id)?.lastCommand).toBe("info breakpoints");
expect(pool.isBusy(id)).toBe(false);
});
it("close 会话时丢弃待执行队列", () => {
const pool = new PShellPool({ busyPolicy: "queue" });
const id = pool.open();
// 直接构造 pending(不真实执行,只验证 close 清空不抛)
expect(pool.close(id)).toBe(true);
expect(pool.has(id)).toBe(false);
});
});
describe("persistent-shell PShellPool — markBusy(gdb/openocd 长会话)", () => {
it("markBusy 标记后 send 被拒(reject 策略)", async () => {
const pool = new PShellPool();
const id = pool.open();
expect(pool.markBusy(id, true)).toBe(true);
expect(pool.isBusy(id)).toBe(true);
const r = await pool.send(id, "ls", makeMockExec(() => `${PSHELL_SENTINEL}0\n`));
expect(r.ok).toBe(false);
expect(r.error).toBe("busy");
// 释放
pool.markBusy(id, false);
expect(pool.isBusy(id)).toBe(false);
});
it("markBusy 未知 id 返回 false", () => {
const pool = new PShellPool();
expect(pool.markBusy("nope", true)).toBe(false);
});
});
describe("persistent-shell PShellPool — sweepIdle 回收", () => {
it("idle 超时被回收", () => {
const pool = new PShellPool();
const id = pool.open();
// lastActivityAt 是 createdAt;sweepIdle(now=now+11min) 会判定 createdAt 距 now 超过 idleMs。
const future = Date.now() + 11 * 60 * 1000;
const closed = pool.sweepIdle(future, 10 * 60 * 1000);
expect(closed).toEqual([id]);
expect(pool.has(id)).toBe(false);
});
it("busy 会话不回收(gdb/openocd 正占用)", () => {
const pool = new PShellPool();
const id = pool.open();
pool.markBusy(id, true);
const future = Date.now() + 11 * 60 * 1000;
const closed = pool.sweepIdle(future, 10 * 60 * 1000);
expect(closed).toEqual([]);
expect(pool.has(id)).toBe(true);
});
it("未超时不回收", () => {
const pool = new PShellPool();
const id = pool.open();
const closed = pool.sweepIdle(Date.now() + 60 * 1000, 10 * 60 * 1000);
expect(closed).toEqual([]);
expect(pool.has(id)).toBe(true);
});
});