Files
my-pi/pi-permission-system/test/authority/local-user-authorizer.test.ts
T
云服务部-叶林立andDevin <158243242+devin-ai-integration[bot]@users.noreply.github.com> 7e6a8faae1 feat(pi-permission-system): AutoReview 改为跟随主模型的对话式工具调用审查
AutoReview:

- 审查器回到 Codex Guardian 风格的对话式审查,默认跟随会话当前主模型
  (每次审查实时读取 ctx.model);provider/model 必须同时设置才固定审查
  模型,只设其一视为配置错误并转人工。
- 结论只通过 approve / reject 两个工具给出,参数仅 reason;不强制
  toolChoice,正文文本(即使是合法 JSON)一律忽略。
- approve 自动放行;reject 转人工并在弹窗显示理由(标注模型生成)。
  超时、Provider 错误、截断、未调用工具、多次调用、参数无效等异常同样
  转人工,并附固定的系统说明;用户按 Esc 中止时直接拒绝。
- 模型调用改为 modelRegistry.streamSimple(...).result():Pi 1.3.0 面向
  扩展的 ModelRegistry 没有 completeSimple,原写法在真实环境中每次都会
  转人工。
- 对话记录保留可信度标注;工具结果在有更短的 pi-compaction 摘要时替换
  为摘要;token 估算改为非 ASCII 字符按 1 token 计;预算可配置。
- 同一条用户消息内完全相同的请求只缓存 approve 结论。
- 默认 reasoning low、总超时 30 秒、最多 2 次尝试、maxOutputTokens 4000。

删除:

- 未发布过的 TypeSafe Jev 分类器实现、DenialCircuitBreaker。
- 整个 annotator 机制(model-explanation、注册表、registerAnnotator、
  provider-timeout);annotators 配置键保留为已弃用并忽略,避免旧配置
  被拒绝。

测试:

- 新增 reviewer / transcript / 弹窗说明 / 默认配置测试;清理重复、恒真
  或只测实现细节的旧测试。
- 使用 deepseek-v4.1-flash 实测 5 个场景各 5 次,25 次结论全部符合预期。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-19 01:54:17 -07:00

