Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

15.3 KB
Raw Blame
import { describe, expect, it } from "vitest";
import {
  applyCompletion,
  composeMentionPrompt,
  detectTrigger,
  findAgentMentions,
  findSkillMentions,
  fileReferenceLabel,
  formatCommandInsert,
  formatFileInsert,
  normalizeLargePasteThreshold,
  restoreInlineComposerFileReferenceTokens,
  rewriteIdeographicCommaTrigger,
  serializeComposerFileReferences,
  serializeInlineComposerFileReferences,
  splitComposerDirectoryPrompt,
  stripInlineComposerFileReferenceTokens,
} from "./composer-trigger.js";

it("serializes agent mentions and saved line references in the same draft", () => {
  const text = serializeInlineComposerFileReferences("\uE001 explain \uE002", [
    { path: "reviewer", kind: "agent", token: "\uE001" },
    { path: "/project/sample.txt", kind: "file", token: "\uE002", lineRange: { start: 2, end: 3 } },
  ]);
  expect(text).toContain("@reviewer explain /project/sample.txt (2:3)");
  expect(text).not.toContain("\uE001");
  expect(text).not.toContain("\uE002");
});

describe("splitComposerDirectoryPrompt", () => {
  const path = "/tmp/a & <b> &lt;";

  it("removes generated markers and guidance from old and current user messages", () => {
    const reference = { path, kind: "directory" };
    for (const content of [
      serializeInlineComposerFileReferences("before after", [reference]),
      serializeInlineComposerFileReferences("before \ue001after", [{ ...reference, token: "\ue001" }]),
    ]) {
      expect(splitComposerDirectoryPrompt(content)).toEqual({ text: "before after", paths: [path] });
    }
    expect(splitComposerDirectoryPrompt(serializeInlineComposerFileReferences("", [reference]))).toEqual({ text: "", paths: [path] });
  });

  it("keeps literal markup in the prompt body when the generated folder block is present", () => {
    const text = "Explain <dir>/tmp/example</dir>";
    expect(splitComposerDirectoryPrompt(text)).toEqual({ text, paths: [] });
    expect(splitComposerDirectoryPrompt(serializeInlineComposerFileReferences(text, [{ path, kind: "directory" }]))).toEqual({ text, paths: [path] });
  });
});

describe("detectTrigger — slash mode", () => {
  it("triggers on a bare slash at position 0", () => {
    expect(detectTrigger("/", 1)).toEqual({
      mode: "slash",
      query: "",
      tokenStart: 0,
      tokenEnd: 1,
    });
  });

  it("carries the typed query", () => {
    expect(detectTrigger("/rev", 4)).toMatchObject({ mode: "slash", query: "rev" });
  });

  it("does not trigger before the slash", () => {
    expect(detectTrigger("/rev", 0)).toBeNull();
  });

  it("closes once the first token has whitespace before the cursor", () => {
    expect(detectTrigger("/review src", 11)).toBeNull();
    expect(detectTrigger("/review ", 8)).toBeNull();
  });

  it("stays open when the cursor is inside the first token", () => {
    expect(detectTrigger("/review src", 4)).toMatchObject({
      mode: "slash",
      query: "rev",
      tokenEnd: 4,
    });
  });

  it("targets later slash tokens independently", () => {
    expect(detectTrigger("hi /cmd", 7)).toMatchObject({ tokenStart: 3, query: "cmd" });
    expect(detectTrigger("hi\n/cmd", 7)).toMatchObject({ tokenStart: 3, query: "cmd" });
    expect(detectTrigger("https://example.com", 8)).toBeNull();
  });
});

describe("rewriteIdeographicCommaTrigger", () => {
  it("turns a leading ideographic comma into the slash trigger", () => {
    expect(rewriteIdeographicCommaTrigger("、")).toBe("/");
    expect(rewriteIdeographicCommaTrigger("、rev")).toBe("/rev");
  });

  it("leaves the mark alone anywhere else in the draft", () => {
    expect(rewriteIdeographicCommaTrigger("你好、世界")).toBe("你好、世界");
    expect(rewriteIdeographicCommaTrigger("/cmd 、")).toBe("/cmd 、");
    expect(rewriteIdeographicCommaTrigger("")).toBe("");
  });

  it("opens the menu through the ordinary detector once rewritten", () => {
    const draft = rewriteIdeographicCommaTrigger("、rev");
    expect(detectTrigger(draft, draft.length)).toMatchObject({
      mode: "slash",
      query: "rev",
      tokenStart: 0,
    });
  });
});

