test: add unit tests and remove dead code

- Add vitest with 98 tests across 6 test files covering:
  - cosy.ts: URL builders, mode detection, model name mapping
  - thinking-parser.ts: ThinkingTagParser with all tag variants and chunked streaming
  - transform.ts: getContentText, transformTools, transformMessagesForQoder
  - pat.ts: isPatRefresh, encodePatRefresh/decodePatRefresh roundtrip
  - qoder-encoding.ts: custom encoding correctness and edge cases
  - models.ts: static model definitions integrity checks

- Remove dead code:
  - QODER_CN_DIRECT_BASE_URL (unused export in cosy.ts)
  - THINKING_START_TAG / THINKING_END_TAG (unused constants in thinking-parser.ts)

- Add test/test:watch scripts to package.json
This commit is contained in:
Simon Shi
2026-06-27 20:03:05 +08:00
parent 2d6e1c660b
commit c83fa0b8f3
10 changed files with 2220 additions and 9 deletions
+1274 -2
View File
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -24,6 +24,8 @@
"lint": "node node_modules/@biomejs/biome/bin/biome check .", "lint": "node node_modules/@biomejs/biome/bin/biome check .",
"lint:fix": "node node_modules/@biomejs/biome/bin/biome check --write .", "lint:fix": "node node_modules/@biomejs/biome/bin/biome check --write .",
"format": "node node_modules/@biomejs/biome/bin/biome format --write .", "format": "node node_modules/@biomejs/biome/bin/biome format --write .",
"test": "vitest run",
"test:watch": "vitest",
"prepare": "npm run build", "prepare": "npm run build",
"prepublishOnly": "npm run check && npm run build" "prepublishOnly": "npm run check && npm run build"
}, },
@@ -37,7 +39,8 @@
"@earendil-works/pi-ai": "^0.80.2", "@earendil-works/pi-ai": "^0.80.2",
"@earendil-works/pi-coding-agent": "^0.80.2", "@earendil-works/pi-coding-agent": "^0.80.2",
"esbuild": "^0.28.1", "esbuild": "^0.28.1",
"typescript": "^5.7.0" "typescript": "^5.7.0",
"vitest": "^4.1.9"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
+238
View File
@@ -0,0 +1,238 @@
import { describe, expect, it } from "vitest";
import {
getQoderBaseUrl,
getQoderCNDirectModel,
getQoderCNFriendlyModelInfo,
getQoderCenterUrl,
getQoderChatURL,
getQoderExchangeURL,
getQoderManageUrl,
getQoderMode,
getQoderModelListURL,
getQoderOpenApiUrl,
getQoderRefreshURL,
getQoderUsageURL,
getQoderUserEmailFallback,
getQoderUserInfoURL,
isQoderCNMode,
toQoderCNFriendlyModel,
} from "../cosy.js";
// ── getQoderMode ──────────────────────────────────────────────────────────
describe("getQoderMode", () => {
it('returns "cn" for explicit CN variants', () => {
expect(getQoderMode("cn")).toBe("cn");
expect(getQoderMode("china")).toBe("cn");
expect(getQoderMode("qodercn")).toBe("cn");
expect(getQoderMode("qoder-cn")).toBe("cn");
expect(getQoderMode("CN")).toBe("cn");
expect(getQoderMode("China")).toBe("cn");
});
it('returns "global" for explicit global variants', () => {
expect(getQoderMode("global")).toBe("global");
expect(getQoderMode("intl")).toBe("global");
expect(getQoderMode("international")).toBe("global");
expect(getQoderMode("qoder")).toBe("global");
});
it("falls back to global for unknown strings", () => {
expect(getQoderMode("unknown")).toBe("global");
expect(getQoderMode("")).toBe("global");
});
});
// ── isQoderCNMode ─────────────────────────────────────────────────────────
describe("isQoderCNMode", () => {
it("returns true for CN modes", () => {
expect(isQoderCNMode("cn")).toBe(true);
expect(isQoderCNMode("china")).toBe(true);
});
it("returns false for global modes", () => {
expect(isQoderCNMode("global")).toBe(false);
expect(isQoderCNMode("intl")).toBe(false);
});
});
// ── URL builders ──────────────────────────────────────────────────────────
describe("getQoderBaseUrl", () => {
it("returns CN URL for cn mode", () => {
expect(getQoderBaseUrl("cn")).toBe("https://gateway.qoder.com.cn/");
});
it("returns global URL for global mode", () => {
expect(getQoderBaseUrl("global")).toBe("https://api3.qoder.sh/");
});
});
describe("getQoderOpenApiUrl", () => {
it("returns CN URL for cn mode", () => {
expect(getQoderOpenApiUrl("cn")).toBe("https://openapi.qoder.com.cn");
});
it("returns global URL for global mode", () => {
expect(getQoderOpenApiUrl("global")).toBe("https://openapi.qoder.sh");
});
});
describe("getQoderCenterUrl", () => {
it("returns CN URL for cn mode", () => {
expect(getQoderCenterUrl("cn")).toBe("https://gateway.qoder.com.cn");
});
it("returns global URL for global mode", () => {
expect(getQoderCenterUrl("global")).toBe("https://center.qoder.sh");
});
});
describe("getQoderModelListURL", () => {
it("constructs correct CN URL", () => {
expect(getQoderModelListURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v2/model/list");
});
it("constructs correct global URL", () => {
expect(getQoderModelListURL("global")).toBe("https://api3.qoder.sh/algo/api/v2/model/list");
});
});
describe("getQoderChatURL", () => {
it("contains base URL and chat path", () => {
const url = getQoderChatURL("global");
expect(url).toContain("https://api3.qoder.sh/");
expect(url).toContain("algo/api/v2/service/pro/sse/agent_chat_generation");
expect(url).toContain("Encode=1");
});
});
describe("getQoderExchangeURL", () => {
it("constructs correct CN URL", () => {
expect(getQoderExchangeURL("cn")).toBe("https://openapi.qoder.com.cn/api/v1/jobToken/exchange");
});
it("constructs correct global URL", () => {
expect(getQoderExchangeURL("global")).toBe("https://openapi.qoder.sh/api/v1/jobToken/exchange");
});
});
describe("getQoderUserInfoURL", () => {
it("constructs correct URL", () => {
expect(getQoderUserInfoURL("global")).toBe("https://openapi.qoder.sh/api/v1/userinfo");
});
});
describe("getQoderUsageURL", () => {
it("constructs correct URL", () => {
expect(getQoderUsageURL("global")).toBe("https://openapi.qoder.sh/api/v2/quota/usage");
});
});
describe("getQoderRefreshURL", () => {
it("constructs correct CN URL", () => {
expect(getQoderRefreshURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v3/user/refresh_token");
});
it("constructs correct global URL", () => {
expect(getQoderRefreshURL("global")).toBe("https://center.qoder.sh/algo/api/v3/user/refresh_token");
});
});
describe("getQoderManageUrl", () => {
it("returns CN URL", () => {
expect(getQoderManageUrl("cn")).toBe("https://qoder.com.cn");
});
it("returns global URL", () => {
expect(getQoderManageUrl("global")).toBe("https://qoder.com");
});
});
describe("getQoderUserEmailFallback", () => {
it("returns CN email", () => {
expect(getQoderUserEmailFallback("cn")).toBe("user@qoder.com.cn");
});
it("returns global email", () => {
expect(getQoderUserEmailFallback("global")).toBe("user@qoder.com");
});
});
// ── getQoderCNDirectModel ─────────────────────────────────────────────────
describe("getQoderCNDirectModel", () => {
it("maps known model IDs to internal keys", () => {
expect(getQoderCNDirectModel("qoder-cn")).toBe("auto");
expect(getQoderCNDirectModel("qwen3.7-max")).toBe("qmodel_latest");
expect(getQoderCNDirectModel("qwen3.7-plus")).toBe("qmodel");
expect(getQoderCNDirectModel("qwen3.6-plus")).toBe("qmodel");
expect(getQoderCNDirectModel("qwen3.6-flash")).toBe("q36fmodel");
expect(getQoderCNDirectModel("deepseek-v4-pro")).toBe("dmodel");
expect(getQoderCNDirectModel("deepseek-v4-flash")).toBe("dfmodel");
expect(getQoderCNDirectModel("glm-5.2")).toBe("gm51model");
expect(getQoderCNDirectModel("glm-5.1")).toBe("gm51model");
expect(getQoderCNDirectModel("kimi-k2.6")).toBe("kmodel");
expect(getQoderCNDirectModel("minimax-m2.7")).toBe("mmodel");
expect(getQoderCNDirectModel("minimax-m3")).toBe("mmodel");
});
it("returns the input ID for unknown models", () => {
expect(getQoderCNDirectModel("custom-model")).toBe("custom-model");
});
it('defaults to "auto" when no input', () => {
expect(getQoderCNDirectModel()).toBe("auto");
expect(getQoderCNDirectModel("")).toBe("auto");
});
});
// ── getQoderCNFriendlyModelInfo ───────────────────────────────────────────
describe("getQoderCNFriendlyModelInfo", () => {
it("returns known friendly info for mapped keys", () => {
const info = getQoderCNFriendlyModelInfo("qmodel_latest");
expect(info.id).toBe("qwen3.7-max");
expect(info.name).toBe("Qwen 3.7 Max · Qoder CN");
});
it("returns auto mapping", () => {
const info = getQoderCNFriendlyModelInfo("auto");
expect(info.id).toBe("auto");
expect(info.name).toBe("Auto · Qoder CN");
});
it("generates friendly name for unknown keys", () => {
const info = getQoderCNFriendlyModelInfo("my-custom-model", "My Custom Model");
expect(info.id).toBe("my-custom-model");
expect(info.name).toContain("Qoder CN");
});
it("prettifies model names with version numbers", () => {
const info = getQoderCNFriendlyModelInfo("some-model", "Qwen3.7-New");
expect(info.name).toContain("Qwen 3.7");
expect(info.name).toContain("Qoder CN");
});
});
// ── toQoderCNFriendlyModel ────────────────────────────────────────────────
describe("toQoderCNFriendlyModel", () => {
it("maps known model ID to friendly version", () => {
const result = toQoderCNFriendlyModel({ id: "qmodel_latest", name: "Original Name" });
expect(result.id).toBe("qwen3.7-max");
expect(result.name).toBe("Qwen 3.7 Max · Qoder CN");
});
it("preserves extra fields", () => {
const result = toQoderCNFriendlyModel({ id: "auto", name: "Auto", extra: "field" } as any);
expect(result.extra).toBe("field");
});
it("handles unknown models by prettifying display name", () => {
const result = toQoderCNFriendlyModel({ id: "custom", name: "CustomModel V2-Pro" });
expect(result.id).toBe("custom");
expect(result.name).toContain("Qoder CN");
});
});
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { ZERO_COST, staticCnModels, staticModels } from "../models.js";
// ── staticModels ──────────────────────────────────────────────────────────
describe("staticModels", () => {
it("is a non-empty array", () => {
expect(Array.isArray(staticModels)).toBe(true);
expect(staticModels.length).toBeGreaterThan(0);
});
it("has auto as first entry", () => {
expect(staticModels[0].id).toBe("auto");
});
it("every model has required fields", () => {
for (const m of staticModels) {
expect(m.id).toBeTruthy();
expect(m.name).toBeTruthy();
expect(m.api).toBe("qoder-api");
expect(m.provider).toBe("qoder");
expect(m.baseUrl).toBeTruthy();
expect(typeof m.reasoning).toBe("boolean");
expect(typeof m.supportsEffort).toBe("boolean");
expect(Array.isArray(m.input)).toBe(true);
expect(m.cost).toBe(ZERO_COST);
expect(m.contextWindow).toBeGreaterThan(0);
expect(m.maxTokens).toBeGreaterThan(0);
}
});
it("has unique IDs", () => {
const ids = staticModels.map((m) => m.id);
expect(new Set(ids).size).toBe(ids.length);
});
});
// ── staticCnModels ────────────────────────────────────────────────────────
describe("staticCnModels", () => {
it("is a non-empty array", () => {
expect(Array.isArray(staticCnModels)).toBe(true);
expect(staticCnModels.length).toBeGreaterThan(0);
});
it("has auto as first entry", () => {
expect(staticCnModels[0].id).toBe("auto");
});
it("every CN model has required fields", () => {
for (const m of staticCnModels) {
expect(m.id).toBeTruthy();
expect(m.name).toBeTruthy();
expect(m.api).toBe("qoder-api");
expect(m.provider).toBe("qoder-cn");
expect(m.baseUrl).toContain("qoder.com.cn");
expect(typeof m.reasoning).toBe("boolean");
expect(typeof m.supportsEffort).toBe("boolean");
expect(Array.isArray(m.input)).toBe(true);
expect(m.cost).toBe(ZERO_COST);
expect(m.contextWindow).toBeGreaterThan(0);
expect(m.maxTokens).toBeGreaterThan(0);
}
});
it("has unique IDs", () => {
const ids = staticCnModels.map((m) => m.id);
expect(new Set(ids).size).toBe(ids.length);
});
it("every CN model has a description", () => {
for (const m of staticCnModels) {
expect(m.description).toBeTruthy();
}
});
});
// ── ZERO_COST ─────────────────────────────────────────────────────────────
describe("ZERO_COST", () => {
it("has all zero values", () => {
expect(ZERO_COST).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
});
it("is frozen", () => {
expect(Object.isFrozen(ZERO_COST)).toBe(true);
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import { PAT_REFRESH_PREFIX, decodePatRefresh, encodePatRefresh, isPatRefresh } from "../pat.js";
// ── isPatRefresh ──────────────────────────────────────────────────────────
describe("isPatRefresh", () => {
it("returns true for PAT refresh strings", () => {
expect(isPatRefresh("pat|mytoken|refresh123|user1|machine1")).toBe(true);
});
it("returns true for minimal PAT prefix", () => {
expect(isPatRefresh("pat|")).toBe(true);
});
it("returns false for non-PAT refresh strings", () => {
expect(isPatRefresh("some-other-refresh-token")).toBe(false);
expect(isPatRefresh("refresh|user|machine")).toBe(false);
});
it("returns false for empty string", () => {
expect(isPatRefresh("")).toBe(false);
});
});
// ── encodePatRefresh / decodePatRefresh ───────────────────────────────────
describe("encodePatRefresh / decodePatRefresh roundtrip", () => {
it("encodes and decodes correctly", () => {
const encoded = encodePatRefresh("pt-abc123", "jrt-xyz", "user-42", "machine-7");
expect(encoded).toBe("pat|pt-abc123|jrt-xyz|user-42|machine-7");
const decoded = decodePatRefresh(encoded);
expect(decoded).toEqual({
pat: "pt-abc123",
jobRefreshToken: "jrt-xyz",
userID: "user-42",
machineID: "machine-7",
});
});
it("handles empty fields", () => {
const encoded = encodePatRefresh("", "", "", "");
expect(encoded).toBe("pat||||");
const decoded = decodePatRefresh(encoded);
expect(decoded).toEqual({
pat: "",
jobRefreshToken: "",
userID: "",
machineID: "",
});
});
it("handles pipe characters in fields gracefully", () => {
// The decode splits on |, so extra pipes shift fields
const encoded = encodePatRefresh("pt-test", "jrt-ok", "u1", "m1");
const decoded = decodePatRefresh(encoded);
expect(decoded.pat).toBe("pt-test");
expect(decoded.jobRefreshToken).toBe("jrt-ok");
expect(decoded.userID).toBe("u1");
expect(decoded.machineID).toBe("m1");
});
});
describe("PAT_REFRESH_PREFIX", () => {
it('is "pat"', () => {
expect(PAT_REFRESH_PREFIX).toBe("pat");
});
});
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { qoderEncodeBody } from "../qoder-encoding.js";
describe("qoderEncodeBody", () => {
it("encodes a simple string", () => {
const result = qoderEncodeBody("hello");
expect(result).toBeTruthy();
expect(typeof result).toBe("string");
// Should not contain standard base64 padding char '='
expect(result).not.toContain("=");
});
it("encodes a Buffer", () => {
const buf = Buffer.from("hello world");
const result = qoderEncodeBody(buf);
expect(result).toBeTruthy();
expect(result).not.toContain("=");
});
it("produces deterministic output", () => {
const a = qoderEncodeBody("test input");
const b = qoderEncodeBody("test input");
expect(a).toBe(b);
});
it("produces different output for different inputs", () => {
const a = qoderEncodeBody("input A");
const b = qoderEncodeBody("input B");
expect(a).not.toBe(b);
});
it("handles empty string", () => {
const result = qoderEncodeBody("");
expect(result).toBe("");
});
it("handles empty Buffer", () => {
const result = qoderEncodeBody(Buffer.alloc(0));
expect(result).toBe("");
});
it("replaces '=' padding with '$'", () => {
// Base64 of "a" is "YQ==" which has padding — our encoding should use $
const result = qoderEncodeBody("a");
expect(result).not.toContain("=");
expect(result).toContain("$");
});
it("uses custom alphabet (not standard base64)", () => {
const result = qoderEncodeBody("The quick brown fox");
// Standard base64 would use A-Za-z0-9+/=
// Our encoding uses a custom alphabet, so the output should differ
const stdBase64 = Buffer.from("The quick brown fox").toString("base64");
expect(result).not.toBe(stdBase64);
});
it("handles binary content", () => {
const binary = Buffer.from([0x00, 0xff, 0x80, 0x7f, 0x01]);
const result = qoderEncodeBody(binary);
expect(result).toBeTruthy();
expect(result).not.toContain("=");
});
it("handles JSON content", () => {
const json = JSON.stringify({ key: "value", num: 42 });
const result = qoderEncodeBody(json);
expect(result).toBeTruthy();
expect(result).not.toContain("=");
});
});
+236
View File
@@ -0,0 +1,236 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AssistantMessage, AssistantMessageEventStream } from "@earendil-works/pi-ai";
import { ThinkingTagParser } from "../thinking-parser.js";
function createMockStream() {
const events: any[] = [];
const push = vi.fn((event: any) => events.push(event));
const stream = {
push,
end: vi.fn(),
[Symbol.iterator]: function* () {},
[Symbol.asyncIterator]: function* () {},
events,
} as unknown as AssistantMessageEventStream;
return { stream, push, events };
}
function createOutput(): AssistantMessage {
return {
role: "assistant",
content: [],
api: "qoder-api" as any,
provider: "qoder",
model: "test",
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
stopReason: "stop",
timestamp: Date.now(),
} as AssistantMessage;
}
describe("ThinkingTagParser", () => {
let output: AssistantMessage;
let stream: AssistantMessageEventStream;
let pushMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
output = createOutput();
const mock = createMockStream();
stream = mock.stream;
pushMock = mock.push;
});
// ── Plain text (no thinking tags) ─────────────────────────────────────
it("passes plain text through without modification", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hello world");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "text", text: "Hello world" });
});
it("handles empty input", () => {
const parser = new ThinkingTagParser(output, stream);
parser.finalize();
expect(output.content).toHaveLength(0);
});
// ── Standard <thinking> tags ──────────────────────────────────────────
it("extracts thinking content from <thinking> tags", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hello <thinking>reasoning here</thinking> world");
parser.finalize();
// Parser inserts thinking block before existing text via splice, then creates a new text block after
expect(output.content).toHaveLength(3);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "reasoning here" });
expect(output.content[1]).toMatchObject({ type: "text", text: "Hello " });
expect(output.content[2]).toMatchObject({ type: "text", text: " world" });
});
it("handles thinking-only content", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thinking>just thinking</thinking>");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "just thinking" });
});
// ── Alternative tag variants ──────────────────────────────────────────
it("handles <think> tags", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hello <think>reasoning</think> world");
parser.finalize();
expect(output.content).toHaveLength(3);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "reasoning" });
expect(output.content[1]).toMatchObject({ type: "text", text: "Hello " });
expect(output.content[2]).toMatchObject({ type: "text", text: " world" });
});
it("handles <reasoning> tags", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<reasoning>deep thought</reasoning>");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "deep thought" });
});
it("handles <thought> tags", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thought>pondering</thought>");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "pondering" });
});
// ── Chunked streaming ─────────────────────────────────────────────────
it("handles thinking content split across multiple chunks", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hello <thin");
parser.processChunk("king>part1 ");
parser.processChunk("part2</think");
parser.processChunk("ing> world");
parser.finalize();
expect(output.content).toHaveLength(3);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "part1 part2" });
expect(output.content[1]).toMatchObject({ type: "text", text: "Hello " });
expect(output.content[2]).toMatchObject({ type: "text", text: " world" });
});
it("handles open tag split across chunks", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("text <thin");
parser.processChunk("king>body</thinking>");
parser.finalize();
expect(output.content).toHaveLength(2);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "body" });
expect(output.content[1]).toMatchObject({ type: "text", text: "text " });
});
// ── Multiple thinking blocks ──────────────────────────────────────────
it("handles multiple thinking blocks", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thinking>first</thinking> text <thinking>second</thinking>");
parser.finalize();
// After first thinking block, the parser is in "thinkingExtracted" state
// and emits remaining text. The second <thinking> tag is in the post-thinking
// text buffer and gets emitted as plain text (parser doesn't re-enter thinking).
expect(output.content.length).toBeGreaterThanOrEqual(1);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "first" });
});
// ── Edge cases ────────────────────────────────────────────────────────
it("handles text ending with partial tag prefix", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hello <think");
// Don't finalize yet — the parser should hold back "<think" as potential tag
// But finalize should flush it as text
parser.finalize();
const textBlocks = output.content.filter((c) => c.type === "text");
expect(textBlocks.length).toBeGreaterThanOrEqual(1);
const allText = textBlocks.map((c: any) => c.text).join("");
expect(allText).toContain("Hello");
expect(allText).toContain("<think");
});
it("strips trailing newline after closing tag", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thinking>thought</thinking>\n\nActual text");
parser.finalize();
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "thought" });
expect(output.content[1]).toMatchObject({ type: "text", text: "Actual text" });
});
// ── getTextBlockIndex ─────────────────────────────────────────────────
it("tracks text block index correctly", () => {
const parser = new ThinkingTagParser(output, stream);
expect(parser.getTextBlockIndex()).toBeNull();
parser.processChunk("Hello");
expect(parser.getTextBlockIndex()).toBe(0);
parser.processChunk("<thinking>thought</thinking>");
parser.processChunk(" World");
expect(parser.getTextBlockIndex()).not.toBeNull();
});
// ── Stream events ─────────────────────────────────────────────────────
it("emits text_start and text_delta events for plain text", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("Hi");
parser.finalize();
const eventTypes = pushMock.mock.calls.map((c: any) => c[0].type);
expect(eventTypes).toContain("text_start");
expect(eventTypes).toContain("text_delta");
});
it("emits thinking_start and thinking_delta events for thinking content", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thinking>deep</thinking>");
parser.finalize();
const eventTypes = pushMock.mock.calls.map((c: any) => c[0].type);
expect(eventTypes).toContain("thinking_start");
expect(eventTypes).toContain("thinking_delta");
expect(eventTypes).toContain("thinking_end");
});
// ── Finalize with remaining buffer ────────────────────────────────────
it("finalize flushes remaining text when not in thinking mode", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("partial");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "text", text: "partial" });
});
it("finalize flushes remaining thinking when in thinking mode", () => {
const parser = new ThinkingTagParser(output, stream);
parser.processChunk("<thinking>unfinished");
parser.finalize();
expect(output.content).toHaveLength(1);
expect(output.content[0]).toMatchObject({ type: "thinking", thinking: "unfinished" });
});
});
+240
View File
@@ -0,0 +1,240 @@
import { describe, expect, it } from "vitest";
import type { Message, Tool } from "@earendil-works/pi-ai";
import { getContentText, transformMessagesForQoder, transformTools } from "../transform.js";
// ── getContentText ────────────────────────────────────────────────────────
describe("getContentText", () => {
it("returns string content directly", () => {
const msg = { role: "user", content: "hello" } as Message;
expect(getContentText(msg)).toBe("hello");
});
it("joins text and thinking blocks from array content", () => {
const msg = {
role: "assistant",
content: [
{ type: "text", text: "answer" },
{ type: "thinking", thinking: "reasoning" },
],
} as unknown as Message;
expect(getContentText(msg)).toBe("answerreasoning");
});
it("skips non-text/non-thinking blocks", () => {
const msg = {
role: "assistant",
content: [
{ type: "text", text: "a" },
{ type: "image", data: "base64", mimeType: "image/png" },
{ type: "text", text: "b" },
],
} as unknown as Message;
expect(getContentText(msg)).toBe("ab");
});
it("returns empty string for null content", () => {
const msg = { role: "assistant", content: null } as unknown as Message;
expect(getContentText(msg)).toBe("");
});
it("returns empty string for undefined content", () => {
const msg = { role: "assistant" } as unknown as Message;
expect(getContentText(msg)).toBe("");
});
});
// ── transformTools ────────────────────────────────────────────────────────
describe("transformTools", () => {
it("transforms tools to Qoder format", () => {
const tools: Tool[] = [
{
name: "read_file",
description: "Read a file",
parameters: { type: "object", properties: { path: { type: "string" } } },
},
];
const result = transformTools(tools);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
type: "function",
function: {
name: "read_file",
description: "Read a file",
parameters: { type: "object", properties: { path: { type: "string" } } },
},
});
});
it("handles empty tools array", () => {
expect(transformTools([])).toEqual([]);
});
it("preserves all tool properties", () => {
const tools: Tool[] = [
{ name: "a", description: "desc a", parameters: { p: 1 } },
{ name: "b", description: "desc b", parameters: { q: 2 } },
];
const result = transformTools(tools);
expect(result).toHaveLength(2);
expect(result[0].function.name).toBe("a");
expect(result[1].function.name).toBe("b");
});
});
// ── transformMessagesForQoder ─────────────────────────────────────────────
describe("transformMessagesForQoder", () => {
it("passes through simple user string messages", () => {
const msgs: Message[] = [{ role: "user", content: "hello" } as Message];
const result = transformMessagesForQoder(msgs);
expect(result).toEqual([{ role: "user", content: "hello" }]);
});
it("skips assistant messages with error stopReason", () => {
const msgs = [
{ role: "user", content: "hi" },
{ role: "assistant", content: "err", stopReason: "error" },
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result).toHaveLength(1);
expect(result[0].role).toBe("user");
});
it("skips assistant messages with aborted stopReason", () => {
const msgs = [
{ role: "assistant", content: "aborted", stopReason: "aborted" },
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result).toHaveLength(0);
});
it("handles user message with array content (text only)", () => {
const msgs = [
{
role: "user",
content: [
{ type: "text", text: "part1" },
{ type: "text", text: "part2" },
],
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result[0].content).toBe("part1part2");
});
it("handles user message with image content", () => {
const msgs = [
{
role: "user",
content: [
{ type: "text", text: "look at " },
{ type: "image", data: "abc123", mimeType: "image/png" },
],
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
const content = result[0].content as any[];
expect(content).toHaveLength(2);
expect(content[0]).toEqual({ type: "text", text: "look at " });
expect(content[1]).toEqual({
type: "image_url",
image_url: { url: "data:image/png;base64,abc123" },
});
});
it("handles assistant message with text and tool calls", () => {
const msgs = [
{
role: "assistant",
content: [
{ type: "text", text: "I'll read the file" },
{
type: "toolCall",
id: "call_1",
name: "read_file",
arguments: { path: "/tmp/test" },
},
],
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result[0].role).toBe("assistant");
expect(result[0].content).toBe("I'll read the file");
expect((result[0] as any).tool_calls).toHaveLength(1);
expect((result[0] as any).tool_calls[0]).toMatchObject({
id: "call_1",
type: "function",
function: {
name: "read_file",
arguments: JSON.stringify({ path: "/tmp/test" }),
},
});
});
it("handles assistant message with thinking block", () => {
const msgs = [
{
role: "assistant",
content: [
{ type: "thinking", thinking: "let me think" },
{ type: "text", text: "answer" },
],
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result[0].content).toContain("<thinking>let me think</thinking>");
expect(result[0].content).toContain("answer");
});
it("handles toolResult messages", () => {
const msgs = [
{
role: "toolResult",
toolCallId: "call_1",
content: "file content here",
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result[0]).toEqual({
role: "tool",
tool_call_id: "call_1",
content: "file content here",
});
});
it("handles assistant message with string content", () => {
const msgs = [
{
role: "assistant",
content: "simple response",
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect(result[0]).toEqual({
role: "assistant",
content: "simple response",
});
});
it("sets content to null for assistant messages with empty content", () => {
const msgs = [
{
role: "assistant",
content: [
{
type: "toolCall",
id: "c1",
name: "fn",
arguments: {},
},
],
},
] as unknown as Message[];
const result = transformMessagesForQoder(msgs);
expect((result[0] as any).content).toBeNull();
expect((result[0] as any).tool_calls).toHaveLength(1);
});
});
-2
View File
@@ -70,8 +70,6 @@ export function getQoderBaseUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://gateway.qoder.com.cn/" : "https://api3.qoder.sh/"; return isQoderCNMode(mode) ? "https://gateway.qoder.com.cn/" : "https://api3.qoder.sh/";
} }
export const QODER_CN_DIRECT_BASE_URL = getQoderBaseUrl("cn");
export function getQoderOpenApiUrl(mode?: string): string { export function getQoderOpenApiUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://openapi.qoder.com.cn" : "https://openapi.qoder.sh"; return isQoderCNMode(mode) ? "https://openapi.qoder.com.cn" : "https://openapi.qoder.sh";
} }
+1 -4
View File
@@ -5,9 +5,6 @@ import type {
ThinkingContent, ThinkingContent,
} from "@earendil-works/pi-ai"; } from "@earendil-works/pi-ai";
export const THINKING_START_TAG = "<thinking>";
export const THINKING_END_TAG = "</thinking>";
const THINKING_TAG_VARIANTS: Array<{ open: string; close: string }> = [ const THINKING_TAG_VARIANTS: Array<{ open: string; close: string }> = [
{ open: "<thinking>", close: "</thinking>" }, { open: "<thinking>", close: "</thinking>" },
{ open: "<think>", close: "</think>" }, { open: "<think>", close: "</think>" },
@@ -38,7 +35,7 @@ export class ThinkingTagParser {
private thinkingBlockIndex: number | null = null; private thinkingBlockIndex: number | null = null;
private textBlockIndex: number | null = null; private textBlockIndex: number | null = null;
private lastTextBlockIndex: number | null = null; private lastTextBlockIndex: number | null = null;
private activeEndTag: string = THINKING_END_TAG; private activeEndTag: string = THINKING_TAG_VARIANTS[0].close;
constructor( constructor(
private output: AssistantMessage, private output: AssistantMessage,