Файли
openidea/src/features/agents/agents.test.ts
T
l0ng-ai e5c5915f2e feat(agents): logos for every agent in the ACP registry (#5884)
Every agent in the ACP registry now shows its own logo instead of the generic agents icon. A provider's logo is looked up by id, with legacy and ACP-adapter ids (claude-acp, codex-acp, kimi-code, opencode-v2) sharing their agent's logo and Hermes profiles using Hermes'. The registry logos are listed in THIRD_PARTY_LICENSES.md.
2026-11-25 19:55:06 +08:00

641 рядки
22 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { AgentConfigOption, AgentEntry, AgentStatus, AgentTask } from "@/bindings";
import {
applyCompletion,
approvalDefaults,
atEdgeLine,
bypassDefaults,
cursorModelDefaults,
isContextOption,
isPerModelOption,
modelConfigOptions,
canSend,
completionAt,
isPathQuery,
resolveTyped,
imageFromDataUrl,
mainOptions,
matchCommands,
hasMention,
mentionOf,
modeIcon,
nextValue,
recall,
toPrompt,
mergeMatches,
messageTokens,
fenced,
fencedBlocks,
fenceLabel,
pastedPaths,
looksLikeTrace,
placesInText,
retryParts,
usageLabel,
limitLabel,
costLabel,
workTime,
} from "./composerModel";
import {
age,
appendEntry,
branchLabel,
entriesKey,
findSubagent,
groupTasks,
providerIcon,
subagentTitle,
turnNumbers,
upsertEntry,
type SubagentEntry,
} from "./model";
import { markdownHtml } from "./Markdown";
function task(id: string, status: AgentStatus, updatedMs: number): AgentTask {
return {
id,
title: id,
provider: "claude",
model: null,
status,
isolation: "worktree",
cwd: "/w",
branch: `agent/${id}`,
base: "main",
baseCommit: "abc",
error: null,
createdMs: 0,
updatedMs,
config: [],
commands: [],
usage: null,
queue: [],
};
}
const option = (category: string, values: string[], current: string | null): AgentConfigOption => ({
id: category,
name: category,
description: null,
category,
current,
values: values.map((value) => ({ value, name: value, description: null })),
via: "option",
});
describe("providerIcon", () => {
it("uses the agent's logo, shared by its legacy and adapter ids", () => {
expect(providerIcon("devin")).toBe("agent-devin");
expect(providerIcon("amp-acp")).toBe("agent-amp-acp");
expect(providerIcon("claude-acp")).toBe("agent-claude");
expect(providerIcon("codex-acp")).toBe("agent-codex");
expect(providerIcon("kimi-code")).toBe("agent-kimi");
expect(providerIcon("opencode-v2")).toBe("agent-opencode");
expect(providerIcon("hermes-work")).toBe("agent-hermes");
});
it("falls back to the generic agents icon", () => {
expect(providerIcon("my-agent")).toBe("toolwindow-agents");
});
});
describe("fenced blocks", () => {
it("finds closed blocks, a longer fence holding backticks", () => {
const text = fenced("a ``` b\n```", "terminal zsh");
expect(text).toBe("````terminal zsh\na ``` b\n```\n````");
expect(fencedBlocks(["x", ...text.split("\n"), "```ts", "open"])).toEqual([
{ open: 1, close: 4, info: "terminal zsh" },
]);
expect(fenceLabel("terminal zsh")).toEqual({ kind: "terminal", label: "zsh", language: null });
expect(fenceLabel("trace")).toEqual({ kind: "trace", label: "", language: null });
expect(fenceLabel("ts")).toEqual({ kind: "code", label: "ts", language: "ts" });
});
});
describe("pasted traces", () => {
const node =
"TypeError: x is undefined\n at fetchUser (/p/src/api/client.ts:12:5)\n at node_modules/lib/x.js:3:1";
const python =
'Traceback (most recent call last):\n File "/p/app/main.py", line 7, in <module>\n run()\nValueError: bad';
const rust = "thread 'main' panicked at src/main.rs:4:5:\nboom";
it("recognises stack traces, not prose", () => {
expect([node, python, rust].map(looksLikeTrace)).toEqual([true, true, true]);
expect(looksLikeTrace("see src/a.ts:3\nand more")).toBe(false);
expect(looksLikeTrace("Error: one line")).toBe(false);
});
it("finds the places a trace names, leaving dependencies out", () => {
expect(placesInText(node)).toEqual([{ path: "/p/src/api/client.ts", line: 12 }]);
expect(placesInText(python)).toEqual([{ path: "/p/app/main.py", line: 7 }]);
expect(placesInText(rust)).toEqual([{ path: "src/main.rs", line: 4 }]);
expect(placesInText("a.ts:1 a.ts:1 b.ts:2", 1)).toEqual([{ path: "a.ts", line: 1 }]);
});
});
describe("pastedPaths", () => {
it("reads absolute paths with lines, quotes and file URLs, one per line", () => {
expect(pastedPaths("/a/b.ts:10-20\n '/a/c d.ts' \nfile:///a/%E4%B8%AD.ts\n/a/dir/\n/a/e.ts:3:7")).toEqual([
{ path: "/a/b.ts", lines: { from: 10, to: 20 } },
{ path: "/a/c d.ts" },
{ path: "/a/中.ts" },
{ path: "/a/dir" },
{ path: "/a/e.ts", lines: { from: 3, to: 3 } },
]);
expect(pastedPaths("C:\\work\\a.ts:4")).toEqual([{ path: "C:\\work\\a.ts", lines: { from: 4, to: 4 } }]);
expect(pastedPaths("/a/b.ts\nnot a path")).toBeNull();
expect(pastedPaths("see /a/b.ts")).toBeNull();
});
});
describe("mergeMatches", () => {
it("ranks folders among files by score, files first on a tie", () => {
const merged = mergeMatches(
[
{ path: "/p/src/agents.ts", relPath: "src/agents.ts", score: 50 },
{ path: "/p/x.ts", relPath: "x.ts", score: 10 },
],
[
{ path: "/p/src/agents", relPath: "src/agents/", score: 50 },
{ path: "/p/docs", relPath: "docs/", score: 70 },
],
3,
);
expect(merged).toEqual([
{ path: "/p/docs", rel: "docs", dir: true, score: 70, indices: [] },
{
path: "/p/src/agents.ts",
rel: "src/agents.ts",
dir: false,
score: 50,
indices: [],
},
{
path: "/p/src/agents",
rel: "src/agents",
dir: true,
score: 50,
indices: [],
},
]);
});
});
describe("agent composer", () => {
it("leaves punctuation after a reference or command to the text", () => {
expect(messageTokens("in @src/a.ts:3-8, keep @src/retry/。then /review.")).toEqual([
{ kind: "text", value: "in " },
{ kind: "file", value: "@src/a.ts:3-8" },
{ kind: "text", value: ", keep " },
{ kind: "file", value: "@src/retry/" },
{ kind: "text", value: "。then " },
{ kind: "command", value: "/review" },
{ kind: "text", value: "." },
]);
});
it("completes @files and /commands anywhere at a word boundary", () => {
expect(completionAt("fix @src/le", 11)).toEqual({
kind: "file",
query: "src/le",
from: 4,
to: 11,
});
expect(completionAt("/rev", 4)).toEqual({
kind: "command",
query: "rev",
from: 0,
to: 4,
});
expect(completionAt("run /rev", 8)).toEqual({
kind: "command",
query: "rev",
from: 4,
to: 8,
});
expect(completionAt("a@b", 3)).toBeNull();
const c = completionAt("see @le and", 7)!;
expect(applyCompletion("see @le and", c, "@src/lexer.rs")).toEqual({
text: "see @src/lexer.rs and",
caret: 18,
});
const cmds = [
{ name: "init", description: "", hint: null },
{ name: "review", description: "", hint: null },
{ name: "pr-review", description: "", hint: null },
];
expect(matchCommands(cmds, "rev").map((c) => c.name)).toEqual(["review", "pr-review"]);
});
it("matches commands by prefix, plugin name, substring, then letters in order", () => {
const cmds = ["triage", "verify", "issue-fix", "brooks-lint:brooks-review", "pr-review", "init"].map((name) => ({
name,
description: "",
hint: null,
}));
const names = (q: string) => matchCommands(cmds, q).map((c) => c.name);
expect(names("trig")).toEqual(["triage"]);
expect(names("brooks-r")).toEqual(["brooks-lint:brooks-review"]);
expect(names("rev")).toEqual(["brooks-lint:brooks-review", "pr-review"]);
expect(names("if")).toEqual(["verify", "issue-fix"]);
expect(names("xyz")).toEqual([]);
expect(names("")).toHaveLength(cmds.length);
});
it("keeps all commands and skills and ranks matches within each source", () => {
const cmds = Array.from({ length: 600 }, (_, i) => ({
name: `item-${i}`,
description: "",
hint: null,
source: i % 2 ? ("command" as const) : ("skill" as const),
}));
const all = matchCommands(cmds, "");
expect(all).toHaveLength(600);
expect(all.slice(0, 300)).toEqual(cmds.filter((c) => c.source === "command"));
expect(all.slice(300)).toEqual(cmds.filter((c) => c.source === "skill"));
const mixed = [
{ ...cmds[0]!, name: "pre-review" },
{ ...cmds[1]!, name: "pre-review" },
{ ...cmds[0]!, name: "review" },
{ ...cmds[1]!, name: "review" },
];
expect(matchCommands(mixed, "rev")).toEqual([mixed[3], mixed[1], mixed[2], mixed[0]]);
expect(matchCommands(mixed, "missing")).toEqual([]);
});
it("sends only the files still mentioned", () => {
const prompt = toPrompt({
text: " look at @src/a.rs:3-5 and @b.rs ",
files: [
{ path: "/w/src/a.rs", rel: "src/a.rs" },
{ path: "/w/b.rs", rel: "b.rs" },
{ path: "/w/b.rs", rel: "b.rs" },
{ path: "/w/gone.rs", rel: "gone.rs" },
],
images: [],
});
expect(prompt).toEqual({
text: "look at @src/a.rs:3-5 and @b.rs",
files: ["/w/src/a.rs", "/w/b.rs"],
images: [],
});
expect(mentionOf("a.rs", { from: 3, to: 3 })).toBe("@a.rs:3");
expect(hasMention("see @a.rs:3 and", "@a.rs:3")).toBe(true);
expect(hasMention("see @a.rs:3-4", "@a.rs:3")).toBe(false);
expect(hasMention("see @a.rs:3", "@a.rs")).toBe(false);
expect(hasMention("@src/a.rs", "@a.rs")).toBe(false);
// A folder counts while `@src/` is left as typed, not once a file inside it was picked.
const folder = { path: "/w/src", rel: "src/" };
expect(toPrompt({ text: "explain @src/ please", files: [folder], images: [] }).files).toEqual(["/w/src"]);
expect(toPrompt({ text: "explain @src/", files: [folder], images: [] }).files).toEqual(["/w/src"]);
expect(toPrompt({ text: "explain @src/a.rs", files: [folder], images: [] }).files).toEqual([]);
expect(canSend({ text: " ", files: [], images: [] })).toBe(false);
const video = {
path: "/home/me/clip.mov",
rel: "clip.mov",
attached: true,
};
expect(toPrompt({ text: "what happens here?", files: [video], images: [] }).files).toEqual(["/home/me/clip.mov"]);
expect(canSend({ text: " ", files: [video], images: [] })).toBe(true);
});
it("recalls history from the edge lines only", () => {
const h = ["newest", "older"];
expect(recall(h, -1, -1)).toBe(0);
expect(recall(h, 0, -1)).toBe(1);
expect(recall(h, 1, -1)).toBeNull();
expect(recall(h, 0, 1)).toBe(-1);
expect(recall(h, -1, 1)).toBeNull();
expect(atEdgeLine("a\nb", 1, -1)).toBe(true);
expect(atEdgeLine("a\nb", 3, -1)).toBe(false);
expect(atEdgeLine("a\nb", 1, 1)).toBe(false);
});
it("defaults Cursor fast mode off even when context precedes fast", () => {
const context = option("model_config", ["256k", "500k"], "256k");
context.id = "context";
context.name = "Context";
const fast = option("model_config", ["false", "true"], "true");
fast.id = "fast";
fast.name = "Fast";
expect(isContextOption("context")).toBe(true);
expect(isPerModelOption(context)).toBe(true);
expect(isPerModelOption(fast)).toBe(true);
expect(cursorModelDefaults("cursor", [context, fast])).toEqual({ fast: "false" });
expect(cursorModelDefaults("claude", [context, fast])).toEqual({});
expect(modelConfigOptions([context, fast]).map((o) => o.id)).toEqual(["context", "fast"]);
});
it("resolves bypass and ask approval defaults across mode, permissions, and approval options", () => {
const codexMode: AgentConfigOption = {
...option("mode", ["read-only", "ask", "auto", "full-access"], "full-access"),
defaultValue: "auto",
};
const permissions: AgentConfigOption = {
...option("allow_all", ["off", "on"], "off"),
category: "permissions",
defaultValue: "off",
};
const approval: AgentConfigOption = {
...option("openidea.cursor.approval", ["ask", "bypass"], "bypass"),
category: "approval",
defaultValue: "ask",
};
expect(approvalDefaults([codexMode, permissions, approval], "bypass")).toEqual({
mode: "full-access",
allow_all: "on",
"openidea.cursor.approval": "bypass",
});
expect(approvalDefaults([codexMode, permissions, approval], "ask")).toEqual({
mode: "auto",
"openidea.cursor.approval": "ask",
});
});
it("picks the main settings and cycles the mode", () => {
const config = [option("fast", ["on"], null), option("mode", ["ask", "code"], "code"), option("model", ["m"], "m")];
expect(mainOptions(config).map((o) => o.id)).toEqual(["model", "mode", "fast"]);
expect(nextValue(config[1]!)).toBe("ask");
const permissions = option("allow_all", ["off", "on"], "off");
permissions.category = "permissions";
expect(mainOptions([...config, permissions]).map((o) => o.id)).toEqual(["model", "mode", permissions.id, "fast"]);
const collaboration = option("collaboration_mode", ["default", "plan"], "default");
expect(mainOptions([...config, collaboration]).map((o) => o.id)).toEqual([
"model",
"mode",
collaboration.id,
"fast",
]);
const approvals = {
...option("openidea.cursor.approval", ["ask", "bypass"], "ask"),
category: "approval",
};
expect(mainOptions([...config, permissions, approvals]).map((o) => o.id)).toEqual([
"model",
"mode",
permissions.id,
approvals.id,
"fast",
]);
expect(
[
"default",
"acceptEdits",
"plan",
"auto",
"bypassPermissions",
"auto_edit",
"read-only",
"x",
"https://agentclientprotocol.com/protocol/session-modes#agent",
"https://agentclientprotocol.com/protocol/session-modes#autopilot",
].map(modeIcon),
).toEqual(["lock", "edit", "todo", "run", "unlock", "edit", "eye", "lock", "run", "run"]);
expect(bypassDefaults([...config, permissions])).toEqual({
allow_all: "on",
});
expect(usageLabel({ used: 24_000, size: 200_000 })).toEqual({
short: "24k/200k (12%)",
percent: 12,
detail: "24k / 200k tokens",
});
expect(imageFromDataUrl("data:image/png;base64,AAA", "a.png")).toEqual({
mimeType: "image/png",
data: "AAA",
name: "a.png",
});
expect(imageFromDataUrl("data:text/plain;base64,AAA")).toBeNull();
});
});
describe("usage meters", () => {
it("formats token counts", () => {
expect(usageLabel({ used: 83_100, size: 1_000_000 }).detail).toBe("83.1k / 1M tokens");
});
it("names usage-limit windows and says when they reset", () => {
const hour = 3_600_000;
expect(
limitLabel(
{
window: "five_hour",
usedPercent: 19.4,
resetsMs: 2 * hour + 51 * 60_000,
},
0,
),
).toEqual({
short: "5h 19%",
percent: 19,
detail: "5-hour limit: 19% used, resets in 2h 51m",
});
expect(
limitLabel(
{
window: "seven_day",
usedPercent: 120,
resetsMs: 5 * 24 * hour + 3 * hour,
},
0,
).detail,
).toBe("Weekly limit: 100% used, resets in 5d 3h");
expect(limitLabel({ window: "spend_limit", usedPercent: 7, resetsMs: null }, 0)).toEqual({
short: "spend_limit 7%",
percent: 7,
detail: "spend_limit: 7% used",
});
});
it("formats the session cost", () => {
expect(costLabel({ amount: 0.4231, currency: "USD" })).toBe("$0.42");
expect(costLabel({ amount: 1.5, currency: "credits" })).toBe("1.50 credits");
});
it("adds up the time spent on turns", () => {
const user = (sentMs: number, doneMs: number | null): AgentEntry => ({
type: "user",
text: "",
attachments: [],
sentMs,
doneMs,
});
const entries = [user(0, 5_000), { type: "agent", text: "" } as AgentEntry, user(10_000, null)];
expect(workTime(entries, 12_000)).toBe(7_000);
expect(workTime(entries, null)).toBe(5_000);
});
});
describe("agents model", () => {
it("groups tasks by what they need, newest first", () => {
const groups = groupTasks([
task("a", "ready", 1),
task("b", "needsInput", 2),
task("c", "running", 3),
task("d", "starting", 4),
task("e", "ready", 5),
]);
expect(groups.map((g) => [g.status, g.tasks.map((t) => t.id)])).toEqual([
["needsInput", ["b"]],
["running", ["d", "c"]],
["ready", ["e", "a"]],
]);
});
it("upserts entries in place and refuses gaps", () => {
const a: AgentEntry = { type: "agent", text: "a" };
const b: AgentEntry = { type: "agent", text: "b" };
expect(upsertEntry([a], 0, b)).toEqual([b]);
expect(upsertEntry([a], 1, b)).toEqual([a, b]);
expect(upsertEntry([a], 3, b)).toBeNull();
});
it("appends streamed text from where the copy here stands", () => {
const u: AgentEntry = { type: "user", text: "q", attachments: [] };
const a: AgentEntry = { type: "agent", text: "He" };
expect(appendEntry([u, a], 1, 2, "llo")).toEqual([u, { type: "agent", text: "Hello" }]);
// Loaded while it streamed: part of the text is already here.
expect(appendEntry([u, { type: "agent", text: "Hel" }], 1, 2, "llo")?.[1]).toEqual({
type: "agent",
text: "Hello",
});
const whole = [u, { type: "agent", text: "Hello" } as AgentEntry];
expect(appendEntry(whole, 1, 2, "llo")).toBe(whole);
expect(appendEntry([u, { type: "agent", text: "H" }], 1, 2, "llo")).toBeNull();
expect(appendEntry([u, a], 0, 0, "x")).toBeNull();
expect(appendEntry([u, a], 2, 0, "x")).toBeNull();
});
it("finds subagent cards and keys their conversations apart", () => {
const card: SubagentEntry = {
type: "subagent",
id: "c1",
title: null,
description: "Find the lexer",
status: "running",
error: null,
prompt: null,
reply: null,
tools: 0,
activity: null,
startedMs: 0,
endedMs: null,
cancellable: false,
};
expect(findSubagent([{ type: "agent", text: "a" }, card], "c1")).toBe(card);
expect(findSubagent(undefined, "c1")).toBeUndefined();
expect(subagentTitle(card)).toBe("Find the lexer");
expect(subagentTitle({ ...card, title: "Explore" })).toBe("Explore");
expect(entriesKey("t", null)).toBe("t");
expect(entriesKey("t", "c1")).not.toBe(entriesKey("t", null));
});
it("formats labels", () => {
expect(branchLabel("agent/fix-lexer")).toBe("fix-lexer");
expect(branchLabel(null)).toBe("");
expect(age(0, 30_000)).toBe("now");
expect(age(0, 5 * 60_000)).toBe("5m");
expect(age(0, 3 * 3_600_000)).toBe("3h");
});
it("renders agent markdown without scripts", () => {
const html = markdownHtml("**bold** <img src=x onerror=alert(1)><script>alert(1)</script>");
expect(html).toContain("<strong>bold</strong>");
expect(html).not.toContain("onerror");
expect(html).not.toContain("<script");
});
it("gives the text of a list item with a nested list its own block", () => {
const html = markdownHtml("- **parent** text:\n - child\n- plain");
expect(html).toContain("<li><div><strong>parent</strong> text:</div><ul>");
expect(html).toContain("<li>child</li>");
expect(html).toContain("<li>plain</li>");
});
});
describe("turns", () => {
it("numbers the messages that start a turn, not those steered into one", () => {
const user = (text: string, steered = false): AgentEntry => ({
type: "user",
text,
attachments: [],
sentMs: null,
doneMs: null,
steered,
});
const entries: AgentEntry[] = [
user("first"),
{ type: "agent", text: "ok" },
user("also", true),
user("second"),
{ type: "agent", text: "done" },
];
expect([...turnNumbers(entries)]).toEqual([
[0, 0],
[3, 1],
]);
});
});
describe("retryParts", () => {
it("counts down to the next attempt and shows the limit when known", () => {
const retry = {
attempt: 3,
maxRetries: 10,
retryAtMs: 5_400,
error: "Connection error.",
};
expect(retryParts(retry, 1_000)).toEqual({ attempt: "3/10", wait: 5 });
expect(retryParts({ ...retry, maxRetries: null }, 9_000)).toEqual({
attempt: "3",
wait: 0,
});
});
});
describe("typed path references", () => {
it("tells a path from a search", () => {
for (const q of ["../", "..", "./a", "/etc", "../x/y"]) expect(isPathQuery(q)).toBe(true);
for (const q of ["", "src/le", ".gitignore", "a/../b"]) expect(isPathQuery(q)).toBe(false);
});
it("resolves against the task root", () => {
expect(resolveTyped("/r/idea", "../kalo/a.ts")).toBe("/r/kalo/a.ts");
expect(resolveTyped("/r/idea", "./src")).toBe("/r/idea/src");
expect(resolveTyped("/r/idea", "/etc/hosts")).toBe("/etc/hosts");
expect(resolveTyped("C:\\r\\idea", "../kalo/a.ts")).toBe("C:/r/kalo/a.ts");
expect(resolveTyped("C:\\r", "../../x")).toBe("C:/x");
});
});
describe("new task defaults", () => {
it("start a draft with the agent's defaults until the draft picks", async () => {
const { draftConfig } = await import("./store");
const option = (id: string, current: string, values: string[]) =>
({
id,
name: id,
description: null,
category: id,
current,
values: values.map((value) => ({
value,
name: value,
description: null,
})),
via: "option",
}) as AgentConfigOption;
const provider = {
id: "claude",
config: [option("model", "sonnet", ["sonnet", "opus"]), option("mode", "default", ["default", "plan"])],
} as unknown as Parameters<typeof draftConfig>[0];
const draft = {
provider: "claude",
config: {},
isolation: "local",
base: null,
} as unknown as Parameters<typeof draftConfig>[1];
const current = (d: typeof draft, defaults: Record<string, string>) =>
draftConfig(provider, d, defaults).map((o) => o.current);
expect(current(draft, { model: "opus", mode: "nope" })).toEqual(["opus", "default"]);
expect(current({ ...draft, config: { model: "sonnet" } }, { model: "opus" })).toEqual(["sonnet", "default"]);
});
});