describe("detectTrigger — file mode", () => {
  it("triggers on a bare @ at start", () => {
    expect(detectTrigger("@", 1)).toEqual({
      mode: "file",
      query: "",
      tokenStart: 0,
      tokenEnd: 1,
    });
  });

  it("triggers after whitespace and pi delimiters", () => {
    expect(detectTrigger("see @src/a", 10)).toMatchObject({
      mode: "file",
      query: "src/a",
      tokenStart: 4,
    });
    expect(detectTrigger("path=@conf", 10)).toMatchObject({ mode: "file", query: "conf" });
    expect(detectTrigger("a\t@x", 4)).toMatchObject({ mode: "file", query: "x" });
  });

  it("does not trigger on a mid-word @ (emails)", () => {
    expect(detectTrigger("mail [email protected]", 12)).toBeNull();
  });

  it("does not trigger when the cursor is outside the token", () => {
    expect(detectTrigger("@src ok", 7)).toBeNull();
  });

  it("supports the quoted form with spaces", () => {
    expect(detectTrigger('@"my file', 9)).toEqual({
      mode: "file",
      query: "my file",
      tokenStart: 0,
      tokenEnd: 9,
    });
    expect(detectTrigger('see @"a b/c', 11)).toMatchObject({
      mode: "file",
      query: "a b/c",
      tokenStart: 4,
    });
  });

  it("treats a just-opened quote as an empty query", () => {
    expect(detectTrigger('@"', 2)).toMatchObject({ mode: "file", query: "" });
  });

  it("closes after the quote is closed", () => {
    expect(detectTrigger('@"a b" next', 11)).toBeNull();
    expect(detectTrigger('@"a b" ', 7)).toBeNull();
  });

  it("keeps completing inside an inserted quoted directory", () => {
    const draft = '@"my dir/sr';
    expect(detectTrigger(draft, draft.length)).toMatchObject({
      mode: "file",
      query: "my dir/sr",
    });
  });

  it("returns null for out-of-range cursors", () => {
    expect(detectTrigger("@a", 5)).toBeNull();
    expect(detectTrigger("@a", -1)).toBeNull();
  });
});

describe("insert formatting", () => {
  it("formats commands with a trailing space", () => {
    expect(formatCommandInsert("review")).toBe("/review ");
  });

  it("formats plain files with a trailing space", () => {
    expect(formatFileInsert("src/a.ts", "file")).toBe("@src/a.ts ");
  });

  it("quotes files containing spaces", () => {
    expect(formatFileInsert("my file.md", "file")).toBe('@"my file.md" ');
  });

  it("leaves directories open for continued completion", () => {
    expect(formatFileInsert("src", "dir")).toBe("@src/");
    expect(formatFileInsert("my dir", "dir")).toBe('@"my dir/');
  });
});

describe("applyCompletion", () => {
  it("replaces the trigger token and moves the cursor", () => {
    const trigger = detectTrigger("see @sr tail", 7);
    expect(trigger).not.toBeNull();
    const result = applyCompletion(
      "see @sr tail",
      trigger!,
      formatFileInsert("src/a.ts", "file"),
    );
    expect(result.value).toBe("see @src/a.ts  tail");
    expect(result.cursor).toBe("see @src/a.ts ".length);
  });

  it("replaces a slash token from the start of the draft", () => {
    const trigger = detectTrigger("/rev", 4);
    const result = applyCompletion("/rev", trigger!, formatCommandInsert("review"));
    expect(result).toEqual({ value: "/review ", cursor: 8 });
  });

  it("chains directory completion into a deeper trigger", () => {
    const step1 = applyCompletion("@", detectTrigger("@", 1)!, formatFileInsert("src", "dir"));
    expect(step1.value).toBe("@src/");
    const next = detectTrigger(step1.value, step1.cursor);
    expect(next).toMatchObject({ mode: "file", query: "src/" });
  });
});

