import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CliError } from "../../core/errors.js"; import { TraceCache } from "./cache.js"; import type { LangfuseConfig } from "./config.js"; import { LangfuseService } from "./service.js"; import { searchTrace } from "./search.js"; import type { LangfuseTraceSummary } from "./types.js"; const CONFIG: LangfuseConfig = { baseUrl: "https://langfuse.invalid", publicKey: "pk-lf-test", secretKey: "sk-lf-test", projectId: "proj-1" }; function sampleTrace(): LangfuseTraceSummary { return { id: "trace-1", name: "approval 驳回 run", projectId: "proj-1", sessionId: "sess-1", userId: "user-1", timestamp: "2026-10-01T00:00:00+08:00", input: "申请单 A", output: "已通过", observations: [ { id: "obs-root", traceId: "trace-1", type: "SPAN", name: "document_parsing", input: { items: [{ name: "invoice.pdf" }] }, output: "解析完成", metadata: { stage: "parsing" } }, { id: "obs-review", traceId: "trace-1", parentObservationId: "obs-root", type: "GENERATION", name: "approval_review", input: "上下文", output: "驳回:材料不全", usageDetails: { input: 10 }, totalCost: 0.01 } ] }; } let originalCwd: string; let originalCacheDir: string | undefined; let workdir: string; beforeEach(() => { originalCwd = process.cwd(); originalCacheDir = process.env.SEAL_USE_LANGFUSE_CACHE_DIR; workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-")); process.env.SEAL_USE_LANGFUSE_CACHE_DIR = join(workdir, "cache"); process.chdir(workdir); }); afterEach(() => { process.chdir(originalCwd); if (originalCacheDir === undefined) delete process.env.SEAL_USE_LANGFUSE_CACHE_DIR; else process.env.SEAL_USE_LANGFUSE_CACHE_DIR = originalCacheDir; rmSync(workdir, { recursive: true, force: true }); }); async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) { const cache = new TraceCache({ baseUrl: CONFIG.baseUrl, projectId: CONFIG.projectId }); await cache.write(trace.id, trace); return cache; } describe("trace cache", () => { test("writes the langfuse-home compatible format in the configured cache directory and round-trips", async () => { const cache = await seedCache(); // The cache root is explicit and independent of cwd, including macOS /var symlinks. expect(cache.path("trace-1")).toBe( join(workdir, "cache", "default", "trace-1.json") ); const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1"); expect(read?.cacheVersion).toBe(1); expect(read?.trace.id).toBe("trace-1"); expect(read?.project.baseUrl).toBe(CONFIG.baseUrl); }); test("returns undefined for a missing or version-mismatched entry", async () => { const cache = new TraceCache({ baseUrl: CONFIG.baseUrl }); expect(await cache.read("missing")).toBeUndefined(); await cache.write("trace-1", sampleTrace()); expect(await cache.exists("trace-1")).toBe(true); }); }); describe("service outline and observation IO (offline, cache-first)", () => { test("builds the observation tree from the cached trace", async () => { await seedCache(); const service = new LangfuseService(CONFIG); const outline = await service.getTraceOutline({ traceId: "trace-1" }); expect(outline.projectId).toBe("proj-1"); expect(outline.flatObservationCount).toBe(2); expect(outline.observations).toHaveLength(1); expect(outline.observations[0]?.id).toBe("obs-root"); expect(outline.observations[0]?.children[0]?.id).toBe("obs-review"); // Size-before-content: lengths instead of bodies. expect(outline.observations[0]?.outputLength).toBe(4); expect(JSON.stringify(outline)).not.toContain("解析完成"); }); test("reading a missing observation or an uncached trace fails with exit 13 guidance", async () => { await seedCache(); const service = new LangfuseService(CONFIG); try { await service.getObservationIo({ traceId: "trace-1", observationId: "nope" }); expect.unreachable("missing observation should throw"); } catch (error) { expect((error as CliError).exitCode).toBe(13); } try { await service.getTraceOutline({ traceId: "trace-other" }); expect.unreachable("uncached trace should throw"); } catch (error) { expect((error as CliError).exitCode).toBe(13); expect((error as CliError).message).toContain("seal-use langfuse cache-refresh"); } }); test("jsonPath selects one nested value and maxChars truncates with a warning", async () => { await seedCache(); const service = new LangfuseService(CONFIG); const picked = await service.getObservationIo({ traceId: "trace-1", observationId: "obs-root", fields: ["input"], jsonPath: "items[0].name" }); // `input`/`output`/`metadata` are dynamic keys filled per requested field. expect((picked as Record).input).toBe("invoice.pdf"); const long = sampleTrace(); long.observations![1]!.output = "驳回理由".repeat(500); await new TraceCache({ baseUrl: CONFIG.baseUrl }).write("trace-1", long); const truncated = await service.getObservationIo({ traceId: "trace-1", observationId: "obs-review", maxChars: 200 }); expect((truncated.warnings ?? []).join(" ")).toContain("truncated"); expect(String((truncated as Record).output).length).toBeLessThan(2_000); }); }); describe("qrep search", () => { test("ranks an observation output match above the trace-level name match", () => { const trace = sampleTrace(); const results = searchTrace("proj-1", trace, ["驳回"], { maxResults: 10, contextChars: 50 }); expect(results.length).toBeGreaterThanOrEqual(2); expect(results[0]?.observationId).toBe("obs-review"); expect(results[0]?.field).toBe("output"); expect(results[0]?.hierarchy.trace.id).toBe("trace-1"); expect(results[0]?.context.match).toBe("驳回"); expect(results.some((result) => result.observationId === undefined)).toBe(true); }); test("filters by observation type and metadata", () => { const trace = sampleTrace(); const typed = searchTrace("proj-1", trace, "解析", { maxResults: 10, contextChars: 50, observationTypes: ["GENERATION"] }); expect(typed.every((result) => result.observationType === "GENERATION" || result.observationId === undefined)).toBe(true); const empty = searchTrace("proj-1", trace, "驳回", { maxResults: 10, contextChars: 50, metadata: { stage: "review" } }); expect(empty).toEqual([]); }); });