Files
fusion/packages/dashboard/app/api.test.ts
gsxdsm 62f87947f6 feat(KB-225): add AI text refinement feature to dashboard
- Add AI text refinement backend service with OpenAI/Anthropic integration
- Add /api/refine-text API endpoint with error handling
- Add QuickEntryBox AI refine button with style presets menu
- Add NewTaskModal AI refine feature for task description editing
- Add comprehensive tests for backend service, API, and components
- Add changeset for the new feature
2026-03-31 04:20:37 -07:00

1299 lines
43 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
fetchTaskDetail,
updateTask,
archiveTask,
unarchiveTask,
fetchAuthStatus,
loginProvider,
logoutProvider,
fetchModels,
addSteeringComment,
fetchGitRemotes,
refineTask,
fetchBatchStatus,
fetchWorkspaces,
fetchWorkspaceFileList,
fetchWorkspaceFileContent,
saveWorkspaceFileContent,
startPlanningStreaming,
fetchTasks,
} from "./api";
import type { Task, TaskDetail, BatchStatusResponse } from "@kb/core";
const FAKE_DETAIL: TaskDetail = {
id: "KB-001",
description: "Test",
column: "in-progress",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
prompt: "# KB-001",
};
function mockFetchResponse(
ok: boolean,
body: unknown,
status = ok ? 200 : 500,
contentType = "application/json"
) {
const bodyText = JSON.stringify(body);
return Promise.resolve({
ok,
status,
statusText: ok ? "OK" : "Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? contentType : null,
},
json: () => Promise.resolve(body),
text: () => Promise.resolve(bodyText),
} as unknown as Response);
}
describe("fetchTaskDetail", () => {
const originalFetch = globalThis.fetch;
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
});
afterEach(() => {
globalThis.fetch = originalFetch;
vi.useRealTimers();
});
it("returns data on first success", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, FAKE_DETAIL));
const result = await fetchTaskDetail("KB-001");
expect(result.id).toBe("KB-001");
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
});
it("retries once on failure then succeeds", async () => {
globalThis.fetch = vi.fn()
.mockReturnValueOnce(mockFetchResponse(false, { error: "Transient error" }))
.mockReturnValueOnce(mockFetchResponse(true, FAKE_DETAIL));
const result = await fetchTaskDetail("KB-001");
expect(result.id).toBe("KB-001");
expect(globalThis.fetch).toHaveBeenCalledTimes(2);
});
it("throws after retry exhaustion", async () => {
globalThis.fetch = vi.fn()
.mockReturnValue(mockFetchResponse(false, { error: "Server error" }));
await expect(fetchTaskDetail("KB-001")).rejects.toThrow("Server error");
expect(globalThis.fetch).toHaveBeenCalledTimes(2); // initial + 1 retry
});
});
describe("updateTask", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
const FAKE_TASK: Task = {
id: "KB-001",
description: "Test",
column: "in-progress",
dependencies: ["KB-002"],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
it("sends PATCH with dependencies and returns updated task", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, FAKE_TASK));
const result = await updateTask("KB-001", { dependencies: ["KB-002"] });
expect(result.dependencies).toEqual(["KB-002"]);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001", {
headers: { "Content-Type": "application/json" },
method: "PATCH",
body: JSON.stringify({ dependencies: ["KB-002"] }),
});
});
it("throws on error response", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Not found" }));
await expect(updateTask("KB-001", { dependencies: [] })).rejects.toThrow("Not found");
});
});
describe("fetchModels", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("returns available models", async () => {
const models = [
{ provider: "anthropic", id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5", reasoning: true, contextWindow: 200000 },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, models));
const result = await fetchModels();
expect(result).toEqual(models);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/models", {
headers: { "Content-Type": "application/json" },
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Server error" }));
await expect(fetchModels()).rejects.toThrow("Server error");
});
});
describe("fetchBatchStatus", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("posts task ids and unwraps the results envelope", async () => {
const response: BatchStatusResponse = {
results: {
"KB-001": {
issueInfo: {
url: "https://github.com/owner/repo/issues/101",
number: 101,
state: "closed",
title: "Issue 101",
stateReason: "completed",
lastCheckedAt: "2026-03-30T12:00:00.000Z",
},
stale: false,
},
},
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await fetchBatchStatus(["KB-001"]);
expect(result).toEqual(response.results);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/github/batch/status", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ taskIds: ["KB-001"] }),
});
});
it("propagates API errors", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "rate limit exceeded" }, 429));
await expect(fetchBatchStatus(["KB-001"])).rejects.toThrow("rate limit exceeded");
});
});
describe("fetchAuthStatus", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("returns providers with auth status", async () => {
const response = { providers: [{ id: "anthropic", name: "Anthropic", authenticated: true }] };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await fetchAuthStatus();
expect(result.providers).toEqual([{ id: "anthropic", name: "Anthropic", authenticated: true }]);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/auth/status", {
headers: { "Content-Type": "application/json" },
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Server error" }));
await expect(fetchAuthStatus()).rejects.toThrow("Server error");
});
});
describe("loginProvider", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends POST and returns auth URL", async () => {
const response = { url: "https://auth.example.com/login", instructions: "Open in browser" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await loginProvider("anthropic");
expect(result.url).toBe("https://auth.example.com/login");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/auth/login", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ provider: "anthropic" }),
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Unknown provider" }));
await expect(loginProvider("bad")).rejects.toThrow("Unknown provider");
});
});
describe("logoutProvider", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends POST to logout", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
const result = await logoutProvider("anthropic");
expect(result.success).toBe(true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/auth/logout", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ provider: "anthropic" }),
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "logout failed" }));
await expect(logoutProvider("anthropic")).rejects.toThrow("logout failed");
});
});
describe("addSteeringComment", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
const FAKE_TASK: Task = {
id: "KB-001",
description: "Test",
column: "in-progress",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
steeringComments: [
{
id: "1234567890-abc123",
text: "Please handle the edge case",
createdAt: "2026-01-01T00:00:00.000Z",
author: "user",
},
],
};
it("sends POST with text and returns updated task", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, FAKE_TASK));
const result = await addSteeringComment("KB-001", "Please handle the edge case");
expect(result.id).toBe("KB-001");
expect(result.steeringComments).toHaveLength(1);
expect(result.steeringComments![0].text).toBe("Please handle the edge case");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/steer", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ text: "Please handle the edge case" }),
});
});
it("throws on error response", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task not found" })
);
await expect(addSteeringComment("KB-001", "Test comment")).rejects.toThrow("Task not found");
});
});
describe("fetchGitRemotes", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("returns array of GitHub remotes", async () => {
const remotes = [
{ name: "origin", owner: "dustinbyrne", repo: "kb", url: "https://github.com/dustinbyrne/kb.git" },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, remotes));
const result = await fetchGitRemotes();
expect(result).toEqual(remotes);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/remotes", {
headers: { "Content-Type": "application/json" },
});
});
it("returns empty array when no remotes", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, []));
const result = await fetchGitRemotes();
expect(result).toEqual([]);
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Failed to execute git command" }));
await expect(fetchGitRemotes()).rejects.toThrow("Failed to execute git command");
});
});
// --- Plan approval API tests ---
import { approvePlan, rejectPlan } from "./api";
describe("approvePlan", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("approves plan and returns updated task", async () => {
const approvedTask: Task = {
...FAKE_DETAIL,
column: "todo",
status: undefined,
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, approvedTask));
const result = await approvePlan("KB-001");
expect(result.column).toBe("todo");
expect(result.status).toBeUndefined();
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/approve-plan", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("throws on error response", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task must be in 'triage' column to approve plan" }, 400)
);
await expect(approvePlan("KB-001")).rejects.toThrow("triage");
});
});
describe("rejectPlan", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("rejects plan and returns updated task", async () => {
const rejectedTask: Task = {
...FAKE_DETAIL,
column: "triage",
status: undefined,
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, rejectedTask));
const result = await rejectPlan("KB-001");
expect(result.column).toBe("triage");
expect(result.status).toBeUndefined();
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/reject-plan", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("throws on error response", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task must have status 'awaiting-approval' to reject plan" }, 400)
);
await expect(rejectPlan("KB-001")).rejects.toThrow("awaiting-approval");
});
});
// --- Refinement API tests ---
describe("refineTask", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
const FAKE_REFINED_TASK: Task = {
id: "KB-002",
description: "Refinement of KB-001",
column: "triage",
dependencies: ["KB-001"],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
it("sends POST with feedback and returns new refinement task", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, FAKE_REFINED_TASK));
const result = await refineTask("KB-001", "Need to add more tests and improve error handling");
expect(result.id).toBe("KB-002");
expect(result.column).toBe("triage");
expect(result.dependencies).toContain("KB-001");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/refine", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ feedback: "Need to add more tests and improve error handling" }),
});
});
it("throws on error response when task not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task not found" }, 404)
);
await expect(refineTask("KB-999", "feedback")).rejects.toThrow("Task not found");
});
it("throws on error response when task not in done/in-review", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task must be in 'done' or 'in-review' column to refine" }, 400)
);
await expect(refineTask("KB-001", "feedback")).rejects.toThrow("done' or 'in-review'");
});
});
// --- Git Management API tests ---
import {
fetchGitStatus,
fetchGitCommits,
fetchCommitDiff,
fetchGitBranches,
fetchGitWorktrees,
createBranch,
checkoutBranch,
deleteBranch,
fetchRemote,
pullBranch,
pushBranch,
} from "./api";
describe("Git Management API", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("fetchGitStatus", () => {
it("returns git status", async () => {
const status = { branch: "main", commit: "abc1234", isDirty: false, ahead: 0, behind: 0 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, status));
const result = await fetchGitStatus();
expect(result).toEqual(status);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/status", {
headers: { "Content-Type": "application/json" },
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Not a git repository" }, 400));
await expect(fetchGitStatus()).rejects.toThrow("Not a git repository");
});
});
describe("fetchGitCommits", () => {
it("returns commits without limit", async () => {
const commits = [
{ hash: "abc123", shortHash: "abc", message: "Test commit", author: "User", date: "2026-01-01", parents: [] },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchGitCommits();
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits", {
headers: { "Content-Type": "application/json" },
});
});
it("includes limit in query string", async () => {
const commits = [{ hash: "abc123", shortHash: "abc", message: "Test", author: "User", date: "2026-01-01", parents: [] }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchGitCommits(50);
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits?limit=50", {
headers: { "Content-Type": "application/json" },
});
});
});
describe("fetchCommitDiff", () => {
it("returns diff for a commit", async () => {
const diff = { stat: "1 file changed", patch: "diff content" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, diff));
const result = await fetchCommitDiff("abc123");
expect(result).toEqual(diff);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits/abc123/diff", {
headers: { "Content-Type": "application/json" },
});
});
it("throws on 404", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Commit not found" }, 404));
await expect(fetchCommitDiff("invalid")).rejects.toThrow("Commit not found");
});
});
describe("fetchGitBranches", () => {
it("returns branches array", async () => {
const branches = [{ name: "main", isCurrent: true, remote: "origin/main" }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, branches));
const result = await fetchGitBranches();
expect(result).toEqual(branches);
});
});
describe("fetchGitWorktrees", () => {
it("returns worktrees array", async () => {
const worktrees = [{ path: "/path/to/repo", branch: "main", isMain: true, isBare: false }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, worktrees));
const result = await fetchGitWorktrees();
expect(result).toEqual(worktrees);
});
});
describe("createBranch", () => {
it("sends POST to create branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { created: true }, 201));
await createBranch("feature-branch");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ name: "feature-branch", base: undefined }),
});
});
it("sends base when provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { created: true }, 201));
await createBranch("feature-branch", "main");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ name: "feature-branch", base: "main" }),
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Invalid branch name" }, 400));
await expect(createBranch("invalid")).rejects.toThrow("Invalid branch name");
});
});
describe("checkoutBranch", () => {
it("sends POST to checkout branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { checkedOut: "main" }));
await checkoutBranch("main");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/main/checkout", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("encodes branch name", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, {}));
await checkoutBranch("feature/test");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature%2Ftest/checkout", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
});
describe("deleteBranch", () => {
it("sends DELETE to remove branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { deleted: "feature" }));
await deleteBranch("feature");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature", {
headers: { "Content-Type": "application/json" },
method: "DELETE",
});
});
it("includes force query param when true", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { deleted: "feature" }));
await deleteBranch("feature", true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature?force=true", {
headers: { "Content-Type": "application/json" },
method: "DELETE",
});
});
});
describe("fetchRemote", () => {
it("sends POST to fetch origin by default", async () => {
const result = { fetched: true, message: "Fetched" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await fetchRemote();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/fetch", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ remote: undefined }),
});
});
it("sends custom remote when provided", async () => {
const result = { fetched: true, message: "Fetched from upstream" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
await fetchRemote("upstream");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/fetch", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ remote: "upstream" }),
});
});
});
describe("pullBranch", () => {
it("sends POST to pull", async () => {
const result = { success: true, message: "Pulled 2 commits" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await pullBranch();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/pull", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("returns conflict info when there are conflicts", async () => {
const result = { success: false, message: "Merge conflict", conflict: true };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result, 409));
const response = await pullBranch();
expect(response.conflict).toBe(true);
});
});
describe("pushBranch", () => {
it("sends POST to push", async () => {
const result = { success: true, message: "Pushed to origin" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await pushBranch();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/push", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("throws on rejection", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Push rejected" }, 409));
await expect(pushBranch()).rejects.toThrow("Push rejected");
});
});
describe("archiveTask", () => {
it("sends POST to archive endpoint", async () => {
const archivedTask: Task = { ...FAKE_DETAIL, column: "archived" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, archivedTask));
const response = await archiveTask("KB-001");
expect(response.column).toBe("archived");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/archive", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not in done" }, 400));
await expect(archiveTask("KB-001")).rejects.toThrow("Task not in done");
});
});
describe("unarchiveTask", () => {
it("sends POST to unarchive endpoint", async () => {
const unarchivedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, unarchivedTask));
const response = await unarchiveTask("KB-001");
expect(response.column).toBe("done");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/KB-001/unarchive", {
headers: { "Content-Type": "application/json" },
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not in archived" }, 400));
await expect(unarchiveTask("KB-001")).rejects.toThrow("Task not in archived");
});
});
describe("workspace file APIs", () => {
it("fetchWorkspaces requests the workspace list", async () => {
const payload = {
project: "/repo",
tasks: [{ id: "KB-001", title: "Task", worktree: "/repo/.worktrees/kb-001" }],
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaces();
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/workspaces", {
headers: { "Content-Type": "application/json" },
});
});
it("fetchWorkspaceFileList sends workspace and path query params", async () => {
const payload = { path: "src", entries: [] };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaceFileList("KB-001", "src");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files?workspace=KB-001&path=src", {
headers: { "Content-Type": "application/json" },
});
});
it("fetchWorkspaceFileContent sends the workspace query param", async () => {
const payload = { content: "hello", mtime: "2026-01-01T00:00:00.000Z", size: 5 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaceFileContent("project", "src/index.ts");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/src%2Findex.ts?workspace=project", {
headers: { "Content-Type": "application/json" },
});
});
it("saveWorkspaceFileContent posts content to the workspace route", async () => {
const payload = { success: true, mtime: "2026-01-01T00:00:00.000Z", size: 5 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await saveWorkspaceFileContent("KB-001", "src/index.ts", "hello");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/src%2Findex.ts?workspace=KB-001", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ content: "hello" }),
});
});
it("propagates workspace API errors", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not found" }, 404));
await expect(fetchWorkspaceFileList("KB-404")).rejects.toThrow("Task not found");
});
});
});
// --- Planning Mode API Tests ---
import { startPlanning, respondToPlanning, cancelPlanning, createTaskFromPlanning } from "./api";
import type { PlanningQuestion, PlanningSummary } from "@kb/core";
describe("Planning Mode API", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
const FAKE_QUESTION: PlanningQuestion = {
id: "q-scope",
type: "single_select",
question: "What is the scope of this plan?",
description: "This helps estimate the size and complexity.",
options: [
{ id: "small", label: "Small", description: "Quick implementation" },
{ id: "large", label: "Large", description: "Complex feature" },
],
};
const FAKE_SUMMARY: PlanningSummary = {
title: "Build user authentication",
description: "Implement login/logout with JWT tokens",
suggestedSize: "M",
suggestedDependencies: [],
keyDeliverables: ["Login form", "JWT middleware", "Logout endpoint"],
};
describe("startPlanning", () => {
it("sends POST with initial plan and returns session", async () => {
const response = { sessionId: "plan-123", currentQuestion: FAKE_QUESTION, summary: null };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response, 201));
const result = await startPlanning("Build a user auth system");
expect(result.sessionId).toBe("plan-123");
expect(result.currentQuestion).toEqual(FAKE_QUESTION);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/start", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ initialPlan: "Build a user auth system" }),
});
});
it("throws on rate limit error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Rate limit exceeded. Maximum 5 planning sessions per hour." }, 429)
);
await expect(startPlanning("Build something")).rejects.toThrow("Rate limit exceeded");
});
it("throws on validation error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "initialPlan must be 500 characters or less" }, 400)
);
await expect(startPlanning("a".repeat(600))).rejects.toThrow("500 characters");
});
});
describe("respondToPlanning", () => {
it("sends POST with responses and returns next question", async () => {
const response = { sessionId: "plan-123", currentQuestion: FAKE_QUESTION, summary: null };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await respondToPlanning("plan-123", { scope: "small" });
expect(result.sessionId).toBe("plan-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/respond", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ sessionId: "plan-123", responses: { scope: "small" } }),
});
});
it("returns summary when planning is complete", async () => {
const response = { sessionId: "plan-123", currentQuestion: null, summary: FAKE_SUMMARY };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await respondToPlanning("plan-123", { final: "yes" });
expect(result.summary).toEqual(FAKE_SUMMARY);
expect(result.currentQuestion).toBeNull();
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session plan-123 not found or expired" }, 404)
);
await expect(respondToPlanning("plan-123", {})).rejects.toThrow("not found");
});
});
describe("cancelPlanning", () => {
it("sends POST to cancel endpoint", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
await cancelPlanning("plan-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/cancel", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ sessionId: "plan-123" }),
});
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session not found" }, 404)
);
await expect(cancelPlanning("plan-123")).rejects.toThrow("not found");
});
});
describe("createTaskFromPlanning", () => {
it("sends POST to create-task endpoint and returns task", async () => {
const createdTask: Task = {
id: "KB-042",
title: "Build user authentication",
description: "Implement login/logout with JWT tokens",
column: "triage",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, createdTask, 201));
const result = await createTaskFromPlanning("plan-123");
expect(result.id).toBe("KB-042");
expect(result.column).toBe("triage");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/create-task", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ sessionId: "plan-123" }),
});
});
it("throws when session is not complete", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session is not complete" }, 400)
);
await expect(createTaskFromPlanning("plan-123")).rejects.toThrow("not complete");
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session not found" }, 404)
);
await expect(createTaskFromPlanning("plan-123")).rejects.toThrow("not found");
});
});
});
// --- API Error Handling Tests ---
import { fetchTasks } from "./api";
/** Mock helper for HTML error responses (e.g., 404 page) */
function mockHtmlErrorResponse(status: number, htmlBody: string) {
return Promise.resolve({
ok: false,
status,
statusText: "Not Found",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "text/html" : null,
},
json: () => Promise.reject(new Error("JSON parse error")),
text: () => Promise.resolve(htmlBody),
} as unknown as Response);
}
describe("API Error Handling", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("JSON responses", () => {
it("parses successful JSON responses correctly", async () => {
const tasks = [{ id: "KB-001", title: "Test Task" }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, tasks));
const result = await fetchTasks();
expect(result).toEqual(tasks);
});
it("extracts error field from JSON error responses", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Task not found" }, 404)
);
await expect(fetchTasks()).rejects.toThrow("Task not found");
});
it("uses status text when JSON error has no error field", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { message: "Different field" }, 500)
);
await expect(fetchTasks()).rejects.toThrow("Request failed: 500 Error");
});
});
describe("Non-JSON error responses", () => {
it("throws meaningful error for HTML 404 response", async () => {
const html404 = "<!doctype html><html><body>Not Found</body></html>";
globalThis.fetch = vi.fn().mockReturnValue(mockHtmlErrorResponse(404, html404));
await expect(fetchTasks()).rejects.toThrow("Request failed: 404 Not Found");
await expect(fetchTasks()).rejects.toThrow("Not Found");
});
it("truncates long HTML responses in error message", async () => {
const longHtml = "<!doctype html>" + "x".repeat(200);
globalThis.fetch = vi.fn().mockReturnValue(mockHtmlErrorResponse(500, longHtml));
await expect(fetchTasks()).rejects.toThrow("...");
await expect(fetchTasks()).rejects.not.toThrow(longHtml);
});
it("handles empty HTML error responses", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockHtmlErrorResponse(500, ""));
await expect(fetchTasks()).rejects.toThrow("Request failed: 500 Not Found");
});
});
describe("Non-JSON success responses", () => {
it("throws a descriptive HTML fallback error including the endpoint URL", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
Promise.resolve({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "text/html" : null,
},
json: () => Promise.reject(new Error("JSON parse error")),
text: () => Promise.resolve("<html>Unexpected HTML</html>"),
} as unknown as Response)
);
await expect(fetchTasks()).rejects.toThrow("API returned HTML instead of JSON for /api/tasks");
});
it("includes planning endpoint URL and status when HTML is returned", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
Promise.resolve({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "text/html" : null,
},
json: () => Promise.reject(new Error("JSON parse error")),
text: () => Promise.resolve("<!DOCTYPE html><html><body>SPA Fallback</body></html>"),
} as unknown as Response)
);
await expect(startPlanningStreaming("Build auth")).rejects.toThrow(
"API returned HTML instead of JSON for /api/planning/start-streaming. The endpoint may not be properly configured. (200 OK)"
);
});
});
describe("JSON parsing edge cases", () => {
it("reports invalid JSON with the endpoint URL", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
Promise.resolve({
ok: false,
status: 500,
statusText: "Internal Server Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.reject(new Error("Invalid JSON")),
text: () => Promise.resolve("{invalid json}"),
} as unknown as Response)
);
await expect(fetchTasks()).rejects.toThrow(
"API returned invalid JSON for /api/tasks. (500 Internal Server Error)"
);
});
});
});
// ── AI Text Refinement API Tests ───────────────────────────────────────────
import { refineText, getRefineErrorMessage, REFINE_ERROR_MESSAGES, type RefinementType } from "./api";
describe("refineText", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends POST with text and type, returns refined text", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(true, { refined: "Refined task description" })
);
const result = await refineText("Original text", "clarify");
expect(result).toBe("Refined task description");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/ai/refine-text", {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ text: "Original text", type: "clarify" }),
});
});
it("works with all four refinement types", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(true, { refined: "Refined" })
);
const types: RefinementType[] = ["clarify", "add-details", "expand", "simplify"];
for (const type of types) {
const result = await refineText("Test text", type);
expect(result).toBe("Refined");
}
});
it("throws on rate limit error (429)", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Rate limit exceeded. Maximum 10 refinement requests per hour." }, 429)
);
await expect(refineText("Test", "clarify")).rejects.toThrow("Rate limit exceeded");
});
it("throws on invalid type error (422)", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "type must be one of: clarify, add-details, expand, simplify" }, 422)
);
await expect(refineText("Test", "invalid" as RefinementType)).rejects.toThrow("type must be one of");
});
it("throws on validation error (400)", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "text must be at least 1 character" }, 400)
);
await expect(refineText("", "clarify")).rejects.toThrow("text must be at least 1 character");
});
it("throws on server error (500)", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "AI service error" }, 500)
);
await expect(refineText("Test", "clarify")).rejects.toThrow("AI service error");
});
});
describe("getRefineErrorMessage", () => {
it("returns rate limit message for rate limit errors", () => {
const error = new Error("Rate limit exceeded");
expect(getRefineErrorMessage(error)).toBe(REFINE_ERROR_MESSAGES.RATE_LIMIT);
});
it("returns rate limit message for 429 status", () => {
const error = new Error("429 Too Many Requests");
expect(getRefineErrorMessage(error)).toBe(REFINE_ERROR_MESSAGES.RATE_LIMIT);
});
it("returns invalid type message for invalid type errors", () => {
const error = new Error("Invalid type selected");
expect(getRefineErrorMessage(error)).toBe(REFINE_ERROR_MESSAGES.INVALID_TYPE);
});
it("passes through text validation errors", () => {
const error = new Error("text must be at least 1 character");
expect(getRefineErrorMessage(error)).toBe("text must be at least 1 character");
});
it("passes through text length errors", () => {
const error = new Error("text must not exceed 2000 characters");
expect(getRefineErrorMessage(error)).toBe("text must not exceed 2000 characters");
});
it("passes through type required errors", () => {
const error = new Error("type is required");
expect(getRefineErrorMessage(error)).toBe("type is required");
});
it("returns network message for unknown errors", () => {
const error = new Error("Network failure");
expect(getRefineErrorMessage(error)).toBe(REFINE_ERROR_MESSAGES.NETWORK);
});
it("returns network message for non-Error values", () => {
expect(getRefineErrorMessage("string error")).toBe(REFINE_ERROR_MESSAGES.NETWORK);
expect(getRefineErrorMessage(null)).toBe(REFINE_ERROR_MESSAGES.NETWORK);
expect(getRefineErrorMessage(undefined)).toBe(REFINE_ERROR_MESSAGES.NETWORK);
});
});
describe("REFINE_ERROR_MESSAGES", () => {
it("has the expected error messages", () => {
expect(REFINE_ERROR_MESSAGES.RATE_LIMIT).toBe("Too many refinement requests. Please wait an hour.");
expect(REFINE_ERROR_MESSAGES.INVALID_TYPE).toBe("Invalid refinement option selected.");
expect(REFINE_ERROR_MESSAGES.NETWORK).toBe("Failed to refine text. Please try again.");
});
});