Skip to content

Your lightweight open-source personal agent.

7.5 KB
Raw Blame
import { describe, expect, it } from "vitest";

import { redactActivityText } from "@/components/thread/activity/activity-text";
import {
  describeGenericToolRun,
  canGroupGenericToolRuns,
  parseGenericToolTrace,
  type GenericToolStatus,
} from "@/components/thread/activity/generic-tool-model";
import i18n, { setAppLanguage } from "@/i18n";

function describeRun(line: string, status: GenericToolStatus = "done") {
  const trace = parseGenericToolTrace(line);
  expect(trace).not.toBeNull();
  return describeGenericToolRun([{ trace: trace!, status }], i18n.t);
}

describe("generic tool activity semantics", () => {
  it.each(["running", "done", "error"] as const)("shows rg arguments during %s", (status) => {
    const presentation = describeRun('rg({"args":["-n","hello world","src"]})', status);
    expect(presentation.detail).toBe('-n "hello world" src');
    expect(presentation.status).toBe(status);
  });

  it("bounds and redacts rg argument previews", () => {
    const presentation = describeRun(`rg(${JSON.stringify({ args: ["sk-proj-abcdefghijklmno", "x".repeat(120)] })})`);
    expect(presentation.detail).toContain("<redacted>");
    expect(presentation.detail.length).toBeLessThanOrEqual(88);
  });

  it("shows rg regex characters and empty arguments", () => {
    const presentation = describeRun(`rg(${JSON.stringify({ args: [String.raw`resolve\(`, ""] })})`);
    expect(presentation.detail).toBe('resolve\\( ""');
  });

  it.each([
    ['find_files({"glob":"*.tsx"})', "File search complete", "*.tsx"],
    ['grep({"pattern":"dream_cursor"})', "Searched files", "“dream_cursor”"],
    ['list_dir({"path":"memory"})', "Listed files", "memory"],
    ['read_file({"path":"docs/guide.md"})', "Read file", "docs/guide.md"],
    ['memory_search({"query":"launch date"})', "Searched memory", "“launch date”"],
    ['generate_image({"prompt":"private launch art"})', "Generated image", ""],
    ['spawn({"label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
    ['subagent("create")', "Subtask created", ""],
    ['subagent({"action":"create","label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
    ['subagent("check")', "Subtask status retrieved", ""],
    ['subagent("send")', "Message queued for subtask", ""],
    ['subagent("cancel")', "Stop request processed", ""],
    ['message({"channel":"telegram","content":"private message"})', "Sent message", "telegram"],
    ['my({"action":"check","key":"context_window_tokens"})', "Checked agent settings", "context_window_tokens"],
    ['my({"action":"set","key":"model","value":"private-model"})', "Updated agent settings", "model"],
    ['cron({"action":"add","name":"Daily digest","message":"private prompt"})', "Scheduled automation", "Daily digest"],
    ['cron({"action":"remove","name":"Daily digest"})', "Removed automation", "Daily digest"],
    ['create_goal({"objective":"private objective","ui_summary":"Benchmark memory"})', "Started long task", "Benchmark memory"],
    ['update_goal({"action":"complete","recap":"private recap"})', "Updated long task", "complete"],
    ['exec_session({"session_id":"session-1234567890-secret","until_exit":true})', "Continued command", "session…ecret"],
    ['write_stdin({"session_id":"legacy-1234567890-secret","chars":"private input"})', "Completed Write stdin", ""],
    ['list_exec_sessions({})', "Checked running commands", ""],
    ['screenshot({"path":"artifacts/home.png"})', "Captured screenshot", ""],
    ['third_party_sync({"token":"secret","payload":"private payload"})', "Completed Third party sync", ""],
  ])("describes %s without exposing implementation syntax", (line, label, detail) => {
    const presentation = describeRun(line);
    expect(presentation.label).toBe(label);
    expect(presentation.detail).toBe(detail);
    expect(`${presentation.label} ${presentation.detail}`).not.toMatch(/[{}]|private|tool-results/);
  });

  it.each([
    ["running", "Generating image"],
    ["done", "Generated image"],
    ["error", "Could not generate image"],
  ] as const)("uses human status copy for %s tools", (status, label) => {
    expect(describeRun('generate_image({"prompt":"private"})', status).label).toBe(label);
  });

  it("groups searches over collected sources without exposing absolute paths", () => {
    const first = parseGenericToolTrace(
      'grep({"pattern":"July","path":"/Users/test/.nanobot/tool-results/session/call_first.txt"})',
    )!;
    const second = parseGenericToolTrace(
      'grep({"pattern":"OpenAI","path":"/Users/test/.nanobot/tool-results/session/call_second.txt"})',
    )!;
    const presentation = describeGenericToolRun([
      { trace: first, status: "done" },
      { trace: second, status: "done" },
    ], i18n.t);

    expect(presentation).toMatchObject({ label: "Reviewed sources", detail: "", aside: "2 files" });
    expect(JSON.stringify(presentation)).not.toContain("/Users/test");
  });

  it("leaves specialized tools to their dedicated activity surfaces", () => {
    for (const line of [
      'web_search({"query":"nanobot"})',
      'web_fetch({"url":"https://example.com"})',
      'exec({"command":"date"})',
      'write_file({"path":"README.md"})',
      'edit_file({"path":"README.md"})',
      'apply_patch({"patch":"private"})',
      'run_cli_app({"name":"github"})',
      'mcp_browser_click({"text":"private"})',
    ]) {
      expect(parseGenericToolTrace(line)).toBeNull();
    }
  });

  it("localizes labels and counts without translating raw search text", async () => {
    await setAppLanguage("zh-CN");
    const first = parseGenericToolTrace('grep({"pattern":"release notes"})')!;
    const second = parseGenericToolTrace('grep({"pattern":"API changes"})')!;

    expect(describeGenericToolRun([
      { trace: first, status: "done" },
      { trace: second, status: "done" },
    ], i18n.t)).toMatchObject({
      label: "文件搜索完成",
      aside: "2 次",
    });
  });

  it("localizes command continuation events", async () => {
    await setAppLanguage("zh-CN");
    const line = 'exec_session({"session_id":"session-1234567890-secret"})';
    for (const status of ["running", "done", "error"] as const) {
      const key = status === "running" ? "continuingCommand"
        : status === "done" ? "continuedCommand" : "continueCommandFailed";
      expect(describeRun(line, status)).toMatchObject({
        label: i18n.t(`message.agentActivity.${key}`),
        detail: "session…ecret",
      });
    }
  });

  it("keeps different subtask actions separate while grouping repeated status checks", () => {
    const item = (action: string) => ({ trace: parseGenericToolTrace(`subagent("${action}")`)!, status: "done" as const });
    expect(canGroupGenericToolRuns(item("create"), item("check"))).toBe(false);
    expect(canGroupGenericToolRuns(item("send"), item("cancel"))).toBe(false);
    expect(canGroupGenericToolRuns(item("check"), item("check"))).toBe(true);
  });

  it.each([
    ["Authorization: Bearer top-secret-token", "Authorization: <redacted>"],
    ["API_KEY=sk-proj-1234567890abcdef", "API_KEY=<redacted>"],
    ["--token xoxb-1234567890-secret", "--token <redacted>"],
    ["https://user:[email protected]/file?access_token=signed-secret", "https://<redacted>@example.com/file?access_token=<redacted>"],
    ["github ghp_1234567890abcdefghijkl", "github <redacted>"],
    ["aws AKIA1234567890ABCDEF", "aws <redacted>"],
    ["telegram 123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcd", "telegram <redacted>"],
  ])("redacts activity text before rendering: %s", (input, expected) => {
    expect(redactActivityText(input)).toBe(expected);
  });
});