describe("compact file references", () => {
  it("derives leaf labels across path separators without changing unicode", () => {
    expect(fileReferenceLabel("src/components/Composer.tsx")).toBe("Composer.tsx");
    expect(fileReferenceLabel("C:\\work\\界面\\截图.png")).toBe("截图.png");
    expect(fileReferenceLabel("src/fallback.ts", "original name.ts")).toBe(
      "original name.ts",
    );
  });

  it("serializes canonical paths after the visible draft", () => {
    expect(
      serializeComposerFileReferences("inspect these", [
        { path: "src/a.ts" },
        { path: "/tmp/session scratch/image.png" },
      ]),
    ).toBe('inspect these\n@src/a.ts @"/tmp/session scratch/image.png"');
  });

  it("supports reference-only prompts and preserves duplicate paths", () => {
    expect(
      serializeComposerFileReferences("", [
        { path: "src/index.ts" },
        { path: "test/index.ts" },
      ]),
    ).toBe("@src/index.ts @test/index.ts");
  });

  it("resolves generated inline tokens in place and leaves chip references separate", () => {
    expect(
      serializeInlineComposerFileReferences("before @pasted-text.txt after", [
        { path: "/tmp/session/pasted/pasted-text.txt", token: "@pasted-text.txt" },
      ]),
    ).toBe("before @/tmp/session/pasted/pasted-text.txt after");
    expect(
      serializeComposerFileReferences("before @pasted-text.txt after", [
        { path: "/tmp/session/pasted/pasted-text.txt", token: "@pasted-text.txt" },
        { path: "src/a.ts" },
      ]),
    ).toBe(
      "before @/tmp/session/pasted/pasted-text.txt after\n@src/a.ts",
    );
  });

  it("resolves a plugin mark to the text it sends, never to a path", () => {
    const references = [
      { path: "", token: "\uE001", plugin: { send: "Issue #42: crash on start" } },
      { path: "src/a.ts", token: "\uE002" },
      { path: "", token: "\uE003", plugin: { send: "#7 #8" } },
    ];
    expect(
      serializeInlineComposerFileReferences("see \uE001\uE002 and \uE003", references),
    ).toBe("see Issue #42: crash on start @src/a.ts and #7 #8");
    // A mark is inline only: once its chip is gone it sends nothing.
    expect(serializeComposerFileReferences("gone", references.slice(0, 1))).toBe("gone");
  });

  it("does not serialize an inline reference after its token is removed", () => {
    expect(
      serializeComposerFileReferences("the token was removed", [
        { path: "/tmp/session/pasted/pasted-text.txt", token: "@pasted-text.txt" },
      ]),
    ).toBe("the token was removed");
  });

  it("keeps one separating space between adjacent sentinel chips", () => {
    expect(
      serializeInlineComposerFileReferences("\uE001\uE002 inspect", [
        { path: "src/a.ts", token: "\uE001" },
        { path: "src/b.ts", token: "\uE002" },
      ]),
    ).toBe("@src/a.ts @src/b.ts inspect");
  });

  it("keeps inline chips intact while enhancing their surrounding text", () => {
    const references = [{ path: "/tmp/image.png", token: "\uE001" }];
    const source = "\uE001make this clearer";
    expect(stripInlineComposerFileReferenceTokens(source, references)).toBe(
      "make this clearer",
    );
    expect(
      restoreInlineComposerFileReferenceTokens(
        source,
        "\uE001Make this much clearer",
        references,
      ),
    ).toBe("\uE001Make this much clearer");
    expect(
      restoreInlineComposerFileReferenceTokens(
        source,
        "Make this much clearer",
        references,
      ),
    ).toBe("\uE001Make this much clearer");
  });

  it("normalizes large-paste thresholds to the supported range", () => {
    expect(normalizeLargePasteThreshold(undefined)).toBe(600);
    expect(normalizeLargePasteThreshold(600)).toBe(600);
    expect(normalizeLargePasteThreshold(0)).toBe(600);
    expect(normalizeLargePasteThreshold(1_000_001)).toBe(600);
    expect(normalizeLargePasteThreshold(601)).toBe(601);
  });

  it("sends a session reference as its link, never as an @path", () => {
    const id = "6f1d2c3b-4a59-4e7f-8a90-b1c2d3e4f506";
    const reference = { path: id, kind: "session", token: "\uE001" };
    expect(serializeInlineComposerFileReferences(`look \uE001 now`, [reference])).toBe(
      `look pi-desktop://session/${id} now`,
    );
    expect(serializeComposerFileReferences(`look \uE001 now`, [reference])).toBe(
      `look pi-desktop://session/${id} now`,
    );
    // Token or not, a session reference never becomes an appended @path.
    expect(serializeComposerFileReferences("", [reference])).toBe("");
    expect(serializeComposerFileReferences("", [{ path: id, kind: "session" }])).toBe("");
  });
});