324 lines
9.5 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { LocalUserAuthorizer } from "#src/authority/local-user-authorizer";
import type { PermissionPromptDecision } from "#src/authority/permission-dialog";
import type { requestPermissionDecision } from "#src/authority/permission-prompt-component";
import type { PromptPermissionDetails } from "#src/authority/permission-prompter";
import { DECIDED_BY_HUMAN } from "#test/helpers/decision-fixtures";
import {
makePromptDetails,
makePromptPayload,
} from "#test/helpers/prompt-details-fixtures";
import { makePromptPreferences } from "#test/helpers/prompt-view-fixtures";
// ── Helpers ─────────────────────────────────────────────────────────────────
/**
* This file's semantic defaults over the shared structural fixture: several
* cases assert `agentName` and `toolName` on a no-override call.
*/
function makeDetails(
overrides?: Partial<PromptPermissionDetails>,
): PromptPermissionDetails {
return makePromptDetails({
requestId: "req-123",
agentName: "test-agent",
toolName: "read",
...overrides,
});
}
/** A `PermissionPromptUi` double; the tool-expansion accessors go unused here. */
function makePromptUi() {
return {
select: vi.fn(),
input: vi.fn(),
custom: vi.fn(),
getToolsExpanded: vi.fn(() => false),
setToolsExpanded: vi.fn(),
};
}
function makeDeps(
overrides: {
requestPermissionDecision?: typeof requestPermissionDecision;
} = {},
) {
const events = {
emit: vi.fn(),
on: vi.fn().mockReturnValue(() => undefined),
};
const ui = makePromptUi();
const decisionFn =
overrides.requestPermissionDecision ??
vi.fn<typeof requestPermissionDecision>().mockResolvedValue({
approved: true,
state: "approved",
decidedBy: DECIDED_BY_HUMAN,
});
return {
deps: {
ui,
mode: "tui" as const,
events,
getPromptPreferences: () => makePromptPreferences(),
requestPermissionDecision: decisionFn,
},
events,
ui,
decisionFn,
};
}
// ── Tests ─────────────────────────────────────────────────────────────────
describe("LocalUserAuthorizer", () => {
it("emits a UI prompt event with normalized surface and value", async () => {
const { deps, events } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({
toolName: "bash",
command: "git push",
toolInputPreview: "git push",
}),
);
expect(events.emit).toHaveBeenCalledWith("permissions:ui_prompt", {
requestId: "req-123",
source: "tool_call",
surface: "bash",
value: "git push",
agentName: "test-agent",
request: makePromptPayload().request,
forwarding: null,
});
});
it("normalizes skill prompt events to the skill surface", async () => {
const { deps, events } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({
source: "skill_input",
toolName: undefined,
skillName: "deploy-helper",
}),
);
expect(events.emit).toHaveBeenCalledWith("permissions:ui_prompt", {
requestId: "req-123",
source: "skill_input",
surface: "skill",
value: "deploy-helper",
agentName: "test-agent",
request: makePromptPayload().request,
forwarding: null,
});
});
it("calls requestPermissionDecision with the threaded view, title, and payload", async () => {
const { deps, ui, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
const details = makeDetails();
await authorizer.authorize(details);
expect(decisionFn).toHaveBeenCalledWith(
{ mode: "tui", ui, ...makePromptPreferences() },
"Permission Required",
details.payload,
undefined,
);
});
it("passes the sessionLabel option when present", async () => {
const { deps, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({ sessionLabel: "Yes, for 'read' tool" }),
);
expect(decisionFn).toHaveBeenCalledWith(
expect.anything(),
expect.any(String),
expect.anything(),
{ sessionLabel: "Yes, for 'read' tool" },
);
});
it("emits the UI event before calling requestPermissionDecision", async () => {
const calls: string[] = [];
const events = {
emit: vi.fn(() => {
calls.push("emit");
}),
on: vi.fn().mockReturnValue(() => undefined),
};
const ui = makePromptUi();
const decisionFn = vi.fn<typeof requestPermissionDecision>(() => {
calls.push("dialog");
return Promise.resolve({
approved: true,
state: "approved",
decidedBy: DECIDED_BY_HUMAN,
});
});
const authorizer = new LocalUserAuthorizer({
ui,
mode: "tui",
events,
getPromptPreferences: () => makePromptPreferences(),
requestPermissionDecision: decisionFn,
});
await authorizer.authorize(makeDetails());
expect(calls).toEqual(["emit", "dialog"]);
});
describe("forwarded provenance", () => {
it("emits a non-degraded forwarded event with populated forwarding and the child's display projection", async () => {
const { deps, events } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({
source: "tool_call",
agentName: "Explore",
surface: "bash",
value: "git push",
forwarding: {
requesterAgentName: "Explore",
requesterSessionId: "child-session",
},
}),
);
expect(events.emit).toHaveBeenCalledWith("permissions:ui_prompt", {
requestId: "req-123",
source: "tool_call",
surface: "bash",
value: "git push",
agentName: "Explore",
request: makePromptPayload().request,
forwarding: {
requesterAgentName: "Explore",
requesterSessionId: "child-session",
},
});
});
it("uses the '(Subagent)' dialog title when the ask is forwarded", async () => {
const { deps, ui, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
const details = makeDetails({
forwarding: {
requesterAgentName: "Explore",
requesterSessionId: "child-session",
},
});
await authorizer.authorize(details);
expect(decisionFn).toHaveBeenCalledWith(
{ mode: "tui", ui, ...makePromptPreferences() },
"Permission Required (Subagent)",
details.payload,
undefined,
);
});
it("offers a sessionScope when the forwarded ask carries a suggestion", async () => {
const { deps, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({
toolName: "bash",
command: "git push",
forwarding: {
requesterAgentName: "Explore",
requesterSessionId: "child-session",
},
sessionApproval: { surface: "bash", patterns: ["git *"] },
}),
);
expect(decisionFn).toHaveBeenCalledWith(
expect.anything(),
"Permission Required (Subagent)",
expect.anything(),
{
sessionScope: {
subagentLabel: "This subagent ('Explore') only",
servingSessionLabel:
'The whole session — allow bash "git *" for parent and all subagents',
},
},
);
});
it("offers no sessionScope for a forwarded ask without a suggestion", async () => {
const { deps, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
await authorizer.authorize(
makeDetails({
forwarding: {
requesterAgentName: "Explore",
requesterSessionId: "child-session",
},
}),
);
expect(decisionFn).toHaveBeenCalledWith(
expect.anything(),
expect.any(String),
expect.anything(),
undefined,
);
});
});
describe("defer notes", () => {
it("forwards chain-supplied deferNotes into the request options", async () => {
const { deps, decisionFn } = makeDeps();
const authorizer = new LocalUserAuthorizer(deps);
const deferNotes = [
{ origin: "system" as const, text: "fidelity uncertain" },
{ origin: "model" as const, text: "user forbade it" },
];
await authorizer.authorize(makeDetails({ deferNotes }));
expect(decisionFn).toHaveBeenCalledWith(
expect.anything(),
expect.any(String),
expect.anything(),
{ deferNotes },
);
});
});
it("returns the decision from requestPermissionDecision", async () => {
const decision: PermissionPromptDecision = {
approved: false,
state: "denied",
decidedBy: DECIDED_BY_HUMAN,
};
const { deps } = makeDeps({
requestPermissionDecision: vi
.fn<typeof requestPermissionDecision>()
.mockResolvedValue(decision),
});
const authorizer = new LocalUserAuthorizer(deps);
const result = await authorizer.authorize(makeDetails());
expect(result).toEqual(decision);
});
});