describe("agent mentions (ADR 0346)", () => {
  const agents = new Set(["explorer", "code-reviewer"]);

  it("reads @name only at a word start and only for a catalog name", () => {
    expect(findAgentMentions("@explorer 帮我查找一下是否存在沙箱", agents)).toEqual([
      { start: 0, end: 9, name: "explorer" },
    ]);
    expect(findAgentMentions("ask @code-reviewer, then @nobody", agents)).toEqual([
      { start: 4, end: 18, name: "code-reviewer" },
    ]);
    expect(findAgentMentions("mail user@explorer now", agents)).toEqual([]);
    expect(findAgentMentions("open @explorer.ts and @explorer/x", agents)).toEqual([]);
    expect(findAgentMentions("end with @explorer.", agents)).toEqual([
      { start: 9, end: 18, name: "explorer" },
    ]);
  });

  it("an agent chip serializes to a resolvable @name even mid-word", () => {
    const reference = { path: "explorer", kind: "agent", token: "\ue010" };
    const content = serializeInlineComposerFileReferences("look\ue010where", [reference]);
    expect(content).toBe("look @explorer where");
    expect(findAgentMentions(content, agents).map((m) => m.name)).toEqual(["explorer"]);
    // A chip-less agent reference never leaks into the trailing path list.
    expect(serializeComposerFileReferences("hi", [{ path: "explorer", kind: "agent" }])).toBe("hi");
  });

  it("serializes adjacent Skill chips as separate canonical mentions, never trailing paths", () => {
    const refs = [
      { kind: "skill", path: "plugin/review", token: "\ue001" },
      { kind: "skill", path: "review", token: "\ue002" },
      { kind: "skill", path: "removed" },
    ];
    const text = serializeComposerFileReferences("go\ue002\ue001now", refs);
    expect(text).toBe("go /skill:review /skill:plugin/review now");
    expect(findSkillMentions(text, new Map([["skill:review", "review"]])).map(m => m.id)).toEqual(["review"]);
  });

  it("keeps the file serialization byte-for-byte unchanged", () => {
    const file = { path: "src/a.ts", kind: "file", token: "\ue011" };
    expect(serializeInlineComposerFileReferences("see\ue011now", [file])).toBe("see@src/a.ts now");
  });

  it("prompts a Task call and keeps the addressed body", () => {
    const content = "@explorer find the sandbox";
    const prompt = composeMentionPrompt(content, [], findAgentMentions(content, agents));
    expect(prompt).toMatch(/^The user explicitly delegated.*`Task`.*"explorer"/);
    expect(prompt.endsWith("\n\n@explorer find the sandbox")).toBe(true);
  });

  it("is unchanged for a Skill-only draft and orders Skills before agents", () => {
    const skills = new Map([["skill:review", "review"]]);
    const skillOnly = "/skill:review check this";
    expect(composeMentionPrompt(skillOnly, findSkillMentions(skillOnly, skills), [])).toBe(
      'Call the `Skill` tool with each of these ids before answering this request, in order: "review". Follow the loaded skill instructions.\n\ncheck this',
    );
    const both = "/skill:review @code-reviewer check this";
    const prompt = composeMentionPrompt(
      both,
      findSkillMentions(both, skills),
      findAgentMentions(both, agents),
    );
    const [skill, agent, body] = prompt.split("\n\n");
    expect(skill).toMatch(/`Skill`/);
    expect(agent).toMatch(/"code-reviewer"/);
    expect(body).toBe("@code-reviewer check this");
  });
});